text:
---
title: "Code Review #1"
date: 2021-09-03T06:55:14Z
header_image: https://static.righttobeoffensive.com/i/code-review-t.png
draft: false
---

Part one out of a probable one.  A lot to say about a small script by a beginner.  This script does some web scraping and variable juggling to present the user with a quiz on various chosen topics.

<!--more-->

This is a compilation of a bunch of reddit posts I made on [/r/Python](https://old.reddit.com/r/Python) in response to a new programmer looking for a code review.

{{< expando id="listing" title="Click here for the full listing." >}}
  [review_code.py](posts/review_code.py)

  {{% listing fname="posts/review_code.py" lang="python" %}}
{{< /expando >}}

If I can be bothered, at a later date I'll find the links to my posts - I don't remember how well they were received and it's coming up for a year since I wrote them compared to now.  I'm also now banned from there for being too spicy when Russia invaded Ukraine.  Again.

---

> I recently started to take my interest in programming seriously

Hell yeah my dude welcome to the fold.  Let's do this.

* First up - use hosted version control.  [github](https://github.com) is free to use and has features that would make this review easier for me to do.  It's also instrumental for working as a team.

* Ship your code with a way to run it.  I notice that it has a dependency on `requests`, but nowhere is that described besides in the source.  I only know the dependency is there ahead of time because I happen to be looking at the codebase, and the import happens to be at the top, and I happen to know that `requests` is not part of the standard library.

The best (in my opinion, and therefore in fact) way to do this is to provide one or more `requirements.txt` files, with each dependency having an exactly specified version per line.  In your case, the requirements file would look like this:

```
requests==2.26.0
```

* Adding on to the above, it's more friendly to your users if you tell them how to run it.  Add a README that explains the prerequisites (Python, which OSs, so forth), and how to install and run the project.

* Nitpick - sort your imports.  `random`, `os`, and `json` are all stdlib, but `requests` is third party.  It's hard to tell that without already knowing, just by looking at the top of the file.  Personally I like to have the groups: standard library; framework; third party; first party; local, but feel free to chop and change these as you see fit.  Also on the topic of sorting imports, sort them alphabetically by module too.  It makes it easier to see at a glance whether something has already been imported.

You can use `isort` to handle this for you automatically (which again feeds in to working with other people - an `isort.cfg` at the top level explains to your colleagues in black & white "this is how we do it").

* Instead of setting a flag to break out of a loop, use `break`:

```python
while True:
    main_quiz()
    ...
    if should_quit_for_some_reason:
        break
```

* `GAME_RUNNING = ...` `PLAY_GAME = ...` save `UPPER_SNAKE_CASE` variable names for constants.

* `global correct` `global incorrect` - don't use `global`.  It is _always_ (in my opinion, you know how this goes, I'm right), incorrect to use `global` outside of throwaway "I literally just want this to run once" scripts.  When you find yourself writing `global`, autocorrect that in your mind to "oh I should be using a class here".

* `main_quiz()` is doing a crazy amount.  It's clearly an orchestrator in disguise - some collection of discrete tasks performed in order, but the discrete tasks are all inlined for no great reason.  You'll notice you've already done a lot of breaking down into functions, but you didn't realise it.

```python
def main_quiz():
    amount, difficulty = start_game_options()
    print_categories()
    questions = get_questions()
```

And so forth.

* `dif = ...` prefer to use proper words for names.  You can get away with short or single letter ones where you're using the variable right then and there, for instance in an enumeration, but `dif` isn't used for another fifteen lines.  Call it what it is, `difficulty`.

* Unsanitised user input.  The API you're calling hopefully has input sanitisation (though it's PHP so who knows), but it's still a better idea to sanitise input yourself - you _know_ that the only valid options for `amount` are `in range(1, 50 + 1)`, and you _know_ the only valid options for `difficulty` are `in ["easy", "medium", "hard"]`, so why aren't you forcing the user to pick one of them?  Similar commentary for `category`.

  Way more typing than is needed.

```python
print(
    "Random: 0\n"
    "General Knowledge: 9\n"
    "Entertainment Film: 11\n"
    "Entertainment Music: 12\n"
    "Entertainment TV: 14\n"
    "Science and Nature: 17\n"
    "Sports: 21\n"
    "Georgphy: 22\n"
    "History: 23\n"
    "Celebrities: 26\n"
    "Vehicles: 28\n"
    "Science: Gadgets: 30"
)
```

In brackets like that, string literals are concatenated together.

* Style: it'd be easier to read that menu if the inputs were on the left, aligned, and the descriptions were on the right:

```
 0: Random
 9: General Knowledge
11: Entertainment Film
12: Entertainment Music
...
```

* `if category == 0:` in Python 3, this will never be true.  `input()` takes input from the user and provides it to te program as a string.  If you want to compare it to an int, you need to cast it yourself:

```python
try:
    category = int(category)
except ValueError:
    # handle the duff input somehow, maybe ask again
    pass

if category == 0:
    ...
```

Of course it would be easier to compare the string input: `if category == "0":`.

If you're in Python 2, `input()` attempts to do some basic conversion, but you shouldn't be relying on that, (use `raw_input()` instead, for Python 3 behaviour), and for the LOVE of god don't start new projects in Python 2.

* UX: as a user, I might be quite reasonable in expecting that `0` and `0 ` are the same, but of course they're not.  Perhaps add some deburring to the input such as "category = category.strip()`.

* Going back to `main_quiz()` being an orchestrator in disguise, using that line of thought as a tool you can see that the following is out of place:

```python
# Score Variables
correct = 0
incorrect = 0
```

Let's rewrite it and its surroundings as if it was an orchestrator and we'll see where it all falls down:

```python
def main_quiz():
    ...
    category, random = get_category()
    correct, incorrect = setup_scores()
    questions = get_questions(category, random)
```

You see how the scoring setup is completely interrupting?  Asking the user for the category is inherently part of getting the questions, and should be as close to it as possible.  There's also an argument to be made for the question getter to do the getting of categories, (and difficulty and amount), which I'll make later unless I forget, which I won't, because I'm perfect.

* `# Score Variables` it's not a title, comments are prose - `# Score variables.`

* `f"https://..."` I do love f-strings, but there are tools to build URLs, which you should be using.  [`urlencode`](https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode) for the query string, and if you want to be super proper about it, [`urlunparse`](https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlunparse) for the whole URL.

```python
query = urlencode(query_params)
url = f"https://example.com/?{query}"
```

I'll get back to `query_params`.

* If `if random:` passes, (which it currently never will, but let's ignore that), you'll make a request to the server, then immediately overwrite the response by doing a different request.  To fix this most simply, use an `else`:

```python
if random:
    response = requests.get(...)
else:
    response = requests.get(...)
```

But there's an even better way, combined with the previous point.

`urlencode()` takes a mapping (or some other stuff I'll ignore), so we can progressively build that, then construct the URL (which is the only thing that changes), then bring the `requests.get()` call out of the `if` statement and only write it once.

```python
query_params = {
    'amount': amount,
    'difficulty': difficulty,
    'type': 'multiple',
}

if not random:
    query_params['category'] = category

query = urlencode(query_params)
url = ...

response = requests.get(url)
```

I remember not quite grokking dictionaries as a beginner, so feel free to write this out line by line in the REPL and make predictions about what the contents of certain variables will be at certain points, then inspect them to prove yourself right.  (In that order.    [Look how trash this is](https://imgur.com/LkJcw4c.png)!  Your code should be a love letter to your fellow developer, (who may be you in three months).  Newspapers and publishers have figured out hundreds of years ago that people tire of reading overly long lines.  That's why broadsheets have columns, and why books have large margins (or layout).  There's a design book I had a flick through one time that I forget the name of that you should check out.  I've asked a friend to remind me of it, so we'll see if his memory is better than mine.  (It was, [here](https://www.amazon.co.uk/Grid-Systems-Graphic-Design-Communication/dp/3721201450) you go).

Keep your lines to 79 characters or less.  If they're lines of prose (block text or comments) keep them to 72.

  Enforcing line length encourages good code practices because it discourages overly indented blocks, overly verbose variable names, and rewards breaking things down into parts as described above.

People _will_ disagree with me on this hardline stance, and I _will_ die on this hill.  See above points about me always being right about everything.

* You call `requests.get(...)` and then never check the result, assuming that it will succeed with 200.  One day the server will go offline.  Sometimes your users will be offline (and might like to know they need network connectivity before they go through all the setup).  Maybe the server will go offline very briefly so you should retry.  Maybe it will stay online but the endpoint will change, and you'll need to update the URL rather than retrying.

Because you never checked the result, you were never forced to think about these things.

* `# Create a formated` *formatted

* `jsonDatabase`, `questionArray`, `qIndex` and so forth are all using `camelCase` naming, which doesn't match Python conventions, nor what you've written in the rest of the file.  Use `snake_case` for variable names.

* `x = json.dumps(response.json(), ...); json.loads(x)` why?  `Response().json()` returns a Python object (if it can), so there's no reason to convert it to JSON (from a Python object) and then back into a Python object, unless I'm missing something to do with `sort_keys`.

(And if I am, there's a better way to do it).

* Nitpick: `#Index of array search` missing a space.

* `# Randomize awnsers ... for correct awnser` *answers, *answer.  I notice this is misspelt in the same way in future variable names with reasonable consistency.

* This upcoming `for` loop is a data transform which doesn't describe its input shape or output shape.  What should I expect to see in `questionArray` from the API?  More importantly, why aren't you checking that it's the right shape?  If the API returns an object that doesn't have `'results` as a top level key, your program will crash instantly and exit.

* `for i in questionArray['results']:` `i` is generally used for an index only, (and there are good arguments floating around against ever using single letter variable names).  It looks like it would be better named here as `for question in questionArray['results']:`.  Also I just noticed it's never used.  Name unused variables a single underscore to make it obvious they're unused, but there's a bigger issue - read on...

* This is bizarre:

```python
i = 0
for _ in some_object['array']:
    some_object['array'][index]  # Repeated like eighty times.

    i += 1
```

As a small point, there's a construct for index tracking, called `enumerate()`:

```python
for i, _ in enumerate(some_object['array']):
    some_object['array'][index]
```

But that's beside the point.  I believe you have a fundamental misunderstanding of iterables.  The variable named in the for loop (the "target") will become the item in the collection as it's iterated over.  There's no need to do index nonsense.

```python
for item in some_object['array']:
    item  # Here it is.
```

* This data transform is pretty confusing.  This is a combination of your inexperience (no shame in that), and that the format returned by the server is a bit sub-standard, requiring some extra work.  Here's a rough breakdown of why I'm confused:

1. No description of the expected data shape

2. Mutation of state

3. Strangeness to do with randomisation interrupting the flow

4. A weird implementation of a mapping

5. The comment that heads the section talks about randomisation and assigning a letter, but _not_ fixing the bizarre input format

Point い can be fixed by including an example of the expected return in a comment.  The best place for this is the docstring of a function that returns the data.

Point ろ I'll go over shortly, but to evangelise on the topic of immutable state for a bit in this context - with mutable state, the reader has to keep in mind what shape the data is in _on each line_.  Let's say they went and got an example of what was returned from the API, and then they glance ahead and see that `incorrect_answers` somehow contains the correct answer.  Very confusing.

Point は I'll also go over shortly, but keep in mind this interruption idea.  I would identify it as a current weakness of yours that you can easily improve on and become stronger and more powerful.  Too powerful.

Point に is simple enough:

```python
correct_answer_letter = {0: "a", 1: "b", 2: "c", 3: "d"}[correct_answer_index]
```

You could be super duper clever and use `chr()` or whatever, but I don't like that for a good amount of reasons - forces sequentiality, silently removes bounds (suddenly you can get a "letter" for the index 150), requires the reader to know ASCII by heart or try it out themselves...  Best to just not.

Point ほ is also simple enough - write good comments.  As a beginner it's hard to understand what a good or bad comment is, but now I've explained why this block is confusing, and what the comment was missing that would have helped, fixing this one seems easy.

Anyway I'm rambling.  Let's talk about this block on the high level, and then set to a solution.

I snagged a response for myself to work off to understand your code, here it is:

```python
{
    "category": "History",
    "type": "multiple",
    "difficulty": "hard",
    "question": "In addition to his career as an astrologer and "prophet", Nostradamus published a 1555 treatise that included a section on what?",
    "correct_answer": "Making jams and jellies",
    "incorrect_answers": [
        "Teaching parrots to talk",
        "Cheating at card games",
        "Digging graves"
}
```

This structure has one data type (answer) split into two parts based on a property of another data type (correctness, based on the question).  Personally I would have gone with something like:

```python
{

    "question": "Is Nostradamus a hella cool fella?",
    "answers": [
        "Yeah",
        "No",
        "Maybe",
        "I don't know, can you repeat the question"
    ],
    "correct_answer": 0
}
```

I notice you're doing a transform that's something _like_ this, but it's very haphazard as it modifies things in place and doesn't respect variable names and such, - `incorrect_answers` gains a correct answer among its ranks, for instance.

Once I had a sensible data structure, (and my goodness I wish I could convince API developers to provide them in the first place, but here we are), if I was going to encode the display logic in the data at this point as you have, the next step would be to randomise the order of the answers.  There's a value being used as an index into the list of answers though, so randomising the order of them must also update that value.

There are a few ways around this.  A nice simple one is to store the contents of the correct answer, shuffle the list, then look up the index and store it.

```python
import random

correct_answer = data["answers"][data["correct_answer"]]
random.shuffle(data["answers"])
data["correct_answer"] = data["answers"].index(correct_answer)
```

Note that `random.shuffle()` shuffles a list in place, so that is mutation.  If you don't like that, (and that's quite reasonable), you can use  `.sample()` instead:

```python
data["answers"] = random.sample(data["answers"], k=len(data["answers"])
```

Whatever.

Next up is the third part of the task, rendering the letter choices.  Again, let's approach this from the high level first by realising that the answers are _already_ keyed by something, just not letters.  `data["answers"][0]` that `0` is the key.  You want those to be specific letters instead.  Let's bring back an old friend.

```python
indices_to_letters = {0: "a", 1: "b", 2: "c", 3: "d"}
data["answers"] = {
    indices_to_letter[index]: answer
    for index, answer in enumerate(data["answers"])
}
data["correct_answer"] = indices_to_letters[data["correct_answer"]]
```

That there is a dictionary comprehension, which is just a fancy way to write the following:

```python
new_answers = {}
for index, answer in enumerate(data["answers"]):
    new_answers[indices_to_letter[index]] = answer

data["answers"] = new_answers
```

You'll notice that each of these three steps is nicely self-contained and makes plenty of sense as its own function.  This is an ultimate-level good idea because then the function can take the input, create the output and return it, (preserving immutability), and the functions can have a docstring each that documents the returned shape, an important part of understanding the code as a reader.

Now, you could add a fourth step in this to transform the data structure you'd have at this point into the one that matches your current `questions` structure, and on an actual project with deadlines and pay and stuff, you or your manager might decide that that's more cost effective than rewriting `main_display()` to accept the new and more sensible data structure.  This, however, is a learning project, so I would recommend you keep the data structure as is after these three steps, and reap the benefits of a good data structure with the rewrite.

Data structures are the most important thing in this craft.

Whew.

* `NEW_ARRAY = ...` again, save `UPPER_SNAKE_CASE` for constants, but more importantly, this line is THREE HUNDRED AND SEVENTY FOUR CHARACTERS LONG!  PLEASE for the LOVE of god split your lines!  How can any reader possibly be expected to keep track of what index each element is at?  How can they be expected to understand what each of the elements is going to be?

Also as a stylistic note, when building up a list of flat collections (1D tuples or lists), generally the name for the temporary variable is `row`.  This is generally only used when a temporary variable is required because the row is being incrementally built:

```python
data = []
for item in collection:
    row = [item]
    row.append(some_data())
    row.append(some_other_data())

    data.append(row)
```

In your case, you have all the data in the first place, so you may as well nupe the temporary variable:

```python
for ...:
    questions.append([
        question["question"],
        question["incorrect_answers"][0],
        question["incorrect_answers"][1],
        ...,
    ])
```

* `def main_display(...):` Line length.  Also, it's not _really_ incorrect, but it's a bit strange that this function is indented at this level, thus defining it within another function.  I don't see much of a reason for this to not be top level.

* This function is, like the other one, doing too much.  It's called "main display", but it displays a _question_, takes user input, checks user input, interacts with the operating system, and modifies global state.

* Plenty more `print(); print(); print(); ...` in this function.  That can be improved.

* `print("")` you can simply do `print()` to output a newline.  You could make an argument for _always_ providing the first argument to make it obvious you haven't forgotten it, but given that there are no others, and the function is almost always called with at most one argument, I'm not sure how strong that argument is.

* `print("Correct"); input("")` `input()` has a prompt - why not just `input("Correct")`?

* `print("The correct awnser was: " + correctAFull)` what happened to using f-strings?  I love those!

* Style: `correct = correct + 1` can be `correct += 1`.  Similar commentary for `incorrect` a little further on.

* `clear_c = input(...)` this variable is unused.

* `clear_c = input ('')` again, this variable is unused.  Also this time (stylistically) there's a space between the `input` function name and its invocation.  Nothing wrong with that per se, but that's against conventions and you haven't done it anywhere else in this file.

* `# Reset qIndex to be reused` I am perfectly capable of reading the next couple of lines, that comment is just noise.  You might want to put a comment there if it was `qIndex = 6` instead, because that would actually be something about which I, the reader, would want to know about.

As a sidenote, that's a pretty contrived example because in that case I'd complain about the "magic number" and tell you to turn it into a constant like `qIndex = SKIP_HEADER_OFFSET` or something.

* `for i in questions: ...` another misuse of a `for` loop here.  See above for details.

* `print("Correct: " + str(correct))` f-striiings!  There's no need for the string cast in f-strings.  `print(f"Correct: {correct}")`.

* There is all sorts of mixing of levels of interaction all over the place here.  You have interface display, user input parsing, interaction with the OS, interaction with the network, maintenance of game state, all in the same breath.  It's kind of difficult to point out how to fix that in a general manner.  It's also difficult to point out why it's problematic and requires fixing without you having first added all the error handling that should be there.

Let's go back to the question getter I alluded to way back when.

The inputs are an integer in `range(1, 50 + 1)`, a string from the collection `["easy", "medium", "hard"]`, an integer from the set `{0, 9, 11, 12, 14, 17, 21, 22, 23, 26, 28, 30}`.  The outputs are some interface elements, and an array of questions as returned by the server.  Right now it's all jumbled together and full of potential vulnerabilities as discussed above.

Here's how I might do it:

```python
import os
import platform
import random  # Usage not shown.

import requests

def get_choice(prompt, valid_choices, transform=lambda x: x):
    """
    Prompts the user with the given string, and returns their chosen
    option assuming it's present in `valid_choices`.

    `valid_choices` should be a collection of strings, but in the case
    where a typed input is expected, and looking it up in the collection
    is cheaper as that type, a `transform` function can be provided,
    taking one argument and returning the value to look up in the
    collection.

    >>> get_choice(
    ...     "Pick a number between 1-50 inclusive: ",
    ...     range(1, 50 + 1),
    ...     transform=lambda x: int(x),
    ... )

    Where a transform is provided, the transformed value is returned.
    """
    choice = None
    while True:
        try:
            choice = transform(input(prompt))
        except Exception:
            # Something went wrong in the provided transform - assume
            # that means the input is not valid.
            pass

        if choice in valid_choices:
            return choice

        print("Invalid choice.")

def clear_screen():
    if platform.uname().system == "Windows":  # Probably, haven't checked.
        os.system("cls")
    else:
        os.system("clear")

def build_url(amount, difficulty, category):
    query_params = {
        'amount': amount,
        'difficulty': difficulty,
        'type': 'multiple',
    }

    ...  # You've seen this before

    return url

class ServiceError(Exception):
    pass

def get_response(url):  # Maybe this should implement retrying.
    try:
        response = requests.get(url, timeout=5)
    except requests.exceptions.ConnectionError as e:
        raise ServiceError("Connection to the server failed.") from e
    except requests.exceptions.Timeout as e:
        raise ServiceError("Connection to the server timed out.") from e
    except requests.exceptions.TooManyRedirects as e:
        raise ServiceError("The server is misconfigured.") from e

    try:
        response.raise_for_status()
    except requests.exceptions.HTTPError as e:
        # Maybe there's something the user cares about in this error
        # from the server, like a message saying "you have requested
        # too many questions today, come back at 18:45 tomorrow".
        raise ServiceError(
            "The server responded with an error: "
            f"{response.status_code}",
        )

    return response

def parse_response(response):  # Maybe `parse_and_validate` is better`.
    bad_return = ServiceError("The server returned malformed data.")
    try:
        decoded = response.json()
    except requests.exceptions.JSONDecodeError as e:
        raise bad_return from e

    try:
        validate_questions(decoded)
    except ValidationError as e:
        raise bad_return from e

    return decoded

def get_questions_from_api(amount, difficulty, category):  # Orchestrator.
    url = build_url(amount, difficulty, category)
    response = get_response(url)
    decoded = parse_response(response)

    return decoded

# The script starts, as does interaction with the user.
amount = get_choice(
    "Enter amount of questions you would like 1-50: ",
    range(1, 50 + 1),
    transform=int,
)
clear_screen()

difficulty = get_choice(
    "Enter difficulty [easy, medium, hard]: ",
    ["easy", "medium", "hard"],
)
clear_screen()

category_prompt = """Select a category from the following options:

    0: Random
    9: General Knowledge
11: ...
12: ...

Category: """
category = get_choice(category_prompt, [0, 9, 11, 12, ...], transform=int)
clear_screen()

# Maybe let the user know what's going on.
try:
    questions = get_questions_from_api(amount, difficulty, category)
except ServiceError:
    ... # Render the error for the user.
```

Note how obvious it is that I haven't completed `get_questions_from_api()` and how completing it would just be another couple of steps in the orchestration.  Also important to note is that I have tested exactly none of that so not only will it probably not work, (at one point I `return url` without defining it, for instance), it will also probably burn down your house and steal your money.


text:
# Feature images for every channel of conv2 layer
Images were optimized by activation maximization.

Model: Caffenet (slightly modified from Alexnet)
Algorithm: Deep visualization toolbox (https://github.com/yosinski/deep-visualization-toolbox)

# Optimization hyper-parameters
## regularization
decay=0.0001, blur-radius=1.0, blur-every=4,
small-val-percentile=0, small-norm-percentile=0, px-benefit-percentile=0, px-abs-benefit-percentile=0

## optimizer
lr-policy='constant', lr-params=100, max-iter=100

# processing
see `processing.py`

# Reference
@inproceedings{yosinski-2015-ICML-DL-understanding-neural-networks,
Author = {Jason Yosinski and Jeff Clune and Anh Nguyen and Thomas Fuchs and Hod Lipson},
Booktitle = {Deep Learning Workshop, International Conference on Machine Learning (ICML)},
Title = {Understanding Neural Networks Through Deep Visualization},
Year = {2015}}

license: MIT

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
# System utilities

* **[`order`](@ref)**   Order of a system.
* **[`size`](@ref)**    Number of outputs and inputs of a descriptor system .
* **[`iszero`](@ref)**   Checking whether the transfer function matrix of a descriptor system is zero.
* **[`evalfr`](@ref)**   Gain of the transfer function matrix at a single frequency value.
* **[`dcgain`](@ref)**   DC gain of a system.
* **[`opnorm`](@ref)**   `L2`- and `L∞`-norms of a descriptor system.
* **[`rss`](@ref)**   Generation of randomized standard state-space systems.
* **[`rdss`](@ref)**   Generation of randomized descriptor state-space systems.
* **[`dsxvarsel`](@ref)**   Building a descriptor systems by selecting a set of state variables.
* **[`dssubset`](@ref)**   Assigning a subsystem to a given descriptor system.
* **[`dszeros`](@ref)**   Setting a subsystem to zero.
* **[`dssubsel`](@ref)**   Selecting a subsystem according to a given zero-nonzero pattern.
* **[`dsdiag`](@ref)**   Building a `k`-times diagonal concatenation of a descriptor system.

```@docs
order
DescriptorSystems.size
DescriptorSystems.iszero
evalfr
dcgain
DescriptorSystems.opnorm
rss
rdss
dsxvarsel
dssubset
dszeros
dssubsel
dsdiag
```

branch_name: refs/heads/main

gha_language: Julia

gha_license_id: MIT


text:
## Full Jenkins installation via Terraform in AWS.
#### This makes Jenkins portable and reusable :)

This is a full installation of Jenkins including a backup job via Terraform in AWS. Once installed, configured and backed up you can restore your jenkins instance using the same method as a new install - restoring all your backed up files.

#### Configuration components:
**files/config/plugins.txt** - this file is used to populate the desired plugins to install in Jenkins. If you're installing for the first time and don't know which plugins you need use the pre-populated list of plugins provided in the repo. If you have an existing instance and you want the same plugins installed you can run the following command to extract a list of plugins from your existing Jenkins instance:
```Shell
curl -s -k 'http://<adminUserName>:<adminPassWord>@localhost:8080/pluginManager/api/json?depth=1' \ | jq -r '.plugins[].shortName' | tee plugins.txt
```
but make sure you have jq installed first:
```Shell
sudo yum install jq -y
```
and then copy the `plugins.txt` file to the `files` subdirectory overwriting the current `plugins.txt` file.

**files/terraform.tfvars** - this file is included in your `.gitignore`. When executing terraform you'll use this file to populate the required global variables needed for Terraform to run. Create and populate the following:
- access_key = "Your AWS access key"
- secret_key = "Your AWS secret key"
- app = "Your app name"
- ec2_ami = "The AMI ID to use with the ec2 instances"

**prod/terraform.tfvars** - this file is included in your `.gitignore`. When executing terraform you'll use this file to populate the required global variables needed for Terraform to run. Create and populate the following:
- env = "The environment you're deploying to"
- region = "The AWS region to deploy to"
- leader_instance_type = "The ec2 instance type for the leader instance"
- cloud_zone = "The Route53 hosted zone Domain Name to create the record in. You can omit the '.' in the Domain Name"
- key_name = "The keypair to use with ec2. This must be generated first through the console"
- record_name = "The name of the Route53 record to created. For example, if your hosted zone Domain Name is 'blah.com' and your record is 'hello' this would create a Route53 record named 'hello.blah.com'"

**files/config/jenkins.env** - this file is included in your `.gitignore`. The file is copied to S3 durring Terraform run and is used to generate the initial admin username and password for Jenkins via `files/config/init.groovy`. Create and populate the following:
- admin_username=adminUserName
- admin_password=adminPassword

#### Deploying Jenkins
Once you have configured the above you're ready to deploy Jenkins! We're going to assume you already have Terraform installed and configured. If not please follow [this link](https://learn.hashicorp.com/terraform/getting-started/install.html) to get Terraform setup.

Open terminal and change to the repo directory > prod (Jenkins/prod) then type:
```Shell
terraform init
```
to initialize Terraform and the associated modules. Next, let's apply our proposed changes to deploy Jenkins:
```Shell
terraform apply --var-file=../files/terraform.tfvars
```
This will generate a plan of what will be applied during the run. Type `yes` to approve and continue:

![apply_plan.png](/readmeFiles/apply_plan.png)

Here's a breakdown of what's being installed on AWS by module (`Jenkins/modules`) and sorted by order:
- S3 - Copies the neccessary files to an pre-created S3 bucket (see `files/terraform.tfvars`) for configuring Jenkins installation. Below is a list of files and description:
    - `init.groovy` - startup script to create initial Jenkins admin account and disable annon UI read access.
    - `install-plugins.sh` - script used to install plugins and dependencies from `plugins.txt`. **Ripped off from https://gist.github.com/micw/e80d739c6099078ce0f3**.
    - `plugins.txt` - list of plugins to install. To extract a list of plugins from an existing Jenkins instance run the [extraction command](#configuration-components) on the Jenkins server
    - `jobs.tgz` - contains our pre-baked backup job.

- VPC - The VPC for Jenkins to run in including subnets, route tables, ACL, routes and associations.
- SEC - Security groups for EC2, ELB and role needed for EC2 to read/write from S3.
- EC2 - Launch config, autoscaling group, ELB and associations.
- Route53 - www record for Jenkins instance.

#### Post install steps
1. Log into Jenkins using the username and password provided in `jenkins.env`.

2. Configure the Jenkins backup job and include the S3 bucket created in the S3 module in the paramter `S3_BUCKET`: ![config_param.png](/readmeFiles/config_param.png) From here you can also configure the job to run on a schedule if desired: ![config_schedule.png](/readmeFiles/config_schedule.png)

3. Run the Jenkins backup job and cross your fingers :) Just kidding. It'll work.

### If you have any issues with any part of the process or questions feel free to [open an issue in Github](https://github.com/bspeagle/Jenkins/issues) and I'll respond as soon as I can. Thanks for trying it out!

repository: sansukh/Jenkins

repo_name: sansukh/Jenkins


text:
## jobManagerAddress

The JobManager is serving the web interface accessible at localhost:8081

## clusterId

Using [native_kubernetes](https://nightlies.apache.org/flink/flink-docs-release-1.14/docs/deployment/resource-providers/native_kubernetes/), when launch the session,
execute the shell script:

```shell script
./bin/kubernetes-session.sh -Dkubernetes.cluster-id=my-first-flink-cluster
```

the control of input textbox shall input the value what system `-Dkubernetes.cluster-id` setted

repository: alldatacenter/alldata

repo_name: alldatacenter/alldata


text:
# Python3 on Ubuntu Docker

Dockerfile for image built off [Ubuntu 20.04](https://wiki.ubuntu.com/FocalFossa/ReleaseNotes/20.04) containing [Python 3.10](https://www.python.org/downloads/release/python-3105/) ([Python 3.6](https://www.python.org/downloads/release/python-368/), [Python 3.7](https://www.python.org/downloads/release/python-374/), [Python 3.8](https://www.python.org/downloads/release/python-387/), [Python 3.9](https://www.python.org/downloads/release/python-3910/) built from source).

[![GitHub Actions Status: CI](https://github.com/matthewfeickert/Docker-Python3-Ubuntu/workflows/CI/badge.svg?branch=master)](https://github.com/matthewfeickert/Docker-Python3-Ubuntu/actions?query=workflow%3ACI+branch%3Amaster)
[![Docker Automated build](https://img.shields.io/docker/automated/matthewfeickert/docker-python3-ubuntu.svg)](https://hub.docker.com/r/matthewfeickert/docker-python3-ubuntu/)
[![Docker Pulls](https://img.shields.io/docker/pulls/matthewfeickert/docker-python3-ubuntu.svg)](https://hub.docker.com/r/matthewfeickert/docker-python3-ubuntu/)
[![download-size number-of-layers](https://images.microbadger.com/badges/image/matthewfeickert/docker-python3-ubuntu.svg)](https://microbadger.com/images/matthewfeickert/docker-python3-ubuntu)

## Installed Dependencies

### apt-get
- gcc
- g++
- git
- zlibc
- zlib1g-dev
- libssl-dev
- libbz2-dev
- libsqlite3-dev
- libncurses5-dev
- libgdbm-dev
- libgdbm-compat-dev
- liblzma-dev
- libreadline-dev
- uuid-dev
- libffi-dev
- tk-dev
- wget
- curl
- make
- software-properties-common
- sudo
- bash-completion
- tree
- vim

### From source

- Python 3.10 (3.6, 3.7, 3.8, 3.9)

gha_language: Shell


text:
## YTMusic
YTMusic is very simple Android application for listening and downloading music from YouTube. It supports work with playlists and videos.

I developing it just for personal purposes, in order to gain programming skills on Android and learn how to work with the YouTube API.

## Credits
* [YouTube url extractor][1]
* Launcher icon and app icons using [AndroidAssetStudio][2]

## License
The code supplied here is covered under the MIT Open Source License.

[1]: https://github.com/HaarigerHarald/android-youtubeExtractor
[2]: https://romannurik.github.io/AndroidAssetStudio


text:
# convert_currency.py

This plugin sets an `entity_type`'s `to_currency_field`'s based on its
`from_currency_field`'s value and `exchange_rate_field`'s value when either:

1. `status_field` is updated to any Status, excluding those in `ignore_statuses`.
2. `exchange_rate_field`'s value is changed.
3. `from_currency_field`'s value is changed.

## Demo

![](images/convert_currency1.gif?raw=true)

## Args

| Arg name            | Type            | Description                                                                               |
| :-                  | :-              | :-                                                                                |
| entity_type         | String          | The type of `entity this` plugin acts on.                                                 |
| from_currency_field | String          | The field on `entity_type` to convert currency from.                                      |
| to_currency_field   | String          | The field on `entity_type` to convert currency to.                                        |
| exchange_rate_field | String          | The field on `entity_type` that stores the exchange rate used in the currency conversion. |
| status_field        | String          | The field on `entity_type` that activates this plugin.                                    |
| ignore_statuses     | List of Strings | A list of Status values on `status_field` that will be ignored.                           |

repository: shotgunsoftware/shotgunEvents

gha_language: Python

gha_license_id: NOASSERTION

repo_name: shotgunsoftware/shotgunEvents


text:
# [Apache Airavata](http://airavata.apache.org/)

Apache Airavata is a software framework for executing and managing computational jobs and workflows on distributed computing resources.
Airavata is dominantly used to build Web-based science gateways and assist to compose, manage, execute, and monitor large scale applications (wrapped as Web services) and workflows composed of these services.

This project is completed as a part of Google Summer of code 2013. The goal of the project is to create a GUI similar to XBaya suite for workflow composer,execution and monitoring.The purpose of this project is to replace the current UI for workflow execution with HTML, Javascript, css3 based UI.

## Quick start

Choose one of the following options:

## Features

## Documentation

## Contributing


text:
# Conformalized Quantile Regression

Python implementation of conformalized quantile regression [1] methodology.

Conformal prediction is a technique for constructing prediction intervals that attain valid coverage in finite samples, without making distributional assumptions. Despite this appeal, existing conformal methods can be unnecessarily conservative because they form intervals of constant or weakly varying length across the input space. **Conformalized quantile regression (CQR)** [1] is a new method that is fully adaptive to heteroscedasticity and often more efficient than other conformal methods. It combines conformal prediction with classical quantile regression, inheriting the advantages of both. CQR is also supported by a theoretical guarantee of valid coverage.

[1] Yaniv Romano, Evan Patterson, and Emmanuel J. Candes, [“Conformalized quantile regression.”](https://arxiv.org/abs/1905.03222) 2019.

## Getting Started

This package is self-contained and implemented in python.

Part of the code is a taken from the nonconformist package available at https://github.com/donlnz/nonconformist. One may refer to the nonconformist repository to view other applications of conformal prediction.

### Prerequisites

* python
* numpy
* scipy
* scikit-learn
* scikit-garden
* pytorch
* pandas

### Installing

The development version is available here on github:
```bash
git clone https://github.com/yromano/cqr.git
```

## Usage

Please refer to [real_data_example.ipynb](real_data_example.ipynb) for basic usage. Comparisons to competitive methods and additional usage examples of this package can be found in [synthetic_data_example.ipynb](synthetic_data_example.ipynb).

## Reproducible Research

The code available under /reproducible_experiments/ in the repository replicates the experimental results in [1].

### Publicly Available Datasets

* [Blog](https://archive.ics.uci.edu/ml/datasets/BlogFeedback): BlogFeedback data set.

* [Bio](https://archive.ics.uci.edu/ml/datasets/Physicochemical+Properties+of+Protein+Tertiary+Structure): Physicochemical  properties  of  protein  tertiary  structure  data  set.

* [Bike](https://archive.ics.uci.edu/ml/datasets/bike+sharing+dataset): Bike  sharing  dataset  data  set.

* [Community](http://archive.ics.uci.edu/ml/datasets/communities+and+crime): Communities   and   crime   data   set.

* [STAR](https://www.rdocumentation.org/packages/AER/versions/1.2-6/topics/STAR): C.M. Achilles, Helen Pate Bain, Fred Bellott, Jayne Boyd-Zaharias, Jeremy Finn, John Folger, John Johnston, and Elizabeth Word. Tennessee’s Student Teacher Achievement Ratio (STAR) project, 2008.

* [Concrete](http://archive.ics.uci.edu/ml/datasets/concrete+compressive+strength): Concrete compressive strength data set.

* [Facebook Variant 1 and Variant 2](https://archive.ics.uci.edu/ml/datasets/Facebook+Comment+Volume+Dataset): Facebook  comment  volume  data  set.

### Data subject to copyright/usage rules

The Medical Expenditure Panel Survey (MPES) data can be downloaded following [this explanation](https://github.com/IBM/AIF360/blob/master/aif360/data/raw/meps/README.md) provided in [IBM's AIF360](https://github.com/IBM/AIF360) github repository.

* [MEPS_19](https://meps.ahrq.gov/mepsweb/data_stats/download_data_files_detail.jsp?cboPufNumber=HC-181): Medical expenditure panel survey,  panel 19. The features and response are extracted using [meps_dataset_panel19_fy2015.py](https://github.com/IBM/AIF360/blob/master/aif360/datasets/meps_dataset_panel19_fy2015.py), **excluding** the threshold used to construct binary labels.

* [MEPS_20](https://meps.ahrq.gov/mepsweb/data_stats/download_data_files_detail.jsp?cboPufNumber=HC-181): Medical expenditure panel survey,  panel 20. The features and response are extracted using [meps_dataset_panel20_fy2015.py](https://github.com/IBM/AIF360/blob/master/aif360/datasets/meps_dataset_panel20_fy2015.py), **excluding** the threshold used to construct binary labels.

* [MEPS_21](https://meps.ahrq.gov/mepsweb/data_stats/download_data_files_detail.jsp?cboPufNumber=HC-192): Medical expenditure panel survey,  panel 21. The features and response are extracted using [meps_dataset_panel21_fy2016.py](https://github.com/IBM/AIF360/blob/master/aif360/datasets/meps_dataset_panel21_fy2016.py), **excluding** the threshold used to construct binary labels.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

repository: valeman/cqr

repo_name: valeman/cqr


text:
---
layout: default
---

# 1996-04-01 - Re: [NOISE] Cable-TV-Piracy-Punks (fwd)

## Header Data

From<EMAIL_ADDRESS>(Timothy C. May)

To: Jim Choate<EMAIL_ADDRESS>Message Hash: a99a181deb5be1ab1d3b9e13e84726f81413706eb0b31bc808ac45446e719958

Message ID<EMAIL_ADDRESS>Reply To: _N/A_

UTC Datetime: 1996-04-01 08:07:58 UTC

Raw Date: Mon, 1 Apr 1996 16:07:58 +0800

## Raw message

```
{% raw  %}From<EMAIL_ADDRESS>(Timothy C. May)
Date: Mon, 1 Apr 1996 16:07:58 +0800
To: Jim Choate<EMAIL_ADDRESS>Subject: Re: [NOISE] Cable-TV-Piracy-Punks (fwd)
Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text/plain

At 7:54 PM 3/31/96, Jim Choate wrote:
>Forwarded message:
>
>> > Presumedly the state of the EEPROM cannot be deduced by any
>> > external examination of the card, and any attempt to
>> > incrementally abrade the card down to the relevent circuit
>> > elements should completely obliterate the minute charge
>> > differences which represent the data.
>>
>> They aren't immune to the laws of physics. If it can be put together,
>> it can be taken apart. I can even surmise HOW it can be taken apart.
>
>You wouldn't even have to take it apart. Just subject it to analysis using
>SQUID's. Using this technology you would not even have to physicaly touch
>the card, let alone remove any parts of it.

Well, I worked on SQUIDs (Superconducting quantum-interferometric devices)
in 1972-3, and also worked on electron-beam analysis of microprocessors and
memory device in 1980-84, and I can assure you that SQUIDs cannot do what
you want them to do.

I'll be happy to supply additional details if there's sufficient interest.

--Tim May

Boycott "Big Brother Inside" software!
We got computers, we're tapping phone lines, we know that that ain't allowed.
---------:---------:---------:---------:---------:---------:---------:----
Timothy C. May              | Crypto Anarchy: encryption, digital money,
<EMAIL_ADDRESS>408-728-0152 | anonymous networks, digital pseudonyms, zero
W.A.S.T.E.: Corralitos, CA  | knowledge, reputations, information markets,
Higher Power: 2^756839 - 1  | black markets, collapse of governments.
"National borders aren't even speed bumps on the information superhighway."

{% endraw %}
```

## Thread

+ Return to [April 1996](/archive/1996/04)

+ Return to<EMAIL_ADDRESS>(Timothy C. May)](/authors/tcmay_at_got_net_timothy_c_may_)"

+ 1996-04-01 (Mon, 1 Apr 1996 16:07:58 +0800) - Re: [NOISE] Cable-TV-Piracy-Punks (fwd) -<EMAIL_ADDRESS>(Timothy C. May)_


text:
# Robots Parser

NodeJS robots.txt parser.

It currently supports:

  * User-agent:
  * Allow:
  * Disallow:
  * Sitemap:
  * Crawl-delay:
  * Host:
  * Paths with wildcards (*) and EOL matching ($)

## Installation

Via NPM:

    npm install npm install --save https://github.com/menno120/robots-parser

## Usage

```ts
import robotsParser from "robots-parser";

var robots = new Robots('http://www.example.com/robots.txt', [
	'User-agent: *',
	'Disallow: /dir/',
	'Disallow: /test.html',
	'Allow: /dir/test.html',
	'Allow: /test.html',
	'Crawl-delay: 1',
	'Sitemap: http://example.com/sitemap.xml',
	'Host: example.com'
].join('\n'));

robots.isAllowed('http://www.example.com/test.html', 'Sams-Bot/1.0'); // false
robots.isAllowed('http://www.example.com/dir/test.html', 'Sams-Bot/1.0'); // true
robots.isDisallowed('http://www.example.com/dir/test2.html', 'Sams-Bot/1.0'); // true
robots.getCrawlDelay('Sams-Bot/1.0'); // 1
robots.getSitemaps(); // ['http://example.com/sitemap.xml']
robots.getPreferedHost(); // example.com
```

### isAllowed(url, [ua])
**boolean or undefined**

Returns true if crawling the specified URL is allowed for the specified user-agent.

This will return `undefined` if the URL isn't valid for this robots.txt.

### isDisallowed(url, [ua])
**boolean or undefined**

Returns true if crawling the specified URL is not allowed for the specified user-agent.

This will return `undefined` if the URL isn't valid for this robots.txt.

### getMatchingLineNumber(url, [ua])
**number or undefined**

Returns the line number of the matching directive for the specified URL and user-agent if any.

Line numbers start at 1 and go up (1-based indexing).

Returns -1 if there is no matching directive. If a rule is manually added without a lineNumber then this will return undefined for that rule.

### getCrawlDelay([ua])
**number or undefined**

Returns the number of seconds the specified user-agent should wait between requests.

Returns undefined if no crawl delay has been specified for this user-agent.

### getSitemaps()
**array**

Returns an array of sitemap URLs specified by the `sitemap:` directive.

### getPreferredHost()
**string or null**

Returns the preferred host name specified by the `host:` directive or null if there isn't one.

# Changes

### Version 1.0.0:

 * Initial release.

# License

	The MIT License (MIT)

	Copyright (c) 2014 Sam Clarke

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	 IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.


text:
This playbook edits rules with unused applications or rules that are port based, and adds an application to the rule. It is used in PAN-OS - Policy Optimizer playbooks and includes communication tasks to get a rule name and the application to edit from the user.

## Dependencies
This playbook uses the following sub-playbooks, integrations, and scripts.

### Sub-playbooks
This playbook does not use any sub-playbooks.

### Integrations
This playbook does not use any integrations.

### Scripts
* SetAndHandleEmpty
* DeleteContext
* IsIntegrationAvailable

### Commands
panorama-edit-rule

## Playbook Inputs
---

| **Name** | **Description** | **Default Value** | **Required** |
| --- | --- | --- | --- |
| rules_list | PAN-OS rules to edit using the playbook. |  | Optional |

## Playbook Outputs
---

| **Path** | **Description** | **Type** |
| --- | --- | --- |
| RulesToEdit | Policy rules to edit using the playbook. | String |

## Playbook Image
---
![Policy Optimizer - Add Applications to Policy Rules](https://github.com/demisto/content/raw/82df056cff9dc4ce8b0753b341a4434593fa4608/Packs/PANOSPolicyOptimizer/doc_files/Policy_Optimizer_-_Add_Applications_to_Policy_Rules.png?raw=true)

repository: demisto/content

repo_name: demisto/content


text:
### New Culling Algorithm Idea

Make a "culling rectangle" class that keeps track of one rectangle of tiles. Something like this:

```lua
local culling = newCullingRectangle(layer)

culling.widthInTiles = numScreenTilesX -- Number of tiles to cull to
culling.heightInTiles = numScreenTilesY

culling.x = display.contentCenterX -- Position of the rectangle
culling.y = display.contentCenterY

culling.update() -- Erase and draw tiles as needed from previous position
```

Just an idea for the future. This could also enable users to keep tiles underneath enemies or other NPCs "alive".


text:
# selenium-ci

## Application Architecture

```
root
 └ log  //log and screenshot files are located in this folder.
 └ mockdata  //mockdata files to test are located in this folder.
 └ src
    └ common  //common function code are located in this folder.
    └ scenario  //unittest code are located in this folder.
 └ case1_xxxx.py  //your test code
 └ case2_yyyy.py  //your test code
 └ case3_zzzz.py  //your test code
```

## Dependent Packages

```
brew cask install chromedriver
conda install selenium
conda install pillow
conda install termcolor
conda install pyyaml
```

## How to use

### 1. prepare test data

you need to prepare your test data in the mockdata folder.
(reference. mockdata/case1_sample.yml)

### 2. code unittest

you need to prepare your unit test code in the root folder.
you can use functions of src/common/selenium.py
(reference. case1_sample.py)

### 3. execute Selinium Test

execute the following commond.
```
python3 ./case1_sample.py -v
```

### 4. check your log

check your test log in the log folder.

the following is sample.
log/seleniumci_20200925_054618_case1_sample/case1_sample.log
```
******************* SELENIUM TEST START : 20200925_054618 *******************

test_case01 (__main__.case1_sample) ... ok
test_case02 (__main__.case1_sample) ... ok
test_case03 (__main__.case1_sample) ... ok
test_case04 (__main__.case1_sample) ... ok
test_case05 (__main__.case1_sample) ... ok
test_case06 (__main__.case1_sample) ... ok
test_case07 (__main__.case1_sample) ... ok
test_case08 (__main__.case1_sample) ... ok
test_case09 (__main__.case1_sample) ... ok
test_case10 (__main__.case1_sample) ... ok
test_case11 (__main__.case1_sample) ... ok
test_case12 (__main__.case1_sample) ... ok
test_case13 (__main__.case1_sample) ... ok
test_case14 (__main__.case1_sample) ... ok
test_case15 (__main__.case1_sample) ... ok
test_case16 (__main__.case1_sample) ... ok
test_case17 (__main__.case1_sample) ... ok
test_case18 (__main__.case1_sample) ... ok
test_case19 (__main__.case1_sample) ... ok
test_case20 (__main__.case1_sample) ... ok
test_case21 (__main__.case1_sample) ... ok
test_case22 (__main__.case1_sample) ... ok
test_case23 (__main__.case1_sample) ... ok
test_case24 (__main__.case1_sample) ... ok
test_case25 (__main__.case1_sample) ... ok
test_case26 (__main__.case1_sample) ... ok
test_case27 (__main__.case1_sample) ... ok
test_case28 (__main__.case1_sample) ... ok
test_case29 (__main__.case1_sample) ... ok
test_case30 (__main__.case1_sample) ... ok
test_case31 (__main__.case1_sample) ... ok

----------------------------------------------------------------------
Ran 31 tests in 471.687s

OK
```


text:
# fromEvent

#### signature: `fromEvent(target: EventTargetLike, eventName: string, selector: function): Observable`

## Turn event into observable sequence.

### Examples

##### Example 1: Observable from mouse clicks

( [jsBin](http://jsbin.com/xikapewoqa/1/edit?js,console,output) |
[jsFiddle](https://jsfiddle.net/btroncone/vbLz1pdx/) )

```js
//create observable that emits click events
const source = Rx.Observable.fromEvent(document, 'click');
//map to string with given event timestamp
const example = source.map(event => `Event time: ${event.timeStamp}`);
//output (example): 'Event time: 7276.390000000001'
const subscribe = example.subscribe(val => console.log(val));
```

### Related Recipes

* [Smart Counter](../../recipes/smartcounter.md)

### Additional Resources

* [fromEvent](http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-fromEvent)
  :newspaper: - Official docs

---

> :file_folder: Source Code:
> [https://github.com/ReactiveX/rxjs/blob/master/src/internal/observable/FromEventObservable.ts](https://github.com/ReactiveX/rxjs/blob/master/src/internal/observable/FromEventObservable.ts)

repository: btiwaree/learn-rxjs

repo_name: btiwaree/learn-rxjs


text:
# API Documentation

## Installation
Install the package:
```
$ npm install --save react-expanding-textarea
```

## Usage
Use this exactly like you would a normal `<textarea>`; the only
difference is that it is doing some simple expanding work behind the scenes for you!
```js
import Textarea from 'react-expanding-textarea'

const MyTextarea = () => {
  const handleChange = useCallback(e => {
    console.log('Changed value to: ', e.target.value)
  }, [])

  return (
    <>
      <label for="my-textarea">
        Please Enter Some Details:
      </label>
      <Textarea
        className="textarea"
        defaultValue="Lorem ipsum dolor sit amet, ..."
        id="my-textarea"
        maxLength="3000"
        name="pet[notes]"
        onChange={handleChange}
        placeholder="Enter additional notes..."
      />
    </>
  )
}
```

### `rows`
If you pass a `rows` prop, then this component will perform a calculation based
on computed `lineHeight`, `borderTopWidth`, `borderBottomWidth`, `paddingTop`
and `paddingBottom` to deduce what the minimum height-in-rows the component
should be.

license: ISC

repository: raunofreiberg/react-expanding-textarea

gha_license_id: ISC

repo_name: raunofreiberg/react-expanding-textarea


text:
# Aircraft separation

## General Separation

While in flight if there is not a more specific rule which applies
then aircraft must be separated by at least 3nm laterally or 1000 feet
vertically.  No separation incidents are registered for aircraft in
their first minute of flight.

A notice will occur for aircraft which do not have sufficient vertical
separation and are within 1nm of the applicable separation minimum
(usually 3nm).

Collisions occur when an aircraft is within approximately 160 feet of
another aircraft. At this time, aircraft on the ground are immune to
collisions.

## Diverging courses

Aircraft may approach closer if they are on courses which differ by at
least 15 degrees and one aircraft has passed the point where the
courses intersect.  If the headings differ by more than 165 degrees,
then the aircraft may approach closer once the distance between them
is increasing.

## Opposite direction runway usage

A warning will be issued if two aircraft within 6 miles of each other
are using the same runway from different ends (by checking heading).

## Reduced lateral separation during runway approach

Aircraft "established" on the localizer of an Instrument Landing System
(ILS) are often eligible for reduced separation minima from other aircraft
on adjacent final approach courses. Aircraft are considered to be fully
"established" when they are laterally within 160 feet of the final
approach course. At this point, the lower lateral separation requirements
will be applied, allowing the aircraft to go under 3nm separation, all the
way down to the appropriate value (depends on distance between runway
centerlines):

  Reduced Separation on Adjacent Final Approach Courses
  See FAA JO 7110.65, para. 5-9-6

  | Dist btwn ctrln (ft) | Separation Minima  |
  |:--------------------:|:------------------:|
  | < 2,500'             | Standard Sep (3nm) |
  | 2,500' --> 3,600'    | 1.0 nautical mile  |
  | 3,601' --> 4,300'    | 1.5 nautical miles |
  | 4,301' --> 9,000'    | 2.0 nautical miles |
  | > 9,000'             | Standard Sep (3nm) |

repository: openscope/openscope

branch_name: refs/heads/develop

gha_language: JavaScript

repo_name: openscope/openscope


text:
---
author: Arun Bhai
date: '2008-08-30 23:13:54'
layout: post
slug: workaround-to-easy-install-pil-on-windows
status: publish
tags: [python, django]
title: Workaround to Easy Install PIL on Windows
wordpress_id: '133'
---

This is a quick workaround for people who are using [easy_install](http://peak.telecommunity.com/DevCenter/EasyInstall) to install Python Imaging Library on Windows. Many people faced issues while doing this. I found a simple workaround for this.

You must have tried the following

    C:> easy_install PIL
    Searching for PIL
    ...
    Finished processing dependencies for PIL
    C:> python
    Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on
    win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import Image
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ImportError: No module named Image

Now you will need to go to your site-packages directory (typically at C:\Python\Lib\site-packages) and change one line that starts with `./PIL-1.1.6-py2.5-win32.egg` to simply `./PIL` and change the sub-directory named similarly to `PIL`

Now your imports should work :smile:

repository: patilswapnilv/arunrocks

extension: markdown

repo_name: patilswapnilv/arunrocks


text:
# Custom request settings

- [Curl options](#curl-options)
- [Client info](#client-info)
- [Current url](#current-url)
- [Visit page](#visit-page)

## Curl options

It is possible to add some additional Curl options for bot requests. For example, you can
set proxy and User Agent like this:

```php
$bot->getHttpClient()->setOptions([
    CURLOPT_PROXY => 'xx.xx.xxx.xx:xxxx',
    CURLOPT_PROXYTYPE => CURLPROXY_HTTP // Or CURLPROXY_SOCKS5,
    CURLOPT_USERAGENT => 'Your_User_Agent',
]);
```

## Client info

With every request Pinterest returns an array with your current client info, with such info as
OS, browser, IP and others:

```php
$info = $bot->getClientInfo();
```

By default it uses client info from the last request. To reload client context pass `true` argument:

```php
// Force to reload client info
$info = $bot->getClientInfo(true);
```

## Current url

You can get an url of the last visited page:
```php
$url = $bot->getHttpClient()->getCurrentUrl();
```

## Visit page

Visit (click) a link. For example, when Pinterest sends you email with some link, and you want bot to visit it:
```
$bot->user->visitPage($url);
```

repository: tuxado/php-pinterest-bot

repo_name: tuxado/php-pinterest-bot


text:
## Anxious in Brooklyn
A blog about overcoming anxiety in New York through action, powered by [Gatsby]https://www.gatsbyjs.com/)

**Running in development**
`gatsby develop`

**Content**
All content is hosted on [Contentful](https://www.contentful.com/).
After updating content, you must restart the Gatsby server in order to see changes.

**Deploying**
Deploying through [Netlify](https://www.netlify.com/) by pushing to master.

repository: knittingarch/AnxiousInBrooklyn

repo_name: knittingarch/AnxiousInBrooklyn


text:
# TacoDNS

Developer-friendly authoritative DNS server written in Rust.

[Original repository: https://gitlab.com/chris13524/tacodns/-/tree/master](https://gitlab.com/chris13524/tacodns/-/tree/master)

## Example

### Docker Compose

```
version: "3.7"
services:
  tacodns:
    restart: always
    image: handz/tacodns
    ports:
      - 53:53/udp
      - 53:53/tcp
    command: --config-env TACODNS
    environment:
      TACODNS: |
        ttl: 30m
        zones:
          example.com:
            A: <IP_ADDRESS>
```

### Cargo

```
cat >tacodns.yml <<EOF
ttl: 30m
zones:
  example.com:
    A: <IP_ADDRESS>
EOF

cargo run -- --config tacodns.yml
```

## Usage

See `config.example.yml` and `tacodns --help`.

## Features

  - Configuration is done via YAML format. No more of those ugly
    BIND-style zone files!
  - Supports ANAME/ALIAS records.
  - Supports more advanced matching than regular DNS wildcards such as
    single, double, and triple wildcards, regular expressions, and
    fall-though zones.
  - RNS (Recursive NS) record: TacoDNS queries another DNS server for
    the results. Supports record types that TacoDNS does not.
  - TRPP (TacoDNS Record Provider Protocol) record: TacoDNS will query
    a JSON HTTP server for the results
    (e.g. [TacoDNS ACME](https://gitlab.com/chris13524/tacodns-acme)).
    Only supports A, AAAA, MX, and TXT records.

### Supported record types

  - A
  - AAAA
  - MX
  - TXT
  - NS
  - CNAME & ANAME

Unsupported types can be provided by an upstream DNS server connected via RNS.

### Planned features

  - SRV records
  - CAA records
  - DNSSEC
  - environment variables in config
  - URL records (resolves address records to itself and does HTTP redirect)

## Spec compliance

This server is mostly spec compliant. There are some semantic cases
where this server isn't fully compliant, but I haven't encountered any
actual real-world problems with them. TacoDNS has production usage at
chris.smith.xyz and fathomstudio.com.

Known incompatibilities:

  - does not support BIND-style zone files
  - does not support zone transfers or master/slave
  - never returns NXDOMAIN, only empty NOERROR's (functional requirement
    due to powerful fall-though nature of TacoDNS zones)
  - SOA record is generated for every request, and may not be accurate
  - EDNS compliance: https://ednscomp.isc.org/ednscomp/cf51805c31

repository: HANDZCZ/tacodns

repo_name: HANDZCZ/tacodns


text:
---
layout: post
title:      "React State and how to best update it"
date:       2021-08-29 23:03:33 +0000
permalink:  react_state_and_how_to_best_update_it
---

React is a component-based user interface library. This means that a React application consists of a set of components that forms a tree with a root and child components.

More often than not, React components will have state. State is a plain JavaScript object which holds information that affects the output of the render() method, i.e what is displayed on the screen. It can be formed of variables that contain things like whether a user is logged in or not, or an array of posts, or a count of some kind.

The state is managed within the component and is initialized in the constructor. Once state is initialized, it should only be updated using the setState() method.

Before we get into the next part, a quick note about JavaScript.

JavaScript, at its base, is a Synchronous, blocking, single-threaded language. This means that only one thing can happen at a time, on a single main thread, and everything else is blocked until an operation completes.

**Spoiler: State Updates May Be Asynchronous.**

React batches multiple setState() calls into a single update for performance. This is because setState alters the state and causes rerendering. This can be an expensive operation and making it synchronous might leave the browser unresponsive. And we don’t want our users staring at an empty page while waiting for our code to finish running.

Thus the setState calls are asynchronous as well as batched for better UI experience and performance.

Because this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

Take this code for example:

```
state = {
   count: 0
}

updateCount = () => {
   this.setState({ count: this.state.count + 1});
   this.setState({ count: this.state.count + 1});
   this.setState({ count: this.state.count + 1});
   this.setState({ count: this.state.count + 1});
}
```

Since there are multiple setState calls, React will batch all those calls and updates the state only in the last call of setState, so at the time of last call to setState this.state.count is not yet updated and its value is still the same as it was before entering into the method so the resulting state will contain count incremented by 1.

To fix this, we can use a second form of setState() that accepts a function rather than an object. That function will receive the previous state as an argument.

```
state = {
   count: 0
}

updateCount = () => {
   this.setState(prevState => ({ count: prevState.count + 1}));
   this.setState(prevState => ({ count: prevState.count + 1}));
   this.setState(prevState => ({ count: prevState.count + 1}));
   this.setState(prevState => ({ count: prevState.count + 1}));
}
```

React will again batch all those calls and update the state only in the last call of setState, however in this example, the prevState will always contain the modified state in the recent setState call. As prevState.count value has already been incremented 3 times by the last call of setState, the resultant state will contain the count value incremented by 4.

What is the difference between passing an object or a function in setState?

Passing an update function allows you to access the current state value inside the updater. Since setState calls are batched, this lets you chain updates and ensure they build on top of each other instead of conflicting.


text:
  Stalla

	Podcast RSS Feed metadata Parser and Writer

[![](https://img.shields.io/maven-central/v/dev.stalla/stalla)](https://package-search.jetbrains.com/package?id=dev.stalla%3Astalla)
![GitHub Workflow Status](https://img.shields.io/github/workflow/status/mpgirro/stalla/Buildbot)
[![Coverage Status](https://coveralls.io/repos/github/mpgirro/stalla/badge.svg?branch=master)](https://coveralls.io/github/mpgirro/stalla?branch=master)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/66d3c5df2fbf4c9aaabe66e52a847cdd)](https://www.codacy.com/app/mpgirro/stalla?utm_source=github.com&utm_medium=referral&utm_content=mpgirro/stalla&utm_campaign=Badge_Grade)

An RSS 2.0 feed parser and writer library for Podcast metadata on the JVM. This library is written in Kotlin and has a Java-friendly API.

## Supported standards

- [RSS 2.0](http://www.rssboard.org/rss-2-0)
- [Atom](https://tools.ietf.org/html/rfc4287) (RFC 4287) – selected elements, no feed support
- [iTunes](https://help.apple.com/itc/podcasts_connect/#/itcb54353390) (Apple Podcast Connect)
- [Content](http://purl.org/rss/1.0/modules/content/) (RDF Site Summary 1.0 Module)
- [Podlove Simple Chapters](https://podlove.org/simple-chapters/)
- [Podcastindex.org v1](https://github.com/Podcastindex-org/podcast-namespace) ([example feed](https://github.com/Podcastindex-org/podcast-namespace/blob/main/example.xml))
- [Google Play](https://developers.google.com/search/reference/podcast/rss-feed)
- [Feedpress](https://feed.press/xmlns)
- Bitlove
- Fyyd

Scheduled:

- [Podcastindex.org v2](https://github.com/Podcastindex-org/podcast-namespace)
  in #49 ([example feed](https://github.com/Podcastindex-org/podcast-namespace/blob/main/example.xml))
- [Spotify](https://drive.google.com/file/d/1KDY1zbRc6J2tkNvhniagor_qcH-pp2T0/view) in #29
- [Dublin Core](http://purl.org/dc/elements/1.1/) ([RFC 5013](https://tools.ietf.org/html/rfc5013)) in #28 – properties in the `/elements/1.1/`
  namespace
- [Media RSS](http://www.rssboard.org/media-rss) in #30 ([example feed](https://gist.github.com/misener/7dd9b587b468aea1ae5a))

Feel free to open an issue if Stalla is missing support for a relevant namespace.

## Usage

### Distribution

Stalla is distributed via [Maven Central](https://search.maven.org/search?q=g:dev.stalla%20AND%20a:stalla).

Maven:

```
<dependency>
  <groupId>dev.stalla</groupId>
  <artifactId>stalla</artifactId>
  <version>1.0.0</version>
</dependency>
```

Gradle Kotlin DSL:

```
implementation("dev.stalla:stalla:1.0.0")
```

### Parsing an RSS feed

To parse an RSS feed, you need to use the [`PodcastRssParser`](src/main/kotlin/dev/stalla/PodcastRssParser.kt) object. Parsing an RSS feed is as easy
as picking the overload of `parse()` that fits your needs:

```kotlin
val rssFeedFile = File("/my/path/rss.xml")
val podcast = PodcastRssParser.parse(rssFeedFile)
```

The `parse()` function will return a parsed `Podcast?`, which may be `null` if parsing was unsuccessful. It will also throw an exception if parsing
fails catastrophically (e.g., the source is a `File` that doesn't exist).

In Java, all overloads of `parse()` are available as static methods.

### Writing an RSS feed

To write an RSS feed, you need to use the [`PodcastRssWriter`](src/main/kotlin/dev/stalla/PodcastRssWriter.kt) object. Writing an RSS feed is as easy
as picking the overload of `write()` that fits your needs:

```kotlin
val rssFeedFile = File("/my/path/rss.xml")
val podcast: Podcast = // ...
  PodcastRssWriter.writeRssFeed(podcast, rssFeedFile)
```

The `write()` function will throw an exception if writing fails for whatever reason.

In Java, all overloads of `write()` are available as static methods.

### Data model

The two central entities in Stalla's entire data model are [`Podcast`](src/main/kotlin/dev/stalla/model/Podcast.kt) (abstracting the RSS `<channel>`)
and [`Episode`](src/main/kotlin/dev/stalla/model/Episode.kt) (abstracting an RSS `<item>`).

#### Model construction in Kotlin

All model types are Kotlin [data classes](https://kotlinlang.org/docs/data-classes.html). Their properties are always un-reassignable (`val`), and the
constructors have default values for optional fields (`null`) and lists (`emptyList()`).

```kotlin
val someEpisode: Episode = // ...
val podcast = Podcast(
  title = "The Stalla Show",
  description = "A show about Stalla development",
  link = "https://stalla.dev/podcast",
  language = Locale.ENGLISH,
  episodes = listOf(firstEpisode)
)
```

#### Model construction in Java

⚠ Direct instantiation of model class objects is discouraged in Java.

The Java language does not provide named arguments. Some of Stalla's model classes take huge parameter lists. To mitigate this limitation, every model
class provides a static `builder()` method that returns a builder instance enabling expressive construction in Java.

```java
Episode someEpisode = // ...
Podcast podcast = Podcast.builder()
  .title("The Stalla Show")
  .description("A show about Stalla development")
  .link("https://stalla.dev/podcast")
  .language(Locale.ENGLISH)
  .addEpisodeBuilder(firstEpisode)
  .build();
```

Note that builders validate lazily upon calling `build()`, i.e., the constructed model instance may be `null` if:

* Not all required constructor properties of the backing data class have been initialized in the builder (technical requirement by the type system).
* Not all mandatory information bas been provided with respect to the backing specification (RSS or other XML namespace). For example, a
  [`Podcast`](src/main/kotlin/dev/stalla/model/Podcast.kt) needs at least one [`Episode`](src/main/kotlin/dev/stalla/model/Episode.kt) (i.e. one
  `<item>` within the `<channel>`), so while technically an empty list satisfies the technical requirement (required to be not `null`), it however
  violates the logical requirement (at least one element).

#### Enumerated types

The supported XML namespaces declare several elements that only accept a finite set of predefined values. In Stalla, these values are usually modeled
via enum classes (e.g., [`GoogleplayCategory`](src/main/kotlin/dev/stalla/model/googleplay/GoogleplayCategory.kt) or
[`TranscriptType`](src/main/kotlin/dev/stalla/model/podcastindex/TranscriptType.kt)). However, some elements, like the Categories of the iTunes
namespace, have a more complex structure (i.e., a hierarchy) that cannot be modeled via enums. These types still try to provide an interface that is
close to that of enums for consistent usage. For example, [`ItunesCategory`](src/main/kotlin/dev/stalla/model/itunes/ItunesCategory.kt) exposes all
possible values as members of the companion object (Kotlin) or as static class members (Java).

Note that the instances exposed by [`MediaType`](src/main/kotlin/dev/stalla/model/MediaType.kt) are not the finite set of possible values, but only
predefined instances for convenience.

### Convenience features

#### Builder factory: builder() method

All model classes expose a `builder()` method as a member of the companion object (Kotlin) or as a static class method (Java). These methods return an
implementation of the respective model classes builder interface. The [builder pattern](https://en.wikipedia.org/wiki/Builder_pattern) enables
expressive object construction using named attribute initializers, and compensate for the lack of named constructor arguments in the Java language.

#### Builder mutation: applyFrom() method

All builders expose an `applyFrom(model)` method that takes an instance of the builder's model class as argument, and returns the builder instance. The
method applies all values of the provided model to the builder's state. This is therefore a mutating operation. The returned builder instance is the
mutated state of the builder on which the `applyFrom` method is called, and not a new instance. The operation does not result in any structural
sharing, e.g., references of lists, etc.

The generic use case of this method is the convenient construction of a new model object based on the properties of an existing model instance:

```java
Episode oldEpisode = // ...
Episode newEpisode = Episode.builder()
  .applyFrom(oldEpisode)
  .title("The latest episode")
  .build();
```

In Kotlin, you can also use the `copy()` method exposed by all data classes to obtain a new model instance with some of its properties mutated.

#### Type factory: of() method

All enumerated types expose an `of(String)` method as a member of the companion object (Kotlin) or as a static class method (Java). This method is a
factory and produces an instance of the type if possible, otherwise `null`. In contrast to the enum classes' `valueOf()` standard method, `of()` is
case-insensitive and also available for non-enum class enumerated types (e.g.,
[`ItunesCategory`](src/main/kotlin/dev/stalla/model/itunes/ItunesCategory.kt)).

Additionally, Stalla has some types that validate a string for certain patterns, e.g. [`MediaType`](src/main/kotlin/dev/stalla/model/MediaType.kt)
models media types as defined by [RFC 2046](https://tools.ietf.org/html/rfc2046), and
[`StyledDuration`](src/main/kotlin/dev/stalla/model/StyledDuration.kt) describes values in several supported time formats (`14:02:56` or `5:23` or
`33.833`). These types also provide the `of()` method as the only means to obtain an instance of the class.

### Generate the documentation

The project uses [Dokka](https://github.com/Kotlin/dokka) to generate its documentation from the KDoc comments in the code. If you want to generate a
fresh version of the documentation, use one of the Dokka Gradle tasks:

```bash
$ ./gradlew dokkaHtml
$ ./gradlew dokkaJavadoc
$ ./gradlew dokkaGfm
$ ./gradlew dokkaJekyll
```

## License

Stalla is released under the [BSD 3-clause license](LICENSE).

repository: mpgirro/stalla

gha_language: Kotlin

repo_name: mpgirro/stalla


text:
# Noop UI

The name has nothing to do with the theme, other than I am a fan of Rick and Morty. A pretty basic theme built from the [Atom Template](https://github.com/atom-community/ui-theme-template)

![preview](https://triangle.black/img/hyperui.png)

repository: gvost/noop-ui

repo_name: gvost/noop-ui


text:
```toml
[advisory]
id = "RUSTSEC-2020-0032"
package = "alpm-rs"
aliases = ["CVE-2020-35885"]
date = "2020-08-20"
informational = "unsound"
url = "https://github.com/pigeonhands/rust-arch/issues/2"

[versions]
patched = []
```

# StrcCtx deallocates a memory region that it doesn't own

`StrcCtx` deallocate a memory region that it doesn't own when `StrcCtx` is created without using `StrcCtx::new`.
This can introduce memory safety issues such as double-free and use-after-free to client programs.

repository: BurntSushi/advisory-db

repo_name: BurntSushi/advisory-db


text:
# inventorforge [![Build Status](https://travis-ci.org/InventorForgeMakerspace/inventorforge.svg?branch=master)](https://travis-ci.org/InventorForgeMakerspace/inventorforge)
InventorForge App

## To Build

1. Install dependencies

```bash
npm install -g ionic@beta
npm install -g typings
npm install -g gulp-cli
npm install
typings install
```

2. Build

```bash
ionic build
gulp compile-server
```

3. Serve

### Ionic client

```bash
ionic serve
```

### Node server

```bash
gulp server
```

## Running (non-development)

1. Start the server

```bash
node server/server.js
```

3. Access the page

(http://localhost:8080/index.html)

## Configuration

The main configuration is stored in the configuration files in the `config/`
directory. Which file is used depends on the value of the `NODE_ENV` environment
variable. (i.e. setting `NODE_ENV` to "production" uses the `production.json` file.
The default environment is "development".

Configuration can also be specified via command line argument or environment
variables.  See
[nconf](https://www.npmjs.com/package/nconf) for information on how these are
set.

Note: By default `serial:disable` is set to `true` in development.  To use on a
sign locally, this must be set to false and `serial:port` and other options set
appropriately.

repository: InventorForgeMakerspace/inventorforge

repo_name: InventorForgeMakerspace/inventorforge


text:
# SoundManager

Sound handle.

## Functions

| Name | Description |
|:---|:---|
| switchBGMByName | Play the background music by resource name. |
| switchBGMBySound | Play the background music by sound itself. |
| playOneShotByNames | Play one shot the sound by using the resource name. |
| playOneShotBySound | Play one shot the sound by using the sound itself. |
| setBGMFadeInTime | Set the background music fade in time. |
| setBGMFadeOutTime | Set the backgroun music fade out time. |
| setBGMVolume | Set the background music volume. |
| getBGMVolume | Returns the background music's sound channel's volume. |


text:
# pass-muster

Objects work well as a single argument to a function. That way you don't have to remember the order of parameters, and your code gets a nice self-documenting look. `passMuster` lets you be a little more sure of those objects that you pass as an argument to functions by validating that the properties you need are there and of the right types. Think of it as a lightweight implementation of interfaces.

Of course, this isn't limited to validating objects passed as arguments. Use it wherever you want to make sure an object has what you need.

The module is written in good ol' ES5, so it works everywhere.

## Usage

```js
myFunction(opts) {
    passMuster(opts, {
        id: 'number',
        username: 'string'
    });
    // do something with opts object
}

myFunction({
    id: 007,
    username: 'jbond'
})
// --> no error thrown, myFunction continues
```

If `myFunction` is called without a required property, `passMuster` will throw an error:

```js
myFunction({
    id: 007
})
// --> "missing property 'username'"
```

It will also throw an error if the property is not the right type:

```js
myFunction({
    id: 007
    username: 12345
})
// --> "property 'username' has wrong type"
```

An array of possible types can be supplied:

```js
let objToValidate = {
    prop: 'test'
}
passMuster(objToValidate, {
    prop: ['string', 'number']
});
// --> no error

passMuster(objToValidate, {
    prop: ['array', 'object']
});
// --> "property 'prop' not one of allowed types"
```

If you have further validation you want to do, a predicate function that returns `true` or `false` can be passed in:

```js
let objToValidate = {
    num: 11
}
passMuster(objToValidate, {
    num: p => (p < 100)
});
// --> no error

passMuster(objToValidate, {
    num: p => (p % 2 === 0)
});
// --> "property 'num' does not pass predicate function"

let alsoValidate = {
    buf: new Buffer(2)
}
passMuster(alsoValidate, {
    buf: _.isBuffer // <-- using lodash
});
// --> no error
```

Predicate functions are executed in the context of the type object, so you can reference the expected type of other properties:

```js
let objToValidate = {
    otherProp: 'foobar',
    num: 11
}
passMuster(objToValidate, {
    otherProp: 'string',
    num: p => (typeof p !== this.otherProp)
});
// --> no error
```

If you need to reference the other values passed in, the object being validated is passed as a second argument to predicate functions:

```js
let objToValidate = {
    otherProp: 'foobar',
    num: 11
}
passMuster(objToValidate, {
    otherProp: 'string',
    num: (p, objIn) => is.not.sameType(p, objIn.otherProp) // <-- using @pwn/is, linked below
});
// --> no error
```

Nested objects also work:

```js
 myFunction(opts) {
    passMuster(opts, {
        id: 'number',
        address: {
            street: 'string',
            city: 'string',
            state: 'string',
            zip: 'number'
        }
    });
    // do something with opts object
}

myFunction({
    id: 007,
    address: {
        street: '123 anywhere st',
        city: 'Los Angeles',
        state: 'CA'
    }
})
// --> "missing property 'zip'"
```

To mark a property as optional, put it in the special `_optional` block:

```js
myFunction(opts) {
    passMuster(opts, {
        id: 'number',
        _optional: {
            username: 'string'
        }
    })
    // do something with opts object
}

myFunction({
    id: 007
})
// --> no error

myFunction({
    id: 007,
    username: 12345
})
// --> "property 'username' has wrong type"
```

To see the function from which you called `passMuster`, just look at the stack trace on the error that gets thrown.

## See also

* [joi](https://github.com/hapijs/joi)
* [obey](https://github.com/TechnologyAdvice/obey)
* [is.js](https://github.com/pwnn/is.js) (see `is.conforms`)
* [rfx](https://github.com/ericelliott/rfx)
* [validator.js](https://github.com/chriso/validator.js)
* [io-ts](https://github.com/gcanti/io-ts)
* [superstruct](https://github.com/ianstormtaylor/superstruct)
* [yup](https://github.com/jquense/yup)

## License

MIT

repository: rebolyte/pass-muster

repo_name: rebolyte/pass-muster


text:
## Typed Forms migration

As of Angular v14, the `AbstractControl` classes and `FormBuilder` methods have generic type parameters. Angular provides `Untyped` versions of the classes for opt-out. This migration:
- Identifies imports of these classes, and also imports the untyped versions.
- At all constructor sites, the typed symbol is replaced with the corresponding untyped symbol.

This migration is idempotent, i.e. it will not add duplicate imports that were added in a previous run. This migration also accounts for qualified imports, and will replace them as needed.

#### Before
```ts
import { Component } from '@angular/core';
import { AbstractControl, FormArray, FormBuilder, FormControl as FC, FormGroup, UntypedFormGroup } from '@angular/forms';

@Component({template: ''})
export class MyComponent {
  private _control = new FC(42);
  private _group = new FormGroup({});
  private _array = new FormArray([]);
  private _ungroup = new FormGroup({});

  private fb = new FormBuilder();

  build() {
    const c = this.fb.control(42);
    const g = this.fb.group({one: this.fb.control('')});
    const a = this.fb.array([42]);
    const fc2 = new FC(0);
  }
}
```

#### After
```ts
import { Component } from '@angular/core';
import { AbstractControl, FormArray, UntypedFormArray, FormBuilder, UntypedFormBuilder, FormControl as FC, UntypedFormControl, FormGroup, UntypedFormGroup } from '@angular/forms';

@Component({template: ''})
export class MyComponent {
  private _control = new UntypedFormControl(42);
  private _group = new UntypedFormGroup({});
  private _array = new UntypedFormArray([]);
  private _ungroup = new UntypedFormGroup({});

  private fb = new UntypedFormBuilder();

  build() {
    const c = this.fb.control(42);
    const g = this.fb.group({one: this.fb.control('')});
    const a = this.fb.array([42]);
    const fc2 = new UntypedFormControl(0);
  }
}
```

repository: gkalpak/angular

gha_language: TypeScript

repo_name: gkalpak/angular


text:
# Level
When you **have downtime (hours or days) and XP equal to (or greater than) your current level+7**, you can reflect on your experiences and hone your skills.

 - Subtract your current level+7 from your XP.
 - Increase your level by 1.
 - Choose a new advanced move from your class.
 - If you are the wizard, you also get to add a new spell to your spellbook.
 - Choose one of your stats and increase it by 1 (this may change your modifier). Changing your Constitution increases your maximum and current HP. Ability scores can’t go higher than 18.

repository: Vindexus/DungeonWorldData

repo_name: Vindexus/DungeonWorldData


text:
# patt-c

This repository provides data and code for reproducing ["Estimating population average treatment effects from experiments with noncompliance"](https://arxiv.org/abs/1901.02991).

Please cite the paper if you use this code for academic research:

```
@ARTICLE{2019arXiv190102991O,
       author = {{Ottoboni}, Kellie and {Poulos}, Jason},
        title = "{Estimating population average treatment effects from experiments with noncompliance}",
      journal = {arXiv e-prints},
     keywords = {Statistics - Methodology, Economics - Econometrics, Statistics - Applications},
         year = "2019",
        month = "Jan",
          eid = {arXiv:1901.02991},
        pages = {arXiv:1901.02991},
archivePrefix = {arXiv},
       eprint = {1901.02991},
 primaryClass = {stat.ME},
       adsurl = {https://ui.adsabs.harvard.edu/abs/2019arXiv190102991O},
      adsnote = {Provided by the SAO/NASA Astrophysics Data System}
}
```
Description of scripts in code/
------
* `package-list.R` install required packages
* `main.R` main run list
  * `main.sh` shell script for main.R
* `simulation.R` runs simulations and produces `results/simulation_res.Rdata`
* `simulation-plots.R` loads `results/simulation_res.Rdata` and saves to `plots/`
* `prepare-ohie.R` merges OHIE data and saves to `data/prepare-ohie.Rdata`
 `prepare-NHIS.R` merges NHIS data and saves to `data/prepare-NHIS.Rdata`
* `prepare-analysis.R` imports NHIS and OHIE datasets and creates outcome vectors and common covariates for the analysis; saves to `data/prepare-analysis.Rdata`
* `analysis.R` produces empirical estimates; change `run.model` to TRUE to train complier and response models; saves to `data/analysis.Rdata`
  * `SuperLearner.R` Super learner helper functions
  * `complier-mod.R` Fit complier model if `run.model` is TRUE
  * `complier-mod-cv.R` Cross-validate accuracy of complier model if `run.model` is TRUE
  * `response-mod.R` Fit response models if `run.model` is TRUE
  * `wtc.R` function for weighted t-test with cluster-bootstrapped SEs
 * `rct-nrt-compare.R` produce estimates for Tables A1 and A2
 * `estimator-compare-plots.R` saves heterogeneous treatment effect estimates to `plots/`
 * `placebo-test.R` produce estimates for Table A3

Instructions
------
* Clone a copy of the repository to your working directory with the command
```
$ git clone https://github.com/jvpoulos/patt-c
```
* The code uses **R** version 3.5.2 (2018-12-20). To install this **R** version on Ubuntu, use the command
```
$ sudo apt-get install r-base-core=3.5.2-1xenial
```
* Download and extract pretrained response models to `results/` directory:
  * [response-mod.tar.xz](https://www.dropbox.com/s/d53jcpj9vbo0tex/response-mod.tar.xz?dl=1)
  * [response-mod-patt.tar.xz](https://www.dropbox.com/s/srgvn4oa2ugmf8p/response-mod-patt.tar.xz?dl=1)
* Open `package-list.R` in a script editor
  * Verify that all required packages in `package-list.R`are installed in your **R** library
* Open `main.R` in a script editor
  * Change the file path specified by `repo.directory` to your working directory
  * Change `patient.simulation` to TRUE to run simulation
  * Save your changes to `main.R`
* Make shell file `main.sh` executable from the Linux/Unix command line:
```
$ chmod +x main.sh
```
* Execute the file:
```
$ ./main.sh > main.txt
```

repository: jvpoulos/patt-c

repo_name: jvpoulos/patt-c


text:
# Dependencies
* Ruby (2.1.0+)
* Bundle

# Setup
* Clone this repository with Git. Run
  `git clone https://github.com/aileenzeng/aileenzeng.github.io.git`
* Run `bundle install` in the root directory to get dependencies.

# Local Testing
* Run `bundle exec jekyll serve`. This starts the local server and watches for changes in the
  website.
* Run `jekyll build` if there are any changes to `_config.yml`. Changes to the config file do not
  automatically show up on the local server and will need to be manually updated. You will need to
  restart the local server after building.
* Open `http://<IP_ADDRESS>:4000/` in your web browser.

If all goes correctly, your terminal should look something like this:
```
aileen$ bundle exec jekyll serve

( some messages... )

Server address: http://<IP_ADDRESS>:4000/
Server running... press ctrl-c to stop.
```

# Misc
## Killing a process at a port
Sometimes you won't be able to start the website because port 4000 will already be in use.


text:
# Example: Gulpfile.js in ES6
A example of how to write gulp files (gulpfile.js) in ES6.

## Getting Started

You will first need to install [gulp](https://github.com/gulpjs/gulp) globally if you
dont already have it installed.

```bash
npm install -g gulp
```

Next, install the required npm packages to run the sample.

```bash
npm install
```

Finally, you can run gulp and validate that it all works.

```bash
gulp
```


text:
### [CVE-2019-16521](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-16521)
![](https://img.shields.io/static/v1?label=Product&message=n%2Fa&color=blue)
![](https://img.shields.io/static/v1?label=Version&message=n%2Fa&color=blue)
![](https://img.shields.io/static/v1?label=Vulnerability&message=n%2Fa&color=brighgreen)

### Description

The broken-link-checker plugin through 1.11.8 for WordPress (aka Broken Link Checker) is susceptible to Reflected XSS due to improper encoding and insertion of an HTTP GET parameter into HTML. The filter function on the page listing all detected broken links can be exploited by providing an XSS payload in the s_filter GET parameter in a filter_id=search request. NOTE: this is an end-of-life product.

### POC

#### Reference
- http://www.openwall.com/lists/oss-security/2019/10/16/3
- https://github.com/sbaresearch/advisories/tree/public/2019/SBA-ADV-20190913-02_WordPress_Plugin_Broken_Link_Checker
- https://wpvulndb.com/vulnerabilities/9917

#### Github
No PoCs found on GitHub currently.

repository: trickest/cve

gha_language: HTML

repo_name: trickest/cve


text:
# website

[![Build Status](https://travis-ci.org/neon-bindings/website.svg?branch=master)](https://travis-ci.org/neon-bindings/website)

The website and docs for [neon](https://github.com/neon-bindings/neon)

## Setup

```bash
git clone https://github.com/neon-bindings/website
cd website
yarn
yarn start

# Styles
yarn styles
yarn styles --watch
```

## Updating the Docs

```bash
git clone https://github.com/neon-bindings/neon
cd neon
cargo doc
cp -r target/doc ../website/static
mv ../website/static/docs ../website/static/api
rm -rf neon
```

repository: stoneG/website

repo_name: stoneG/website


text:
---
title: "My next project(s)"
date: "2015-07-16"
---

The last month, or so, has been quite hectic, but now that we have finally settled in, in our new apartment, I have time to start on my next project(s). I have several things lined up, and hopefully I’m able to set aside enough time to complete each project within reasonably time. It’s worth mentioning that these are all personal projects, not projects done at my job.

I will tell you a little bit about each project, and naturally I will give updates during development. I have not prioritized this, but the projects I have planned is the following:

1. A new cross-platform app
2. A project involving IoT
3. Increasing my skills as a developer The top priority now is none of the above. Before I go on to work on those, I need to finish the Android version of [Parker Gratis](http://parkergratis.no). I am aiming to do that within a week’s time. After that, I plan to do some marketing for it, to increase the user volume.

On to the list above.

**A new cross-platform app**

This is an idea I’ve had a few years, however I have not done any work on it for several reasons. Now I feel I have the skillset needed, as well as the right tools to develop it. The app will be an informational app to find the nearest vet from where you are. This can come in handy in case you are on a vacation with your pets, and the pet gets ill or injured. I guess the biggest part of the job is to gather all the data needed, and as a start, I will only include Norwegian vets. The app itself should be simple, and intuitive to the user, and hopefully it won’t take that long to develop.

**A project involving IoT**

![IoT illustration](/images/network-782707_1280.png)

IoT (Internet of Things) is a subject that have had my interest for a while. Seeing as I haven’t found any use for it, I haven’t worked with it though. Now that we have moved to a new apartment, I have seen an opportunity to use it for home automation. Our new apartment have been refurbished recently, and as a part of that, the previous owner installed wireless lights. My first thought was to use some sort of transmitter to control the lights by a webapp (or mobile app) in our local network, and from there new ideas came to my head.

For now I have the following list of stuff I want to automate:

1. Monitor lights in all the rooms, to check whether or not they are on.
2. Controlling the lights in the rooms where they are wireless.
3. Humidity monitoring in the basement.
4. Temperature monitoring in all rooms
5. Monitoring the mailbox to check if we have mail or not.
6. Monitor on the fridge, so we get warnings if the door has been open for a longer period of time. Laying around I have a starter kit from [Particle](http://particle.io), namely the Particle Core. I have been playing around with it lately to see its capabilities, and I believe I can do everything I want with it. So over the next months I will buy in equipment I need and work on this. It will be an exciting project, which will be a bit different than other projects I work on.

If you happen to have ideas to other parts I can automate in my home do share!

**Increasing my skills as a developer**

One can argue that I will be doing this by working on the projects, mentioned above, and I agree. I do however want to do some more specific to increase my skills. In particular I have started doing coding katas, which you can read more on at [codekata.com](http://codekata.com/). My goal by doing this is to become an even better problem solver. I aim to solve different katas in different ways, so I can see possible solutions to the same problem.

Are you doing code katas? Why/why not?


text:
Template: bookref
BookName: Modern Chemistry
BookAuthor: Mickey Sarquis & Jerry L. Sarquis
BookPublisher: Houghton Mifflin Harcourt
BookLanguage: 英语
BookCover: /images/Covers/Modern Chemistry - Mickey Sarquis.jpg
BookBaidupanDownloadUrl: https://pan.baidu.com/s/1jDP0JI1iyB9S9Ue4y9tbeQ
BookBaidupanDownloadCode: 8f5n

[TOC]

本书pdf是 **文字版** ，**彩图版** 。

### Matter and Change

### Measurements and Calculations

### Atoms: The Building Blocks of Matter

### Arrangement of Electrons in Atoms

### The Periodic Law

### Chemical Bonding

### Chemical Formulas and Chemical Compounds

### Chemical Equations and Reactions

### Stoichiometry

### States of Matter

### Gases

### Solutions

### Ions in Aqueous Solutions and Colligative Properties

### Acids and Bases

### Acid-Base Titration and pH

### Reaction Energy

### Reaction Kinetics

### Chemical Equilibrium

### Oxidation-Reduction Reactions

### Electrochemistry

### Nuclear Chemisry

### Organic Chemistry

### Biological Chemistry

url: https://raw.githubusercontent.com/a358003542/a358003542.github.io/aa0fe86f152c127dc8f6dc319483bc9999a08d85/content/articles/化学/化学 - 基础化学/Modern Chemistry - Mickey Sarquis.md

filename: Modern Chemistry - Mickey Sarquis.md