text:
# Contribution Guide

* [Before you get started](#before-you-get-started)
    * [Code of Conduct](#code-of-conduct)
* [Your First Contribution](#your-first-contribution)
    * [Find a good first topic](#find-a-good-first-topic)
* [Setting up your development environment](#setting-up-your-development-environment)
    * [Fork the project](#fork-the-project)
    * [Clone the project](#clone-the-project)
    * [New branch for a new code](#new-branch-for-a-new-code)
    * [Test](#test)
    * [Commit and push](#commit-and-push)
    * [Create a Pull Request](#create-a-pull-request)
    * [Sign the CLA](#sign-the-cla)
    * [Get a code review](#get-a-code-review)

## Before you get started

### Code of Conduct

Please make sure to read and observe our [Code of Conduct](./CODE_OF_CONDUCT.md).

## Your First Contribution

### Find a good first topic

You can start by finding an existing issue with the
[good first issue](https://github.com/dgraph-io/badger/labels/good%20first%20issue) or [help wanted](https://github.com/dgraph-io/badger/labels/help%20wanted) labels. These issues are well suited for new contributors.

## Setting up your development environment

Badger uses [`Go Modules`](https://github.com/golang/go/wiki/Modules)
to manage dependencies. The version of Go should be **1.12** or above.

### Test

Build and run all tests:

```sh
$ ./test.sh
```

### Commit and push

Commit your changes:

```sh
$ git commit
```

When the changes are ready to review:

```sh
$ git push origin my_new_feature
```

### Create a Pull Request

Just open `https://github.com/$GITHUB_USER/badger/pull/new/my_new_feature` and
fill the PR description.

### Sign the CLA

Click the **Sign in with Github to agree** button to sign the CLA. [An example](https://cla-assistant.io/dgraph-io/badger?pullRequest=1377).

### Get a code review

If your pull request (PR) is opened, it will be assigned to one or more
reviewers. Those reviewers will do a code review.

To address review comments, you should commit the changes to the same branch of
the PR on your fork.

repository: dgraph-io/badger

gha_language: Go

repo_name: dgraph-io/badger


text:
## Project setup

If you want to execute `docker` locally without root privileges (and without security) issues, you can install [Podman](https://podman.io/) and add an alias: `sudo ln -s /usr/bin/podman /usr/bin/docker`.

## Tasks

 * Build the project: `./gradlew assemble`
 * Test the project: `./gradlew test`
 * Check the code style: `./gradlew lint`
 * Fix the code style: `./gradlew fixStyle`
 * Build the docker container to your local docker installation: `./gradlew buildDocker`
 * Start/stop the docker container in your local docker installation: `./gradlew dockerRun` / `./gradlew dockerStop`
 * Remove the docker container from your local docker installation: `./gradlew dockerRemoveContainer`

license: MIT

repository: Pandemieduell/server

branch_name: refs/heads/master

extension: md

gha_language: Java

gha_license_id: MIT

license_type: permissive

repo_name: Pandemieduell/server


text:
---
layout: til
title: "Today I learnt about SQL Alchemy relationship filters ⚗"
date: 2021-08-26
---

I was working on an SQLAlchemy project where I wanted to select all the tasks on a list which hadn't been completed, it turns out this custom relationship filter can be done with the use of `primaryjoin` parameter. The values provided are Python code rather than raw SQL.
```
tasks = relationship(
    "Task",
    order_by="Task.priority",
    primaryjoin="and_(Task.list_id==List.id, Task.completed==None)",
    back_populates="task_list",
)
```

branch_name: refs/heads/main

gha_language: JavaScript


text:
# Mixins

The `mixins` module contains a few framework mixins that are **required** for
using any of the rest of framework.

Install using Bower:

```sh
$ bower install tree-mixins --save
```

Install using npm:

```sh
$ npm install tree-mixins --save
```

## Credits

* **[inuitcss](https://github.com/inuitcss)** Powerful, Sass-based, OOCSS
framework designed with scalability and performance in mind.


text:
# Common issues with Assignment 3.0

## Repository

#### Not pushing config files

All configuration files should be generated. Non-config autogenerated directories (i.e. `node_modules`) should not be.

###### Bad

```
.DS_Store

.vscode, .idea, etc

node_modules/
npm-debug.*
yarn-error.log

.env

coverage/

web-build/
expo/
```

###### Good

```
src/

tests/
__mocks__/

package.json
package-lock.json or yarn-lock.json

tsconfig.json

.eslintrc.json
.eslintignore
.prettierrc.json
.prettierignore

jest.config.ts

app.config.js
.expo-shared
```

#### Organization of files

You should be logically separating your code into directories.

###### Bad

```
App.tsx
Repository.tsx
List.tsx
api-code.ts
test.App.js
package.json
package-lock.json
.eslintrc.json
```

###### Good

```
src/
  App.tsx
  screens/
    Profile.tsx
    Repository.tsx
    Followers.tsx
    Following.tsx
  components/
    User/
      UserBio.tsx
      UserList.tsx
      UserListItem.tsx
    Repository/
      RepositoryList.tsx
      RepositoryListItem.tsx
  github-api/
    query-profile.ts

__mocks__/
  src/
    github-api/
      query-profile.ts

tests/
  test.api.ts
  test.repository.ts
  test.profile.ts
  test.navigation.ts

.eslintrc.json
tsconfig.json
jest.config.ts
package.json
package-lock.json
```

## Eslint

#### Disabling eslint rules

Some students disable eslint rules that we required. If they do this, they cannot get credit for eslint on the rubric.

###### Bad

```ts
/* eslint-disable some rule here */
```

###### Good

Code that follows our eslint configuration.

## React

#### Components should have doc comments

Components should have standard doc comments that explain what the component is as well as what the props are

###### Bad

```tsx
const Repository: React.FC<{ repo: Repo }> = ({ repo }) => {
  return (
    <View>
      <Text>{repo.name}</Text>
    </View>
  );
};
```

###### Good

```tsx
/**
 * A component that renders a repository.
 *
 * @param repo The repository from the GitHub API
 */
const Repository: React.FC<{ repo: Repo }> = ({ repo }) => {
  return (
    <View>
      <Text>{repo.name}</Text>
    </View>
  );
};
```

#### Use functional components instead of class components

Students should be using functional components whenever possible.

###### Bad

```tsx
class ProfileScreen extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      profile: null,
    };
  }

  componentDidMount() {
    (async () => {
      const profile = await getProfile();

      this.setState(() => ({
        profile,
      }));
    })();
  }

  render() {
    return (
      <View>
        <Text>{profile?.username ?? "Loading..."}</Text>
      </View>
    );
  }
}
```

###### Good

```tsx
const ProfileScreen: React.FC = () => {
  const [profile, setProfile] = React.useState<Profile | undefined>();

  React.useEffect(() => {
    (async () => {
      const profileData = await getProfile();

      setProfile(() => profileData);
    })();
  }, []);

  return (
    <View>
      <Text>{profile?.username ?? "Loading..."}</Text>
    </View>
  );
};
```

#### Missing dependencies for hooks

Hooks must have all dependencies used in the hook listed in the array, no more, no less. If there are no dependencies, there should be an empty array. Supplying no array means everything becomes a dependency (which is rarely the desired result).

###### Bad

```tsx
useEffect(() => {
  dispatch(action.getProfile());
}, []);
```

###### Good

```tsx
useEffect(() => {
  dispatch(action.getProfile());
}, [dispatch]);
```

#### Manually assembling DOM

Students should inline assemble DOM elements whenever possible rather than building the DOM in multiple pieces.

###### Bad

```tsx
const ProfileScreen: React.FC = () => {
  const [profile, setProfile] = React.useState<Profile | undefined>();

  React.useEffect(() => {
    (async () => {
      const profileData = await getProfile();

      setProfile(() => profileData);
    })();
  }, []);

  const repositories = [];

  profile?.repositories.forEach((repo) => {
    repositories.push(<Repository repo={repo} />);
  });

  return (
    <View>
      <Text>{profile?.username ?? "Loading..."}</Text>

      {repositories}
    </View>
  );
};
```

###### Good

```tsx
const ProfileScreen: React.FC = () => {
  const [profile, setProfile] = React.useState<Profile | undefined>();

  React.useEffect(() => {
    (async () => {
      const profileData = await getProfile();

      setProfile(() => profileData);
    })();
  }, []);

  return (
    <View>
      <Text>{profile?.username ?? "Loading..."}</Text>

      {profile?.repositories.map((repo) => (
        <Repository key={repo.id} repo={repo} />
      ))}
    </View>
  );
};
```

#### Spread props inside the component declaration

Students should spread their props inside of the functional component declaration. This makes the definition more clear, allows for default values, and avoids constantly accessing the props variable. This is especially crucial if they are not using TypeScript.

###### Bad

```tsx
const ProfileScreen = (props) => {
  const openPage = (page: string) => {
    props.navigation.navigate(page);
  };

  return (
    <View>
      <Text onPress={() => openPage("Repositories")}>Repositories</Text>
    </View>
  );
};
```

###### Good

```tsx
const ProfileScreen = ({ navigation }) => {
  const openPage = (page: string) => {
    navigation.navigate(page);
  };

  return (
    <View>
      <Text onPress={() => openPage("Repositories")}>Repositories</Text>
    </View>
  );
};
```

#### Do not write API requests directly in components

Students should never write their API requests directly inside their components. The API request shoud be extracted into a helper function in a separate file and imported into the component file. If you see a student calling `fetch` directly in the component, chances are they need to improve their decomposition.

###### Bad

```tsx
const ProfileScreen: React.FC = () => {
  const [profile, setProfile] = React.useState<Profile | undefined>();

  React.useEffect(() => {
    (async () => {
      const res = await fetch("http....");
      const profileData = await res.json();

      setProfile(profileData);
    })();
  }, []);

  return (
    <View>
      <Text>{profile?.username ?? "Loading..."}</Text>
    </View>
  );
};
```

###### Good

```tsx
const ProfileScreen: React.FC = () => {
  const [profile, setProfile] = React.useState<Profile | undefined>();

  React.useEffect(() => {
    (async () => {
      const profileData = await getProfile();

      setProfile(profileData);
    })();
  }, []);

  return (
    <View>
      <Text>{profile?.username ?? "Loading..."}</Text>
    </View>
  );
};
```

###### Good

#### Do not use global variables as an alternative to state

Students should not store stateful data in globals that are imported into components. This is a very severe violation of the fundamental principles of React and should be worth decomposition points proportional to the violation's severity. The correct answer is to use global state management via a library like `Redux`. If `Redux` is too difficult for them, they can use a `Context` or at a minimum store their data inside state and pass it as props. `Redux` is greatly preferred.

###### Bad

```tsx
let profile: Profile | undefined;

const ProfileScreen: React.FC = () => {
  React.useEffect(() => {
    (async () => {
      profile = await getProfile();
    })();
  }, []);

  return (
    <View>
      <Text>{profile?.username ?? "Loading..."}</Text>
    </View>
  );
};
```

###### Good

```tsx
import { useSelector, useDispatch } from "react-redux";
import { ReduxState, actions } from "./redux";

const ProfileScreen: React.FC = () => {
  const profile = useSelector((state: ReduxState) => state.github.profile);

  const dispatch = useDispatch();
  const dispatchGetProfile = React.useCallback(
    () => dispatch(actions.getProfile()),
    [dispatch]
  );

  React.useEffect(() => {
    dispatchGetProfile();
  }, []);

  return (
    <View>
      <Text>{profile?.username ?? "Loading..."}</Text>
    </View>
  );
};
```

#### Do not use inline styles

Students should not hardcode styles inline. Instead they should define styles in a `StyleSheet`. This is a reusability issue as well as a refactoring one and often indicates poor decomposition / design.

###### Bad

```tsx
<Text style={{ fontWeight: 600 }}>Repositories:</Text>
```

###### Good

```tsx
const styles = StyleSheet.create({
  boldText: {
    fontWeight: 600,
  },
});
```

```tsx
<Text style={styles.boldText}>Repositories</Text>
```

#### Combine state hooks if they come from the same source

Using a lot of separate state hooks for data that comes from the same source (ie is always set at the same time) is unnecessarily complex and makes code harder to follow as well as clutters the namespace. It also means they have to call a ton of separate setters to update each piece individually. Instead students should use a single `useState` hook for the entire object, often the user's profile. If they are worried about triggering re-renders, they can look into using the `useMemo` hook.

###### Bad

```tsx
const [username, setUsername] = React.useState<string>("");
const [name, setName] = React.useState<string>("");
const [imageUrl, setImageUrl] = React.useState<string>("");

React.useEffect(() => {
  (async () => {
    const profile = await getProfile();

    setUsername(profile.username);
    setName(profile.name);
    setImageUrl(profile.imageUrl);
  })();
}, []);
```

###### Good

```tsx
const [profile, setProfile] = React.useState<Profile | undefined>();

React.useEffect(() => {
  (async () => {
    const profile = await getProfile();

    setProfile(profile);
  })();
}, []);
```

#### Define stateful functions inside the component

Students should not write their functions outside of a component if they only depend on state or props. They should instead take advantage of scoping their functions to automatically have access.

###### Bad

```tsx
const ProfileScreen: React.FC<{ navigation: Navigation }> = ({
  navigation,
}) => {
  return (
    <View>
      <Text onPress={() => openPage(navigation, "Repositories")}>
        Repositories
      </Text>
    </View>
  );
};

const openPage = (navigation: Navigation, page: string) => {
  navigation.navigate(page);
};
```

###### Good

```tsx
const ProfileScreen: React.FC<{ navigation: Navigation }> = ({
  navigation,
}) => {
  const openPage = (page: string) => {
    navigation.navigate(page);
  };

  return (
    <View>
      <Text onPress={() => openPage("Repositories")}>Repositories</Text>
    </View>
  );
};
```

#### Writing code that only works in web

Students seem to be writing code that uses web-only packages such as `css` or regular `html` elements like `<img />`. This is **invalid** React-Native code. They must only use React-Native specific components or their app will work in the web browser but will fail on a device.

###### Bad

```tsx
<img src={imageUrl} style={styles.image} />
```

###### Good

```tsx
import { Image } from "react-native";

<Image source={{ uri: imageUrl }} style={styles.image} />;
```

## General coding issues

#### Use `async`/`await` instead of `Promise` chaining

Students should use `async`/`await` over `Promise` chaining. It produces easier to follow code as well as avoids creating unnecessary nested scopes.

###### Bad

```ts
const getProfile = (): Promise<Profile | string> => {
  return new Promise<Profile | string>((resolve) => {
    let errorMessage = "";
    let responseJson;

    fetch()
      .then((res) => res.json())
      .then((res) => {
        responseJson = res;
      })
      .catch((error) => {
        errorMessage = error.message;
      })
      .finally(() => {
        if (responseJson) {
          resolve(responseJson);
        } else {
          resolve(errorMessage);
        }
      });
  });
};
```

###### Good

```ts
const getProfile = async (): Profile | string => {
  try {
    const response = await fetch();
    const responseJson = await response.json();

    return responseJson;
  } catch (error) {
    return error.message ?? "";
  }
};
```

#### Use `const` instead of `let` whenever possible

If a variable is not reassigned, it should always use `const` instead of `let`

###### Bad

```ts
let profile: Profile | null = null;

let res = await getProfile();

profile = res.profile;
```

###### Good

```ts
let profile: Profile | null = null;

const res = await getProfile();

profile = res.profile;
```

#### Use template literals over string concatenation

Students should use template literals instead of string concatenation. It is a more readable syntax and avoids mutations.

###### Bad

```ts
const repoCount = "Repo count: " + profile.repoCount;
```

```tsx
<Text>{"Repo count: " + profile.repoCount}</Text>
```

###### Good

```ts
const repoCount = `Repo count ${profile.repoCount}`;
```

```tsx
<Text>{`Repo count: ${profile.repoCount}`}</Text>
```

#### Use spreads

Students should be using object and array spreads whenever possible rather than doing direct mutations.

###### Bad

```ts
const getProfileWithCount = async () => {
  let data = await getProfile();
  data.repoCount = data.repositories.length;

  return data;
};
```

###### Good

```ts
const getProfileWithCount = async () => {
  const data = await getProfile();

  return {
    ...data,
    repoCount: data.repositories.length,
  };
};
```

#### Use a date package

Students should not manually manipulate `Date` objects or timestamps. If they need to format or process a date, they should use a dedicated library like `moment` or `date-fns`. Both libraries have similar functionality but `date-fns` focuses on using the built in `Date` object and functions that accept the date and return the result rather than mutating a class. This is better than using `moment` both for this immutability but also because `moment` is not compatible with `tree-shaking`.

###### Bad

```ts
const creationDate = profile.creationDate.toISOString().split("T")[0];
```

###### Good

```ts
import moment from "moment";

const creationDate = moment(profile.creationDate).format("YYYY-MM-DD");
```

#### Watch out for strange spacing

Students should be following the `airbnb` style guide. For good opinionated styling, students can use `Prettier`.

###### Bad

```ts
interface Profile {
  // prettier-ignore
  username : string;
  // prettier-ignore
  name:string;
}

// prettier-ignore
const username = profile? profile.username : "N/A";
```

```ts
interface Profile {
  username: string;
  name: string;
}

const username = profile ? profile.username : "N/A";
```

#### Use optional chaining

Students should take advantage of optional chaining instead of using explicit if statements to verify a chain.

###### Bad

```ts
let repositories: Repository[] = [];

const data = getProfile();

if (data && data.user && data.user.repositories) {
  repositories = data.user.repositories.nodes;
}
```

###### Good

```ts
const data = getProfile();

const repositories: Repository[] = data?.user?.repositories?.nodes;
```

#### Use the nullish coalescing operator

The nullish coalescing operator should be used as a shorthand for the equivalent `!== undefined` or `!== null` check when a default value is desired.

###### Bad

```ts
const username = profile?.username ? profile?.username : "N/A";
```

###### Good

```ts
const username = profile?.username ?? "N/A";
```

## TypeScript

#### Do not use the `any` type

If a student is using TypeScript, they cannot use the `any` type or the `Object` type or `{}` or any equivalent escape type. This defeats the purpose of TypeScript because they are disabling types. I subtract one bonus point if a student uses any of those.

###### Bad

```ts
const profile: any = {
  username: "jtaylorchang",
  repositories: [
    {
      name: "sp21-cs242-assignment3",
    },
  ],
};
```

###### Good

```ts
interface Repository {
  name: string;
}

interface Profile {
  username: string;
  repositories: Repository[];
}

const profile: Profile = {
  username: "jtaylorchang",
  repositories: [
    {
      name: "sp21-cs242-assignment3",
    },
  ],
};
```

#### Use correct types and keywords

When using TypeScript, students should make sure that they use the correctly cased types as opposed to the classes for those types. If they use arrays, they should use the bracket notation instead of `Array<>`.

###### Bad

```ts
interface Profile {
  name: String;
  repoCount: Number;
  repos: Array<Repository>;
}
```

###### Good

```ts
interface Profile {
  name: string;
  repoCount: number;
  repos: Repository[];
}
```

#### Use the `as` keyword instead of casting

Sometimes a student will need to cast a value into a specific type, a common situation for this is when getting responses back from API requests. They should use the `as` keyword instead of casting.

###### Bad

```ts
const profile = <Profile>await response.json();
```

###### Good

```ts
const profile = (await response.json()) as Profile;
```


text:
+++
date = "2017-06-01T11:00:00+02:00"
draft = false
title = "Producing up-to-date container images"
+++

Even though Docker Hub supports automated builds — triggering builds when you
push to a git repository, you still need to actually push to your git
repository in order to get the image build.  That is pretty tedious, to just
update versions and run tests to verify it works. It would be much simpler to
let it update itself automatically and just resolve issues.

<!--more-->

And that's actually pretty easy to do. All you need is GitHub repository,
Docker Hub repository and one script running as a Cron Job in Travis CI. And
that's it.

So let's take a closer look how [I set this up for Rust](https://github.com/TomasTomecek/rust-container/).

1. Travis CI initiates a build every day using its [Cron Jobs](https://github.com/travis-ci/beta-features/issues/1) feature.

2. [This build script](https://github.com/TomasTomecek/rust-container/blob/master/hack/ci.sh) is executed. It's as simple as:
  ```
  mkdir -p ~/.docker && echo "${DOCKER_AUTH}" >~/.docker/config.json
  docker build --tag=$USER/rust .
  make test
  TESTS_PASSED=$?
  if [[ $TESTS_PASSED == 0 ]] ; then
      VERSION=$(docker run $USER/rust rustc --version)
      docker tag $USER/rust tomastomecek/rust:$VERSION
      docker push tomastomecek/rust:$VERSION
  fi
  ```

3. So the image gets built, tested, tagged with correct version and then it's pushed to Docker Hub.

4. Tests verify that
  * Rust compiler is able to compile Rust code.
  * Cargo is able to create a new project.
  * This cargo project can be built.

And that's pretty much it. With such a simple pipeline you get Docker images which are:

 * up to date
 * functional
 * correctly tagged

For implementation details, such as
[Dockerfile](https://github.com/TomasTomecek/rust-container/blob/master/Dockerfile),
[Makefile](https://github.com/TomasTomecek/rust-container/blob/master/Makefile),
[.travis.yml](https://github.com/TomasTomecek/rust-container/blob/master/.travis.yml),
[tests](https://github.com/TomasTomecek/rust-container/blob/master/tests/test_functional.py)
or the precise
[cron job script](https://github.com/TomasTomecek/rust-container/blob/master/hack/ci.sh),
please check my [TomasTomecek/rust-container](https://github.com/TomasTomecek/rust-container) GitHub repository.

repository: TomasTomecek/the-real-blog

repo_name: TomasTomecek/the-real-blog


text:
# Challenge

- Create an application that chooses an int between 0 and 100, inclusive, at random.
- The User will be explained the game and given 10 opportunites to guess the number.
- The program will tell the user if the random number is higher or lower than their guess.
- The program will print out a list of the users guesses for each turn in this format, "50, 20, 35"
- After 10 unsuccessful guesses, the user loses and is given an opportiunity to play again.

# Constraints
- You must have a GetRandomNumber() method to get the random number between 0 and 100, inclusive, an int.
- You must have a GetUsersGuess() method to get users input, validate that is is an in between 0 and 100, includive, and return the int. Reprompt until the user enters a correct value.
- You must have a CompareNums() method to compare the random number and the user input.
- You must have a PlayGameAgain() method to offer the user the chance to play again. Return true if they want to play again and false if they do not.
- Replay the game until the user chooses not to play again.
- You cannot use the .NET .CompareTo() method. You must create your own method to compare user input to the random number chosen.

 # Note
 - Make sure to follow SOLID Principles.
 - This game will require the Random Class ('System' Namespace) - https://docs.microsoft.com/en-us/dotnet/api/system.random?view=netcore-3.1
 - It is not best practice to have user interaction within a method, but we are doing it here to allow testing.
 - EVERY method is called in Main() and returns to Main().

gha_language: HTML


text:
## Language translations

If you would like to contribute to CoVizu by providing a page translation in another language, thank you!

* To get started, make a copy of `index.html` and add a [two-letter language code](https://en.wikipedia.org/wiki/ISO_639-1) suffix to the basename, *e.g.*, `index-fr.html`.

* We have moved all text elements into a single file `index.html` so that contributors do not have to search through the various JavaScript files for content to translate.
In order for this to work, we have had to create a [JSON](https://en.wikipedia.org/wiki/JSON) object at the top of the `<head>` section of `index.html`.
This maps keywords, *e.g.*, `number_cases`, to the language-specific replacement, *e.g.*, "nombre de cas".
A translation should be provided for every keyword in this JSON.

* Please check through the following HTML elements for content to translate:
  * `<label>` elements
  * `<option>` elements within `<select>` inputs
  * `title` tags within `<div>` and `<span>` elements
  * text enclosed in `<div>` and `<span>` elements
  * header elements, *e.g.*, `<h3>`

* There are several help texts to translate that are enclosed in `<p>` tags in the bottom half of the `index.html` document.
  * Text enclosed in the `title` tag of a `<span>` element must be written in a single line (no line breaks) to render properly.
  * Please leave the GISAID Acknowledgements statement: "We gratefully acknowledge all the Authors" in its original English.

## Development environment

Development of CoVizu is primarily being carried out on workstations and servers running Ubuntu 16.04+.
However, we have also run the system on desktop computers running macOS 10.13.
Most web development is tested in Google Chrome.

## Coding style

### Python

* Use four spaces to indent, and other conventions described in the [PEP8](https://www.python.org/dev/peps/pep-0008/) style guide.  It is easier to use a Python-aware [IDE](https://en.wikipedia.org/wiki/Integrated_development_environment) like [PyCharm](https://www.jetbrains.com/pycharm/) or [Atom](https://atom.io/) to automate this for you.

* Organize your code into functions to facilitate testing and so that methods can be called from other scripts.

* Isolate the main loop of your code under `if __name__ == '__main__'` to be executed only if the script is being run at the top level (from the command line).

* Try to use `argparse` to provide help documentation for command line execution.

* Use lowercase with underscores to separate words for function and variable names.  Do not use [camel-case](https://en.wikipedia.org/wiki/Camel_case).

* Every function should open with a [docstring](https://www.python.org/dev/peps/pep-0257).  If the function is very brief with a small number of self-explanatory arguments, then a one-line docstring is fine.  Otherwise, use a multi-line docstring.  Use `:param varname: description` entries to document arguments. Use `:return: type, description` entries to document return values.

## Committing your code

* Do not push commits to the `master` branch.  All development should be tracked in the `dev` branch and then merged into `master` after it has been tested.
* If you are trying to implement something new that can potentially break parts of the code that other developers may be working on, then [create a new branch](https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging) and merge it into `dev` after you have finished building and testing the code.
* Please try to write concise and informative [commit messages](https://xkcd.com/1296/).

## Front-end Testing

* Front-end testing is carried out using [Cypress](https://www.cypress.io/).
* For the purposes of this project, Cypress needs to be installed via direct download. An installation guide can be found [here](https://docs.cypress.io/guides/getting-started/installing-cypress#Direct-download).
* The `baseUrl` is currently set as `"http://<IP_ADDRESS>:8001/`. Changes to it can be made in `Cypress.json`.

repository: yemilawal/covizu

repo_name: yemilawal/covizu


text:
|Travis| |PyPI| |Anaconda|

Numpy indexed operations
========================

This package contains functionality for indexed operations on numpy ndarrays, providing efficient vectorized functionality such as grouping and set operations.

* Rich and efficient grouping functionality:

  - splitting of values by key-group
  - reductions of values by key-group

* Generalization of existing array set operation to nd-arrays, such as:

  - unique
  - union
  - difference
  - exclusive (xor)
  - contains / in (in1d)

* Some new functions:

  - indices: numpy equivalent of list.index
  - count: numpy equivalent of collections.Counter
  - mode: find the most frequently occuring items in a set
  - multiplicity: number of occurrences of each key in a sequence
  - count\_table: like R's table or pandas crosstab, or an ndim version of np.bincount

Some brief examples to give an impression hereof:

.. code:: python

    # three sets of graph edges (doublet of ints)
    edges = np.random.randint(0, 9, (3, 100, 2))
    # find graph edges exclusive to one of three sets
    ex = exclusive(*edges)
    print(ex)
    # which edges are exclusive to the first set?
    print(contains(edges[0], ex))
    # where are the exclusive edges relative to the totality of them?
    print(indices(union(*edges), ex))
    # group and reduce values by identical keys
    values = np.random.rand(100, 20)
    # and so on...
    print(group_by(edges[0]).median(values))

Installation
------------

.. code:: python

    > conda install numpy-indexed -c conda-forge

or

.. code:: python

    > pip install numpy-indexed

See: https://pypi.python.org/pypi/numpy-indexed

Design decisions:
-----------------

This package builds upon a generalization of the design pattern as can
be found in numpy.unique. That is, by argsorting an ndarray, many
subsequent operations can be implemented efficiently and in a vectorized
manner.

The sorting and related low level operations are encapsulated into a
hierarchy of Index classes, which allows for efficient lookup of many
properties for a variety of different key-types. The public API of this
package is a quite thin wrapper around these Index objects.

The two complex key types currently supported, beyond standard sequences
of sortable primitive types, are ndarray keys (i.e, finding unique
rows/columns of an array) and composite keys (zipped sequences). For the
exact casting rules describing valid sequences of key objects to index
objects, see as\_index().

Todo and open questions:
------------------------

- There may be further generalizations that could be built on top of
  these abstractions. merge/join functionality perhaps?

.. |Travis| image:: https://travis-ci.org/EelcoHoogendoorn/Numpy_arraysetops_EP.svg?branch=master
   :target: https://travis-ci.org/EelcoHoogendoorn/Numpy_arraysetops_EP
.. |PyPI| image:: https://badge.fury.io/py/numpy-indexed.svg
   :target: https://pypi.org/project/numpy-indexed/
.. |Anaconda| image:: https://anaconda.org/conda-forge/numpy-indexed/badges/version.svg
   :target: https://anaconda.org/conda-forge/numpy-indexed

extension: rst

gha_language: Python


text:
Given a string  **_s_**  , find the length of the longest substring **_t_** that contains  **at most** 2 distinct characters.

**Example 1:**

**Input:** "eceba"
**Output:** 3
**Explanation: _t_**  is "ece" which its length is 3.

**Example 2:**

**Input:** "ccaabbb"
**Output:** 5
**Explanation: _t_**  is "aabbb" which its length is 5.

url: https://raw.githubusercontent.com/gurfinkel/leetCode/ba41e63e12bee7cfe4e91966771077cdf765b598/problems/Longest Substring with At Most Two Distinct Characters/lengthOfLongestSubstringTwoDistinct.md

repository: gurfinkel/leetCode

repo_name: gurfinkel/leetCode


text:
It's a simple version header generator for C/C++ projects.
==========================================================

Why?
----
**Because sometimes you need to know which version of the code you are working with.**

How to use?
-----------
1.	Edit your_config_file.xml,
2.	Run:
`./VersionHeaderGenerator.py your_config_file.xml`,
3.	The generated file is placed in a proper place (look to the config file to check the place).

Buildin variables*:
-------------------
1.	`NAME`,
2.	`GIT_REVISION_HASH`,
3.	`GIT_SHORT_REVISION_HASH`,
4.	`GIT_BRANCH`,
5.	`GENERATION_TIME`,
6.	`GENERATION_DATE`,
7.	`COMPILATION_TIME`,
8.	`COMPILATION_DATE`,
9.	`GUARD_DEF`.

Your own variables*:
--------------------
Insert proper entry in your your_config_file.xml.
E.g:
`<your_important_variable>(0xDEADBEEF)</your_important_variable>`

You can try using attached example:
-----------------------------------
Run it:
`cd example ; make`

*) Of course, they aren't variables from the point of view C/C++ language and its compilation. They are variables from point of view of project management.

repository: mgorzkowski/VersionHeaderGenerator

repo_name: mgorzkowski/VersionHeaderGenerator


text:
[![CircleCI](https://circleci.com/gh/ngx-kit/ngx-kit.svg?style=svg)](https://circleci.com/gh/ngx-kit/ngx-kit)
[![npm version](https://badge.fury.io/js/%40ngx-kit%2Fcore.svg)](https://www.npmjs.com/@ngx-kit/core)

# [ngx-kit](https://ngx-kit.com)

Boost your Angular development!

Components customizing should be simple. Just generate components from ngx-kit collection and modify them as you like.

## Packages

* [@ngx-kit/core](https://ngx-kit.com/core) — low level services and directives for hiding complex logic.
* [@ngx-kit/collection](https://ngx-kit.com/collection) — set of components based on ngx-kit core and packed into Angular-cli schematics.

## Features

* AOT support
* Server-rendering support
* OnPush strategy support

## Requirements

* Angular 7
* Angular-cli 7

## Usage

![](./website/assets/demo.gif)

#### Add ngx-kit to your project

```
ng add @ngx-kit/core
```

#### Generate UI module

Pick a module from [Collection](https://ngx-kit.com/collection) and put the code to your project.

A button for example:

```
ng g @ngx-kit/collection:ui-button ui-button
```

#### Import generated module

```typescript
@NgModule({
  ...
  imports: [
    ...
    UiButtonModule,
```

#### Use component

```html
<button uiButton color="primary">Let's do it!</button>
```

#### Modify by your requirements

Only complex (but stable) logic is stored in [Core](https://ngx-kit.com/core), so you can change generated templates and styles in any way.

### Hammerjs

Some collection modules use Hammer.js.

For proper working:

1. Install `npm i hammerjs --save`

2. Import `import 'hammerjs';` in `main.ts`.

## License

MIT

repository: ngx-kit/ngx-kit

gha_language: TypeScript

repo_name: ngx-kit/ngx-kit


text:
---
id: combobox
title: fast-combobox
sidebar_label: combobox
custom_edit_url: https://github.com/microsoft/fast/edit/master/packages/web-components/fast-foundation/src/combobox/README.md
description: fast-combobox is a web component implementation of a combobox.
---

As defined by the [W3C](https://w3c.github.io/aria-practices/#combobox):

> A combobox is an input widget with an associated popup that enables users to select a value for the combobox from a collection of possible values. In some implementations, the popup presents allowed values, while in other implementations, the popup presents suggested values, and users may either select one of the suggestions or type a value. The popup may be a listbox, grid, tree, or dialog. Many implementations also include a third optional element -- a graphical Open button adjacent to the combobox, which indicates availability of the popup. Activating the Open button displays the popup if suggestions are available.

## Setup

### Basic Setup

```ts
import {
    provideFASTDesignSystem,
    fastCombobox,
    fastOption,
} from "@microsoft/fast-components";

provideFASTDesignSystem().register(fastCombobox(), fastOption());
```

### Customizing the indicator

```ts
import {
    provideFASTDesignSystem,
    fastCombobox,
    fastOption,
} from "@microsoft/fast-components";

provideFASTDesignSystem().register(
    fastCombobox({
        indicator: `...your indicator...`,
    }),
    fastOption()
);
```

## Usage

```html live
<fast-combobox autocomplete="both">
    <fast-option>Christopher Eccleston</fast-option>
    <fast-option>David Tenant</fast-option>
    <fast-option>Matt Smith</fast-option>
    <fast-option>Peter Capaldi</fast-option>
    <fast-option>Jodie Whittaker</fast-option>
</fast-combobox>
```

## Create your own design

### Combobox

```ts
import {
    Combobox,
    ComboboxOptions,
    comboboxTemplate as template,
} from "@microsoft/fast-foundation";
import { comboboxStyles as styles } from "./my-combobox.styles";

export const myCombobox = Combobox.compose<ComboboxOptions>({
    baseName: "combobox",
    template,
    styles,
    shadowOptions: {
        delegatesFocus: true,
    },
    indicator: `...default indicator...`,
});
```

:::note
This component is built with the expectation that focus is delegated to the input element rendered into the shadow DOM.
:::

### Option

See [listbox-option](/docs/components/listbox-option) for more information.

## API

### class: `FormAssociatedCombobox`

#### Superclass

| Name        | Module                                   | Package |
| ----------- | ---------------------------------------- | ------- |
| `_Combobox` | src/combobox/combobox.form-associated.ts |         |

#### Mixins

| Name             | Module                                  | Package |
| ---------------- | --------------------------------------- | ------- |
| `FormAssociated` | /src/form-associated/form-associated.js |         |

#### Fields

| Name               | Privacy   | Type                  | Default | Description                           | Inherited From |
| ------------------ | --------- | --------------------- | ------- | ------------------------------------- | -------------- |
| `proxy`            |           |                       |         |                                       |                |
| `length`           | public    | `number`              |         | The number of options.                | FASTListbox    |
| `options`          | public    | `FASTListboxOption[]` |         | The list of options.                  | FASTListbox    |
| `typeAheadExpired` | protected |                       |         |                                       | FASTListbox    |
| `disabled`         | public    | `boolean`             |         | The disabled state of the listbox.    | FASTListbox    |
| `selectedIndex`    | public    | `number`              | `-1`    | The index of the selected option.     | FASTListbox    |
| `selectedOptions`  | public    | `FASTListboxOption[]` | `[]`    | A collection of the selected options. | FASTListbox    |

#### Methods

| Name                 | Privacy | Description                                    | Parameters | Return | Inherited From |
| -------------------- | ------- | ---------------------------------------------- | ---------- | ------ | -------------- |
| `selectFirstOption`  | public  | Moves focus to the first selectable option.    |            | `void` | FASTListbox    |
| `setSelectedOptions` | public  | Sets an option as selected and gives it focus. |            |        | FASTListbox    |

#### Attributes

| Name | Field    | Inherited From |
| ---- | -------- | -------------- |
|      | disabled | FASTListbox    |

### Variables

| Name                   | Description                       | Type                                                              |
| ---------------------- | --------------------------------- | ----------------------------------------------------------------- |
| `ComboboxAutocomplete` | Autocomplete values for combobox. | `{ inline: "inline", list: "list", both: "both", none: "none", }` |

### class: `FASTCombobox`

#### Superclass

| Name                     | Module                                    | Package |
| ------------------------ | ----------------------------------------- | ------- |
| `FormAssociatedCombobox` | /src/combobox/combobox.form-associated.js |         |

#### Fields

| Name               | Privacy   | Type                                | Default | Description                                                                              | Inherited From         |
| ------------------ | --------- | ----------------------------------- | ------- | ---------------------------------------------------------------------------------------- | ---------------------- |
| `autocomplete`     | public    | `ComboboxAutocomplete or undefined` |         | The autocomplete attribute.                                                              |                        |
| `filteredOptions`  | public    | `FASTListboxOption[]`               | `[]`    | The collection of currently filtered options.                                            |                        |
| `open`             | public    | `boolean`                           | `false` | The open attribute.                                                                      |                        |
| `options`          | public    | `FASTListboxOption[]`               |         | The list of options.                                                                     | FASTListbox            |
| `placeholder`      | public    | `string`                            |         | Sets the placeholder value of the element, generally used to provide a hint to the user. |                        |
| `value`            | public    |                                     |         | The value property.                                                                      |                        |
| `cleanup`          | public    | `() => void`                        |         | Cleanup function for the listbox positioner.                                             |                        |
| `proxy`            |           |                                     |         |                                                                                | FormAssociatedCombobox |
| `length`           | public    | `number`                            |         | The number of options.                                                                   | FASTListbox            |
| `typeAheadExpired` | protected |                                     |         |                                                                                | FASTListbox            |
| `disabled`         | public    | `boolean`                           |         | The disabled state of the listbox.                                                       | FASTListbox            |
| `selectedIndex`    | public    | `number`                            | `-1`    | The index of the selected option.                                                        | FASTListbox            |
| `selectedOptions`  | public    | `FASTListboxOption[]`               | `[]`    | A collection of the selected options.                                                    | FASTListbox            |

#### Methods

| Name                 | Privacy | Description                                                                | Parameters | Return | Inherited From |
| -------------------- | ------- | -------------------------------------------------------------------------- | ---------- | ------ | -------------- |
| `validate`           | public  | {@inheritDoc (FormAssociated:interface).validate}                          |            | `void` |                |
| `filterOptions`      | public  | Filter available options by text value.                                    |            | `void` |                |
| `setPositioning`     | public  | Calculate and apply listbox positioning based on available viewport space. |            | `void` |                |
| `selectFirstOption`  | public  | Moves focus to the first selectable option.                                |            | `void` | FASTListbox    |
| `setSelectedOptions` | public  | Sets an option as selected and gives it focus.                             |            |        | FASTListbox    |

#### Events

| Name     | Type | Description                                          | Inherited From |
| -------- | ---- | ---------------------------------------------------- | -------------- |
| `change` |      | Fires a custom 'change' event when the value updates |                |

#### Attributes

| Name           | Field        | Inherited From |
| -------------- | ------------ | -------------- |
| `autocomplete` | autocomplete |                |
| `open`         | open         |                |
| `placeholder`  | placeholder  |                |
|                | disabled     | FASTListbox    |

#### CSS Parts

| Name             | Description                                                            |
| ---------------- | ---------------------------------------------------------------------- |
| `control`        | The wrapper element containing the input area, including start and end |
| `selected-value` | The input element representing the selected value                      |
| `indicator`      | The element wrapping the indicator slot                                |
| `listbox`        | The wrapper for the listbox slotted options                            |

#### Slots

| Name        | Description                                                 |
| ----------- | ----------------------------------------------------------- |
| `start`     | Content which can be provided before the input              |
| `end`       | Content which can be provided after the input               |
| `control`   | Used to replace the input element representing the combobox |
| `indicator` | The visual indicator representing the expanded state        |
|             | The default slot for the options                            |

### class: `DelegatesARIACombobox`

#### Fields

| Name               | Privacy | Type                                                       | Default | Description                                                                       | Inherited From |
| ------------------ | ------- | ---------------------------------------------------------- | ------- | --------------------------------------------------------------------------------- | -------------- |
| `ariaAutoComplete` | public  | `"inline" or "list" or "both" or "none" or string or null` |         | See https://www.w3.org/TR/wai-aria-1.2/#aria-autocomplete for more information. |                |
| `ariaControls`     | public  | `string or null`                                           |         | See https://www.w3.org/TR/wai-aria-1.2/#aria-controls for more information.     |                |

## Additional resources

- [Component explorer examples](https://explore.fast.design/components/fast-combobox)
- [Component technical specification](https://github.com/microsoft/fast/tree/master/packages/web-components/fast-foundation/src/combobox)
- [W3C Component Aria Practices](https://w3c.github.io/aria-practices/#combobox)

repository: microsoft/fast

gha_license_id: NOASSERTION

repo_name: microsoft/fast


text:
---
layout: project
type: project
image: images/multi_arm_bandit2.png
title: An Application and Visualization of
Deep Learning Neural Networks and Reinforcement Learning for
Stock Portfolio Management
permalink: projects/social network
# All dates must be YYYY-MM-DD format!
date: 2020-05-05
labels:
  -  LSTM Model
  -  Reinforcement Learning
  -  Stock Price Forecasting
  -  Stock Portfolio Management
summary: Master Project
---

I have used the deep learning neural network, LSTM to predict the stock prices. The result shows that the LSTM network captures the memory of the time series data and can predict the stock price return well.  I then framed the stock portfolio selection problems as a multi-bandit problem where the agents can select from the results from CNN network, mean-variance portfolio strategy, and uniform buy and sell strategy to gain the most benefit from the stock market. The results show that reinforcement learning can potentially help stock traders better allocate stock portfolios.
However, since deep learning network models are highly sensitive to factors such as hyperparameters and network structures, one could also investigate  different network structures and calibrate their hyperparameters, to obtain more satisfactory forecasting results.

The youtube video:
https://youtu.be/SHpspYWX0nE


text:
![img](http://res.cloudinary.com/dtoqqxqjv/image/upload/c_scale,w_1000/v1489323685/github/VagrantVBAnsible.png)

# Vagrant box for development isolation services with long term data life cycle.
Vagrant environment and services sandbox for development application. Possible to set partial isolation or full
> Vagrant box is build for fast up and running development environment with Ubuntu, Postgres, Redis, ElasticSearch tools as default tools. Build on [Oracle Virtual Box](https://www.virtualbox.org/), [Vagrant HashiCorp](https://www.vagrantup.com/), [Ansible](https://www.ansible.com/) and [provisioner](https://github.com/khusnetdinov/provisioner/).

## Getting started

### Files structure
```
├── /.vagrant/                  # The source code
│   ├── /machines/              # Vagrant internal folder
│   ├── /provisioners/          # Vagrant internal folder
│   └── /provisioner/           # Main provision folder
│       ├── /temp/              # Ansible logs
│       │   └── .keep           # Git keep file
│       ├── /roles/             # Ansible roles / receipts from ansible-galaxy
│       │   ├── ....            # Roles
│       │   └── .keep           # Git keep file
│       ├── ansible.cfg         # Ansible local config
│       ├── provision.yml       # Ansible playbook linked from VagrantFile
│       ├── requirements.yml    # Ansible receipts for downloading from ansible-galaxy
│       └── settings.yml        # Variables are used in provision.yml and other roles
│
│── Makefile                    # Makefile for installation Ansible receipts
│── VagrantFile                 # Vagrant configuration file
│── README.md                   # README
│── LICENSE                     # License
└── .gitignore                  # Git ignored files
```

### Commands

 `make install` - Run installation for ansidle requirements.yml

 `vagrant ...`  - Vagrant commands for up and run box

## Requirements

You need to install [Oracle Virtual Box](https://www.virtualbox.org/), [Vagrant HashiCorp](https://www.vagrantup.com/);

Optinal: run `vagrant plugin install vagrant-triggers` . Plugin will be installed on first run `vagrant up` or `vagrant provision`

## Sandbox

If you want work on host machine and use services that run in vagrant
box use `USE_VAGRANT_AS_SERVICES_BOX`.

## SSH keys

Use `ssh-add $ssh_key` for possibility to use it inside vagrant.

## Installation

### MacOs

`brew cask install virtualbox`

`brew cask install vagrant`

`vagrant plugin install vagrant-triggers`

### Ubuntu

`sudo apt-get install virtualbox`

`sudo apt-get install vagrant`

`vagrant plugin install vagrant-triggers`

# License

### This code is free to use under the terms of the MIT license.

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.

repository: khusnetdinov/vagrant

gha_language: Makefile

repo_name: khusnetdinov/vagrant


text:
# supplant
Python module to replace variables and generate a full factorial design.

How to use
----------

Considering a folder called 'skeletonFolder' containing the 'base_case.txt' file.

*base_case.txt*:
```
mass = __MASS__
velocity_x = __VELOCITY_X__
velocity_y = _VELOCITY_Y__
force_x = __FORCE_X__
```

You want to create new cases based on this layout, replacing the mass value by a constant, the velocity_x and velocity_y by a list, and force_x by a list dependent on velocity_x. You proceed with the following implementation:

*example.py*:
```python
import supplant

sim = supplant.Configuration('skeletonFolder')
sim.add_constant('__MASS__', 1)
sim.add_variable('__VELOCITY_X__', [0.2, 0.4])
sim.add_variable('__VELOCITY_Y__', [-0.1, -0.5])
sim.add_dependent('__FORCE_X__', [200, 400], '__VELOCITY_X__')
sim.write_configurations()
```

The final output will be 4 new cases (case_0 to case_3) containing the desired values.

repository: PIMELAB/supplant

repo_name: PIMELAB/supplant


text:
## Travel Log

A personal travel log diary.

### Demo Link

link: [https://travel-dev.netlify.app/](https://travel-dev.netlify.app/)

### Technologies Used

- React
- MapBox

### License

[MIT](https://choosealicense.com/licenses/mit/)

repository: mhshifat/travel-log-client

repo_name: mhshifat/travel-log-client


text:
# android-diffpatch

diffpatch with android

## Getting Started
### BsDiffPatch
website： [http://www.daemonology.net/bsdiff/](http://www.daemonology.net/bsdiff/)

1. write in the build.gradle as follows:
```
sourceSets {
    main {
        jniLibs.srcDirs = ['libs']
    }
}
```
1. copy `app/libs/armeabi-v7a/libbsdiffpatch.so` to your project.
1. copy `app/src/main/java/com/github/snowdream/bsdiffpatch` and `app/src/main/java/com/github/snowdream/diffpatch` to your project, with the exact package and filename.

### HDiffPatch
website：[https://github.com/sisong/HDiffPatch](https://github.com/sisong/HDiffPatch)

1. write in the build.gradle as follows:
```
sourceSets {
    main {
        jniLibs.srcDirs = ['libs']
    }
}
```
1. copy `app/libs/armeabi-v7a/libhdiffpatch.so` to your project.
1. copy `app/src/main/java/com/github/snowdream/hdiffpatch` and `app/src/main/java/com/github/snowdream/diffpatch` to your project, with the exact package and filename.

## Usage
### BsDiffPatch
```
IDiffPatch bsDiffPatch = new BSDiffPatch();
bsDiffPatch.init(getApplicationContext());
//diff
bsDiffPatch.diff(oldFilePath, newFilePath, diffFilePath);
//patch
bsDiffPatch.patch(oldFilePath, diffFilePath, gennewFilePath);
```

### HDiffPatch
```
IDiffPatch hDiffPatch = new HDiffPatch();
hDiffPatch.init(getApplicationContext());
//diff
hDiffPatch.diff(oldFilePath, newFilePath, diffFilePath);
//patch
hDiffPatch.patch(oldFilePath, diffFilePath, gennewFilePath);
```

## License
```
Copyright (C) 2016 snowdream<EMAIL_ADDRESS>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```

repository: zhanpple/android-diffpatch

repo_name: zhanpple/android-diffpatch


text:
Sets the overall score for the strings similarity scoring for the text extracted from the RDP cache image.

## Script Data

---

| **Name** | **Description** |
| --- | --- |
| Script Type | python3 |
| Tags | dynamic-section |
| Cortex XSOAR Version | 6.9.0 |

## Inputs

---
There are no inputs for this script.

## Outputs

---

| **Path** | **Description** | **Type** |
| --- | --- | --- |
| RDPOverallScore | The overall score of matches found in the extracted strings by StringSifter and StringSimilarity analysis. This is a value of 1 to 100  which is a precent of malicious strings found. | Unknown |

repository: demisto/content

repo_name: demisto/content


text:
---
layout: post
title: tmux output formatting
tags:
  - autodidactics
  - tmux
---

_Here's what I learned today about FORMATS in tmux output._

This week I came across [Waylon Walker](https://twitter.com/_WaylonWalker) who is doing some lovely learning-and-sharing on the topic of `tmux`, the terminal multiplexer. He has a [YouTube channel](https://www.youtube.com/user/quadmx08) and a [blog](https://waylonwalker.com), and there are plenty of `tmux` nuggets that are explained in short video and blog post formats.

I read Waylon's post [tmux fzf session jumper](https://waylonwalker.com/tmux-fzf-session-jump/) that he published yesterday, and, having been curious to learn more about his `tmux` setup and usage, I stared a bit at the commands he'd shared. Here's what he was using, in his `tmux` popup based session selector (I was so happy to learn about `tmux` popups from Waylon, more on that topic another time, perhaps):

```bash
tmux bind C-j \
  display-popup \
  -E \
  "tmux list-sessions \
   | sed -E 's/:.*$//' \
   | grep -v \"^$(tmux display-message -p '#S')\$\" \
   | fzf --reverse \
   | xargs tmux switch-client -t"
```

That's quite a bit to unpack and learn from! I've taken the liberty of inserting lots of newlines so we can stare at it more easily.

Before we start to unpack it, you can see what it does in this screenshot - on invocation, it brings up a session chooser in a popup for me to be able to switch to a different session. Nice!

![session chooser in popup]({{ "/images/2021/08/session-chooser.png" | url}})

## Unpacking the invocation

The invocation itself is creating a new key binding (`prefix` `ctrl-j`) with the `bind` (short for `bind-key`) command. The command that is invoked when this key combination is used is a relatively new one: `display-popup`. It seems that the popup feature appeared only about a year ago with `tmux` version 3.2 - see the [associated change notes and discussion for 3.2](https://github.com/tmux/tmux/issues/2645) for more context.

The `-E` switch goes with the `display-popup` command and causes the popup to close automatically when the shell command that's executed within it completes.

The shell command to execute within the popup follows, and is basically the rest of the line - everything inside the outermost double-quote pair (`"tmux list-sessions ... -t"`). This is a pipeline that starts with the output of whatever `tmux list-sessions` produces - here's an example of that output, from the sessions I'm running right now:

```
another session: 1 windows (created Fri Aug  6 11:24:34 2021) (attached)
tmux experiments: 2 windows (created Thu Aug  5 21:04:16 2021)
writing: 2 windows (created Fri Aug  6 11:02:10 2021)
```

I added a third session, "another session", to have more than just a couple for the example, and it's in that third session that I invoked the `tmux list-sessions` command just now - which is why that is the one marked as `(attached)` in the output.

### Removing unwanted information

That output is passed to `sed -E 's/:.*$//'` which uses an extended (that's what the `-E` denotes) regular expression to replace everything on the line\* starting with a colon and going all the way to the end of the line, with nothing. This would change the output above to this:

```
another session
tmux experiments
writing
```

\* `sed` is a stream editor and processes each line in turn

### Filtering out the name of the current session

This reduced output is then piped into `grep`, the search utility. The `-v` switch used inverts the match, effectively printing what is _not_ matched by the regular expression that is given.

And what is that, exactly? It's this: `\"^$(tmux display-message -p '#S')\$\"`. First, because we're already in the context of the pair of outermost double-quotes, the double-quotes used here to enclose the entire pattern need to be escaped, with the backslashes. And within those escaped double-quotes we have `^` that anchors the match to the start of the line, and `$` (escaped again, because it has special meaning within double-quotes) which anchors to the end of the line. And what should actually be matched? If we stare hard enough, we see that what should be matched is the output of running the following command in a subshell (`$(...)`):

```bash
tmux display-message -p '#S'
```

The `display-message` command normally writes a message to the `tmux` session's status line, but the `-p` switch directs the command to write the message to STDOUT instead. What is the message to be written? Well, it's the value of `#S`, which is a variable (identified by the `#`), and specifically, `S` is an alias for `session_name`. So this command prints the name of the current session to STDOUT. In the same context as before (i.e. attached to the "another session" session), running this command would produce this:

```
another session
```

So the ultimate result of piping the list of session names into this inverted matching `grep` invocation is that it would filter out the current session's name, resulting in:

```
tmux experiments
writing
```

Why do this? Well, it makes sense that if I'm going to pick another session to jump to, I probably won't want to jump to my current session.

### Presenting the list for selection

This reduced list is then piped into `fzf`, about which I've written a couple of posts on this autodidactics blog before:

* [fzf - the basics part 1 - layout](https://qmacro.org/autodidactics/2021/02/02/fzf-the-basics-1-layout/)
* [fzf - the basics part 2 - search results](https://qmacro.org/autodidactics/2021/02/07/fzf-the-basics-2-search-results/)

Using `fzf` here is perfect, it's my tool of choice for mini-UIs in the terminal where a choice has to be made, where an item (or items) must be selected. And because it fits with the Unix philosophy too, the output is simply the value of the item(s) selected. And in case you're wondering, the `--reverse` switch is a synonym for `--layout=reverse` which causes `fzf` to display the selection from the top.

### Jumping to the selected session

In the last part of the pipeline, this value (the name of the session that was selected) is passed to `xargs`, the powerful but oft-misunderstood utility that helps you build and execute commands from STDIN. Here, with the invocation `xargs tmux switch-client -t`, we're using it to pass that selected value (e.g. "writing") as a parameter, adding it to the end of the entire set of arguments passed to `xarg`, resulting in an invocation like this:

```bash
tmux switch-client -t writing
```

This of course is the denoument to which we've been building up, and our `tmux` client is switched to the session we selected. Success!

## Formats and an alternative approach

The reference to the `#S` variable got me thinking, and I remembered seeing an awful lot of potential, particularly in the "FORMATS" section of the [`tmux` man page](https://man7.org/linux/man-pages/man1/tmux.1.html). So I thought I'd use this opportunity, having been inspired by what Waylon showed, to see if I could come up with a different way of doing it.

First, could I use something from "FORMATS" to avoid the need to invoke `sed` in the pipeline (i.e. to not do this bit: `sed -E 's/:.*$//'`)? Turns out that the answer is yes; a format string can be used with the `list-sessions` command, with the `-F` option. So this would be an alternative, using the same variable as we saw earlier. Here's the invocation:

```bash
tmux list-sessions -F '#{session_name}'
```

which produces:

```
another session
tmux experiments
writing
```

That is, none of the extraneous information is there, so we don't need to remove it.

We can go a bit further, too, with a conditional expression. Here it is, in action:

```bash
tmux list-sessions -F '#{?session_attached,,#{session_name}}'
```

The value of the `session_attached` variable is `1` if the session currently being listed is attached (i.e. is the one we're in) and `0` if not. So this conditional expression `#{?COND,A,B}` outputs A if condition COND is true, otherwise B. What a lovely ternary style operator just waiting to be used within `tmux` formatting!

So this version produces:

```

tmux experiments
writing
```

The empty line comes from the fact that for the A value in the conditional expression above, we specified nothing (there was nothing between the two commas `,,`) when the session to which we're currently attached is listed.

That means we still have something to filter out, with `grep`, but it becomes simpler, with the briefest of patterns needed for `grep`, to match and filter out (with `-v`) empty lines: `^$` - i.e. "the start of the line followed immediately by the end of the line". Like this:

```bash
tmux list-sessions -F '#{?session_attached,,#{session_name}}' | grep -v '^$'
```

This produces:

```
tmux experiments
writing
```

which then can be passed as before into `fzf` for selection.

## Wrapping up

This is in no way an attempt to "better" Waylon's post - far from it. It's a different way of approaching things, but most importantly, it's a classic example of folks learning together and from each other. Thanks Waylon, I'm looking forward to learning more from what you share.

gha_language: CSS


text:
# Managing ConductR services

During installation ConductR registers a linux service named `conductr`. The service is started automatically during boot-up.

## Service user
The `conductr` service runs as the daemon user `conductr` in the user group `conductr`. When the service is started the first time it creates the user and group itself.

The `conductr` user executes the commands in the background without any shell. You can specify additional environment variables in `/etc/default/conductr`. This file will be sourced before the actual service gets started.

## Change service state

In order to start, stop or restart ConductR on one node change the state of the service.

**sysvinit**

```bash
sudo service conductr start
sudo service conductr stop
sudo service conductr restart
```

## Configuring ConductR

The application.ini file, located in /usr/share/conductr/conf, is the primary configuration file for the ConductR service. This file is used to specify ConductR service settings, such as '-Dconductr.ip' used during installation. See the comments section of the application.ini file for more examples.

Akka module configuration can also be set using this file. For example, to assign a ConductR node the roles of `megaIOPS` and `muchMem` instead of the default, `web`, set `akka.cluster.roles` in application.ini:

```bash
 -Dakka.cluster.roles.0=megaIOPS
 -Dakka.cluster.roles.1=muchMem
```

With this setting the node would offer the roles `megaIOPS` and `muchMem`.Only bundles with a `BundleKeys.roles` of `megaIOPS,` `muchMem` or both `megaIOPS` and `muchMem` will be loaded and run on this node.

The ConductR service must be restarted for changes to this file to take effect.

## Roles

Roles allow machines to be targetted for specific purposes. Some machines may have greater IO capabilities than others, some may have more CPU, memory and other resources. Some may also be required to maintain a volume that holds a database.

When getting started with ConductR it is reasonable to have each ConductR service rely on its default role of `web`. You can also use the `-Dconductr.resource-provider.match-offer-roles=off` declaration of `application.ini` to tell ConductR not to consider roles during scheduling. However when moving into a production scenario you should plan and assign roles for your ConductR cluster.

When a bundle is to be scheduled for loading or scaling, a check is made to first see whether a resource offer's roles intersect with the roles that the bundle requires. If it does then it is eligible. If no resource offers provide the roles required by the bundle, the bundle cannot be loaded or scaled. Bundles will only be loaded to member nodes providing the bundle required roles. If no members of the cluster provide those roles, the bundle will fail to load.

### Using Roles

Roles can be leveraged in varying levels of specificity as needed to achieve the desired results. Small clusters running multiple apps will generally need few roles. Bundles need to be able to relocated to other nodes in the event of failure. Overly dividing a small cluster into small sub-sets reduces relience.  Smaller clusters therefore will generally use few roles to create a few sub-sets of nodes.

Larger clusters on the other hand will generally want more specialization and therefore benefit from further use of roles. Bundles with specific needs, such as resource intensive and data storage applications, will generally want exclusive use of a subset of nodes by using highly specific roles.

## Service Monitoring

For best resilience, the ConductR service daemons should be monitored and restarted in the event of failure. [sbt-native-packager](https://github.com/sbt/sbt-native-packager) has experimental [systemd support](http://www.scala-sbt.org/sbt-native-packager/archetypes/java_server/customize.html#systemd-support). As systemd support matures, ConductR will made available as a package manged by systemd with restart on failure enabled. Until that time, third party daemon monitors can be utilized to provide restart on failure.

# Upgrading ConductR

A running cluster can be upgraded without downtime either at the node or cluster level. On a per node basis, new updated nodes are introduced to the cluster while the old nodes are removed from the cluster. On a per cluster basis, incoming requests are directed from the old cluster to the new cluster using load balancer membership or DNS changes. Per node upgrades are generally easier, however they cannot be performed across ConductR releases that are marked as not compatible with previous releases.

To perform a per node upgrade, introduce new cluster members to the cluster. The new nodes could be created with updated versions of Conductr, Java, the Linux operating system or any other component installed during provisioning. As old members are removed from the cluster, bundles will be relocated to the new resources. It is critical to allow sufficient time for bundle relocation and replication before removing old members. In addition to ConductR replicating bundles to new nodes, stateful bundles may require additional time to replicate application data. Removing a cluster member before application data has fully replicated can result in application data loss. Elasticsearch bundle provided along with ConductR, for example, requires [verification](#Elasticsearch Verification) to ensure the data is transferred into the new member.

Application specific data replication should also be monitored during an upgrade to prevent data loss.

Be certain to ensure that sufficient resources for all roles are provisioned. Stopping the sole member providing a role leaves no members for bundles requiring that role to relocate to. With no nodes to replicate to and run on, affected bundles would require re-loading of the bundle after the role was re-provisioned in order to run again.

To perform a per cluster upgrade, build a new cluster in isolation from the current running cluster. Once the new cluster is fully prepared, cut-over traffic using DNS, load balancers, routers, etc. Per cluster upgrades may require more complicated strategies for migrating data storage managed by the cluster.

## Elasticsearch Verification

To perform deployment on a running cluster without downtime, Elasticsearch requires the new node to join the Elasticsearch cluster, the primary shard(s) is relocated from the old node to the new node, and Elasticsearch master is re-elected if required. Elasticsearch has the means to perform automatic relocation of primary shard(s) from the old node to the new node.

Firstly, we will use Elasticsearch cluster health endpoint to ensure the cluster is in a good health after the new node joined.

```bash
curl -XGET 'http://localhost:9200/_cluster/health?pretty=true'
```

The fields of interest are `status`, `number_of_nodes`, and `unassigned_shards`. The healthy cluster is indicated by the `status` having `green` value.

During the transfer between old node to the new node, the cluster health will transition from `green` to `yellow`, and back to `green` once the new node successfully joined.

It is crucial to wait for this transition to occur successfully.

Once this transition has occurred successfully, the `number_of_nodes` should display the number of running Elasticsearch nodes, and `unassigned_shards` should have the value of `0`. The `unassigned_shards` having the value of `0` means the primary shards has been successfully allocated to all members of the cluster, including the new node.

Next we will use Elasticsearch endpoint to ensure master has been elected. This endpoint will display the name and IP address of the elected master within the Elasticsearch cluster.

```bash
curl -XGET 'http://localhost:9200/_cat/master'
```

Once these steps has been performed with successful result, Elasticsearch cluster should be in a good working order.

## Recovering from Red Elasticsearch Cluster

Should Elasticsearch cluster endpoint `status` has the `red` value, this means one or more shard has not been allocated to the member of the cluster.

The recovery process involves allocating the unassigned shards to the member of the cluster.

 We can also see primary shard `1` and `3` are assigned to the node called `Spectra`, while the node called `Thin Man` and `Sam Wilson` does not have any primary shards assigned.

We will distribute shard `0`, `2`, and `4` between `Thin Man` and `Sam Wilson` to resolve this situation.

To distribute shard `0` to `Thin Man`, we will invoke the cluster reroute endpoint.

```bash
curl -XPOST 'localhost:9200/_cluster/reroute' -d '{
     "commands" : [ {
           "allocate" : {
               "index" : "conductr",
               "shard" : 0,
               "node" : "Thin Man",
               "allow_primary" : true
           }
         }
     ]
 }'
```

Ensure shard is allocated successfully by re-checking the shard allocation.
```bash
curl -XGET 'http://localhost:9200/_cat/shards'
```

The shard `0` should now be allocated to the node called `Thin Man`. Repeat these steps for each of the unassigned shards.

When allocating shards, ensure the shards are distributed as evenly as possible across all nodes of the Elasticsearch cluster. This will improve the resiliency of the cluster.

Once all the shards has been reallocated, the cluster health endpoint `status` should be back to `green` and the Elasticsearch cluster should be back in a working order.

repository: JustinPihony/conductr-doc

repo_name: JustinPihony/conductr-doc


text:
# Exercise 14.13

Which other arithmetic operators, if any, do you think `Sales_item` ought to support? Define those that you think the class should include.

**Answer**:

```cpp
Sales_item& operator-=(const Sales_item &item)
{
    units_sold -= item.units_sold;
    revenue -= item.revenue;
    return *this;
}

Sales_item operator-(const Sales_item &item1, const Sales_item &item2)
{
    Sales_item ret = item1;
    ret -= item2;
    return ret;
}
```


text:
# README

[融云](http://www.rongcloud.cn/) ruby sdk.

## NOTE: This gem is expired, please check out new version at [Martin288/rongcloud-ruby](https://github.com/Martin288/rongcloud-ruby).

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'rongcloud', github: 'FlowerWrong/rongcloud-ruby'
```

And then execute:

    $ bundle install

## Usage

```ruby
# 基本配置
# rails_app/config/initializers/rongcloud.rb
Rongcloud.configure do |config|
  config.app_key = ''
  config.app_secret = ''
  config.host = ''
  config.log_level = :warn
  config.log_file = "#{Rails.root}/log/rongcloud.log"
end
$service = Rongcloud::Service.new

# 获取用户token
$service.get_token('yang', 'yangfusheng', 'https://ruby-china-files.b0.upaiyun.com/user/big_avatar/9442.jpg')

# 创建群组
$service.create_group(user_id, group_id, name = nil)
# 加入群组
$service.add_group(user_id, group_id, name = nil)
# 退出群组
$service.out_group(user_id, group_id)
# 解散群组
$service.dismiss_group(user_id, group_id)
# 刷新群组信息
$service.refresh_group(group_id, name)
```

More usage to see [gem rspec](https://github.com/FlowerWrong/rongcloud-ruby/blob/master/spec/rongcloud/service_spec.rb#L162)

## Rspec

```ruby
cp config.yml.example config.yml
# edit it
rake spec
```

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/FlowerWrong/rongcloud. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).

repository: FlowerWrong/rongcloud-ruby

gha_language: Ruby

repo_name: FlowerWrong/rongcloud-ruby


text:
# Zookeeper deployment

## Single

```bash
make up-single
```

## Ensemble

```bash
make up-ensemble
```

## Observers

Scale Zookeeper nodes to handle a higher load without increasing the number of nodes required to form quorum.

Useful when enabling clients to access ensemble on different Datacenters.

```bash
make up-observers
```

Reference: <https://zookeeper.apache.org/doc/current/zookeeperObservers.html>

## Hierarchical

When deploying Zookeeper in 2 Data Centers, deploying an ensemble becomes difficult as Quorum ends up leaning into one of the datacenters.

Hierarchical deployment makes the weights even between DCs by paying the cost of adding an additional nodes.

The challenge is that quorum has to be maintained inside and outside the groups, so inside a group at least 3 nodes will be required, leading to a cluster with 6 nodes.

Reference: <https://zookeeper.apache.org/doc/current/zookeeperHierarchicalQuorums.html>

repository: jeqo/docker-composes

repo_name: jeqo/docker-composes


text:
## Page
A page is a model which is:
- viewable as a browsable page on the frontend site.
- has a unique url to serve its content.

## Module
A module is a model which is:
- a block element that should be positioned on a page.
- viewable on the frontend site as a portion of a page.

repository: thinktomorrow/chief

gha_language: PHP

repo_name: thinktomorrow/chief


text:
## Data Point Structure

When a subscriber has issued a [subscribe command](Commands.md#subscribe-command) to its publisher for select set of data points, the publisher will start sending [data point packet commands](Commands.md#data-point-packet-commands) each with a payload of several data point values serialized using the `DataPoint` structure, defined as follows:

```C
struct {
  int32 runtimeID;         // -1 if not specified, can optionally be sent instead of `id`.
  SttpValue id;            // A point Identifier.
  SttpValue timestamp;     // A timestamp, SttpTimestamp is highly recommended for this field but not required.
  SttpValue value;         // The single value that represents this Data Point.
  uint64 quality;          // Unstructured quality bits. Quality bits use may be specified in template for standardization - See appendix F for examples.
  SttpValue ExtendedData;  // Additional data that can be sent if `value` is insufficient.
}
DataPoint;
```

The actual number of `DataPoint` structures contained in the data point packet command depends the configured maximum payload size and the serialized size of the data point structures, see [Figure 6](#user-content-figure6).

![Data Packet Command Details](Images/data-packet-command-details.png)

Figure 6

> :information_source: The maximum size of a `DataPoint` structure instance is unspecified, but controlled indirectly at the wire level protocol. With simple encoding techniques this size can be reduced down to a few bytes for most value types.

### Runtime ID
Runtime ID's are negotiated with the connection and are the default value type in the Data Point Structure.  The runtime ID is used to associate a group of communications under a single STTP connection.

While the normal use case is to use RuntimeIDs, for systems that have an indefinite number of IDs, it's not practical to map every point to a Runtime ID. In this case, it's allowed to send the identifier with the measurement.

If no runtime ID is used -1 should be sent

### Data Point Identifier

When identifying a Data Point, one of 4 mechanics are encouraged to identify the source of the time series data.   STTP expects a ID to be unique per data point.  Common ids include:

* [Guid] - Some kind of integer based identifier.
* [String] - This is commonly referred to as a tag in a time series databases.
* [SttpMarkup] - Essentially this is a connection string that combines a set of unique identifiers.

If using a template to standarize metadata the template may specify additional constraints on the ID.  See  [Appendix F - STTP Templates](Templates.md) for example templates

### STTP Value Types

The data types available to a `DataPoint` are described in the `ValueType` enumeration, defined below:

```C
enum {
  Null = 0,              // 0-bytes
  Int64 = 1,             // 8-bytes
  Single = 2,            // 4-bytes
  Double = 3,            // 8-bytes
  SttpTime = 4,          // Universal Time with Leap Seconds
  Bool = 5,              // 1-byte
  Guid = 6,              // 16-bytes
  String = 7,            // Limit defined in NegotiateSession
  SttpBuffer = 8,        // Limit defined in NegotiateSession
  SttpMarkup = 9,        // An array of SttpValue. Up to 255 elements.
  SttpBulkTransport = 10 // A pointer to a large object. Data must be requested as a seperate command.
}
ValueTypeCode; // sizeof(uint4), 1-nibble
```

- `Null`: No space occupied
- `Int64`: [64-bit Signed Integer](https://en.wikipedia.org/wiki/Integer_%28computer_science%29#Value_and_representation) (8-bytes, big-endian)
- `Single`: [32-bit Single Precision Floating Point](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) (4-bytes, per [IEEE 754-2008](https://en.wikipedia.org/wiki/IEEE_754))
- `Double`: [64-bit Double Precision Floating Point](https://en.wikipedia.org/wiki/Double-precision_floating-point_format) (8-bytes, per [IEEE 754-2008](https://en.wikipedia.org/wiki/IEEE_754))
- `SttpTime`: [Time as `Timestamp`](https://en.wikipedia.org/wiki/System_time) (8-bytes, see [data point timestamp](#data-point-timestamp))
- `Bool`: [Boolean as 1-bit](https://en.wikipedia.org/wiki/Boolean_data_type) (1-bit, zero is `false`, 1 is `true`)
- `Guid`: [Globally Unique Identifer](https://en.wikipedia.org/wiki/Universally_unique_identifier) (16-bytes, big-endian for all components)
- `String` [Character String as `StringValue`](https://en.wikipedia.org/wiki/String_%28computer_science%29) (encoding is UTF8)
- `SttpBuffer` [Untyped Data Buffer as `BufferValue`](https://en.wikipedia.org/wiki/Data_buffer)
- `SttpMarkup` [Untyped Data Buffer as `BufferValue`](https://en.wikipedia.org/wiki/Data_buffer)
- `SttpBulkTransport` [Untyped Data Buffer as `BufferValue`](https://en.wikipedia.org/wiki/Data_buffer)

### Encoding Methods

When encoding each of these values, a 4-bit ValueTypeCode will be written first, then the value itself will be written. The 4-bit prefix can be optimally eliminated, but a separate encoding algorithm must make that determination.

All serialization will occur through the Bit-Byte-Block. So reference that section for additional serialization details.

Unless specifically called out below, the types are serialized using the BitByteBlock corresponding type.

#### Int64

These values are variable length encoded where leading 0's are not stored. In order to prevent a value of -1 from consuming a full 8 bytes, this value will undergo a lossless transformation of its bits so it has leading 0's. The transformation is described in the following code:

Encoding: rotate left 1, then inverts bits 1-63 if bit 0 is 1.
Decode: invert bits 1-63 if bit0 is 1, then rotate right 1.

``` C
long PackSign(long value)
{
    if (value >= 0)
        return value << 1;
    return (~value << 1) + 1;
}

long UnPackSign(long value)
{
    if ((value & 1) == 0)
        return (value >> 1) & long.MaxValue;
    return (~value >> 1) | long.MinValue;
}
```

After Packing the value, it is serialized using Write8BitSegments.

#### SttpTime

SttpTime is a specially encoded timestamp based on Microsoft's .NET DateTime field, however, a leap second can be added at the end of every minute. There are approximately 145 billion seconds of space unused in the first 62-bits of the DateTime field. However, there are only 5 billion distinct minutes between year 1 and 9999. The space above DateTime.MaxValue has been allocated to a 61st second.

SttpTime is encoded/decoded as a typical int64 consuming 8 bytes (as opposed to a variable length SttpValueTypeCode.Int64)

#### SttpBuffer

This value contains only a byte buffer, and is serialized using `BitByteBlock.Write(byte[] data);`

#### SttpMarkup

At it's core, a SttpMarkup is only a byte buffer, and is serialized using `BitByteBlock.Write(byte[] data);`

See SttpMarkup section for more details on how the internals of this object are serialized.

#### SttpBulkTransport

This value is a pointer type, and contains the following fields.

```C
struct {
  SttpValueTypeCode fundamentalType;  // The type of the underlying data.
  Guid bulkTransportID                // The ID that can be used to request this data.
  long length;                        // The length of the data.
}
SttpBulkTransport;
```

And is serialized as:
- Bits4(fundamentalType);
- Guid(bulkTransportID);
- Int64(length);

repository: joshgay/Specification

repo_name: joshgay/Specification


text:
# Make Change

Write a function that takes a `price` and `amountGiven` from a hypothetical customer and returns the appropriate change that should be returned.
The return value should be an object with the following properties and their respective values: `dollars`, `quarters`, `dimes`, `nickels`, `pennies`.
Your function should return the least number of items possible, however assume you only have dollar bills to give back.

For example, given price `9.49` and amountGiven `10`, your function should return `{ dollars: 0, quarters: 2, dimes: 0, nickels: 0, pennies: 1 }`.

Given price `1` and amountGiven `10`, return `{ dollars: 9, quarters: 0, dimes: 0, nickels: 0, pennies: 0 }`

repository: BootcampersCollective/Coders-Workshop

repo_name: BootcampersCollective/Coders-Workshop


text:
---
title: Music Auto Tagging
categories: projects
tags: [AI, music-tag, classification, metric-learning]
math: false
mermaid: false
---

This project is based on Fall 2021 GCT 634 at KAIST

github link: [https://github.com/YoonjinXD/Music-Auto-Tagging](https://github.com/YoonjinXD/Music-Auto-Tagging)

***

# SUMMARY
1. I implemented and performed related experiments to verify the improvement suggestion for the multi-label classification.
2. I implemented music-tag pair triplet dataset and sampling for music retrieval by tag.
3. I applied data augmentation, multi-channel mel-spectograms and practical searching for hyperparameters as common strategies to improve the models.
4. To improve music tag classification, I suggested the CNN architecture for music data and applied focal loss function.
5. In retrieval problem, I mainly focused on building a triplet data sampling strategy and suggested classification-based triplet sampling.

Through the suggested approaches, the final improved models result in 0.86% roc accuracy for classification and ({'R@1': 0.47634560692813116, 'R@2': 0.6166209464753155, 'R@4': 0.7485045429220182, 'R@8': 0.8455286622762342}) recall for retrieval.

You can check more details in the report [here](https://github.com/YoonjinXD/Music-Auto-Tagging/blob/main/hw2_report.pdf). The approaches and detailed methods for the improvement are explained in section 2. Remained discussion and future study are summarized in section 3.

You can also check all the implementations in the uploaded notebook.

gha_language: Shell


text:
Let's call  `product(x)`  the product of  `x`'s digits. Given an array of integers  `a`, calculate  `product(x)`  for each  `x`  in  `a`, and return the number of distinct results you get.

Example

For  `a = [2, 8, 121, 42, 222, 23]`, the output should be
`uniqueDigitProducts(a) = 3`.

Here are the products of the array's elements:

-   `2`:  `product(2) = 2`;
-   `8`:  `product(8) = 8`;
-   `121`:  `product(121) = 1 * 2 * 1 = 2`;
-   `42`:  `product(42) = 4 * 2 = 8`;
-   `222`:  `product(222) = 2 * 2 * 2 = 8`;
-   `23`:  `product(23) = 2 * 3 = 6`.

As you can see, there are only  `3`  different products:  `2`,  `6`  and  `8`.

Input/Output

-   **[execution time limit] 3 seconds (cs)**

-   **[input] array.integer a**

    _Guaranteed constraints:_
    `1 ≤ a.length ≤ 105`,
    `1 ≤ a[i] ≤ 109`.

-   **[output] integer**

    -   The number of different digit products in  `a`.

repository: M-Ekrim/codeSignal

repo_name: M-Ekrim/codeSignal


text:
# sfOauthServerPlugin

## Introduction

This plugin allows you to create easily an authentication system for a module or an action. It works with OAuth 1.0 and 2.0 For example, it allows you to secure an API and control access and permissions of each customer (application).

If you find bugs or if you have some suggestions, please contact me.

## Installation

  * Install the plugin (via a package)

        symfony plugin:install sfOauthServerPlugin

  * Activate the plugin in the `config/ProjectConfiguration.class.php`

        [php]
        class ProjectConfiguration extends sfProjectConfiguration
        {
          public function setup()
          {
            $this->enablePlugins(array(
              'sfDoctrinePlugin',
              'sfDoctrineGuardPlugin',
              'sfOauthServerPlugin'
            ));
          }
        }
  * Rebuild your model

  * Enable modules
There are five modules in this plugin : sfOauthAuth, sfOauthApplication,sfOauthDeveloper sfOauthAdmin, sfOauthTest

sfOauthAuth : to exchange token and code for the authentication.

sfOauthApplication : has just one action for the moment : authorize
 It is in this action that an user accept or not an application to access to data.

sfOauthDeveloper : It is for developers. You can define developers for an application. For the moment they can change some parameters and see how many people use their application.

sfOauthAdmin : for the backend to manage consumers.

sfOauthTest: examples.

You have to enabled these modules in yours applications.
( In my case, i have three applications :  api where "sfOauthAuth" is enabled, the frontend ("sfOauthApplication" and "sfOauthDeveloper enabled) and the backend with "sfOauthAdmin". )

  * For example :

         Enable the modules sfOauthAuth in "settings.yml" file of api application
          all:
           .settings:
             enabled_modules: [...,sfOauthAuth]

## Usage
Now to secure a module/action, just create a config file "oauth.yml" in the config repertory of the module.
It works exactly like the security.yml

  * This is an example of configuration :

        oauth.yml
        all:
          is_secure : false
        info:
          is_secure : true
        permissions : [ read , write ]

For more information about how write permissions please see here : [http://www.symfony-project.org/jobeet/1_4/Doctrine/en/13#chapter_13_sub_authorization](http://www.symfony-project.org/jobeet/1_4/Doctrine/en/13#chapter_13_sub_authorization)

To fix permissions (or scope) of a consumer, just write them in the field scope of sfOauthServerConsumer with a space between eatch right.
for example :

  `$consumer->setScope('read write');`

## How it works

This plugin uses two vendor libraries :

  * **oauth2-php** [http://code.google.com/p/oauth2-php/](http://code.google.com/p/oauth2-php/)
  * **oauth** [http://code.google.com/p/oauth2-php/](http://code.google.com/p/oauth-php/)

When requests from application are not good they throw exceptions. By default symfony catch them and show an 500 internal error for the production and an error page with many information about exceptions for developmennt.
sfOauthServerPlugin listens exceptions (event : 'application.throw_exception') and if the type (class name) is OAuthException it treats it to show it in the good way and readable for application.
Two formats are avaibles for the display of exceptions ( json and xml) but you can easily add an other by adding a file in /sfOauthServerPlugin/config/error/error.myformat.php

You can find more informations about OAuth authentication steps in the repertory "doc"

## License and credits

This plugin has been developed by Jean-Baptiste Cayrou and is licensed under the MIT license.

extension: markdown


text:
# Wave Function Collapse and Growing Grids

![alt text](https://github.com/axksel/WFC-GG/blob/CleanupBranch/rpgGame/Assets/Images/by.png)
Wave Function Collapse and Growing Neural Grids combined! The main branch is cleaned up version  of our implementation without all the extra things we have worked on. The project was made for our master thesis. The master thesis can be found [here](https://www.researchgate.net/publication/334416222_Expanding_Wave_Function_Collapse_with_Growing_Grids_for_Procedural_Content_Generation_Project_Expanding_Wave_Function_Collapse_with_Growing_Grids_for_Procedural_Content_Generation).

#### Modulesets.
The modulesets are all based on marching squares. A really good introduction can be found [here](https://www.boristhebrave.com/2013/07/14/tileset-roundup/).

#### Growing Grid
The growing grid implementation is based on Dr. Bernd Fritzkes [work](https://www.demogng.de/) .
The adjustable parameters is largely the same as in his implementation and a explanation can found at the demo website.

#### Instructions
There are three different modulesets included. Each have a scriptable object that needs to be added to the "gridmanager" script in the main gameObject.

- 3dModuleSet. This set contains a city moduleset made for three dimmensions. The bool "Corner Setup Clockwise" should be false when using this set.

- HandDrawnset. This is a two dimmensional set of a handrawn city. The Grid Y should be set to 1 and the "Corner Setup Clockwise" should be true.

- modules. This is the original set and is a 2.5 dimmensional cavern set. The Grid Y should be set to 1 and the "Corner Setup Clockwise" should be true.

![alt text](https://github.com/axksel/WFC-GG/blob/CleanupBranch/rpgGame/Assets/TestStuff/outputfromhandrawn.PNG)

#### Made by
- [Tobias]( https://github.com/Tobiasnm)
- [Jonas]( https://github.com/axksel)

repository: axksel/WFC-GG

branch_name: refs/heads/CleanupBranch

gha_language: C#

repo_name: axksel/WFC-GG


text:
# Problem Shooting

## Node Down at RabbitMQ Server

You can see [here](https://www.techsfo.com/blog/2013/06/rabbitmq-breaks-when-you-rename-hostname/) when you confront the following problem:

```bash
Error: unable to connect to node 'rabbit@somename': nodedown
```

repository: Kipsora/KitJudge

repo_name: Kipsora/KitJudge


text:
---
title: How to check if a point is inside a rectangle in JavaScript
tags:
    - JavaScript
    - ES6
    - one-line
    - js
    - Math
layout: note
---

In this Article we will go through how to check if a point is inside a rectangle only using single line of code in JavaScript.
This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`.

Let's define this short function:

```js {.wrap}
const isInside = (point, rect) => point.x > rect.left && point.x < rect.right && point.y > rect.top && point.y < rect.bottom;
```


text:
# Cavs guard Porter suspended 1 game for bumping official

Published at: **2019-11-05T10:33:23+00:00**

Author: **Associated Press**

Original: [Fox News](https://www.foxnews.com/sports/cavs-guard-porter-suspended-1-game-for-bumping-official)

Cavaliers rookie guard Kevin Porter Jr. has been suspended by the NBA for one game without pay for bumping an official.
At the end of the third quarter of Cleveland's 131-111 loss to Dallas on Sunday night, Porter brushed into referee Bill Spooner's shoulder as he ran back down the floor after missing a shot. The contact knocked Spooner off balance, and he immediately looked at Porter, who didn't turn around.
The league announced the discipline for Porter on Monday.
The Cavs drafted the 19-year-old Porter with the No. 30 overall pick in this year's draft. Considered one of the most talented players available, he was passed over by some teams after being suspended for conduct issues at Southern California. He played 21 games for the Trojans.
Porter is averaging 5.3 points in six games for the Cavs, who host the Boston Celtics on Tuesday night.

license: Unlicense

repository: dsadlollioygjmzvcxv/tdc-exported

repo_name: dsadlollioygjmzvcxv/tdc-exported