Command Prompt freezes when creating a venv

Question: I am starting a new django project and when I try to add a venv to the project folder my command prompt freezes at the last line of the following code:
C:\Users\ab\workspace\rc>virtualenv venv
Using base prefix 'c:\\users\\ab\\appdata\\local\\programs\\python\\python36-32'
New python executable in C:\Users\ab\workspace\rc\venv\Scripts\python.exe
Installing setuptools, pip, wheel...

Same thing when I try to install it using the command prompt in my PyCharm project.
When I Control-C I see the following:
    Traceback (most recent call last):
      File "c:\users\ab\appdata\local\programs\python\python36-32\lib\runpy.py", line 193, in _run_module_as_main
        "__main__", mod_spec)
      File "c:\users\ab\appdata\local\programs\python\python36-32\lib\runpy.py", line 85, in _run_code
        exec(code, run_globals)
      File "C:\Users\ab\AppData\Local\Programs\Python\Python36-32\Scripts\virtualenv.exe\__main__.py", line 9, in <module>
      File "c:\users\ab\appdata\local\programs\python\python36-32\lib\site-packages\virtualenv.py", line 713, in main
        symlink=options.symlink)
      File "c:\users\ab\appdata\local\programs\python\python36-32\lib\site-packages\virtualenv.py", line 945, in create_environment
        download=download,
      File "c:\users\ab\appdata\local\programs\python\python36-32\lib\site-packages\virtualenv.py", line 901, in install_wheel
        call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=SCRIPT)
      File "c:\users\ab\appdata\local\programs\python\python36-32\lib\site-packages\virtualenv.py", line 786, in call_subprocess
        logger.info(line)
      File "c:\users\ab\appdata\local\programs\python\python36-32\lib\site-packages\virtualenv.py", line 198, in info
        self.log(self.INFO, msg, *args, **kw)
      File "c:\users\ab\appdata\local\programs\python\python36-32\lib\site-packages\virtualenv.py", line 220, in log
        if self.level_matches(level, consumer_level):
    KeyboardInterrupt

When I try vitrualenv venv -v I get:
Creating C:\Users\ab\Desktop\venv\Lib
Symlinking Python bootstrap modules
  Copying to C:\Users\ab\Desktop\venv\lib\os.py
  Cannot import bootstrap module: posix
  Copying to C:\Users\ab\Desktop\venv\lib\posixpath.py
  Ignoring built-in bootstrap module: nt
  Copying to C:\Users\ab\Desktop\venv\lib\ntpath.py
  Copying to C:\Users\ab\Desktop\venv\lib\genericpath.py
  Copying to C:\Users\ab\Desktop\venv\lib\fnmatch.py
  Copying to C:\Users\ab\Desktop\venv\lib\locale.py
  Copying to C:\Users\ab\Desktop\venv\lib\encodings
  Copying to C:\Users\ab\Desktop\venv\lib\codecs.py
  Copying to C:\Users\ab\Desktop\venv\lib\stat.py
  Cannot import bootstrap module: UserDict
  Cannot import bootstrap module: readline
  Cannot import bootstrap module: copy_reg
  Copying to C:\Users\ab\Desktop\venv\lib\types.py
  Copying to C:\Users\ab\Desktop\venv\lib\re.py
  Cannot import bootstrap module: sre
  Copying to C:\Users\ab\Desktop\venv\lib\sre_parse.py
  Copying to C:\Users\ab\Desktop\venv\lib\sre_constants.py
  Copying to C:\Users\ab\Desktop\venv\lib\sre_compile.py
  Ignoring built-in bootstrap module: zlib
  Cannot import bootstrap module: _abcoll
  Copying to C:\Users\ab\Desktop\venv\lib\warnings.py
  Copying to C:\Users\ab\Desktop\venv\lib\linecache.py
  Copying to C:\Users\ab\Desktop\venv\lib\abc.py
  Copying to C:\Users\ab\Desktop\venv\lib\io.py
  Copying to C:\Users\ab\Desktop\venv\lib\_weakrefset.py
  Copying to C:\Users\ab\Desktop\venv\lib\copyreg.py
  Copying to C:\Users\ab\Desktop\venv\lib\tempfile.py
  Copying to C:\Users\ab\Desktop\venv\lib\random.py
  Copying to C:\Users\ab\Desktop\venv\lib\__future__.py
  Copying to C:\Users\ab\Desktop\venv\lib\collections
  Copying to C:\Users\ab\Desktop\venv\lib\keyword.py
  Copying to C:\Users\ab\Desktop\venv\lib\tarfile.py
  Copying to C:\Users\ab\Desktop\venv\lib\shutil.py
  Copying to C:\Users\ab\Desktop\venv\lib\struct.py
  Copying to C:\Users\ab\Desktop\venv\lib\copy.py
  Copying to C:\Users\ab\Desktop\venv\lib\tokenize.py
  Copying to C:\Users\ab\Desktop\venv\lib\token.py
  Copying to C:\Users\ab\Desktop\venv\lib\functools.py
  Copying to C:\Users\ab\Desktop\venv\lib\heapq.py
  Copying to C:\Users\ab\Desktop\venv\lib\bisect.py
  Copying to C:\Users\ab\Desktop\venv\lib\weakref.py
  Copying to C:\Users\ab\Desktop\venv\lib\reprlib.py
  Copying to C:\Users\ab\Desktop\venv\lib\base64.py
  Copying to C:\Users\ab\Desktop\venv\lib\_dummy_thread.py
  Copying to C:\Users\ab\Desktop\venv\lib\hashlib.py
  Copying to C:\Users\ab\Desktop\venv\lib\hmac.py
  Copying to C:\Users\ab\Desktop\venv\lib\imp.py
  Copying to C:\Users\ab\Desktop\venv\lib\importlib
  Copying to C:\Users\ab\Desktop\venv\lib\rlcompleter.py
  Copying to C:\Users\ab\Desktop\venv\lib\operator.py
  Copying to C:\Users\ab\Desktop\venv\lib\_collections_abc.py
  Copying to C:\Users\ab\Desktop\venv\lib\_bootlocale.py
  Copying to C:\Users\ab\Desktop\venv\lib\enum.py
Creating C:\Users\ab\Desktop\venv\Lib\site-packages
Writing C:\Users\ab\Desktop\venv\lib\site.py
Writing C:\Users\ab\Desktop\venv\lib\orig-prefix.txt
Writing C:\Users\ab\Desktop\venv\lib\no-global-site-packages.txt
Copying to C:\Users\ab\Desktop\venv\Include
Creating C:\Users\ab\Desktop\venv\Scripts
New python executable in C:\Users\ab\Desktop\venv\Scripts\python.exe
Changed mode of C:\Users\ab\Desktop\venv\Scripts\python.exe to 0o777
Also created pythonw.exe
Also created python36.dll
Testing executable with C:\Users\ab\Desktop\venv\Scripts\python.exe -c "import sys;out=sys.stdout;getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))"
Got sys.prefix result: 'c:\\users\\ab\\desktop\\venv'
Creating C:\Users\ab\Desktop\venv\lib\distutils
Writing C:\Users\ab\Desktop\venv\lib\distutils\__init__.py
Writing C:\Users\ab\Desktop\venv\lib\distutils\distutils.cfg
Installing setuptools, pip, wheel...
  Collecting setuptools

I am on Windows 7. Any idea what is holding it up?
Comment: Can you please use the -v switch and share the output? `virtualenv venv -v`
Comment: This might be a connectivity issue. If so, and if you wait a bit more you should see a connection time out log. Are you behind a proxy?
Comment: PyCharm may be using your system proxy settings but `virtualenv` looks for environment variables. Can you please check your system proxy by going to: Control Panel --> Network and Internet --> Internet Options --> Connections --> LAN Settings and see if there are any values in the address fields?
Comment: How long have you waited?  What happens when you issue a keyboard interrupt (i.e. hit `CTRL+C`)?
Comment: Take a look at [this](https://www.google.si/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&cad=rja&uact=8&ved=0ahUKEwivw5XLxIHWAhWFbZoKHZKzBB0QtwIIMTAB&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPIxOjvjrkPg&usg=AFQjCNEYLO0ilFWsADg4vBKxKhzJPpN-RQ) and make sure you didn't miss a tiny bit in the process
Comment: @Billy I added what I see after Control-C. As far as how long I wait...30 minutes was the last one.
Comment: @McMutton I updated the answer with the output
Comment: @McMutton it gets stuck after  Collecting setuptools
Comment: @McMutton no idea. Will have to call IT. Funny thing is that I was able to create a venv in PyCharm UI by going to Preferences -> Project Interpreter -> Create new venv. But in the command prompt no luck.
Comment: @McMutton nothing there. Just says detect automaticly
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/153376/discussion-between-mcmutton-and-user3088202).
Comment: @McMutton I gotta run to a meeting. I do appreciate all your help. Thank you again. For now I will just use the UI.
Answer: You are doing the correct thing. For creating virtual environment use this command:-

virtualenv venv

Just you need to wait for few minutes for virtual environment to get created. It will take a minute or two. After the virtual environment gets created you need to activate it using the command:

. venv/bin/activate

Do not press Ctrl+c while creation. It will terminate the progress.
Visit the following link if required.
http://www.swegler.com/becky/blog/2011/08/28/python-django-mysql-on-windows-7-part-2-virtual-environments/


Touch Bar API availability

Question: When will the new Touch Bar functionality be available for use, and will it be available for both Swift and Objective-C? For which macOS version will it be available?
Comment: **This is not a general computing question** and should not be closed as such.
Comment: https://developer.apple.com/macos/touch-bar/ seems to be a good starting point: Reference, sample code, guidelines, ...
Comment: Swift and ObjectiveC are just programming languages. The API for adding support to your MacOS app to use this new hardware feature should be accessible from either language. Likely Mac OS Sierra will have support and so will Xcode 8.1.
Answer:
Xcode 8.1 supports Touch Bar for Macs that include it, and supports adding Touch Bar functionality to your app. Reference.
Will be available for both Swift and Objective-C
Available for macOS 10.12.1+

Read more on NSTouchBar from Apple.
Answer: According to Apple Developer's documentation:

To develop apps that use the Touch Bar, your Mac will need to run Xcode 8.1 on macOS Sierra 10.12.1 (16B2657) or later.

There are two builds for macOS Sierra 10.12.1:

However, Touch Bar specifically requires Build 16B2657, Build 16B2555 doesn't work.

Touch Bar API availability


Multiple SpringBoot apps, want to run only one

Question: I'm currently working with SpringBootApplications, I have two differets @SpringBootApplication , one for Web Application, and a CommandLineRunner .
The problem is, no matter which of them I execute, it tries to run both of the applications.
package com.ws;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Configuration;

@EnableAutoConfiguration
public class Init extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(Init.class);
}

/**
 * Main method.
 *
 * @param args String[].
 * @throws Exception Exception.
 */
public static void main(String[] args) throws Exception {
    SpringApplication.run(Init.class, args);
}

And this is my other InitBatch.java :
package com.batch;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class InitBatch implements CommandLineRunner {

@Autowired
private Batch batch;

@Override
public void run(String... args) throws Exception {
    batch.processFiles();
}

public static void main(String[] args) throws Exception {
    SpringApplication.run(InitBatch.class, args);
}

   }

If I run the CommandLineRunner app, after it is executed, continues to load the Web App.
I need to be able to run each of them separately from each one.  But I don't know how to configure this.
Thanks!
Comment: Please include packages into main class sources.
Comment: Possible duplicate of [How do I tell Spring Boot which main class to use for the executable jar?](http://stackoverflow.com/questions/23217002/how-do-i-tell-spring-boot-which-main-class-to-use-for-the-executable-jar)
Comment: are you using maven to build your code?
Answer: the spring docs say:

SpringBootApplication: This is a convenience annotation that is equivalent to declaring @Configuration, @EnableAutoConfiguration and @ComponentScan.
You should only ever add one @EnableAutoConfiguration annotation. We generally recommend that you add it to your primary @Configuration class.

so effectively you're adding 2 EnableAutoConfiguration annotations which just isn't allowed by spring boot. I would suggest using spring Profiles to achieve what you need.


Why is snap rstore failing with "expected a non-negative integer argument"?

Question: I have tried to re-install a snap package and I want my settings back. I did a snap save before removing the snap. Now I am trying to restore the saved snapshot with snap restore and it's failing:
root@josh-workstation:/# snap restore lxd 1
error: invalid argument for snapshot set id: expected a non-negative integer argument (see 'snap help saved')

However I am following the instructions from snap help restore and snap help saved, so... what's the deal?
root@josh-workstation:/# snap help restore
Usage:
  snap restore [restore-OPTIONS] <snap> <id>...

The restore command replaces the current user, system and
configuration data of included snaps, with the corresponding data from
the specified snapshot.

Answer: snap help is backwards and the actual command takes the ID first
It should read:
root@josh-workstation:/# snap help restore
Usage:
  snap restore [restore-OPTIONS] <id> [<snap>]...

The restore command replaces the current user, system and
configuration data of included snaps, with the corresponding data from
the specified snapshot.

Running snap restore 1 lxd worked.
root@josh-workstation:/# snap --version
snap    2.44.3
snapd   2.44.3
series  16
ubuntu  18.04
kernel  5.3.0-51-generic


Is it conjectured that there are no odd multi-perfect numbers?

Question: It is conjectured that there is no odd perfect number.
But is there a stronger conjecture that there are no odd
multi-perfect numbers ? Wikipedia shows a useful link, but my
conjecture is not mentioned. Here is the link :
http://wwwhomes.uni-bielefeld.de/achim/mpn.html
The site claims that there are infinite many even perfect numbers,
although the mersenne-prime-conjecture is still open.

Does anyone know if there are proofs that all multi-perfect numbers
with abundancy $3$ to $6$ have been discovered ?
Is it conjectured that no odd multi-perfect numbers exist ?
Comment: A number $n$ is called multi-perfect, if $\sigma(n)$, the sum of the divisors of $n$, is a multiple of $n$. In particular, $n$ is called perfect, if $\sigma(n)=2n$.
Comment: It might make sense to include the definition.
Comment: It seems the site should *not* have reported it as known that there are an infinite number of even perfect numbers. These are equivalent to knowing Mersene primes, and the count for the latter is not known to be infinite.
Answer: Regarding your question in the title, there is already an answer to a related MO question here.
I hereby reproduce the answer from the referenced MO question here:

The earliest reference seems to be from 1966: E.A. Bugulov, On the question of the existence of odd multiperfect numbers, Kabardino-Balkarskaya State University Učen. Zap. 30 (1966) 9-19. [I could not find this article online.]
Bugulov showed that an odd multiperfect number must have at least 11 distinct prime divisors, more precisely, odd $k$-perfect numbers contain at least $\omega$ distinct prime factors, where $(k,\omega) =$ (3, 11), (4,21), (5, 54),... This result is discussed and improved by Shigeru Nakamura, On k-perfect numbers, Journal of the Tokyo University of Mercantile Marine (Natural Sciences), 33 (1982) 43–50. [Listed here, but not available online.]


Modal resets the counter back to 1

Question: Not sure how did it reset/s itself even though it's inside the foreach loop. Here's a snippet from  of my blade view:

    <?php $counter = 1; ?>
    @foreach ($guidelines as $guideline)

        {{ $counter }}
        {{ $guideline->description }}

            id }}/edit" class="btn btn-warning btn-sm">
            <button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#myModal"></button>

Confirm Delete

Are you sure you want to delete this?

                            id }}/delete" class="btn btn-danger">Confirm
                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

        <?php $counter++; ?>

    @endforeach

Edit works with /general-guidelines/1/edit, /general-guidelines/2/edit, /general-guidelines/5/edit, etc. But /delete would always end up at /1/delete
Answer: First, because you have only one modal (#myModal), and your button always reference to the(#myModal), so that it will always open up the first modal. Try the solution #myModal{{ $loop->index }}.
Secondly, You can use $loop->iteration instead of $counter in the foreach loop.
Try this.

@foreach ($guidelines as $guideline)

    {{ $counter }}
    {{ $guideline->description }}

        id }}/edit" class="btn btn-warning btn-sm">
        <button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#myModal{{ $loop->index }}"></button>

index }}" role="dialog">

Confirm Delete

Are you sure you want to delete this?

                        id }}/delete" class="btn btn-danger">Confirm
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

@endforeach

Comment: So, it's basically passing a value inside the modal. Got it thanks
Answer: with for loop, multiple modals are created but for all the modals generated with for loop, you can not use same id 'myModal' . id should be unique.

Modal resets the counter back to 1


How to trigger (change) on select option when the component loads

Question: <select (change)="onChange($event.target.value)" class="custom-select">
  <option value="Running">Running</option>
  <option value="Paused">Paused</option>
</select>

This gets the value of the option when the option value changes but I also what that when the component loads then onChange method should trigger and bring the value of the currently selected option which is the first value
onChange(selectedStatus: string) {
  console.log(selectedStatus);
}

Comment: Shouldn't need to do that? Standard html `selected` should do it, or use `ngModel`
Answer: A better solution is to use ngModel like this:
<select (change)="onChange($event.target.value)" [(ngModel)]="selectedValue" class="custom-select">

and in your *.ts file:
selectedValue="Running";

but if you insist on using the event, you can use ngAfterViewInit like this:
ngAfterViewInit{
  this.onChange("Running");
}

Answer: you can use HTMLElement on angular and fire change event
   let element:HTMLElement=document.getElementById('') as HTMLElement;
    element.onchange(undefined);


Fail to import Parrot Security OVA for VMWare 15.5

Question: I tried to import Parrot Security OVA into VMWare 15.5 and it is giving me the following errors:
Line 150: Unsupported element 'StorageItem'.
Line 159: Unsupported element 'EthernetPortItem'.
According to previous questions about Parrot Security OVA, it seems that VMWare requires another format to import. If so, can anyone please tell me a possible way to change the Parrot OVA format/ VMWare settings appropriately to resolve these errors?
Answer: OVA file is not recommended. ISO is best everytime. Since OVA is pre-configured it's easy to use but you may lack some requirements which will make it fail to import. On the other hand in ISO you can configure all , so chances of errors are less


signing assemblies with a strong name, ok, but what if some 3rd party DLL isn't signed?

Question: I understand the basic idea behind signing assemblies but have a problem when using Telerik or 2rd party DLLs.
I have an .exe that uses 2 of my own .DLLs, the DLLs in turn make use of the Enterprise library DLLs and Telerik DLLs.
I gave all my projects a strong name .snk, but when compiling the compiler explains that the enterprise library DLLs, for example, aren't signed, which makes sense.
I don't want to turn off the verification with te sn.exe -Vr command or even delay sign my projects. But then how is this going to work? I'm grateful for any insight.
Answer: It's inconvenient, but not rocket science to sign/resign third party assemblies.
Assuming you want to sign an unsigned dll like System.ComponentModel.Composition.dll with the default.snk key:
open the VS command prompt and cd to your folder with the unsigned dll(s)

ildasm /all /out=System.ComponentModel.Composition.il System.ComponentModel.Composition.dll
ilasm /dll /key=default.snk System.ComponentModel.Composition.il
del System.ComponentModel.Composition.il

In each applicable VS project, remove and add back the reference to your signed assembly System.ComponentModel.Composition.dll
Comment: Is signing assembly that is installed via nuget package recommended ?
Comment: Don't forget `/resource=somename.res` if the `.res` file was created by `ildasm`
Answer: Yes, quite possible.
 Here are the steps.
Comment: page not found.
Comment: -1 for linking to a resource instead of answering the question. Luckily, [there's a cached version of that page at archive.org](http://web.archive.org/web/20160604075757/http://buffered.io/posts/net-fu-signing-an-unsigned-assembly-without-delay-signing/).


Simplify $\frac{\frac{1}{x-1} + \frac{1}{x^2-1}}{x-\frac 2{x + 1}}$

Question: Simplify: $$\frac{\frac{1}{x-1} + \frac{1}{x^2-1}}{x-\frac 2{x + 1}}$$
This is what I did.
Step 1: I expanded $x^2-1$ into: $(x-1)(x+1)$. And got: $\frac{x+1}{(x-1)(x+1)} + \frac{1}{(x-1)(x+1)}$
Step 2: I calculated it into: $\frac{x+2}{(x-1)(x+1)}$
Step 3: I multiplied $x-\frac{2}{x+1}$ by $(x-1)$ as following and I think this part might be wrong:

$x(x-1) = x^2-x$. Times $x+1$ cause that's the denominator =
$x^3+x^2-x^2-x = x^3-x$.
After this I added the $+ 2$
$\frac{x^3-x+2}{(x-1)(x+1)}$

Step 4: I canceled out the denominator $(x-1)(x+1)$ on both sides.
Step 5: And I'm left with: $\frac{x+2}{x^3-x+2}$
Step 6: Removed $(x+2)$ from both sides I got my UN-correct answer: $\frac{1}{x^3}$
Please help  me. What am I doing wrong?
Comment: Don't forget that for this problem, you have as an assumption $x \ne 1$, $x \ne -1$, and $x - \frac{2}{x+1} \ne 0 \Rightarrow x \ne -2$.  So whatever your simplified form is, you need to add $x \not \in \{1, -1, -2\}$, even if your simplified form is defined for those values.
Comment: I almost always forget that. Thank you for reminding!
Answer: First recall that
\[ \frac{a}{b} \pm \frac{c}{d} =\frac{ad \pm cb}{bd} \]
And
\[ \frac{\frac{a}{b}}{\frac{c}{d}} =\frac{ad}{bc} \]
Now just simplify, no fancy fractions needed:
\[
\frac{\frac{1}{x-1}+\frac{1}{x^2-1}}{x-\frac{2}{x+1}}
= \frac{\frac{(x^2-1)+(x-1)}{(x-1)(x^2-1)}}{\frac{x(x+1)-2}{x+1}}
= \frac{\frac{(x-1)(x+1)+(x-1)}{(x-1)^2(x+1)}}{\frac{(x+2)(x-1)}{x+1}}
= \frac{\frac{(x-1)(x+2)}{(x-1)^2(x+1)}}{\frac{(x+2)(x-1)}{x+1}}
= \frac{(x-1)(x+2)(x+1)}{(x-1)^3(x+1)(x+2)}
= \frac{1}{(x-1)^2}
\]
I attempted to be as clear as possible. If you'd like me to elaborate further, just let me know.
Comment: I now understand how I can get (x+2)(x-1). Thanks for the clear explanation!
Comment: Your welcome. Glad I could help.
Answer: You need to multiply the +2 by (x-1) before you add it to $x^3-x$ because
$$\frac{2}{x+1}=\frac{2(x-1)}{(x-1)(x+1)}$$
Also, in step 6, you can't remove (x+2) from top and bottom.  Firstly, $x^3-x+2=x^3-(x-2)$, so there is no $x+2$ in the denominator.  Secondly, you need (x+2) to be a factor of the whole denominator, not just part.
Comment: That makes sense, since I only multiplied x and the 2 only has (x+1). I'm gonna try to solve it with that. Thanks.
Comment: But If I multiply it with 2 I got 2x-2. If I add in front the x³-x-(2x-2). I get: x³-3x+2. That can probably be factored into x+2. Let me check.
Answer: It simplifies things a lot if you just multiply the numerator and denominator by $(x+1)(x-1)$
$$\frac{\frac{1}{x-1} + \frac{1}{x^2-1}}{x-\frac 2{x + 1}}\cdot\frac{\frac{(x+1)(x-1)}{1}}{\frac{(x+1)(x-1)}{1}} = \frac{(x+1)+1}{x(x+1)(x-1)-2(x-1)}=\frac{x+2}{(x-1)(x(x+1)-2)}$$
$$=\frac{x+2}{(x-1)(x^2+x-2)}=\frac{x+2}{(x-1)(x+2)(x-1)}=\frac{1}{(x-1)^2}$$


What is the inverse Laplace transform of $\frac{p^2}{(p^2+4)^2}$

Question: Given $$f(p)=\dfrac{p^2}{(p^2+4)^2}$$
So $$f(p)=\dfrac{p^2}{(p^2+4)^2}=\dfrac{p^2+4-4}{(p^2+4)^2}=\frac{1}{p^2+4}-\frac{4}{(p^2+4)^2}$$
I know the inverse Laplace transform of the first term but stuck on the second term. How can I do this? Any hints?
Answer: $$F(s)=\frac{s^2}{(s^2+4)^2}=s\frac{d}{ds}((\frac{1}{s^2+4})\times\frac1{2})$$
$$f(t)=\frac{d}{dt}(t\times(\frac{\sin(2t)}{2}\times\frac1{2}))=\frac1{4}(\sin(2t)+2t\cos(2t))$$
Comment: NIce. One more thing please explain a little about that $s$ vanishes in the third step
Comment: $$L[\frac{d f(t)}{dt}]=sF(s)$$
$$L[t f(t)]=\frac{d F(s)}{ds}$$
Comment: $s$ is converted to derivative in time domain. While $\frac{d}{ds}$ is converted into $t$.
Comment: Got it. Nice ..
Comment: [link](http://www.wolframalpha.com/input/?i=InverseLaplaceTransform[s^2%2F%28s^2%2B4%29^2])


How to add a rule to the Zend URL mapping and compose multiple MVC paths?

Question: This is because I want to develop a web platform with more than one application in the same project.

In any MVC web application we should have this default URL schema:
domain/controller/action/parameters
1: In Zend, what can I do (in which files) to change this schema to add the application name before the controller name?
Expected Result: domain/application/controller/action/parameters
2: How can I implement the consequences of this new URL block in terms that I will separate the MVC for each application, maintaining the shared resources in a separate directory? What changes may I do in Zend autoloader
Expected Result:
/public_html/
/public_html/platform
/public_html/platform/apps

/public_html/platform/apps/base (user interface container)

/public_html/platform/apps/crm
/public_html/platform/apps/crm/model
/public_html/platform/apps/crm/view
/public_html/platform/apps/crm/control
/public_html/platform/apps/crm/public
/public_html/platform/apps/crm/public/css (and etc.)

/public_html/platform/apps/erp
/public_html/platform/apps/erp/model
/public_html/platform/apps/erp/view
/public_html/platform/apps/erp/control
/public_html/platform/apps/erp/public
/public_html/platform/apps/erp/public/js (and etc.)

/public_html/platform/sys
/public_html/platform/sys/core
/public_html/platform/sys/cfg

/public_html/platform/libs/
/public_html/platform/libs/zend
/public_html/platform/libs/template_it
/public_html/platform/libs/custom

Comment: Each individual module in ZF2 defines it's own routing structure in the module's module.config file. If there is shared structure needed across modules, the application.config is where you will put those.
Comment: First things first: Are you using ZF1 or ZF2?
Comment: @STLMikey I intend to use latest ZF2 but if this situation gets two difficult, I may build a simple MVC and use some Zend libs, specially for DB and PDF.
Comment: Why is your PHP code in a subfolder of "public HTML"?
Comment: Will be there or will be in in the same *ancestor* directory...
Comment: @STLMikey but what about the controllers, views and models routes?
Comment: Come on guys, help me out! ;-)
Answer: i think it is as easy as having actual different ZF2 application, every one in its own folder, and in the same level, a "vendor" folder where you put all the shared structure (coming from zend, third party libraries, etc).
Then inside the vendor folder, i would create another folder for your own shared code, including all your  modules that has to be used by more than one of the applications, so your code is a library for yourself.
Since your app is actually in domain/application, and everyone has it own config, it is very straightforward to have  domain/application/controller/action/parameters routes: you just create  your normal  controller/action/parameters routes, since the app actually resides in domain/application/ and the router doesnt have to care about it.
As you noticed, another problem is the autoloader. YOu just need to update the references to the shared modules inside your application.config.php for everyone of your apps
return array(
    'modules' => array( //....
    ),
    'module_listener_options' => array(
        'config_glob_paths'    => array(
            'config/autoload/{,*.}{global,local}.php'
        ),
        'config_cache_enabled' => false,
        'cache_dir'            => 'data/cache',
        'module_paths' => array(
            './module',
            '../vendor',//reference to your library modules
        ),
    ),
  //...
);

of course, if the modules doesnt reside directly inside vendor/module but something like vendor/libraryname/module, you have to take a look at your autoload system (Composer autoloading or whatever) and add the classes or namespaces to the corresponding maps.


How to find mean and standard deviation?

Question: An urn contains a large number of cards of which 1/4 have the number 1,1/4 have the number 2 and 1/2 have the number 3.
a) Let $X$ be the number of the card when a card is taken from the urn. Find the mean and standard deviation of $X$.
b) Let $X$ be the sample mean when card samples are taken, compute $\mu_{\overline x}$ and $\sigma_{\overline x}$.
Any hint please I don't know what to do

Edit: By definition $E(x)=\sum xp(x),$ thus $E(x)=9/4$
Comment: @Rivaldo oh ok so $E(x)=1/4+1/2+3/2=2+1/4=9/4$
Comment: Hint: what is the definition of expected value?
Comment: @SeanRoberson $E(x)=\sum xp(x)$, what would be p(x) in this case?
Comment: p(x=1)=1/4... yes like you said above since its a discrete random variable. So X=1 X=2 X=3 are the possible values.
Comment: Personally i think this question belongs to Cross-Validated
Comment: for b) think of each "to be observed value" as an identical independently distributed random value (each with same distribution as population distribution) and the simple formula for x_bar (sample mean).
Answer: Your probability mass function (pmf) $p$ is
$$
p(x)=P(X=x)=
\begin{cases}
\frac{1}{4} &\mbox{ if } x=1, \\
\frac{1}{4} &\mbox{ if } x=2, \\
\frac{1}{2} &\mbox{ if } x=3. \\
\end{cases}
$$
a.) The expected value (mean) of $X$ is
$$
\mu=\mu_X = E[X] = \sum_{x=1}^{3} xp(x) = 1\left(\frac{1}{4}\right)+ 2\left(\frac{1}{4}\right)+ 3\left(\frac{1}{2}\right) = \frac{9}{4}
$$
and the variance of $X$ is
$$
V(X) = \sum_{x=1}^{3}(x-\mu)^2 p(x)
= \left(1-\frac{9}{4}\right)^2 \frac{1}{4} + \left(2-\frac{9}{4}\right)^2 \frac{1}{4} + \left(3-\frac{9}{4}\right)^2 \frac{1}{2} = \frac{11}{16}.
$$
So the standard deviation of $X$ is
$$
\sigma = \sigma_X = \sqrt{V(X)} = \sqrt{\frac{11}{16}}=\frac{\sqrt{11}}{4}.
$$
b.) We have
$$
\mu_{\overline X} = \mu_X = \frac{9}{4}
$$
while
$$
\sigma_{\overline X} = \frac{\sigma_X}{\sqrt{n}} = \frac{\sqrt{11}}{4\sqrt{n}},
$$
where $n$ is the sample size.
Comment: Thank you so much Mee Seong Im, your answer is very clear.


Firebase Realtime Database - Using query-based rules to retrieve specific data

Question: I am very new to queries in Firebase and query-based rules. I am trying to use query-based rules to retrieve specific data from the database, if and only if the group_id passed in the query is matching the group_id in the database at the given user with {user_id}
Code
Database reference: ref(users/{user_id}
Query
db.ref()
    .orderByChild("group_id")
    .equalTo(group_id) <- variable
    .on("value", (snapshot) => {
        return snapshot.val();
    });

JSON
root: {
  "users" : {
    "{user_id}" : {
      "email" : "email@example.com",
      "group_uid" : "{group_id}",
      "name" : "username",
    },
}

Rules
users:{
  $user_id:{
      ".read": auth.uid != null
               && query.orderByChild == 'group_id'
               && query.equalTo == data.child('group_id').val()
    }
}

My goal is to fetch the information about the user (email, group_uid and name), but the result returns null, and I can't seem to understand why.
Comment: Can you edit your question to show: 1) the JSON you're querying (as text, no screenshots please)? You can get this by clicking the "Export JSON" link in the overflow menu (⠇) on your [Firebase Database console](https://console.firebase.google.com/project/_/database/data). 2) the minimal, full rules, so that we can see where you are defining this? 3) The minimal `cb` implementation, and its output.
Comment: Thanks for the quick reply. Updated the question now
Answer: There are a few things wrong in your code/rules.
First off, you seem to be querying at the root, but are hoping to read the nodes under /users. So you'll want to fix that to:
db.ref("users")
    .orderByChild("group_id")
    .equalTo(group_id)

Second, indexes and rules need to be defined at the location in the JSON that the user reads. Since the above reads from /users, that's where you need to have the ".read" rule to allow the query:
users:{
  ".read": auth.uid != null
           && query.orderByChild == 'group_id'
           && query.equalTo == data.child('group_id').val()
}

I'm not really sure what the data.child('group_id').val(), but I doubt it'll work as you have it now. If you need more help defining your data structure, please update your question to show a more complete snippet of the JSON.
Comment: My intention with `data.child('group_id').val()` was to access the value of the `group_uid` of the given user. Also I am trying to query at a given user with `db.ref(users/{user_id})`
Comment: The query you showed `.orderByChild("group_id").equalTo(group_id)` only works when you run it on `/users` in the JSON you showed.
Comment: Okey thanks! So this query will order the users by the given `group_id`? My intention with the rule `query.equalTo == data.child('group_id').val()` was to ensure that the `group_id` given in the query is the same as the `group_id` value at the users. However, when the query is runned on `/users`,  how do i access values from the users, such as `group_id`?
Comment: I'm not sure that is possible. Firebase security rules only check whether the query is valid when it is attached. They can't check every child node now and in the future, as that wouldn't scale. You may have to change your data model to allow the use case, for example by storing the messages keyed by group id.
Comment: Okey thanks again. To ensure that i am targeting the correct child, is it possible to run the query at `ref("users/{user_id}")`? Then use the rule `query.equalTo == data.child('group_id').val()` to ensure that the group_id given in the query is the same as the group_id value at the given the given user with `{user_id}`
Comment: No. As said: `The query you showed .orderByChild("group_id").equalTo(group_id) only works when you run it on /users in the JSON you showed.` But why do you want to use a query, if you know what node to return? If a user can only belong to a single group, consider setting that group as a custom claim on their profile - as shown in my answer to your [previous question](https://stackoverflow.com/questions/65993204/firebase-database-sending-payload-with-rest-request).
Comment: I tried to install the Admin SDK in my React Native project, but i get the following error when starting the project after importing `* as admin from "firebase-admin";`: `unable to resolve module fs....` - isn't is compatible with react native?
Comment: I found a solution to my initial problem and ended up using queries. Thanks a lot for the help and effort Frank!


What is the name of the hardware used to build this dinner console table?

Question: What is the name of the hardware used to build this dinner console table?
If you are aware of a similar design I would really appreciate some links. I am looking for a dinner table that has to be "almost invisible" when not in use.
Answer: They're called table slides or extension slides.  They generally come in 2 versions - one for pedestal type tables (sometimes called equalizer slides) and one for traditionally legged tables.
As far as the design goes, you're pretty much limited to your imagination and woodworking ability. Just build it like you would any other extending table, but with the fixed table top only long enough to accommodate the hardware.
Comment: @user2059078 - I'm not sure what you mean by "regular" table slides. They look like heavy duty steel slides designed for a roughly 6' opening.  How the slide itself is designed really doesn't matter as long as it opens as far as you want it to and is rated for the weight you intend to put on it.
Comment: @user2059078 - So they're table slides that open up to 115" - they're still table slides.  If you can't find slides that long, one option would be to use 4 equalizer slides to bridge 2 pedestals.  The pedestals would then move apart as the 2 sets of slides opened.
Comment: that is specialized hardware they are not regular table slides...
Comment: With a bit of work, you could probably adapt regular drawer slides to perform the same function. Just put sets of them back to back for as much length as you need. They wouldn't be structural, so you'd need intermediate support, or a really stiff tabletop. (Which brings up the problem of where you store a really big and heavy tabletop, but maybe that's another question...)
Comment: @Comintern: they don't. The actual opening goes as far as 115"
Comment: @Aloysius Defenestrate: that is the point, not to have to store a table top or the table itself. The table top must be modular, it expands with the rails (you add more planks) http://www.godownsize.com/goliath-table-extreme-folding-table/  So again: are these specialized rails available off the shelf or they are custom made by the manufacturer?
Comment: It looks like the manufacturer has stacked/crossboltted multiple off the shelf slides, plus affixing the additional support legs... but I can't be at all sure from the photo.
Comment: Probably you need 4 of these http://www.hardwaretree.com/proddetail.php?prod=DTL-3506U  There must be longer ones ...this model extends to 68" "only"
Comment: Here is the original manufacturer for this. It is in China and I need to order 100 pairs. http://fsweihua.en.alibaba.com/product/513433831-213090363/48mm_width_adjustable_extension_folding_table_slide.html
Comment: Hypothetically, you could be a manufacturer, seeking a couple of samples to consider production...
Answer: This
is the only one I've found, after being inspired by the same table.
But I did buy them, and I can stretch a small table for 2 to a table for 8-10.
Comment: Hello, and welcome to Stack Exchange. We discourage answers where the bulk of the information is on the end of a link, because it isn't durable over time (links decay). If you could edit at least some of the information from the link into your answer (e.g. a picture, or a description of the hardware) it would help.


Missing Stream Events for Empty File Read inside Timeout

Question: I'm working on code which reads from a file and includes timeout code. I'm having some issues with empty files.
Without the timeout, the below would print something like "readable:true, open, data (0+ times), end". This works the same with an empty file or a file with content. With the timeout (even of 0), the behavior varies drastically depending on if the file is empty. For a file with content, I get something like I did without the timeout, but with an empty file all I get is "readable: false".
Why does this work so different with empty files when I have a timeout (even of 0)? Is there an easy workaround for this issue?
var stream = fs.createReadStream(fileNameTarget);
stream.pause();
setTimeout(function() {
  stream.resume()
  console.log('readable: ' + stream.readable);
  stream.on('open', function() {
    console.log('open');
  });
  stream.on('data', function() {
    console.log('data');
  });
  stream.on('end', function() {
    console.log('end');
  });
}, 0);

Answer: The difference is that setTimeout yields control to node event loop.
This means that while without setTimeout control doesn't leave your code until stream event handlers are all set up, in the version with setTimeout following can happen:

You start reading the stream at var stream = fs.createReadStream(fileNameTarget);
Control is immediately yield to node event loop with setTimeout
'open', 'data' and 'end' events are triggered, but handlers aren't yet set up (since the setTimeout callback didn't take his turn to execute yet).
setTimeout callback executes, but the file has been read already.

File with content is slower to read and open, hence you get the same behavior as without setTimeout - the stream events all happen after the timeout event.
Comment: I added a pause and resume which I thought would prevent me from losing events. I'm still getting similar output. Is this expected?
Comment: @EmilyGerner-Microsoft that is strange.
Comment: @fmsf stream.pause() only pauses stream event emitting, not the whole runtime
Comment: @EmilyGerner-Microsoft mystery solved! `stream.pause()` only pauses emitting `'data'` events. So `'open'` will be unaffected by pause. You're not getting `stream.readable == false` in this case, are you?
Comment: I realized pause() only paused event emitting - I was hoping to prevent end from being emitted! Does it really still emit end even with pause state? To answer your question, with pause added I sometimes DO get readable: false, other times I get stream.readable == true and an open and end event. Some kind of timing thing. Ideas?
Comment: I'd say so. The stream is read on lower level even if the event emitting is paused - the events are buffered then. Once the event emitting is resumed the stream is no longer readable and all the buffered events are emitted.


Event when a multicast address is added to the tap driver

Question: I'm in the process of porting a user-space network driver to a newer linux version.
The idea is to get rid of a custom kernel module that connected the network stack of the kernel to the driver and use TUN/TAP instead.
The problem I face now is with adding/removing multicast addresses that the driver should listen to on the wire.
I know how to obtain the list of current multicast addresses for the interface with
cat /proc/net/dev_mcast

But I don't get any event when the list changes.
When the driver should listen to a new multicast address, user space calls:
struct ip_mreq group;
group.imr_multiaddr.s_addr = inet_addr("220.127.116.11");     // multicast address
group.imr_interface.s_addr = inet_addr("172.16.72.100"); // interface address

setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *) &group, sizeof(group));

This leads in the kernel to a call of
struct net_device_op.ndo_set_rx_mode

The driver then can update its (hardware) multicast filters.
Unfortunately the callback in the TAP driver is empty.
Is there any alternative way to detect changes in the multicast reception (without polling)?
I tried netlink messages, but the RTNLGRP_NEIGH doesn't report changes to the multicast addresses.
Monitoring /proc/net/dev_mcast with inotify also doesn't work, as inotify is not supported on virtual file systems.
Thanks,
   Wolfgang
Answer: Usespace routing daemons normally listen to a routing netlink socket and epoll for status to react to events. I think that should give you the desired behavior.
If you have to do more advanced multicast routing you may want to look into a special Linux kernel hook meant for multicast routing daemons to manage the multicast route table labeled CONFIG_IP_MROUTE.
The mechanism is explained well in this article:
http://www.linuxjournal.com/article/6070
An example of a simple multicast routing daemon that uses this hook is:
http://troglobit.com/projects/smcroute/
Comment: I already opened a netlink socket and subscribed to all available groups. I tried "ip monitor" which does the same according to strace. All this provided no event in case of IP_ADD_MEMBERSHIP. And using the interface provided for mcast routing daemons is too complex for my application. As I'm on an embedded system I ended up patching the kernel/TUN module. Thanks for your help.


Telegram Bot Webhook Not Working on My Laravel and Let's Encrypt SSL

Question: I can get update via getUpdatesbut not with webhook.
Here is my route:
Route::post('/<MY BOT TOKEN>', function () {
Telegram::sendMessage([
    'chat_id' => "468613362",
    'parse_mode' => 'HTML',
    'text' => " Test message from webhook update, Hinbo Love you"
]);

return 'ok';
});

I did test the URL with Postman and it is returning "ok" as expected.
Excluded in VerifyCSRFToken.php:
 protected $except = [
    '/<MY BOT TOKEN>',
];

Webhook set by sending this request
https://api.telegram.org/bot<MY BOT TOKEN>/setWebhook?url=https://lomba.ikarin.site/<MY BOT TOKEN>

and here is the response from telegram:
{
 ok: true,
 result: true,
 description: "Webhook was set"
}

My website is using let's encrypt ssl, my site: https://lomba.ikarin.site
I worried about the cert chain, so i checked https://www.ssllabs.com/ssltest/analyze.html?d=lomba.ikarin.site and it says

Chain Issues: None

Worried about SSL/TLS version, so I contacted my shared hosting's support team and they said it is in version 1.2 as required.
what am I missing here?
Comment: What is the webhook status of your robot? (you can see it by calling `getWebhookInfo` function of the bot like [here](https://core.telegram.org/bots/api#getwebhookinfo) ).
Comment: @AliKhalili it says it is set, but connection time out
Answer: getUpdates not working if you use webhook. try to use Telegram::getWebhookUpdates();


Prove or find a counterexample

Question:
Suppose $f(x)$ is bounded and differentiable on $[0,\infty)$. Consider the statement:
If $\lim_{x\to \infty}f(x)=0 $, then $\lim_{x\to \infty}f'(x)=0 $.
Prove it if it's right or show a counterexample.

I think it's not true and trying to find a counterexample by using functions containing $\cos(\frac{1}{x})$ or $e^{-x}$ or other things. The final goal is to find something make it's derivative' limit at infite doesn't exist. Since if it exists, it must equals zero or $f(x)$ will not be bounded.
Comment: Related (dup, I'd say) https://math.stackexchange.com/questions/162078/
Answer: You can take $f(x)=e^{-x}\sin(e^x)$, for instance. Note that $f'(x)=-e^{-x}\sin(e^x)+\cos(e^x)$ and that therefore the limite $\lim_{x\to+\infty}f'(x)$ does not exist.

Prove or find a counterexample


steel windows diy design+construction

Question: I would like your suggestions/experience/opinions on designing steel windows+patio doors, using hollow sections (RHS as they call them) and angle sections.
The window style I have in mind (but can not afford to buy and transport to my country) are the iconic Crittall windows.

(first image was taken from here, second image from here)
Alas! Crittall use a special steel section which they manufacture themselves and I can not find in the market here. So I have to use steel sections which I can find in my country: angles, tees and hollow sections:

As far as aesthetics are concerned, my main worry is "thin sight-line", i.e. the frame to be thin, maybe a width of 30mm.
I have solved (i think) life-expectancy and maintenance issues as I intend to bath-galvanise them and then (optionally) powder paint them to give them a nice gloss color and life expectancy (maintenance free) of 20 years at least, if not 50!
The welding will be undertaken by a professional.
My main problem is air-tightness. It is easy to design on paper but in practice I do not know how efficient it will be.
Basically I follow the rule that when closed, the frame of a window should 'kiss'/'push against' the steel case (screwed on the wall) at two different places. Thus air trying to get inside the house must by-pass two obstacles/seals/weatherstrips.
I also intend to 'glue' (somehow, or even screw) on the steel frame rubber/insulation foam/seals (weatherstrip they call it) - something which aluminium and crittall windows do very well because their sections have been designed to have a channel where the rubber seal goes in and stays there without need of glue or screw. Glueing on metal is probably a nightmare.
The basic idea can be seen from these crittall drawings:
http://www.crittall-windows.co.uk/wp-content/uploads/HOMELIGHT-DG-WEB-DOWNLOAD-11-15.pdf
There will be two types.
1) Opening out, 'casement' windows, height 2m, width of each pane 0.6m.
They will be hinged on the sides, top and bottom. Here is a drawing of the
side-section (i hope it makes sense):

2) Swivel or vertical pivot type. The hinges will be at the middle of the window frame, top+bottom. Sorry no drawing for this.
My questions:
1) Do you have any comments/suggestions about the air-tightness of the design in the image attached?
2) Do you have any suggestions on how to implement the vertical pivot window type (using the same RHS, flat and angles as with the openout window) as far as air-tightness is concerned. Suggestions about the hinge?
3) From the drawing you can see a wooden frame at the inside of the window securing the glasspane against the exterior steel angle. This wood will be screwed onto the steel frame. What do you think as far as safety is concerned?
4) What is the best way to secure the weatherstrips/seals onto the metal frame?
Notes:
1) glass will be double-glazed 5mm+18mm airgap+6mm, weighting about 30Kg/m2, so for a 2m x 0.6m window, the total weight will be 45Kg plus, say, 10Kg of steel=55Kg.
2) The windows will imitate the crittall look of horizontal splits every 30cm by using a one-piece glass pane and then welding on the outside thin pieces of metal horizontally.
I have given only an outline of the project, if you need clarification let me know.
thanking you in advance,
bliako
Comment: Hi. Although this is a cool question, it doesn't really seem like a good fit for our "home improvement" topic; it's more engineering and manufacturing than we usually cover.
Comment: I'm voting to close this question as off-topic because it's very broad and not a DIY topic.
Answer: The windows in the top photo are actually doors. They are aluminum, probably a custom extrusion.
You will have a VERY heavy window. Your opening mechanism will need to account for that, as well as the structure which supports the hinges.
The windows in the lower photo are actually made of steel T-section.  Yes, they are welded.  The glass is glazed in using traditional putty glazing (on the outside of the building, very impressive!) However I would use a quality silicone, and a great deal less of it.
You get sealing by designing for gravity and using rubber gaskets. Trying to do it with steel fitting tightly is going to create windows which bind, get stuck, and are sensitive to tram problems.  You won't knock the window out of tram, but the window frame? You betcha.
I don't like the screw-in plywood.  You are dealing with heavy windows and it will not hold unless you use a lot of screws.  I would go with metal for that. Tolerances should be not too critical since you should glue in the windows with a quality silicone caulk.  Caulk has no shelf life, it is garbage after a year or so, so don't use old stock.
Designing windows well is an iterative design. The best aren't good because they're smart.  They're good because they've made mistakes, learned, made more, learned, repeat.
Comment: well crittall claims they are steel doors.
Comment: Thanks for your comments. Many building from the 70's around here have windows and doors made of steel ala Crittall. Fair enough they use single-glaze glass. I have calculated that each window frame will have 17Kg of metal (frame not the casing screwed on the wall) and 36Kg of double-glaze glass. A total weight of 53Kg for each 1.2m x 0.6m window frame. And that will be on two hinges (top+bottom). I don't see a problem (in theory). The plywood was a design effect. I can do without. Crittall design is very impressive I agree - doesn't matter if I get cold.... Thanks.
Comment: I'll be darn.  They really look aluminum. They must be new and the paint must be perfect.
Answer: i have multiple questions, but first, where is this being done and what is your climate like.
i think you will have huge sealing, glazing and warpage problems trying to weld that out of steel.  even if you get someone who has a harmonic resonator, the thin sections will twist enough to make glass mounting a problem.
why not use aluminum.  its stiffer per unit mass, available in multiple profiles to suit your purposes, and is just as weldable as steel, but doesn't warp.  you just need someone who can TIG or MIG with an aluminum gun and gas.
Comment: it's being built in malta. the climate there is hot in summer, about 30-40 degrees C, and in winter rarely reaches freezing point.
Comment: okay, so that answers the question as to why your glass wont be in sealed thermal panels.  if i were you, i would do it in aluminum - not steel.  a little more cost, but no corrosion or warpage, and you can get profiles that will do the job in a single extrusion
Comment: I will see what's on the market for alu profiles. A local alu-window assembly factory has shown me some very ugly sightlines costing a fortune. I doubt it will be cheaper than me DIY-ing it (dying too!:)). For steel, my calculation for cantilever-beam deflection (fixed on hinge) of RHS 40x20x3, assuming a uniform 70Kg (glass+metal) and length=0.6m is 4mm. Not bad I think given that the window rectangular frame as a whole will decrease the deflection.
Comment: Twisting is another problem but don't forget the steel bars welded horizontally. Anyway it's better to make one frame and test it in practice. will keep posted. thanks
Comment: you misunderstand - i am not talking about sagging or bowing.  the warpage i am talking about is during welding.  if everything doesnt stay flat and true, you will have all sorts of problems with sealing and heat related glass failure.  you can still diy  this if you want (its actually much easier to fabricate in aluminum than steel), you just need someone who knows how to weld aluminum properly (there are lots of monkeys who say they can but can't)
Comment: cheers, now I understand what you mean.

steel windows diy design+construction


Deep copy of a queue using assignment operator

Question: I have troubles with the pointers using my assignment opperator, it doesn't make a new qeueu, instead the new array points to the old one. So when I delete in the new queue the values in my old queue changes.
First off all I can see that my copy constructor isn't called in my main for some unknown reason, the problem is probably related with that.
Some of my main code used to illustrate the problem:
aQueue.enqueue(10);
    aQueue.enqueue(20);

    Queue<int> cQueue = aQueue;

    cout << "aQueue: "; aQueue.printQeueue(2, 0);
    cout << "cQueue: "; cQueue.printQeueue(3, 0);

    cQueue.dequeue();
    cout << "aQueue: "; aQueue.printQeueue(4, 1);
    cout << "cQueue: "; cQueue.printQeueue(5, 1);
    system("pause 4");

This is where the problems start, if I enqueue aQueue with 10 and 20 and then assign cQueue to aQueue, if I print aQueue the result is: 10 20. After that dequeue cQueue and print aQueue the result is: -179016023. If I print cQueue the result is: 20, as it should be.
The output: https://i.stack.imgur.com/0xRwC.jpg
Here follows the functions used direct or indirect:
template <typename T>
T Queue<T>::dequeue(){

    T temp = front();

    Node *old = fronten;
    fronten = fronten->next;

    delete old;

    return temp;

}

template <typename T>
Queue<T>::Queue(const T &rhs){

    Node *tempfront = rhs.fronten;

    while (tempfront.fronten!=rhs.back){
        enqueue(tempfront);
        tempfront = tempfront->next;

    }
}

template <typename T>
void Queue<T>::enqueue(const T& item){

    if (isEmpty()){
        back = fronten = new Node(item);
    }
    else
        back = back->next = new Node(item);
}

Node(const T &theElement, Node *n = nullptr): element(theElement), next(n) {};

Comment: you don't have a copy ctor for Queue, yours template
Queue::Queue(const T &rhs) is constructor for Queue from the type it stores
Comment: please paste complete example that compiles
Comment: @0d0a Now you lost me, but it sounds like it makes sence. So how should I define my copy ctor?
Comment: inside class : Queue::Queue(const Queue &rhs){//...}
Answer: You don't have at the moment copy constructor for your Queue class (or you don't show it). Yours
template <typename T> Queue<T>::Queue(const T &rhs)

is constructor for Queue from the type it stores. You need something like:
template <class T>
class Queue
{
  public:
    Queue( const Queue &);                // copy ctor
    Queue& operator=( const Queue& q);   // assignment operator
  //...
};

Comment: Thank you! Been working so much it made me blind + my unknowledge ;D


Why import bootstrap css with webpack instead of just linking to it?

Question: I have been learning webpack for use in a Single Page App.
One of the examples is using:
<code> import 'bootstrap/dist/css/bootstrap.min.css';
</code>
along with a loader like this:
<code>{
   test: /\.css$/,
   use: ['style-loader', 'css-loader']
}
</code>
This works to inject bootstrap css into main.js and it then gets injected into the dom at runtime.
Ok fine.  But why?  I don't see a benefit to this over just have a normal link.
The other side of the code is that this is now increasing the size of the bundle (my app bundle is already over 5 megs) is just going to increase the startup time vs using a CDN.
Am I missing anything?
Update
I think I found the answer to this: The next step is to extract the imported css to a css file with MiniCssExtractPlugin like explained here
Comment: if you're using Bootstrap css with webpack, I would recommend using an additional plugin like PurifyCss which will allow you to 'treeshake' all the bootstrap classes you do not actually use and therefore will reduce your bundle size. https://www.npmjs.com/package/purifycss-webpack
Answer: It will not make any difference when you have one dependency. But if you have a bunch of third party libraries , you can bundle and minify in to one. It will give you advantage when your application gone in to production.
And also other benefits would be converting .scss in to css
Sample web pack configuration
<code>module.exports = {
    mode: 'development',
    entry: {
        'main.app.bundle': ['main.ts', "./somestyle.css"]
    },
    optimization: {
        splitChunks: {

               cacheGroups: {
                commons: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'vendors',
                    chunks: 'all'
                }
            }
        }
    },
    output: {
        publicPath: '/dist/',
        filename: '[id].js',
        chunkFilename: "[name].js",
        path: path.resolve(__dirname, 'dist'),

    },
    module: {
        rules: [{
                test: /\.(sa|sc|c)ss$/,
                use: [
                    'exports-loader?module.exports.toString()',
                    {
                        loader: MiniCssExtractPlugin.loader,
                    },
                    'css-loader',
                    'sass-loader',
                ]
            },

            {
                // This plugin will allow us to use html templates when we get to the angularJS app
                test: /\.html$/,
                exclude: /node_modules/,
                loader: 'html-loader',
            },
            {
                test: /\.tsx?$/,
                loader: 'ts-loader',
            }
        ]
    },
    node: {
        fs: 'empty'
    },
    resolve: {
        modules: [
            __dirname,
            'node_modules',
        ],
        extensions: [".ts", ".tsx", ".js"]
    },
    plugins: [
        new CleanWebpackPlugin(['dist']),
        new HashOutput({
            validateOutput: false,
        }),
        new MiniCssExtractPlugin({
            filename: 'application.bundle.css',
            chunkFilename: '[name].css'
        })
    ],
    devtool: 'source-map',
    externals: [],
    devServer: {
        historyApiFallback: true
    }
};
</code>
Comment: plus 1 for the example - very helpful


Issues related to Google reCaptcha v3

Question: I wanted to integrate reCaptcha in a website and bit of confused, about it's working.
Here's how I configured:

Added this code in head:

Used this code on page load to get reCaptcha response

Use this code to verify captcha response
$secret = 'SECRET_KEY';
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['recaptcha']);
$responseData = json_decode($verifyResponse);
if($responseData->success){
    //valid response, move forward
}else{
    //captcha check failed, throw an error
}

It seems to work fine for me, and I'm getting 0.9 score for my requests.
Problem:
Assume captcha failed for a valid user request because of any reason (like ip was used for spamming or any other google verification check failed). But the user is legitimate so:

how do a user can prove his humanity? (like in previous checkbox version)
if user loads registration form and go for other activities, the user came back after sometime (e.g 10 mins). When user will try to submit form, the captcha check will fail. (I tried this and got error back 'timeout-or-duplicate')
Is there any way to reload captcha, without page reload?

Please lemme know, how to overcome those issues?
Answer: Add reCAPTCHA V2 with V3.
If V3 fails. Use V2 to verify the user.

Issues related to Google reCaptcha v3


How to cap and round number in ruby

Question: I would like to "cap" a number in Ruby (on Rails).
For instance, I have, as a result of a function, a float but I need an int.
I have very specific instructions, here are some examples:
If I get 1.5 I want 2 but if I get 2.0 I want 2 (and not 3)
Doing number.round(0) + 1 won't work.
I could write a function to do this but I am sure one already exists.
If, nevertheless, it does not exist, where should I create my cap function?
Answer: Try ceil:
 1.5.ceil => 2
 2.0.ceil => 2

Comment: 1.1.ceil => 2   (another example)
Answer: How about number.ceil?
This returns the smallest Integer greater than or equal to number.
Be careful if you are using this with negative numbers, make sure it does what you expect:
1.5.ceil      #=> 2
2.0.ceil      #=> 2
(-1.5).ceil   #=> -1
(-2.0).ceil   #=> -2

Answer: .ceil is good, but remember, even smallest value in float will cause this:
a = 17.00000000000002
17.0
a.ceil
18

Answer: Use Numeric#ceil:
irb(main):001:0> 1.5.ceil
=> 2
irb(main):002:0> 2.0.ceil
=> 2
irb(main):003:0> 1.ceil
=> 1

Answer: float.ceil is what you want for positive numbers.  Be sure to consider the behavior for negative numbers.  That is, do you want -1.5 to "cap" to -1 or -2?

How to cap and round number in ruby


Display a  with information from an API in?

Question: I'm trying to figure out how to display information from an API in a select.
The user has to select a start station with the  itself linked to the api. But I can't create option, having the names of each station, in my select.
Can you help me understand my mistake?

list

  <select id="subwaystation">
  </select>

var apiStations = "https://api-ratp.pierre-grimaud.fr/v4/stations/metros/8";

function req1() {
fetch(apiStations, {
  method: "get"
})
  .then(response => response.json())
  .then(data => {
   let allstations= data.result.stations;
    for(var i = 0; i < allstations.length; i++) {
      html += "<option value=" + key  + ">" +obj[key] + "</option>"
  }
  document.getElementById("subwaystation").innerHTML = html;
  })
}
req1();
Answer: Your code contains some simple errors which you should be able to see in your browser's Console, which would give you clues about why it's not working.
First you'd see that html is not defined before you try to append to it. You can't append to something which doesn't exist.
if you fix that then you'd see that key and then obj are also not defined. It's not clear where you expected those to come from or what you think they would contain. I wonder if you simply copied and pasted some code you found without stopping to examine it properly or consider whether it fits with the context you pasted it into.
You can fix these issues very straightforwardly by

declaring html as an empty string before your loop starts, so the += has something to append to

When creating the <option, referring to the station object at the current index (i) of the loop and then the specific properties found in that object (slug and name, as shown in the raw JSON), instead of using key and obj which do not come from anywhere else in your code.

Demo:

var apiStations = "https://api-ratp.pierre-grimaud.fr/v4/stations/metros/8";

function req1() {
  fetch(apiStations, {
      method: "get"
    })
    .then(response => response.json())
    .then(data => {
      let allstations = data.result.stations;
      let html = '';
      for (var i = 0; i < allstations.length; i++) {
        html += "<option value=" + allstations[i].slug + ">" + allstations[i].name + "</option>"
      }
      document.getElementById("subwaystation").innerHTML = html;
    })
}
req1();
<select id="subwaystation">
</select>
Comment: Thank you, i was trying so much things and i was not so far from the right answer.I would need to be put on voice if you don't mind. I can display the api messages but how do I get the message to change when I choose another station :
https://api-ratp.pierre-grimaud.fr/v4/schedules/metros/8/balard/A
as each message will be different depending on the station selected. I can't think of a solution where when I select my station, the right message is displayed (in this case, Balard).


How do I create an Azure SQL Database copy during runtime?

Question: I am new to VB.NET and Azure SQL services and I have spent the last 3 days searching for an answer and cannot come up with an answer I can truly understand.   Here is my scenario and problem:
I have a VB.NET application where a user will log into their account and have their own set of tables under their own Azure SQL Database.  I would like my program to automatically create their database for them (using their own selected name), which would be a database copy of an existing empty Database in Azure.
I can already access the data tables in my master database, but I do not know how to make a copy of it from my program during runtime.  When I run my application and it debugs the following snippit of code, I get an exception error saying "You must be logged into the master database"  I'm not sure how to resolve that error from popping up as I am using the master admin account in my normal SQL connection string.
<code>Private Sub BtnActivate_Click(sender As Object, e As RoutedEventArgs)
    If passwrd1.Password <> passwrd2.Password Then
        MsgBox("Password doesn't match Confirm Password.", vbOKOnly)
    Else
        Dim commandString = "CREATE DATABASE " & dbname.Text & " AS COPY OF DBDEV;"
        Using connection As New SqlConnection(My.Settings.DBDEVConnectionString)
            Dim command As New SqlCommand(commandString, connection)
            Try
                connection.Open()
                command.ExecuteNonQuery()
                MsgBox("DATABASE SETUP.  USE " & dbname.Text & "AS DBNAME TO CONNECT TO")
            Catch ex As Exception
                Throw ex
            End Try
        End Using
    End If
End Sub
</code>
Please help, I've been moving nowhere and everything I'm searching for doesn't give me a clear answer to this simple scenario.
Answer: After many attempts, I solved the problem:  in my connection string, I had the initial catalog default to my database and so I changed it to say "master" (even though I don't have a database named master) and it performed the Database copy for me.  Woohoo!


Can you select multiple players in a command?

Question: When you use a command like this:
<code>/effect Tisajokt 1 30 1
</code>
You can give the IGN Tisajokt speed. Is there any way to list off multiple people in a command like the above, without scoreboard objectives?
Comment: You know about `@a` and `@p`, right?  I'm assuming that since you mentioned scoreboard objectives.
Comment: @MBraedley Of course :)
Answer: No there isn't. You can only filter the list of players by certain criteria when using the <code>@a</code> selector. The ways in which you can filter are by position (including radius), min/maxscoreboard objective scored, having a certain item, min/max experience level, game mode or team.
See the wiki for a full description of each filter.
If there are two specific, named players you want to target, just use two command blocks.
Answer: There is one other way of doing this besides using Scoreboard. In 1.9 there was a new data tag introduced called a tag. If you tag the players or entities you want to get this effect, use the ! Selector with this tag to select everything you do not want to get this speed effect. If you need to know how to do this, I believe Dragnoz made a video about it on YouTube.


How to handle NullProviderCultureResult? Isn't it strange to render the homepage without redirection?

Question: In a Net 7 project I am setting localization in Program:
builder.Services.Configure<RequestLocalizationOptions>(x => {
  x.AddSupportedCultures("pt", "en");
  x.AddSupportedUICultures("pt", "en");
  x.SetDefaultCulture("pt");
  x.RequestCultureProviders.Clear();
  x.AddInitialRequestCultureProvider(new RouteDataRequestCultureProvider { RouteDataStringKey = "culture" });
});

application.UseRequestLocalization();

I have two Razor Pages (Index and About):
Index: @page "{culture?}"

About: @page "/{culture?}/about"

I am able to access Homepage (Index) using:
/
/en
/pt

But I am only able to access About page using:
/en/about
/pt/about

When I try to access "/about" the url is not changed but the homepage is rendered.
Isn't this strange?
Shouldn't redirect to Index and change the Index Url?
Or even Redirect to "/pt/about" because PT is the default culture?
I checked the RouteDataRequestCultureProvider source and I has:
  if (culture == null && uiCulture == null)
  {
    // No values specified for either so no match
    return NullProviderCultureResult;
  }

Can't I define what to do when a NullProviderCultureResult occurs?
Answer: This may not answer your question, but at least will explain why it works like this.

But I am only able to access About page using:

/en/about
/pt/about

When I try to access "/about" the url is not changed but the homepage is rendered.

That is basically because the url "/about" is matching with the route /{culture} and so it assumes that "culture=about", as a result it redirects to the index page because it matches the route:
Index: @page "{culture?}"

However, since there is no culture named "about" it renders the default culture "pt" in your case.


How do I avoid Python Unicode encoding error when reading in a text file?

Question: I have written the following Python code, which uses the folder selected by the user (data_fold) to navigate through the text files in the folder that contain the data.
rootdir = self.data_fold;
   for subdir, dirs, files in os.walk(rootdir):
        for file in files:
            file2read = open(os.path.join(subdir, file));
            data = file2read.read();
            file2read.close();
            data;

I get the following errors:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1536, in __call__
return self.func(*args)
File "PIM_Reporter.py", line 71, in genPimPlot
self.ExtractPIMDataFromFiles(self.data_fold);
File "PIM_Reporter.py", line 75, in ExtractPIMDataFromFiles
for subdir, dirs, files in os.walk(rootdir):
File "C:\Python27\lib\os.py", line 278, in walk
names = listdir(top)
TypeError: coercing to Unicode: need string or buffer, list found

I need the code to do a few things: open the file, read the data in, add the data to a dictionary, close the file. I am new to Python, so explicit solutions would be greatly appreciated. Thank you for your time and expertise.
Comment: If you solved, you should post your answer.
Comment: print `rootdir`. `os.walk` expects string but you probably use list.
Comment: Maybe `for subdir, dirs, files in os.walk(rootdir[0]):` will work then? Since you're getting a list with one element
Comment: @Connor could you read a book without opening it? But on a serious level, why is that a concern for you? Calling `open` on a gigantic file will not consume all your memory, only if you try to load it into memory.
Comment: The error appears to come from `for subdir, dirs, files in os.walk(rootdir):` and therefore is not explicitly associated with what you're trying to do in the bottom paragraph or the question title.
Comment: print of rootdir gave me: ['C:/Users/qlab/Desktop/nsiReporter/pim/pimDataEx/R1']
Comment: If that does work then the actual question you've asked is relatively simple but building a dictionary is not possible if you don't give an indication of the file structure and the expected outcome
Comment: Thank you both @furas & roganjosh. The problem was that the rootdir was a list. The solution I used was to redefine the rootdir as: rootdir = ''.join(self.data_fold);
Comment: Can I read the file without opening it?
Comment: no, you can't read without opening.
Comment: As @AaronHall wrote, post your answer. Purpose of SO is to maintain a database of answers to questions, so that everyone who encounters the same problem can find the solution which helped others.
Answer: you can try this
import os
d = {}
for root, dirs, files in os.walk('path'):
    for file in files:
        print(file)
        with open(os.path.join(root,file)) as f:
            d[file]= f.read()
            f.close()
print(d)

output:
{'file1':'data','file2':'data',.......}


Whoa, what the TryParse

Question: I've got a Session that contains particular integer values, which are indexed with given controls.  Normally, the following would work just fine:
int value;
int.TryParse(Session["Key"].ToString(), out value);

However, I do need to account for null.  Where, if the string fails the default out would return a null.  Except I noticed that int.TryParse doesn't work with:
int? value = null;
int.TryParse(Session["Key"].ToString(), out value);

So how can you try that parse, if fails it results in the null?
I found this question and the Microsoft Developer Network dictates:

When this method returns, contains the signed integer value
  equivalent of the number contained in s, if the conversion succeeded,
  or zero if the conversion failed. The conversion fails if the string
  parameter is null or String.Empty, is not of the correct format, or
  represents a number less than Min Value or greater than Max Value. This
  parameter is passed uninitialized.

Which plainly states, if int.TryParse fails the integer will hold a value of zero.  In the instance of my usage, zero could be a valid value.  So I need null, any thoughts?
Comment: Why would not regular cast work? `(int?)(Session["Key"])`
Comment: @AlexeiLevenkov I could potentially do: `Session["Key"] as int?` where it returns nullable if it fails.
Comment: I'm sort of confused - I assume you put nullable into session state - so there will be either valid `int?` value or key missing - both should work with cast/as successfully. I see no case where "it fails"...
Comment: @AlexeiLevenkov Your correct, but other developers may do 'bad data'.  Though they shouldn't.
Comment: @AlexeiLevenkov The other potential issue with a regular cast, if it fails it throws an exception within IIS which you wouldn't want users to see.
Answer: Sure; utilize the return value of int.TryParse (which returns if the conversion succeeded or not):
int? retValue = null;
int parsedValue = 0;

if (int.TryParse(Session["Key"].ToString(), out parsedValue))
    retValue = parsedValue;
else
    retValue = null;

return retValue;

A little verbose I'll admit, but you could wrap it in a function.
Answer: int tmp;
int? value = int.TryParse(Session["Key"].ToString(), out tmp) ? (int?)tmp : null;

Comment: This code obviously throws NullReferenceException when key does not exist/has `null` value (exactly the same behavior as OP wants, but not necessary one what others may need. Beware).
Comment: @AlexeiLevenkov No doubt, but I guess it is beyond the scope of the question to cover this case.
Answer: The problem is the word "null."  What does it mean?  null could mean the value was indeterminable, an exception was thrown, simply that the value is null, or some other contextual meaning.  Your question is a perfect example, because you, yourself, are arbitrarily stating that, in your opinion, null means the parsing of the string failed.
Microsoft's TryParse paradigm is great, but for limited usage.  Consider these Scenarios:

string == "89"
string == null
string == "Hello World"
string == ""
string == "2147483650"

Yet, your only options are to assign an Integer or Null to your output, and to return true or false.
Assuming it worked, what are you going to do with that information?  Something like this?
int? value = null;
if (int.TryParse(Session["Key"].ToString(), out value)) {
    if (value == null)
        // Handle "Appropriate" null
    else
        // Handle appropriate numeric value
}
else {
    // Note: value == null here, and TryParse failed
    // Handle null...
    // What if the reason it failed was because the number was too big?
    // What if the string was Empty and you wanted to do something special?
    // What if the string was actually junk?  Like "(423)322-9876" ?
    // Long-Story Short: You don't know what to do here without more info.
}

Consider this NullableInt TryParse example:
public bool TryParseNullableInt(string input, out int? output)
{
    int tempOutput;
    output = null;
    if (input == null) return true;
    if (input == string.Empty) return true; // Would you rather this be 0?

    if (!int.TryParse(input, out tempOutput))
        return false; // What if string was "2147483650"... or "Twenty Three"?
    output = tempOutput;

    return true;
}

One solution is to use an enumeration TryParse instead of a boolean TryParse:
public ParseStatus TryParseNullableInt(string input, out int? output)
{
    int tempInteger;
    output = null;
    if (input == null) return ParseStatus.Success;
    if (input == string.Empty) { output = 0; return ParseStatus.Derived; }

    if (!int.TryParse(input, out tempInteger)) {
        if (ParseWords(input, out tempInteger)) { // "Twenty Three" = 23
            output = tempInteger;
            return ParseStatus.Derived;
        }
        long tempLong;
        if (long.TryParse(input, out tempLong))
            return ParseStatus.OutOfRange;
        return ParseStatus.NotParsable;
    }
    output = tempInteger;

    return ParseStatus.Success;
}

Another problem is the existence of the out variable.  Your third option is to use a descriptive monad, something like this:
public Maybe<int?> TryParseNullableInt(string input)
{
    if (input == null) return Maybe.Success(null);
    if (input == string.Empty) { return Maybe.Derived(0); }

    int tempInteger;
    if (!int.TryParse(input, out tempInteger)) {
        if (ParseWords(input, out tempInteger)) { // "Twenty Three" = 23
            return Maybe.Derived(tempInteger);
        }
        long tempLong;
        if (long.TryParse(input, out tempLong))
            return Maybe.OutOfRange();
        return Maybe.NotParsable();
    }

    return Maybe.Success(tempInteger);
}

You can use Monads as Single-Enumerable Values, or like so:
Maybe<int?> result = TryParseNullableInt("Hello");
if (result.HasValue) {
    if (result.Status == ParseStatus.Success)
        // Do something you want...
    else if (result.Status == ParseStatus.Derived)
        // Do something else... more carefully maybe?
}
else if (result.Status == ParseStatus.OutOfRange)
    MessageUser("That number is too big or too small");
else if (result.Status == ParseStatus.NotParsable)
    // Do something

With Monads, and possibly enumeration TryParses, you now have all the info you need from a descriptive return and nobody has to guess what null might mean.
Comment: Great answer! I've just thinking about replacing TryParse pattern with simply Maybe monad. I think that 'out' parameter adds unnecessary complexity. For simpler scenarios I even use a named tuple that has better support nowadays. `(success, result) = FuncName(..);`
`public (bool success, Subject result) FuncName (args..) {}`

Whoa, what the TryParse


Position Vectors, please help!

Question: If anyone is able to help with this question that would be great, I'm very confused at the moment with my a-b or a+b.
The solution given to me is super basic, and only provides an answer. Would really be grateful for an explained solution.
Thanks
Click for question :)
Here's a text version:

Let A, B, C be three points with position vectors a, b, c respectively.
Write down, in terms of a, b, c, the position vectors
m of M which is on AB, three-fifth of the distance from A to B;
n of N which is on CM, five-eleventh of the distance from C to M.
  Show that the vector AN is a multiple of the vector (NB + 2NC).
Answer: $$m=a+\frac{3}{5}(b-a)=\frac{3}{5}b+\frac{2}{5}a.$$
$$n=c+\frac{5}{11}(m-c)=\frac{5}{11}m+\frac{6}{11}c=\frac{5}{11}\left(\frac{3}{5}b+\frac{2}{5}a\right)+\frac{6}{11}c=$$
$$=\frac{3}{11}b+\frac{2}{11}a+\frac{6}{11}c.$$
Thus, $$\vec{AN}=-\frac{9}{11}a+\frac{3}{11}b+\frac{6}{11}c.$$
Now, $$\vec{NB}+2\vec{NC}=b-n+2(c-n)=b+2c-3n=-\frac{6}{11}a+\frac{2}{11}b+\frac{4}{11}c,$$
which says
$$\vec{AN}=\frac{3}{2}\left(\vec{NB}+2\vec{NC}\right).$$
Comment: Great that is super helpful, makes complete sense now.
Comment: If its not too much to ask, do you have a drawing of this solution?
Comment: Yes, of course I have a picture, but I don't know to draw in the net.
Comment: If you could attach an imgur link that would be so great !
Comment: Why you can not draw it by yourself?
Comment: The image I draw doesn't really make sense, I'm imagining they start at an origin O which is completely wrong, so geometrically it confuses me. Sorry.
Comment: You can take the origin in any point. It does not change anything.
Comment: Really? And these points will still fall along a line?
Comment: Yes, of course! But it's better to take the origin away  from given points.
Comment: You are welcome!

Position Vectors, please help!


how to check availability seats in c code linked list

Question: I want to show the availability of the seats in linked list, but I don't know somehow the logic in the chekcavailability() doesn't work.
First input is okay, the second input when I entered the same value it shows seat has been taken and return back to the particular function.
But when I enter again the different value which is available, it gives me an error.
Please help thank you.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>

#define A 20

struct passenger
{
char name[20];
char booking_id[20];
char passno[20];
char seatno[20];
struct passenger *next;
}*start,*curr;

void datainput(), savefile(), loadfile(), checkavailability(),   validationseat();

int main()
{
void reserve_seat(), cancel_seat(), modify_seat(), display_layout(), exit();
int choice;
start=curr=NULL;

do
{

    system("cls");
    printf("\n\n*************************************************");
    printf("\n\n********AIRLINE RESERVATION MENU*****************");
    printf("\n\n*************************************************");
    printf("\n\n\t\t* 1. Reserve seat       *");
    printf("\n\n\t\t* 2. Modify seat        *");
    printf("\n\n\t\t* 3. Cancel seat        *");
    printf("\n\n\t\t* 4. Display seat layout*");
    printf("\n\n\t\t* 5. Exit               *");
    printf("\n\n*************************************************");
    printf("\n\n\n\n\t\t Enter your choice: ");
    scanf("%d",&choice);fflush(stdin);
    switch (choice)
    {
    case 1:
        reserve_seat();
        break;

    case 2:
        modify_seat();
        break;

    case 3:
        cancel_seat();
        break;

    case 4:
        display_layout();
        break;
    case 5:
        {
        exit();
        break;
        }
    default:
        printf("invalid choice!!, please try again");
    }
    getch();

}while (choice != 5);

}

void datainput()
{
printf("\n\t\t enter your booking ID: ");
gets(curr->booking_id); fflush(stdin);
printf("\n\t\t enter your seat number: ");
gets(curr->seatno); fflush(stdin);
printf("\n\t\t Enter Name: ");
gets(curr->name); fflush(stdin);
printf("\n\t\t Enter Passport Number: ");
gets(curr->passno); fflush(stdin);

}

void reserve_seat()
{
curr=start;
checkavailability();
if(start==NULL)
    {
        start=curr=(struct passenger *)malloc(sizeof(struct passenger));
        datainput();
        curr->next=NULL;
        printf("\n\t data has been recorded");
        return;
    }
    while(curr->next=NULL)
        curr=curr->next;
    curr->next=(struct passenger *)malloc(sizeof(struct passenger));
    curr=curr->next;
    datainput();
    curr->next=NULL;
    printf("\n\t data has been recorded");

void checkavailability()
{
int i;
char cmp3[20];
printf("select your seat(1-20)");
gets(cmp3);fflush(stdin);
while(curr)
{
    if (strcmp(curr->seatno, cmp3)==0)
    {
        printf("Seat has been taken\n");
        checkavailability();
    }
    else
    {
        break;
    }
}
printf("seat available");
return;
}

Comment: Take your time edit your post and then post it . ok . correct all the errors pointed by Tom . then post it
Answer: There are many error with your code, and the worst is that he cannot compile (unless conio declare an exit function with no parameter).
First, you need to activate a decent compiler option. At least -Wall -Wextra (depend of the compiler).
In main function, this : exit();
The exit function need a parameter. Fix that.
modify_seat();
cancel_seat();
display_layout();

These function aren't implemented, so you shouldn't make a call to them. Fix that either.
Do not use gets ! It's dangerous and unsafe.
Do not fflush(stdin) ! It's undefined behavior.
The "A" define is useless and not really explicite. What was it supposed to be ? "Array" ?
For your safety, try to not use global variable.
I suggest to define a structure and declare a variable in main.
In "reserve_seat" :
 while(curr->next=NULL)
you made a mistake here : it's  while(curr->next != NULL)
You assign NULL to curr->next, maybe it's the reason that why your linked list is broken.
Well, it's a dirty code for me, because it severly lack rigourous coding.
For example, check if your function call failed (like malloc).
I suggest you to rewrite the code.
Comment: sorry for  my bad behavior, actually i didnt send the full code, because its too long, i just send the specific that is matter to the problem i counter, basically i only need the logic for check the availability, thank you very much for the answer and suggestion
Comment: Yep, but for our sake, give us an MVC (Minimal, Complete, and Verifiable) example, especialy because you use global variable !
Frankly, your code is like playing the russian roulette with a semi-automatic pistol.
Comment: should i ask the same question with the full code?, where should i put it by the way?
Comment: In MVC, there is M (Minimal), so no, you shouldn't put the full code.
http://stackoverflow.com/help/mcve


how to add a selector color to a view programmatically

Question: as shown below in the code, i have some views and i want to add a selector color to the view, so that when the view is clicked its color changes. exactly as happens when one clicks on an item in a listview, that's what i am
trying to do.
i referred to some posts and i troed both of the following:
view.setBackgroundResource(android.R.attr.listChoiceBackgroundIndicator);//highlighted with red color
view.setBackground(android.R.attr.listChoiceBackgroundIndicator);//highlighted with red color

but it doesnt work and AndroidStudio highlight them with red color.
please let me know how to add a selector color to my vies programmatically
code:
LayoutInflater inflator = this.getLayoutInflater();
    final View view = inflator.inflate(R.layout.versicherungs_docs_footer, null);

    RelativeLayout relLay = (RelativeLayout) view.findViewById(R.id.versicherungslisteactivity2_meinedocs_lisvie_footer_mainContainer);
    final TextView texVieShowMore = (TextView) view.findViewById(R.id.versicherungslisteactivity2_meinedocs_lisvie_footer_texVie_showMore);
    final TextView texVieShowLess = (TextView) view.findViewById(R.id.versicherungslisteactivity2_meinedocs_lisvie_footer_texVie_showLess);
    final TextView texVieShowMoreArrow = (TextView) view.findViewById(R.id.versicherungslisteactivity2_meinedocs_lisvie_footer_texVie_showMoreArrow);
    final TextView texVieShowLessArrow = (TextView) view.findViewById(R.id.versicherungslisteactivity2_meinedocs_lisvie_footer_texVie_showLessArrow);

    view.setBackgroundResource(android.R.attr.listChoiceBackgroundIndicator);//highlighted with red color
    //view.setBackground(android.R.attr.listChoiceBackgroundIndicator);//highlighted with red color

Comment: So do you want to change item's background once clicked? (and by item I'm refering to a listItem)
Comment: yes i wantto change the color of the background once clciked..and my views in the posted code, are normal views as you can see..it is nt a listview
Comment: it should work with setBackgroundResource, can you add the full example?
Comment: @petrumo have you checked [this question](http://stackoverflow.com/questions/4761686/how-to-set-background-color-of-an-activity-to-white-programmatically)?
Comment: yes i have just checked it..but if you realized in my question, i want to set "android.R.attr.listChoiceBackgroundIndicator" as a background to the view when clciked..and i could not find answer for that in our website
Answer: You need to get the drawable that points to  android.R.attr.listChoiceBackgroundIndicator as suggested in this link and set it programatically.
// Create an array of the listChoiceBackgroundIndicator attribute
int[] attrs = new int[] { listChoiceBackgroundIndicator /* index 0 */};

// Obtain the styled attributes. 'themedContext' is a context with a
// theme, typically the current Activity (i.e. 'this')
TypedArray ta = themedContext.obtainStyledAttributes(attrs);

// To get the value of the 'listChoiceBackgroundIndicator' attribute that was
// set in the theme used in 'themedContext'. The parameter is the index
// of the attribute in the 'attrs' array. The returned Drawable
// is what you are after
Drawable drawableFromTheme = ta.getDrawable(0 /* index */);

// Then, free the resources used by TypedArray
ta.recycle();

// Finally, set drawable as background
view.setBackground(drawableFromTheme);

Comment: i tried your answer, actually i did not work there is no effect when the view is clicked moreover, it is available from API 16 while i am targeting API 15


How to secure wardrobe to wall if 1.25" gap exists between wall and wardrobe

Question: How do a secure a wardrobe to a wall if there is a roughly 1.25" gap between the wall and the wardrobe due to the molding on the wall? I'd prefer to not have a screw visibly poking out the back of the wardrobe and going into the wall because it positioned where it will be visible often. Are there any tricks I can employ to avoid the eyesore? Thanks!
Comment: Is this a permanent wardrobe?
Answer: I'd fasten a decorative/coordinating rail to the upper back of the wardrobe, or to the wall in that position, such that it appears to be a component of the wardrobe. Screw through the wardrobe back and the block into the wall. Its design depends on the design of the cabinet.
Comment: What does a coordinating rail look like? I'm a bit of a DIY noob.
Comment: I have no idea. Post a photo and I'll take a crack at it.
Comment: http://imgur.com/a/bVvv5
Comment: It is IKEA furniture. The doors are very heavy and the wardrobe leans forward when the doors open. The red circle areas are the designated holes to secure the wardrobe to the wall. The green circle indicates where the screws will come through. It is right next to the bed so if a screw were to come through it would be highly visible. Thanks for your help!
Answer: You might try something like the Hangman Anti-Tip kits.  You can locate the anchors in the middle of the wardrobe so that the hardware isn't easily visible.  You would need to hit a stud to really get holding power.
Editing to add that while that would mean cutting a hole through the back panel, this is IKEA furniture, so the back panel is really just cardboard.  The anchors for the anti-tip install to the underside of the top, so if this is the route you try, be sure the screws you are using won't poke through the top!
Comment: Wow! Didn't know something like this existed! The top is thick enough so the screws won't poke through. I'm going with this. Thanks a lot!
Comment: How is this solution different from a screw showing at the middle of the wardrobe?
Comment: isherwood, It's not different from a screw showing in the middle of the wardrobe. It is better than one screw at each end of the wardrobe. You'd really have to look behind the wardrobe to see in the middle. Thanks for your help!


Equivalence for bounded sets

Question: Let $(X,d)$ be a metric space and $A \subset X$. Show that $A$ is bounded if and only if there exists a constant $\lambda > 0$ such that $A \subset \lambda \mathcal{B}_{1}(0)$ where $\mathcal{B}_{1}(0)$ is the unit ball centered at $0$.
Now for my proof, I've two definitions: $A$ is bounded if the diameter $d(A) \leq M < \infty$ or $A$ is bounded if there exist $r>0$ and $a \in A$ such that $A \subset \mathcal{B}_{r}(a)$. With the second definition, I can see why the statement holds; if $A \subset \mathcal{B}_{r}(a)$ I can "move" the center of the ball to $0$ and dilate the radius as necessary. What I should prove is that if $x \in A$ then $x = \lambda y$ with $d(y,0) < 1$ for some $\lambda >0$, but how can I relate these concepts to give a formal proof? Thanks
Edit: the diameter of a set is $d(A) = \sup_{x,y \in A} d(x,y)$
Comment: So one needs to assume $X$ has $0$ as an element?
Comment: @hardmath added
Comment: @coffeemath I was thinking the same. I guess so
Answer: For this theorem to be true, some relation between scalar multiplication and the metric has to be assumed, otherwise it may be false. For example, with the discrete metric, every subset is metrically bounded but only $\{0\}$ is topologically bounded. Usually the following axiom is assumed: $$d(\lambda x,\lambda y)=|\lambda|d(x,y)$$ In what follows, the slighly weaker axiom $d(\lambda x,\lambda y)\le c\lambda\, d(x,y)$ for $\lambda>0$ is taken.
Let $A$ be metrically bounded, $\mathrm{diam}(A)\le M$. Fix a point $x_0\in A$. Then for any $x\in A$, $$d(x,0)\le d(x,x_0)+d(x_0,0)\le M+d(x_0,0)=:r$$ Let $\lambda>cr$ and $x':=x/\lambda$; then $$d(x',0)=d(x/\lambda,0)\le \frac{c}{\lambda}d(x,0)<1$$ so $A\subseteq\lambda B_1(0)$.
Let $A$ be topologically bounded, $A\subseteq \lambda B_1(0)$. Then for any $x,y\in A$, $x=\lambda x'$, $y=\lambda y'$ with $x',y'\in B_1(0)$. $$d(x,y)=d(\lambda x',\lambda y')\le c\lambda d(x',y')\le c\lambda(d(x',0)+d(0,y'))<2c\lambda$$ so $\mathrm{diam}(A)\le2c\lambda$.
Comment: Thanks, I understand your answer, but how are you using the set $\lambda B_{1}(0)$? I mean, I though that I've to prove that if $x \in A$ then $x \in \lambda B_{1}(0)$ which means that $x = \lambda y$ with $d(y,0) < 1$. First I though that $\lambda B_{1}(0) = B_{\lambda}(0)$ but that's not true.
Comment: @Jeybe See amended answer.

Equivalence for bounded sets


How to set height and width of iframe code which is inside textbox using jquery

Question: I have a textbox in which uers will paste the embed code of video.
Now i want to change the width and height according to me and also if there is no width or/and height property then it must be automatically added.
Please help me.
Thanks in advance.
HTML:

         IFrame Code:

        <asp:TextBox Style="width: 250px;height: 50px" onblur="validate()"
             ID="txturl" runat="server" CssClass="Textbox1"
             TextMode="MultiLine">
        </asp:TextBox>

Answer: i would recommend using a jQuery plugin (there are plenty).
take a look at jQuery Autosize.
hope that helps.
Comment: i want to change the height of that iframe which is inside textbox.
Comment: you can't put an iframe in a textbox
Comment: i am putting iframe code in the textbox and this code will be stored in database and on another page this code will be retrieved in "literal" text property.


Compactness used to get a covering by special smaller balls

Question: Suppose $(X,d)$ is a compact metric space. Suppose we have a set $A \subseteq X$ such that the set of open $\epsilon$-balls around the points of $A$ cover $X$. I've read that "By compactness, there exists $\epsilon_{1} < \epsilon$ such that the $\epsilon_{1}$-balls centered at the points of $A$ also cover $X$." Do any of you have hints for how to think about this/get running with this? I know that compact metric spaces are totally bounded, so for any $\epsilon_{2}$ there's a finite collection of $\epsilon_{2}$-balls that cover $X$, but then we don't have any information about whether or not (any) of those balls are centered around our desired points.
There's a little bit of information about $A$ that I don't think is needed - if it is, however, I'll gladly provide it.
Thanks for any hints!
Answer: Consider the open cover $B(a, \delta)$ for all $a \in A$ and all $\delta < \epsilon$. Since $X$ is compact, there is a finite subcover $B(a_i, \delta_i)$ for $i \in \{1, \ldots, n\}$. Now put $\epsilon_1 = \max(\delta_i : i \in \{1, \ldots, n\})$.
Answer: Let $x_1,...x_n$ be points such that $\bigcup_1^nB_\epsilon(x_i)=X$. For $x_1$ the function $d(x_1,y):X-\bigcup_2^n B_\epsilon(x_i)\to\Bbb R$ attains a maximum $m$ since the domain is compact. This $m$ must be smaller than $\epsilon$, so choose $m<\epsilon_1<\epsilon$. Then $B_{\epsilon_1}(x_1)\cup\bigcup_2^n B_{\epsilon}(x_i)$ still covers $X$, so we can replace the $\epsilon-$balls by $\mathcal U_1:=\{B_{\epsilon_1}(x_1),B_{\epsilon}(x_2),...,B_{\epsilon}(x_n)\}$. Again the set $X-\bigcup\mathcal U_1$ is compact, and by the same argument there is an $\epsilon_2<\epsilon$ such that $\mathcal U_2:=\{B_{\epsilon_1}(x_1),B_{\epsilon_2}(x_2),B_{\epsilon}(x_3),...,B_{\epsilon}(x_n)\}$ is still an open cover of $X$. Repeating this process gives you a finite number of values each smaller than $\epsilon$. Let $\delta=\max\{\epsilon_1,\epsilon_2,...,\epsilon_n\}$, then the balls $B_\delta(x_i)$ form an open cover of $X$.
We have proven that there exists a so-called shrinking of the original cover.