text:
---
layout: post
title: "Freedom Trail"
date: 2018-03-22 00:00:00 -0600
category: Tech
tags: DP
cover: /assets/freedom_trail_cover.png
math: true
---

### Introduction

This article is about the research on the algorithm problem "Freedom Trail".

Quoting from [LeetCode 514](https://leetcode.com/problems/freedom-trail/description/),

> In the video game Fallout 4, the quest "Road to Freedom" requires players to reach a metal dial called the "Freedom Trail Ring", and use the dial to spell a specific keyword in order to open the door.

> Given a string ring, which represents the code engraved on the outer ring and another string key, which represents the keyword needs to be spelled. You need to find the minimum number of steps in order to spell all the characters in the keyword.

> Initially, the first character of the ring is aligned at 12:00 direction. You need to spell all the characters in the string key one by one by rotating the ring clockwise or anticlockwise to make each character of the string key aligned at 12:00 direction and then by pressing the center button.
> At the stage of rotating the ring to spell the key character key[i]:
> 1. You can rotate the ring clockwise or anticlockwise one place, which counts as 1 step. The final purpose of the rotation is to align one of the string ring's characters at the 12:00 direction, where this character must equal to the character key[i].
> 2. If the character key[i] has been aligned at the 12:00 direction, you need to press the center button to spell, which also counts as 1 step. After the pressing, you could begin to spell the next character in the key (next stage), otherwise, you've finished all the spelling.

> Example:

> Input: ring = "godding", key = "gd"
> Output: 4

> Explanation:
> For the first key character 'g', since it is already in place, we just need 1 step to spell this character.
> For the second key character 'd', we need to rotate the ring "godding" anticlockwise by two steps to make it become "ddinggo".
> Also, we need 1 more step for spelling.
> So the final output is 4.

This problem seems intimidating at first, but it's actually a textbook dynamic programming problem. Below I give my process of thoughts on it. This article is also published on [LeetCode discuss](https://discuss.leetcode.com/topic/121027/solution-by-zachwen).

#### Approach #1 Brute Force

**Intuition**

The very natural brute force approach is to simply try all possible paths to finish the desired key, and return the length of the shortest one.

**Algorithm**

Let the length of `ring` be `r`, and that of `key` be `k`. Since the string `ring` is circular, the distance between any two indices is bound by floor of $$\frac{r}{2}$$. The calculation of this "circular distance" is encapsuled in the helper function `circularDistance`.

In this naive (in terms of both space and time complexity) solution, the vector `paths` holds a list of pairs, for which the `first` of the pair is the number of steps to reach current state, and the `second` of the pair is the current index in the `ring`. We process each character of `key` one by one, and for each one of them, we find every possible move (duplicate of this character) in the ring, and expand our vector of paths by calculating the current "circular distance", which we add to each one of the existing paths of the previous step, to find our paths for this step. Finally, we iterate through all paths and find the one with minimum steps.

This solution is terribly naive and should not be taken seriously. It is only for illustrating the natural thought after first encountering the problem.

**C++**

```c++
class Solution {
public:
    int findRotateSteps(string ring, string key) {
        int r = ring.size(), k = key.size();
        vector<pair<int, int>> paths(1, make_pair(0, 0));
        for (int i = 0; i < k; ++i) {
            vector<pair<int, int>> currentPaths;
            for (int j = 0; j < r; ++j)
                if (key[i] == ring[j])
                    for (auto path : paths)
                        currentPaths.push_back(make_pair(path.first + circularDistance(r, path.second, j), j));
            paths = currentPaths;
        }
        int minSteps = INT_MAX;
        for (auto path : paths)
            if (path.first < minSteps)
                minSteps = path.first;
        return minSteps + k;
    }
    int circularDistance(int n, int i, int j) {
        int d = abs(j - i);
        return d > n / 2 ? n - d : d;
    }
};
```

**Complexity Analysis**

* Time complexity: $$O(kr^k)$$.

Every character of `key` (length $$k$$) is process one by one, and for each of them, we iterate through `ring` (length $$r$$) and find all possible moves for current step, and for each step, we iterate through the previous steps to find all the current steps. The number of steps is bound by $$O(r^k)$$.

Thus the time complexity is: $$O(kr^k)$$.

* Space complexity: $$O(r^k)$$.

Here `paths` is bounded by $$r^k$$.

---
#### Approach #2 DFS Recursion with Memoization

**Intuition**

Use depth first search to explore the solution space of possible paths: choose the path with optimal step number at every step, instead of choosing the optimal path out of all steps at last.

**Algorithm**

The definition of `r` and `k` and the helper function `circularDistance` are the same as in last approach.

We employ recursion to process each character of `key`, and choose the current move out of moves available at this step top-down. The variable `ringIdx` represents the index in `ring` of current step, and `keyIdx` is the index in `key` that is being processed at this step. `c` is a minor optimization structure that keeps track of the indices of all duplicates of a character in `ring`.

**C++**

```c++
class Solution {
private:
    unordered_map<char, vector<int>> c;
public:
    int findRotateSteps(string ring, string key) {
        for (int i = 0; i < ring.size(); ++i)
            c[ring[i]].push_back(i);
        return rotate(ring, key, 0, 0);
    }

    int rotate(string ring, string key, int ringIdx, int keyIdx) {
        if (keyIdx >= key.size())
            return 0;
        int distance = INT_MAX;
        for (int possibleIdx : c[key[keyIdx]]) {
            distance = min(distance, 1 + circularDistance(ring.size(), ringIdx, possibleIdx) + rotate(ring, key, possibleIdx, keyIdx + 1));
        }
        return distance;
    }

    int circularDistance(int n, int i, int j) {
        int d = abs(j - i);
        return d > n / 2 ? n - d : d;
    }
};
```

Note that the above solution will still result in "Time Limit Exceeded" because it has overlapping sub-problems. A memoization could be easily added to reduce the time complexity: `ringIdx` and `keyIdx` combined could encode a unique state of the exploration in the solution space, so they can be used as the key value of memoization structure, which is simply a 2-D matrix of `r` by `k`.

```c++
class Solution {
private:
    unordered_map<char, vector<int>> c;
    vector<vector<int>> mem;
public:
    int findRotateSteps(string ring, string key) {
        for (int i = 0; i < ring.size(); ++i)
            c[ring[i]].push_back(i);
        mem = vector<vector<int>>(ring.size(), vector<int>(key.size(), 0));
        return rotate(ring, key, 0, 0);
    }

    int rotate(string ring, string key, int ringIdx, int keyIdx) {
        if (keyIdx >= key.size())
            return 0;
        if (mem[ringIdx][keyIdx])
            return mem[ringIdx][keyIdx];
        int distance = INT_MAX;
        for (int possibleIdx : c[key[keyIdx]]) {
            distance = min(distance, 1 + circularDistance(ring.size(), ringIdx, possibleIdx) + rotate(ring, key, possibleIdx, keyIdx + 1));
        }
        mem[ringIdx][keyIdx] = distance;
        return distance;
    }

    int circularDistance(int n, int i, int j) {
        int d = abs(j - i);
        return d > n / 2 ? n - d : d;
    }
};
```

**Complexity Analysis**

* Time complexity: $$O(r^k)$$, without memoization; $$O(r^2k)$$, with memoization.

From the recurrence we know the following equations to be true, where $$k$$ stands for length of `key`:

$$T(k) = rT(k - 1)$$

$$rT(k - 1) = r^2T(k - 2)$$

$$...$$

$$r^{k - 1}T(1) = r^kT(0)$$

Adding them all yields: $$T(k) = r^kT(0)$$.

Hence the time complexity is: $$O(r^k)$$.

See next approach for time complexity analysis for the memoized version.

* Space complexity: $$O(1)$$, without memoization; $$O(rk)$$, with memoization.

---
#### Approach #3 Dynamic Programming Bottom-Up

**Intuition**

Process `key` one by one, bottom-up. At each step, calculate and store the current optimal paths for re-use in next step.

**Algorithm**

The idea is basically the same as last approach with memoization, but implemented using the bottom-up approach, saving much of the recursion overhead.

The algorithm logic should be self-evident from reading the code and variable names. A catch is that the memoization structure must be initialized with `INT_MAX`, except `dp[0]`, which should be filled with zeros. Here `prevStep` and `currStep` are indices in `ring`, and `dp[i][currStep]` represents the optimal step number after processing `key[i - 1]`, with the current move stepped on `ring[currStep]`. At last, we find the optimal path in `dp[k]` with STL's quick select function.

**C++**

```c++
class Solution {
private:
    unordered_map<char, vector<int>> c;
public:
    int findRotateSteps(string ring, string key) {
        int r = ring.size(), k = key.size();
        for (int i = 0; i < r; ++i)
            c[ring[i]].push_back(i);
        vector<vector<int>> dp(k + 1, vector<int>(r, INT_MAX));
        vector<int> prevSteps(1, 0);
        fill(dp[0].begin(),dp[0].end(),0);
        for (int i = 1; i <= k; ++i) {
            for (int prevStep : prevSteps)
                for (int currStep : c[key[i - 1]])
                    dp[i][currStep] = min(dp[i][currStep], circularDistance(r, prevStep, currStep) + dp[i - 1][prevStep]);
            prevSteps = c[key[i - 1]];
        }
        nth_element(dp[k].begin(), dp[k].begin(), dp[k].end());
        return dp[k][0] + k;
    }

    int circularDistance(int n, int i, int j) {
        int d = abs(j - i);
        return d > n / 2 ? n - d : d;
    }
};
```

**Complexity Analysis**

* Time complexity: $$O(r^2k)$$.

The algorithm only consists of a three nested loops. The outer loop has `k` iterations, and the middle and inner one have `prevSteps` and `currSteps` iterations which are both bounded by `r`. The last quick select is $$O(r)$$. Hence the time complexicity: $$O(r^2k)$$.

* Space complexity: $$O(rk)$$.

 Signing off.

repository: zachwen/thoughts

repo_name: zachwen/thoughts


text:
---
title: "Block Pod Exec by Pod Label"
category: Sample
version: 1.4.2
subject: Pod
policyType: "validate"
description: >
    The `exec` command may be used to gain shell access, or run other commands, in a Pod's container. While this can be useful for troubleshooting purposes, it could represent an attack vector and is discouraged. This policy blocks Pod exec commands to Pods having the label `exec=false`.
---

## Policy Definition
/other/block-pod-exec-by-pod-label.yaml

```yaml
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: deny-exec-by-pod-label
  annotations:
    policies.kyverno.io/title: Block Pod Exec by Pod Label
    policies.kyverno.io/category: Sample
    policies.kyverno.io/minversion: 1.4.2
    policies.kyverno.io/subject: Pod
    policies.kyverno.io/description: >-
      The `exec` command may be used to gain shell access, or run other commands, in a Pod's container. While this can
      be useful for troubleshooting purposes, it could represent an attack vector and is discouraged.
      This policy blocks Pod exec commands to Pods having the label `exec=false`.
spec:
  validationFailureAction: enforce
  background: false
  rules:
  - name: deny-exec-by-label
    match:
      resources:
        kinds:
        - PodExecOptions
    context:
    - name: podexeclabel
      apiCall:
        urlPath: "/api/v1/namespaces/{{request.namespace}}/pods/{{request.name}}"
        jmesPath: "metadata.labels.exec"
    preconditions:
    - key: "{{ request.operation }}"
      operator: Equals
      value: CONNECT
    validate:
      message: Exec'ing into Pods protected with the label `exec=false` is forbidden.
      deny:
        conditions:
          - key: "{{ podexeclabel }}"
            operator: Equals
            value: "false"

```

branch_name: refs/heads/main

extension: md

license_type: permissive


text:
---
layout: default
---

# 1995-09-16 - Re: CYPHERPUNK harmful.  THE TRUTH IS TOLD

## Header Data

From: Bill Stewart<EMAIL_ADDRESS>To: Steven Greenberg<EMAIL_ADDRESS>Message Hash: 8dc8fc22d48535d6841871227d7237842d1bf818956b2034b505ef15f551e5ce

Message ID<EMAIL_ADDRESS>Reply To: _N/A_

UTC Datetime: 1995-09-16 01:27:20 UTC

Raw Date: Fri, 15 Sep 95 18:27:20 PDT

## Raw message

```
{% raw  %}From: Bill Stewart<EMAIL_ADDRESS>Date: Fri, 15 Sep 95 18:27:20 PDT
To: Steven Greenberg<EMAIL_ADDRESS>Subject: Re: CYPHERPUNK harmful.  THE TRUTH IS TOLD
Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text/plain

>Hmmmm... If memory serves, a year or so ago there was just such a schism
>when a prominent cypherpunk split off and formed the "cypherWONKS" list.

:-) :-)  And starting a new list lets us decided on a new LOGO to replace
that old tacky rose-and-bits thingy :-)

Cryptographic Professionals for Social Responsibility
Cryptographic Industry Association
National Steganography Alliance
Cryptographers for Foreign Reflexivity
Extremely Private Institute for Cryptography
NII Institute of Cryptography
American Cryptographic Legal Union
Free Banking Institute
Cryptographic Defense Taskforce
Cryptographic Organization for Privacy and Security
Entropy, Steganography, and Cryptography Research Organization for Women

(If anything, what we need is a way to separate the technical/mathematical
discussions from rants like this, but any time we get the list focused
on mostly technical issues, the government goes out of its way to do
something egregiously stupid or offensive...)

Somewhat more seriously, though, there are times that it's useful to have
a more respectable-sounding organization (or at least a letterhead...),
that's open to participation by members and not just directors (which has
been some people's concern about the EFF, CDT, EPIC, and maybe TAP or CPSR.)

If none of those are respectable/accessible/non-socialist enough for you,
and the
British Cryptographic Privacy Association (or whatever their name was)
can't be found or sounds too much like International Outside Agitators,
and the various academic groups are too busy being academicly respectable
to do political agitation ("CryptoAcademics Write Papers!"),
then come up with a name and a Postscript letterhead, and start an
email list that you can gateway to cypherpunks (as long as you can
prevent duplications or mail-floods.)  If the main goal is to have a calmer
name and mostly the same activities, an alter-ego mailing list is one approach.

#---
# Bill Stewart, Freelance Information Architect<EMAIL_ADDRESS># Phone +1-510-247-0664 Pager/Voicemail 1-408-787-1281
#---

{% endraw %}
```

## Thread

+ Return to [September 1995](/archive/1995/09)

+ Return to "[Bill Stewart <stewarts@ix.netcom.com>](/authors/bill_stewart_stewarts_at_ix_netcom_com_)"

+ 1995-09-16 (Fri, 15 Sep 95 18:27:20 PDT) - Re: CYPHERPUNK harmful.  THE TRUTH IS TOLD - _Bill Stewart<EMAIL_ADDRESS>

license: MIT

branch_name: refs/heads/master

gha_license_id: MIT


text:
# QEMU Provider
UniK supports running rumprun unikernels through QEMU.
In order to run on QEMU, you must have `qemu` installed.

To run UniK instances with QEMU, add a QEMU stub to your `daemon-config.yaml`:

```yaml
providers:
  #...
  qemu:
    - name: my-qemu
      no_graphic: false
```

`no_graphic` specifies whether or not QEMU instances will be launched using a `no-graphic` mode. Set to `true` for environments with no desktop/graphical interface.

As QEMU is not a full hypervisor, the QEMU provider has some limitations, and is ideal mostly for debugging unikernels.

The QEMU provider supports the `--debug-mode` option for running unikernels, which will launch a unikernel in *stopped* mode and attach [`gdb`](https://www.gnu.org/software/gdb/) remotely to the unikernel, allowing line-by-line debugging of the source code for the unikernel.

Limitations of QEMU provider:
* Instances cannot be powered down. Powering down an instance will terminate it. Killing the UniK Daemon will terminate all QEMU instances, but they will still have to be deleted from UniK's state with `unik rm --instance <instance_name>` in order for UniK to know they are no longer running.
* QEMU instances will be assigned IPs and will have network connectivity, but will not be reachable from the host network. It is possible to configure a `tap` device with a bridge to enable instances to be reachable, but we are not supporting this feature at this time.
* QEMU instances do not make use of the UniK bootstrapping stub/wrapper.

repository: urjitbhatia/unik

repo_name: urjitbhatia/unik


text:
---
title: Cloud Manager - Cloud Services FAQs
seo-title: Cloud Manager FAQs
description: Refer to Cloud Manager for Cloud Services FAQs to get some troubleshooting tips
seo-description: Follow this page to get answers on Cloud Manager - Cloud Services FAQs
exl-id: eed148a3-4a40-4dce-bc72-c7210e8fd550
---
# Cloud Manager FAQs {#cloud-manager-faqs}

The following section provides answers to frequently asked questions related to Cloud Manager for Cloud Services.

## Is it possible to use Java 11 with Cloud Manager builds? {#java-11-cloud-manager}

AEM Cloud Manager build fails when attempting to switch the build from Java 8 to 11. The problem can have many causes and most common ones are documented below:

* Add the maven-toolchains-plugin with the correct settings for Java 11 as documented [here](https://experienceleague.adobe.com/docs/experience-manager-cloud-manager/using/getting-started/create-application-project/using-the-wizard.html?lang=en#getting-started).  For example, see the [wknd sample project code](https://github.com/adobe/aem-guides-wknd/commit/6cb5238cb6b932735dcf91b21b0d835ae3a7fe75).

* If you encounter the error below then you need to remove use of `maven-scr-plugin` and convert all OSGi annotations to OSGi R6 annotations. For instructions, see [here](https://cqdump.wordpress.com/2019/01/03/from-scr-annotations-to-osgi-annotations/).

   `[main] [ERROR] Failed to execute goal org.apache.felix:maven-scr-plugin:1.26.4:scr (generate-scr-scrdescriptor) on project helloworld.core: /build_root/build/testsite/src/main/java/com/adobe/HelloWorldServiceImpl.java : Unable to load compiled class: com.adobe.HelloWorldServiceImpl: com/adobe/HelloWorldServiceImpl has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0 -> [Help 1]`

* For Cloud Manager builds, the maven enforcer plugin fails with error `"[main] [WARNING] Rule 1: org.apache.maven.plugins.enforcer.RequireJavaVersion"`. This is a known issue due to Cloud Manager using a different version of Java to run the maven command versus compiling code. For now, omit `requireJavaVersion` from your maven-enforcer-plugin configurations.

## Our deployment is stuck because the Code Quality check failed. Is there a way to bypass this check? {#deployment-stuck}

All Code Quality failures except for *Security Rating* are non-critical metrics, so they can be bypassed by expanding the items in the results UI.

A user with [Deployment Manager, Project Manager, or Business Owner](https://experienceleague.adobe.com/docs/experience-manager-cloud-manager/using/requirements/setting-up-users-and-roles.html?lang=en#requirements) role can override the issues, in which case the pipeline proceeds or they can accept the issues, in which case the pipeline stops with a failure.  See [Three-Tier Gates while Running a Pipeline](https://experienceleague.adobe.com/docs/experience-manager-cloud-manager/using/how-to-use/understand-your-test-results.html?lang=en#how-to-use) for more details.

## Are we allowed to use SNAPSHOT in the version of the Maven project? How does versioning of the packages and bundle jar files work for Stage and Production deployments? {#snapshot-version}

Refer to the following scenarios to learn about versioning of the packages and bundle jar files for Stage and Production deployments:

1. For developer deployments, the Git branch `pom.xml` files must contain `-SNAPSHOT` at the end of the `<version>` value. This allows subsequent deployment where the version does not change to still get installed. In developer deployments, no automatic version is added or generated for the maven build.

1. In Stage and Production deployment, an automatic version is generated as documented [here](https://experienceleague.adobe.com/docs/experience-manager-cloud-manager/using/managing-code/activating-maven-project.html?lang=en#managing-code).

1. For custom versioning in Stage and Production deployments, set a 3 part proper maven version like `1.0.0`. Increase the version each time you have to do another deploy to production.

1. Cloud Manager automatically adds its version to Stage and Production builds and even creates a Git branch. No special configuration is required. If step 3 above is skipped, the deployment would still work fine and a version would automatically be set.

1. There are no issues, if you leave the version with `-SNAPSHOT` for Stage and Production builds or deployments. Cloud Manager automatically sets a proper version number and creates a tag for you in Git. This tag can be referred to later, if required.

1. If you want to try out some experimental code on Development environment, you can create a new Git branch and set the pipeline to use that different branch. This is useful when deployments start failing and you would like to test with older versions of the code to see when it broke.

   The Git command below creates a remote branch named *testbranch1* against a specific pre-existing commit `485548e4fbafbc83b11c3cb12b035c9d26b6532b`.  This special branch could be used in Cloud Manager without affecting any other branches:

   `git push origin 485548e4fbafbc83b11c3cb12b035c9d26b6532b:refs/heads/testbranch1`

   See the [Git documentation](https://git-scm.com/book/en/v2/Git-Internals-Git-References) for more details.

   If you want to delete the test branch later, then use the delete command:

   `git push origin --delete testbranch1`

## Maven build fails in Cloud Manager deploys but builds locally without errors. How to debug? {#maven-build-fail}

See [Git Resource](https://github.com/cqsupport/cloud-manager/blob/main/cm-build-step-fails.md) for more details.

## What to do if Cloud Manager deployment fails at deploy step in AEM as a Cloud Service Environment? {#cloud-manager-deployment-cloud-service}

The most common reason for deploys to fail is due to insufficient permissions for the *sling-distribution-importer* user.
Refer to the example below to understand an issue, cause, and solution:

**Issue**
During a Cloud Manager deployment on AEM as a Cloud Service environments the deploy step fails and errors like the ones below are observed.

`[Queue Processor for Subscriber agent forwardPublisherSubscriber] org.apache.jackrabbit.vault.fs.io.Importer Error while committing changes. Retrying import from checkpoint at /. Retries 4/10`
`[Queue Processor for Subscriber agent forwardPublisherSubscriber] org.apache.sling.distribution.journal.impl.subscriber DistributionSubscriber Error processing queue item`
`org.apache.sling.distribution.common.DistributionException: Error processing distribution package`
`dstrpck-1583514457813-c81e7751-2da6-4d00-9814-434187f08d32. Retry attempts 162/infinite.`
`Caused by: org.apache.sling.api.resource.PersistenceException: Unable to commit changes to session.`
`Caused by: javax.jcr.AccessDeniedException: OakAccess0000: Access denied [EventAdminAsyncThread #7] org.apache.sling.distribution.journal.impl.publisher.DistributionPublisher [null] Error processing distribution package` `dstrpck-1583514457813-c81e7751-2da6-4d00-9814-434187f08d32. Retry attempts 344/infinite. Message: Error trying to extract package at path /etc/packages/com.myapp/myapp-base.ui.content-5.1.0-SNAPSHOT.`

**Cause**

The sling-distribution-importer user needs additional permissions per the content paths defined in the ui.content package.  This usually means we need to add permissions for both /conf and /var.

**Solution**
The solution to this is to add a [RepositoryInitializer OSGi configuration](https://experienceleague.adobe.com/docs/experience-manager-cloud-service/implementing/deploying/overview.html?lang=en#deploying) script to your apps deployment package to add ACLs for the sling-distribution-importer user.
In the example error above, the package myapp-base.ui.content-*.zip includes content under `/conf` and `/var/workflow`. In order for the deployment to not fail, we would need to add permissions for sling-distribution-importer under those paths.
Here's an example [org.apache.sling.jcr.repoinit.RepositoryInitializer-DistributionService.config](https://github.com/cqsupport/cloud-manager/blob/main/org.apache.sling.jcr.repoinit.RepositoryInitializer-distribution.config) of one such OSGi configuration that adds additional permissions for the sling-distribution-importer user.  This configuration adds permissions under /var.  This xml file below [1] needs to be added to the application package under `/apps/myapp/config` (where myapp is the folder where your application code is stored).
org.apache.sling.jcr.repoinit.RepositoryInitializer-DistributionService.config

1. If the *sling-distribution-importer* is not the cause, then the deploy might be failing due to a bad OSGi configuration that breaks an out of the box service. Check the logs during deployment to see if there are any obvious errors.

1. The deployment might fail due to bad dispatcher or apache configurations. Make sure to test your Apache configurations and Dispatcher configurations locally using the Docker image included in the SDK. See [Dispatcher in the Cloud](https://experienceleague.adobe.com/docs/experience-manager-cloud-service/implementing/content-delivery/disp-overview.html?lang=en#content-delivery) on how to set up the dispatcher Docker container for easy local testing.

1. The deployment might fail due to some other failure during replication of the content packages (sling distribution) from author to publish instances.

   Refer to the steps below to simulate this on a local setup:

      * Install an Author and Publish instance (using the latest AEM SDK jars)
      * Log into the Author instance
      * Go to **Tools** -> **Deployment** -> **Distribution**
      * Distribute the content packages that are part of the code base and see if the queue gets blocked with an error

## Unable to set a variable via aio cloud manager set pipeline variables. How to debug these issues? {#set-variable}

If you are getting a `403` error when attempting to list or set pipeline variables via commands similar to the ones below, then you need to be added as a *Deployment Manager* Cloud Manager product role in the Admin Console.
See [API Permissions](https://www.adobe.io/apis/experiencecloud/cloud-manager/docs.html#!AdobeDocs/cloudmanager-api-docs/master/permissions.md) for more details.

Related commands and errors:

`$ aio cloudmanager:list-pipeline-variables 222`

*Error*: `Cannot get variables: https://cloudmanager.adobe.io/api/program/111/pipeline/222/variables (403 Forbidden)`

`$ aio cloudmanager:set-pipeline-variables 222 --variable TEST 1`

*Error*: `Cannot get variables: https://cloudmanager.adobe.io/api/program/111/pipeline/222/variables (403 Forbidden)`

`$ aio cloudmanager:set-environment-variables 1755 --variable TEST 1`

`setting variables... !`

*Error*: `Cannot set variables: https://cloudmanager.adobe.io/api/program/111/environment/222/variables (403 Forbidden)`


text:
# utest/core

The "core" tests exist for one main purpose:
To test basic functionality when things like devmgr aren't working.

If the kernel is told to run core-tests instead of devmgr, these tests
will run without any userspace device manager, device drivers, io plumbing,
etc.

## Example usage

```
fx set core.x64   # any of {bringup,core}.{x64,arm64} are fine too.
fx build
fx core-tests [gtest-filter]
```

The helper fx command runs AEMU providing the specially-built core-tests.zbi as
a `-z` argument.

`gtest-filter` can be optionally specified to run only the given gtest suite,
e.g. `fx core-tests 'FutexTest.*'`.

## Notes

The tests here are for "core" functionality (channels, etc.), but
not all "core" functionality can go here.  For example, you can't
start a process in your test with launchpad because core tests are for
when that functionality isn't working.  Core tests can't use fdio and
launchpad uses fdio.

Since these tests can't use fdio core/libc-and-io-stubs.c stubs out the needed
functions from fdio.

repository: oshunter/fuchsia

repo_name: oshunter/fuchsia


text:
# RISC-V

https://riscv.org/technical/specifications/

The RISC-V Instruction Set Manual Volume I: Unprivileged ISA Document Version 20191213
to transrate Japanese language.

The RISC-V Instruction Set ManualVolume 2: Privileged Architecture Privileged Architecture Version 1.10 Document Version 1.10
to transrate Japanese language.

OLD:
The RISC-V Instruction Set ManualVolume I: User-Level ISA Document Version 2.2
to transrate Japanese language.

# License

These codes are licensed under CC0.

[![CC0](http://i.creativecommons.org/p/zero/1.0/88x31.png "CC0")](http://creativecommons.org/publicdomain/zero/1.0/deed.ja)

# Auther

@shibatchii

repository: shibatchii/RISC-V

repo_name: shibatchii/RISC-V


text:
## Last Updated

August 18, 2023

NOTES:
- Removed Mac Workflow support due to persistent up-stream failures in the GitHub action tool for Mac

## Build Status

[![Checks](https://github.com/aladshaw3/cats/actions/workflows/conda-build.yml/badge.svg)](https://github.com/aladshaw3/cats/actions/workflows/conda-build.yml)
[![Checks2](https://github.com/aladshaw3/cats/actions/workflows/personal-conda-build.yml/badge.svg)](https://github.com/aladshaw3/cats/actions/workflows/personal-conda-build.yml)

CATS
=====

Catalysis And Treatment Simulations (CATS)

This MOOSE module is can be used to simulate catalysis reactions in the exhaust systems for vehicles or in electrochemical catalysis for flow batteries and chemical conversion. Combines the standard MOOSE SUPG methods for fluid flow around through the domain and uses DG methods to simulate the mass/energy balances in the fluid streams, as well as electric potential and electric current balances. This module also includes an experimental DG implementation of Navier-Stokes equations for fluid flow.

Methods to resolve microscale intralayer diffusion include: (i) Dividing your full mesh into subdomains and using
interface kernels to transfer mass between macro- and micro-scale subdomains or (ii) Using a hybrid FD/FE method
to resolve the micro-scale for simple geometries, such as spherical/cylindrical particles or monolith walls/washcoat
of roughly uniform thickness.

Properties such as diffusivities, velocities, and mass transfer rates can be calculated using the (i) 'GasProperties' auxiliary system, (ii) the 'SimpleGasProperties' auxilary system, or (iii) the 'SimpleFluidProperties' auxilary system. The 'GasProperties' are
calculated from the full list of gases and associated parameters for each gas species using kinetic theory of
gases. The 'SimpleGasProperties' are easier to use, but make the assumption of an ideal gas that is primarily
made up of non-reactive standard air. Similarly, the 'SimpleFluidProperties' assumes an electrolyte liquid solution made primarily of water.

For more information, please read through the 'CATS-UserGuide-*.pdf' in the home directory of the source code.

Installation and Usage
-----
To use CATS, a user must first download and install the MOOSE framework (https://mooseframework.inl.gov/). Follow the installation instructions contained therein first.

After MOOSE is installed, you can download this source code repository to a sub-directory at the same level as the 'moose/' directory. (e.g., if MOOSE is installed in '(HOME)/projects/moose', then perform the 'git clone ...' commands in the '(HOME)/projects/' directory.)

For example (assuming MOOSE is located in '(HOME)/projects/moose'), do the following in the '(HOME)/projects' folder...

<code> git clone https://github.com/aladshaw3/cats.git </code>

Then, you can build CATS using the 'make' commands in the '(HOME)/projects/cats' folder created. You can
pass the '-j4' argument to run make with multiple processors (in this case, using 4 processors).

NOTE: MOOSE now builds using 'conda' environments. Your 'moose' conda environment MUST be active before
attempting to build the source code. See https://mooseframework.inl.gov/getting_started/installation/conda.html.

<code> make -j4 </code>

NOTE: If this is the first time running the 'make' command, it may take several minutes to an
hour to run, because it will also need to compile all of the MOOSE dependencies as well.

After the source code is built, you can test the code using the 'run_tests' command.

<code> ./run_tests -j4 </code>

This project may update frequently. If you are using this repository, please keep your copy up-to-date. You can
stay up-to-date by using...

<code> git fetch origin </code>

<code> git rebase origin/master </code>

Running the Program
-----
To run CATS, use the command line to run a simulation case by giving the path and name of the input file to run.

For example...

<code> ./cats-opt -i path/to/file.i </code>

Or, to run on multiple CPU cores...

<code> mpiexec --n 4 ./cats-opt -i path/to/file.i </code>

WARNING
-----
There may be a current bug in MOOSE that is caused by applying an integrated boundary
condition on a node set internal to a domain. MOOSE will report an error stating that
the variable does not exist on that node set, however, if you run the code with...

<code> mpiexec --n # ./cats-opt -i path/to/file.i </code>

where # > 1, then the code should run fine. See issue #13 for more information.

Citation
-----
Ladshaw, A.P., "CATS: Catalysis And Treatment Systems -- MOOSE based catalysis simulation tool," https://github.com/aladshaw3/cats, Accessed (Month) (Day), (Year).

Contact Information
-----

For questions, contact Austin Ladshaw<EMAIL_ADDRESS>

gha_language: Assembly


text:
# mdast(3) -- Markdown processor

## SYNOPSIS

```javascript
// Load dependencies:
var mdast = require('./index.js');
var html = require('mdast-html');
var yamlConfig = require('mdast-yaml-config');

// Use plugins:
var processor = mdast().use(yamlConfig).use(html);

// Process the document:
var doc = processor.process([
    '---',
    'mdast:',
    '  commonmark: true',
    '---',
    '',
    '2) Some *emphasis*, **strongness**, and `code`.'
].join('\n'));
```

## DESCRIPTION

This is the application programming interface documentation for **mdast**.
To find documentation for the command line interface, see **mdast**(1).

## mdast.use(plugin\[, options\])

Change the way **mdast** works by using a plugin.  Plugins are documented
at <https://github.com/wooorm/mdast/blob/master/doc/plugins.md>.

**Signatures**

*   `processor = mdast.use(plugin[, options])`;
*   `processor = mdast.use(plugins)`.

**Parameters**

*   `plugin` (`Function`) — Plugin.
*   `plugins` (`Array.<Function>`) — List of plugins.
*   `options` (`Object?`) — Passed to plugin.  Specified by its documentation.

**Returns**

`Object` — An instance of **mdast**.  The instance functions just like the
**mdast** library itself (it has the same methods), but caches the `use`d
plugins.

## mdast.parse(file\[, options\])

Parse a markdown document into an **mdastnode**(7).

**Signatures**

*   `node = mdast.parse(file|value[, options])`.

**Parameters**

*   `file` (`VFile`) — Virtual file;
*   `value` (`string`) — String representation of a file;
*   `options` (`Object`) — Configuration given to the parser.

**Returns**

`Node` — Node.  Nodes are documented at **mdastnode**(7).

## mdast.run(node\[, file\]\[, done\])

Transform a node by applying plug-ins to it. Either a node or a file which
was previously passed to `parse()`, must be given.

**Signatures**

*   `node = mdast.run(node[, file|value][, done])`;
*   `node = mdast.run(file[, done])`.

**Parameters**

*   `node` (`Object`) — Node as returned by `parse()`, see **mdastnode**(7);

*   `file` (`VFile`) — Virtual file;

*   `value` (`string`) — String representation of a file;

*   `done` (`function done(err, node, file)`) — See
    FUNCTION DONE(ERR, NODE, FILE).

**Returns**

`Node` — The given node.

**Throws**

When no `node` was given and no node was found on the file.

### function done(err, node, file)

Invoked when transformation is complete.

**Signatures**

*   `function done(err)`;
*   `function done(null, node, file)`.

**Parameters**

*   `err` (`Error`) — Failure;
*   `node` (`Node`) — Transformed node;
*   `file` (`File`) — File object representing the input file;

## mdast.stringify(node\[, file\]\[, options\])

Compile a node into a document.

**Signatures**

*   `doc = mdast.stringify(node[, file|value][, options])`;
*   `doc = mdast.stringify(file[, options])`.

**Parameters**

*   `node` (`Object`) — Node as returned by `parse()`, see **mdastnode**(7);
*   `file` (`VFile`) — Virtual file;
*   `value` (`string`) — String representation of a file;
*   `options` (`Object`) — Configuration.

**Returns**

`doc` (`string`) — Document.

**Throws**

When no `node` was given and no node was found on the file.

## mdast.process(file\[, options\]\[, done\])

Parse, transform, and compile markdown into something else.

**Signatures**

*   `doc? = mdast.process(file|value[, options][, done])`.

**Parameters**

*   `file` (`File`) — Virtual file;
*   `value` (`string`) — Source of a (virtual) file;
*   `options` (`Object`) — Settings.  See **mdastsetting**(7);
*   `done` (`function done(err?, doc?, file?)`.

**Returns**

`string?` — Document.  Formatted in markdown by default, or in whatever a
plugin generates. When an async transformer is used, `null` is returned and
`done` must be given to receive the results upon completion.

### function done(err?, doc?, file?)

Invoked when processing is complete.

**Signatures**

*   `function done(err)`;
*   `function done(null, doc, file)`.

**Parameters**

*   `err` (`Error`) — Failure;
*   `doc` (`string`) — Document generated by the process;
*   `file` (`File`) — File object representing the input file;

## FileSet()

**mdast**(1) compiles multiple files using a `FileSet` instance.  This set
is exposed to plug-ins as an argument to the attacher. `FileSet`s
should not be created by plug-ins.

## fileSet.valueOf()

## fileSet.toJSON()

Get access to the file objects in a set.

**Signatures**

*   `files = fileSet.valueOf()`.

**Returns**

`Array.<File>` — List of files being processed by **mdast**(1).

## fileSet.use(completer)

Add a completer to the middleware pipeline of a file-set.  When all
files are transformed, this pipeline is run and `completer` is invoked
with `fileSet`.

**Signatures**

*   `fileSet.use(completer)`.

**Parameters**

*   `completer` (`Function`).

## fileSet.add(file|filePath)

Add a new file to be processed by **mdast**(1). The given file is
processed just like other files, with a few differences.

Programmatically added files are:

*   Ignored when their file-path is already added;
*   Never written to the file-system;
*   Not logged about.

**Signatures**

*   `fileSet.use(filePath)`;
*   `fileSet.use(file)`.

**Parameters**

*   `filePath` (`string`) - Path to virtual file;
*   `file` (`File`) - Virtual file.

## BUGS

<https://github.com/wooorm/mdast/issues>

## SEE ALSO

**mdast**(1), **mdastconfig**(7), **mdastnode**(7), **mdastsetting**(7).

## AUTHOR

Written by Titus Wormer<EMAIL_ADDRESS>

repository: anandthakker/mdast

repo_name: anandthakker/mdast


text:
### Origin

The application.

### Proxy

The ingress.

### Scaler

The background controller.

The Go standard library has a built-in reverse proxy. Let's
discuss why that isn't enough for us in a dynamic system like Kubernetes.

gha_language: JavaScript


text:
storcli_show_slots
==================

**Summary**

Display LSI storcli command output in a pictorial grid on your terminal.

**Features**

- light-weight tool for displaying LSI array data using Perl5, no Java or web server needed.
- ANSI color codes for failed pdisks and vdisks.
- No firewall changes needed.

**Technical Details**

- Written in Perl5.
- Tested on a Dell 2950 with PERC6i and PERC5e controllers and several MD1000 disk arrays running CentOS5.

**Screenshot**

`usage: storcli_show_slots`

![storcli_show_slots screenshot](storcli_show_slots.png?raw=true "storcli_show_slots screenshot")

**See Also**

My dell-ipmi-console gocons project for invoking Dell IPMI commands.


text:
# Installation

1. Use VirtualBox for virtualization.
    - Windows: https://download.virtualbox.org/virtualbox/6.0.10/VirtualBox-6.0.10-132072-Win.exe
    - OS X: https://download.virtualbox.org/virtualbox/6.0.10/VirtualBox-6.0.10-132072-OSX.dmg
    - Linux: https://www.virtualbox.org/wiki/Linux_Downloads
1. Create a virtual machine in VirtualBox using Ubuntu 18.04.03 as a base image. Get the .iso here http://releases.ubuntu.com/18.04/
1. Configure the VM with at least 2 CPUs.
1. Configure main memory to use 4 GB.
1. Configure video memory to use the maximum of 128 MB.
1. Call the user ``travis``
1. Set his password to ``password``
1. Update packages

    ```
    sudo apt update
    sudo apt upgrade
    ```

1. Enable Bash completion from history

    ```
    echo '"\e[A": history-search-backward            # arrow up' >> ~/.inputrc
    echo '"\e[B": history-search-forward             # arrow down'  >> ~/.inputrc
    echo 'set completion-ignore-case on' >> ~/.inputrc
    ```

1. Install Java version 11

    ```
    sudo apt install openjdk-11-jre
    ```

1. Get docker (instructions from here https://docs.docker.com/install/linux/docker-ce/ubuntu/#install-docker-ce)

    ```
    # Install packages to allow apt to use a repository over HTTPS:
    sudo apt-get install \
        apt-transport-https \
        ca-certificates \
        curl \
        gnupg-agent \
        software-properties-common

    # Add Docker’s official GPG key:
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

    # Confirm you have the correct key ending in 0EBFCD88
    sudo apt-key fingerprint 0EBFCD88
    pub   rsa4096 2017-02-22 [SCEA]
          9DC8 5822 9FC7 DD38 854A  E2D8 8D81 803C 0EBF CD88
    uid           [ unknown] Docker Release (CE deb<EMAIL_ADDRESS>    sub   rsa4096 2017-02-22 [S]

    # add the correct repository depending on architecture and linux distribution:
    sudo add-apt-repository \
       "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
       $(lsb_release -cs) \
       stable"

    # update package index
    sudo apt-get update

    # install docker packages
    sudo apt-get install docker-ce docker-ce-cli containerd.io
    ```

1. Configure the current user to allow running docker without asking for password

    ```
    # docker install should have created the docker group already, but just in case:
    sudo groupadd docker

    # add current user to docker group
    sudo usermod -aG docker $USER

    # start using the new settings (no sudo)
    # Note: I actually had to reboot to make this work.
    newgrp docker
    ```

1. Install Git

    ```
    sudo apt install git
    ```

1. Get a copy of the tutorial materials:

    ```
    git clone https://github.com/xenon-middleware/xenon-tutorial.git
    ```

1. Install dependencies for generating the Sphinx documentation

    ```
    sudo apt install python3-pip
    cd ~/xenon-tutorial/readthedocs/
    pip3 install --user -r requirements.txt
    ```

1. Add the user-space Python packages to the PATH

    ```
    echo '' >> ~/.bashrc
    echo '# add directory where python has user space packages, e.g. when installing' >> ~/.bashrc
    echo '# with pip3 install --user <package name>' >> ~/.bashrc
    echo 'PATH=$PATH:~/.local/bin' >> ~/.bashrc

    # enable the new settings
    source ~/.bashrc
    ```

1. Generate the Sphinx documentation

    ```
    cd ~/xenon-tutorial/readthedocs/
    sphinx-build -b html . build/
    ```

1. Get a copy of xenon cli, install it, add to PATH:

    ```
    cd ~/Downloads
    wget https://github.com/xenon-middleware/xenon-cli/releases/download/v3.0.4/xenon-cli-shadow-3.0.4.tar
    tar -xvf xenon-cli-shadow-3.0.4.tar
    mkdir -p ~/.local/bin/xenon
    mv xenon-cli-shadow-3.0.4 ~/.local/bin/xenon/

    echo '' >> ~/.bashrc
    echo '# add xenon-cli directory to PATH' >> ~/.bashrc
    echo 'PATH=$PATH:~/.local/bin/xenon/xenon-cli-shadow-3.0.4/bin' >> ~/.bashrc

    # enable the new settings
    source ~/.bashrc

    ```

1. Check that the downloaded version of xenon-cli uses the same xenon as what is defined in ``readthedocs/code-tabs/java/build.gradle``.
1. Check that the downloaded version of xenon-cli is the same as what is defined in ``.travis.yml``.
1. Create filesystem fixtures

    ```
    mkdir -p /home/travis/fixtures/dir1
    mkdir -p /home/travis/fixtures/.dir2
    echo 'dir1/file1.txt' > /home/travis/fixtures/dir1/file1.txt
    echo 'dir1/.file2.txt' > /home/travis/fixtures/dir1/.file2.txt
    echo '.dir2/file3.txt' > /home/travis/fixtures/.dir2/file3.txt
    echo '.dir2/.file4.txt' > /home/travis/fixtures/.dir2/.file4.txt
    ```

1. Install ``tree``

    ```
    sudo apt install tree
    ```

1. Install simple editors: nano, others

    ```
    sudo apt install geany
    sudo apt install leafpad
    sudo apt install joe

    # choose which editor should be default (nano)
    sudo update-alternatives --config editor

    ```

1. Install Eclipse

    ```
    # (from https://download.eclipse.org/eclipse/downloads/drops4/R-4.12-201906051800/)
    # download platform runtime binary
    cd ~/Downloads
    wget http://ftp.snt.utwente.nl/pub/software/eclipse//eclipse/downloads/drops4/R-4.12-201906051800/eclipse-platform-4.12-linux-gtk-x86_64.tar.gz
    tar -xzvf eclipse-platform-4.12-linux-gtk-x86_64.tar.gz

    mkdir -p ~/opt/eclipse/
    mv eclipse ~/opt/eclipse/eclipse-4.12
    ```

    ```
    mkdir -p $HOME/.local/share/applications/

    echo "[Desktop Entry]
    Type=Application
    GenericName=Text Editor
    Encoding=UTF-8
    Name=Eclipse
    Comment=Java IDE
    Exec=$HOME/opt/eclipse/eclipse-4.12/eclipse
    Icon=$HOME/opt/eclipse/eclipse-4.12/icon.xpm
    Terminal=false
    Categories=GNOME;GTK;Utility;TextEditor;Development;
    MimeType=text/plain" > $HOME/.local/share/applications/eclipse.desktop

    echo "
    # Add directory containing eclipse to the PATH
    PATH=\$PATH:$HOME/opt/eclipse/eclipse-4.12
    " >> $HOME/.profile
    ```

    Configure Eclipse by installing _Help_ >> _Install New Software..._ >> (select _--All Available Sites--_) >> _Programming Languages_ >> _Eclipse Java Development Tools_ (see https://medium.com/@acisternino/a-minimal-eclipse-java-ide-d9ba75491418).

    Prepare Java snippets directory as an Eclipse Java project:

    ```
    cd $HOME/xenon-tutorial/readthedocs/code-tabs/java
    ./gradlew eclipse
    ```

    In Eclipse, _Import project_.

1.  Generate the Sphinx documentation locally just in case there are network problems
1. Configure OpenSSH

    ```
    sudo apt install openssh-client
    chmod go-w /home/travis
    chmod 700 /home/travis/.ssh
    cp vm-prep/.ssh/known_hosts /home/travis/.ssh/known_hosts
    chmod 644 /home/travis/.ssh/known_hosts
    cp vm-prep/.ssh/config /home/travis/.ssh/config
    chmod 600 /home/travis/.ssh/config
    chown -R travis:travis /home/.ssh
    ```

1. Install python ``virtualenv``, make a virtual environment, activate it, and
install ``pyxenon`` in it (pyxenon does not work outside a virtual environment).

    ```
    sudo apt install virtualenv
    cd ~/xenon-tutorial/readthedocs/code-tabs/python/
    virtualenv -p /usr/bin/python3.6 venv36
    source venv36/bin/activate
    pip3 install -r requirements.txt
    ```

    Also include the test framework

    ```
    pip3 install -r requirements-dev.txt
    ```

    Check that it works by

    ```
    which xenon-grpc
    ```
    and

    ```
    pytest tests/ --ignore=tests/test_upload_file_local_to_sftp_absolute_paths.py \
    --ignore=tests/test_download_file_sftp_to_local_absolute_paths.py
    ```

1. Export vm as ova
1. Test the installation

----

This here is @jmaassen's setup to avoid having to deal with intricacies related to an OS that is not your own. With this setup, you can ssh into the VM, then make edits there from the comfort of the terminal that you are used to, with the tooling that you are used to.

1. Start the RSE2017 Fedora virtual machine from VirtualBox, log in as user ``tutorial`` using password ``tutorial``
1. In the VM, open a terminal and type ``ifconfig``. Look for an entry that has an ``inet`` value starting with ``10.`` (mine is ``<IP_ADDRESS>``). We will use this value as Guest IP later.
1. In the terminal, start the SSH server with ``sudo systemctl start sshd.service``
1. In VirtualBox, change the port forwarding settings, as follows:
    1. Go to menu item ``Machine``
    1. Go to ``Settings``
    1. Go to ``Network``
    1. On tab ``Adaptor 1``, go to ``Advanced``, click on ``Port Forwarding``
    1. Click the ``plus`` icon to add a rule
        1. Under ``protocol`` fill in ``TCP``
        1. Under ``Host IP`` fill in ``<IP_ADDRESS>``
        1. Under ``Host Port`` fill in ``2222``
        1. Under ``Guest IP`` fill in the value we got from ``ifconfig``
        1. Under ``Guest Port`` fill in ``22``
1. Outside the VM, open a terminal, type ``ssh -p 2222<EMAIL_ADDRESS>(type password ``tutorial`` when asked). You should now be logged in to the RSE2017 VM.

----

Not sure we still need any of this (from the rse17 tutorial)

```

preparations for the rse vm
 - virtualbox guest additions
 - number of cpus

import ovafile
set number of cpus to 2
# enable 3D hardware acceleration
# set virtual memory to max, 128 MB
start fedora

in terminal
sudo dnf update kernel*
reboot
sudo dnf install gcc kernel-devel kernel-headers dkms make bzip2 perl
KERN_DIR=/usr/src/kernels/`uname -r`
export KERN_DIR
from top virtualbox dropdown menu, select devices, insert guest additions
let guest additions install from the autorun, shutdown afterwards
# disable 3d acceleration again
login

```

repository: xenon-middleware/xenon-tutorial

gha_language: Java

repo_name: xenon-middleware/xenon-tutorial


text:
# User App Library

This document is the registry for user defined applications in _Bench_.

[markup syntax]: https://winbench.org/ref/markup-syntax/
[app properties]: https://winbench.org/ref/app-properties/
[app types]: https://winbench.org/ref/app-types/

For the syntax of app definitions, take a look at the
documentation for the [markup syntax][] and the supported [app properties][].
Learn about the different [app types][] you can define.

Activate your apps by adding them to the list of activated apps in `apps-activated.txt`,
or activate them via the _Bench Dashboard_ setup dialog,
or activate them by calling `bench app activate <App ID>`.

## User

Place your own app definitions here.

repository: winbench/bench

repo_name: winbench/bench


text:
# StasisCraft Workshop 2
## Visualising Homeostasis: Body Temperature

![stasiscraftdynmapsmall](https://cloud.githubusercontent.com/assets/128456/11134653/6ae6e364-8996-11e5-910b-b4cab7d953d9.png)

Uses Minecraft PC client version `1.7.9` with the server `mc.fact.uk`

### Activity

#### Revisiting Thermoregulation zone

 1. Sit in groups at the breakout tables with some paper and whiteboard
 * Introduce Minecraft for those who have not played it.
 * Explain the **Performing Thermoregulation game** again
 * Play through

#### Thermo-Regulation Game

to get to the StasisCraft zone you need to `/warp stasiscraft`

#### Performing Thermoregulation

 * We are going to split into 2 groups

#### Temperature Stimulus Team

 * CloudMaker01 - CloudMaker04 Temperature rising Hypothalamus group
  * `/warp skintemp1` to get to your area

It's your job to be the stimulus in the system, in this case we are representing temperature through glass *silos* with giant flowchart labels. When the silo is full (top centre block) of sand it will be marked as **too hot** ie the Dermis and other parts of the nervous system will send signals to the **Hypothalamus** to react.

You will use the [RF-Craft](https://github.com/cheapjack/StasisCraft/blob/master/Workshop2.md#hypothalamus-radio) buttons like a **Hypothalamus radio** stimulaing the system to increase temperature, and then responding to the Hypothalamus alerts and commands. You need to **STIMULATE** then **LISTEN** to the feedback response or you will all die...

 * Use the `GREEN` & `YELLOW` RF-Craft Buttons to fill the 2 Temperature silos with sand. The trigger point is the centre top of each silo
 * Once we have triggered the response you need to wait from orders from Hypothalamus
 * Hypothalamus orders with `/say Hypo says reduce SkinTemp1` or `/say Hype says reduce SkinTemp2 with BLUE button`
 * Please respond to the Hypothalamus or your bacterial mega-community will die!

#### Hypothalamus Team

 * CloudMaker07 - CloudMaker09 & CloudMaker
  * `/warp hair`

This team are effectively the **Hypothalamus** team and act out in the game the  autonomous nervous system's response to rises in temperature. This is the start of the negative feedback 'system'

Your main task is to perform the sweat response with water buckets following the Dermis hair and vascular responses. Listen to your Hypothalamus commands and once youve made enough 'sweat' you can remove it by using the `/drain 100` command near the water. You will need to be op to do that so choose one person and request this from the `sysadmin`

The silo **SkinTemp2** triggers the epidermal vascular response; blood vessels near the skin surface constrict and blood flows deeper in the skin to conserve heat.

 * CloudMaker05 - 06
Keep an eye on all things you are the Hypothalamus! Hit the red button to trigger a Hypothalamus redstone ore sphere to flash in the dermis area and send messages to your team.

Primarily the team simulates the sweat response. Once the dermis is sufficiently flooded use the chat to tell the SkinTemp team to use the `BLUE` button

### Game - Over

Hypothalamus can call game over and we can break away from our computers and disconnect from the game.

### RF-Craft: The Hypothalamus Radio

RF-Craft is a [CloudMaker](https://github.com/cheapjack/CloudMaker/) resource that sends messages through concrete using the  868MHz amateur radio band as an alternative to managed WiFi

We are using the RF-Craft Buttons to trigger certain events:
 * RED - **Hypothalamus Alert** Builds a hypothalamus shaped redstone ore sphere as an alert
 * GREEN - **SkinTemp1 Silo Increase** Fills the SkinTemp1 silo with sand to visualise increase in temperature
 * YELLOW - **SkinTemp2 Silo Increase** Fills the SkinTemp2 silo with sand to visualise increase in temperature
 * BLUE - **Decrease Temperature** Removes sand from both silos to visualise decrease in temperature

### Activity 2

#### Labelling Thermoregulation

  * Labelling and modding the dermis landscape model

### Activity 3

#### Building Parkour FlowCharts

 * Use `ScriptCraft` to build flowcharts

Format is `/js box("35:4", x (east/west coordinate, y (up or down coordinate), z (north/south coordinate)` but you always need to build from a start block, the one you are **looking** at to refer from: look at the block and run the command to build from that point

You can also add `/up()` and `down()` functions before you start to
so `/js up(2).box("35:14", 10, 6, 2)` builds a box 10 across, 6 high and 2 thickness/depth) after moving up 2 blocks from the one you are looking at.

 * Use `ScriptCraft` to label charts with text

Format is as above to position the text, but using the blocktype() funtion

`/js blocktype("My\nMessage", 89)`

This builds minecraft style text "MY MESSAGE" from the block you are looking at `\n` is `newline` so you can have multiple lines of text. It will always render the last `newline` at the bottom of the block you are looking at.

 * Use `ScriptCraft` to build stairs between the flow charts to make a **parkour** style map which players have to complete.

![hypothalamus_small](https://cloud.githubusercontent.com/assets/128456/11132490/17ac85fe-8988-11e5-8daf-c4e3992d1681.gif)

#### Hypothalamus Says

(using `/say` & `/whisper` commands)

#### Minecraft 101

It's a building game that uses these basic controls:

 * `MENU` - `esc` then customise controls in `OPTIONS` or use defaults below
 * `UP` - `w`
 * `DOWN` - `s`
 * `LEFT` - `a`
 * `RIGHT` - `s`
 * `JUMP` - `SPACE`
 * `FLY` - double-hit the `SPACE` bar and hold it to fly
  * use `SHIFT` to descend and another double-hit on `SPACE` to fall
 * `BUILD` - `right-click` on the `MOUSE`
 * `BREAK` - `left-click` on the `MOUSE`
 * `SELECT` - custom key
 * `INVENTORY` - `e`

Typing `/` will open the minecraft chat/terminal window where you can issue commands like

 * `/say Hello` - Say Hello to the server
 * `/whisper <message> <playername>` - Whisper something directly to another player
 * `/warp <warplocation>` - Warp to specific warp locations, we use:
  * `/warp hair` , `/warp skintemp1` , `/warp stasiscraft
 * `/js box(20)` build a glass box on the block you are looking at
 * `/` then `delete` the forward slash to just talk to the server

#### ScriptCraft Reference
Get the full info on github from http://scriptcraftjs.org/

Shapes

 * box( blocks.material, width, height, depth ) - creates a solid box
 * box0( blocks.material, width, height, depth ) - creates an empty box (with the insides hollowed out - perfect for dwellings.
 * box( blocks.material, width, height, depth ) - creates an empty box (with the insides hollowed out - perfect for dwellings.
 * cylinder( blocks.material, radius, height ) - creates cylinders, perfect for Chimneys.
 * cylinder0( blocks.material, radius, height ) - creates empty cylinders
 * prism( blocks.material, width, depth ) - creates a Prism - good for roofs.

Just substitute 'block.material' for 'block.wool.red' or 'block.ice' or 'block.brick.red' type /js block. then use tab to see the different materials autocomplete in the command line

### Movement

The 'drone' is the invisible cursor that 'builds' things in minecraft; whatever block is highlighted as you look at it is the drone start position. You can combine commands by using a dot between commands. So /js box(block.ice).right(2).box(block.ice, 2,2,2) makes a single block of ice, moves 2 blocks to the right and makes a 2x2x2 block of ice

 * up( numberOfBlocks ) - moves the Drone Up. For example: up() will move the Drone 1 block up. You can tell it how many blocks to move if you want it to move more than one block.
 * down( numberOfBlocks ) - moves the Drone Down.
 * left( numberOfBlocks ) - moves the Drone Left.
 * right( numberOfBlocs ) - moves the Drone Right.
 * fwd( numberOfBlocs ) - moves the Drone Forward (away from the player).
 * back( numberOfBlocs ) - moves the Drone Back (towards the player)
i
 * turn( numberOfTurns ) - Turns the Drone Clock-wise (right). For example: turn() will make the Drone turn right 90 degrees. turn(2) will make the Drone turn twice so that it is facing in the opposite direction.

repository: cheapjack/StasisCraft

repo_name: cheapjack/StasisCraft


text:
# ortools-with-cmake
How-to demonstrating integration of binary OR-tools for C++ package inside of a cmake project.

## Install `or-tools` from binary

Follow the steps [here](https://developers.google.com/optimization/install/cpp/).

## Build this repo
_Note:_ this has only been tested on Ubuntu 18.04 but should work on other distros / OSes.

```bash
cd {path-to-this-repo}
mkdir build && cd build
cmake -DORTOOLS_ROOT:STRING="{path-to-ortools-root-dir}" ..
make
```

You'll see some warnings most likely.

## Test the build
The test executable built in the previous step uses the toy example provided by Google from [here](https://developers.google.com/optimization/introduction/cpp).

Run the test:

```bash
./test-app
```

You should see the following output:

```bash
WARNING: Logging before InitGoogleLogging() is written to STDERR
I0814 10:15:02.698244 12745 program.cc:12] Number of variables = 2
I0814 10:15:02.698365 12745 program.cc:19] Number of constraints = 1
I0814 10:15:02.700047 12745 program.cc:29] Solution:
I0814 10:15:02.700063 12745 program.cc:30] Objective value = 4
I0814 10:15:02.700076 12745 program.cc:31] x = 1
I0814 10:15:02.700080 12745 program.cc:32] y = 1
```


text:
# Derived Classes

cf. pp. 577, Ch. 20 **Derived Classes** by Bjarne Stroustrup, **The C++ Programming Language**, *4th Ed.*.

*object-oriented programming* - its basis is the simple idea of hierarchical relationships, i.e. to express commonality between classes; *base* class or *superclass* is the common class, classes derived from that are *derived* classes or *subclasses*.

C++ language features support building new classes from existing ones:
- *implementation inheritance* to save implementation effort by sharing facilities provided by base class
- *interface inheritance* - allow different derived classes to be used interchangeably through interface provided by common base class

Interface inheritance often referred to as *run-time polymorphism* (or *dynamic polymorphism*).
  - In contrast, uniform use of classes not relate by inheritance provided by **templates** (Sec. 3.4, Ch. 23) is referred to as *compile-time polymorphism* (or *static polymorphism*)

Derived class is typically larger (and never smaller) than base class in sense it holds more data and provides more functions.

A class must be **defined** in order to be used as a base.

Typically, cleanest solution is for derived class to use only the public members of its base class.

## Constructors and Destructors

cf. 20.2.2 Constructors and Destructors, Ch. 20 *Derived Classes* by Bjarne Stroustrup, **The C++ Programming Language**, *4th Ed.*.

* Objects are constructed from bottom up (base before member, and member before derived), and destroyed top-down (derived before member, and member before base); Sec. 17.2.3
* Each class can initialize its members and bases (but not directly members or bases of its bases); Sec. 17.4.1
* Typically, destructors in a hierarchy need to be `virtual` Sec. 17.2.5
* Copy ctors of classes in a hierarchy should be used with care (if at all) to avoid slicing (Sec. <IP_ADDRESS>)
* resolution of a virtual function call, a `dynamic_cast` or `typeid()` in a ctor or dtor reflects stage of construction and destruction (rather than the type of the yet-to-be-completed object), Sec. 22.4

## Type Fields

cf. 20.3.1 Type Fields, Ch. 20 *Derived Classes* by Bjarne Stroustrup, **The C++ Programming Language**, *4th Ed.*.

To use derived classes as more than a convenient shorthand in declarations, we must solve the following problem:
Given a pointer of type `Base*`, to which derived type does the object pointed to really belong?
There are 4 fundamental solutions:
1. Ensure only objects of a single type are pointed to (Sec. 3.4, Ch. 23)
2. Place type field in base class for functions to inspect
3. Use `dynamic_cast` (Sec. 22.2, 22.6)
4. Use virtual functions (Sec. 3.2.3, 20.3.2)

cf. pp. 245, Exploration 37 *Inheritance*, by Ray Lischner. **Exploring C++11 (Expert's Voice in C++)**.  *2nd. ed.* Apress (2013).

Unless you've used `final` (Sec. <IP_ADDRESS>), solution 1 relies on more knowledge about types involved than available to the compiler.
  - In general, it's not a good idea to try to be smarter than the type system, but (especially in combination with the use of templates), it can be used to implement homogeneous containers (e.g. standard-library `vector` and `map`) with unsurpassed performance.

Solutions 2, 3, 4 can be used to build heterogenous lists, i.e. lists of (**pointers to**) objects of several different types.
Solution 3 is a language-supported variant of Solution 2.
Solution 4 is a special type-safe variable of solution 2.

Combinations of solutions 1, 4 are particularly interesting and powerful; in almost all situations, they yield cleaner code than do solutions 2, 3.

Simple type-field solution best avoided because
 - programmer must consider every function that could conceivably need a test on the type field after a change.
 - each function using a type field, must know about representation and other details of implementation of every class derived from 1 containing type field.

## Virtual Functions

cf. 20.3.2 Virtual Functions, Ch. 20 *Derived Classes* by Bjarne Stroustrup, **The C++ Programming Language**, *4th Ed.*.

Virtual functions allows for declaration of functions in a base class that can be redefined in each derived class. Compiler and linker will guarantee correct correspondence between objects and functions applied to them.

A virtual function *must* be defined for class in which it's first declared (unless it's declared to be a **pure** virtual function, Sec. 20.4)

A virtual function **can be used even if no class is derived from its class**.
Derived class that doesn't need its own version of a virtual function need not provide one.
  - When deriving a class, simply provide an appropriate function if it's needed.

Function from derived class with same name and same set of argument types as a virtual function in a base is said to *override* base class version of virtual function.
  - Furthermore, it's possible to override virtual function from a base with a more derived return type (Sec. 20.3.6)

Except where we explicitly say which version of a virtual function is called, overriding function is chosen as most appropriate for the object for which it's called.

Independently of which base class (interface) is used to access an object, we always get the same function when we use the virtual function call mechanism.

**polymorphism** - getting "the right" behavior from `Employee`'s functions independently of exactly what kind of `Employee` is actually used is called *polymorphism*.
- A type with virtual functions is called a *polymorphic type* or (more precisely) a *run-time polymorphic type*.
To get runtime polymorphic behavior in C++, member functions called must be `virtual` and objects must be manipulated through ptrs or references.
  - When manipulating an object *directly* (rather than through a ptr or reference), its exact type is known by the compiler so that run-time polymorphism isn't needed.

`std::is_polymorphic` means non-union class that declares or inherits at least 1 virtual function.

Indeed, by default, a function that overrides a virtual funciton itself becomes `virtual`. We can, but don't have to repeat `virtual` in derived class; Stroustrup doesn't recommend repeating `virtual`; for explicit, use `override`.

### vtables, vptrs

Clearly, to implement polymorphism compiler must store some kind of type information in each object of class `Employee` and use it to call right version of virtual function `print()`.

In a typical implementation, space taken is just enough to hold a ptr (Sec. 3.2.3).
  - size of a ptr is dependent on platform. 64-bit = 8 bytes = size of ptr.

Usual implementation is for compiler to convert name of vritual function into index into a table of pointers to functions.  That table is called *virtual function table* or **`vtbl`**.

Each class with virtual functions has its own `vtbl` (I'll call it vtable) identifying its virtual functions.

For base class `A`, derived class `B`

```
class A
{
  public:
    virtual bool is_A() { return true; }

  private:
    double a_;
};

class B : public A
{
  public:
    bool is_A() { return false; }

  private:
    double b_;
}
```

A
######
vptr 8 bytes -----------> A vtable ------------>  A::is_A()
a_   8 bytes
######

B
######
vptr 8 bytes -----------> B vtable ------------> B::is_B()
b_   8 bytes
######

virtual call mechanism can be made almost as efficient as "normal function call" mechanism (within 25%), so efficiency concerns shouldn't deter anyone from using a virtual function.

Space overhead is 1 ptr in each object of a class with virtual functions, plus 1 vtable for each such class; you pay this overhead only for objects of a class with a virtual function.

Virtual function invoked from ctor or dtor reflects that object is partially constructed or partially destroyed (Sec. 22.4). It's therefore *typically bad idea to call virtual function from ctor or dtor.*

## Explicit Qualification, `::`, `A::`

cf. 20.3.3 Explicit Qualification, Ch. 20 *Derived Classes* by Bjarne Stroustrup, **The C++ Programming Language**, *4th Ed.*.

Calling a function using scope resolution operator, `::`, as is done in `Manager::print()` ensures `virtual` mechanism is *not used*:

```
void Manager::print() const
{
  Employee::print(); // not a virtual call
  std::cout << "\t level " << level << '\n';
  //...
}
```

Otherwise, `Manager::print()` would suffer *infinite recursion*.

Use of a qualified name also has desirable effect that, if virtual function is also `inline` (not uncommon), then inline substitution can be used for calls specified using `::`.
  - provides efficient way to handle some important special cases in which 1 virtual function calls another for same object.
  - because type of object is determined in call of `Manager::print()`, it need not be dynmaically determined again for resulting call of `Employee::print()`

## Override Control

cf. 20.3.4 Override Control, Ch. 20 *Derived Classes* by Bjarne Stroustrup, **The C++ Programming Language**, *4th Ed.*.

If you declare a function in a derived class that has *exactly same name and type as a virtual function in a base class*, then function in derived class *overrides the one in base class*.
  - simple rule

For larger class hierarchies, can be difficult to be sure you actually override.

Stroustrup don't (redundantly) use `virtual` for function that's meant to override.

For larger hierarchies,
  * `virtual` - function may be override (Sec. 20.3.2)
  * `= 0` function must be `virtual` and must be overridden (Sec. 20.4)
  * `override` function meant to override virtual function in a base class (Sec. <IP_ADDRESS>)
  * `final` function not meant to be overridden (Sec. <IP_ADDRESS>)

### `override`

cf. <IP_ADDRESS> `override`, Ch. 20 *Derived Classes* by Bjarne Stroustrup, **The C++ Programming Language**, *4th Ed.*.

In large or complicated class hierarchy with many virtual functions, it's best to use `virtual` only to introduce a new virtual function, and to use `override` on all functions intended as overriders.
  - Using `override` is a bit verbose, but clarifies programmer's intent.

`override` specifier can't be repeated in an out-of-class definition.

`override` isn't a keyword, it's a *contextual keyword*

### `final`; when to use `virtual`

cf. <IP_ADDRESS> `final`, Ch. 20 *Derived Classes* by Bjarne Stroustrup, **The C++ Programming Language**, *4th Ed.*.

Use `virtual` for functions we want writers of derived classes to be able to define or redefine.
* can we imagine need for further derived classes?
* Does designer of derived class need to redefine function to achieve plausible aim?
* is overriding function error-prone (i.e. is it hard for overriding function to provide expected semantics of a virtual function?)

If answer is "no" to *all 3 questions*, leave function *non-`virtual`*.

Far more rarely, we have a class hierarchy that starts out with virtual functions, but after definition of a set of derived classes, 1 of the answers become "no".
Prevent users from overriding virtual functions. After using `final` for a member function, it can no longer be overridden and attempts to do so is error.
  - It also **prevents further derivation from a class**.
  - Don't blindly use `final` as optimization (non-`virtual` function is faster than `virtual` one); it affects class hierarchy design (often negatively), and performance improvements are rarely significant. Do some serious measurements before claiming efficiency improvements.
  - Use `final` where it clearly reflects class hierarchy design, i.e. reflect semantic need.

A `final` specifier isn't part of the type of a function and cannot be repeated in an out-of-class definition.
e.g.
```
class Derived : public Base
{
  void f() final; // OK if Base has a virtual f()
  void g() final; // OK if Base has a virtual g()
  // ...
};

void Derived::f() final // error: final out of class
{
  // ...
}

void g() final // OK
{
  // ...
}
```

### `using` Base Members, inheriting ctors

cf. 20.3.5 `using` Base Members. Ch. 20 *Derived Classes* by Bjarne Stroustrup, **The C++ Programming Language**, *4th Ed.*.

Functions don't overload across scopes (Sec. 12.3.3); e.g.

```
struct Base
{
  void f(int);
};

struct Derived : Base
{
  void f(double);
};

void use(Derived d)
{
  d.f(1); // call Derived::f(double)
  Base& br = d;
  br.f(1); // call Base::f(int)
}
```
This could surprise people.
Sometimes we want overloading to ensure that best matching member function is used.
  - `using`- declarations can be used to add a function to a scope

### Inheriting Constructors

cf. <IP_ADDRESS> Inheriting Constructors, Ch. 20 *Derived Classes* by Bjarne Stroustrup, **The C++ Programming Language**, *4th Ed.*.

Solve the problem by simply saying constructors should be inherited:
```
template<class T>
struct Vector : std::vector<T> {
  using vector<T>::vector;		// inherit constructors

  T& operator=[](size_type i) {check(i); return this->elem(i);}
  const T& operator=(size_type i) const {check(i); return this->elem(i);}

  void check(size_type i) {if (this->size()<i) throw Bad_index(i); }
};

Vector<int> v {1, 2, 3, 5, 8}; // OK: use initializer-list constructor from std::vector
```

### Use of `protected` Members

cf. <IP_ADDRESS> Use of `protected` Members, Ch. 20 *Derived Classes* by Bjarne Stroustrup, **The C++ Programming Language**, *4th Ed.*.

Members declared `protected` are far more open to abuse than members declared `private`.  In particular, declaring data members `protected` is usually a design error.
- placing significant amounts of data in a common class for all derived classes to use leaves that data open to corruption.
- Fortunately, you don't have to use protected data; `private` is default in classes and is usually better choice.

However,
`protected` is a fine way of specifying operations, protected member *functions*, for use in derived classes.
- had implementation class been `private` in this example, further derivation would've been infeasible.
- on the other hand, making bases providing implementation details `public` invites mistakes and misuse.

## Access to Base Classes, `public`, `protected`, `private` inheritance, `using`-Declarations and Access control

cf. pp. 605 Sec. 20.5.2 Use of `protected` Members, Ch. 20 *Derived Classes* by Bjarne Stroustrup, **The C++ Programming Language**, *4th Ed.*.

base class can be declared `private`, `protected`, or `public`.  For example,
```
class X : public B { /* ... */ };
class Y : protected B { /* ... */ };
class Z : private B { /* ... */ };
```
* `public` derivation makes derived class a subtype of its base. For example, `X` is a kind of `B`.  This is the most common form of derivation.
* `private` *inheritance*, `private` bases are most useful when defining a class by restricting the interfaces to a base, so that stronger guarantees can be provided.
  - e.g., `B` is an implementation detail of `Z`.
  - e.g. `Vector` of pointers template that adds type checking to its `Vector<void*>` base from Sec. 25.3 is a good example.

Access specifier `public`, `protected`, `private` for a base class controls access to members of the base class and conversion of pointers and references from the derived class type to the base class type.
Consider class `D` derived from base class `B`:
* if `B` is `private` base, its public and protected members can be used only by member functions and friends of `D`.  Only friends and members of `D` can convert a `D*` to a `B*`.

cf. pp. 606 Sec. 20.5.3 `using`-Declarations and Access Control, Ch. 20 *Derived Classes* by Bjarne Stroustrup, **The C++ Programming Language**, *4th Ed.*.

`using`-declaration can't be used to gain access to additional information; it's simply a mechanism for making accessible information more convenient to use.  On the other hand, once access is available, it can be granted to other users.
* When `using`-declaration combined with private or protected derivation, it can be used to specify interfaces to some, but not all, of the facilities usually offered by a class; e.g.
```
class BB : private B // give access to B::b and B::c, but not B::a
{
  public:

    using B::b;
    using B::c;
};
```

## Pointers to Members; Pointers to Function Members, Pointers to Data Members

cf. pp. 607 Sec. 20.6 Pointers to Members, Ch. 20 *Derived Classes* by Bjarne Stroustrup, **The C++ Programming Language**, *4th Ed.*

Pointer to member is offset-like construct that allows programmer to indirectly refer to member of a class.
Operators `->*`, `.*` are arguably most specialized and least used C++ operators.
- `->`, we can access member of class, `m` by naming it: `p->m`
- `->*`, we can access member that (conceptually) has its name stored in a pointer to mmeber, `ptom: p->*ptom`
This allows us to access members with their names passed as arguments.
In both cases, `p` must be a pointer to an object of an appropriate class.

Pointer to member can't be assigned to `void*` or any other ordinary pointer.
Null pointer (`nullptr`) can be assigned to pointer to member, and then represents "no member."

We can use a pointer to member to indirectly refer to member of a class.

```
class StdInterface
{
  public:
    virtual void start() = 0;
    virtual void suspend() = 0;
    virtual void resume() = 0;
    virtual void quit() = 0;
    virtual void full_size() = 0;
    virtual void small() = 0;

    virtual ~StdInterface() {}
};
```

I need a pointer to member referring to `StdInterface::suspend()`, and
pointer or reference to object I need to suspend.

```
using Pstd_mem s = &StdInterface::suspend; // pointer to suspend()

void f(StdInterface* p)
{
  PstdMem s = &StdInterface::suspend; // pointer to suspend()
  p->suspend(); // direct call
  p->*s(); // call through pointer to member
}
```
*Pointer to member* can be obtained by applying address-of operator `&` to fully qualified class member name, e.g. `&StdInterface::suspend`.
A variable of type "pointer to member of class `X`" declared using declarator of form `X::*`.

Pointer to member `m` can be used in combination with object.
Operators `->*`, `.*` allow programmer to express such combinations:
e.g. `p->*m` binds `m` to object pointer to by `p`, and `obj.*m` binds `m` to object `obj`.
Result can be used in accordance with `m`'s type.
  - It's not possible to store result of `->*` or `.*` operation for later use.

A pointer to member isn't a pointer to piece of memory, the way pointer to variable or pointer to function is.
It's more like an offset into structure or index into an array.

Becuase pointer to virtual member is a kind of offset, it doesn't depend on object's location in memory; pointer to virtual member can therefore be passed between different address spaces as long as same object layout is used in both.
Like pointer to ordinary functions, pointers to non-virtual member functions can't be exchanged between address spaces.

Note that function invoked through pointer to function can be `virtual`.
e.g. when we call `suspend()` through pointer to function, we get the right `suspend()` for object to which pointer to function is applied; this is an essential aspect of pointers to functions.

When writing an interpreter, we might use pointers to members to invoke functions presents as strings:
```
map<string, StdInterface*> variable;
map<string, Pstd_mem> operation;

void call_member(string var, string oper)
{
  (variable[var]->*operation[oper])(); // var.oper()
}
```

`static` member isn't associated with a particular object, so a pointer to a `static` member is simply an ordinary pointer; e.g.

```
class Task
{
  // ...
  static void schedule();
};

void (*p)() = &Task::schedule; // OK
void (Task::* pm)() = &Task::schedule; // error: ordinary pointer assigned
  // to pointer to member.
```

#### Pointers to Data Members, to member functions with arguments and return types

cf. pp. 609 Sec. 20.6.2 Pointers to Data Members, Ch. 20 *Derived Classes* by Bjarne Stroustrup, **The C++ Programming Language**, *4th Ed.*

e.g.

```
struct C
{
  const char* val; // data member
  int i; // data member

  // member functions

  void print(int x)
  {
    std::cout << val << x << '\n';
  }

  int f1(int);
  void f2();
  C(const char* v)
  {
    val = v;
  }
};

using Pmfi = void (C::*)(int); // pointer to member function of C taking an int
using Pm = const char* C::*; // pointer to char* data member of C
```

```
void f(C& z1, C& z2)
{
  C* p = &z2;
  Pmfi pf = &C::print;
  Pm pm = &C::val; // pointer to char* data member

  z1.print(1);
  (z1.*pf)(2);

  z1.*pm = "nv1 ";
  p->*pm = "nv2 ";

  z2.print(3);
  (p->*pf)(4);

  pf = &C::f1; // error: return type mismatch
  pf = &C::f2; // error: argument type mismatch
  pm = &C::i; // error: type mismatch
  pm = pf; // error: type mismatch
};
```

#### Pointers to Base and Derived Members

cf. pp. 610 Sec. 20.6.3 Base and Derived Members, Ch. 20 *Derived Classes* by Bjarne Stroustrup, **The C++ Programming Language**, *4th Ed.*

A derived class has at least the members that it inherits from its base classes.
Often it has more.

This implies that we can safely assign a pointer to a member of a base class to a pointer to a member of a derived class.
But not the other way around (assign a pointer to a member of a derived class to a pointer to a member of a base class).
Called *contravariance*.

e.g.

```
class Text : public StdInterface
{
  public:

    void start();
    void suspend();

    // ...

    virtual void print();

  private:

    vector s;
};
```

```
void (StdInterface::*pml)() = &Text::print; // error
void (Text::*pmt)() = &StdInterface::start; // OK
```

*Contravariance rule* appears opposite of rule that says,
  - we can assign pointer to a derived class to pointer to its base class

Both rules exist to preserve fundamental guarantee that pointer may never point to an object that doesn't at least have properties that pointer promises.
  - In this case, `StdInterface::*` can be applied to any `StdInterface` and most such objects presumably aren't of type `Text`
  - consequently, they don't have member `Text::print`, which we tried to initialize with `pml`

repository: ernestyalumni/HrdwCCppCUDA

repo_name: ernestyalumni/HrdwCCppCUDA


text:
[![npm version](https://badge.fury.io/js/homebridge-xiaomi-purifier-pro.svg)](https://badge.fury.io/js/homebridge-xiaomi-purifier-pro)

# homebridge-xiaomi-purifier-pro

![mi-air-purifier](https://imgaz.staticbg.com/thumb/large/oaupload/ser1/banggood/images/55/22/4e668990-f7be-4361-8626-06d87f4e4cb7.jpg)

### Features

* Switch on / off.
* Switch auto / manual mode.
* Change fan rotation speed.

* Switch LED light on / off.
* Switch buzzer sound on / off.
* Display temperature.
* Display humidity.
* Display air quality.
* Display filter state.

### Installation

1. Install required packages.

```
	npm install -g homebridge-xiaomi-purifier-pro
	```

2. Make sure your Homebridge server is same network with your device, then run following command to discover the token.

```
	miio discover --sync
	```

3. You may need to wait few minutes until you get the response similar to below:

```
	Device ID: 49466088
	Model info: Unknown
	Address: <IP_ADDRESS>
	Token: 6f7a65786550386c700a6b526666744d via auto-token
	Support: Unknown
	```

4. Record down the `Address` and `Token` values as we need it in our configuration file later.

5. If you are getting `??????????????` for your token value, please reset your device and connect your Homebridge server directly to the access point advertised by the device.

6. Then run the command again.

```
	miio discover --sync
	```

7. Add following accessory to the `config.json` .

```
		"accessories": [
			{
				"accessory": "MiAirPurifierPro",
				"name": "Bed Room Air Purifier",
				"ip": "192.168.1.x",
				"token": "xxxxxxxxxxxxxxxxxxx",
			    "enableLED": true (optional),
				"enableLEDName": "Some custom LED name" (optional),
				"enableBuzzer": true (optional),
				"enableBuzzerName": "Some custom buzzer name" (optional),
				"showTemperature": true,
                "showTemperatureName": "Some custom Temperature name" (optional),
                "showHumidity": true (optional),
                "showHumidityName": "Some custom Humidity name" (optional),
                "showAirQuality": true (optional),
                "showAirQualityName": "Some custom Air Quality name" (optional),
				"pm25_breakpoints": [5, 12, 35, 55] (optional),
				"polling_interval": 60000 (optional)
			}
		]
	```

	**Notes:** Set value for `enableLED` , `enableBuzzer` , `showTemperature` , `showHumidity` , `showAirQuality`  to **true** or **false** to show or hide these sensors in Home app.

8. Restart Homebridge, and your device will be added to Home app.

# License

MIT License


text:
# `<TabLabel />`

This is a very simple component that renders a `label`. You can add any **inline elements** as children of a TabLabel.
Do not use `div`s and other block level elements as this is against the HTML spec. Although modern browsers don't really
break if you do invalid HTML.

The `label` is linked to the `input` element rendered by TabPanel, which means TabLabel is always a clickable state
changing element.

## Props

Property          | Type          | Description
:-----------------|:--------------|:-----------
component         | component     | Defaults to `label`.

You can use a custom component to render, but your custom component should also always render a `label`. You can use
your own composing component to add more elements in the middle if you don't like `label` being in the same level with
content.

```jsx
// wrap a header element around label
function MyLabel(props) {
    return (
        <header>
            <label {...props} />
        </header>
    )
}

...

<TabLabel component={MyLabel}>
    This is my clickable title
</TabLabel>
```

repository: Merri/react-tabbordion

repo_name: Merri/react-tabbordion


text:
fongandrew:login-as-user
========================
A simple token-based implementation of allowing someone to login as another
user in Meteor.

Installation
------------
`meteor add fongandrew:login-as-user`

Usage
-----
You'll need to call `Accounts.impSvc.set(userId)` on the server with the
userId of the user you want to login as. This will return a token you can
use to log in. How you get the token from server to client is up to you, but
you'll probably just want to use a Meteor method.

Note that this package does not provide any permission checking that the person
requesting a token to login as someone else is actually authorized to do so.
You must implement that part yourself -- e.g. check inside the Meteor method
before requesting a token.

Once you have a token on the client, call
`Accounts.loginWithImpersonate(token, callback)`. The callback will return
with an error if it failed or nothing upon success.

repository: rfarris/meteor-login-as-user

repo_name: rfarris/meteor-login-as-user


text:
# one-voice
As more and more devices allow for voice commands, it will become increasingly difficult to keep up with the syntax of the commands.

As an example:
One device may allow for "ok [device], play [song] by [artist]"
While another device may allow for "[device], jam out to [song] by [artist]"

This codebase (coupled with an input/output device) will handle the translation for you.

Devices: Smart TV's, PS4, GoPro, Alexa, OK Google, etc.

repository: KraFusion/one-voice

repo_name: KraFusion/one-voice


text:
#Highlight Mixed Whitespace

A plugin for [Sublime Text](http://www.sublimetext.com) to highlight mixed
tabs and spaces.

Shamelessly ripped from https://github.com/SublimeText/TrailingSpaces and modified.

![Highlight Mixed Whitespace Screenshot](https://github.com/bluegray/Highlight-Mixed-Whitespace/raw/master/images/mixed-whitespace.png "Highlight Mixed Whitespace Screenshot")

repository: mreq/Highlight-Mixed-Whitespace

repo_name: mreq/Highlight-Mixed-Whitespace


text:
# elm benchmarks on the command line

[elm-explorations/benchmark]: https://package.elm-lang.org/packages/elm-explorations/benchmark/latest

An experiment to bring [elm-explorations/benchmark] to the command line.

## How to run

```sh
cd example
elm install
elm make Main.elm --optimize --output elm.js >/dev/null
node run.js
```

## Thanks

- Ilias van Peer for an [earlier prototype](https://github.com/zwilias/elm-benchmark-cli)
- Richard Feldman for [console-print](https://github.com/rtfeldman/console-print)
- Brian Hicks and other contributers for [elm-explorations/benchmark]

repository: folkertdev/elm-test-rs

repo_name: folkertdev/elm-test-rs


text:
## Assignment 3
## CMPT 825 Natural Language Processing
* Student Name: Anmol Sharma
* Student ID: asa224
* Student Email ID<EMAIL_ADDRESS>
## Contributions:

1. Implemented the baseline algorithm for alignment of words from french to english.
2. Fixed the bugs pertaining to the implementation.
3. Trained several models for different number of epochs to gauge any performance improvment.

 Needs debugging

commit eb5918aecefc9bde6f91b717244da0aa3998b48e
Author: asa224<EMAIL_ADDRESS>Date:   Tue Nov 7 14:37:46 2017 -0800

    fixed uniform prob issue

commit 45e961393b952187afb646584380ef46075d2165
Merge: 00590d0 7752a65
Author: asa224<EMAIL_ADDRESS>Date:   Tue Nov 7 14:23:34 2017 -0800

    Merge branch 'master' of csil-git1.cs.surrey.sfu.ca:group-nlp/assignments

commit 00590d064f2beb3f97f79340ed27d9bfe4ce5045
Merge: 4f81ca7 1692b48
Author: asa224<EMAIL_ADDRESS>Date:   Tue Nov 7 14:23:17 2017 -0800

    fixed a small bug in cond prob calculation

commit 7752a659a212495011c63fb6511f583a4e50c4aa
Author: asa224<EMAIL_ADDRESS>Date:   Tue Nov 7 14:20:33 2017 -0800

    working implementation, running on en-de dataset

commit a23f221d67eea14d94cde3147664e8475ff0f035
Author: asa224<EMAIL_ADDRESS>Date:   Tue Nov 7 12:01:01 2017 -0800

    first working implementation after fixing memory issues by memoization

commit c5776a3ad8422c08f1113fb83f59a080a3222c35
Author: asa224<EMAIL_ADDRESS>Date:   Tue Nov 7 11:07:35 2017 -0800

    building conditional probabilities, getting memory error with large dictionary of probs...

commit 7d1a11959d03e8134083847037220f4fda6150c5
Author: asa224<EMAIL_ADDRESS>Date:   Tue Nov 7 09:42:48 2017 -0800

    starting baseline implementation

~~~


text:
# Cerebral View Snabbdom

Cerebral View Snabbdom makes Cerebral a first class citizen of components. That means you have to do a lot less wiring to build components and Snabbdom is faster than React. Read more about the JSX syntax over at [snabbdom-jsx](https://github.com/yelouafi/snabbdom-jsx), it differs from React. Instead of JSX you can use the built in [snabbdom hyperscript helper](https://github.com/paldepind/snabbdom#snabbdomh).

## Install
````
npm install cerebral-view-snabbdom
```

### Optional JSX support

To use JSX syntax you also need `snabbdom-jsx` and Babel with the `transform-react-jsx` package.

```
npm install snabbdom-jsx
npm install babel-plugin-transform-react-jsx
```

Add a `.babelrc`

```js
{
  "presets": ["es2015"],
  "plugins": [
    ["transform-react-jsx", { "pragma": "Component.DOM" }]
  ]
}
```

## Render

```js
import { Component, render } from 'cerebral-view-snabbdom'
import App from './App'
import controller from './controller'

render(() => <App/>, document.querySelector('#app'), controller)
```

> **Note:** `() => <App/>` is the same as `() => { return <App/> }`

or without JSX

```js
render(() => App(), document.querySelector('#app'), controller)
```

Note that you have to pass a callback to render the initial component, returning it. And you also have to pass the controller.

## Component

```js
import { Component } from 'cerebral-view-snabbdom'

export default Component(() => (
  <h1>Hello world!</h1>
))
```

or without JSX

```js
import { Component, h } from 'cerebral-view-snabbdom'

export default Component(() => h('h1', 'Hello World!'))
```

### Use state from state store
By default you have access to all the state from your state tree on the `state` property passed into each components.

```js
import { Component } from 'cerebral-view-snabbdom'

export default Component(({state}) => (
  <h1>{state.title}</h1>
))
```

You can optionally extract specific state and customize its property name:

```js
import { Component } from 'cerebral-view-snabbdom'

export default Component({
  title: ['title'],
  rows: ['admin', 'users']
}, ({state}) => (
  <div>
    <h1>{state.title}</h1>
    <ul>
      {state.rows.map(row => <li>{row.name}</li>)}
    </ul>
  </div>
))
```
In this case only *title* and *rows* are available in the component, via the *state* property.

### Use props passed to component

*MyComponent.js*
```js
import {Component} from 'cerebral-view-snabbdom'

export default Component(({props}) => (
  <h1>{props.title}</h1>
))
```

```js
import MyComponent from './MyComponent'

<MyComponent title="whatup!"/>
```

### Use signals

*MyComponent.js*
```js
import {Component} from 'cerebral-view-snabbdom'

export default Component(({state, signals}) => (
  <div>
    <h1 style={{color: state.color}}>{props.title}</h1>
    <button on-click={() => signals.colorChanged({color: 'blue'})}>Change color</button>
  </div>
))
```

### Access modules
Modules access is primarily necessary for components related to specific modules. The need to expose modules i yet to be discussed.

 It will shallow check its properties to decide if a render is necessary.

*MyComponent.js*
```js
import {Component} from 'cerebral-view-snabbdom'

const MyComponent = Component(({props}) => (
  <h1>{props.title}</h1>
))

<MyComponent key="main-title" title="test"/>
```
The key has to be **unique**. The component will only render when *title* actually changes. If you want to also optimize on the state used from the state store you can define the state used by the component.

*MyComponent.js*
```js
import {Component} from 'cerebral-view-snabbdom'

const MyComponent = Component({
  version: ['version']
}, ({props, state}) => (
  <h1>{props.title} ({state.version})</h1>
))
```
Now the component will only update if either *title* from props or *version* from the state has changed.

repository: garth/cerebral-view-snabbdom

repo_name: garth/cerebral-view-snabbdom