text:
Q: is there a way to solve Python, TypeError: string indices must be integers for data downloaded from yahoo finance I am working on building a machine learning model. I got the data in CSV format from yahoo finance. In this code snippet I am trying to figure out the daily moving average, but I am getting a 'Value Error' if try to convert using the code:
df[Moving_Average] = df['Adj Close'].rolling(ma).mean()

MY ACTUAL CODE

ma_day = [10,30,50]
for ma in ma_day:
    for df in df:
        Moving_Average = f"MA for {ma} days"
        df[Moving_Average] = df['Adj Close'].rolling(ma).mean()

 ***THE ERROR***
    --------------------------------------------------------------------------- TypeError                                 Traceback (most recent call last) /var/folders/m_/7qrjlgz130q_m51m48k7h0w80000gn/T/ipykernel_1389/3705405762.py in <module>
      6     for df in df:
      7         Moving_Average = f"MA for {ma} days"
----> 8         df[Moving_Average] = df['Adj Close'].rolling(ma).mean()

TypeError: string indices must be integers

A: Your for df in df is the problem. Remove it and it works
import pandas as pd
from numpy.random import random

df = pd.DataFrame(data=random(100), columns=["Adj Close"])
ma_day = [10, 30, 50]
for ma in ma_day:
    Moving_Average = f"MA for {ma} days"
    rolling = df['Adj Close'].rolling(ma).mean()
    df[Moving_Average] = rolling

print(df)

Output:
    Adj Close  MA for 10 days  MA for 30 days  MA for 50 days
0    0.614659             NaN             NaN             NaN
1    0.464262             NaN             NaN             NaN
2    0.818697             NaN             NaN             NaN
3    0.620061             NaN             NaN             NaN
4    0.277084             NaN             NaN             NaN
..        ...             ...             ...             ...
95   0.921534        0.485049        0.448652        0.510355
96   0.016339        0.409455        0.440603        0.498022
97   0.460253        0.451836        0.439674        0.490771
98   0.421445        0.431691        0.445054        0.490880
99   0.665695        0.494151        0.442298        0.499515

[100 rows x 4 columns]


text:
Q: Releasing root view controller I have the following statement inside
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

The statement is :
root_view_controller = [[Root_View_Controller alloc] initWithNibName:@"Base_View" bundle : nil];

I am not using ARC, so I am thinking of releasing root_view_controller in
- (void)applicationWillTerminate:(UIApplication *)application

My question is : Is the above practice ok ?   And : Is there any other clean up code that should be added before releasing root_view_controller ?

A: AppDelegate.m
- (void)dealloc
{
    [_window release];
    [_viewController release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    self.viewController = [[[MLViewController alloc] initWithNibName:@"MLViewController" bundle:nil] autorelease];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

If you want release your Root_View_Controller you need to do it in dealloc method like the code above

A: There is no need to release memory in
- (void)applicationWillTerminate:(UIApplication *)application

because when an app is terminated, the memory it used is released anyway.

redpajama_set_name: RedPajamaStackExchange


text: Q: How do i hide certain forms like signin forms when a person is logged in? Currently i am using sessions to accomplish that and everything like displaying an error msg to restrict access to a page to everything and it is messy.Is there a better way to do it?As of right now i only know php a bit.


text:
Q: Crontab : Running a jar file I have a jar file that generates reports and i want to schedule to run it on every sunday,
For this purpose, i am using the crontab functionality on linux,
i have created the crontab entry using
     crontab -e
     45 15 * * 1 /usr/java/default/bin/java -jar /home/name/example/withouttimer.jar

but the job does not run as it should, Can you please help me find the issue with it,
Is there a way to check crontab logs?, thanks

A: Probably the profile used when running cron jobs does not have some variables set (JAVA_HOME? CLASSPATH?)
Do a crontab that does printenv > myfile.txt and check what is defined.

As a last test, create a .sh file and run it, that does
echo 'hello'
printenv
echo 'goodbye'

and see if redirecting the execution of your script to a log shows something.

A: That job runs at 3:45 pm on every monday (0 is for sunday)Are you sure you are checking it at right time?
Try running a dummy program at lesser interval to check whether its working.

A: Finally got the solution,
There was a couple of things that i was doing incorrectly,

*

*The timezone of the server was different, so i had to set it accordingly.

*The jar was not able to locate the input file(bad location), had to fix it.
Works gr8 now, thanks for the suggestion on adding MAILTO= , helped in debugging.


text:
Q: Redirect to Mobile site? When the user join my site.. if they use mobile.. I want to redirect to the mobile site..
How can I do that with javascript or .net?

A: Put this on your page load:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If Request.Browser("IsMobileDevice") = "True" Then
Response.Redirect("put url here", True)

End If

End Sub

Hope this will help.

A: Typically, you'd compile a list of user-agent strings for mobile browsers and extract which patterns you want to handle. Then in your server code, send a 302 response header OR issue a page with a META refresh to your mobile URL.


text:
Q: Sending Email with attachment from Parse.com I am working on my first IOS app which will be displayed in a public place where a user can draw an image and send this image to an email adres. I don't want to use Mail for this and the image also can not be stored on the iPad.
Therefore, i use Parse.com to store the image including name and email adres.
Now, i need to make a simple interface to send all the emails to the correct email adres including the image. We would like to check the image an email adres before sending. So i was thinking of showing some sort of tabel, with the image, name and emailadres and a send or delete button. So with a quick click we can send the image.
Now I don't know where to start!
What is the most easy way to do this? Making a second IOS app where all the images will be shown and can send/delete from? Using Mailgun and Cloud Code?
Or true a web-base interface? Using PHP?
I am all very new to this, so please help me.

A: Parse integrates with mail services like Mandrill so you can send e-mails from there using cloud code.
You need to have some users in the system, or some store of user details at least, then you can upload the images. Look at using a class for images, where the class just has a single PFFile and a relationship to a user.
Now, in your app you can display images and the associated user info. When hitting the 'send' button you would call a cloud function with the image objectId. The cloud code can use that to find the image, it can use Parse.Cloud.httpRequest to get the data for the image from the PFFile. Once you have that you can create your e-mail and send it.


text:
Q: How can I use wildcards to `cp` a group of files with the AWS CLI? I'm having trouble using * in the AWS CLI to select a subset of files from a certain bucket.
Adding * to the path like this does not seem to work:
aws s3 cp s3://data/2016-08* .

A: The Order of the Parameters Matters
The exclude and include should be used in a specific order, We have to first exclude and then include. The vice versa of it will not be successful.
aws s3 cp s3://data/ . --recursive  --include "2016-08*" --exclude "*"

This will fail because order of the parameters maters in this case. The include is excluded by the *.
aws s3 cp s3://data/ . --recursive --exclude "*" --include "2016-08*"`

This one will work because then we excluded everything, but later we had included the specific directory.

A: To download multiple files from an Amazon AWS bucket to your current directory, you can use the recursive, exclude, and include flags. The order of the parameters matters.
Example command:
aws s3 cp s3://data/ . --recursive --exclude "*" --include "2016-08*"

For more information on how to use these filters: Use of Exclude and Include Filters

A: Okay I have to say the example is wrong and should be corrected as follows:
aws s3 cp . s3://data/ --recursive --exclude "*" --include "2006-08*" --exclude "*/*"

The . needs to be right after the cp. The final --exclude is to make sure that nothing is picked up from any subdirectories that are picked up by the --recursive (learned that one by mistake...)
This will work for anyone struggling with this by the time they got here.

A: If there is an error while using ' * ' you can also use recursive, include, and exclude flags like
aws s3 cp s3://myfiles/ . --recursive --exclude "*" --include "file*"


text:
Q: Armadillo Does not Find BLAS Linear Algebra Package I have cross-compiled Armadillo for ARMv7 using my Red Hat.
When I try to do matrix multiplication I get the error:
armadillo_bits/blas_wrapper.hpp:79: undefined reference to `wrapper_dgemv_'

I built BLAS and LAPACK from source, it seems to find LAPACK as it lets me do Cholesky decomposition without errors.
I have built like this:
arm-linux-gnueabihf-g++  -march=armv7-a     -mthumb-interwork -mfloat-abi=hard
-mfpu=neon
-mtune=cortex-a9 --sysroot=/home/mg/yocto/build/tmp/sysroots/socfpga_cyclone5
-DHAVE_CONFIG_H -I. -I..   --sysroot=/home/mg/yocto/build/tmp/sysroots
/socfpga_cyclone5  -g -O2 -L/opt/altera-linux/linaro/gcc-linaro-arm-linux-gnueabihf-
4.7-2012.11-20121123_linux/arm-linux-gnueabihf/lib -I/opt/altera-linux/linaro
/gcc-linaro-arm-linux-gnueabihf-4.7-2012.11-20121123_linux/arm-linux-gnueabihf
/include  -llapack -lf2c  -lblas -lm --sysroot=/home/mg/yocto/build/tmp/sysroots
/socfpga_cyclone5 -MT AlgoLibTests.o -MD -MP -MF .deps/AlgoLibTests.Tpo -c -o
AlgoLibTests.o AlgoLibTests.cpp

I put my BLAS and LAPACK here:
/opt/altera-linux/linaro/gcc-linaro-arm-linux-gnueabihf-
4.7-2012.11-20121123_linux/arm-linux-gnueabihf/lib

If I disable that BLAS support, it does the calculations very slowly.
This is defined in the config file
ARMA_USE_BLAS

And this is disabled.
ARMA_USE_WRAPPER

ATLAS is also disabled.  Why does it not find that BLAS library?

A: I encountered this error too when I tried to compile Armadillo for my Android project. I am sure that ARMA_USE_WRAPPER is not yet disabled. That is why you get the error undefined reference to `wrapper_dgemv_'. Check it again.
I also notice that the matrix computation on Mobile is way slower than that in my Mac OS.


text:
Q: how can i go about checking if a file exists
Possible Duplicate:
C check if file exists

I was just wondering if someone could point me in the right direction regarding to how I should go about checking if a file exists? At this point in time I plan on going with something along the lines of the following;
if(NULL==(fp=fopen(filepath, "r"))){

my ultimate goal would be to find a solution to replace this in bash (just the file finding part)
if ! (find /dev/shm/request-summon-*-$MCEXEC_PLAYERNAME.txt > /dev/null 2>&1); then

any help is really appreciated, thanks!

A: Look at the manual page for stat() also covering lstat() and fstat(). If you get -1 as the return value, the file you tried to get summary information on does not exist, or may not have rights to read it (see last example below which shows the difference from your fopen() test as a file may exist but not let you open it).
edd@max:/tmp$ cat stat.c

#include <stdio.h>

int main(int argc, char *argv[]) {
    if (argc > 1)
        printf("Returned %d for %s\n", stat(argv[1]), argv[1]);
}
edd@max:/tmp$ gcc -o stat stat.c
edd@max:/tmp$ ./stat stat.c
Returned 0 for stat.c
edd@max:/tmp$ ./stat does-not-exist
Returned -1 for does-not-exist
edd@max:/tmp$ ./stat /root/.ssh/id_dsa    ## exists, but I can't read it
Returned -1 for /root/.ssh/id_dsa
edd@max:/tmp$

A: Use stat() or lstat(). Personally I prefer using lstat() because it tells you whether a directory entry is a symbolic link, rather than following the link.
For your ultimate goal, traverse the directory tree. You can do this with opendir() and readdir().

A: On a POSIX system, you can try to open the file and check whether errno == ENOENT if it fails (returns NULL):
if ((fp = fopen(path, "r")) == NULL)
    if (errno == ENOENT)
        // file doesn't exist

There's no pure ISO C way of doing this.
Using stat or lstat is also possible, but can lead to a race condition when the file is created in between the stat and the opening of the files.


text:
Q: senfing POST in fetch return null I want to learn how fetch works. Backend is very simple
<?php
    print_r(json_encode($_POST['test']));

And I created this fetch
fetch('http://localhost/test.php', {
    method: 'POST',
    body: JSON.stringify({
        test: 'test'
    })
})
     .then(res => res.json())
     .then(data => console.log(data))

All the time this code return null in console.log. Where I make a mistake?

A: You have two problems.
Strings and Fetch
If you POST a string using fetch it will default to sending it with a Content-Type: text/plain header.
Plain text isn't JSON. Specify the correct Content-Type.
fetch('http://localhost/test.php', {
    method: 'POST',
    headers: {
        "Content-Type": "application/json",
    },
    body: JSON.stringify({
        test: 'test'
    })
})

PHP won't process JSON formatted requests automatically
You need to read the raw body and parse it yourself. This is a FAQ. Here is the solution.


text:
Q: File was not quarantined properly when trying to install chromedriver using brew I have already tried to install via brew cask install chromedriver but I get this error:
Error: /Library/Caches/Homebrew/downloads/42621d77ecaa889fa8ca73ac4b2a2228e3c1d11f20d84c6898e7645397d00f1d--chromedriver_mac64.zip was not quarantined properly.

How do I fix this error? I am using macOS High Sierra version 10.13.5


text:
Q: Magento 1.9 out of memory I have a project installed by git, composer dependencies are updated, database installed (/app/etc/config.xml). Running xampp with php 7.1 (4GB memory limit).
PHP throws the same error every time, memory limit doesn't affect this.

Fatal error: Allowed memory size of 2147483648 bytes exhausted (tried
  to allocate 262144 bytes) in
  Z:\www\app\code\core\Mage\Core\Model\Resource.php on line 209

'tried to allocate bytes' doen't change with php memory limit. How to troubleshoot that problem?
Z:\www\app\code\core\Mage\Core\Model\Resource.php
/**
 * Retrieve default connection name by required connection name
 *
 * @param string $requiredConnectionName
 * @return string
 */
protected function _getDefaultConnection($requiredConnectionName)
{
    if (strpos($requiredConnectionName, 'read') !== false) {
        return $this->getConnection(self::DEFAULT_READ_RESOURCE);
    }
    return $this->getConnection(self::DEFAULT_WRITE_RESOURCE); // <-- line 209
}


text:
Q: unable to install gcc-multilib after upgrading to 14.04 I recently upgraded from 12.04 to 14.04. After upgrading things started to break.
I am getting crt1.o: No such file: No such file or directory. So, I  tried to install gcc-multilib, but, that is also running into errors.
$ sudo apt-get install gcc-multilib
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 gcc-multilib : Depends: gcc-4.8-multilib (>= 4.8.2-5~) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

I tried
$ sudo apt-get -o Debug::pkgProblemResolver=yes dist-upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Starting pkgProblemResolver with broken count: 0
Starting 2 pkgProblemResolver with broken count: 0
Done
Done
Starting pkgProblemResolver with broken count: 0
Starting 2 pkgProblemResolver with broken count: 0
Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

I tried to post the output of the following commands but I am unable to do it.
cat /etc/apt/sources.list
cat /etc/apt/sources.list.d/*

How can I resolve this?
 $ sudo apt-get install gcc-4.8-multilib

 Reading package lists... Done
 Building dependency tree
 Reading state information... Done
 Some packages could not be installed. This may mean that you have
 requested an impossible situation or if you are using the unstable
 distribution that some required packages have not yet been created
 or been moved out of Incoming.
 The following information may help to resolve the situation:

 The following packages have unmet dependencies:
  gcc-4.8-multilib : Depends: lib32gcc-4.8-dev (= 4.8.2-19ubuntu1) but it is not going to be installed
                    Depends: libx32gcc-4.8-dev (= 4.8.2-19ubuntu1) but it is not going to be installed
 E: Unable to correct problems, you have held broken packages.

 $ sudo apt-get install lib32gcc-4.8-dev

 Reading package lists... Done
 Building dependency tree
 Reading state information... Done
 Some packages could not be installed. This may mean that you have
 requested an impossible situation or if you are using the unstable
 distribution that some required packages have not yet been created
 or been moved out of Incoming.
 The following information may help to resolve the situation:

 The following packages have unmet dependencies:
  lib32gcc-4.8-dev : Depends: lib32gcc1 (>= 1:4.8.2-19ubuntu1) but it is not going to be installed
                    Depends: libx32gcc1 (>= 1:4.8.2-19ubuntu1) but it is not going to be installed
                    Depends: lib32asan0 (>= 4.8.2-19ubuntu1) but it is not going to be installed
                    Depends: libx32asan0 (>= 4.8.2-19ubuntu1) but it is not going to be installed
 E: Unable to correct problems, you have held broken packages.

$ sudo apt-get install lib32gcc1 libx32gcc1 lib32asan0 libx32asan0

 Reading package lists... Done
 Building dependency tree
 Reading state information... Done
 Some packages could not be installed. This may mean that you have
 requested an impossible situation or if you are using the unstable
 distribution that some required packages have not yet been created
 or been moved out of Incoming.
 The following information may help to resolve the situation:

 The following packages have unmet dependencies:
  lib32gcc1 : Depends: gcc-4.9-base (= 4.9-20140406-0ubuntu1) but 4.9.1-0ubuntu1 is to   be installed
  libx32gcc1 : Depends: gcc-4.9-base (= 4.9-20140406-0ubuntu1) but 4.9.1-0ubuntu1 is    to be installed
 E: Unable to correct problems, you have held broken packages.

 $ apt-cache policy lib32gcc-4.8-dev  lib32gcc1 gcc-4.9-base

 lib32gcc-4.8-dev:
  Installed: (none)
  Candidate: 4.8.2-19ubuntu1
  Version table:
     4.8.2-19ubuntu1 0
        500 http://archive.ubuntu.com/ubuntu/ trusty/main amd64 Packages
 lib32gcc1:
  Installed: (none)
  Candidate: 1:4.9-20140406-0ubuntu1
  Version table:
     1:4.9.1-0ubuntu1 0
        100 /var/lib/dpkg/status
     1:4.9-20140406-0ubuntu1 0
        500 http://archive.ubuntu.com/ubuntu/ trusty/main amd64 Packages
 gcc-4.9-base:
  Installed: 4.9.1-0ubuntu1
  Candidate: 4.9.1-0ubuntu1
  Version table:
 *** 4.9.1-0ubuntu1 0
        100 /var/lib/dpkg/status
     4.9-20140406-0ubuntu1 0
        500 http://archive.ubuntu.com/ubuntu/ trusty/main amd64 Packages

Link to the output of sudo apt-get update: http://paste.ubuntu.com/9810181/

A: I do not often use aptitude, but in case of problems with different gcc versions and unmet dependencies, apt-get is some times unable to correct problems saying "you have held broken packages"
That's the day, you should install aptitude, and try to install the package you wish.
It clearly shows all dependencies and makes not only one suggestion.
First suggestions is often the same apt-get would do, but if you click "no" aptitude will show you another one, which maybe fits your needs better.
Give it a try!

Answer is a little late, but I often searched for problems like these and was happy about different solutions.

A: The observed behavior seems to result from a legitimate bug that is described at
https://bugs.launchpad.net/ubuntu/+source/eglibc/+bug/1365375
The above-cited report contains my short-term workaround that will render apt-get usable again.
I believe that, in essence, sudo apt-get -f install fails is a duplicate of this question.


text:
Q: Is there any way to get the date on which the application was compiled? React Native App I need to pass the date of the day which the application was compiled. I mean, if tomorrow I compile and launch version 3.4 of my app, I need to save it into a variable local. I obviously could do it by saving the date manually before compile, but I need to save it in another way to avoid to forget to change the local variable before compile it.
My application is powered by React-Native. So I was searching a library to do it with but i had no luck.


text:
Q: Multiple logic cheks for if-clause in JavaScript I've got 2 variables: dif and j and I want to execute some code only if dif is 10 and j is 0 or 1 OR if dif is -10 and j is 2 or 3. I tried:
if (((dif == 10) && (j == 0 || 1)) || ((dif == -10) && (j == 2 || 3)))

but then the code is executed as soon as dif is -10 and j is 0.

I've also tried with less brackets, same problem.


text:
Q: What is the use of the different libraries? In VS so are so many different libraries. I dont know which one to choose to create a reusable library for different projects. Can someone please explain the usage of each of the following when and why to pick which one.
Here is a list of the available libraries:

*

*WCF service library

*Class library (.NET Core)

*Class library (.NET Standard)

*Class library (.NET Framework)

*Class library (portable)

*Class library (universal windows)

A: For your case you should go for Class library (.NET Framework). Am not sure about all of them but

*

*WCF service library: for WCF service

*Class library (.NET Core): if you're targetting .NET Core Framework

*Class library (universal windows): if you're targetting for Windows Phone App

*Class library (.NET Standard): The .NET Standard is a formal specification of .NET APIs that are intended to be available on all .NET runtimes. Read
Here

*Class library (portable): The .NET Framework Portable Class Library project type in Visual Studio helps you build cross-platform apps and libraries for Microsoft platforms quickly and easily. Read Here


text:
Q: When are async and await needed in c#? Exactly as the title says.  I wonder if i am writing async and await when it is not needed.
I have seen methods like this with the async tag
public async Task CreateAsync(User user)
{
    if (_context.Entry<User>(user).State == EntityState.Detached)
    {
        _context.Set<User>().Add(user);
    }

    _context.Entry<User>(user).State = EntityState.Added;

    await _context.SaveChangesAsync();
}

and like this without it
public Task CreateAsync(User user)
{
    if (_context.Entry<User>(user).State == EntityState.Detached)
    {
        _context.Set<User>().Add(user);
    }

    _context.Entry<User>(user).State = EntityState.Added;

    return _context.SaveChangesAsync();
}

Both compile fine.  I am always adding the async and await keywords and wonder maybe if i am doing it wrong and writing them when they are not needed?
EDIT:
If you are actually returning a value, should this be written using the async/await keywords, or without. Here is a version with the keywords
public async Task<User> CreateAsync(User user)
{
    if (_context.Entry<User>(user).State == EntityState.Detached)
    {
        _context.Set<User>().Add(user);
    }

    _context.Entry<User>(user).State = EntityState.Added;

    await _context.SaveChangesAsync();

    return user;
}

here is another example
public Task<User> FindByIdAsync(long userId)
{
    return _context.Users.FindAsync(userId);
}

public async Task<User> FindByIdAsync(long userId)
{
    return await _context.Users.FindAsync(userId);
}

EDIT 2
Excellent answers so far, but 1 last example.  Since i have my async calls, how would i cope with calling multiple async functions from 1 method.  here is an example of what i have, but i dont know if it is right.  I do not want the method to exit until all AddAsync methods are completed. Is this correct
private async Task AddPermissions(DataContext context)
{
    var permissionService = new PermissionService(context);

    await permissionService.AddAsync(new Permission("CanView", "View company"));
    await permissionService.AddAsync(new Permission("CanAdd", "Add and view company"));
    await permissionService.AddAsync(new Permission("CanEdit", "Edit and view company"));
    await permissionService.AddAsync(new Permission("CanDelete", "Delete and view company record"));

    await permissionService.AddAsync(new Permission("CanAdd", "Add new pages"));
    await permissionService.AddAsync(new Permission("CanEdite", "Edit existing pages"));
    await permissionService.AddAsync(new Permission("CanDelete", "Delete a page"));

    await permissionService.AddAsync(new Permission("CanAdd", "Add new page content"));
    await permissionService.AddAsync(new Permission("CanEdit", "Edit existing page content"));
    await permissionService.AddAsync(new Permission("CanDelete", "Delete page content"));
}

A: IMHO you would only need to use the await if you want the SaveChangesAsync operation to have finished when the method returns or you need to do something with the result of the async operation. In this case you are not doing anything with it so it is better to not have an async method and avoid the generation of the state machine withing the method, resulting in more efficient code.
Regarding your second edit, you are correct. Although the method will return as soon as the first await is encountered all other awaited statements will be executed one after the other on the thread pool and then the result of the task will be updated. So if you await AddPermissions that statement will only complete once all internal permissionService.AddAsync calls are complete, unless an exception is thrown.
It is also possible to execute permissionService.AddAsync calls in parallel if necessary, by storing the returned tasks in a list and then awaiting Task.WhenAll
private async Task AddPermissions(DataContext context)
{
    var permissionService = new PermissionService(context);

    List<Task> permissionRequests = new List<Task>();

    permissionRequests.Add(permissionService.AddAsync(new Permission("CanView", "View company")));
    permissionRequests.Add(permissionService.AddAsync(new Permission("CanAdd", "Add and view company")));
    permissionRequests.Add(permissionService.AddAsync(new Permission("CanEdit", "Edit and view company")));
    permissionRequests.Add(permissionService.AddAsync(new Permission("CanDelete", "Delete and view company record")));

    permissionRequests.Add(permissionService.AddAsync(new Permission("CanAdd", "Add new pages")));
    permissionRequests.Add(permissionService.AddAsync(new Permission("CanEdite", "Edit existing pages")));
    permissionRequests.Add(permissionService.AddAsync(new Permission("CanDelete", "Delete a page")));

    permissionRequests.Add(permissionService.AddAsync(new Permission("CanAdd", "Add new page content")));
    permissionRequests.Add(permissionService.AddAsync(new Permission("CanEdit", "Edit existing page content")));
    permissionRequests.Add(permissionService.AddAsync(new Permission("CanDelete", "Delete page content")));

    await Task.WhenAll(permissionRequests);
}

So each call to permissionService.AddAsync kicks off the request and adds the corresponding task to the list. Once you have kicked off all the requests, you can await all their completion with await Task.WhenAll, this will wait until they are all complete or have returned an error. Any exceptions thrown will be stored in the task returned from Task.WhenAll. Awaiting that task will rethrow the first exception, but you can access all of them using the Task.Excpetion property which contains an
AggregatedException which in turn contains all the thrown exceptions.

A: The topic can be deep, but here is a high level overview.
There is a key difference between the two versions of code you have posted above.. But first the important similarity..
They both tell _context to save changes asynchronously.. Because that's how SaveChangesAsync is implemented.

Now, the difference..
In first version, when you use async and await keyword, any code which may be after the await call (in this case, the await call is the last call in the function), compiler turns it into a continuation, and it is supposed to execute after the await call finishes (asynchronously).
This includes any exception handling which might wrap the async call.
In contrast, in the second version, when we take the return value of the async call as a Task, then while the async operation has been kicked off, and yet to finish, the execution will continue on in that method (It is not turned into a continuation by the compiler). No code is set to execute after the async operation finishes (unless you explicitly use .ContinueWith on the Task object).

Why would you use one over the other?
Again, at high level async and await should would fine for normal scenarios, where you want to advantage of compiler doing some magic for you, in order to make it easier to deal with async calls.. However, it is also less flexible for some scenarios. Example - What if you want to kick off 10 ping operations asynchronously, and then write a continuation when all 10 finish. The same is not possible using async and await keywords for each async ping. (First call to await makes rest of the code a continuation to first async call).

Search more on internet for more details on async await.. It can be pretty deep, but worth understanding the details.

A: The second version is slightly more efficient, but it doesn't allow you to go back and add more code later without rewriting it to use async/await.
That's pretty much it. I wouldn't complain if I saw either pattern in my code base.

A: A simpler way would be to call Task.Factory.StartNew
Task.Factory.StartNew(() => new Permission("CanView", "View company"));
Task.Factory.StartNew(() => new Permission("CanAdd", "Add and view company"));
...


text:
Q: Why are foreign key names created with an underscore in EF I have read and understood the convention. I have followed the convention and in most cases the sql column name for foreign key is 'ForeignKeyEntityId' in the database. Unfortunately this is not always consistent and I get ForeignKeyEntity_Id as the sql column name.
public class Step : BaseModel
{
    private ObservableCollection<StepRecord> _stepRecords;

    public Step()
    {
        _stepRecords = new ObservableCollection<StepRecord>();
    }

    public int Id { get; set; }

    public DateTime? StartTime { get; set; }
    public DateTime? EndTime { get; set; }

    public int? PassStatusTypeId;
    public  virtual PassStatusType PassStatusType

    public int? SaveStatusTypeId;
    public  virtual SaveStatusType SaveStatusType

    public int? StepTypeId;
    public virtual StepType StepType { get; set; }

    public virtual ObservableCollection<StepRecord> StepRecords { get; set; }
}

All of the references in this class are named with ForeignKeyEntity_Id pattern. This is not what I was expecting.

A: If you are wanting to give a specific name to your foreign keys you can use the ForeignKey attribute like this:
[ForeignKey("MyChildEntity")]
public int? ChildEntityId {get;set;}
public ChildEntity MyChildEntity {get;set;}

In this case, your database will use the ChildEntityId name instead of the default naming convention.
In your case it would be something like:
[ForeignKey("PassStatusType")]
public int? PassStatusTypeId {get;set;}
public  virtual PassStatusType PassStatusType {get;set;}

A: Probably Entity Framework does not map public fields at all, only public properties. As a result the fields PassStatusTypeId, SaveStatusTypeId and StepTypeId are not recognized as foreign keys and EF creates its own foreign key columns that have an underscore in their names by convention. You should use properties instead:
public int? PassStatusTypeId { get; set; }
public virtual PassStatusType PassStatusType { get; set; }

public int? SaveStatusTypeId { get; set; }
public  virtual SaveStatusType SaveStatusType { get; set; }

public int? StepTypeId { get; set; }
public virtual StepType StepType { get; set; }


text:
Q: Rails - how to instantiate a model with a secondary association? Is there an alternative to the << operator for instantiated records? Context:
With Rails & ActiveRecord, my understanding is that if you want an instantiated, not yet saved, child & its attributes to be accessed via a parent, you need to instantiate the child record through the parent. For example:
# when instantiated through parent
order = ParentA.last.orders.new(notes:"asdf")
order.notes
> "asdf"
order.parent_a.present?
> true
order.parent_a.orders.map(&:notes)
> ["asdf"]

# when NOT instantiated through parent
order = Order.new(parent_a_id:ParentA.last.id, notes: "asdf")
order.notes
> "asdf"
order.parent_a.present?
> true
order.parent_a.orders.map(&:notes)
> []

In the above example, I want the first scenario to occur, but where I have to instantiate order across 2 parents, ParentA and ParentB. I.e., something like...
order = ParentA.last.orders.new(notes:"asdf")
ParentB.last.orders << order

order.parent_a.orders.map(&:notes)
> ["asdf"]
order.parent_b.orders.map(&:notes)
> ["asdf"]

Now actually the above code DOES work IF order is valid, since to use the << operator, order basically has to be a fully valid child object.
However, in my case, I want to do instantiation now and order later. In other words, I'm almost wondering if there's an alternative to << that can associate an instantiated child on a parent?
Also note the << operator will also save an additional record if the instantiated order object is valid, so depending on circumstance, that may be bad

A: The point of the shovel operator is really just to implicitly associate two items. You can always assign the assocation or foreign key values directly:
order = ParentA.last.orders.new(notes:"asdf", parent_b: ParentB.last)
order.save
ParentB.last.orders.last == order # should be true


text:
Q: Is there a way to convert umlauts to their ascii equivalent?
Possible Duplicate:
What is the best way to remove accents in a python unicode string?

In a certain system, I need to generate usernames that are only allowed plain-ascii characters (a-z, 0-9, dashes). Many users have names however that don't simply match those restrictions, for example the German names "Müller" or "Röthlin".
Now those umlauts have an alternative way of typing them (I'm sure there's a name for it, but I don't know that - might help Googling)
A naive approach would be to employ a translation table:
name = name.replace('Ä', 'Ae')
name = name.replace('ä', 'ae')
name = name.replace('ö', 'oe')

and so forth.
This approach however fails as soon as you have users from cultures other than, say, German, where other characters might appear. So I'm looking for a generic way to "convert" as many non-ascii characters as possible before falling back to simply strip them out.


text:
Q: Reading *.cdf files in ArcMap? I received some geospatial data (on rainfall) in a "cdf" format.
I have worked with "nc" files and uses the 'Make NetCDF Raster Layer' tool in ArcMap to read NetCDF files.
However, I wasn't able to use it to read the file with .cdf extension.
Is there an alternative way to read such files?
I have access to ArcMap, QGIS and Python so if there's a solution using any of these tools please let me know.

A: you could try changing the file extension to.nc. The format of the files basically the same, as the software doesn't use file extensions, and this has been recommended to users of other software here and here.

A: ESRI developed a Multidimension Supplemental toolbox which you could download here. There are several tools dealing with cdf format.
The tools are:

*

*Describe Multidimensional Dataset

*Make NetCDF Regular Points Layer

*Make NetCDF Station Points Layer

*Make NetCDF Trajectory Points Layer

*OPeNDAP to NetCDF

*Get Variable Statistics

*Get Variable Statistics Over Dimension

*Multidimensional Zonal Statistics

*Multidimensional Zonal Statistics As Table


text:
Q: Выводит слова не в правильном порядке public void defineLanguages(String words) {
    String[] listWords = words.split(" ");

    mapOfLanguages.entrySet().forEach(list -> {
        list.getValue().entrySet().forEach(line -> {
            for (String myWord : listWords) {
                if (line.getKey().equalsIgnoreCase(myWord)) {
                    System.out.print(line.getValue() + " ");
                }
            }

        });
    });
}

A: Вы проходите по картам в порядке следования записей в них, а нужно следовать по порядку слов в предложении. Можно сделать, например, так:
mapOfLanguages.forEach(
    (key, map) ->
        System.out.println(
            Stream.of(words.split(" "))
                .map(word -> map.getOrDefault(word, word))
                .collect(Collectors.joining(" "))
        )
);


text:
Q: GLUT OpenGL glRotatef I have been attempting to create a very simple asteroid game using OpenGL, GLUT, and C++.
I cannot figure out for the life of me why this is happening, but on key press "a" or "d" I want the triangle to rotate along its Z axis.  The problem is that when those keys are pressed, the glRotatef() rotates about the 0,0 position or the bottom left of the screen.  I have tried many different approaches, tutorials and the code I'm going to link is the best running example.
I'm sure I'm missing something, but I cannot get the triangle to rotate about itself and not the origin of the screen.
#include <iostream>
#include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

//g++ -o game.exe -Wall main.cpp glut32.lib -lopengl32 -lglu32 -static-libgcc -static-libstdc++

float posX = 0, posY = 0, posZ = 0;

int width = 100, height = 100;
int triangle_height = 5, triangle_width = 4;
float move_unit = 1;

void display() {

    std::cout << "display" << std::endl;

    //glLoadIdentity();

    glClear(GL_COLOR_BUFFER_BIT);

    glPushMatrix();
    glTranslatef(posX, posY, posZ);
    glColor3f(1,1,1); //sets the current color to white
        glBegin(GL_TRIANGLES); //tells openGL we are going to draw some triangles

            //glTranslatef(0, 0, 0);
            glVertex2i( width/2 , height/2 ); //specifies the first vertext of our triangle
            glVertex2i( width/2 + triangle_width , height/2 ); //specifies the second vertext of our triangle
            glVertex2i( width/2 , height/2 + triangle_height); //specifies the third vertext of our triangle

        glEnd(); //tells openGL that we are done drawing

    glPopMatrix();
    glutSwapBuffers();

    glFlush();

}

void keyboard(unsigned char key, int x, int y) {

    switch(key) {

        case 'w':
            std::cout << "moving up" << std::endl;
            posY += move_unit;
        break;

        case 's':
            std::cout << "moving down" << std::endl;
            posY -= move_unit;
        break;

        case 'a':
            std::cout << "rotate left" << std::endl;
            glRotatef(5.0f, 0.0f, 0.0f, 1.0f);
        break;

        case 'd':
            std::cout << "rotate right" << std::endl;
            glRotatef(5.0f, 0.0f, 0.0f, -1.0f);
        break;

    }

    glutPostRedisplay();

}

void init() {

    glClearColor(0.0, 0.0, 0.0, 1.0);
    glMatrixMode(GL_PROJECTION); //changes the current matrix to the projection matrix
    glLoadIdentity();
    gluOrtho2D(0, width, 0, height);
    glMatrixMode(GL_MODELVIEW);

}

int main(int argc, char **argv) {

    glutInit(&argc, argv); //inits the GLUT framework

    glutInitWindowSize(800, 600);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutCreateWindow("Eric's Game");

    init();

    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);

    glutMainLoop(); // Infinite event loop

    return 0;

}

A: OpenGL applies matrices in the reverse order. In other words, if you want to rotate and then translate, you need to call glRotatef after glTranslatef. The best way to do this would be to store the current rotation explicitly, rather than just making a series of calls to glRotatef:
float rotation = 0.0;

void display() {
    // ...
    glPushMatrix();
    glTranslatef(posX, posY, posZ);
    glRotatef(rotation, 0.0f, 0.0f, 1.0f);
    // Rewrite triangle vertex coordinates to be centered at (0, 0)
    glPopMatrix();
    // ...
}

void keyboard(unsigned char key, int x, int y) {
    switch(key) {
        // ...
        case 'a':
            std::cout << "rotate left" << std::endl;
            rotation += 5.0f;
            break;

        case 'd':
            std::cout << "rotate right" << std::endl;
            rotation -= 5.0f;
            break;
    }
    // ...
}

As a general rule, you should only ever call OpenGL functions inside your draw routines.

A: Since the rotation is applied on the origin, you should concatenate three transformations:
 1. First you translate your triangle on the origin
 2. Then you apply the rotation
 3. After that, you reverse the first translation, in order to put it back in its original position.


text:
Q: Let $p$ be a prime number. Prove that there exists $x∈Z$ for which $p|x^2−x+ 3$ if and only if there exists $y∈Z$ for which $p|y^2−y+ 25$.
Let $p$ be a prime number. Prove that there exists $x∈Z$ for which $p|x^2−x+ 3$ if and only if there exists $y∈Z$ for which $p|y^2−y+ 25$.

I've copied the question verbatim from an elementary number theory assignment.  I'm not making much ground on it, but here's what I've determined so far:
Each equation is based on the following sequence:
x^2 - x: 0, 2, 6, 12, 20, 30, 42, 56, 72, ...

I'm not sure what to call this type of sequence, but I'm thinking of it as a sequence with an acceleration of $2$, as in, each number on the sequence is increased by a number which is increased by $2$ each iteration.
The only difference between the two equations is the starting point of the sequence: one starts at $3$ while the other starts at $25$.  This is how I have been thinking about the problem but unfortunately I think I'm working in the wrong direction.
If anyone could help me move in the right direction of this problem, I would appreciate it

A: Both equations have no solutions mod $2$.
Both equations have solutions mod $3$.
So, let's assume $p>3$.
The discriminant of $x^2-x+3$ is $-11$. So, $x^2-x+3=0$ has a solution mod $p$ iff $-11$ is a square mod $p$.
The discriminant of $y^2-y+25$ is $-99$. So, $y^2-y+25=0$ has a solution mod $p$ iff $-99$ is a square mod $p$.
Since $-99 = 3^2 \cdot (-11)$, we have that $-11$ is a square mod $p$ iff $-99$ is a square mod $p$.


text:
Q: How to assign SplFileObject::fpassthru output to variable I'm currently writing some data to an SplFileObject like this:
$fileObj = new SplFileObject('php://text/plain,', "w+");

foreach($data as $row) {

    $fileObj->fputcsv($row);
}

Now, I want to dump the whole output (string) to a variable.
I know that SplFileObject::fgets gets the output line by line (which requires a loop) but I want to get it in one go, ideally something like this:
$fileObj->rewind();
$output = $fileObj->fpassthru();

However, this does not work as it simply prints to standard output.
There's a solution for what I'm trying to achieve using stream_get_contents():
pass fpassthru contents to variable
However, that method requires you to have direct access to the file handle.
SplFileObject hides the file handle in a private property and therefore not accessible.
Is there anything else I can try?

A: After writing, do a rewind() then you can read everything. The example is for understanding:
$fileObj = new SplFileObject('php://memory', "w+");

$row = [1,2,'test'];  //Test Data

$fileObj->fputcsv($row);
$fileObj->rewind();

//now Read
$rowCopy = $fileObj->fgetcsv();

var_dump($row == $rowCopy);//bool(true)

$fileObj->rewind();
$strLine = $fileObj->fgets();  //read as string
$expected = "1,2,test\n";

var_dump($strLine === $expected);  //bool(true)

//several lines
$fileObj->rewind();
$fileObj->fputcsv(['test2',3,4]);
$fileObj->fputcsv(['test3',5,6]);

$fileObj->rewind();
for($content = ""; $row = $fileObj->fgets(); $content .= $row);

var_dump($content === "test2,3,4\ntest3,5,6\n");  //bool(true)

If you absolutely have to fetch your content with only one command then you can do this too
// :
$length = $fileObj->ftell();
$fileObj->rewind();
$content = $fileObj->fread($length);

getSize() doesn't work here.

A: In the absence of an inbuilt function I've decided to do php output buffering as @CBroe had suggested.
...

$fileObj->rewind();

ob_start();

$fileObj->fpassthru();

$buffer = ob_get_clean();

See @jsplit's answer for a better method using SplFileObjects inbuilt functions


text:
Q: Animation in beamer? I was wondering if it is possible to make an animation in beamer. I normally work on graph theory. By a graph I mean a set of vertices and some edges joining them.
I wish to make an animation showing an isomorphism from one graph to the other. I could draw graphs using tikz package. But I don't know how to make the motion. So what I really want is to make an animation showing one point smoothly move to another point.
For example, I want something as below happen:

A: I don't use beamer but one can start with that :

\documentclass[margin=5pt]{standalone}
\usepackage{tikz,animate}
\usepackage[active,tightpage]{preview}
\usetikzlibrary{calc}

\xdef\C{8}
\xdef\H{4.5}

\begin{document}

\foreach \nxb in {0,.05,...,1,1,.95,...,0,0} {%
\begin{preview}
%\begin{animateinline}[controls]{10}
%   \multiframe{11}{nxb=0+.1}{%

    \begin{tikzpicture}

    \draw (-1,-.5) rectangle (2*\H,2*\H-.5) ;

    \coordinate (C6) at (0,0) ;
    \coordinate (C4) at (\C,0) ;
    \coordinate (C1) at (0,\C) ;
    \coordinate (C3) at (\C,\C) ;
    \coordinate (C2) at ($(C1)!.5!(C3)$) ;
    \coordinate (C5) at ($(C6)!.5!(C4)$) ;
    \coordinate (C7) at ($(C6)!.5!(C3)$) ;

    \coordinate (H5) at ($(C1)!.5!(C4)$) ;
    \begin{scope}[shift=(H5)]
    \coordinate (H6) at (0:\H) ;
    \coordinate (H7) at (60:\H) ;
    \coordinate (H4) at (120:\H) ;
    \coordinate (H3) at (180:\H) ;
    \coordinate (H2) at (240:\H) ;
    \coordinate (H1) at (300:\H) ;
    \end{scope}

    \foreach \i in {1,...,7} {%
        \fill ($(H\i)!\nxb!(C\i)$) circle (2pt) coordinate (M\i) ; }
    \draw (M1)--(M2)--(M3)--(M4)--(M5)--(M6)--(M7)--(M4)
        (M6)--(M1)--(M5) ;

    \end{tikzpicture}
    %}
%\end{animateinline}
\end{preview}}
\end{document}


text:
Q: PriorityQueue not sorting properly Currently this is my enum (VisitorInfo) class:
public enum Ticket{
    NO_TICKET(0), REG_TICKET(1), FAST_TICKET(2);
    private int status;

    Ticket(int status)
    {
        this.status = status;
    }

    int getStatus() {
        return status;
    }
}

And this is currently my Queue declaration:
    PriorityQueue<VisitorInfo> pq = new PriorityQueue<VisitorInfo>(20, new Comparator<VisitorInfo>() {
        public int compare(VisitorInfo n1, VisitorInfo n2) {
            if (n1.ticket.getStatus() == n2.ticket.getStatus())
                return 0;
            if (n1.ticket.getStatus() > n2.ticket.getStatus())
                return -1;
            return 1;
        }
    });

And my main method:
public static void main(String[] args) throws FullQueueException {
RideQueue bleh = new RideQueue("hi", 20);

VisitorInfo bleh1 = new VisitorInfo("NO1", VisitorInfo.Ticket.NO_TICKET);
VisitorInfo bleh2 = new VisitorInfo("NO2", VisitorInfo.Ticket.NO_TICKET);
VisitorInfo bleh3 = new VisitorInfo("NO3", VisitorInfo.Ticket.NO_TICKET);
VisitorInfo bleh4 = new VisitorInfo("REG1", VisitorInfo.Ticket.REG_TICKET);
VisitorInfo bleh5 = new VisitorInfo("REG2", VisitorInfo.Ticket.REG_TICKET);
VisitorInfo bleh6 = new VisitorInfo("REG3", VisitorInfo.Ticket.REG_TICKET);
VisitorInfo bleh7 = new VisitorInfo("FAST1", VisitorInfo.Ticket.FAST_TICKET);
VisitorInfo bleh8 = new VisitorInfo("FAST2", VisitorInfo.Ticket.FAST_TICKET);

bleh.pq.add(bleh1);
bleh.pq.add(bleh2);
bleh.pq.add(bleh3);
bleh.pq.add(bleh4);
bleh.pq.add(bleh5);
bleh.pq.add(bleh6);
bleh.pq.add(bleh7);
bleh.pq.add(bleh8);

for (int i = 1; i<9; i++)
{
    System.out.println(bleh.pq.poll().getName());
}

}

My output:
FAST1
FAST2
REG3
REG2
REG1
NO2
NO1
NO3

Why is it not sorting properly?
I'm sorry I forgot to add, Fast should be printing out first, then reg, then no.

A: Do you want your sort by name or your sort by status? Your Comparator is based upon the status, but you're expecting the order to be by name. N01, N02, N03 are all NO_TICKET with a status of 0. So which one would go first?


text:
Q: Confused about open and closed sets I am slightly confused about part of a problem about open and closed sets, from Stephen Abbott's Understanding Analysis. Consider the set $A = \{ 1 + \frac{1}{4} + \frac{1}{9} + \cdots + \frac{1}{n^2} : n \in \mathbb{N} \}.$ Obviously the set is not closed, because $\sum_{n=1}^\infty \frac{1}{n^2}$ converges. What I'm confused about is the fact that $A^c = (-\infty) \cup (1 , 1+\frac 14) \cup (1+\frac 14, 1+\frac 14 + \frac 19)\cup ......\cup (\sum_{k=1}^n \frac 1{k^2}, \sum_{k=1}^{n+1} \frac 1{k^2})$. This seems to be a union of open sets, which should be open. But clearly, if $A^{\mathsf{c}}$ was open, then $A$ would be closed, which it is not. What am I missing here?

A: But $A^{\mathsf{c}} \ne (-\infty, 1) \cup (1, 1+\frac{1}{4}) \cup (1 + \frac{1}{4}, 1 + \frac{1}{9}) \cup \cdots \cup (1+\frac{1}{n^2}, 1 + \frac{1}{(n+1)^2}) \, \forall n \in \mathbb{N}$[*]
You are omitting that $\{x| x > \sum_{k=1}^n \frac 1{n^2} \forall n \in \mathbb N\}\subset A^c$.
And $\{x| x > \sum_{k=1}^n \frac 1{n^2} \forall n \in \mathbb N\}\subset A^c = [\lim_{n\to \infty} \sum_{k=1}^n \frac 1{n^2}, \infty)$ is a closed set.


text:
Q: What is the Cthaeh in Wise Man's Fear? What is the Cthaeh in Wise Man's Fear?

 Bast has an almost absurd fear of it.  From how they described it, it sounds like by simply talking to the tree, it would make you notorious in history, being single-handedly responsible for bringing about plagues and starting wars.

Also,

 You can ask it anything and it must tell the truth, and by the things it tells you, it will make you be the worst kind of person you can be?  I'm not sure I completely understand the idea.

And what is it that Kvothe does that is so horrible?  Didn't they sort of imply that he was the cause for the war?
Is this Cthaeh supposed to be the prophetical "Broken Tree" that he mentioned in his first book?

A: The thing is, I get the feeling that while the Cthaeh is horribly powerful in its manipulations, it is not as all knowing as Bast made it out to be.
Think about it. If it were truly omniscient and malevolent, why would it have performed any action that would have led the Fae to blockade its tree? In its very essence, that prevents it from manipulating people to accomplish the greatest malice. If it were all knowing and wanted to accomplish the greatest harm, it would act more subtly so as to never alert those around it to its true nature, thus freeing it to speak to more people and accomplish more harm. And if you know EVERYTHING that can possibly happen, it wouldn't be hard to cause extreme amounts of harm without letting people know you caused it.
So, the way I see it, there are four major possibilities:

*

*The Cthaeh can see the future, but is not all knowing--there is a limit to how well he can know what to do and how to manipulate.

*The Cthaeh is all knowing, but the nature of Rothfuss's universe is more fluid and quantum--nothing is set in stone. The Cthaeh can merely influence events to be more likely to result in the greatest harm, but not assure that it happens.

*The Cthaeh is all knowing and can manipulate to assure the most harm--but it nature was known from the very beginning, perhaps before it was born, and so the Fae set out to limit it.

*The Cthaeh is not malevolent, or at least not totally.
There are two other possibilities that spring to mind--the first, the Cthaeh is all knowing and can assure the future it manipulates towards, but cannot control its impulses, and tries to do the most harm as fast as possible, which allowed its nature to be known. This doesn't seem likely as its nature seems to be patient--after all, if instant gratification was its thing, wouldn't it simply enrage Kvothe to do violence to the nearest possible person?
The second--The Cthaeh is all knowing, it can assure the future it selects, and it only let its nature be known...because being trapped is part of its overarching plan that in the end causes more harm. I don't want to think about this one. I can't see any ending to the story that won't break my heart if that's true.

A: The power of the Cthaeh is

 to see all the possible futures. This means that through the butterfly effect, he has the power to change the world dramatically. Since he cannot leave the tree, his only tool to effect change is the conversations he has with people. So for example, the Cthaeh could inflame Kvothe's opinions of Ambrose and it may later cause Kvothe to kill Ambrose, thus causing Ambrose's father to kill Kvothe, thus causing a civil war between the Maer and King of Vintas.

However, I personally believe that the Cthaeh is not as powerful as he is made out to by Bast.

 Sure, it can see all the possible futures. But that does not necessarily mean that it can make that future occur via its words. For example, if a person is dying of poison and Cthaeh talks to him, can the Cthaeh really accomplish anything?

As to what Kvothe does, it seems that he kills a King (in Imre) because of Denna, and that plunges the world in a devastating civil war.

A: More spoilers.

You can tell what Kvothe does from the title of the series, which is The Kingkiller Chronicles. He kills a king, which causes the political chaos that we see in the framing narrative. It's not yet clear which king he kills.

And.

I'm sure we'll be getting more about the Cthaeh in the third book, but don't underestimate the power of being able to reveal any truth, and knowing exactly how things will work out if you do.

A: The insidious thing about the Cthaeh's influence is that you cannot escape it.  If you know it's danger, and think "I have to kill myself instantly to protect the world" --well of course, the Cthaeh knew what your reaction would be, so if you kill yourself, that is what will cause the damage in the end.  And if you realize that, then you must realize that the Cthaeh knew you would.  Thus no matter what you do, it is going to be the worst possible thing--at least so far as it is influenced by the Cthaeh's words.
This creature is one of the greatest and most chilling 'monster' creations in literature.  The more you consider it, the better it is.
One question I have is: What effect does its bite have?  That was the instant worry of Felurian--that he was bitten.  What an excellent touch by Rothfuss!  It's unseen so the imagination of the reader supplies the most horrifying interpretation--Lovecraft-style.  And the effect of its bite is unspoken but suggested to be really, really bad and scary, so the reader's imagination is once again fueled to provide the most frightening and disturbing possibilities.    Love it.

A: The Cthaeh is a Fae creature described as an omniscient being having the ability to see all possible timelines.  It is also said to be perfectly malicious/malevolent, in that when given an opportunity to do so it will always choose the timeline that causes the greatest amount of misery/suffering/despair for the greatest number of people.
Thus the Cthaeh is a perfect manipulator.  It does not do anything directly, but if there is something that it can say to a person to cause them to bring ruin and destruction to themselves and others then that is what it will do without fail.  So it won't bring the plague itself, but it may convince a plague-infested person that they need to return to their home city and confront their spouse over the affair that they have been secretly having for the past year, resulting in a bloody confrontation that ultimately brings the plague into the city.
However this doesn't mean that the Cthaeh can turn anyone into an unstoppable instrument of destruction.  For instance, if we imagine a person dying of poison who stumbles upon the Cthaeh with only minutes or hours left to live, there is very little malevolent purpose that it might bend them towards.  However the Cthaeh works in subtle ways, using the people it manipulates to manipulate other, more influential people perhaps years or decades down the line.  This can be exceedingly dangerous, particularly when it is given the opportunity to manipulate a young, healthy, powerful, and short-tempered subject like Kvothe.

The thing to take away from this is that everything that Kvothe does after his conversation with the Cthaeh is essentially tainted by its influence.  We don't know exactly what it is that he does yet, but it's probable that he kills a king (possibly Denna's yet unnamed patron) thereby starting a war.  It's also possible that he may be directly or indirectly responsible for the demons (the scrael, the demon that possessed the soldier and killed Shep) that have been appearing in the mortal plane.  Plus it appears that whatever happens he ultimately ends up losing Denna, his ability to make music, his ability to perform sympathy, and perhaps also his Ademic combat ability and his skill at naming.  And the Chandrian remain at large.  Given this, it seems that the Cthaeh is quite dangerous indeed.  It set the world in turmoil, and robbed Kvothe of everything he held dear.

A: The Cthaeh is the loss of free will. Because of its ability to see all available futures and choose among them, anything you do afterwards will be because the Cthaeh either planned it or allowed it.
It does seem to me that the Cthaeh's power is incompatible with quantum uncertainty. There will be events over which it has no control e.g. quantum or geological; and thus its ability to control would diminish over time.

A: On the nature of its power.
Let's go off what we observe and draw a set of conclusions, rather then a single overarching theme.
I perpose that The cthaeh gains some power after each level of interaction with what ever it comes in contact with. Listening to it, talking to it, asking it a question, asking it a favor, etc..
This happens explicitly and Felurian asks Kvothe about these "did you speak, did you ask of it, did it bite you (touch you)"
I suspect that the Cthaeh isn't all knowing, instead at each level of interaction it gains power over the subject. After Kvothe asks its a question it becomes very talkative and knows a lot about Kvothe's life. I believe it gained the power to know everything Kvothe does, but like a machine it sees everything all at once, it can piece things together Kvothe couldn't.
It flowers in couple well informed guesses (e.g that denna was hurt using a cane recently) to mask its true nature or maybe just to steer things in the direction it wants.

A: The problem here, and this explains why the answers range from 'the cthaeh is the total worst' to 'potentially not that bad', is that the entire story makes use of the unreliable narrator writing effect.
In the same way that the books highlight just how a legend of a hero or villain can be over exaggerated with Qvoth's retelling compared to the patrons of the pub's retelling of his various exploits, its possible that the Cthaeh also experiences the same misinformed legend.
We can safely assume that the retelling of Qvoth's story by Qvoth himself is reliable, because although its fantastical it is also accepting of several basic truths behind the mystical elements. In Qvoth's retelling of the encounter with the Cthaeh, the Cthaeh admits to having to make assumptions about what Qvoth has been thinking of Denna: "youve thought of her too, im guessing".
There are several ways of explaining this, maybe Qvoth incorrectly remembered the events, maybe the Cthaeh carefully chose its words, maybe the Cthaeh cannot read events as accurately when they occur in Felurian's domain but taken at face value its possible to assume that the influence the creature has is not as strong as the rumours.

A: I thought it was a solid creation, but not believable. The Cthaeh is a good example of PRockfuss' stylistic "weaknesses" (which don't need to bother you), which is being emphatic and emotional or rhetorical rather than proving. If he tells you that something is really, really bad, he can be insistent enough that the reader just goes with it. But the horribleness of the Cthaeh can't be that great for reasons of probability. Since it is bound to actual conditions, there is obviously a limit to what it can do and how bad it can be.
The thing tells you only the truth. So either it needs to coincidentally meet a person which is haunted by traumatic experiences (and unable to overcome them, so the Cthaeh might not even make a big difference), or knows somebody who currently undergoes a horrible treatment; or the author buys into an idea of truth that is less informative, useful, necessary or neutral than actively harmful, or can freely be given a harmful bent, and is ultimately impossible for any average individual to bear. Which is contrary to the necessity of (relevant) information, even bad one, in life, and therefore extremely strange (albeit convincing in a minor, melodramatic tradition).
The second reason why the Cthaeh is the most horrible thing in existence, which is not limited to the hearer's psyche, is that it tells you things which will come to pass as long as it gauges the hearer's reactions correctly (which it always does) and so makes the hearer part of the events. Now that is a really cool concept, but it doesn't work either. The likelihood that any hearer is or can be made an important actor in events, again relies on the hearer, their background, capabilities and interests, and the set of conditions in the world, and what difference a piece of information can actually make in it. The suggestion is that the Cthaeh of course chooses the worst possible outcome, but that doesn't make it any more likely that the consequences are momentous or so incredibly harmful.
And the two evils pretty much don't work together, as the first one (traumatise until you lose your personality...) has to fail a little in order for the second one to work, and if the first one can fail, it is admitted that the second one can (since the conditions are related), and in fact both failing contains a gigantic likelihood, making the Cthaeh practically an unscary "mean" fairytale spirit.
It might actually work within his world (which is why one can go with it), even always, but only in a fictional world. Even if it is all-knowing and evil, it is is still completely dependent on the conditions and factors, i.e. the persons and what they could/would actually do (and what difference it can play for the worst outcome).

A: The Cthaeth's control is as described above by Kushana. Because of quantum uncertainty it can only vastly increase the probabilities involved. For instance it cant change Kvothe causing him to kill some king but it can change him to the point where there is a 90% chance he will kill a king. Also the more that incredibly small parts of the  90% do not occur (which would occur over time) the less influence the Cthaeth has. Therefore it eventually loses the influence from 1 interference.
In other words there is a chance for a happy ending.


text:
Q: How to have an in-place string that updates on stdout I want to output to stdout and have the output "overwrite" the previous output.
For example; if I output On 1/10, I want the next output On 2/10 to overwrite On 1/10. How can I do this?

A: Use this solution if you want to rewrite multiple lines to the output.  For instance, I made a decent Conway's "Game of Life" output using this method.
DISCLAIMER: this only works on ANSI Terminals, and besides using fmt this isn't a Go-specific answer either.
fmt.Printf("\033[0;0H")
// put your other fmt.Printf(...) here

Brief Explanation: this is an escape sequence which tells the ANSI terminal to move the cursor to a particular spot on the screen.  The \033[ is the so-called escape sequence, and the 0;0H is the type of code telling the terminal move the cursor to row 0, column 0 of the terminal.
Source: https://en.wikipedia.org/wiki/ANSI_escape_code#Sequence_elements

A: Found something worth sharing for problems like this.
Sharing for people who might be facing same problem in future
Check if output is being written to terminal. If so, use \r (carriage return) defined by terminal to move cursor to the beginning of line
package main

import (
    "flag"
    "fmt"
    "os"
    "time"
)

var spinChars = `|/-\`

type Spinner struct {
    message string
    i       int
}

func NewSpinner(message string) *Spinner {
    return &Spinner{message: message}
}

func (s *Spinner) Tick() {
    fmt.Printf("%s %c \r", s.message, spinChars[s.i])
    s.i = (s.i + 1) % len(spinChars)
}

func isTTY() bool {
    fi, err := os.Stdout.Stat()
    if err != nil {
        return false
    }
    return fi.Mode()&os.ModeCharDevice != 0
}

func main() {
    flag.Parse()
    s := NewSpinner("working...")
    isTTY := isTTY()
    for i := 0; i < 100; i++ {
        if isTTY {
            s.Tick()
        }
        time.Sleep(100 * time.Millisecond)
    }

}

Example code taken from

A: The solution for one string which will replace whole string
fmt.Printf("\033[2K\r%d", i)
For example, it correctly prints from 10 to 0:
for i:= 10; i>=0; i-- {
    fmt.Printf("\033[2K\r%d", i)
    time.Sleep(1 * time.Second)
}
fmt.Println()

which previous answers don't solve.

A: stdout is a stream (io.Writer). You cannot modify what was already written to it. What can be changed is how that stream's represented in case it is printed to a terminal. Note that there's no good reason to assume this scenario. For example, a user could redirect stdout to a pipe or to a file at will.
So the proper approach is to first check:

*

*if the stdout is going to a terminal

*what is that terminal's procedure to overwrite a line/screen

Both of the above are out of this question's scope, but let's assume that a terminal is our device. Then usually, printing:
fmt.Printf("\rOn %d/10", i)

will overwrite the previous line in the terminal. \r stands for carriage return, implemented by many terminals as moving the cursor to the beginning of the current line, hence providing the "overwrite line" facility.
As an example of "other" terminal with a differently supported 'overwriting', here is an example at the playground.


text:
Q: Is there any way to see a number in it's 64 bit float IEEE754 representation Javascript stores all numbers as double-precision 64-bit format IEEE 754 values according to the spec:

The Number type has exactly 18437736874454810627 (that is, 264−253+3)
  values, representing the double-precision 64-bit format IEEE 754
  values as specified in the IEEE Standard for Binary Floating-Point
  Arithmetic

Is there any way to see the number in this form in Javascript?

A: You can use typed arrays to examine the raw bytes of a number. Create a Float64Array with one element, and then create a Uint8Array with the same buffer. You can then set the first element of the float array to your number, and examine the bytes via the Uint8Array. You'll have to do some shifting and combining for the various pieces of the number of course, but it's not hard.
There are no built-in facilities to do things like extract the exponent.

A: Based on @Pointy's suggestion I've implemented the following function to get a number in it's 64 bit float IEEE754 representation:
function to64bitFloat(number) {
    var f = new Float64Array(1);
    f[0] = number;
    var view = new Uint8Array(f.buffer);
    var i, result = "";
    for (i = view.length - 1; i >= 0; i--) {
        var bits = view[i].toString(2);
        if (bits.length < 8) {
            bits = new Array(8 - bits.length).fill('0').join("") + bits;
        }
        result += bits;
    }
    return result;
}

console.log(to64bitFloat(12)); // 0100000000101000000000000000000000000000000000000000000000000000
console.log(to64bitFloat(-12)); // 1100000000101000000000000000000000000000000000000000000000000000

A: You can use Basenumber.js to transform a number into its IEEE754 representation:

let x = Base(326.9);
let y = Base(-326.9);

// specify double precision (64)
let a = x.toIEEE754(64);
let b = y.toIEEE754(64);

console.log(a);
console.log(b);

// You can join them in an unique string this way
console.log(Object.values(a).join(""));
console.log(Object.values(b).join(""));
<script src='https://cdn.jsdelivr.net/gh/AlexSp3/Basenumber.js@main/BaseNumber.min.js'></script>


text:
Q: Selectize.js: Prepopulate items from database selectize multiselect I have looked far and wide for examples on how to do this.
I am trying to prepopulate items from a database into a select element using the Selectize jQuery plugin. The idea is that the user has previously selected item(s) and comes to this page to edit or add more items.
From what I can tell, you populate an array using the "items" option. I have had zero success trying to get this to work.
Here is my code:
$('#nsn').selectize({
    persist: false,
    maxItems: null,
    valueField: 'id',
    labelField: 'name',
    searchField: ['nsn', 'part_name', 'id'],
    sortField: [
        {field: 'nsn', direction: 'asc'},
        {field: 'part_name', direction: 'asc'}
    ],
//"items" below should pre-populate select element
    items: [
        {nsn: '2840-01-461-8833NZ', part_name: 'adfasdfasdf', id:'562'},
        {nsn: '1111-22-333-4444', part_name: 'afafdsdf', id:'902'},
    ],
    options: [
        {nsn: 'NA', part_name: 'F100 Variable Vane', id:'329'},
{nsn: 'N/A', part_name: 'F100 Variable Vane', id:'331'},
{nsn: '6685-01-281-6849AW', part_name: 'Generator Oil Temperature   Indicator', id:'672'},
{nsn: '6680-01-350-8049RK', part_name: 'Fuel Quantity Indicator', id:'391'},
{nsn: '6680-01-350-8048RK', part_name: 'Indicator, Liquid Quantity', id:'367'},
{nsn: '6680-01-224-7271RK', part_name: 'Fuel Quantity Indicator', id:'390'},
{nsn: '6680-00-220-4090RK', part_name: 'Fuel Quantity Indicator', id:'389'}
],
    render: {
        item: function (item, escape) {
            var name = formatName(item);
            return '
' +
            (item.nsn ? '' + escape(item.nsn) + ', ' : '') +
            (item.part_name ? '' +    escape(item.part_name) + '' : '') +
            '
';
        },
        option: function (item, escape) {
            var name = formatName(item);
            var label = name || item.nsn;
            var caption = name ? item.nsn : null;
            return '
' +
            '' + escape(label) + '' +
            (caption ? '' + escape(caption) + '' : '') +
            '
';
        }
    },
    create:false
});

So based on the array in items, two items should appear already selected in the multiselect. Everything else works perfectly. Any help is appreciated.

A: You can use addItem(value, silent) to select the items.

A: Check out this How to add item into selectize js automatically after document ready?
I am using the standalone library. Other accepted answers didn't work for me.
$(document).ready(function(){
   var selectize_element = $("#select-links")[0].selectize;
   selectize_element.addOption({
      text:'First Item',
      value: 'First Item'
   });
   selectize_element.refreshOptions() ;
   selectize_element.addItem('First Item');
});


text:
Q: Logo will not display appropriately on Actual Mobile Device [But does when changing desktop screen size] Website logo is not displaying appropriately on the physical mobile device, I am using an iPhone X. However when changing the screen size of the desktop version; the logo adapts appropriately
I am modifying the theme, so please bear with me. I have attempted to modify the size with max-width tags
Code within the Custom CSS:
@media (max-width: 767px){
#logo .retina-logo {
    height: 35%;
    width: 45%;
    margin-top: -2px;
}
}

@media (max-width: 600px){
#logo .retina-logo {
    height: 90%;
    width: 60%;
    margin-top: -2px;
}
}

@media (max-width: 500px){
#logo .retina-logo {
    height: 100%;
    width: 90%;
    margin-top: 4px;
}
}

Feel free to view www.TattiniBoots on your mobile device to see what I am talking about. You will notice that the logo is very tiny and not the correct width that is displayed when changing the screen size on desktop

A: Apparently your media queries are in the wrong order on your website (inspector says the rules are inline on line 28 / 19 / 11 for 500 / 600 / 767px) - a different order than what you posted in your code above. So just reverse the order of those media queries, since otherwise the 767px rule will overwrite the others when it follows the others.

A: Try adding <meta name="viewport" content="width=device-width, initial-scale=1.0" /> in the <head>


text:
Q: React Navigation - undefined is not an object (evaluating 'this.navigation.navigate') I am following this tutorial to implement a switch navigator for user authentication: https://snack.expo.io/@react-navigation/auth-flow-v3.
However, this.navigation.navigate appears to undefined when I try to navigate to the next screen.
undefined is not an object (evaluating 'this.props.navigation.navigate')

I am using expo for my app, and I've already looked at the solutions posted to a similar question at React Native - navigation issue "undefined is not an object (this.props.navigation.navigate)" to no avail.
import * as React from 'react';
import { createBottomTabNavigator } from 'react-navigation-tabs';

import profile from './app/screens/profile.js'
import home from './app/screens/home.js'
import createCompetition from './app/screens/create.js'
import explore from './app/screens/explore.js'
import Icon from 'react-native-vector-icons/MaterialIcons'
import login from './app/screens/login.js';
import { f } from './config/config.js';
import { ActivityIndicator, AsyncStorage, Button, StatusBar, StyleSheet, View } from 'react-native';
import { createStackNavigator } from 'react-navigation-stack';
import { createAppContainer, createSwitchNavigator } from 'react-navigation';
/**
 * Tab Stack is the Bottom Navigator for the different pages
*/
const TabStack = createBottomTabNavigator(
  {
    Home: {
      screen: home,
      navigationOptions: {
        tabBarIcon: ({ tintColor }) => (
          <Icon name="home" size={25} style={{ color: tintColor }} />
        ),

      },
    },
    Explore: {
      screen: explore,
      navigationOptions: {
        tabBarIcon: ({ tintColor }) => (
          <Icon name="search" size={25} style={{ color: tintColor }} />
        ),

      }
    },
    Profile: {
      screen: profile,
      navigationOptions: {
        tabBarIcon: ({ tintColor }) => (
          <Icon name="person" size={25} style={{ color: tintColor }} />
        ),

      }
    },
    Create: {
      screen: createCompetition,
      navigationOptions: {
        tabBarIcon: ({ tintColor }) => (
          <Icon name="add" size={25} style={{ color: tintColor }} />
        ),

      }
    },
  },
  {
    tabBarOptions: {
      showIcon: true,
      showLabel: false,
      activeTintColor: 'black',

      style: { backgroundColor: 'white', }
    },

  },
)

/**
 * Loading Screen during authorization process
 */
class AuthLoadingScreen extends React.Component {
  constructor() {
    super();
    this._bootstrapAsync();
  }

  // Fetch the token from storage then navigate to our appropriate place
  _bootstrapAsync = async () => {
    f.auth().onAuthStateChanged(function (user) { //checks if user is signed in or out
      this.props.navigation.navigate(user ? 'App' : 'Auth');
    })
  };

  // Render any loading content that you like here
  render() {
    return (
      <View style={styles.container}>
        <ActivityIndicator />
        <StatusBar barStyle="default" />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

const AppStack = createStackNavigator({ Home: TabStack });
const AuthStack = createStackNavigator({ Login: login });
const RootStack = createSwitchNavigator(
  {
    AuthLoading: AuthLoadingScreen,
    App: AppStack,
    Auth: AuthStack,
  },
  {
    initialRouteName: 'AuthLoading',
  }
);

const App = createAppContainer(RootStack);
export default App;

A: You are not giving access to this to your _bootstrapAsync function and your onAuthStateChanged callback. Just pass the callback inside of it using arrow function, as it autobinds the current function to the current app this
_bootstrapAsync = async () => {
   f.auth().onAuthStateChanged((user) => { //checks if user is signed in or out
   this.props.navigation.navigate(user ? 'App' : 'Auth');
   })
};

A: The problem is with function keyword, which doesnt bind this keyword. Better replace it with ES6 arrow functions which implictly binds this to the inner scope :
f.auth().onAuthStateChanged((user) => { //checks if user is signed in or out
   this.props.navigation.navigate(user ? 'App' : 'Auth');
   })

Hope it helps .feel free for doubts


text:
Q: cell array of strings to matlab structure I need to create a matlab structure as such ds=struct('name',{{'my_name_is'},{'matlab_thining_hair'}}) which stores as a 1x2 struct array with fields: name. A call to ds.name generates the output:

ds.name
ans =
    'my_name_is'
ans =
    'matlab_thining_hair'

Please note the single quotes in the output. They are important. That said, I need to create the above mentioned structure using the following variable:
X = [1x46 char] [1x47 char] i.e., 1x2 cell, which I believe is actually a cell array of strings. Among other things, I've tried the following:
Y = cell2struct(X, 'name', 1)'
which results in a 1x2 structure array with fields name, however a call to Y generates the output:

Y.name
ans = my_name_is
ans = matlab_thining_hair

Note that the single quotes in the output are missing, and albeit both Y and ds are 1x2 struct arrays with fields name, the field values are not formatted the same and the structures also vary in their bytes size. How to format the field values as character arrays?

A: In your first case you have created a struct with two fields whose values are cell arrays. The  cell arrays are displayed with quotes.
In your second case your struct fields have char arrays which is what you want. Char arrays display without quotes.
You can verify this by typing in your command prompt {'abc'} and then 'abc'.
In your first case you can create non-cell array field values by passing the strings outside cell parenthesis.
ds=struct('name',{'my_name_is','matlab_thining_hair'})

A: Stick your char strings in another layer of cells before calling cell2struct. Instead of:
X = { 'foo', 'bar' }

Try:
X = { {'foo'}, {'bar'} }

That is, a 1-by-2 cell whose cell contents are themselves cells, not chars. Then cell2struct(X, 'name', 1) should give you a struct array with fields of cell arrays.
If your existing X is a cellstr, I think you can just call num2cell on it to push each cell down into another layer of cell indirection.


text:
Q: How can I correct spacing issues? When using the following code I get unsightly spaces (following the opening parentheses, after the = and between the x' and y'):
[$](\quad \overline{x+y})=\quad \overline{x}\quad \overline{y}[/$]

What am I doing wrong?
If it helps, I am using Anki with its default header and footer settings:
\documentclass[12pt]{article}
\special{papersize=3in,5in}
\usepackage[utf8]{inputenc}
\usepackage{amssymb,amsmath}
\pagestyle{empty}
\setlength{\parindent}{0in}
\begin{document}

\end{document}

Also, please forgive me if I am unclear or have duplicated a question; I am new to TeX and unfamiliar with the terminology.

A: LaTeX provides a number of ways to print skips (blanks, or whitespace):
\def\thinspace{\kern .16667em }
\def\negthinspace{\kern-.16667em }
\def\enspace{\kern.5em }
\def\enskip{\hskip.5em\relax}
\def\quad{\hskip1em\relax}
\def\qquad{\hskip2em\relax}

The above are in addition to using \hspace{<len>} that you can use to print whitespace of length <len>. In your specific example, \quad skips "forward" by exactly 1em, which leaves the blank spaces you witness. Removing them leaves the correct typesetting:

\documentclass{article}
\begin{document}
$(\overline{x+y})=\overline{x}\overline{y}$
\end{document}

With the introduction of some of these spaces, you can also improve the presentation by inserting (say) a \thinspace between the x and y:

\documentclass{article}
\begin{document}
$(\overline{x+y})=\overline{x}\thinspace\overline{y}$
\end{document}

For completeness, here's a table from Herbert Voss' mathmode document that illustrates some of the well-known spacing techniques/commands (Section 11.2 Additional horizontal spacing, Table 7, p 29):


text:
Q: Can you add a preprocessor directive for a C# version? Is there a way to add a preprocessor directive that compares the C# version used by the compiler?
For example :
public T MyMethod<T>()
{
#if CS_7
    return default; // Feature 'default literal' is not available in C# 7.0. Please use 7.1 or greater.
#else
    return null; // Ignore the fact that this won't work, it isn't the point of the question
#endif
}

Would the .NET version be the way to go here? Wouldn't there be situations where the compiler used is different for the same project? (i.e. if different employess use different versions of Visual Studio)

A: Apparently you can't, but the C# version used depends on the framework version (list of version per framework) used in the project, which provides a default C# version, unless configured otherwise manually through something like the  property (see linked documentation).
Thus, most situations where you would want a C# version preprocessor directive can either be resolved by adding a framework preprocessor directive or forcing a specific C# version in the project itself using the  property in the project file.


text:
Q: Installing Ubuntu from USB drive I used both programs from http://pendrivelinux.com.
Whenever I boot from USB and choose Install to Hard Drive, it stucks at:
nouveau [ VBIOS][0000:01:00.0] checking PRAMIN for image

How to fix this?

A: I think the problem is a missing file on your USB.
I would recommend using Unetbootin to burn the image
to your USB and use that to install Ubuntu.
I have had errors like your in the past using pendrivelinux
but Unetbootin has always created good images.


text:
Q: How to show $ \Big\vert \frac{\sin(x)}{x} \Big\vert $ is bounded by $1$? This may be a silly question, but I cannot figure it out. I want to prove that
$ \Big\vert \frac{\sin(x)}{x} \Big\vert \leq 1 $ for $x\in[-1,0)\cup(0,1]$,
but I don't even know where to start.

A: If you draw a picture, it looks like we can use the triangle with points $A =(\cos(x),\sin(x))$, $B = (1,0)$, $C = (\cos(x),0)$. $AC$ has length $\sin(x)$, and $AB$ is the hypotenuse.  So $AC$ is longer than $\sin(x)$.  But then, since the shortest path connecting two points is a straight line, we must have $|AB| \leq x$.  So we get $|\sin(x)| \leq |x|$ when $x$ is in the range $(-\pi/2, \pi/2)$.

A: Hint By the MVT you have
$$\frac{\sin(x)-\sin(0)}{x-0} =\cos(c)$$
for some $c$.

A: Simple geometric proof:
Consider the  unit circle, centred at $O$, with origin $A(1,0)$, and the point $M$ on the unit circle such that $\overset{\displaystyle\frown}{AM}=x$. Then
$$\text{triangle } OAM \subset \text{circle sector }OAM  $$
hence
$$\text{area tr. }OAM=\frac12\lvert\sin x\rvert\le \text{area c. sect.}OAM=\frac12\lvert x\rvert.$$


text:
Q: Many buttons appear on my confirmation dialog I want to make confirmation dialog before delete some data. But there are so many buttons appear like this:

This is my code:
<t:pagelink page="SUM01005e" context="[clientProduct.client.clientId, clientProduct.aggregator.aggregatorId, clientProduct.postpaidProduct.billerCode]" onclick="return deleteConfirmation(this, '${clientProduct.aggregator.name}','${clientProduct.postpaidProduct.billerCode}','${clientProduct.productName}');"></t:pagelink>

This is my jquery:
function deleteConfirmation(ele, agName, productCode, productNameBox){

            $j("#agName").html(agName);
            $j("#productCode").html(productCode);
            $j("#productNameBox").html(productNameBox);

            $j("#deleteConfirmation").dialog({
                buttons:[
                    {
                        text: "OK",
                        "class": "button button-pill button-flat-primary button-tiny ui-state-focus",
                        click: function() {
                             window.location = $j(ele).attr("href");
                        }
                    },
                    {
                        text: "Cancel",
                        style: "margin-left:10px",
                        "class": "button button-pill button-flat-primary button-tiny ui-state-focus",
                        click: function() {
                             $j(this).dialog("close");
                        }
                    }
                ]
            });

            return false;

with this:

${message:areyousuretoremovethisdata}

                Aggregator
                :

                Product Code
                :

                Product Name
                :

How to fix that?

A: I was unable to replicate the issue as you described it. I used the following test code snippet.

$(function($j) {
  function deleteConfirmation(ele, agName, productCode, productNameBox) {
    $j("#agName").html(agName);
    $j("#productCode").html(productCode);
    $j("#productNameBox").html(productNameBox);
    $j("#deleteConfirmation").dialog({
      buttons: [{
          text: "OK",
          "class": "button button-pill button-flat-primary button-tiny ui-state-focus",
          click: function() {
            window.location = $j(ele).attr("href");
          }
        },
        {
          text: "Cancel",
          style: "margin-left:10px",
          "class": "button button-pill button-flat-primary button-tiny ui-state-focus",
          click: function() {
            $j(this).dialog("close");
          }
        }
      ]
    });

    return false;
  }

  $j(".delete").click(function() {
    deleteConfirmation(this, $(this).data("ag-name"), $(this).data("product-code"), $(this).data("product-name-box"));
  });
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">

   Delete

      Are you sure to remove this data?

      Aggregator
      :

      Product Code
      :

      Product Name
      :

This suggests something else is modifying or adding code to your script or your dialog HTML. I would check your console and all libraries added to your page.


text:
Q: .NET Core project does not automatically reference net40 library in NuGet package In .NET Core projects, you don't have explicit references to assemblies within a NuGet package. Instead, you just have this snippet in your project file:
<ItemGroup>
  <PackageReference Include="PackageName" Version="1.2.3" />
</ItemGroup>

and the .NET Core toolchain is expected to take care of downloading/installing the package then referencing the correct assembly within. However, that isn't working for me in this case.
I am working to bundle a library into a NuGet package. This is a .NET Framework 4.0 library. I also have a .NET Core 2.1 project which references this library. This works fine with an explicit assembly reference, no issues detected from testing and the .NET Portability Analyzer gives the library a perfect score.
When I bundle the library into a NuGet package in the lib/net40 directory then add a reference to the package from my .NET Core 2.1 project, the project does not auto-reference the library as expected. I have to put the library in a lib/netstandard2.0 directory for the auto-reference to work. I don't want to do this, because the library is not in fact a .NET Standard 2.0 library.
How can I override the .NET Core auto-reference behavior to reference the library in the lib/net40 directory? I've found this documentation on .NET Framework compatibility mode for NuGet packages referenced from .NET Core projects, but I'm guessing it only applies to net45 and above.


text:
Q: Prove BC tangent to the circle (XYM) Given $\Delta BC$ inscribed $(O)$ and the altitudes $BE,CF$. Let $O'$ be the reflection of $O$ over line $BC$. Let $X,Y$ be the center of $(O'BE),(O'CF)$ respectively. Let $M$ be the midpoint of $BC$. Prove $BC$ tangents to the circle $(XYM)$

Here's what I've obtained so far:  $MX \perp EB$ and $MY \perp CF$. Let $P,Q$ be the projections of $M$ on $EB,FC$ and let $H$ be the orthocenter, $D$ be the projection of $A$ on $BC$. We have $(H,P,Q,D,M)$ concyclic. Therefore, I'm thinking about using inversion on $H$ (which sent $(H,P,Q,D,M)$ to a line through $A$ and the intersection of $AM$ with $(AEF)$)

A: This is a beautiful problem. Here is first a proof involving trigonometry. (I will try to also give a synthetic proof, avoiding it.)
But so far this is a solution, searching for a better one may be easier now.
First of all, let us show the following:

Lemma: Fix a triangle $\Delta ABC$. Let $M,N,P$ be the mid points of its sides, opposite to $A,B,C$ respectively. Let $(O)$ be the circumscribed circle, its center is $O$. Let $O'$ be the symmetric of $O$ w.r.t. $BC$ (and $M$).
  Let $(S)$ be the circle through $B,C,O'$, centered in $S$. Let $X,Y$ be the intersection with the side perpendicular bisectors of the sides $O'B$, and $O'C$. Then $$MX\cdot MP=MY\cdot MN\ .$$

Proof: The trigonometric proof is simple, since we know all angles in the two triangles $\Delta SMX$ and $\Delta SMY$. (So the bridge between $X$ and $Y$, the idea, is to consider $SM$ and relate $MX$, $MY$ to it.)
$$
\begin{aligned}
\frac{MX}{MY}
&=
\frac{MX}{MS}\cdot\frac{MS}{MY}
\\
&=
\frac{\sin(90^\circ-x)}{\sin(180^\circ-y)}
\cdot
\frac{\sin(180^\circ-z)}{\sin(90^\circ-x)}
=
\frac{\sin z}{\sin y}
\\
&=\frac{AB}{AC}=\frac{MN}{MP}\ .
\end{aligned}
$$
$\square$
Now back to the problem. The points from the above Lemma correspond in name with the points in the constellation

and we have shown the relation:
$$
MX\cdot MP=MY\cdot MN\ .
$$
From this, $PXYN$ is inscriptible. ($\Delta MXY\sim\Delta MNP$, $XY$ antiparallel to $NP$, $\angle MXY=\angle MNP$, $\angle MYX=\angle MPN$.)
We get now
$$
\frac 12\operatorname{measure}(\overset\frown{MY}\text{ in circle }(O))
=\frac 12\widehat{YXM}
=\frac 12\widehat{PNM}
=\frac 12\widehat{NMC}
=\frac 12\widehat{YMC}
\ ,
$$
so $MC$ is tangent to $(O)$ in $M$.
$\square$

Notes:

*

*The point $X$ constructed above is the center of the circumscribed circle of the triangle $\Delta O'BE$, since it lies on two perpendicular bisectors of the sides of the triangle,

*

*the one side is $O'B$,

*and the other side is $BE$, its perpendicular bisector being $MP$, since it is parallel to $AC\perp BE$, and goes (as mid line in the triangle) through the mid point of $BE$.

*The directions $XY\| FE$ and $PN\| BC$ are antiparallel, if considered with respect to the angle in $M$ formed by the half lines $MP$ and $MN$.

*An inversion with respect to $M$ may be the solution, since the Lemma isolates the power of the point $M$ with respect to the circle through $N,P,X,Y$. So the "complicated points" $X,Y$ become through this inversion the "simpler points" $NP$. For this inversion $W\to W'$, there correspond:
$$
\begin{aligned}
X&\to X'=P\ ,\\
Y&\to Y'=N\ ,\\
P&\to P'=X\ ,\\
N&\to N'=Y\ ,\\
\text{Circle }(MXY)&\to \text{Projective line }X'Y'=PN\ ,
\end{aligned}
$$
and so on.

A: Proof
Let $H$ be the orthocenter of $\triangle ABC$.
Since $HB \cdot HE=HC \cdot HF$, $H$ lies on the radical axis of $\bigodot X$ and $\bigodot Y$. Hence, $XY \perp O~'H $. But $O~'H \parallel OA$, thus $XY \perp OA.$ Since $OA \perp EF$, therefore, $XY \parallel EF$.
Notice that $M$ is the center of $\bigodot BFEC$, and $BF$ is the radical axis of $\bigodot BFEC$ and $\bigodot X$. Hence, $MX \perp BE$. Similarily, $MY \perp CF$. Further, we may have that $MX \parallel AC, MY \parallel AB$.
Now, let's chase the angles. According to the parallel relations above, it's easy to have $$\angle XMB=\angle ACB=\angle AFE=\angle XYM.$$ Thus, $\angle XMB$ is necessarily the chord tangent angle of $\bigodot XYM$,namely, $BC$ is the tangent of that. We are done.


text:
Q: How to autofill a range in VBA with differing variables I am trying to figure out how to autofill a specific range of cells based on already defined data in the same row. My task is more complex, but a simplification of the step can be seen in the code below. What I want to achieve is:

*

*Define a range where I want to output my values

*Multiply two values in the same row of the selected range cell (to its left), and output this number in the currently selected range cell. To do this, one of the numbers to be multiplied will be dependant on a string also in the row (which describes its type).

*Loop through the defined range and repeat the calculation on each row.

My current code is as follows and outputs a "application defined or object defined error".
Any help would be much appreciated.
For a = Range("P12") To Range("P33") 'Range of cells I want to fill.
    If Cells(a, -10).Value = "B" 'If the cell 10 to the left of our "a" value is = "B".
    Then c = Cells(a, -10).Value * Worksheets("LCI").Range("D4").Value 'Then new variable "c" = (cell 9 to left of a) * (number from another sheet containing a database)

    Cells(a).Value = c 'Update value of selected range cell to contain c which we calculated.
Next 'Repeat for all rows in range.

A: You are close.

*

*You need to think of a as a cell or Range object. That variable is the cell itself which has properties like a.row and a.column that describe its location on the sheet in which it lives.
When you say Cells(a, -10) you are saying "On the Activesheet I want a Cell where the row is a, and where the column has the number -10". There is no row a (as a is a range/cell object and because you didn't specify which property of a you are wanting here it will default to a.value which is probably nothing) and there is no column -10 on the Activesheet.

*Your loop is defined incorrectly. You can use a For Each loop to loop through cells in a range.
Instead:
For Each a In Range("P12:P33")
    'clear `c` each loop
    c=0
    If a.Offset(,-10).Value = "B" Then 'start at cell `a` and move back 10 columns and grab the value
        c = a.Offset(, -10).Value * Worksheets("LCI").Range("D4").Value
    End If
    a.Value = c
Next a


text:
Q: Trigger Gitlab-CI Pipeline only when there is a new tag, with some rules in the answer of this (Trigger Gitlab-CI Pipeline only when there is a new tag ), I understand to set only as filter
But How can I trigger the pipeline only:

*

*there is a new tag created, these tags are semantic versioning tags, how can I filter them? something like

only:
  - /[0-9]+\.[0-9]+\.[0-9]+/

but the tags are not always as 1.0.2, sometimes, they have beta or fc, such as 0.2.3-rc.1 or 2.3.5-beta, will the filter to be /[0-9]+\.[0-9]+\.[0-9]+.*/ is fine?

*second rule is, the trigger is only on master or main branch

Regarding the Semantic versioning regex, I found this gist
https://gist.github.com/jhorsman/62eeea161a13b80e39f5249281e17c39
the sample is too complex
^([0-9]+)\.([0-9]+)\.([0-9]+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+)?$

A: Using only is deprecated in favor of rules.

rules replaces only/except and they can't be used together in the same job.
https://docs.gitlab.com/ee/ci/yaml/#rules

Create a rule and check the predefined variable CI_COMMIT_TAG for your pattern.
job:
  script: echo "Hello, Rules!"
  rules:
    - if: $CI_COMMIT_TAG =~ /^\d+\.\d+\.\d+.*/

You can list multiple of these rules. So if you want to execute the job also on every push to the master branch, you'd add another rule:
rules:
  - if: ...
  - if: $CI_COMMIT_REF_NAME == "master"

The extended pattern with .* at the end would be fine, but you could also be a bit more specific like this (-[0-9a-zA-Z.]+)? if you want to enforce a specific syntax.


text:
Q: How to list only the exquisite items with FirebaseRecyclerAdapter? I have database "items",with all items. And I have list with keys of some of these items. How to list only those items with FirebaseRecyclerAdapter?

A: Have a look at the FirebaseIndexRecyclerAdapter, which was specifically made for this structure. From the FirebaseUI documentation:

If your data is properly indexed, change your adapter initialization like so:
For a RecyclerView, use FirebaseIndexRecyclerAdapter instead of FirebaseRecyclerAdapter:
new FirebaseIndexRecyclerAdapter<Chat, ChatHolder>(
      Chat.class,
        android.R.layout.two_line_list_item,
        ChatHolder.class,
        keyRef, // The Firebase location containing the list of keys to be found in dataRef.
        dataRef) //The Firebase location to watch for data changes. Each key key found at keyRef's location represents a list item in the RecyclerView.

So keyRef is a reference to the location with just the keys, and dataRef is a reference to the location with all the full items.
If you're interested in how this works under the hood, have a look at the code