text:
Q: Jenkins pipelineJob DSL not interpreting variables in pipeline script I'm trying to generate Jenkins pipelines using the pipelineJob function in the jobDSL pluging, but cannot pass parameters from the DSL to the pipeline script. I have several projects that use what is essentially the same Jenkinsfile, with differences only in a few steps. I'm trying to use the JobDSL plugin to generate these pipelines on the fly, with the values I want changed in them interpreted to match the parameters to the DSL.
I've tried just about every combination of string interpretation that I can in the pipeline script, as well as in the DSL, but cannot get Jenkins/groovy to interpret variables in the pipeline script.
I'm calling the job DSL in a pipeline step:
def projectName = "myProject"
def envs = ['DEV','QA','UAT']
def repositoryURL = 'myrepo.com'

jobDsl targets: ['jobs/*.groovy'].join('\n'),
    additionalParameters: [
        project: projectName,
        environments: envs,
        repository: repositoryURL
    ],
    removedJobAction: 'DELETE',
    removedViewAction: 'DELETE'

The DSL is as follows:
pipelineJob("${project} pipeline") {
    displayName('Pipeline')
        definition {
            cps {
                script(readFileFromWorkspace(pipeline.groovy))
            }
        }
    }

pipeline.groovy:
pipeline {
    agent any

    environment {
        REPO = repository
    }

    parameters {
        choice name: "ENVIRONMENT", choices: environments
    }

    stages {
        stage('Deploy') {
            steps {
                echo "Deploying ${env.REPO} to ${params.ENVIRONMENT}..."
            }
        }
    }
}

The variables that I pass in additionalParameters are interpreted in the jobDSL script; a pipeline with the correct name does get generated. The problem is that the variables are not passed to the pipeline script read from the workspace - the Jenkins configuration for the generated pipeline looks exactly the same as the file, without any interpretation on the variables.
I've made a number of attempts at getting the string to interpret, including a lot of variations of "${environments}", ${environments}, $environments, \$environments...I can't find any that work. I've also tried reading the file as a gstringImpl:
script("${readFileFromWorkspace(pipeline.groovy)}")

Does anyone have any ideas as to how I can make variables propagate down to the pipeline script? I know that I could just use a for loop to do string.replaceAll() on the script text, but that seems cumbersome; there's got to be a better way.

A: I've come up with a way to make this work. It's not what I'd prefer, which is having the string contents of the file implicitly interpreted during job creation, but it does work; it just adds an extra step.
import groovy.text.SimpleTemplateEngine

def fileContents = readFileFromWorkspace "pipeline.groovy"

def engine = new SimpleTemplateEngine()
template = engine.createTemplate(fileContents).make(binding.getVariables()).toString()

pipelineJob("${project} pipeline") {
    displayName('Pipeline')
    definition {
        cps {
            script(template)
        }
    }
}

This reads a file from your workspace, then uses it as a template with the binding variables. The other changes needed to make this work are escaping any variables used in your Jenkinsfile script, like \${VARIABLE} so that they are expanded at runtime, not at the time you build the job. Any variables you want to be expanded at job creation should be referenced as ${VARIABLE}.

A: You could achieve what you're trying to do by defining environment variables in the pipelineJob and then using those variables in your pipeline.
They are a bit limited because environment variables are strings, but it should work for basic stuff
Ex.:
//job-dsl
pipelineJob('example') {
    environmentVariables {
        // these vars could be specified by parameters of this job
        env('repository', 'blah')
        env('environments', "a,b,c"]) //comma separated string
    }
    displayName('Pipeline')
        definition {
            cps {
                script(readFileFromWorkspace(pipeline.groovy))
            }
        }
    }
}

And then in the pipeline:
//pipeline.groovy
pipeline {
    agent any

    environment {
        REPO = env.repository
    }

    parameters {
        choice name: "ENVIRONMENT", choices: env.environments.split(',')
        //note the need to split the comma separated string above
    }
}

A: You need to use the complete job name as a variable without the quotes. E.g., if JOBNAME is a parameter containing the entire job name:
pipelineJob(JOBNAME) {
    displayName('Pipeline')
        definition {
            cps {
                script(readFileFromWorkspace(pipeline.groovy))
            }
        }
    }


text:
Q: Preserving sort order of .json file that gets created from api response I am having a problem with getting the correct sort order of a .json file that gets created from an api response using PyCharm Community Edition with python 3.7.
This is the api request:
import requests
import json

url = "https://pokemon-go1.p.rapidapi.com/pokemon_names.json"

headers = {
    'x-rapidapi-key': "c061ae2dffmshc2a33d10b00cee7p121f42jsn11f39d53dd1e",
    'x-rapidapi-host': "pokemon-go1.p.rapidapi.com"
    }

response = requests.request("GET", url, headers=headers)

If i now print(response.text), I get the following output: (That's how I want my .json file to look like later)
{
    "1": {
        "id": 1,
        "name": "Bulbasaur"
    },
    "2": {
        "id": 2,
        "name": "Ivysaur"
    },
    "3": {
        "id": 3,
        "name": "Venusaur"
    },
    "4": {
        "id": 4,
        "name": "Charmander"
    },
    "5": {
        "id": 5,
        "name": "Charmeleon"
    }
}

After that I write the response to the file "pokemondata.json" by doing this:
response_json = json.loads(response.text)

writeFile = open("pokemondata.json", "w")
writeFile.write(json.dumps(response_json, indent=4, sort_keys=True))
writeFile.close()

And then the file looks like this:
{
    "1": {
        "id": 1,
        "name": "Bulbasaur"
    },
    "10": {
        "id": 10,
        "name": "Caterpie"
    },
    "100": {
        "id": 100,
        "name": "Voltorb"
    },
    "101": {
        "id": 101,
        "name": "Electrode"
    },
    "102": {
        "id": 102,
        "name": "Exeggcute"
    }
}

I could not figure out how to get it done so that the file is sorted by ids (or the numbers before the id, e.g. "1") correctly. Could anybody please explain to me, how I can fix it?

A: import requests
import json

url = "https://pokemon-go1.p.rapidapi.com/pokemon_names.json"

headers = {
    'x-rapidapi-key': "c061ae2dffmshc2a33d10b00cee7p121f42jsn11f39d53dd1e",
    'x-rapidapi-host': "pokemon-go1.p.rapidapi.com"
    }

response = requests.request("GET", url, headers=headers)

response_json = response.json()

int_keys = {int(k):v for k,v in response_json.items()}

with open("sample.json", 'w') as file_obj:
    json.dump(int_keys, file_obj, indent=4, sort_keys=True)

Issue is with keys in your json which are in string format. Convert them to integers and save in the file

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I assemble a Laptop from parts Yesterday, I had the privilege of opening and upgrading the RAM of a P4 computer a relative had assembled from scratch. Thats when this weird thought occurred to me: Why can't I assemble a laptop in a manner similar to a standard desktop computer? What exactly stops the assembling of a laptop from scratch?
My search let me to this post which nicely explains that this is not possible due to lack of standards in the laptop world. For instance, there is the Atx standard which is universal for desktop motherboards. A poster proposes a hypothetical Ltx standard for laptops:

Let's break LTX down into a few sizes, for displays. your basic LTX
  case comes with a power supply, a display, and cords. the display size
  dictates the exact LTX size. so, a 14 inch display would be LTX-14.
  tentatively, lets start with -8, -14, -17, and -22.
LTX-14 motherboards would be required to fit into an LTX-17, but not
  the other way around for obvious reasons. if you wanted to (for
  whatever reason), you could put something together using standard
  components that is only slightly more expensive than a current
  netbook, and has a 22 inch display. put a LTX-9 ATOM motherboard into
  a LTX-22 case.
MicroLTX would be similar, but not have space for a separate laptop
  video card (o yes, we are standardizing laptop video cards, too) and
  perhaps top off at two RAM slots. MicroLTX motherboards fit into LTX
  cases, but not the other way around.
all connectors pertaining to the display, power, etc, would be
  identical. individual case OEM's can use different hinges to attach
  the display to the base and whatnot, but the wiring all needs to be
  identical.

Leaving aside the topic of standards, is it possible for an average John Doe like me to assemble a laptop from scratch in a cost effective manner? If yes, then how do I go about it?

A: You can indeed build your own laptop. It might be slightly more complicated than building a desktop, but not horribly more difficult. It probably won't be much cheaper than buying a pre-built laptop, and you won't have the wide range of hardware options and customization options you'd get with a desktop, because there aren't a lot of people who want to build their own laptops, and because the OEMs can order components custom designed to allow them unique construction arrangements in their laptops.
While I build all my own desktops, I have never considered building my own laptop for these preceding reasons.
However, if you want to go about building one, finding compatible components will be the first and most important step. Check out guides such as this one from Computer Shopper as a starting place: http://www.computershopper.com/feature/build-your-own-laptop


text:
Q: Can we expect find constant $C>0$ so that $(x+y)^r\geq C( x^{r}+y^r)$? Let $x, y >0, r>0.$ Assume that $r\notin \mathbb N.$

Can we say that  $(x+y)^r\geq x^{r}+y^r$?

Edit: In view  of the answer below: I'm modifying my question:

Can we expect to find a constant $C>0$ so that
  $(x+y)^r\geq C( x^{r}+y^r)$?

A: No.
Let $x=y=1$, then you are claiming $2^r\geq 2$ for all noninteger $r>0$, which fails to hold for all $r\in(0,1)$.

A: To the modified question: yes, and $C=1/2$ will do. Since $y>0$, $(x+y)^r>x^r$, and similarly $(x+y)^r>y^r$. One of $x^r$ and $y^r$ must be at least $\frac{x^r+y^r}2$, so $(x+y)^r>\frac{x^r+y^r}2$.
user10354138's answer shows that you cannot do better than $1/2$ in general: for any $C>1/2$ there is an $r$ sufficiently small for which the inequality would fail.


text:
Q: Is SQL Server Management Studio capable of managing SQL Server 2000 databases? I know this is really basic, but I can't find the answer in Google or SF, so I thought I'd better just ask.
If I run SQL Server 2008 R2 Management Studio on my PC, can I manage a SQL Server 2000 database server?
I know I can do it from SQL Server 2008 (non-R2) Management Studio, though I need a legacy component to manage Data Transformation Services.  I can cope fine without that component - all my DTS has been migrated to SSIS on a SQL 2005 / 2008 Servers, but I still have a legacy 2000 server and I'd like to be able to admin everything from one console.

A: I'm pretty sure that it can connect to a SQL 2000 server.

A: Yes it can connect to a SQL Server 2000 instance. You do lose some functionality like the activity monitor so depending on your daily needs in terms of database monitoring you may need to have multiple version of the management studio installed.


text:
Q: What's the meaning of bold sentence in the given excerpt from the economist The local population in Venice has roughly halved over the past 30 years. So, over the past two decades, has that of Dubrovnik in Croatia, an old walled city best known as King's Landing in "Game of Thrones". Academics now worry that services for ordinary residents, such as cheap cafés and doctors' surgeries, will collapse if populations continue to fall.
In the above excerpt, what's the meaning of- So, over the past two decades, has that of Dubrovnik in Croatia, an old walled city best known as King's Landing in "Game of Thrones".

A: By the way, this sentence is a bit of a chore even for native speakers, and it has a strong smell of the lamp about it. "So" is able refer to nearly any type of thing in a previous sentence. It is only after reading the parallel structure of the rest of the sentence, which effectively eliminates other possibilities, that we can deduce so is anaphoric to roughly halved and that is anaphoric to local population.
Over the past 20 years, the same thing has happened in Dubrovnik

A:
so (adverb) = "in the same way, also"  Collins

The population of Venice has halved. So has the population of Dubrovnik.
The population of Venice has halved.  The population od Dubrovnik has also halved.


text:
Q: Saving an Image in jpeg format in Matlab I'm new to image processing in Matlab and got stuck in the same. Kindly help me understand the issue or provide me some pointers. Also I apologize for the big problem statement. I hugely appreciate any guidance that you can provide me on this.
Problem: I'm working on a project to store one colour image(secret image) within another colour image(cover Image). Both these images are in jpg format. After the processing, I created an embedded image which looks similar to cover image but also has stored the secret image. The embedded image has stored the secret image bits correctly. However, upon extracting back the secret image bits, I'm not able to get the coloured secret image back. Below are the two approaches I used to recreate the secret image.
Approach 1: While recreating the secret Image, I created a zero matrix of the size of secret image and started storing the secret image bits in the matrix. But this recreated image looks completely white with few spots.
Approach 2: I manually created a white jpg image and read that image in my code. Then I started storing the secret Image bits in it. Upon display, this image showed the secret image properly.
The only difference in both were, in first approach I created a zero matrix and stored the secret image bits. In second approach, I read a white jpg image and stored the secret image bits. In first approach, I couldn't recreate the secret image but in second, I could.
Two possible solutions:

*

*In Approach 1: Obtain the secret image properly from the secret Image matrix.

*In Approach 2: Generate a white jpg image of the reuired dimensions automatically through the code and then read the same into the code and proceed.

Kindly suggest me to implement either of these above solutions.
Thanks in advance.

A: JPG is a lossy compression technique, which means data is lost when creating the image.  If you're 'embedding' an image inside another by altering each pixels least significant bit (or something similar) and then saving it as a JPG, it is possible some data may be lost.
Solution: use a loss-less compression technique, such as .PNG
Good Luck!


text:
Q: boto3 how to connect different account in different region I have two different AWS account in two region CN and US,  Can I use boto3 connect to different region service? look like following up code.
Boto2 code:
sqs = boto.sqs.connect_to_region(
  region, aws_access_key_id=access_key, aws_secret_access_key=secret_key)

how Boto3 do it like boto2

A: One possible method would be to use boto Session
from boto3 import Session

# Example: connecting to 'us-east-1' region

session = Session(aws_access_key_id=*****,aws_secret_access_key=****,region_name='us-east-1')
sqs_client = session.client('sqs')
sqs_resource = session.resource('sqs')

A: There is many ways to do it. Refer to credential configuration guide  for a start.
You can quickly get the info from from  boto3.Session
# use aws credential profile
session = boto3.Session(profile_name='dev')

# Or hardcoded your credentail
session = boto3.Session(
    aws_access_key_id="****",
    aws_secret_access_key="****",
    region_name="us-east-1"
)

Second way is supply hard coded credential in the client call. NOTE: You cannot specify profile_name using client.
client = boto3.client(
    's3',
    aws_access_key_id="****",
    aws_secret_access_key="****",
    region_name="us-east-1"
)

NOTE: If you setup EC2 instance using STS/temporary security credential, then you can retrieve the session token like this.
sts = boto3.client('sts')
my_token = sts.get_session_token()
s3 = boto3.client(
        's3',
        region_name="us-east-1",
        aws_session_token = my_token
    )


text:
Q: What voltage, in theory, should you read between the terminals if you hook a 18 volt solar panel to a 12 volt car battery? Well I thought it would be either 12 or 18 but... I have a battery and a solar panel so I thought I'd just try it.
I actually measured the voltage to be 9.7 before hand (btw it's an old lead acid car battery) and then I measured the volts on the solar panel and it was 20 +- a few (bc clouds and what not) then I hooked up the positive to positive and negative to negative, and measured 10.2 volts. Why not 9.7 or 20!?
I'm theorizing that this is because the battery put a drain on the solar causing that things volts to drop, so not 20. And the solar is boosting the battery causing it's volts to increase so not 9.7... and of course the internal resistance of the battery  is causing the whole thing to slide towards the lower end of the scale. Well is anything I said even making sense? Are there other considerations? Or is my original expectation right and it should read 20v and the solar setup is anomalous? lol.
Ps I took a few physics classes and even a circuits class years ago so if your answer gets technical I may still be able to follow.
Thanks in advance.
Edit:
I drew this picture which is a simplified circuit diagram of my setup (voltages shown are only approximations):

If you get rid of the battery between points a and b you read 20, if you get rid of the solar panel you read 9, my question is simply why 10 and not 9 or 20? What calculation results in a 10? Is it an average, subtraction? In other words it doesn't look like it is simply related to either of the starting voltages. :/

A: Solar panels are actually constant current sources. They supply a constant current regardless of what is connected to them, up to a maximum voltage. In your case that maximum is about 18V.
When you connect the panel to the battery, it will supply its nominated current, as the battery's 9.7V is below the 18V of the panel. The panel would supply that same current even if you shorted it.
When the battery receives that current, it's voltage rises, and will keep rising until it reaches the 18V of the panel. Of course, a 12V battery will have died well before that.
The moral of the story? Do not connect the solar panel to the battery like that. You should connect the panel through a circuit that will limit the voltage to something the battery will tolerate.


text:
Q: Ошибка в xml файле AAPT: error: unbound prefix В xml теге AAPT: error: unbound prefix. Ошибку выводит в самое первой строчке <Button. Вот отрывок кода, в котором выводит ошибку:
<Button
android:id="@+id/button_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/back"
android:background="@drawable/button_stroke_black95_press_white"
android:textSize="24sp"
androi:paddingLeft="5dp"
android:paddingRight="5dp"
android:textColor="@color/black95"
android:textAllCaps="false"/>

A: У вас неверный префикс в строке 7
androi:paddingLeft="5dp


text:
Q: "normal" number of processes/threads Considering a standard LAMP server (aka webhosting) what should be a limit at number of processes/thread?
ps -elfT | wc -l
475

"Limit" I mean: on DDOS probably the numbers of children-processes of httpd will increase quickly.


text:
Q: GIT push command is very slow on CentOS, Apache I created GIT server on my CentOS with Apache. (push/pull are go trough http and Apache)
I followed those instructions: http://www.jedi.be/blog/2009/05/06/8-ways-to-share-your-git-repository/
Push command is very slow. Every time I push it takes more than 10s (even if I changed one line of code from last push).
Is this normal?
Size of repozitory is 150MB.
Operation which takes most of the time is:

updating 'refs/heads/master'   from
  00c9d81959fc020c9f273e7c2887af461a52e0cf   to
  ccf47c31b7dcb32952f5251857660fa34018c5e1

What could be wrong?

A: WebDAV is not particularly fast, although you might want to see about disk and CPU usage on your server.  My advice would be to create a brand new repository with nothing in it, and see how the speeds increase/decrease as you add commits, just to verify that its not a size issue (or a diff issue).


text:
Q: API Unit Testing (Test Endpoints vs. Test Everything) we are building an API using Laravel, and we are facing an essential question:
Are we supposed to test everything (every method in every Model, Controller, and any other class)? or just test the API endpoints since testing endpoints means that everything else will be tested, because an API endpoint is using a Controller's method, that is in turn using a Model's method!
In fact I tend to the later one which is testing endpoints will help you test everything else, but I need to be sure that this is the right thing to do.
Edit:
Consider the following two points:

*

*testing endpoints means that I have to send an HTTP request and wait for the response to see if it is what I need, and that may be very bad con for this method.

*testing everything means that I have to find some way to mock up laravel request and its headers, and that may be very bad con for this method.

Any hints or comments will be appreciated.

A: Arguments and supporters exist for both sides. I suspect there are as many opinions on this subject as there are developers doing any form of developer testing.
In a nutshell:

*

*Unit tests put greater pressure on your design. Bad code will hurt more if you are testing at the unit level.

*Unit tests allow you to pinpoint problems more accurately, since they test each unit of work in isolation. If a unit test fails, you know where to look for the problem. If an integrated test blows up, you know something's wrong but typically have to start debugging to find the actual problem.

I like the phrase twitter user @everzet recently used:

When they're green, all tests look the same. It's when they're red you
  see the real difference.

On the other hand, integrated tests provide more freedom when refactoring. If you test only at the API level, you can change the entire implementation without affecting your tests. If you test at the unit level, a refactoring might mean you have to update/rewrite a whole lot of tests.


text:
Q: Will Caching affect time evaluation loops? Consider a situation where I use the following code to evaluate time taken by a function to execute.
long double Measure_micro_sec ( void (*foo) () )
{
    auto start = std::chrono::system_clock::now();
    for(long i =0; i <1000000; ++i)
    {
        foo();
        foo();
        if(i%1000 == 0)
            std::cout << i << "iterations\n";
    }
    auto end = std::chrono::system_clock::now();
    std::chrono::duration<long double> t_1 = end - start;

    auto start = std::chrono::system_clock::now();
    for(long i =0; i <1000000; ++i)
    {
        foo();
        foo();
        foo();
        if( i%1000 == 0 )
            std::cout << i << "iterations\n";
    }
   auto end = std::chrono::system_clock::now();
    std::chrono::duration<long double> t_2 = end - start;

    return (t_2.count() - t_1.count());
}

In the above code the change in total time of execution of the loops differ by (theoretically) n times (1000000) the execution time of foo(). Therefore the execution time of foo() is (t2 - t1)/n seconds or (t2 - t1) micro seconds.
Will the function foo() be cached? Will it affect the computation of the execution time of foo()? i.e. will the time difference (t2-t1) be different for when foo() is cached and foo() is not cached.
Consider foo() to be :
void foo()
{
    std::cout << "Example function\n";
}

As @Hugo and @LightnessRacesinOrbit have said that caching is dependant on the function. Will this function be cached?
EDIT: I have used std::chrono::system_clock for use as timer


text:
Q: SwiftUI, Notification about the end, the cancellation of a drag operation I have implemented drag and drop for one view. Now I want to change the state of the source view at the start of a drag operation and change the state back at completion or cancellation.
The following example code should illustrate this.
import UniformTypeIdentifiers

struct DragableView: View {
    @State var isActiveDropTarget: Bool = false
    @State var isDragged: Bool = false

    var body: some View {
        Text("Hello world")
            .overlay(RoundedRectangle(cornerRadius: 8)
                        .fill(Color.accentColor.opacity(0.1))
                        .opacity(isActiveDropTarget ? 1.0 : 0.0))
            .opacity(isDragged ? 0.5 : 1)
        .onDrag {
            isDragged = true
            return NSItemProvider(object: "Test" as NSString)
        }
        .onDrop(of: [UTType.data], delegate: self)
    }
}

extension DragableView: DropDelegate
{
    func dropEntered(info: DropInfo)
    {
        isActiveDropTarget = true
    }

    func dropExited(info: DropInfo)
    {
        isActiveDropTarget = false
    }

    func performDrop(info: DropInfo) -> Bool
    {
        isActiveDropTarget = false
        /* Handle drop
         ...
         */
        return true
    }
}

The problem with the current implementation is that I do notice when a drag operation starts (.onDrag is called), but I don't know when the operation ends.


text:
Q: Ruby on rails-->Mysql2::Error Lost connection to MySQL server at 'waiting for initial communication packet', system error: 0 Hi
I just started on Ruby on Rails. I try to launch my first 'HelloWorld' app using WebRick and MySQL 5.5, Windows XP
In firefox I can see the Rails standart page on "localhost:3000" but if I click on the link "about your apps environment" or try to see a pretty basic "hello world" page on localhost:3000/demo/index/ i get the error(after a minute or 2)
"Could not connect: Lost connection to MySQL server at 'reading initial communication packet', system error: 0.
Rails 3.0.7
MySQL 5.5
Gem 1.8.1
Ruby 1.9.2p180
Win XP 32
Tried both mysql and mysql2 gems on various versions.
The database seems to work fine through the console.
Tried also to connect with no password
Using utf8 and stating that in the database.yml.
tried https://github.com/ghazel/mysql2/commit/a9515ed75f3b7a7ce2813a364a0e7ede66394a41
tried to turn off firewalls completely
development:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: simple_db
  pool: 5
  username: simple
  password:
  host: localhost
  port: 3000

Help me!!!! So frustrated.....

A: It looks like you're trying to connect your MySQL connection to the Mongrel socket, so that's not going to work very well, as your application will just call itself when trying to make a database call.
You should probably change that to the default port 3306, or just leave it out and let the configuration defaults come into play.


text:
Q: Analogy between `F[_ <: A] <: B` at type-level and `f: A => B` at value-level Assuming F[_ <: A] <: B as type-level analog of f: A => B, let [F[_ <: Int] <: List[Int], A <: Int], then should't type application F[A] yield List[Int] when A = Int, so f(List(42)) should compile in the following case
$ scala3-repl
scala> def f[F[_ <: Int] <: List[Int], A <: Int](as: F[A]) = as
def f[F[_$1] <: List[Int], A <: Int](as: F[A]): F[A]

scala> f(List(42))
1 |f(List(42))
  |  ^^^^^^^^
  |Found:    List[Int]
  |Required: F[A]
  |
  |where:    A is a type variable with constraint <: Int
  |          F is a type variable with constraint <: [_$1 <: Int] =>> List[Int]

Applying the error message by explicitly providing type parameters makes it work
scala> f[[_ <: Int] =>> List[Int], Int](List(42))
val res0: List[Int] = List(42)

Where does the analogy break? Where is my mental model of considering F[_ <: Int] <: List[Int] as a type-level function from Int to List[Int] wrong?

A: Firstly regarding inferring type lambdas, I think that type inference would not go to the extent of coming up with type lambdas just to satisfy the constraints otherwise intuitively it would seem like everything would essentially be able typecheck with some convoluted type lambda and that would not be useful in picking up type errors.
As to why f[List, Int](List(42)) fails to compile (and thus fails to get inferred) we would need to refer to the Subtyping Rules of type lambdas:

Assume two type lambdas
type TL1  =  [X >: L1 <: U1] =>> R1
type TL2  =  [X >: L2 <: U2] =>> R2

Then TL1 <: TL2, if

*

*the type interval L2..U2 is contained in the type interval L1..U1 (i.e. L1 <: L2 and U2 <: U1),

*R1 <: R2

Also note that:

A partially applied type constructor such as List is assumed to be equivalent to its eta expansion. I.e, List = [X] =>> List[X]. This allows type constructors to be compared with type lambdas.

Which means all of these will compile:
f[[_ <: Int] =>> List[Int], Int](List(42)) //author's compiler example
f[[_] =>> List[Int], Int](List(42)) //input type bounds can be wider, output stays the same
f[[_] =>> List[42], Int](List(42)) //input wider, output narrower
f[[x <: Int] =>> List[x], Int](List(42))//input same, output narrower

And all of these will not:
f[[x] =>> List[x], Int](List(42)) //input type bounds can be wider but in this case it will also make the output wider
f[List, Int](List(42)) //equivalent to preceding case
f[[_ <: 42] =>> List[Int], Int](List(42)) //input type bounds cannot be narrower

In the case of:
def f[F[x] <: List[x], A <: Int](as: F[A]) = as

If you view it from the same type lambda perspective f[[x] =>> List[x], Int](List(42)) should work, and thus f[List, Int](List(42)) would also compile (and be inferred).


text:
Q: Putting year() directly into a array I am currently creating a array that holds a bunch of different data. One of the data points is to hold the most recent date accessed. For some reason I can't put year() into the array without the program breaking. Code below.
world_saves.push([[year()]]);

What's the reasoning behind this, and how do I set put the year into the array without a error. I've tried defining year() into a variable, but once again I get a error. Error below.
World_Data.js:5 Uncaught ReferenceError: year is not defined

Thanks in advance!

EDIT:
For anyone viewing this, this is the correct code to use.
var pjs = new Processing();
world_saves.push([[pjs.year()]]);

A: With the caveat that I've never used processing.js, it appears that you have to instantiate an instance of it first before calling methods on it.
Something like:
var pjs = new Processing();
world_saves.push([[pjs.year()]]);

also note:  You do realize you're pushing an array of an array containing the year here, right? (vs. just world_saves.push(pjs.year());)

A: I see that you already got this sorted out, but just for your information: with Processing.js, typically you'd write Processing code and have Processing.js create the Processing instance and call the setup() and draw() functions for you. There are a ton of ways to do this (many are outline on this page), but the basics would look like this:
<script src="processing-1.3.6.min.js"></script>
<script type="application/processing" data-processing-target="pjs">

int[] worldSaves = new int[1];

void setup() {
  size(200, 200);
  worldSaves[0] = year();
}

void draw(){
  background(0);
  text(worldSaves[0], 10, 10);
}

</script>
<canvas id="pjs"> </canvas>

What you came up with isn't really wrong or anything, but I also don't know why you're using Processing.js if you aren't using the Processing part of it. So eventually you might end up with something more like the above.


text:
Q: Converting Shopify API JSON to CSV Hoping that I may be able to get some assistance in regards to my code. I have spent the last couple of days crawling the site to try and find a response that would fit the requirements and while I found some excellent information, I am still struggling to implement a working version.
I have taken my code from this thread.
As the title suggests I am trying to take a nested JSON file received from a Shopify Webhook, flatten it and convert it to a CSV.
This is my JSON file:
{"id":788032119674292922,"title":"Example T-Shirt","body_html":null,"vendor":"Acme","product_type":"Shirts","created_at":null,"handle":"example-t-shirt","updated_at":null,"published_at":"2018-01-23T03:11:38-05:00","template_suffix":null,"published_scope":"global","tags":"mens t-shirt example","variants":[{"id":642667041472713922,"product_id":788032119674292922,"title":"","price":"19.99","sku":"example-shirt-s","position":0,"inventory_policy":"deny","compare_at_price":"24.99","fulfillment_service":"manual","inventory_management":null,"option1":"Small","option2":null,"option3":null,"created_at":null,"updated_at":null,"taxable":true,"barcode":null,"grams":200,"image_id":null,"inventory_quantity":75,"weight":200.0,"weight_unit":"g","inventory_item_id":null,"old_inventory_quantity":75,"requires_shipping":true},{"id":757650484644203962,"product_id":788032119674292922,"title":"","price":"19.99","sku":"example-shirt-m","position":0,"inventory_policy":"deny","compare_at_price":"24.99","fulfillment_service":"manual","inventory_management":"shopify","option1":"Medium","option2":null,"option3":null,"created_at":null,"updated_at":null,"taxable":true,"barcode":null,"grams":200,"image_id":null,"inventory_quantity":50,"weight":200.0,"weight_unit":"g","inventory_item_id":null,"old_inventory_quantity":50,"requires_shipping":true}],"options":[{"id":527050010214937811,"product_id":null,"name":"Title","position":1,"values":["Small","Medium"]}],"images":[{"id":539438707724640965,"product_id":788032119674292922,"position":0,"created_at":null,"updated_at":null,"width":323,"height":434,"src":"\/\/cdn.shopify.com\/s\/assets\/shopify_shirt-39bb555874ecaeed0a1170417d58bbcf792f7ceb56acfe758384f788710ba635.png","variant_ids":[]}],"image":null}

This is my code:
    import csv
    import json

    with open('product.json') as file:
         x = json.load(file)
        print x

    f = csv.writer(open("test.csv", "wb+"))

    f.writerow(["id", "title", "option1", "grams"])

    for x in x:
        f.writerow([x["id"],
                    x["title"],
                    x["variants"]["option1"],
                    x["variants"]["grams"]])

When running this code, I get the following error:
Traceback (most recent call last):
  File "parser5.py", line 17, in <module>
    f.writerow([x["id"],
 TypeError: string indices must be integers

I believe that the issue is to do with the fact that there is not an index reference '[0]', though I am unsure how to assign the key correctly and have failed in all of my attempts to do so.
I am fairly new to Python, I have tried to read as many posts on the site to try not to duplicate the question - apologies if this was in vain.
The desired output that I am looking for from the file would be something like this:
id,title,option1,grams
788032119674292922,Example T-Shirt, Small, 200
null,null,Medium,200

Any help or guidance that you may be able to offer would be greatly appreciated.

A: your json file contains a single dict(after json.load),
making this line for x in x: unnecessary, unless your file contains many lines like the one you provided
the other issue you have is the way you access x["variants"]["option1"]
 because x["variants"] returns a list of dicts! so your foreach should be there:
for item in x["variants"]:
    item["option1"]
    #etc...

A: Given the advice - this is the code that has worked for me on this problem:
import csv
import json

with open('product.json') as file:
x = json.load(file)
print x

f = csv.writer(open("test.csv", "wb+"))

f.writerow(["url", "sku", "parent_id", "title", "vendor", "product type",
"tags", "body_html", "image"])

f.writerow([x["handle"], x["id"],
    "",
    x["title"],
    x["vendor"],
    x["product_type"],
    x["tags"],
    x["body_html"],
    x["image"]])

for item in x["variants"]:
    f.writerow(["",item["sku"], x["id"],x["title"],"","","","",
    item["option1"]])

A: I think it would be easier to parse the JSON first and then use the csv writer as follows (please note I just googled this since I was doing something similar and this solution worked for me). I am pasting the example from the site I found, link to source bellow :)
import json
import csv
employee_parsed = json.loads(employee_data)
emp_data = employee_parsed['employee_details']
# open a file for writing
employ_data = open('/tmp/EmployData.csv', 'w')
# create the csv writer object
csvwriter = csv.writer(employ_data)
count = 0
for emp in emp_data:
      if count == 0:
             header = emp.keys()
             csvwriter.writerow(header)
             count += 1
      csvwriter.writerow(emp.values())
employ_data.close()

Source: http://blog.appliedinformaticsinc.com/how-to-parse-and-convert-json-to-csv-using-python/


text:
Q: Adding a new object to context So apparently I don't understand EF well enough yet. Someone here at SO suggested I shouldn't keep a context object open for the life of my application, so I changed things slightly and now here is how it is currently working:

*

*I read required data from the DB using EF and store it in an ObservableCollection(Of MyEntity).

*The application keeps adding new objects to this collection, modifying/deleting existing objects in the ObservableCollection.

*Upon application exit or Save button, I try to submit changes back to the DB, but apparently cannot. Here's the submission code.
For Each entity In MyObservableCollection
  If entity.EntityState = EntityState.Added OrElse entity.EntityState = EntityState.Detached Then
    Dim key = context.CreateEntityKey(entitySetName, entity)
    entity.EntityKey = key
    context.FilmTypes.Attach(entity)
  ElseIf entity.EntityState = System.Data.EntityState.Modified Then
    Dim originalItem As Object = Nothing
    Dim key = context.CreateEntityKey(entitySetName, entity)
    If context.TryGetObjectByKey(key, originalItem) Then
        context.ApplyCurrentValues(key.EntitySetName, entity)
    End If
  End If
Next

context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave)

EF tells me that there is already an object with the same key. My PK column is defined as Identity in the Model, so I expect it to auto-generate a temporary key (just like old good DataSets did).
How exactly do we work in "disconnected" mode in EF?

A: Found it myself. The code for Modified state is correct. For new objects, it should be like this:
If entity.EntityState = EntityState.Added OrElse entity.EntityState = EntityState.Detached Then
    context.FilmTypes.AddObject(entity)

No need to specify key parameter. EF will take care of it.


text:
Q: Is iterator's rule of Iterator and Listiterator different from each other?(Java) I'm practicing Java code - iterator and listIterator
and having a hard time understanding the result of the code below.
Code:
import java.util.*;

public class ListIteratorCollection {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("A","B","C","D");
        list = new ArrayList<>(list);

        ListIterator<String> litr = list.listIterator();
        String str;

        while(litr.hasNext()){
            str = litr.next();
            System.out.print(str + '\t');
            if(str.equals("A"))
                litr.add("A-add");
        }
        System.out.println();

        while(litr.hasPrevious()){
            str = litr.previous();
            System.out.print(str + '\t');
            if(str.equals("C"))
                litr.add("C-add");
        }
        System.out.println();

        for(Iterator<String> itr = list.iterator(); itr.hasNext();)
            System.out.print(itr.next() + '\t');
        System.out.println();
    }
}

Result:

A B   C   D
D C   C-add   B   A-add   A
A A-add   B   C-add   C   D

I wonder why A-add is not printed (in the first while loop), but C-add is printed (in the second while loop).
Both of them are just newly added to the existing list, and the while loop structure is alike (I think?).
Can anyone explain this?

A: This is explained by the documentation of ListIterator.add:

[...] The new element is inserted before the implicit cursor: a subsequent call to next would be unaffected, and a subsequent call to previous would return the new element.

So in your example (^ indicating the cursor)

*

*First iteration (forward):
A B C D
 ^ →

// litr.add("A-add");
A A-add B C D
       ^ →

*Second iteration (backward)
A A-add B C D
       ← ^

// litr.add("C-add");
A A-add B C-add C D
             ← ^

*Third iteration (forward)
 A A-add B C-add C D
^ →


text:
Q: How can I prevent switching branch in git when there are untracked modifications? Git does not allow switching to another branch if I have uncommitted changes that would be overwritten by the checkout.
Git will allow switching to another branch if the changes are not conflicting.
Is there a way to block switching branches even if the changes will not be overridden as a result? I would like to prevent an uncommitted change from being accidentally committed to the wrong branch.
Thanks,
Eyal

A: I am not aware of, nor could I find, any configuration that would change how checkout works in this way.
You could write a script that checks for uncommitted changes and, only if there are none, calls checkout.  (For example, you could use git diff --quiet HEAD to verify that your worktree looks like the last commit, plus git diff --quiet --cached HEAD if you want to additionally be sure you haven't staged changes and then undone them in the worktree.)  Then you could alias that if you want, or just invoke it directly, to do "safer" branch checkouts.
The safest thing is to always check what you're about to commit (or, at least, what you're about to push; you can generally undo a commit pretty easily if you notice it's in error before pushing).

A: As there is no pre-checkout hook, it's impossible to prevent switching branches. But Git has a post-checkout hook, which makes it possible to switch back to the previous branch/state automatically when there is one or more untracked files.
Here's a sample of post-checkout. Deploy it under .git/hooks and make it executable.
#!/bin/bash

foo=$(git config --get my.foo)
if [[ "$foo" = "yes" ]];then
    exit 0
fi

oldref=$1
newref=$2
flag=$3
if [[ "$flag" -eq 1 ]] && [[ "$(git status --porcelain | grep -oe '^??' | uniq)" = ?? ]];then
    echo "There are untracked files. Go back to the previous state."
    git -c my.foo=yes checkout -
fi
exit 0

*

*flag is 1 when checking out a branch, and 0 when checking out
files.

*?? is the status for untracked files.

*-c my.foo=yes prevents invoking post-checkout infinitively. In case you want to bypass this post-checkout, run git -c my.foo=yes checkout .... You can name my.foo whatever is different from any existing configuration variable.

*git checkout - is a shortcut to go back to the previous state.


text:
Q: Trying to get a section to display on right of web page (HTML) We have a Daddyleagues account for our Madden league. It allows you to edit with HTML, your home page. I am having an issue with some content, being displayed at the very bottom, left side, instead of starting from top, on the right side.
Take a look here: http://www.daddyleagues.com/maddenhub   Notice if you scroll to the bottom. Everything starting with NFC Playoff Race and below that, I want to display top right, the opposite of where AFC Playoff Race is.
Also, I dont know why, but everything is italicized font for some reason and havent been able figure that out either. Any help would be appreciated.
Daddyleagues has Layout divided into a few sections. We use League Header and League Homepage
League Header code:

<link rel="stylesheet"
 href="https://9cb1ad0ddfa4639c452deac616a4da79ba538f1d.googledrive.com/host/0BxrpWnd_UZ7leDFJM1pOVy1xNzQ/SOSDL.css">

<map
 name="Teams">
<area shape="RECT" coords="20, 10, 60, 37"
 href="/maddenhub/team/BUF" target="_self" title="Bills">
<area shape="RECT" coords="64, 10, 104, 37"
 href="/maddenhub/team/MIA" target="_self"
 title="Dolphins">
<area shape="RECT" coords="108, 10, 148, 37"
 href="/maddenhub/team/NE" target="_self" title="Patriots">
<area shape="RECT" coords="152, 10, 192, 37"
 href="/maddenhub/team/NYJ" target="_self" title="Jets">
<area shape="RECT" coords="203, 10, 243, 37"
 href="/maddenhub/team/BAL" target="_self" title="Ravens">
<area shape="RECT" coords="247, 10, 287, 37"
 href="/maddenhub/team/CIN" target="_self" title="Bengals">
<area shape="RECT" coords="291, 10, 331, 37"
 href="/maddenhub/team/CLE" target="_self" title="Browns">
<area shape="RECT" coords="335, 10, 375, 37"
 href="/maddenhub/team/PIT" target="_self"
 title="Steelers">
<area shape="RECT" coords="20, 44, 60, 71"
 href="/maddenhub/team/HOU" target="_self" title="Texans">
<area shape="RECT" coords="64, 44, 104, 71"
 href="/maddenhub/team/IND" target="_self" title="Colts">
<area shape="RECT" coords="108, 44, 148, 71"
 href="/maddenhub/team/JAC" target="_self" title="Jaguars">
<area shape="RECT" coords="152, 44, 192, 71"
 href="/maddenhub/team/TEN" target="_self" title="Titans">
<area shape="RECT" coords="203, 44, 243, 71"
 href="/maddenhub/team/DEN" target="_self" title="Broncos">
<area shape="RECT" coords="247, 44, 287, 71"
 href="/maddenhub/team/KC" target="_self" title="Chiefs">
<area shape="RECT" coords="291, 44, 331, 71"
 href="/maddenhub/team/OAK" target="_self" title="Raiders">
<area shape="RECT" coords="335, 44, 375, 71"
 href="/maddenhub/team/SD" target="_self" title="Chargers">
<area shape="RECT" coords="586, 10, 626, 37"
 href="/maddenhub/team/DAL" target="_self" title="Cowboys">
<area shape="RECT" coords="630, 10, 670, 37"
 href="/maddenhub/team/NYG" target="_self" title="Giants">
<area shape="RECT" coords="674, 10, 714, 37"
 href="/maddenhub/team/PHI" target="_self" title="Eagles">
<area shape="RECT" coords="718, 10, 758, 37"
 href="/maddenhub/team/WAS" target="_self"
 title="Redskins">
<area shape="RECT" coords="769, 10, 809, 37"
 href="/maddenhub/team/CHI" target="_self" title="Bears">
<area shape="RECT" coords="813, 10, 853, 37"
 href="/maddenhub/team/DET" target="_self" title="Lions">
<area shape="RECT" coords="857, 10, 897, 37"
 href="/maddenhub/team/GB" target="_self" title="Packers">
<area shape="RECT" coords="901, 10, 941, 37"
 href="/maddenhub/team/MIN" target="_self" title="Vikings">
<area shape="RECT" coords="586, 44, 626, 71"
 href="/maddenhub/team/ATL" target="_self" title="Falcons">
<area shape="RECT" coords="630, 44, 670, 71"
 href="/maddenhub/team/CAR" target="_self"
 title="Panthers">
<area shape="RECT" coords="674, 44, 714, 71"
 href="/maddenhub/team/NO" target="_self" title="Saints">
<area shape="RECT" coords="718, 44, 758, 71"
 href="/maddenhub/team/TB" target="_self"
 title="Buccaneers">
<area shape="RECT" coords="769, 44, 809, 71"
 href="/maddenhub/team/ARI" target="_self"
 title="Cardinals">
<area shape="RECT" coords="813, 44, 853, 71"
 href="/maddenhub/team/SEA" target="_self"
 title="Seahawks">
<area shape="RECT" coords="857, 44, 897, 71"
 href="/maddenhub/team/SF" target="_self" title="49ers">
<area shape="RECT" coords="901, 44, 941, 71"
 href="/maddenhub/team/STL" target="_self" title="Rams">
</map>

League Homepage:

AFC Standings

NFC Standings

AFC Playoff Race

Offensive Leaders

Power Rankings

Click Here For Full Rankings

Advance Countdown

Game of the Week

Padders of the Week

Offensive

Defensive

League Twitter

Media Twitter

Around The League

NFC Playoff Race

Defensive Leaders

Transactions Log

Here is the CSS code:
@charset "utf-8";
/* CSS Document */

@font-face{font-family:'NFLEndzoneSansCondMedium';src:url('http://i.nflcdn.com/static/site/7.1/img/fonts/endzone-sans/medium-cond.eot')}
@font-face{font-family:'NFLEndzoneSansCondMedium';src:url('//:') format('no404'),
url('http://i.nflcdn.com/static/site/7.1/img/fonts/endzone-sans/medium-cond.eot?#iefix') format('eot'),
url('http://i.nflcdn.com/static/site/7.1/img/fonts/endzone-sans/medium-cond.woff') format('woff'),
url('http://i.nflcdn.com/static/site/7.1/img/fonts/endzone-sans/medium-cond.ttf') format('truetype'),
url('http://i.nflcdn.com/static/site/7.1/img/fonts/endzone-sans/medium-cond.svg#webfont9DqcIwJf') format('svg');font-weight:normal;font-style:normal}

@font-face{font-family:'NFLEndzoneSlabBold';src:url('http://i.nflcdn.com/static/site/7.1/img/fonts/endzone-slab/bold.eot')}
@font-face{font-family:'NFLEndzoneSlabBold';src:url('//:') format('no404'),
url('http://i.nflcdn.com/static/site/7.1/img/fonts/endzone-slab/bold.eot?iefix') format('eot'),
url('http://i.nflcdn.com/static/site/7.1/img/fonts/endzone-slab/bold.woff') format('woff'),
url('http://i.nflcdn.com/static/site/7.1/img/fonts/endzone-slab/bold.ttf') format('truetype'),
url('http://i.nflcdn.com/static/site/7.1/img/fonts/endzone-slab/bold.svg#EndzoneSlab-Bold') format('svg');font-weight:normal;font-style:normal}

@font-face{font-family:'NFLEndzoneTechBold';src:url('http://i.nflcdn.com/static/site/7.1/img/fonts/endzone-tech/bold.eot')}
@font-face{font-family:'NFLEndzoneTechBold';src:url('//:') format('no404'),
url('http://i.nflcdn.com/static/site/7.1/img/fonts/endzone-tech/bold.eot') format('eot'),
url('http://i.nflcdn.com/static/site/7.1/img/fonts/endzone-tech/bold.woff') format('woff'),
url('http://i.nflcdn.com/static/site/7.1/img/fonts/endzone-tech/bold.ttf') format('truetype'),
url('http://i.nflcdn.com/static/site/7.1/img/fonts/endzone-tech/bold.svg#EndzoneTech-Bold') format('svg');font-weight:normal;font-style:normal}

/***** Daddyleagues Layout *****/

#PageContent {
    border:2px solid #a1a1a1;
    padding:10px 10px;
    background:#dddddd;
    height: auto;
    box-shadow: 0px 4px 10px 10px #000000;
    border-radius:5px;
    -moz-border-radius:25px; /* Firefox 3.6 and earlier */
}

#hmPageWrapper {
    margin:0 auto;

    border:2px solid #ffffff;
background:#ffffff;
height: auto;

    }

.home-column {
  float:left;
  margin-right:0px;
}

.home-left-column {
    width:212px;
    padding: 0px 0px 0px 0px;
}

.home-middle-column {
    width:474px;
    padding: 0px 0px 0px 0px;
    margin-left:6px;
}

.home-right-column {
    width:212px;
    padding: 0px 0px 0px 0px;
    margin-left:6px;
}

img{max-width:100%;height:auto;vertical-align:middle;border:0;-ms-interpolation-mode:bicubic;}

.hmPortletDecoration  {
    border: 1px #606060 solid;
    padding: 0px 0px;
    background: #000000 url('http://i1208.photobucket.com/albums/cc380/NDAlum/NFLfiller_zpsudwwfw3r.png');
    height: 40px;
    line-height: 40px;
    padding-left: 0px;
    color: white;
    font-weight: bold;
}

.hmPortletContent{
    border: 2px #242323 solid;
    margin-bottom:20px;
    color: #00000;
    font-family: NFLEndzoneTechBold, sans-serif;
    font-size: 11px;
    line-height: 1.4em;
    font-weight: bold;
    background-color: #ffffff;
    font-weight: bold;
            border-radius: 0px 0px 7px 7px;
-moz-border-radius: 0px 0px 7px 7px;
-webkit-border-radius: 0px 0px 7px 7px;
}

.hmPortletContent2{
    border: 2px #242323 solid;
    height: 140px;
    margin-bottom:0px;
    color: #00000;
    font-family: NFLEndzoneTechBold, sans-serif;
    font-size: 11px;
    line-height: 1.4em;
    font-weight: bold;
    background-color: #ffffff;
    font-weight: bold;
            border-radius: 0px 0px 7px 7px;
-moz-border-radius: 0px 0px 7px 7px;
-webkit-border-radius: 0px 0px 7px 7px;
}
.hmPortletContent3{
    border: 2px #242323 solid;
    height: 340px;
    margin-bottom:20px;
    color: #00000;
    font-family: NFLEndzoneTechBold, sans-serif;
    font-size: 11px;
    line-height: 1.4em;
    font-weight: bold;
    background-color: #ffffff;
    font-weight: bold;
            border-radius: 0px 0px 7px 7px;
-moz-border-radius: 0px 0px 7px 7px;
-webkit-border-radius: 0px 0px 7px 7px;
}
.visitor{
    margin-left:55px;
}

.hmPortletContentPadding{
    padding: 2px;
}

/***** Daddy GOW*****/
.gameoftheweek {
position:relative;
    width:100%;
    line-height:30px;
    border-bottom:0px;
    background: #000 center center;
font-family: NFLEndzoneTechBold, sans-serif;
}

.gameoftheweek .cfm-table tr td.cfm-at {
    width:60px;
    background-image:url('http://www.easports.com/madden-nfl/connected-franchise/bundles/maddenccm/images/game-details-at.png');
    background-repeat:no-repeat;
background-position:center;
}

.gameoftheweek .cfm-table tr td .score {
    color:#FFF;
}

.cfm-table {
    color:#FFF;
}

.gameoftheweek .ng-scope { background-position:100% 50%; background-repeat:no-repeat; background-size:75%; height:140px; margin:0 10px 0 0;}
.gameoftheweek .align-right.ng-scope { background-position:0% 50%; background-repeat:no-repeat; margin:0px 0px 0px 10px;}
.gameoftheweek .team { position:absolute; bottom:0; left:0; font-family: NFLEndzoneTechBold, sans-serif;display:none; font-size:14px}
.gameoftheweek .team i { font-family: NFLEndzoneTechBold, sans-serif; font-style:normal; }

/* Daddy League Overrides */
.adsense:first-of-type { display:none;}
#daddyleagues-navbar { margin-bottom:20px;}
.maincontent { padding-top:5px;}
.headerWrapper { width:960px;}
.container { width: 960px; background:none;}
.content {background:#fff;}

html { background:#011226; }
body { background:url('http://i1208.photobucket.com/albums/cc380/NDAlum/SOSbackground_zps7mpfoxc6.jpg') repeat center top;}
.scorelist {background: #F0F0F0;width: 100%;}
.scorelist .yui3-scorestrip-tile {font-family: NFLEndzoneTechBold, sans-serif;}

.yui3-scorestrip-tile-visitor-wins .yui3-scorestrip-tile-visitor, .yui3-scorestrip-tile-home-wins .yui3-scorestrip-tile-home { color:#222;}

    #player-profile { position:relative;}
    #player-team-overlay-container { margin:0;}

/* Bootstrap Overrides */
.panel-gir .panel-heading, .panel-afc .panel-heading, .panel-nfc .panel-heading  { text-transform:uppercase; padding:10px;}
.panel-gir .panel-body, .panel-afc .panel-body, .panel-nfc .panel-body  { padding:10px; background:url("http://i1208.photobucket.com/albums/cc380/NDAlum/Whitefiller_zpsi42dlfl0.png");}
.panel-gir .panel-footer, .panel-afc .panel-footer, .panel-nfc .panel-footer  { font-size: 10px; padding: 4px 10px;}

.panel-gir .panel-heading a, .panel-afc .panel-heading a, .panel-nfc .panel-heading a,
.panel-gir .panel-footer a, .panel-afc .panel-footer a, .panel-nfc .panel-footer a { color:#fff;}
.panel-gir .panel-heading a:hover, .panel-afc .panel-heading a:hover, .panel-nfc .panel-heading a:hover,
.panel-gir .panel-footer a:hover, .panel-afc .panel-footer a:hover, .panel-nfc .panel-footer a { color:#eee;}

.standings .panel-body { padding:0;}
.nopad .panel-body { padding:0;}

.panel-gir {border-radius:0px; border-color: #222;}
.panel-gir > .panel-heading,
.panel-gir > .panel-footer { color: #fff; text-shadow: 1px 1px 0px #222; background:url("http://i1208.photobucket.com/albums/cc380/NDAlum/NFLfiller_zpsudwwfw3r.png"); border-color: #222; border-radius:0; font-family: NFLEndzoneTechBold, sans-serif;}
.panel-gir > .panel-heading + .panel-collapse > .panel-body { border-top-color: #bfbfbf;}
.panel-gir > .panel-heading .badge { color: #fff; background-color: #222;}

.panel-afc {border-radius:0px; border-color: #000000;}
.panel-afc > .panel-heading,
.panel-afc > .panel-footer  { color: #fff; text-shadow: 1px 1px 0px #000000; background:url("http://i1208.photobucket.com/albums/cc380/NDAlum/AFCfiller_zpsj6v4l87f.png"); border-color: #000000; border-radius:0; font-family: NFLEndzoneTechBold, sans-serif;}
.panel-afc > .panel-heading + .panel-collapse > .panel-body { border-top-color: #000000;}
.panel-afc > .panel-heading .badge { color: #000000; background-color: #fff;}

.panel-nfc {border-radius:0px; border-color: #000000;}
.panel-nfc > .panel-heading,
.panel-nfc > .panel-footer { color: #fff; text-shadow: 1px 1px 0px #000000; background:url("http://i1208.photobucket.com/albums/cc380/NDAlum/NFCfiller_zpsw4kf8oq3.png"); border-color: #000000; border-radius:0; font-family: NFLEndzoneTechBold, sans-serif;}
.panel-nfc > .panel-heading + .panel-collapse > .panel-body { border-top-color: #000000;}
.panel-nfc > .panel-heading .badge { color: #000000; background-color: #fff;}

/* Standings */
.standings .data-table1 td, .standings .data-table1 th { font-size:10px; line-height:12px; padding:0 4px;}

.standings #afc-east-container,
.standings #afc-north-container,
.standings #afc-south-container,
.standings #afc-west-container,
.standings #nfc-east-container,
.standings #nfc-north-container,
.standings #nfc-south-container,
.standings #nfc-west-container { width:25%; float:left; border-right:1px solid;}

.standings #afc-west-container, .standings #nfc-west-container { border-right:0px solid;}

.panel-afc .data-table1 .thd1 td { background:#000000;}
.standings #afc-east-container,
.standings #afc-north-container,
.standings #afc-south-container,
.standings #afc-west-container { border-color:#000000;}

.panel-nfc .data-table1 .thd1 td { background:#000000;}
.standings #nfc-east-container,
.standings #nfc-north-container,
.standings #nfc-south-container,
.standings #nfc-west-container { border-color:#000000;}

.standings img { height:12px; width:12px; margin-right:2px;}
.teamLogo { margin-right:2px;}

/* transactions */
.transactions .data-table1 td, .transactions .data-table1 th { font-size:11px; line-height:12px; padding:2px 4px;}
.transactions img { height:12px; width:12px; margin-right:2px;}

/* Countdown */
.countdownHolder { width:200px; height:auto;}
.countdownHolder .countText { color:#222; font-family: NFLEndzoneTechBold, sans-serif;}

/* Powerrankings */
#powerrankings div {display: none;}

/* Playoffs */
.playoffs .data-table1 td, .standings .data-table1 th { padding:0 4px;}

.panel-afc.playoffs td.bubble { background:#000000!important; color:#fff!important; border:none!important;}
.panel-nfc.playoffs td.bubble { background:#000000!important; color:#fff!important; border:none!important;}

/* POTW */
.playeroftheweek { margin:0;}
.panel-player { width:50%; display:block; float:left; background:none; border:none; box-shadow:none; margin-bottom:0;}
.panel-player a { color:inherit;}
.panel-player .panel-heading {color: #222;text-shadow: 1px 1px 0px #ccc;background:none;;border-radius: 0;font-family: NFLEndzoneTechBold, sans-serif; padding:5px 10px 0px 10px; text-align:center;}
.panel-player .panel-body { margin:5px; padding:5px; background:none; margin-top:0; padding-top:0;}
.panel-player .avatar {width: 203px;height:203px;position:relative;background:url("http://i1208.photobucket.com/albums/cc380/NDAlum/Whitefiller_zpsi42dlfl0.png");-webkit-border-radius: 5px;-moz-border-radius: 5px;-ms-border-radius: 5px;-o-border-radius: 5px;border-radius: 5px;}
.panel-player .avatar img {width: 100%;height: 100%;position: absolute;bottom: 0;left: 0;z-index: 6;-webkit-border-radius: 5px;-moz-border-radius: 5px;-ms-border-radius: 5px;-o-border-radius: 5px;border-radius: 5px;background: -ms-linear-gradient(bottom, rgba(35,35,35,0.5) 0%, rgba(153,153,153,0) 80%);background-image: -webkit-gradient(linear, 50% 100%, 50% 0%, color-stop(0%, rgba(35,35,35,0.5)), color-stop(80%, rgba(153,153,153,0)));background-image: -webkit-linear-gradient(bottom, rgba(35,35,35,0.5) 0%, rgba(153,153,153,0) 80%);background-image: -moz-linear-gradient(bottom, rgba(35,35,35,0.5) 0%, rgba(153,153,153,0) 80%);background-image: -o-linear-gradient(bottom, rgba(35,35,35,0.5) 0%, rgba(153,153,153,0) 80%);background-image: linear-gradient(bottom, rgba(35,35,35,0.5) 0%,rgba(153,153,153,0) 80%);}
.panel-player .avatar img.teamLogo {display: block;filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=20);opacity: 0.2; background:none;}
.panel-player .playeroftheweek-name {font-family: NFLEndzoneTechBold, sans-serif; font-size:; line-height:; margin-bottom:0; color:#222;}
.panel-player .text .stat-value {font-family:NFLEndzoneTechBold, sans-serif; font-size: 12px; line-height:; letter-spacing:0px;margin-bottom:0; color:#666;}
.panel-player .text { padding:0px 10px;}

.panel-gir.potw>.panel-body {
position: relative;
background: #fcfcfc;
background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJod…EiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+);
background: -moz-linear-gradient(top, #fcfcfc 0%, #f8f8f8 25%, #f3f3f3 44%, #f8f8f8 65%, #e8e8e8 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #fcfcfc), color-stop(25%, #f8f8f8), color-stop(44%, #f3f3f3), color-stop(65%, #f8f8f8), color-stop(100%, #e8e8e8));
background: -webkit-linear-gradient(top, #fcfcfc 0%, #f8f8f8 25%, #f3f3f3 44%, #f8f8f8 65%, #e8e8e8 100%);
background: -o-linear-gradient(top, #fcfcfc 0%, #f8f8f8 25%, #f3f3f3 44%, #f8f8f8 65%, #e8e8e8 100%);
background: -ms-linear-gradient(top, #fcfcfc 0%, #f8f8f8 25%, #f3f3f3 44%, #f8f8f8 65%, #e8e8e8 100%);
background: linear-gradient(to bottom, #fcfcfc 0%,#f8f8f8 25%,#f3f3f3 44%,#f8f8f8 65%,#e8e8e8 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fcfcfc', endColorstr='#e8e8e8',GradientType=0 );
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
-ms-border-radius: 4px;
-o-border-radius: 4px;
border-radius: 4px;
border: 1px solid #e4e4e4;
}

.panel-nfc.stats .hm-table-caption td { background:#000000!important;}

.injuryBox { font-weight:normal;}

A: The three columns are the div 's where the class is col-xs-3, col-xs-6, and col-xs-3. These classes set the width of the three columns. You have a section that isn't in any of the columns and is pushing your third column down. Specifically this section.

Around    The League

Remove this section or put it inside of the one of the div sections with the classes mentioned before. As long as it and the rest of the sections have non-specific widths the columns should align correctly.


text:
Q: Task.WaitAll keeps in loop I'm trying this async code just for testing the async keyword:
public async Task<string> AsyncMethod()
{
    var link = "http://www.google.com";

    var webclient = new WebClient();
    var result = await webclient.DownloadStringTaskAsync(new Uri(link));

    return result;
}

public async Task<ActionResult> Index()
{
    var a = AsyncMethod();
    var b = AsyncMethod();

    Task.WaitAll(a, b);

    return View();
}

but when I debug it, the debugger hits the Task.WaitAll and just do nothing(the return keywork is never executed)..
If I set await before the two 'AsyncMethod' and remove the Task.WaitAll it works.. So what am I doing wrong?

A: Because your method looks like ASP.NET MVC controller action, I'm assuming you're running on ASP.NET.
By default, an async method resumes on the same context where it was suspended (i.e. where you called await). In ASP.NET, this means the current request context. And only one thread can be in a specific context at a time. So, what happens is that the thread that executes Index() is in the request context, blocked in WaitAll(). On the other hand, both invocations of AsyncMethod() are trying to resume on the same context (after they finished downloading), but they are unable to do so, because Index() is still executing in that context. Because of this, the methods are in a deadlock and so nothing happens.
(The same deadlock would also happen in an GUI application, because GUI context behave similarly in this regard. Console applications don't have this issue, because they don't have any context.)
The fix for this is twofold:

*

*Never wait synchronously for an async method. (Probably the sole exception is if want to execute an async method from the Main() method of a console application.)
Instead, wait for them asynchronously. In your case, that means using await Task.WhenAll(a, b).

*Use ConfigureAwait(false) in your "library" methods (i.e. those that don't actully need to execute on the request context).
Using 1 or 2 would fix your issue, but it's probably best if you do both.
For some more information about this issue, read Stephen Cleary's article Don't Block on Async Code.

A: It works this way:
public Task<string> FakeAsyncMethod()
{
    var link = "http://google.com";
    var webclient = new WebClient();
    var t = new Task<string>(() => webclient.DownloadString(new Uri(link)));
    return t;
}

public async Task Index()
{
    var a = FakeAsyncMethod();
    var b = FakeAsyncMethod();
    a.Start();
    b.Start();
    Task.WaitAll(a, b);
}

async void AsyncCall()
{
    await Index();
}

I don't know why it won't work with your method, but I suspect it's because tasks returned by methods marked with the async keyword are created in running state (more precisely, with Status equals to WaitingForActivation). I will look into it more.
EDIT: an alternative is to use Task.WhenAll paired with the await keyword.
public async Task Index()
{
    var a = AsyncMethod();
    var b = AsyncMethod();
    await Task.WhenAll(a, b);
}

A: Make sure that your async methods make use of the CancellationToken:
// the cancellation token from the request triggers
// when the user cancels the HTTP request in the web browser
public async Task<IActionResult> Index(CancellationToken cancellationToken = default)
{
    // internal cancellation token for the timeout
    using var ctsTimeout = new CancellationTokenSource(TimeSpan.FromMilliSeconds(2000));

    // cancels when either the user cancels the request
    // or the timeout expires
    using var cts = CancellationToken.CreateLinkedTokenSource(cancellationToken, ctsTimeout.Token);

    // make sure your methods make use of the cancellation token internally
    // ie. check the token in loops and on I/O requests
    var a = AsyncMethod(cts.Token);
    var b = AsyncMethod(cts.Token);

    // optional: pass the token to the Task.WaitAll method
    // ensures the HTTP request completes
    // even when the internal tasks won't
    Task.WaitAll(new [] { a, b }, cts.Token);

    return View();
}

If one of the called methods don't return, then the timeout will ensure that the tasks get cancelled and the Task.WaitAll throws an Exception.


text:
Q: How exactly does $\frac{\partial f}{\partial \bar{z}}$ work? I'm currently learning about complex analysis, and I keep coming across expressions involving $\frac{\partial f}{\partial \bar{z}}$. But I don't understand what this means. For example people might write
$$\frac{\partial }{\partial \bar{z}}z\bar{z}=z$$
But how does that make any sense? Why can we regard $z$ and $\bar{z}$ as independent variable while they clearly aren't?
In some material I've also read that  $\frac{\partial f}{\partial \bar{z}}=0$ can be interpreted as meaning that $f$ is 'independent' of $\bar{z}$. But $f$ depends on $z$, and $z$ can be thought of as 'depending' on $\bar{z}$, so clearly $f$ depends as much on $\bar{z}$ as it does on $z$.
This  $\frac{\partial f}{\partial \bar{z}}=0$ condition, whatever it even means, seems to also be equivalent to $f$ being analytic, which then leads to people saying things like 'If $f$ can be expressed without involving $\bar{z}$ then it is analytic'. But this again seems very strange to me. For example
$$f(z)=\bar{z}=z-2\Im(z)$$
Can certainly 'be expressed' without explicitly involving $\bar{z}$, but is not analytic, so this also doesn't make any sense to me.
Basically I'm asking for clarification on why in complex analysis people seem to be doing these dodgy things, and what they mean by them.

A: $\newcommand{\dd}{\partial}$The complex differential operators may be defined as complex linear combinations of ordinary partial derivatives:
$$
\frac{\dd}{\dd z} = \frac{1}{2}\left(\frac{\dd}{\dd x} - i\frac{\dd}{\dd y}\right),\qquad
\frac{\dd}{\dd \bar{z}} = \frac{1}{2}\left(\frac{\dd}{\dd x} + i\frac{\dd}{\dd y}\right).
\tag{1}
$$
This is what the chain rule would give if you treated $z = x + iy$ and $\bar{z} = x - iy$ as independent (so that $x = \frac{1}{2}(z + \bar{z})$ and $y = \frac{1}{2i}(z - \bar{z})$).
Then it's just a matter of formalities to check that
$$
\frac{\dd z}{\dd z} = \frac{\dd \bar{z}}{\dd \bar{z}} = 1,\qquad
\frac{\dd \bar{z}}{\dd z} = \frac{\dd z}{\dd \bar{z}} = 0
$$
and
$$
\frac{\dd}{\dd z} f(z, \bar{z}) = D_{1}f(z, \bar{z}),\qquad
\frac{\dd}{\dd \bar{z}} f(z, \bar{z}) = D_{2}f(z, \bar{z}),
$$
i.e., that a function expressed in terms of $z$ and $\bar{z}$ can be (formally) differentiated using the standard manipulations as if $z$ and $\bar{z}$ were independent variables.

If you must know, there's a rigorous construction (well-known to all students of complex geometry) that involves complexifying the tangent bundle of $\mathbf{R}^{2}$—equipped with the "complex structure" $J$ that rotates each tangent plane a quarter turn—and splitting the complexified tangent bundle into eigenbundles of (the natural extension of) $J$. The formulas (1) then define a complex-linear isomorphism between $(T\mathbf{R}^{2}, J)$ and the $i$-eigenbundle of $J$, and an anti-linear isomorphism with the $(-i)$-eigenbundle.


text:
Q: Understanding Ember routes Assume I have routemap like this:
App.Router.map ->
    @resource 'posts', ->
        @resource 'post', {path: '/:post_id'}

So I have list of posts on /posts route and a single post on posts/2. By default posts template will be rendered to {{outlet}} of a parent template (application) which is OK and post template to {{outlet}} of posts template which is not what I want. I want to replace list of posts with a single post.
So I came with that solution to set desired template to render to it's {{outlet}}:
App.PostRoute = Em.Route.extend
    renderTemplate: ->
        this.render(into: 'application')

But as a result I have list of posts and a single post rendered into one {{outlet}}. I can emtpy {{outlet}} each new route but then it breaks back button, cuz Ember wont render previous template again, assuming that is already rendered.
So questions is how to use single {{outlet}} for different routes and don't break ember's logic. Of course I can avoid nested routes but they a really usefull when you need semantic links like this post/2/comment/12/edit.

A: If your templates are not nested, you shouldn't nest your routes, or you'll end up fighting Ember.  Acting as Ember's state manager, routes describe your app structure. Nesting should follow your UI, not how you want your URLs to look like.
If your concern is URLs, you can just modify the path to fit your needs:
App.Router.map ->
  @resource 'posts'
  @resource 'post', { path: 'posts/:post_id' }

A: The approach I have used for handling nested and non nested templates even when my routes are nested is to use named outlets. Ember makes it really easy.
I have a top level menu outlet that always holds a menu relevant to the route being visited.
Example Application Template:

  {{partial "nav"}}

  {{outlet "menu"}}

  {{outlet}}

{{outlet "modal"}}

I have two named outlets, "menu" and "modal", which are used to hold content which is not nested but used by nested routes or any route to be precise. Any route can render a modal in response to actions into the global "modal" outlet, and similarly any route can render a menu into the "menu" outlet.
My examples use coffeescript.
Router:
App.Router.map ->
  @resource "posts", ->
    @route "create"
    @resource "post", {path: ':id'}, ->
      @resource "comments", {path: ':id'}, ->
        @route "create"
      @resource "comment", {path: ':id'}, ->

Routes which render a menu into a named outlet that is not nested:
App.PostsIndexRoute = Em.Route.extend
  renderTemplate: (controller, model)->
    # default render
    @_super arguments...
    # render posts menu into the application menu outlet
    @render "posts.menu",
      outlet: "menu"
      into: "application"

App.CommentsIndexRoute = Em.Route.extend
  renderTemplate: (controller, model)->
    # default render
    @_super arguments...
    # render comments menu into the application menu outlet
    @render "comments.menu",
      outlet: "menu"
      into: "application"

You don't have to do the default nested rendering as above, you could just   define a route type that always renders into a named outlet such as "content" (just don't call it "main" because Ember uses that).
App.ContentRoute = Em.Route.extend
  renderTemplate: (controller, model)->
    @render outlet: "content", into: "application"

And then subclass from it for any routes that should always render into the application 'content' outlet:
App.PostsIndexRoute = App.ContentRoute.extend()
App.CommentsIndexRoute = App.ContentRoute.extend()

But it would be better to do it with a mixin so you can easily include whatever concerns you wish into any route (eg authenticated route concerns).
App.RenderIntoContent = Em.Mixin.create
  renderTemplate: (controller, model)->
    @render outlet: "content", into: "application"

App.PostsIndexRoute = Em.Route.extend App.RenderIntoContent,
  ...

App.CommentsIndexRoute = Em.Route.extend App.RenderIntoContent,
  ...


text:
Q: Restrict Sharepoint List Items I have a web part on my home page for SharePoint announcements. On my announcements I have a public / private option.
I want my web part to show private options to users who are a member of a certain permission group.
how would I do this?

A: You would have to do two web parts on the same page and set the audience targeting on the web part to cover the two groups. The user should only see the web part if they're a member of whichever group. As an example (with made up group names) a web part might target members of 'Managers' the other would target 'Employees'. Each would only see one web part.
If the two groups aren't separate presently, you'd have to go through Central Admin to create any missing audiences that include or exclude users as necessary.


text:
Q: Proving trig relations in a circle
From the Picture
Following identities are true for every cirlce
$$ If\space 2\varphi+\theta=180$$
$$\frac{1}{\cos\theta}-1=\frac{tan\theta}{\tan\varphi}\space -Eqn\space 1$$
$$\frac{1}{2cos^2\varphi}-1=\frac{tan\varphi}{tan\theta}\space-Eqn\space 2$$
Any Proof for this identities ?

A: Let the top vertex of the triangle be $D$. $$\frac{1-\cos\theta}{\cos\theta}=\frac{\frac{\sin\theta}{\cos\theta}}{\frac{\sin\varphi}{\cos\varphi}}$$ $$\frac{1-\cos\theta}{\cos\theta}=\frac{\sin\theta}{\cos\theta}.\frac{\cos\varphi}{\sin\varphi}$$ $$1-\cos\theta=\sin\theta\cos\varphi\csc\varphi$$
$$1-\frac{AB}{AD}=\frac{BD}{AD}.\frac{BC}{CD}.\frac{DC}{DB}$$
$$AD=AC$$ $$BC=BD.\frac{BC}{DB}$$
$$BC=BC$$ $$\text{Q.E.D.}$$
For (ii),
$$\frac{1}{cos^2\varphi\cdot2}-1=\frac{tan\varphi}{tan\theta}$$
$$\frac{-\cos2\varphi}{2\cos^2\varphi}=\frac{\sin\varphi}{\cos\varphi}*\frac{\cos\theta}{\sin\theta}$$
$$\frac{-\cos2\varphi}{\sin2\varphi}=\cot\theta$$
So we have to prove that $$-\cot2\varphi=\cot\theta$$
Now use: $\cot2\varphi=\frac12[\cot\varphi-\tan\varphi]$
 I think you can take it from here.


text:
Q: Lack of understanding about simple question involving Lognormal distribution Given that $S_2$ is the accumulated value of a £1 investment over 2 years , with independent rates $i_1, i_2$ in the first and second year respectively (so $S_2 = (1 + i_1)(1 + i_2)$), I was told that $E[S_2] = 1.076$ and $Var[S_2] = 0.0027$.
Now, suppose that $(1+i_1)$ and $(1+i_2)$ are independent, identically distributed,
lognormal random variables with parameters $µ$ and $σ^2$.
Find the values of the parameters $µ$ and $σ^2$
for $(1+i_1)$ and $(1+i_2)$ knowing that E[$S^2$] and Var($S^2$) are equal to the values given.
I'm always quite confused by questions involving the lognormal distribution, so any guidance through this question would be appreciated.
( In the check sheet the answer is given as $µ = 0.036$ and $σ^2 = 0.0012$ )

A: You should probably start by saying that

*

*the mean of a lognormal distribution is $\exp\left(\mu+\frac{\sigma^2}{2}\right)$ and the variance is $\left(\exp\left(\sigma^2\right)-1\right)\exp\left(2\mu+\sigma^2\right)$

*If for $S_2$ these are $1.076$ and $0.0027$, then $\exp\left(\sigma^2\right) -1 = \frac{0.0027}{1.076^2}$ so $\sigma^2\approx 0.00233$ and $\mu \approx 0.072$

*But those are for two years combined. For one year, using the i.i.d. property,  the values are half these, i.e. $\mu \approx 0.036$ and $\sigma^2 \approx 0.0012$


text:
Q: Observer pattern with a filter, at what level to filter? Assume I have a class broadcaster to broadcast certain events.
Eg:
List<Observers> observers = …

Public void broadcast(Event e) {
    for (each observer: observers) {
       observer.observe(e);
   }
}

Then I have a class called EventReceiver which does the following
public void processEvent(Event e) {
    saveToDatabase(e);
    broadcast(e);
}

Now: a new requirement comes up, saying that when Event is of type "foo", we should save it to database but not broadcast it.
At which layer should I filter ?  At broadcast.java or in EventReceiver.java ?
Eg:
Public void broadcast(Event e) {
If (event != foo) {
    for (each observer: observers) {
       observer.observe(e);
   }
 }
}

Or
public void processEvent(Event e) {
    saveToDatabase(e);
   If (event != foo) {
        broadcast(e);
   }
}

A: I'd say processEvent, your second sample. The responsibility to filter should come from the body of code first processing the event, before you decide to broadcast it. There's no sense in passing off an event to broadcast which will not, or should not, be broadcasted.

A: If you have 2 observers, one broadcasts and another writes to DB, then you can use a Decorator pattern to filter.
class Broadcaster implements Observer {
    public void process(Event e) {
        broadcast(e);
    }
}

class DbWriter implements Observer {
    public void process(Event e) {
        writeToDb(e);
    }
}

class FilterOutFoo implements Observer {
    private Observer decorated;

    public Filter(Observer decorated) {
        this.decorated = decorated;
    }

    public void process(Event e) {
        if (!e.isFoo())
            decorated.processs(e);
    }
}

observed.addObserver(new Broadcaster());
observed.addObserver(new FilterOutFoo(new DbWriter()));

A: The filter should be clearly implemented in EventReceiver.java as you could upgrade the Broadcast.java class later on to broadcast other events.
You could have many receivers, each one implementing their own filter depending on the use case.
Moreover, as Michael pointed out, there is no point in broadcasting an event that wont be broadcasted.
It would be like muting a cell phone tower instead of the cell phone itself. You'll never get any call. But if you mute your cell phone instead, you decide whenever to unmute it. (sorry for the coparison :))

A: Don't filter. Subclass. If there is an event of type Foo, then there should be a class FooEvent. Let observers register for FooEvent notifications, so that observers only receive notifications they care about.
The root of the problem is a single Event class representing multiple event types. Instead, each event type should have its own class and its own list of observers.


text:
Q: Referencing data in a struct using switch in C++ I have a switch statement in my code to decide between several cases.  Depending on the choice, I would like to load a specific dataset and use that dataset for the remainder of the program.  One of the challenges as well is that the arrays in my structs will be arbitrary lengths.  What I am trying to avoid is rewriting my main program multiple times for every case.  My data is included in my scenariodata.h file, and my program is in test.cpp.  Right now it doesn't compile, but if it works the way I want, it should show '10' in the console. Many thanks in advance.
test.cpp
#include <iostream>
#include "scenarioData.h"

int main(){
    int choice = 1;

    //initialize a blank struct with generic name 'sd'
    sd_fmt sd;

    switch((int) choice){
        //Make a decision of which data set to use
        case 1:
            std::cout << "Using data1\n";
            sd = data1;
            break;
        case 2:
            std::cout << "Using data2\n";
            sd = data2;
            break;
    }

    //From here on do all my work with general variable name 'sd'
    std::cout << sd.speed[1];  //Should show 10 in the console

    return 0;
}

scenarioData.h
struct sd_fmt {
    double *speed;
};

struct sd_fmt {
    double speed[4] = {1,10,100,1000};
} data1;

struct sd_fmt{
    double speed[5] = {2,200,2000, 20,20000};
} data2;

A: I've updated the fragment to a more modern style of C++.
The structure definitions were confused with the declaration of an instances of the struct. Instead of creating a structure containing a pointer, the std::vector is used.  Use of pointer should be avoid where possible.
The vector has multiple advantages including being variable sized.  The initialize of the vector is straightforward as well.  If a vector has a known size then the at() member can be used to access a particular element.
The switch statement makes a copy of the vector which is not ideal.  If the vector was very large then using a reference to the vector would be more efficient. For this small example, it is a non-issue.
#include <vector>
#include <iostream>

using sd_fmt = std::vector<double>;

sd_fmt data1 = {1,10,100,1000};
sd_fmt data2 = {2,200,2000, 20,20000};

int main(){
    int choice = 1;

    //initialize a blank struct with generic name 'sd'
    sd_fmt sd;

    switch((int) choice){
        //Make a decision of which data set to use
        case 1:
        std::cout << "Using data1\n";
        sd = data1;
        break;
        case 2:
        std::cout << "Using data2\n";
        sd = data2;
        break;
    }

    //From here on do all my work with general variable name 'sd'
    std::cout << sd.at(1);  //Should show 10 in the console

    return 0;
}


text:
Q: Azure Automation - Runbook parameters not found? After adding a runbook with parameters, I'm unable to start it, either in the Test Pane or as a Job after publishing.

*

*Runbooks that existed prior to this do populate parameters.

*Unable to start a Test Job in ISE (aka, it's not simply a Portal/browser problem).

*GET from the ARM API returns a runbook with an empty Parameters property.

[edit] I should probably add it doesn't matter if I have [CmdletBinding()] specified or not. [/edit]

A: The runbook (script) in your screenshot contains a function definition (which takes parameters), but does not ever call the function. Your runbook does not take parameters, the function does. That is why the test pane is showing no parameters.
Try this:
param([string]$Bar)

function test-set {
  param([string]$Bar)
  "$Bar"
}

test-set -Bar $Bar

A: My memory of this 'support' was incorrect. As Joe points out, Workflow runbooks require the function declaration, but old-school scripts do not.
Commenting the function func-name { } bits allows the runbook parameters to be found again..


text:
Q: Ruby encapsulation I'm working with the book "Beginning Ruby", everything was going great up until the point where I got to encapsulation. I get what this piece of code is doing, I just don't know why it is set up this way with the methods.
For those interested this is the link with the page on encapsulation in the book.
class Person
    def initialize(name)
        set_name(name)
    end

    def name
        @first_name + ' ' + @last_name
    end

    def set_name(name)
        first_name, last_name = name.split(/\s+/)
        set_first_name(first_name)
        set_last_name(last_name)
    end

    def set_first_name(name)
        @first_name = name
    end

    def set_last_name(name)
        @last_name = name
    end
end

p = Person.new("Fred Bloggs")
puts p.name

It seems to me something like this can achieves the same:
class Person
    def initialize(name)
        @first_name, @last_name = name.split(/\s+/)
    end

    def name
        @first_name + ' ' + @last_name
    end
end

p = Person.new("Fred Bloggs")
puts p.name

Why go through the trouble of setting the object variables in their seperate methods?

A: Setter methods are useful to modify state of already existing object. In your case person's name is "kind of" immutable. You can't change person's name, you can only create a new person with new name.

A: Here you can find a similar explanation - Classes in Ruby Using Getters and Setters
p RUBY_VERSION

class Person
    def initialize(name)
        set_name(name)
    end

    def name
        @first_name + ' ' + @last_name
    end

    def set_name(name)
        first_name, last_name = name.split(/\s+/)
        set_first_name(first_name)
        set_last_name(last_name)
    end

    def set_first_name(name)
        @first_name = name
    end

    def set_last_name(name)
        @last_name = name
    end
end

John = Person.new("Fred Bloggs")
p John.name # now suppose you misrepresented the last name at time of `John` object creation. Then what would you do?

John.set_last_name "roy" # this setter method would then help you out to update the last name.

p John.name

Explanation: If you do set a person name at the time of that person like object creation,if any thing wrong information you have entered at the time creation,you can't change those. Because you don't have setter in your 2nd part of code.
Output:
"2.0.0"
"Fred Bloggs"
"Fred roy"

A: They are pretty much teaching you very basics of getters and setters for instance variables. Say you wanted to change the variables with the way you wrote your code you would have to access the instance variables directly. Instead, they create methods that allow you access to those variables so that you can use them outside of the class without giving complete access to the instance variables.
I'm assuming they will be leading up to attr_accessor, attr_reader, and attr_writer which are like macros that dynamically create accessors for your instance variables.

A: Suppose you have a name like your username. The class with just the two methods is not usable in that case, while in the original class you just do something like
Person.new("Stephan").set_last_name("de Vries")


text:
Q: Proof involving neighborhood of a limit point Let $f:D \to R$ with $x_0$ as an accumulation point of $D$. Prove that $f$ has a limit at $x_0$ if for each $\epsilon >0$ there is a neighborhood $Q$ of $x_0$ such that, for an $x,y \in Q \cap D$, $x \ne x_0$ and $y \ne x_0$, we have $\lvert f(x)-f(y) \rvert < \epsilon$.
Pf:Let $x_0$ be an accumulation point of $D$.
It is true that $\lvert f(x)-L \rvert =\lvert f(x) -f(x_0) \rvert<\frac{\epsilon}{2}$ for all $x \in Q \cap D$ if $0<\lvert x-x_0 \rvert < \delta$
$$\lvert f(x)-f(y) \rvert = \lvert f(x)-f(x_0)+f(x_0)-f(y) \rvert \le \lvert f(x)-f(x_0) \rvert + \lvert f(x_0)-f(y) \rvert < \frac{\epsilon}{2}+\frac{\epsilon}{2}=\epsilon$$
Therefore $\lvert f(x) -f(y) \rvert < \epsilon$ for all $x,y \in Q \cap D$ such that $0<\lvert x-y \rvert < \delta $
I feel like I can word this proof better

A: Your answer is fine, but you $\delta$ argument could be a little stronger, and predicate your $\epsilon$ argument.
The general argument for $\epsilon, \delta$ argument should be phrased,

*

*Let $\epsilon > 0$ be given

*Then for $|x-y| < \delta$ the following is true,

*Math statement $< \epsilon$

In addition, when you say, "It is true [stuff] for $x \in Q \cap D$ and $|x - x_0| < \delta$", you should really add something like "so, $|x-y| \leq |x-x_0| + |y-x_0| < \frac{\delta}{2} + \frac{\delta}{2} = \delta$ [...]"


text:
Q: Is there any way to draw a table using Raphael js library I am using Raphael JS to creating a ERD like tool, but don't know to to create a table like instance by using Raphael.

A: paper = new Raphael(0,0,500,500);

var x = 100;
var y = 50;
var height = 50
var width = 100;

WriteTableRow(x,y,width*2,height,paper,"TOP Title");
y= y+height;
WriteTableRow(x,y,width,height,paper,"Score,Player");
y= y+height;
for (i=1;i<=4;i++)
{
var k;
k = Math.floor(Math.random() * (10 + 1 - 5) + 5);
WriteTableRow(x,y,width,height,paper,i+","+ k + "");
y= y+height;
}

function WriteTableRow(x,y,width,height,paper,TDdata)
{
    var TD = TDdata.split(",");
    for (j=0;j<TD.length;j++)
    {
        var rect = paper.rect(x,y,width,height).attr({"fill":"white","stroke":"red"});
        paper.text(x+width/2, y+height/2, TD[j])
        x = x + width;
    }
}

//http://jsfiddle.net/LG5zn/116/

A: Raphael can draw anything, but if you're doing a lot of manual creation of tables and so forth than you're probably fighting the framework. My favorite aspect of the library is that is works so seamlessly with traditional HTML, CSS and Javascript. I would strong suggest taking what you want from HCJ and using Raphael for whatever that can't easily do.


text:
Q: In an iOS application, what is typically considered the model in the MVC paradigm? I'm trying to understand the MVC paradigm, and I understand that the model is the data layer. I'm confused as to how that manifests specifically in applications however.
Say I have a Core Data database of Animal objects/entities (with properties such as genus, region, etc.). Is the Core Data database considered the model? Is the Animal class considered the model?
Could anyone offer a practical explanation of what a model would be in a typical iOS application?

A: Model has your application logic/algorithm/computations, manipulation of the data etc. View is the presentation, and receives user interactions. Controller orchestrates the application and the flow to another controller and interactions with the view and the model.
So, in your example if there is certain rules that are to be followed before data is stored in DB or returned to the view (user), that will go in your model. It could well be your animal class.

A: -The Model is the brain of the application. It does the calculations and creates a virtual world for itself that can live without the views and controllers. In other words, think of a model as a virtual copy of your application, without a face!
-A View is the window through which your users interact with your application. It displays what's inside the model most of the time, but in addition to that, it accepts users' interactions. Any interaction between the user and your application is sent to a view,which then can be captured by a view controller and sent to the model.
-Controllers in iOS programming usually refer to view controllers. Think of view controllers as a bridge between the model and your views. They interpret what is happening on one side (what the user does on the view side, or the information provided by the model) and use that information to alter the other side as needed.


text:
Q: Erased HDD "Free Space" with 0x00, but now Windows 7 is reporting a false storage size I have a virtual disk (VMDK) on an SSD, and I ran a program (DiskGenius -> Erase Free Space) to erase free space on that VMDK. It erased about 800 GB of room which used to be available to me in Windows 7.
However, now when I boot Windows 7 in VMWare Workstation, it says there's only 644 MB free. Where did all my free space go and how I can I recover it?
Should I run a defrag (not really wanting to do that since it's destroy my SSD write cycles) or perhaps a chkdsk on boot up Windows 7?
DiskGenius:

Windows 7 Explorer Report:

VMWare HDD Options
VMWare Cleanup

A: SOLUTION: Run in VMWare the 'Cleanup Disks' option from the toolbar, and then run a chkdsk in Windows (performed on bootup).


text:
Q: Http POST multipart x-mmixed-replace I am sending this request to the server:
POST /stream.php?K=pparam HTTP/1.0
Content-Type: multipart/form-data;boundary=MY_BOUNDARY_STRING_NOONE_HAS
Host: someweb.com
Content-Length:22182

--MY_BOUNDARY_STRING_NOONE_HAS
Content-Disposition: form-data; name="XXXXX16" filename="YYYYY17"
Content-Type: application/octet-stream

[IMAGE 22182 BUFFER]
--MY_BOUNDARY_STRING_NOONE_HAS

Content-Disposition: form-data; name="XXXXX12" filename="YYYYY13"
Content-Type: application/octet-stream

[IMAGE 22163 BUFFER]
--MY_BOUNDARY_STRING_NOONE_HAS

But at the server:
The php $_FILES is empty
Array
(
)
<?php
 print_r($_FILES);
?>

A: The whole request should have the Accept: header
Now I am able to upload a camera stream
POST /stream.php?K=127.0.0.1_camera1 HTTP/1.1
Host: localhost
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate
Liveimage: camera1
Content-Type: multipart/form-data; boundary=212367691630846570233068106084
Content-Length:20209
Connection: keep-alive

--212367691630846570233068106084
Content-Disposition: form-data; name="file10"; filename="S11"
Content-Type: application/octet-stream

[IMAGE 20209]
boundary=--212367691630846570233068106084

Content-Disposition: form-data; name="file12"; filename="S13"
Content-Type: application/octet-stream

[IMAGE 20209]
boundary=--212367691630846570233068106084

RRRRRR   POST
Content-Disposition: form-data; name="file14"; filename="S15"
Content-Type: application/octet-stream

[IMAGE 20209]
boundary=--212367691630846570233068106084


text:
Q: Use ggplot to plot over an image with legend I would like to map OHS incidents over a PNG of a hospital floorplan using ggplot2. I have tried reading this non-geographic map in as a ggimage.

So far I have tried the following with the dataset (14462) observations that I have.
Example dataset
toy <- data.frame(patient_ID = c(1001,1001,1002,1003,1004),
               SEX = c("M","M","F","F","F"),
              phenotype = c("Psychiatric","Psychiatric", "Cardio",
                            "Cancer","Psychiatric"),
                            x = c(0.5737, 0.5737, 0.6968, 0.4704, 0.6838),
                            y= c(0.3484, 0.3484, 0.62, 0.5216, 0.2486))

I have tried reading the file in as a raster and then using ggmaps but the difficulty is no legend.
library(ggmap)
library(png)
library(ggplot2)
library(data.table)

toy <- fread("toy.csv")

# read in image

r <- readPNG("ICU-crop.png")

#use ggimage to convert to plot and add gender
ggimage(r, scale_axes = TRUE) +
  geom_point(aes(x = x, y = y, colour = SEX), data = toy,
             size = I(1), fill = NA)

I would really like to use ggplot but need the legend. I am not sure what other methods I can use to ggplot over a PNG.

A: The real "magic" for this is just fullpage=FALSE in the call to ggimage(), but you'll have to clean up axes a bit then:
ggimage(r, fullpage = FALSE, scale_axes = TRUE) +
 geom_point(aes(x = x, y = y, colour = SEX),
            data = toy, size = I(1), fill = NA) +
  labs(x=NULL, y=NULL) +
  theme(axis.text=element_blank()) +
  theme(axis.ticks=element_blank())

You should prbly clean up the legend, too and I'd suggest lightening the base image a bit since it will be difficult to see the contrast between it and the colors you're going to overlay (unless they're large objects).


text:
Q: MySQL: Convert a string representation of hh mm into actually minutes I have a column in my database where time has been stored in the format hh mm
e.g. 03 00 = 3 hours
e.g. 03 15 = 3 hours 15 minutes

How can I convert this into actual minutes
e.g. 03 00 = 180 minutes
e.g. 03 15 = 195 minutes


text:
Q: Creating a new variable based on conditions of 3 other variables in R I have a data set (n=500) in R that looks like this
ID    A      C      S
1     4      4      4
2     3      2      3
3     5      4      2

Id like to create a new variable(I am calling this variable "same")  that tells me whether any of my columns have the same value (excluding my ID column). So,
ID    A      C      S     Same
1     4      4      4     all
2     3      2      3     as
3     5      4      2     none
4     7      7      2     ac

Any help would be much appreciated! I am pretty lost! Thank you!

A: We may loop over the rows with apply (MARGIN = 1) with selected columns ([-1] without the 'ID' column), then check the length of unique elements, if it is 1, return 'all' or else paste the names of the duplicated elements.  If there are no duplicates, then it returns blank "", change the blank to 'none'
df1$Same <- apply(df1[-1], 1, \(x) {
    x1 <- if(length(unique(x)) == 1) 'all' else
  paste(tolower(names(x))[duplicated(x)|duplicated(x,
    fromLast = TRUE)], collapse = "")
    x1[x1 == ""] <- "none"
  x1})

-output
> df1
  ID A C S Same
1  1 4 4 4  all
2  2 3 2 3   as
3  3 5 4 2 none
4  4 7 7 2   ac

data
df1 <- structure(list(ID = 1:4, A = c(4L, 3L, 5L, 7L), C = c(4L, 2L,
4L, 7L), S = c(4L, 3L, 2L, 2L)), class = "data.frame", row.names = c(NA,
-4L))

A: Try this using dplyr rowwise with rle
df |> rowwise() |> mutate(Same = case_when(length(rle(sort(c_across(A:S)))$values) == 1 ~ "all" ,
length(rle(sort(c_across(A:S)))$values) == 3 ~ "none" ,
c_across(A) == c_across(C) ~ "ac" ,
c_across(C) == c_across(S) ~ "cs" , TRUE ~ "as"))

*

*output

# A tibble: 4 × 5
# Rowwise:
     ID     A     C     S Same
  <int> <int> <int> <int> <chr>
1     1     4     4     4 all
2     2     3     2     3 as
3     3     5     4     2 none
4     4     7     7     2 ac