text:
Q: Prompt error when user enters a char instead of an expected int I'm making a menu that lists options 1-3. The user is expected to enter an integer.
scanf("%d", &select_option)

How do I prompt error when user enters a char (for example "a", or "asd" for long strings, or a mixture like "1a2") instead of an expected int? Thanks.
Note: When the user enters a 'char' like 'a', 'asd', the code goes into an infinite loop for some reason.
Here's my program (minimal example):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

        int main(void)
            {
                printf("Favourite sports? \n");
                printf("1. Tennis\n");
                printf("2. Badminton\n");
                printf("3. Basketball\n");
                printf("4. Exit program.\n");
                printf("Enter your choice (1-4): ");
                scanf("%d", &select_option);

                while(select_option != 4)
                {
                    switch(select_option)
                    {
                        case 1:
                            printf("You like tennis! Nice! \n");
                            break;

                        case 2:
                            printf("You like badminton! Nice!");
                            break;

                        case 3:
                            printf("You like basketball! Nice!");
                            break;

                        default:
                            system("clear");
                            printf("Invalid option. Please re-enter your choice (1-4).\n");

                    }//end switch

                printf("Favourite sports? \n");
                printf("1. Tennis\n");
                printf("2. Badminton\n");
                printf("3. Basketball\n");
                printf("4. Exit program.\n");
                printf("Enter your choice (1-4): ");
                scanf("%d", &select_option);

                }//end while
            }//end main

A: You could do this:
#include <stdio.h>

int main(void) {
    int v;
    int ret = scanf("%d", &v);
    if(ret == 1)
        printf("OK, %d\n", v);
    else
        printf("Something went wrong!\n");
    return 0;
}

where I took advantage of the return value of scanf(), and based on that value, I made an assumption. This will fail for the case of "1a2", but will succeed for "12" and "a".
However, this is a broad question and personally the way I would go for it is:

*

*Use fgets() to read input.

*Discard newline.

*Convert string to integer (with strtol() for example).

*Validate input.

A: I am assuming u are a beginner. You can use Switch Case which is used usually for creating menus and depending on the choice of the user executes the particular case.
I will show u a small example.
#include<stdio.h>
#include<conio.h>
int main()
{
  int n;
  printf("Select the sports u want to do\n");
  printf("1.Tennis\n2.Karate\n3.Football\n");
  scanf("%d",&n);
  Switch(n)
  {
     case 1:printf("You chose Tennis\n");
          break;   //To prevent from all cases being executed we use
                   //break which helps from coming out of a loop
     case 2:printf("You chose Karate\n");
          break;

     case 3:printf("You chose Football\n");
          break;

     default:printf("Please enter an appropriate number !");
            //Cases which dont match with the input are handled by default !
  }
}

Also to make the user enter input until he wants to exit add a while loop with a variable !
I hope this helps!


text:
Q: Drawing Circle in scheme language I have recently used midpoint circle algorithm in scheme to draw a circle, however it can only draw a small circle that radius not bigger than 10, when the radius increase, it become a octagon. Can anyone tell me how to correct my code?
(define (Circle x0 y0 r)
  (let ((x 0) (y r) (dp (- 1 r)))
   (CircleGo dp x0 x y0 y)))

(define (CircleGo dp x0 x y0 y)
  (let ((x1 (+ x 1))(y1 (- y 1)))
    (let ( (dp1 (+ (* 2 x1) 3)) (dp2 (+ (- (* 2 x1) (* 2 y1)) 5)))
        (if (<= x y)
              (if (< dp 0)
              (append (list (+ x0 x)(+ y0 y)
                        (- x0 x) (+ y0 y)
                         (+ x0 x) (- y0 y)
                             (- x0 x) (- y0 y)
                                (+ x0 y) (+ y0 x)
                                     (- x0 y) (+ y0 x)
                                        (+ x0 y) (- y0 x)
                                          (- x0 y) (- y0 x))
                (CircleGo dp1 x0 x1 y0 y))
              (append (list (+ x0 x) (+ y0 y)
                         (- x0 x) (+ y0 y)
                           (+ x0 x) (- y0 y)
                             (- x0 x) (- y0 y)
                               (+ x0 y) (+ y0 x)
                                 (- x0 y) (+ y0 x)
                                   (+ x0 y) (- y0 x)
                                    (- x0 y) (- y0 x))
                (CircleGo dp2 x0 x1 y0 y1)))
          (list )))))

A: I think this question has a lot more to do with math than with programming. It sounds like you need a function that accepts a center, a radius, and an angle in radians and returns the x and y coordinates of the specified point. Sine and Cosine are your friends here. Specifically, (x0 + r * Cos(theta), y0 + r * Sin(theta)).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Chinese Text to Speech in iOS Does anyone know how to implement Text to Speech with Chinese language in iOS?
Any links or suggestions would be helpful.

A: As Sten said, you could use iSpeech. Here is the same answer, in more detail:
You can use their API, but the problem with that is that it is limited to 200 uses/day.
If you want to have unlimited uses, you need to buy it. One way to get around that is to access the data returned by their demo program (which returns in mp3 format).
I made a small piece of code that demonstrates that in Python. Python is available for iOS from this site. The demo program has a limit of 20 words a go, so your program must split every 20 words, and feed the segments in separately. The following code does not use a buffer, so there might be a slight delay between segments.
from urllib import quote_plus

def speak(text):
    import pydshow
    words = text.split()
    temp = []
    stuff = []
    while words:
        temp.append(words.pop(0))
        if len(temp) == 24:
            stuff.append(' '.join(temp))
            temp = []
    stuff.append(' '.join(temp))
    for i in stuff:
        pydshow.PlayFileWait('http://api.ispeech.org/api/rest?apikey=8d1e2e5d3909929860aede288d6b974e&format=mp3&action=convert&voice=chchinesemale&text='+quote_plus(i))

if __name__ == '__main__':
       speak('Hello. This is a text-to speech test.')

I find this ideal because the demo program DOES use the API, but it uses the API key that is used for the demo program. Therefore, it never runs out. The key is 8d1e2e5d3909929860aede288d6b974e. Also, the program is quite simple, and may be adapted to work in any programming language.
You can actually test this at work without the program, by typing the following into your address bar:
http://api.ispeech.org/api/rest?apikey=8d1e2e5d3909929860aede288d6b974e&format=mp3&action=convert&voice=chchinesemale&text=Hello
Here is how you can tailor that to your needs:
http://api.ispeech.org/api/rest?apikey=8d1e2e5d3909929860aede288d6b974e&format=mp3&action=convert&voice=chchinesemale&text=

Followed by the text you want to speak. You can also adjust the gender, by changing, in this case, the chchinesemale to something else that iSpeech offers. For example, chchinesefemale. This will speak the same text, but in a feminine voice. Specifications on the codes can be found here.
Hope I helped!
NOTE: Pydshow is my wrapper around DirectShow, which is Windows-only. You have to find an alternative to it for iOS if you choose this method.

A: iSpeech can handle Chinese, is free for shorter messages and works well. The voice rendered online however, so you need a connection. You can test the voice here:


text:
Q: why mongo count doesn't add up? Does anyone know why mongodb returns strange result count when performing the next 3 queries? It seems that the result of the first and second counts should be equal to the third, but it does not. All I do is count the number of docs that contain a certain field + the ones that do not contain that field.. I expect this to be equal to the total number of docs:
> db.col1.find({f1:{$exists:false}}).count()
0
> db.col1.find({f1:{$exists:true}}).count()
267837
> db.col1.count()
268185

A: Maybe because you have a sparse index on f1 field?
If that is true, try this and see if they match:
db.col1.find({f1:{$exists:false}}).hint({f1:1}).count()
db.col1.find({f1:{$exists:false}}).hint({_id:1}).count()


text:
Q: Adding a Cocoapod to a Cocoapod I am creating my own custom library and I want to implement a QR Code Reader in it.
My plan was to add a QR Code reader cocoapod to my library, but I am struggling to do that.
Any tips?

A: You can certainly do this. You add the other pod as a dependency of your own pod in the podspec file.
e.g. spec.dependency 'MyQRCodeReaderPod', '~> 1.0'
Here's the official guide:
https://guides.cocoapods.org/syntax/podspec.html#dependency


text:
Q: Can a Supervised Routine be Compared Against an Unsupervised? Just a question out of curiosity. Suppose that I had generated:
(1) an unsupervised decision tree using 'interpretable clustering,' and (2) a second supervised decision tree (whether CART, or a decision tree from the optimal decision tree paradigm).
If I had these two decision trees available to me, is it somehow possible to evaluate what the inclusion of a dependent variable brings to the party, rather than just using visual inspection of both trees?
Would be helpful if anyone knew of anything here, such as an objective score/information criteria/whatever. Or similarly, if people just thought this was a ludicrous question. All feedback welcomed.


text:
Q: R function to identify unique rows from previous rows, not within the dataframe altogether I have a dataframe in which I need to identify or index the start of each new trial. A new trial is indicated by variable Location from 0-8. Example below:
    zPos        Location
    1.9148150   6
    1.914815    6
    1.914815    6
    1.914815    6
    1.914815    6
    0.9018518   3
    0.9018518   3
    0.9009259   3
    0.9009259   3
    0.9009259   3
    0.9009259   3

There are 72 trials in each dataframe, so each location value repeats 8 times meaning unique won't work. I am a novice when it comes to R, so I haven't tried much outside of base R and dplyr to tackle this problem.
Ideally I would like to create a new variable for trial number, example below:
    zPos        Location       TrialNum
    1.9148150   6              1
    1.914815    6              1
    1.914815    6              1
    1.914815    6              1
    1.914815    6              1
    0.9018518   3              2
    0.9018518   3              2
    0.9009259   3              2
    0.9009259   3              2
    0.9009259   3              2
    0.9009259   3              2

But I could also work with an index of the starting location for each new trial rather than a new variable in the dataframe.
This is my first question on stackoverflow, so I greatly appreciate any assistance or insight.

A: You could use rle to do this.
df <- data.frame(
  zPos = c(1.9148150, 1.914815, 1.914815, 1.914815, 1.914815, 0.9018518,
           0.9018518, 0.9009259, 0.9009259, 0.9009259, 0.9009259),
  Location = c(6, 6, 6, 6, 6, 3, 3, 3, 3, 3, 3)
)

get_trial <- function(col) {
  r <- rle(col)
  rep(seq(length(r$lengths)), r$lengths)
}

df %>%
  mutate(TrialNum = get_trial(Location))

        zPos Location TrialNum
1  1.9148150        6        1
2  1.9148150        6        1
3  1.9148150        6        1
4  1.9148150        6        1
5  1.9148150        6        1
6  0.9018518        3        2
7  0.9018518        3        2
8  0.9009259        3        2
9  0.9009259        3        2
10 0.9009259        3        2
11 0.9009259        3        2

A: This can work:
df$iTrialNum <- match(df$Location, unique(df$Location))

# -------------------------------------------------------------------------
#     zPos Location iTrialNum
# 1  1.9148150        6         1
# 2  1.9148150        6         1
# 3  1.9148150        6         1
# 4  1.9148150        6         1
# 5  1.9148150        6         1
# 6  0.9018518        3         2
# 7  0.9018518        3         2
# 8  0.9009259        3         2
# 9  0.9009259        3         2
# 10 0.9009259        3         2
# 11 0.9009259        3         2

Sample data (df)
dput(df)
structure(list(zPos = c(1.914815, 1.914815, 1.914815, 1.914815,
1.914815, 0.9018518, 0.9018518, 0.9009259, 0.9009259, 0.9009259,
0.9009259), Location = c(6L, 6L, 6L, 6L, 6L, 3L, 3L, 3L, 3L,
3L, 3L)), class = "data.frame", row.names = c(NA, -11L))


text:
Q: how to get the world position of cursor which is attached to camera in aframe i want to get the world location of cursor to help me create hotspots for 360 tour for that i have created a component that returns the position of cursor. The component is working fine but it returns the relative position of cursor so what should i do to get the world position of cursor
link to glich project

A: You can use one of these THREE.js methods:
// set a vector from the cursors matrix world
vec3.setFromMatrixPosition(cursorEl.object3D.matrixWorld);

// fill a vector using the getWorldPosition
cursorEl.object3D.getWorldPosition(vec3)

Check it out in this fiddle.

Using it within a custom component.
Having a setup like this
<a-camera>
   <a-cursor my-component></a-cursor>
</a-camera>

You could have a component like this:
AFRAME.registerComponent("my-component", {
   init: function() {
       this.vec = new THREE.Vector3()
   },
   tick: function() {
       this.vec.setFromMatrixPosition(this.el.object3D.matrixWorld);
       // do something with this.vec
   }
})


text:
Q: How to customize Visual Studio C/C++ indentation/formatting beyond None/Block/Smart (Like Eclipse Can) Is there a way to customize Visual Studio indentation/formatting in detail?  There seems to be just three options: None, Block, Smart (in Options > Text Editor > C/C++ > Tabs).  There are a couple more options under Options > Text Editor > C/C++ > Formatting, but these don't provide the the options I am looking for (e.g. how much to indent line wrapping).
In contrast there are a huge number of options to configure in formatting Eclipse, as described here (e.g. a line wrapping tab with various options), so I would expect there to be some similar configuration options in Visual Studio.

A: Tools > Options > Text Editor > C/C++ > Formatting is all there is built-in to VS.
An alternative that's smarter is clang-format: http://clang.llvm.org/docs/ClangFormat.html. There's an installer that integrates in into Visual Studio for you: http://llvm.org/builds/. Note that it only deals with the file's actual formatting rather than things like soft-wrapping lines. Soft-wrapping source code is horrific anyway.


text:
Q: How can I check a for specific character as well as these lengths using regex I have this regular expression
^(?=[\s\S]*$)(?:.{10}|.{11})$
This will get a match as long as it is 10 or 11 characters, but how can I make it check for a specific character / as well?
So it has to be 10 or 11 characters and contain a /

A: You can use this
^(?=.*\/).{10,11}$

*

*^ - Start of string.

*(?=.*\/) - Positive lookahead. condition for / must.

*.{10,11} - Match anything except new line 10 or 11 time.

*$ - End of string.

Demo


text:
Q: Adding Spring for android dependency to gradle + Android studio project Official Spring for Android page mentions to add following dependency code.
dependencies {
    compile 'org.springframework.android:spring-android:1.0.1.RELEASE'
}

which is latest version of build as of this time.(as per website)
I have added it in apps' build.gradle but I get an error as
Error:Failed to find: org.springframework.android:spring-android:1.0.1.RELEASE

What is the right way to do it?
I could add google play services as dependency in the same way.

A: Here is the correct dependency for the Rest Template module. I've corrected this on the Spring for Android project page. Thank you very much for pointing out this error.
dependencies {
    compile 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE'
}

A: You can find correct and lastest version on spring site. Under the Quick Start title.
http://projects.spring.io/spring-android/


text:
Q: Google Oauth in functional components / Uncaught TypeError: Cannot read properties of undefined I beg your assistance on this. I'm using react  v16.13.1 and I have a class component which I want to convert to functional component.  My goal was to implement a google authenticate feature using functional components.

*

*Should all class property be substitued by an State?  this.auth I've converted it to authState.

*My functional component code returns this error from time to time. I assume this an asyncrony error and I should put an async function and its await inside the useEffect?
functional component returns this error
Thanks in advance for your time.
A. Class component
import React, { Component } from "react"
import { Link } from "react-router-dom"

class GoogleAuthButton extends Component {
  state = { isSignedIn: null }

  componentDidMount() {
    window.gapi.load("auth2", () => {
      window.gapi.auth2
        .init({
          client_id: process.env.REACT_APP_GAUTH2_CLIENT_ID,
          scope: "email",
        })
        .then(() => {
          this.auth = window.gapi.auth2.getAuthInstance()
          // updating  state so component will re-render
          this.setState({ isSignedIn: this.auth.isSignedIn.get() })
        })
    })
  }

retrieveUserStatus() {
    if (this.state.isSignedIn === null) {
      return "UNKNOWN"
    } else if (this.state.isSignedIn) {
      return "SIGNED IN"
    } else {
      return "NOT SIGNED IN"
    }
  }
  render() {
    return (
      <Link to="/" className="item">

Status: {this.retrieveUserStatus()}

      </Link>
    )
  }
}

export default GoogleAuth

B. Functional component
import React, { useState, useEffect } from 'react';
const GoogleAuthButton = () => {
    const  [isSignedInState, isSignedInSetState] = useState({ isSignedIn: null });
    const  [authState, setAuthState] = useState({});

       useEffect(()=> {
// the following line arises the error:
                window.gapi.load("auth2", () => {
                window.gapi.auth2
                .init({
                    client_id: process.env.REACT_APP_CLIENT_ID,
                    scope: "email",
                })
                .then(() => {
                    //gapi.auth2 becomes an state of our function component
                    setAuthState(window.gapi.auth2.getAuthInstance());
                    // update state so that component will re-render
                    isSignedInSetState({ isSignedIn: authState.isSignedIn.get() });

                })
            } )
        },[])

     // updates auth state to current auth status.It's triggered when authentication status changes
         const onAuthChange = () => {
            isSignedInSetState(authState.isSignedIn.get())
          }

        console.log("authentication", authState)

        return (

is the user signed in? {isSignedInState}

        )

    }

I've added the google auth script in:
index.html
<!DOCTYPE html>

    <meta charset="utf-8" />

   ****


text:
Q: Elasticsearch 5.6.5 cannot starup on Ubuntu14.04 All
I am new to elasticsearch. and I have installed the elasticsearch 5.6 on Ubuntu 14.04, with apt-get following the instruction on this page.
However, it fail to start when I was trying this command

sudo -i service elasticsearch start

Then I add a log line to check what the command really is.

log_daemon_msg "sudo -u $ES_USER $DAEMON $DAEMON_OPTS"
start-stop-daemon -d $ES_HOME --start --user "$ES_USER" -c "$ES_USER" --pidfile "$PID_FILE" --exec       $DAEMON -- $DAEMON_OPTS

It returns

sudo -u elasticsearch /usr/share/elasticsearch/bin/elasticsearch -d -p /var/run/elasticsearch/elasticsearch.pid -Edefault.path.logs=/var/log/elasticsearch -Edefault.path.data=/var/lib/elasticsearch -Edefault.path.conf=/etc/elasticsearch

I try to run is command directly, and the command exit without print any log. I also check the /var/log/elasticsearch, which is an empty dir.
Could anyone help to find out what do I miss?
Thanks.
BTW. I am running a 512M RAM, and 1G swap machine. and I have modifed the jvm.options to -Xms256m and -Xmx256m


text:
Q: Flutter Dart - non breaking space producing no space at all I'm trying to use non breaking space in order to keep a Brand name on the same line.
I've successfully implemented the solution found here: https://stackoverflow.com/a/67049738
But the non breaking space end up with no space at all.
I even tried a simpler solution adding the unicode directly into the String, and still no luck.
Text(
 "Brand\u{00A0}Name",
 textAlign: TextAlign.center,
)

And how it's rendered

Is it possible the font used doesn't support non-breaking space?

A: My guess was right, the custom font I use does not support non breaking space char.
I've tried to use the default native font "Roboto" instead of my custom font and the solution posted in my previous message works just fine, as well as the one linked.
:: custom font:

Text(
     "Brand\u{00A0}Name",
     style: TextStyle(fontFamily: 'CustomFont'),
)

:: Roboto font:

Text(
       "Brand\u{00A0}Name",
       style: TextStyle(fontFamily: 'Roboto'),
)


text:
Q: Finding the smallest base
$(2)(4)_b$ represents a number written in base $b$. For example $21_3
 = 7$. How to find the smallest $b$ such that $(17)(3)_b$ is a multiple of $7$?

Assuming,$(17)$ as the single digit,I computed the smallest base to be $32$.Unfortunately,there is no way I could confirm this answer,so I am asking it here.Am i right?

A: We must have
$$17b + 3 \equiv 3(b + 1)\equiv 0\ \pmod 7\Longrightarrow b \equiv 6\ \pmod 7$$
So we can have $b = 6, 13, 20, ...$. The 17 suggests that b > 17, the smallest multiple of which is 20.


text:
Q: can I handle & display message for ERROR: ORA-12154 in batch file I have test.bat batch file in which I am connecting to the different databases.
In test.bat i am executing mysql.sql, and redirect output into result.csv file. But if ERROR:
ORA-12154 occurs it display on command prompt not in csv file I want to display it into the result.csv file.
here is my test.bat :-
@ECHO On
setlocal enabledelayedexpansion

for /f "delims== tokens=1,2" %%a in (D:\batch\InstallList.txt) do (
sqlplus %%b @D:\batch\mysql.sql %%a rem %%b is dbname & password.
)
pause;

mysql.sql is :-
set heading off;
set verify off;
var ename varchar2(20)

exec :ename := '&1'

spool D:\batch\result.csv app
begin
select user_name, user_id from employee where designation = 'manager';
end;

I want to show ERROR: ORA-12154 in result.csv.


text:
Q: InnerHTML *ngIf does not work Angular5 To show a pop up on a GIS openlayers map i use the InnerHtml attribute.
If a field is false I want to hide is DIV.
It looks like angular ignores my ngif this is my code:
this.content.innerHTML = `
      <div style="width: 150px; float: right; font-size: 13px;" *ngIf="!test">
              ${ test }
      </div> `

My boolean test is false. Is it true that ngIf does niet work with innerHTML?
thx al lot

A: Angular will not entertain your *ngIf when you are using innerHTML
Whenever you pass some content via innerHTML, Angular is just going to render that content does not evaluate any expression or binding within that content like you did by adding a ngIf event.

A: You need to add and remove the styles like below
constructor(private elRef: ElementRef) {

 this.elRef.nativeElement.querySelector('#showResponsiveNavbarone')
 .classList.remove('visibletrue');

}
 <style>
  .visiblefalse{
  display: none !important;
}
.visibletrue{
 display: block !important;
}


text:
Q: How composer check php version? I just wondering how composer check which php to use when check for requirements. I use MacOS and in terminal type:
composer require phpunit/phpunit

the result is something like:
Problem 1
- phpunit/phpunit 5.0.4 requires php >=5.6 -> your PHP version (5.5.27) or "config.platform.php" value does not satisfy that requirement....

When I check php version:
php -v

The result is:

PHP 5.6.10 (cli) (built: Jun 12 2015 14:08:56) Copyright (c) 1997-2015
  The PHP Group Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend
  Technologies
      with Xdebug v2.2.5, Copyright (c) 2002-2014, by Derick Rethans

Which is:
which php

php: aliased to /Applications/MAMP/bin/php/php5.6.10/bin/php
Can someone explain this. Thanks in advance!

A: Composer can tell you what version of PHP it's running on, if you specify debug verbosity -vvv.
I like to run it with the about command, since the output is relatively short.

composer -vvv about

Example output:

...
     Running 1.8.5 (2019-04-09 17:46:47) with PHP 7.3.5 on Darwin / 18.6.0
     ...

Edit:
This has gotten more interest than I expected, so here's a version with cleaner output:

composer -vvv about 2>&1 | grep "PHP"

A: On MacOs X the default installation of php resides in /usr/bin. If you upgrade your php it will most likely be installed somewhere else (like /usr/local/php5), or if you use MAMP or something else it will be elsewhere. Just make sure that the first occurrence of php when traversing your PATH is the same as the version your webserver is using. (like have /usr/local/php5/bin before /usr/bin in your PATH). That will solve your problem.

A: If you used a package install method, such as apt-get on Ubuntu, chances are that the executable will include a "shebang" pointing to the specific php that should be used to run that specific composer file.
When using the command composer the cli will first resolve which binary to use. By running which composer you can find what binary that is.
$ which composer
/usr/bin/composer

Once you know that, you can open the file, for instance using vim: vim /usr/bin/composer (generally it takes super user access to modify binaries so you shouldn't be able to mess composer up doing that).
On the first line of the composer binary should be a shebang, possibly looking like #!/usr/bin/php that would instruct the composer executable on how it should run.
You can then call that php binary directly to verify its version:
/usr/bin/php -v

A: ( sharing this here because I was looking for it an landed here but nothing satisfied me so I will share for those who land here for the same reason: )
With the following command you can check which composer packages depend on a specific php version:
composer depends php | grep 8.1

will output something like:
symfony/console                    v6.1.4  requires php (>=8.1)
symfony/css-selector               v6.1.3  requires php (>=8.1)
symfony/deprecation-contracts      v3.1.1  requires php (>=8.1)
symfony/error-handler              v6.1.3  requires php (>=8.1)
symfony/event-dispatcher           v6.1.0  requires php (>=8.1)
symfony/event-dispatcher-contracts v3.1.1  requires php (>=8.1)
symfony/finder                     v6.1.3  requires php (>=8.1)
symfony/http-foundation            v6.1.4  requires php (>=8.1)
symfony/http-kernel                v6.1.4  requires php (>=8.1)
symfony/mailer                     v6.1.4  requires php (>=8.1)
symfony/mime                       v6.1.4  requires php (>=8.1)
symfony/process                    v6.1.3  requires php (>=8.1)
symfony/routing                    v6.1.3  requires php (>=8.1)
symfony/service-contracts          v3.1.1  requires php (>=8.1)
symfony/string                     v6.1.4  requires php (>=8.1)
symfony/translation                v6.1.4  requires php (>=8.1)
symfony/translation-contracts      v3.1.1  requires php (>=8.1)
symfony/var-dumper                 v6.1.3  requires php (>=8.1)


text:
Q: PHP if/else and AND/OR to check mandatory and optional fields I have eight input fields in my form that I need to check whether they are empty. Four of these are text fields, the other four are list boxes. When the user submits the form, the four text boxes need to be filled. The fifth field is a Yes/No selection. If the selection in this field is "No", then the remaining three can be left blank. However, if the selection in the fifth field is "Yes" then the last three also have to be selected using the list boxes.
Let us call the first four (textboxes) "mandatory-text1", "mandatory-text2", "mandatory-text3", and "mandatory-text4", the Yes/No selection list box "yes-no" and the optional selections "a", "b" and "c".
SO:
If mandatory-text1, or mandatory-text2, or mandatory-text3, or mandatory-text4, are blank, the processing php will abort.
However, if mandatory-text1, mandatory-text2, mandatory-text3, and mandatory-text4, are all filled in, the next check is to see whether the yes-no contains a "Yes" or a "No".

*

*If it contains a No, then a, b and c have to be necessarily left
blank.

*If it contains a Yes, then a, b and c (list boxes) have to be
necessarily selected.

With my level of proficiency in PHP, I have been able to reach this far:
    if ((mandatory-text1 || mandatory-text2 || mandatory-text3 == "") OR (yes-no == "Yes" AND (!(a || b || c  == ""))) {
    echo "blah" ;
    exit();
    }
    else {
    //do some stuff
    }

I haven't coded the 'do some stuff' part yet because when I try this code, I get the 'blah' message even when all the text fields are filled in, the yes-no is "Yes" and a, b and c have been selected.
I tried it first with a simple "||" for all the fields and that works fine - i.e. if even one of the fields is left blank I get the 'blah' message. I have also tried just checking for the yes-no and a,b,c and that too works fine i.e. if there is a Yes in the yes-no i get the blah if the a,b,c fields are blank.
But I need to satisfy all the conditions before I can proceed to the next step. The posts I have read here on SO brought me to the stage I am in right now. But none went to the level I want for my project.
Any hints for the logic would be appreciated!

A: Okay first of all, you are supposed to use $ before variable names
Second,
mandatory-text1||mandatory-text2||mandatory-text3==""
is wrong logic. It should be $mandatory-text1=""||$mandatory-text2==""|| ...
It works because if(mandatory-text1) alone means if mandatory-text1 is defined and not empty or null string, so in this case  $mandatory-text1||$mandatory-text2||$mandatory-text3 alone is sufficient
if ((mandatory-text1 || mandatory-text2 || mandatory-text3 == "") OR (yes-no == "Yes" AND (!(a || b || c  == ""))) {
echo "blah" ;
exit();
}
else {
//do some stuff
}

same for a||b||c

A: (mandatory-text1 || mandatory-text2 || mandatory-text3 == "")

This isn't working the way you think it is. This says:
if mandatory text 1 is not empty or mandatory 2 text is not empty or mandatory 3 text is equal to ''.
Try:
(mandatory-text1 == "" || mandatory-text2 == "" || mandatory-text3 == "")

A: You may redesign your control in a more readable way, with a function or code block per field type, for example :
<?php

function checkFields( $data )
{
    // List of field to check
    $fields = array( 'mandatory-text1', 'mandatory-text2', 'mandatory-text3', 'mandatory-text4', 'a', 'b', 'c' );

    foreach ($fields as $field )
    {
        switch( $field )
        {
            case 'mandatory-text1':
            case 'mandatory-text2':
            case 'mandatory-text3':
            case 'mandatory-text4':
                if ( $data[$field] == '' )
                {
                     return false;
                }
            break;

            case 'a':
            case 'b':
            case 'c':
                if ( $data['yes-no'] == 'yes' && $data[$field] == '' )
                {
                    return false;
                }
                elseif( $data['yes-no'] == 'no' && $data[$field] != '' )
                {
                    return false;
                }
            break;
        }
    }

    // If we have not returned false so far, then all is clear
    return true;
}

// Usage :
if( checkFields( $_POST ) )
{
    // every thing is ok
}
else
{
    // bad submission
}
?>

You should mostly avoid 2 things here :

*

*Long AND / OR statements

*Repeating your self with the smae controls

A: If I understood correctly, something like this should work. Do NOT use dashes in variable names.
if ($mandatory1 && $mandatory2 && $mandatory3 && $mandatory4)
{
    if ($choice == "Y" && $a && $b && $c)
    {
        // do whatever
    }
    elseif ($choice == "N" && !$a && !$b && !$c)
    {
        // do something else
    }
}
else
{
    // submission incorrect
}


text:
Q: MVC4 model property should be a list or an ICollection of another class I'm making a type of test-generation application using Entity Framework code-first. I have a base class called Question, from which MultipleChoiceQuestion, EssayQuestion, and other question types descend.  MultipleChoiceQuestions obviously have multiple answers from which the test taker must select. My question has to do with choosing the best way to store them in the question instance.
I could declare the class with a List of Strings to hold the answers, like so:
public class MulitpleChoiceQuestion : Question
{
    private List<String> Answers = new List<String>();
    // other declarations, etc.
}

Instead I could declare another class called Answers, and let my Question classes use a collection of Answers.
public class Answer
{
    public int AnswerID { get; set; }
    public String AnswerText { get; set; }

    public virtual Question Question { get; set; }
}

And then in my question subclasses (not just MultipleChoiceQuestions)
public class MulitpleChoiceQuestion : Question
{
    public virtual ICollection<Answer> Answers { get; set; }
    // other declarations, etc.
}

Is there a better way than either of these? If not, which of these is better, and why? I'm having a difficult time finding anything this detailed on the web, and most books don't go this deep either.
Thanks in advance for any guidance.

A: I asked a .NET professor friend of mine this question, and this is his response:

Both of your declarations are invoking collections. A list is a typed
  collection while ICollection is untyped. Typed Collection (List) has
  two advantages over untyped collections. The type of each collection
  is checked at compile time and thus preventing runtime errors. Second,
  they reduce the amount of casting that is needed when retrieving
  objects.

I first implemented the ICollection solution, and it was clunky in a couple of places (for example, the Initializer for seed data):
    var mcQuestions = new List<MultipleChoiceQuestion>
    {
        new MultipleChoiceQuestion {
            QuestionText = "What is the value returned by the expression (true == false? 'yes': 'no')?",
            Answers = new List<Answer> { new Answer { AnswerText="true"}, new Answer { AnswerText = "false"}, new Answer { AnswerText = "can't be determined"}, new Answer {AnswerText = "45"}, new Answer { AnswerText = "blue"}}
        },
        new MultipleChoiceQuestion {
            QuestionText = "C-Sharp responds to a global variable declaration by:",
            Answers = new List<Answer> { new Answer { AnswerText="throwing a compile error"}, new Answer { AnswerText = "throwing a runtime error"}, new Answer { AnswerText = "Throwing an Invalid operator warning"}, new Answer {AnswerText = "Printing a warning to the console"}, new Answer { AnswerText = "doing nothing; global variables are legal"}}
        }
    };
    mcQuestions.ForEach(mcq => context.MultipleChoiceQuestions.Add(mcq));
    context.SaveChanges();

Although this solution may be more flexible, I think the List will be much cleaner, and more maintainable in the long run. I can't think of a reason to keep the complexity as a trade-off for possible flexibility in the future. So it's List for me.
Hope this helps someone else out there.
Good luck, and good code.
J

A: I haven't tried out something similar yet, but I would expect EF to turn your List into a seperate Answers table on your database side, so I would expect that both solutions will result in the same database model. In any case, if both methods work, deciding which one to pick is going to be a matter of taste.
Personally I would go with the List as it looks like the most simple solution and simple is generally better. If you wish your classes to better represent your database that could be a reason to make a seperate Answer class. If you expect to expand your Answer in the future, that could be another reason to pick a seperate Answer class over the simple List.
In general I would say: if you have two ways of solving a problem, the one to pick is the one that makes your code the easiest to read/understand when looking at the code.


text:
Q: Git patch create and send it to an email I just created a patch using the following command git format-patch master --stdout > raj_powar.patch
In order to send the 'raj_powar.patch', i ran the following command git send-email --subject="stringval"  --to="address" raj_powar.patch
But i keep getting the error "No subject line in raj_powar.patch ? at /Library/Developer/CommandLineTools/usr/libexec/git-core/git-send-email "
What am i doing wrong, how do i email this patch?

A: Your format-patch command didn't specify a range of commits, so likely your patch file is empty.  If you just want a patch for the top commit on master, you can use "-1" or use "master^..master".
Use git format-patch -1 master --stdout > raj_powar.patch instead.


text:
Q: Illustrator svg icon - which size? Lets say I am creating an icon in illustrator, which should be saved as an svg. If I create a large nice vector icon, lets say 800x800 pixels, I can always scale it as I want to, and its "easier" to work with. Problem is, when this icon is saved, the file size is big.
If I instead make a small icon in illustrator, on a document size which has the proportions the icon will be used as, lets say 20x20, the file size is much smaller.
So what is good practice when working with icon sizes?
Thanks!

A: You are mistaken.  A vector graphic that is 800x800 should have the same file size (more or less) as a vector graphic that is 20x20.  That is because the shapes that make up the file are defined "mathematically" and can be rendered at any size.
If your files have significantly different sizes, you have probably not created a purely vector file.  It probably has bitmap images in it.  Bitmap image file sizes are greater if the image size is larger.
However, in answer to your primary question, it doesn't really matter what the page size is when creating vector icons.  They could be either of the two sizes you mentioned.  Or any other size.  Whatever dimensions you choose, they should be rendered nicely at any final size you need.


text:
Q: fancybox is not working correctly inside ajax Code Edited Please Reaview.
i'm trying to show fancybox after testing a value using ajax after clicking a link but the fancybox keeps disappearing and showing up for ever as it's inside a loop any solution ?
 $(document).ready(function () {
    $("a.add_to_cart[pro_id]").click(function (e) {
        e.preventDefault();
        var pro_name = $(this).attr("pro_name");
        var pro_id = $(this).attr("pro_id");
        var qst = "?pro=" + pro_id;
        var ajax = false;
        ajax = new XMLHttpRequest();
        ajax.open("get", "ajax/check_exists.php" + qst);
        ajax.onreadystatechange = function () {
            if (ajax.readyState == 4 && ajax.status == 200) {
                var result = ajax.responseText;
                if (result == 'product in cart') {
                    alert(result);
                } else {
                    $("a.add_to_cart[pro_id=" + pro_id + "]").fancybox({
                        'transitionIn': 'elastic',
                        'transitionOut': 'elastic'
                    }).trigger('click');
                }
            }
        }
        ajax.send(null);
    });
});

A: Just add the click right after you apply the fancybox:
$("a.add_to_cart").fancybox({
    'transitionIn'  : 'elastic',
    'transitionOut' : 'elastic'
}).click();

A: You'll need to unbind the event in order to prevent recursive click triggering:
$("a.add_to_cart").unbind("click");
$("a.add_to_cart").fancybox({
    'transitionIn'  : 'elastic',
    'transitionOut' : 'elastic'
}).click();

But you should try to separate the elements because unbind will destroy the binding for all the elements with your add_to_cart class.
Try to set id instead of class for the elements and as selector, so that only the current clicked element's binding will be destroyed.


text:
Q: Array of Gauges with angular.js I am using gauge.js(http://bernii.github.io/gauge.js/) on my angular.js and I am trying to create dynamic instans of gauges, with settings value throw ng-model,
I have in my template:

{{ item.name }}

{{item.waitTimeEstimationSec}}

{{ item.streetAddress }}

          <canvas gaugejs options="gaugeOptions" value="12" max-value="15" animation-time="animationTime"></canvas>

but still how can I set values for my gauge with ng model?
thanks!

A: I found the best gauge for me and its wj-radial-gauge. very easy to use.


text:
Q: App engine Python NDB map_async using callback, objects and inheritance pattern I have a Parser class which has methods to parse docs. Parser is like a "container" of parser functions. Now Parser also encloses a NDB map_async callback to pass additional arguments to the callback.
Class P has an instance for every mapped doc entity, which uses the single Parser instance to parse a doc.
class P (object):

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

    def get_content(...)
        ....             # using methods from P and self.parser

    def other methods ...
        ....             # using methods from P and self.parser

class Parser(object):

    def __init__(args)
        ....

    def some parser methods()
        ....

    def callback(entity):   # Is now a method of Parser, but ....

        p = P(self, ...)
        ....
        content = p.get_content(...)
        ....

parser = Parser(...)   # initialize Parser (instance, closure)
query = Docs.query()
multi_future = query.map_async(parser.callback)
....    # process results

This works fine, but does not feel well structured.
I look for a solution where P inherits from Parser:
(The callback can / should be part of P)
query = Docs.query()
multi_future = query.map_async(????? P ??????)
....    # process results

A: I figured it out, using a lambda.
query = Docs.query()
multi_future = query.map_async(lambda entity: P(...).callback(entity))


text:
Q: How can I trigger a Meteor template to update manually even if the dependencies didn't change? The reason I'm asking is because I'm evaling a compiled different version of the template at runtime and want to re-execute it and update all instances of it already rendered to the dom.
I imagine something like Templates.some_name.changed() which I can call that would do that.
Any ideas?

A: The problem would be getting the template instance object outside that template's helper functions, which may be possible using private methods, but I'm not sure how off the top of my head.
However, you can just make a new dependency for this specific purpose.
some_nameDep = new Deps.Dependency();

In one of your Templates.some_name.helpers functions add (before the function returns):
some_nameDep.depend();

If it doesn't have any helpers, add one that includes that line but returns nothing and make sure you call the helper within the spacebars template itself.
Then you can re-execute all some_name instances with:
some_nameDep.changed();


text:
Q: Random variable and total variation distance Suppose X, Y are random variables from probability measures F(x), G(y) respectively. The total variation distance of F and G is bounded by a constant c. Is there a way to quantify the distance between X and Y in terms of c?
The expression of this problem may not be accurate since I don't know what the answer looks like.


text:
Q: Fitting a linear mixed effects model on longitudinal data with lme4: handling missing values and dates I'm still pretty new to linear mixed models, so any help is highly appreciated.
In my experiment, a test group (gets the intervention) and a control group (does not get the intervention) are observed over time. There are five measurement points (one might think of them as "waves of measurement") for each participant. Within a given measurement point the date one participant fills out her questionnaire might differ from the date for a another participant (i.e. one particpant fills out her questionnaire for measurement point #4 on 2019-02-01 while another particpant fills out her questionnaire for measurement point #4 on 2019-02-20).
I'm interested in the effect of the intervention and the effect of time on some outcome variable.
Based on the things I've read so far, I assume a "naive model" (random slope only, no interaction between fixed effects) in lme4 might look like this:
outcome ~ group + measurement_point + (1|subject)
Now, I've some general questions on this:

*

*Is the naive model above reasonable?

*What is the best way to model the measurement points (i.e., as individual dates on which participants filled out the questionnaire or as a factor variable representing the number of "waves", e.g. going from 1 to 5)?

*Should I care about missing data assuming that it is missing at random? I have up to 19% of missing values for some measurement points. What's the best way to handle this?

Edit: Here's a plot of the data. There is probably no effects of group or time just based on this visual exploration, but I still want to fit a model that examines it. :)

A: A couple of points:

*

*The fixed-effects part of the model specifies the mean structure. Based on the design of your study and your research question, you would probably want to assume that there is a difference in the average longitudinal evolutions between the two groups. To achieve this you would need to include the interaction term between your follow-up time variable and the intervention, and test for this interaction term.

*The longitudinal evolutions in the two groups may be nonlinear. You could at least test for that by including polynomials or splines.

*The random-effects part of the model accounts for the correlation in the repeated measurements of each participant. The random intercepts models you have posted above assumes that the correlations over time remains constant. Most often this is not a reasonable assumption. Including both random intercepts and random slopes can give you more flexibility, and postulates that the correlations decrease with the time lag between measurements. You could test for that using a likelihood ratio test.

*When the mean and variance-covariance structure of the mixed model are correctly/flexibly specified, and your missing data are missing at random, then the mixed model will provide you with valid inferences without having to do anything about these missing data.

You may find more information regarding all these issues in my course notes.


text:
Q: How to build an Rc or Rc<[T]>? I'd like to create an Rc<str> because I want reduce the indirection from following the 2 pointers that accessing an Rc<String> requires. I need to use an Rc because I truly have shared ownership. I detail in another question more specific issues I have around my string type.
Rc has a ?Sized bound:
pub struct Rc<T: ?Sized> { /* fields omitted */ }

I've also heard that Rust 1.2 will come with proper support for storing unsized types in an Rc, but I'm unsure how this differs from 1.1.
Taking the str case as example, my naive attempt (also this for building from a String) fails with:
use std::rc::Rc;

fn main() {
    let a: &str = "test";
    let b: Rc<str> = Rc::new(*a);
    println!("{}", b);
}

error[E0277]: the trait bound `str: std::marker::Sized` is not satisfied
 --> src/main.rs:5:22
  |
5 |     let b: Rc<str> = Rc::new(*a);
  |                      ^^^^^^^ `str` does not have a constant size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `str`
  = note: required by `<std::rc::Rc<T>>::new`

It's clear that in order to create an Rc<str>, I need to copy the whole string: RcBox would be itself an unsized type, storing the string itself alongside the weak and strong pointers — the naive code above doesn't even make sense.
I've been told that one can not instantiate such type, but instead instantiate an Rc<T> with a sized T and then coerce it to an unsized type. The example given is for the storing a trait object: first create Rc<ConcreteType> and then coerce to Rc<Trait>. But this doesn't make sense either: neither this nor this work (and you can't coerce from &str or String to str anyway).

A: As of Rust 1.21.0 and as mandated by RFC 1845, creating an Rc<str> or Arc<str> is now possible:
use std::rc::Rc;
use std::sync::Arc;

fn main() {
    let a: &str = "hello world";
    let b: Rc<str> = Rc::from(a);
    println!("{}", b);

    // or equivalently:
    let b: Rc<str> = a.into();
    println!("{}", b);

    // we can also do this for Arc,
    let a: &str = "hello world";
    let b: Arc<str> = Arc::from(a);
    println!("{}", b);
}

(Playground)
See <Rc as From<&str>> and <Arc as From<&str>>.

A: Creating an Rc<[T]> can be done via coercions and as-casts from fixed sized arrays, e.g. coercions can be done as follows:
use std::rc::Rc;

fn main() {
    let x: Rc<[i32; 4]> = Rc::new([1, 2, 3, 4]);

    let y: Rc<[i32]> = x;

    println!("{:?}", y);
}

However, this doesn't work for strings, since they have no raw fixed-sized equivalent to create the first value. It is possible to do unsafely, e.g. by creating a UTF-8 encoded Rc<[u8]> and transmuting that to Rc<str>. Theoretically there could be a crate on crates.io for it, but I can't find one at the moment.
An alternative is owning_ref, which isn't quite std::rc::Rc itself, but should allow, for example, getting an RcRef<..., str> pointing into an Rc<String>. (This approach will work best if one uses RcRef uniformly in place of Rc, except for construction.)
extern crate owning_ref;
use owning_ref::RcRef;
use std::rc::Rc;

fn main() {
    let some_string = "foo".to_owned();

    let val: RcRef<String> = RcRef::new(Rc::new(some_string));

    let borrowed: RcRef<String, str> = val.map(|s| &**s);

    let erased: RcRef<owning_ref::Erased, str> = borrowed.erase_owner();
}

The erasing means that RcRef<..., str>s can come from multiple different sources, e.g. a RcRef<Erased, str> can come from a string literal too.
NB. at the time of writing, the erasure with RcRef requires a nightly compiler, and depending on owning_ref with the nightly feature:
[dependencies]
owning_ref = { version = "0.1", features = ["nightly"] }


text:
Q: Where does UiPath CE install to? Where does UiPath CE (Community Edition) install to? The installer doesn't create a Start menu or desktop shortcut.
So far I've looked in:

*

*C:\Program Files

*C:\Program Files (x86)

A: It installs to %localappdata%:
%localappdata%\UiPath

Here's how the UiPath CE installer works as of April 2019 (version 19.4.2.0):

*

*Doesn't create shortcuts

*Silently extracts

*Silently overwrites files (including settings)

*Silently launches UiPath

Again, the installer silently overwrites your settings if UiPath is already installed, so avoid rerunning it after installation.


text:
Q: Xcode 4.4: Reloading docset Without Restarting Windows It seems the script presented at Reloading docset without restarting Xcode no longer works with the latest release 4.4.1 of Xcode.
tell application "Xcode"
    load documentation set with path
        "~/Library/Developer/Shared/Documentation/DocSets/myDocSet.docset"
end tell

Quitting and then relaunching Xcode are required.
Any idea on how to update the script to avoid quitting and relaunching?

A: With Xcode version 4.5.1 (4G1004), the reload is done automatically.
So, no script needed :)
Here is what I use to generate the documentation, maybe it can help you:
appledoc --project-name "MyProjectName" --project-company "Awesome Company" --no-repeat-first-par --output docset_folder --ignore .m .


text:
Q: Appending list but got "AttributeError: 'NoneType' object has no attribute 'append'" Python 2.7 I keep having this error on my code, which says:
"AttributeError: 'NoneType' object has no attribute 'append'"
But there is interesting fact, it only occurs when "n" is odd.
Here is the piece of code I'm using:
Note: I'm using Python 2.7.18
def sol(n, df):
    if n == 1:
        result = df
    elif n == 2 or n == 0:
        df.append(1)
        result = df
    elif n % 2 == 0:
        df.append(n/2)
        df = sol(n/2, df)
    else:
        df_2 = df[:]
        df_2 = df_2.append(n-1)
        n_2 = n-1
        df_2 = sol(n_2, df_2)

    return df

df = []
n = input('n == ')
sol(n, df)

The error is as follow:
n == 3
Traceback (most recent call last):
  File "Challenge_3_1_vTest.py", line 27, in <module>
    solution(n)
  File "Challenge_3_1_vTest.py", line 6, in solution
    print((sol(n, df)))
  File "Challenge_3_1_vTest.py", line 21, in sol
    df_2 = sol(n_2, df_2)
  File "Challenge_3_1_vTest.py", line 12, in sol
    df.append(1)
AttributeError: 'NoneType' object has no attribute 'append'

A: The append function doesn't return a thing, that's why I was having the error and was passing a none when using number that are not power of 2.
 df_2 = df_2.append(n-1)
This line of code was the source of the problem, I should have done:
df_2.append(n-1)


text:
Q: How frequently do "Tag stats" pages get updated? I believe the Tag Stats are not updated immediately when an answer is first upvoted. They seem to be updated every few hours. So my question is: What is the "frequency of updation" of Tag Stats?

A: This is by-design, this page is heavily cached.
At the moment there is about a 15 minute cache interval (depending on the tag), in future I am looking at only updating that page daily (when that happens I will make sure some text in the page explains that)
It runs some very expensive queries so we need caching.

A: The change that waffles mentioned in his answer has taken place. The bottom of the tag stats pages now include this statement:

Only non community-wiki questions and answers are included in these totals (updated daily)


text:
Q: Notation: Vector with two subscripts Suppose I have a vector with four elements:
$\mathbf{X} = [v_1, v_2, v_3, v_4]$
Now I want to add a time component to denote 12 separate vectors for each month in a single year.
For example:
$\mathbf{X_t} = [v_{1t}, v_{2t}, v_{3t}, v_{4t}]$
But I know this is not correct but not sure how to correct the notation.
What is an appropriate way to accomplish this notation?
Here is a simple matrix algebra example:
Edit:
Matrix Algebra example:
I'm trying to clean up this notation so it includes a time component.
$\mathbf{SP_{t}} = \begin{bmatrix} \mathcal{A}_{11} & \mathcal{A}_{12} & \mathcal{A}_{13} & \mathcal{A}_{14} \\ \mathcal{A}_{21} & \mathcal{A}_{22} & \mathcal{A}_{23} & \mathcal{A}_{24} \\ \mathcal{A}_{31} & \mathcal{A}_{32} & \mathcal{A}_{33} & \mathcal{A}_{34} \\ \mathcal{A}_{41} & \mathcal{A}_{42} & \mathcal{A}_{43} & \mathcal{A}_{44}  \end{bmatrix}$
$\mathbf{X_t} = [v_{1t}, v_{2t}, v_{3t}, v_{4t}]$
$\mathbf{Y_t} = \mathbf{X_t} \cdot \mathbf{SP_t} $
$\mathbf{Y_1} = \mathbf{X_1} \cdot \mathbf{SP_1}$

A: Consider adding a subscript to the left hand side as well, $$\mathbf{X}_t = [v_{1t}, v_{2t}, v_{3t}, v_{4t}]$$
To indicate that $SP_t$ indeed depends on time. Perhaps replace $\mathcal{A}_{ij}$ with $\mathcal{A}_{ijt}$.


text:
Q: How can I construct a matrix by programming in mathematica? I want to write a matrix in Mathematica by programming. How can I write it?
The matrix is :
$
M=
  \begin{bmatrix}
    0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
    0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0
  \end{bmatrix}
$
Considering $p$- Number of rows
and $2n+1$- Number of columns
I wrote the following program which is added.
But this code is not working.
I can form a matrix by matrix tool option. but it is 1000 entries or more that will a problem.

A: p = 2; n = 5;
mat = ConstantArray[0, {p, 2 n + 1}];
mat[[1, Floor[n/2 + 1]]] = 1;
mat // MatrixForm // TeXForm

$\left(
\begin{array}{ccccccccccc}
 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
\end{array}
\right)$

A: How about this
yourMatrix[p_, n_] := SparseArray[{1, Floor[n/2 + 1]} -> 1, {p, 2 n + 1}]

yourMatrix[2, 5] // MatrixForm


text:
Q: List not recognising for Plotly I'm trying to run a simple bar chart on plotly with a one dimensional list taken  from Excel. The file prints ok (myList  = ['45,21,45,54,87,34,52,78,9,79']) and I'm assuming that I split it into a list of strings. I want to now change them into int so that Plotly can recognise to chart as its only plotting as one big bar now (I'm guessing the string all together?)
    import plotly.graph_objects as go

    file = open("myFile.csv", "r") *

    myData= file.read()
    myList = myData.split("\n")
    print(myList)

    newList = []

    for element in myList:
        newList.append(int(element))

    print(newList)

    y = newList

    fig = go.Figure([go.Bar(y=y)])
    fig.update_layout(title_text='This is my bar chart displaying my figures')
    fig.show()

A: A) Why do you put this in brackets? y = (myList)
B) Isn't it because here: fig = go.Figure([go.Bar(y=y)]) you use your old list with strings instead of using newlist?
This solves your error:
mylist = "".join(mylist)
mylist = mylist.split(",")

It can be done in 1 line.


text:
Q: Algorithm to keep collection sorted while inserting in the middle Let's say I have a large collection of elements.
Each element has a "position" field, which is a positive integer.
No two elements have the same value for the field "position".
The only supported operation of the collection is: addElement(newElement, positionAfterElement), where:
 - newElement is the new element to be added (its position is unknown for now)
 - positionAfterElement is an existing element of the collection.
The function will guarantee that:
 - position(positionAfterElement) < position(newElement)
 - no other element in the collection has a position between position(positionAfterElement) and position(newElement)
I can change the value of all the element positions as I wish but I want to minimize the number of changes (on average).
How should I implement the addElement function?
I could just push all the elements with higher positions by 1 but I am pretty sure there must be a better way to do this.
Thanks all for your help.

A: Use a balanced tree.  At every node of the tree, keep a count of the number of items below it (left.count + right.count + 1).  Then, you can compute the index of an item easily while traversing to it.  This is O(n log n) time in the number of operations.

A: Here's a basic idea:
expected_number_of_elements = 10^6
spread_factor = 100
first element gets position = spread_factor * expected_number_of_element
each following element inserted:
    if its inserted in last position, give it the last element's position + spread_factor
    if its inserted in the first position, give it the first element's position - spread_factor
    otherwise, put it in the middle between its 2 closest neighbors
    if you don't have any space left: expand_the_array

expand_the_array:
    spread_factor = spread_factor * 10
    iterate over all the elements, and multiply position by 10.

expanding the array is an expensive operation, but since it multiplies the size of the array, on average (assuming your input is random, and not crafted by an adversary) you'll have to do this operation very rarely.
the major drawback of this solution, is that you'll have to watch out for int overflow....

A: OK, so here is what I implemented, in pseudo-code:
addElement(newElement, positionAfterElement):
    p0 <- positionOf(positionAfterElement)
    c <- 5
    finished <- false
    while (not finished):
        search for all elements which positions are in the range [p0 + 1, p0 + c]
        if there are less than c elements in that range:  // the range is not full
            adjust position of elements in the range, and position of newElement,
            so that
              - elements are correctly ordered
              - element positions are "evenly spread out" within the range
            finished <- true
        else:                                             // the range is full
            c <- c * 2
    end while
end addElement


text:
Q: D3 + Leaflet with Albers USA Projection I'd like to use D3 + Leaflet with the Albers USA projection.
I used Mike Bostock's D3 + Leaflet demonstration as a starting point (found here: http://bost.ocks.org/mike/leaflet/). I'm not sure how to properly use the Albers USA projection. I've encountered a couple problems while trying to figure out how to do this:

*

*I'm not sure how to make Leaflet use the Albers USA projection. I think I might be able to do it using the Proj4Leaflet plugin, but I've been unable to find the parameters that I need to pass to it when creating the CRS that specify Albers USA. I've found some potential configuration strings on spatialreference.org, but I don't know what to specify for origin or resolutions and haven't found anything out there that explains it.

*D3's Albers USA projection is returning null for some points in the collection and for the bounds. I'm using the us-states.json file that Mike Bostock used. I found the explanation for that here: https://github.com/mbostock/d3/issues/1287. "[...]it will now return null for points outside the composite projection's clip extent, since such points would not be displayed when using the projection stream". I'm not sure how to proceed from here. Should I be using a different data set?

If anyone has any advice on how to proceed, I'd greatly appreciate it!

A: You may have two separate questions, so here are brief answers to both -
1.) Your source data doesn't need to be in Albers-US (which isn't strictly speaking a projection anyway - AK and HI aren't in Mexico) in order to bring it into Leaflet. Here's the US States dataset as GeoJSON, in geographic coordinates: https://gist.github.com/wboykinm/6979292
2.) Whatever the projection of the source data, Leaflet only renders in the Google Mercator projection (The projection you see in the example you started from). If you absolutely must have Albers US, it shouldn't really be a pan-able/zoomable map for reasons of context distortion. Just use Mike's D3 example for a static map: http://bl.ocks.org/mbostock/6320825
If you're determined to make a slippy map for Leaflet using Albers US, who am I to stop you? But that process would require a.) moving of feature geometry in a GIS program, and b.) fooling Tilemill into using the wrong projection as it creates tiles for you to use in Leaflet. Not a recommended course of action.
I would also be remiss if I didn't mention that you can always make your D3 graphic zoomable with d3.behavior.zoom()


text:
Q: Обновление изменённой с помощью ajax сессии Столкнулся с такой проблемой: в index.php передаю через ajax запрос данные в CreatingShoppingCart.php, где они записываются в сессию. Но на index.php эта сессия как была пустой, так и остаётся и чтобы она обновилась нужно перезапустить страницу, чего я хочу избежать.
index.php
<?php
session_start();
?>

    <?php
    $sql1 = "SELECT * FROM coffee ORDER BY id ASC";

        if($result = $conn->query($sql1))
        {
            foreach($result as $row)
            {
                ?>

                            <img src="<?php echo $row["LinkToThePicture"]; ?>" alt="">

<?php echo $row["Name"]; ?>

<?php echo $row["Price"];?>₽

                            <input type="submit" id="add-btn" name="add_to_cart" class="btn qwe" value="Добавить в карзину"/>
                            <input type="hidden" class="id" name="id" value="<?php echo $row["id"];?>"/>
                            <input type="hidden" class="linkToThePicture" name="linkToThePicture" value="<?php echo $row["LinkToThePicture"];?>"/>
                            <input type="hidden" class="name" name="name" value="<?php echo $row["Name"];?>"/>
                            <input type="hidden" class="price" name="price" value="<?php echo $row["Price"];?>"/>
                            <input type="hidden" class="quantity" name="quantity" value="1"/>

                <?php
            }
        }
    ?>

'тут просто вывод масива этой сессии приложил для наглядности'

    <?php
    if(count($_SESSION["shopping_cart"]) > 0)
    {
        $total = 0;
        foreach($_SESSION["shopping_cart"] as $key => $product)
        {
        ?>

                <a class="fas fa-times" href="index.php?action=delete&id=<?php echo $product["id"]; ?>">

                <a class="fas fa-plus" href="index.php?action=plus&id=<?php echo $product["id"]; ?>">

                <a class="fas fa-minus" href="index.php?action=minus&id=<?php echo $product["id"]; ?>">

                <img src="<?php echo $product["linkToThePicture"];?>" alt="">

<?php echo $product["name"];?>

<?php echo $product["price"];?>₽

<?php echo $product["quantity"];?>

        <?php
        $total = $total + ($product["quantity"]*$product["price"]);
        }
        ?>
<?php echo number_format($total, 2); ?>₽

        Оформить заказ<?php
        show();
    }
    else
    {
        ?>
Карзина пуста
<?php
        show();
    }
    ?>

CreatingShoppingCart.php
<?php

$id = $_POST["id"];
$name = $_POST["name"];
$price = $_POST["price"];
$quantity = $_POST["quantity"];
$linkToThePicture = $_POST["linkToThePicture"];

echo "$id $linkToThePicture $name $price $quantity
";

session_start();
$product_ids = array();

        if(isset($_SESSION['shopping_cart']))
        {
            $count = count($_SESSION['shopping_cart']);
            $product_ids = array_column($_SESSION['shopping_cart'], 'id');

            if (!in_array($_POST["id"],$product_ids))
            {
                $_SESSION['shopping_cart'][$count] = array
                (
                    'id' => $_POST["id"],
                    'name' => $_POST["name"],
                    'price' => $_POST["price"],
                    'quantity' => $_POST["quantity"],
                    'linkToThePicture' => $_POST["linkToThePicture"]
                );
            }

            else
            {
                for($i = 0; $i < count($product_ids); $i++)
                {
                    if ($product_ids[$i] == $id)
                    {
                        $_SESSION['shopping_cart'][$i]['quantity'] += $quantity;
                    }
                }
            }
        }
        else
        {
            $_SESSION['shopping_cart'][0] = array
            (
                'id' => $id,
                'name' => $name,
                'price' => $price,
                'quantity' => $quantity,
                'linkToThePicture' => $linkToThePicture
            );
        }
 ?>

A: В качестве быстрого решения предлагаю следующее:
перенесите код, который формирует корзину из index.php в файл CreatingShoppingCart.php. При загрузке страницы и при каждом изменении корзины обращайтесь к нему по аякс и полученный HTML вставляйте на страницу.
Хотя я бы сделал API, которое возвращает корзину в виде JSON, а для фронта задействовал фреймворк вроде VueJs.


text:
Q: Escape special characters in a Python string Does Python have a function that I can use to escape special characters in a string?
For example, I'm "stuck" :\ should become I\'m \"stuck\" :\\.

A: As it was mentioned above, the answer depends on your case. If you want to escape a string for a regular expression then you should use re.escape(). But if you want to escape a specific set of characters then use this lambda function:
>>> escape = lambda s, escapechar, specialchars: "".join(escapechar + c if c in specialchars or c == escapechar else c for c in s)
>>> s = raw_input()
I'm "stuck" :\
>>> print s
I'm "stuck" :\
>>> print escape(s, "\\", ['"'])
I'm \"stuck\" :\\

A: Use re.escape
>>> import re
>>> re.escape(r'\ a.*$')
'\\\\\\ a\\.\\*\\$'
>>> print(re.escape(r'\ a.*$'))
\\\ a\.\*\$
>>> re.escape('www.stackoverflow.com')
'www\\.stackoverflow\\.com'
>>> print(re.escape('www.stackoverflow.com'))
www\.stackoverflow\.com

Repeating it here:

re.escape(string)
Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

As of Python 3.7 re.escape() was changed to escape only characters which are meaningful to regex operations.

A: I'm surprised no one has mentioned using regular expressions via re.sub():
import re
print re.sub(r'([\"])',    r'\\\1', 'it\'s "this"')  # it's \"this\"
print re.sub(r"([\'])",    r'\\\1', 'it\'s "this"')  # it\'s "this"
print re.sub(r'([\" \'])', r'\\\1', 'it\'s "this"')  # it\'s\ \"this\"

Important things to note:

*

*In the search pattern, include \ as well as the character(s) you're looking for.
You're going to be using \ to escape your characters, so you need to escape
that as well.

*Put parentheses around the search pattern, e.g. ([\"]), so that the substitution
pattern can use the found character when it adds \ in front of it. (That's what
\1 does: uses the value of the first parenthesized group.)

*The r in front of r'([\"])' means it's a raw string. Raw strings use different
rules for escaping backslashes. To write ([\"]) as a plain string, you'd need to
double all the backslashes and write '([\\"])'. Raw strings are friendlier when
you're writing regular expressions.

*In the substitution pattern, you need to escape \ to distinguish it from a
backslash that precedes a substitution group, e.g. \1, hence r'\\\1'. To write
that as a plain string, you'd need '\\\\\\1' — and nobody wants that.

A: Use repr()[1:-1]. In this case, the double quotes don't need to be escaped. The [-1:1] slice is to remove the single quote from the beginning and the end.
>>> x = raw_input()
I'm "stuck" :\
>>> print x
I'm "stuck" :\
>>> print repr(x)[1:-1]
I\'m "stuck" :\\

Or maybe you just want to escape a phrase to paste into your program? If so, do this:
>>> raw_input()
I'm "stuck" :\
'I\'m "stuck" :\\'

A: If you only want to replace some characters you could use this:
import re

print re.sub(r'([\.\\\+\*\?\[\^\]\$\(\)\{\}\!\<\>\|\:\-])', r'\\\1', "example string.")

A:
Note: This answer was written in response to the original question which was written in a way that it asked for a generic "function which can [be used] to escape special characters", without specifying that these would be used for regular expressions, and without further specifying what special characters would have to be escaped.

In order to escape an arbitrary set of "special characters", you can write a custom function that replaces each of these characters with an escaped variant. Something like this:
def escapeSpecialCharacters ( text, characters ):
    for character in characters:
        text = text.replace( character, '\\' + character )
    return text

>>> escapeSpecialCharacters( 'I\'m "stuck" :\\', '\'"' )
'I\\\'m \\"stuck\\" :\\'
>>> print( _ )
I\'m \"stuck\" :\

A: use json:
import json
print(r"""(I'm "stuck" :\)""")               # (I'm "stuck" :\)
print(json.dumps(r"""(I'm "stuck" :\)"""))   # (I'm "stuck" :\)

for json to string with escape character
json.dumps(json.dumps(d))


text:
Q: PineScript "barssince" trouble I'm here asking for help because i'm in trouble with 'barssince' function. This function actually returns the bars count since the condition between () was met. My problem is that my condition is always true, it always have one value assigned to it so 'barssince' is always returning me "0" as result because condition is met in the current bar [0].
What I'm trying to do is to get the maximum/minimum RSI value in the last 80 days with the functions rsimax = highest(rsi14, 80) and rsimin = lowest(rsi14, 80) and after that i want to know how many bars away am I from the highest RSI value in the last 80 days.
EG: Maximum RSI in the last 80 days was 75 and it ocourred 12 days ago. I want the 'barrsince' function to return 12.
As i already said, the function rsimax always carry a value with it, because there always will be a maximum RSI value and the 'barssince' condition will always be true at bar [0].

//RSI Score
float rsiscore1 = 0
int spotmax = 0
int spotmin = 0
rsiscore1 := 0
spotmax := 0
spotmin := 0

rsimax = highest(rsi14, 80)
rsimax5 = highest(rsi14, 5)
rsimin = lowest(rsi14, 80)
rsimin5 = lowest(rsi14, 5)
spotmax := barssince (rsimax)
spotmin := barssince (rsimin)

Thanks!

A: The argument of the function barssince must be a condition, so the correct code is
spotmax := barssince(rsimax==rsi14)
spotmin := barssince(rsimin==rsi14)

It may be necessary to adjust the result depending on whether the extreme bars should be included in the calculation or not.

A: You might want to try:
spotmax = barssince(change(rsimax))
spotmin = barssince(change(rsimmin))


text:
Q: Folder from one branch, that's been added to my .gitignore, exists when I switch to a different branch I'm working on two branches: branch A and branch B. The contents of each branch are as follows:

**branch A**
  |-parent
    |-folder1
    |-folder2
**branch B**
  |-parent
    |-folder3
      |-some_folder
      |-some_other_stuff
      |-more_stuff

I have added "some_folder" to .gitignore. New files are created and added to "some_folder" while working on branch B, hence modifying it. Even though it's supposed to get ignored and git status doesn't list the folder at all (as it should), when I switch to branch A, folder3 is now listed when I execute ls along with "some_folder", but when I execute git status it says my working tree is clean. My working tree in branch A now looks like this:

|-parent
    |-folder1
    |-folder2
    |-folder3
      |-some_folder

Shouldn't folder3 and "some_folder" be contained in branch B and not carried over when switching to my other branch?

A: TL;DR
Git must leave folder3 and subdirectories therein behind if there are any files in them.  In general, it should remove them if not, but I've seen corner cases where empty directories get left behind for some reason.  I've never tracked down when: every time I test something to see if I found the problem, Git cleans up.
Long
Git cares little about folders.  Git cares about files.1  A file has a path name, such as dir1/dir2/file.ext.  The operating system cares about folders (directories) and hence, for file.ext to exist, Git must create dir1 and then dir1/dir2, if they do not exist yet.  Having created those directories, Git can now create file.ext within the second one—and that is all that Git cares about, on git checkout: that files that are in the commit being checked out be extracted into both Git's index,2 and the work-tree.
The work-tree is where you see files: they have their normal everyday form and you can work on them.  The copies in the index are the ones that Git is really concerned with, as Git will make any new commit that you make, from the copies in the index.  But the copies in the index are in the special, compressed, Git-only form that Git freezes into commits, so Git kindly extracts the files both to the index (where Git wants them) and to your work-tree.  It's the extract-to-work-tree step that creates directories (folders) if needed.
When you switch from commit a123456... (at the tip of BranchA) to commit b789abc... (at the tip of BranchB), Git will:

*

*remove from the index and work-tree any files that are only in a123456

*create in the index and work-tree any files that are only in b789abc

*replace in the index and work-tree any files that are different in b789abc than they are in a123456.

The remove and create steps sometimes allow Git to remove an empty directory, or require Git to create a new directory.  The replace steps generally do not involve directory manipulation.3
If you have files that Git is not storing in its index, these are untracked files.  They exist in the work-tree, but they are not in the index, so they are largely irrelevant to Git.  As long as switching from commit a123456 (at the tip of BranchA) to b789abc (at the tip of BranchB) does not require that Git do anything about these files—i.e., as long as they aren't in b789abc either—Git does nothing at all about these files.  Having done nothing about the files, Git does nothing about their containing directories either.

1This is either a little too weak, or a little too strong.  Git really cares about commits.  However, a commit contains files: a full and complete snapshot of every file, as of the state it had as of that commit.  More precisely, each commit contains the files it contains—but that's kind of obvious and useless.  Really, it contains the files that were in the index, when whoever made the commit, made the commit.  That's why the index (see footnote 2) is so important.
2The index is also sometimes called the staging area, or the cache, depending on who / which part of Git is doing the calling.  The index starts out with a copy of each file from the current commit, ready to go into the next commit.  Using git add copies new files, or new versions of existing files, into the index, making them ready to commit.  Hence, the best short description of the index is this: The index is the set of files that will go into the next commit.  This does not capture all of the little fiddly details—especially, how the index works during merges—but covers the most important part.
3There's a rare case where you have, for some reason, wiped out a bunch of work-tree files that are in the index from a123456, and you've taken away their work-tree directory too.  In this case Git will just re-create the directory so as to satisfy the OS's compulsion to have a directory to hold the file(s).  Git doesn't need, or care about, the directory—Git only needs the file in the index—but you probably want the file, so Git makes the directory if necessary, just as it does for files that weren't in a123456.


text:
Q: How to use the Aggregate Hadoop package to find the minimum value across all keys? I am using Hadoop through Cloudera.
 I need to find the minimum value and the key, across few text files
The text files (*.txt) are of this format containing key value pairs:
A  1
B  2
C  3

The output should be :
A   1

But I am getting:
A  1
B  2
C  3

as the code is giving the minimum value based on the keys 'A', 'B' and 'C' respectively. Is there a way to use the aggregate package to be able to get the output as the minimum value is:
A   1

This is the mapper.py.
import sys

def generateLongMinToken(word,value):
    return "LongValueMin:" + word + "\t" + value

def main(argv):
   line = sys.stdin.readline()
   try:
        while line:
        word, value =  line.rstrip().split() # remove leading and trailing whitespace  # split the line into words
        print generateLongMinToken(word,value)
        line = sys.stdin.readline()
   except "end of file":
        return None

if __name__ == "__main__":
 main(sys.argv)

And this is the hadoop command :
 hadoop jar /usr/lib/hadoop-mapreduce/hadoop-streaming.jar \
-file mapper.py -mapper mapper.py \
-reducer aggregate \
-input /user/cloudera/gutenberg/min/* \
-output /user/cloudera/gutenberg/min_output


text:
Q: Reinstall broken recovery partition on High Sierra macOS High Sierra (10.13) is the main OS on my Mac and it boots without issue. However, the recovery partition is corrupted and I cannot boot to it without seeing an error. How do I reinstall the recovery partition without having to disrupt my working main OS?
The machine I'm using was upgraded from Mavericks.
Meta Note: While there are similar questions for previous MacOS versions, I think unique issues relating to the new APFS in High Sierra justify a new question.

A: Before doing anything related to partitions on your main Mac, it's best to perform a Time Machine backup.
After doing that, run the latest macOS High Sierra installer from the App Store. This should update macOS and restore the Recovery partition.


text:
Q: jQuery slideToggle for multiple divs What I am trying to do is have four links that each will display and hide a certain div when clicked. I am using slideToggle and I was able to get it to work with really sloppy and repetitive code. A friend of mine gave me a script he used and I tried it out and finally was able to get something to happen. However, all it does is hide the div and wont redisplay. Also it hides all the divs instead of just the specific one. Here is a jsfiddle I made. Hopefully you guys can understand what I am trying to do and help! Thanks alot.
Here is the script I'm using.
$(document).ready(function () {
$(".click_me").on('click', function () {
    var $faq = $(this).next(".hide_div");
    $faq.slideToggle();
    $(".hide_div").not($faq).slideUp();
});
});

http://jsfiddle.net/uo15brz1/

A: Here's a  link to a fiddle.  http://jsfiddle.net/uo15brz1/7/
I changed your markup a little, adding id attributes to your divs.  The jquery, gets the name attribute from the link that's clicked, adds a # to the front, hides the visible div, then toggles the respective div.  I also added e.preventDefault to stop the browser from navigating due to the hash change.  As an aside, javascript don't require the $ prefix.
$(document).ready(function () {
    $(".click_me").on('click', function (e) {
        e.preventDefault();
        var name = $(this).attr('name');
        var target = $("#" + name);
        if(target.is(':visible')){
            return false; //ignore the click if div is visible
        }
        target.insertBefore('.hide_div:eq(0)'); //put this item above other .hide_div elments, makes the animation prettier imo
        $('.hide_div').slideUp(); //hide all divs on link click
        target.slideDown(); // show the clicked one
    });
});

A: Welcome to Stack Overflow!
Here's a fiddle:
http://jsfiddle.net/uo15brz1/2/
Basically, you need a way to point to the relevant content <div> based on the link that's clicked. It would be tricky to do that in a robust way with your current markup, so I've edited it. The examples in the jquery documentation are pretty good. Spend some time studying them, they are a great way to start out.


text:
Q: Terminology for set systems: "trace" or "projection"? Although the following question is not in itself mathematical, it is the expertise/breadth of the research community in mathematics that I wish to appeal to, beyond the filtered/trained search results I'd just get from Googling.

Let $\Omega$ be a non-empty set and ${\mathcal F}$ a non-empty subset of the powerset ${\mathcal P}(\Omega)$. In some work with coauthors we found ourselves frequently needing the following construction: take some $\Gamma\subseteq\Omega$ and form the new set
$$
{\mathcal F} \wedge \Gamma := \{ X \cap \Gamma \colon X \in {\mathcal F} \} \subseteq {\mathcal P}(\Gamma).
$$
Actually, we then need to take subsets of ${\mathcal F}\wedge \Gamma$; and then iterate this process.
The terminology we are using in the current draft is to call ${\mathcal F}\wedge \Gamma$ the projection of ${\mathcal F}$ onto $\Gamma$, since this seems like the intuitive picture/metaphor. On the other hand, while browsing Bollobas's Combinatorics earlier this year, I noticed that in the setting where $\Omega$ is finite, various people (Frankl, Bollobas himself, presumably others) have called ${\mathcal F}\wedge \Gamma$ the trace of ${\mathcal F}$ on $\Gamma$.

Question.  Is the terminology used in Bollobas's book now the standard one? If so, have people seen the notion of "subtrace" before?

For sake of comparison, I don't think anyone would refer to a graph minor as anything but a "graph minor", this is now completely standard as far as I can tell. So my question is really about whether traces and subtraces are just as standard, or whether this is a convenient bit of terminology popular within a particular cluster of researchers. I don't think this is an overly subjective question; I am hoping for combinatorists or lattice theorists to weigh in here with references or informed personal observation.

Another question (less important, more subjective): which is preferable, "subprojection" or "subtrace" ?


text:
Q: How can i add a infowindow on markers loaded form a XML file Can someone tell me how i can add a info window on markers loaded from a Xml file.
This is the code I'm using to load the markers.
google.load("maps", "3",  {other_params:"sensor=false"});
google.load("jquery", "1.3.2");

function initialize() {
    var myLatlng = new google.maps.LatLng(52.132633, 5.2912659999999505);
    var myOptions = {
        zoom: 8,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    jQuery.get("locaties.xml", {}, function(data) {
        jQuery(data).find("marker").each(function() {
            var marker = jQuery(this);
            var latlng = new google.maps.LatLng(
                parseFloat(marker.attr("lat")),
                parseFloat(marker.attr("lng"))
            );
            var marker = new google.maps.Marker({position: latlng, map: map});
        });
    });
}
function loadScript() {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
    document.body.appendChild(script);
}

window.onload = loadScript;

google.setOnLoadCallback(initialize);

this is the XML file;
<markers>
<marker lat="52.08920341101735" lng="4.279875700000048" />
<marker lat="52.083408210994186" lng="4.314160399999992"/>
<marker lat="52.08598371100446" lng="4.301652100000069"/>
</markers>

A: After you create the marker, all you need to do is to assign the infowindow:
jQuery.get("locaties.xml", {}, function(data) {
    jQuery(data).find("marker").each(function() {
        var markerXML = jQuery(this);
        var latlng = new google.maps.LatLng(
            parseFloat(markerXML.attr("lat")),
            parseFloat(markerXML.attr("lng"))
        );
        var marker = new google.maps.Marker({position: latlng, map: map});

        // now that the marker is placed, assign event listener on the marker
        // and create/assign infowindow to the event trigger.
        markerInfoWindow(marker, markerXML.attr("info"));
    });
});

// ..... other code here .....

// the marker event handler onclick and infowindow creation/assignment
function markerInfoWindow(marker, information){
    google.maps.event.addListener(marker, 'click', function(){
        var infowindow = new google.maps.InfoWindow({
            content: information
        });
        infowindow.open(map, marker);
    });
}


text:
Q: margin-bottom not working? I am having trouble for some reason with getting the bottom of my page to have some padding. I have a content box that goes to the end of the page and hits the bottom and doesn't look the greatest. I want to give some space from the bottom of the page to fix this issue, but it seems that margin-bottom isn't working as I expect it to? I have included the following code which should be everything that affects the content box. I have tried removing the margin:0 in the html/body (even though I kind of need that), but that doesn't seem to work either? I feel like I am missing something really obvious.
html, body {
margin:0;
padding:0;
width:100%;
height:100%;
text-align:left;}

#content {
position: absolute;
left: 50%;
margin-left: -368px;
top: 104px;
padding-left: 35px;
padding-right: 35px;
padding-top: 15px;
padding-bottom: 15px;
background-color: white;
border: 1px solid black;
width: 664px;
margin-bottom: 20px;}

Any help would be greatly appreciated :) Thanks!
Live link - http://quintinmarcus.com/portfolio/

A: Since content has position: absolute, its after margins do nothing, nor should it stretch the inner height of the body so that the body's padding-bottom does anything.

A: If you want to centre your layout, modify your current style for #content to the following:
CSS:
#content {
width:664px;
margin:104 auto 20px auto;
padding: 15px 35px;
background-color: white;
border: 1px solid black;
}

This will also enable you to give the margin at the bottom you want.


text:
Q: Time relative to pressure? We all know the effects of speed on time, and we have a formula for that, but I have a hunch, that time also is relative to pressure, and that by increasing the pressure on matter, in fact time will speed up for that matter.
I am not a physics expert ( I have a Masters Degree in Computer Engineering, and have hence taken several physics, math and chemistry classes ) so don't slaughter me, I would appreciate a talkative tone.
So I will say some "ideas" in my head that might be stupid, or assumptions from my understanding of how things are that are in fact wrong from an expert view, but please try to understand my intention or follow my idea of what I am thinking instead of focusing on details.
So, my thinking is that once something starts travelling near the speed of light, or the speed of light, it will start to dissolve, before turning into energy and becoming the lightest of all while dissolving = light, and hence is why it can travel at the speed of light. So if something is to travel at the speed of light, it actually have to be dissolved into energy.
The idea I have with pressure, is that if matter, in a pressure chamber, where pressure is turned up, the matter will eventually turn into pure energy as well = light.
I also have this thought, that once pressure is applied to matter, the atoms starts to vibrate, move faster, and a reaction that would normally take hundreds of years, can be achieved with quicker results in a pressure chamber because time for all that materia increases, not because of the pressure, but because time is happening faster, which supports my idea of time actually speeding up for those particles.
What happens with used reactor fuel in a pressure chamber today? How much can we speed up the halftime?
It appears to me that if this was true, it will be the contradiction to speed. A twin X travelling near the speed of light, will come back to visit an older twin Y on earth.
However, with pressure, it might just be the opposite, that twin X in the pressure chamber will in fact be older than twin Y outside.
Surely turning up pressure on a twin might not be so healthy, but neither is acceleration from 0 to the speed of light in 1s. So pressure is probably not a healthy way to speed up time for matter, it will probably destroy certain things in it.
Am I on something here? No?

A: Your idea about massive objects turning into energy as they approach the speed of light is unfounded. I know of nothing in physics that offers any way for this to happen. In the LHC we have accelerated massive particles to a hairs breadth away from the speed of light and they remain the same massive particles that they were in the lab rest frame.
However, although your going in point is entirely wrong you are actually correct that pressure can cause time to slow down - just not in the way you think. Pressure can act as a source of gravity. Although we usually think of mass being the source of gravity, in General Relativity the source is the stress-energy tensor. In most cases the stress-energy tensor is dominated by mass, but it does include pressure, and pressure does act as a source of gravity. Increasing the pressure will therefore decrease (make more negative) the gravitational potential energy and this will cause gravitational time dilation compared to an observer far from the gravitational field.
However the effect of pressure is entirely negligable except possible in extreme cases such as the interior of neutron stars. The effect of pressure on radioactive decay is immeasurably small for any pressures we could generate, which is a shame really as otherwise it would be a nice way to get rid of radioactive waste.


text:
Q: Emailing multiple people from a config file I'm writing a program which emails multiple people and it takes the addresses from a config file. The problem is that every time it runs it only takes to first address and sends it to that one. By the way this is using the configparser modual in python.
heres my code:
reporter_email = '%s' %config.get("email", "reporter_email")
notification_emails = ['%s' %(config.get("email", "notification_emails"))]
to = '%s' %config.get("email", "to")
subject = '%s' %config.get("email", "subject")
body = ('''%s\n
%s
%s''' %(config.get("email", "intro_body"), str(fileNames), config.get("email", "con_body")))

to = "To: %s\n" %(to)
subject = "Subject: %s\n\n" %(subject)

smtpObj = smtplib.SMTP('%s' %config.get("email", "portal"), 25)
smtpObj.sendmail(reporter_email, notification_emails, to + subject + body)
smtpObj.quit()

A: the problem is here:
notification_emails = ['%s' %(config.get("email", "notification_emails"))]

this builds the list of destination emails, but after executing this line, notification_emails contains a single item. you have to use some sort of loop (or list comprehension) to insert multiple items in this list.
what is the content of your config file ? how can you extract multiple values from the notification_emails entry ?
(printing the content of variables of interrest during the execution of the script allows to see what they contains, and is a good starting poitn when debugging)

A: take address and Throw into list or dict,
after that use "for loop" and send emails
other way: use bcc

A: i used a list w/o a for loop.
[Mail Recipients]
p1 = user1@email.com
p2 = user2@email.com
# users defined in config file

p1 = config.get('Mail Recipients', 'p1')
p2 = config.get('Mail Recipients', 'p2')
# pulling users into my script

sendTo = [p1,p2]

now you can use smtp function/method and plug in the 'sendTo' variable in the 'to:' portion of sendmail code and it should work.


text:
Q: How to specify driver class path when using pyspark within a jupyter notebook? I want to query a PostgreSQL with pyspark within a jupyter notebook. I have browsed a lot of questions on StackOverflow but none of them worked for me, mainly because the answers seemed outdated. Here's my minimal code:
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
url = 'jdbc:postgresql://host/dbname'
properties = {'user': 'username', 'password': 'pwd'}
df = spark.read.jdbc(url=url, table='tablename', properties=properties)

Running this from a notebook would raise the following error:
Py4JJavaError: An error occurred while calling o69.jdbc.
: java.sql.SQLException: No suitable driver
at java.sql.DriverManager.getDriver(DriverManager.java:315)
at org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions$$anonfun$7.apply(JDBCOptions.scala:85)
at org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions$$anonfun$7.apply(JDBCOptions.scala:85)
at scala.Option.getOrElse(Option.scala:121)...

The principal tips I have found were summed up in the link below but unfortunately I can't get them to work in my notebook:
Pyspark connection to Postgres database in ipython notebook
Note: I am using Spark 2.3.1 and Python 3.6.3 and I am able to connect to the database from the pyspark shell if I specify the jar location.
pyspark --driver-class-path /home/.../postgresql.jar --jars /home/.../jars/postgresql.jar

Thanks to anyone who can help me on this one.
EDIT
The answers from How to load jar dependenices in IPython Notebook are already listed in the link I shared myself, and do not work for me. I already tried to configure the environment variable from the notebook:
import os
os.environ['PYSPARK_SUBMIT_ARGS'] = '--driver-class-path /path/to/postgresql.jar --jars /path/to/postgresql.jar'

There's nothing wrong with the file path or the file itself since it works fine when I specify it and run the pyspark-shell.

A: Using the config method worked for me:
from pyspark.sql import SparkSession
spark = SparkSession.builder.config('spark.driver.extraClassPath', '/path/to/postgresql.jar').getOrCreate()
url = 'jdbc:postgresql://host/dbname'
properties = {'user': 'username', 'password': 'pwd'}
df = spark.read.jdbc(url=url, table='tablename', properties=properties)