text:
<repo_name>senyouhq/startup-kit<file_sep>/src/components/Header/Sidemenu.js
import React from 'react'
import { makeStyles } from '@material-ui/core/styles'
import Drawer from '@material-ui/core/Drawer'
import List from '@material-ui/core/List'
import Divider from '@material-ui/core/Divider'
import ListItem from '@material-ui/core/ListItem'
import ListItemText from '@material-ui/core/ListItemText'
import ListItemIcon from '@material-ui/core/ListItemIcon'
import ExitToAppIcon from '@material-ui/icons/ExitToApp'
import AccountCircleIcon from '@material-ui/icons/AccountCircle'

const useStyles = makeStyles({
  list: {
    width: 250,
  },

  fullList: {
    width: 'auto',
  },

  sideMenu: {
    width: '60vw',
    maxWidth: 250,
  },
})

export default function Sidemenu({
  user,
  open,
  onClose,
  onAccountClick,
  onMenuClick,
  onLogout,
  menus = [],
}) {
  const classes = useStyles()

  const Menus = menus.map((menu, index) => {
    if (menu.divider) {
      return <Divider key={index} />
    }
    return (
      <ListItem button key={menu.name} onClick={() => onMenuClick(menu)}>
        {menu.icon && <ListItemIcon>{menu.icon}</ListItemIcon>}
        <ListItemText primary={menu.label || menu.name} />
      </ListItem>
    )
  })
  return (
    <Drawer anchor="left" open={open} onClose={onClose}>

        <List>
          <ListItem key={'User name'} onClick={onAccountClick}>
            <ListItemIcon>
              <AccountCircleIcon />
            </ListItemIcon>
            <ListItemText primary={user.displayName} secondary={user.isAdmin ? '(admin)' : ''} />
          </ListItem>
        </List>
        {!!menus.length && <Divider />}
        <List>{Menus}</List>
        <Divider />
        <List>
          <ListItem button key={'Sign out'} onClick={onLogout}>
            <ListItemIcon>
              <ExitToAppIcon />
            </ListItemIcon>
            <ListItemText primary={'Sign out'} />
          </ListItem>
        </List>

    </Drawer>
  )
}
<file_sep>/src/hooks/useForm.js
import * as React from 'react'

export default function ({ schema }) {
  const [values, setValues] = React.useState({})
  const [isValid, setIsValid] = React.useState({})
  const [isDirty, setIsDirty] = React.useState(false)
  const [errors, setErrors] = React.useState()
  const [validatedValues, setValidatedValues] = React.useState({})
  const [focusAt, setFocusAt] = React.useState('')

  React.useEffect(() => {
    if (!schema) {
      return
    }

    if (!isDirty) {
      return
    }

    let validateErrors
    const { error, value } = schema.validate(values, {
      abortEarly: false,
      allowUnknown: true,
      convert: true,
    })

    if (error) {
      validateErrors = {}
      error.details.forEach((err) => {
        validateErrors[err.path[0]] = err.message
      })
    }

    setValidatedValues(value)
    setErrors(validateErrors)
    setIsValid(!validateErrors)
  }, [schema, values])

  const setInitialValues = (initialValues) => {
    setValues({ ...initialValues })
  }

  const validate = React.useCallback(() => {
    if (!schema) {
      throw Error('No schema for validate')
    }

    let validateErrors
    const { error, value } = schema.validate(values, {
      abortEarly: false,
      allowUnknown: true,
      convert: true,
    })

    if (error) {
      validateErrors = {}
      error.details.forEach((err) => {
        validateErrors[err.path[0]] = err.message
      })
    }

    setValidatedValues(value)
    setErrors(validateErrors)
    setIsValid(!validateErrors)

    return { errors: validateErrors, values: value }
  }, [schema, values])

  const onChange = React.useCallback(
    (name, value) => {
      setIsDirty(true)
      setValues({ ...values, [name]: value })
    },
    [values]
  )

  const onFocus = (name) => () => {
    setFocusAt(name)
  }

  const onBlur = () => {
    setFocusAt('')
  }

  return {
    onChange,
    onFocus,
    onBlur,
    focusAt,
    setInitialValues,
    validate,
    values,
    validatedValues,
    errors,
    isDirty,
    isValid,
  }
}
<file_sep>/src/components/PrimaryButton/index.js
export default from './PrimaryButton'
<file_sep>/src/containers/Top/index.js
export default from './Top'
<file_sep>/src/App/App.js
import React from 'react'
import firebase from 'service/firebase'
import { BrowserRouter as Router } from 'react-router-dom'
import { makeStyles } from '@material-ui/core/styles'

import Box from '@material-ui/core/Box'
import LinearProgress from '@material-ui/core/LinearProgress'
import useAuth from 'hooks/useAuth'
import AppRouter from './Router'

import css from './styles.scss'

const useStyles = makeStyles((theme) => ({
  app: {
    paddingBottom: theme.spacing(4),
  },
}))

function App(props) {
  const classes = useStyles()
  const auth = useAuth()

  React.useEffect(() => {
    firebase.auth().onAuthStateChanged(handlAuthStateChanged)
  }, [])

  async function handlAuthStateChanged(user) {
    if (!user) {
      auth.dispatch({
        type: 'set',
        payload: {
          initialChecked: false,
          user: null,
          tokenResult: null,
        },
      })

      window.location.assign('/sign-in')
      return
    }
    const tokenResult = await firebase.auth().currentUser.getIdTokenResult()
    auth.dispatch({
      type: 'set',
      payload: {
        initialChecked: true,
        user: user,
        tokenResult,
      },
    })
  }

  if (!auth.state.initialChecked) {
    return <LinearProgress />
  }

  return (
    <Box className={`app ${css.class} ${classes.app}`}>
      <Router>
        <AppRouter />
      </Router>
    </Box>
  )
}

export default App
<file_sep>/src/components/PrimaryButton/styles.scss
@import "common.scss";

:local(.class) {
  padding: 8px 12px;
  font-size: 12px;
  font-weight: bold;
  line-height: 18px;
  color: #fff;
  // background-color: $glay-600;
  border: none;
  border-radius: 4px;

  &.primary {
    // background-color: $brand-core-orange;
  }

  &.link {
    color: #000;
    background-color: transparent;
    outline: none;
  }

  &:disabled {
    opacity: 0.7;
  }
}
<file_sep>/src/components/FormInputField/index.js
export default from './FormInputField'
<file_sep>/src/components/FormInputField/FormInputField.js
export default function FormInputField(props) {
  const { form, name, type, render, value } = props

  const renderProps = {
    type,
    name,
    value,
  }

  if (type === 'checkbox') {
    renderProps.checked = !!form.values[name]
    renderProps.onChange = ({ target }) => form.onChange(name, target.checked)
  } else if (type === 'radio') {
    renderProps.checked = form.values[name] === value
    renderProps.onChange = ({ target }) => form.onChange(name, value)
  } else {
    renderProps.value = form.values[name] || ''
    renderProps.onChange = ({ target }) => form.onChange(name, target.value)
  }

  return render(renderProps)
}
<file_sep>/src/LoginConfirmation/UserNameDialog.js
import React from 'react'
import { makeStyles } from '@material-ui/core/styles'
import Box from '@material-ui/core/Box'
import Avatar from '@material-ui/core/Avatar'
import Button from '@material-ui/core/Button'
import TextField from '@material-ui/core/TextField'
import Dialog from '@material-ui/core/Dialog'
import DialogTitle from '@material-ui/core/DialogTitle'
import DialogActions from '@material-ui/core/DialogActions'
import DialogContent from '@material-ui/core/DialogContent'

const useStyles = makeStyles({
  bigAvatar: {
    margin: 10,
    width: 120,
    height: 120,
  },
  pictureUpload: {
    appearance: 'none',
    opacity: 0,
    position: 'absolute',
    top: 0,
    left: 0,
    width: '100%',
  },
})

export default function UserNameDialog({ open, onRegister, user }) {
  const classes = useStyles()
  const [inputs, setInputs] = React.useState({
    name: '',
    brandName: '',
    introduction: '',
    photo: '',
  })

  const handleUpdateInput = (key) => (event) => {
    setInputs({ ...inputs, [key]: event.target.value })
  }

  function handlePhotoSelected(event) {
    if (event.target.files.length < 1) {
      return
    }
    setInputs({ ...inputs, photo: event.target.files[0] })
  }

  if (!open) {
    return null
  }

  const resigterDisabled = inputs.name.trim() === '' || inputs.brandName.trim() === ''

  return (
    <Dialog open={open} aria-labelledby="form-dialog-title" fullWidth={true} maxWidth="sm">
      <DialogTitle>新規ユーザー登録</DialogTitle>

      <DialogContent>
        <Box display="flex" justifyContent="flex-start" alignItems="center">
          <Avatar
            alt={user && user.name ? user.name : 'profile photo'}
            src={user && user.photoURL}
            className={classes.bigAvatar}
          ></Avatar>
          <Button variant="contained">
            写真を選択
            <input
              type="file"
              accept="image/*"
              className={classes.pictureUpload}
              onChange={handlePhotoSelected}
            />
          </Button>
        </Box>

        <TextField
          InputLabelProps={{
            shrink: true,
          }}
          defaultValue={user.email || user.userInfo.user_email}
          disabled
          fullWidth
          label="メール"
          variant="filled"
        />

        <TextField
          autoFocus
          margin="normal"
          type="text"
          label="ユーザー名"
          fullWidth
          value={inputs.name}
          onChange={handleUpdateInput('name')}
        />
        <TextField
          autoFocus
          margin="normal"
          type="text"
          label="ブランド名"
          fullWidth
          value={inputs.brandName}
          onChange={handleUpdateInput('brandName')}
        />
        <TextField
          autoFocus
          margin="normal"
          type="text"
          label="自己紹介"
          fullWidth
          value={inputs.introduction}
          onChange={handleUpdateInput('introduction')}
        />
      </DialogContent>
      <DialogActions>
        <Button onClick={() => onRegister(inputs)} color="primary" disabled={resigterDisabled}>
          登録
        </Button>
      </DialogActions>
    </Dialog>
  )
}
<file_sep>/stylelint.config.js
module.exports = {
  extends: [
    'stylelint-config-recommended-scss',
    'stylelint-config-standard',
    'stylelint-config-recess-order',
  ],
  plugins: ['stylelint-declaration-block-no-ignored-properties', 'stylelint-prettier'],
  rules: {
    'at-rule-no-unknown': null,
    'selector-pseudo-class-no-unknown': [
      true,
      {
        ignorePseudoClasses: ['local'],
      },
    ],
    'scss/at-rule-no-unknown': [
      true,
      {
        ignoreAtRules: ['use', 'forward'],
      },
    ],
    'no-duplicate-selectors': null,
    'plugin/declaration-block-no-ignored-properties': true,
    'prettier/prettier': true,
  },
}
<file_sep>/src/components/Header/Header.js
import React from 'react'
// import { useHistory } from 'react-router-dom'

import { makeStyles } from '@material-ui/core/styles'
import AppBar from '@material-ui/core/AppBar'
import Toolbar from '@material-ui/core/Toolbar'
import Typography from '@material-ui/core/Typography'
import IconButton from '@material-ui/core/IconButton'
import MenuIcon from '@material-ui/icons/Menu'
import useAuth from 'hooks/useAuth'

import Sidemenu from './Sidemenu'

const useStyles = makeStyles((theme) => ({
  root: {
    flexGrow: 1,
  },

  menuButton: {
    marginRight: theme.spacing(2),
  },

  title: {
    flexGrow: 1,
  },
}))

function Header({ className, onClick, disabled, children, varient }) {
  // const history = useHistory()
  const classes = useStyles()
  const [sidemenuOpen, setSidemenuOpen] = React.useState(false)
  const { state: userState, signOut } = useAuth()
  // const [sidemenus, setSidemenus] = React.useState([])

  // React.useEffect(() => {
  //   setSidemenus(filtered)
  // }, [brandId])

  function handleLogout() {
    return signOut().then(() => {
      window.location.assign('/sign-in')
    })
  }

  // function handleAccountClick() {
  //   setSidemenuOpen(false)
  //   history.push(`/users/${auth.state.user.id}/edit`)
  // }

  return (

      <AppBar position="static">
        <Toolbar>
          <IconButton
            edge="start"
            className={classes.menuButton}
            color="inherit"
            aria-label="menu"
            onClick={() => setSidemenuOpen(true)}
          >
            <MenuIcon />
          </IconButton>
          <Typography variant="h6">Startup-kit</Typography>
        </Toolbar>
      </AppBar>
      <Sidemenu
        // user={auth.state.user}
        user={userState.user}
        // menus={sidemenus}
        open={sidemenuOpen}
        // onAccountClick={handleAccountClick}
        // onMenuClick={handleMenuClick}
        onClose={() => setSidemenuOpen(false)}
        onLogout={handleLogout}
      />

  )
}

export default Header
<file_sep>/src/containers/Sample/index.js
export default from './Sample'
<file_sep>/src/containers/Top/Top.js
import React from 'react'
// import { useHistory } from 'react-router-dom'

import css from './styles.scss'

function Top() {
  // const history = useHistory()

  return (
    <div className={`top ${css.class}`}>

Top

  )
}

export default Top
<file_sep>/src/LoginConfirmation/LoginConfirmation.js
import React from 'react'
import axios from 'axios'
import firebase from 'service/firebase'
import { decodeJwt } from 'utility/endecode'

import LinearProgress from '@material-ui/core/LinearProgress'
import UserNameDialog from './UserNameDialog'

import css from './styles.scss'

const api = axios.create({
  baseURL: process.env.API_BASE_URL,
})

function LoginConfirmation() {
  const [open, setOpen] = React.useState(false)
  const [user, setUser] = React.useState(null)
  React.useEffect(() => {
    firebase.auth().onAuthStateChanged(handleAuthStateChanged)
  }, [])

  async function handleAuthStateChanged(user) {
    if (!user || user.isAnonymous) {
      window.location.assign('/sign-in')
      return
    }

    const token = await firebase.auth().currentUser.getIdToken(/* forceRefresh */ true)
    const userInfo = decodeJwt(token)
    setUser({ ...user, userInfo })

    try {
      const result = await api.get(`/v1/admin/client-users/check-registration?token=${token}`)

      if (!result.data.registered) {
        setOpen(true)
        return
      }

      window.location.assign('/')
    } catch (error) {
      alert('ユーザー情報読み込みエラー')
      // location.reload()
      throw error
    }
  }

  async function handleRegister(data) {
    setOpen(false)

    let token = await firebase.auth().currentUser.getIdToken()
    try {
      await api.post(`/v1/admin/client-users?token=${token}`, {
        name: data.name,
        brandName: data.brandName,
        introduction: data.introduction,
        email: user.email || user.userInfo.user_email,
        photo: user.photoURL,
      })

      // Refresh custom claim to take id
      await firebase.auth().currentUser.getIdToken(/* forceRefresh */ true)
      token = await firebase.auth().currentUser.getIdToken()
    } catch (error) {
      window.alert('登録失敗しました。')
      window.location.assign('/sign-in')
      return
    }

    if (data.photo) {
      try {
        const params = new FormData()
        params.append('photo', data.photo)
        await api.put(`/v1/admin/client-users/me/photo?token=${token}`, params)
      } catch (error) {
        window.alert('写真の設定が失敗しました。')
      }
    }
    window.location.assign('/')
  }

  return (
    <div className={`login-confirmation ${css.class}`}>
      <LinearProgress />
      Login confirmation
      <UserNameDialog open={open} user={user} onRegister={handleRegister}></UserNameDialog>

  )
}

export default LoginConfirmation
<file_sep>/src/containers/Sample/Sample.js
import React from 'react'
import Joi from 'joi'

import useForm from 'hooks/useForm'
import Box from '@material-ui/core/Box'

import FormInputField from 'components/FormInputField'

import css from './styles.scss'

const schema = Joi.object({
  userName: Joi.string().min(3).max(15).trim().required(),
  gender: Joi.number().only().allow(1, 2).required(),
})

function Customers() {
  const form = useForm({ schema })
  const [errors, setErrors] = React.useState({})

  React.useEffect(() => {
    form.setInitialValues({
      userName: 'Ma ni',
      gender: 2,
      note: 'hello',
      occupation: 'teacher',
      married: false,
    })
  }, [])

  const handleSave = () => {
    // Call API here
    setErrors({})
    const { values, errors } = form.validate()

    if (errors) {
      setErrors(errors)
    }

    console.log('errors', errors)
    console.log('values', values)
  }

  return (
    <Box className={`customer ${css.class}`} flexGrow={1}>

        <FormInputField form={form} name="userName" render={(props) => <input {...props} />} />
        {errors.userName &&
User name is not correct
}

        <FormInputField form={form} name="note" render={(props) => <input {...props} />} />

        <FormInputField
          form={form}
          name="gender"
          render={(props) => {
            return (
              <select {...props}>
                <option value={1}>Man</option>
                <option value={2}>Woman</option>
                <option value={3}>None</option>
              </select>
            )
          }}
        />
        {errors.gender &&
Gender is not correct
}

        <FormInputField
          form={form}
          name="married"
          type="checkbox"
          render={(props) => {
            return (

                <input {...props} />
                Married

            )
          }}
        />

        <FormInputField
          form={form}
          name="occupation"
          type="radio"
          value="student"
          render={(props) => {
            return (

                <input {...props} />
                Student

            )
          }}
        />
        <FormInputField
          form={form}
          name="occupation"
          type="radio"
          value="teacher"
          render={(props) => {
            return (

                <input {...props} />
                Teacher

            )
          }}
        />
        <FormInputField
          form={form}
          name="occupation"
          type="radio"
          value="engineer"
          render={(props) => {
            return (

                <input {...props} />
                Engineer

            )
          }}
        />

      <button onClick={handleSave}>Save</button>

{JSON.stringify(form.values)}

{JSON.stringify(form.errors)}

    </Box>
  )
}

export default Customers
<file_sep>/src/App/Router.js
import React from 'react'
import { Switch, Route, Redirect } from 'react-router-dom'

import Container from '@material-ui/core/Container'

import Top from 'containers/Top'
import Sample from 'containers/Sample'

import Header from 'components/Header'

function BaseRouter() {
  return (

      <Container maxWidth="md">
        <Switch>
          <Route exact path="/" component={Top} />
          <Route exact path="/sample" component={Sample} />
          <Redirect to="/" />
        </Switch>
      </Container>

  )
}

export default BaseRouter
<file_sep>/src/SignIn/SignIn.js
import React from 'react'
import firebase from 'service/firebase'

import Box from '@material-ui/core/Box'
import Button from '@material-ui/core/Button'
import Typography from '@material-ui/core/Typography'
import LinearProgress from '@material-ui/core/LinearProgress'

export default function SignIn() {
  const [loading, setLoading] = React.useState(false)
  const signInInitiated = React.useRef()

  React.useEffect(() => {
    firebase.auth().onAuthStateChanged(handleAuthStateChanged)
  }, [])

  async function handleAuthStateChanged(user) {
    if (signInInitiated.current) {
      return
    }
    if (!user || user.isAnonymous) {
      signInInitiated.current = true
      return
    }

    window.location.assign('/')
  }

  async function handleLoginWithGoogle(user) {
    const provider = new firebase.auth.GoogleAuthProvider()

    firebase
      .auth()
      .signInWithPopup(provider)
      .then(async function (result) {
        setLoading(true)
        window.location.assign('/')
      })
      .catch(function (error) {
        setLoading(false)
        const { code, message } = error
        if (code === 'auth/popup-closed-by-user') {
          return
        }

        alert(`Loginエラー：${message}`)
        throw error
      })
  }

  return (

      {loading && <LinearProgress />}

      <Box textAlign="center">
        <Typography variant="h6" color="primary">
          {"Welcome to Senyou's startup-kit"}
        </Typography>
      </Box>
      {!loading && (
        <Box textAlign="center">
          <Button variant="outlined" color="primary" onClick={handleLoginWithGoogle}>
            Google でログイン
          </Button>
        </Box>
      )}

  )
}
<file_sep>/src/constants/conts.js
export const pagination = {
  ROW_PER_PAGE: 10,
}
<file_sep>/src/SignIn/index.js
import 'core-js/stable'

// HMR対応するのためReactより先にインポートする必要あり
// https://github.com/gaearon/react-hot-loader#getting-started
import rootRender from 'helpers/rootRender'

import SignIn from './SignIn'

import 'css/index.scss'

rootRender(SignIn)
<file_sep>/src/SignIn/styles.scss
@import "common.scss";

:local(.class) {
  position: relative;
}

languages: SCSS JavaScript

repo_language: SCSS

repo_name: senyouhq/startup-kit


text:
<file_sep># Laravel CI tools

This image is for building, testing and deploying Laravel applications from docker based CI/CD solutions. This image was tested with Bitbucket Pipelines and Gitlab CI/CD, but feel free to use any other CI/CD solutions.

## Softwares included

- PHP 8.1
- Node.js 16 (current LTS version)
- Yarn
- Composer
- Laravel Envoy
- Laravel Vapor CLI

## Example list

- Gitlab CI/CD with Laravel Vapor

## Contributing

If you would like to extend the toolset, or just provide other CI/CD templates, you are welcome!
<file_sep>FROM php:8.1

# Install linux dependencies
RUN apt-get update &&  apt-get install -qq curl apt-transport-https git build-essential \
    libssl-dev libzip-dev wget unzip bzip2 libbz2-dev zlib1g-dev libfontconfig \
    libfreetype6-dev libjpeg62-turbo-dev libpng-dev  libicu-dev libxml2-dev \
    libldap2-dev libmcrypt-dev jq gnupg  zip unzip openssh-client libsodium23 libsodium-dev \
    rsync grsync \
    && apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

# Install and enable mcrypt
RUN pecl install mcrypt
RUN docker-php-ext-enable mcrypt

# Install additional php extensions
RUN docker-php-ext-install zip gd exif sodium

# Install Composer
# copy the Composer PHAR from the Composer image into the PHP image
ENV COMPOSER_ALLOW_SUPERUSER 1
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
# show that both Composer and PHP run as expected
RUN composer --version && php -v && composer global config --list | grep "vendor-dir" && sleep 5s

# Install Laravel Envoy
RUN composer global require "laravel/envoy=~1.0"

# Install Laravel Vapor CLI
RUN composer global require "laravel/vapor-cli"

# Install Node (with NPM), and Yarn (via package manager for Debian)
# https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions
RUN curl -sL https://deb.nodesource.com/setup_16.x | bash -
RUN apt-get update \
    && apt-get install -y \
    nodejs
RUN npm install -g yarn

branch_name: refs/heads/master

languages: Markdown Dockerfile

repo_language: Markdown

repo_name: drahosistvan/laravel-ci-tools


text:
<file_sep>using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using UnityEngine.UI;

public class GameOfLife : MonoBehaviour
{
    [SerializeField]
    GameObject block;
    [SerializeField]
    Vector2 gridSize;
    public Slider sl;

    public float rate = 1f;
    // Start is called before the first frame update
    void Start()
    {
        System.Random rand = new System.Random();
        for(int i=0;i< (int)gridSize.x; i++)
        {
            for(int j=0;j< (int)gridSize.y; j++)
            {
                Instantiate(block, new Vector3(i, 0, j), Quaternion.identity, transform);
            }
        }
        foreach(Transform t in transform)
        {
            t.GetComponent<Block>().alive = 0;
        }
    }
    public void ChangeRate()
    {

        rate = sl.value;

    }
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Block : MonoBehaviour
{
    public int alive = 1;
    Renderer ren;
    float timer=1f;
    bool moveGen = false;
    List<Transform> neighbors = new List<Transform>();
    private void Awake()
    {
        ren = GetComponent<Renderer>();
    }
    private void Start()
    {
        Collider[] col = Physics.OverlapBox(transform.position, new Vector3(.6f, .6f, .6f));
        foreach(Collider c in col)
        {
            if (c.transform == transform) continue;
            neighbors.Add(c.transform);
        }
    }
    private void Update()
    {
        timer -= Time.deltaTime;
        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            moveGen = !moveGen;
        }
        if (moveGen&&timer<=0)
        {
            timer = GetComponentInParent<GameOfLife>().rate;
            GameLogic();
        }
        if (alive == 1)
        {
            ren.material.color = Color.blue;
        }
        else
        {
            ren.material.color = Color.black;
        }
    }
    void GameLogic()
    {

        int countAlive = 0;
        foreach(Transform t in neighbors)
        {
            if (t.transform.GetComponent<Block>().alive == 1)
            {
                countAlive++;
            }
        }
        if (alive == 1 && (countAlive == 2 || countAlive == 3))
        {
            alive = 1;
        }
        else if (alive == 0 && countAlive == 3)
        {
            alive = 1;
        }
        else
        {
            alive = 0;
        }

    }
    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.green;
        Gizmos.DrawWireCube(transform.position, new Vector3(1.2f, 1.2f, 1.2f));
    }
}

<file_sep>using UnityEngine;

public class BlockSelection : MonoBehaviour
{
    public RectTransform selectionBox;
    public Vector2 startPos;
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            startPos = Input.mousePosition;
            if (Physics.Raycast(Camera.main.ScreenPointToRay(startPos),out RaycastHit hit))
            {
                hit.transform.GetComponent<Block>().alive = 1;
            }
        }
        if (Input.GetMouseButton(0))
        {
            UpdateSelectionBox(Input.mousePosition);
        }
        if (Input.GetMouseButtonUp(0))
        {
            ReleaseSelection();
        }
    }
    void ReleaseSelection()
    {
        selectionBox.gameObject.SetActive(false);
        Vector2 min = selectionBox.anchoredPosition - (selectionBox.sizeDelta / 2);
        Vector2 max = selectionBox.anchoredPosition + (selectionBox.sizeDelta / 2);
        foreach(Transform t in transform)
        {
            Vector3 screenPos = Camera.main.WorldToScreenPoint(t.position);
            if (screenPos.x > min.x && screenPos.x < max.x && screenPos.y > min.y && screenPos.y < max.y)
            {
                t.GetComponent<Block>().alive = 1;
            }
        }
    }
    void UpdateSelectionBox(Vector2 pos)
    {
        if (!selectionBox.gameObject.activeInHierarchy)
        {
            selectionBox.gameObject.SetActive(true);
        }
        float width = pos.x - startPos.x;
        float height = pos.y - startPos.y;
        selectionBox.sizeDelta = new Vector2(Mathf.Abs(width), Mathf.Abs(height));
        selectionBox.anchoredPosition = startPos+new Vector2(width/2,height/2);
    }
}

branch_name: refs/heads/main

repo_language: C#

repo_name: athasiop/The-Game-Of-Life


text:
<file_sep>from Bio import Entrez, SeqIO
from Bio.SubsMat import MatrixInfo as mi

#macierz substytucji
values = mi.blosum62
#kara za przerwanie
gap_penalty = -7

#zwraca wartosc dopasowania z blosum62, np A i B daja -2
def lookup(a, b):
	if (a, b) in values:
		return values[(a, b)]
	else:
		return values[(b, a)]

#zwraca tablice wypelniana zerami oraz i*d w 0 kolumnie i 0 wierszu
#przygotowanie tablicy do pozniejszych obliczen
def init(str1, str2):
	tab = [[0] * (len(str1) + 1) for i in range(len(str2) + 1)]
	for i in range(1, len(str1) + 1):
		tab[0][i] = i * gap_penalty
	for i in range(1, len(str2) + 1):
		tab[i][0] = i * gap_penalty
	return tab

#generuje pusta tablice (zawierajaca puste listy), tu beda trzymane kierunki
def gen_array(n, m):
    arr = []
    for x in range(0, m):
        tmp = []
        for y in range(0, n):
            tmp.append([])
        arr.append(tmp)
    return arr

#glowna czesc algorytmu, dopasowuje wartosc wg schematu:
# tab[i][j] = max(
#				tab[i-1][j-1] + values(a,b), // pasuja
#				tab[i-1][j] + gap_penalty) // delecja
#				tab[i][j-1] + gap_penalty)) // insercja
# przy okazji w tablicy move usupelnia informacje, ktory ruch byl najkorzystniejszy.
# poniewaz chcemy wszystkie optymalne wyniki, dlatego musimy sprawdzic czy przypadkiem
# wszystkie przypadki nie sa rowne max
def fill(str1, str2, tab, move):
	for j in range(1, len(str1) + 1):
		for i in range(1, len(str2) + 1):
			match = tab[i-1][j-1] + lookup(str1[j-1], str2[i-1])
			delete = tab[i-1][j] + gap_penalty
			insert = tab[i][j-1] + gap_penalty
			maks = max(match, delete, insert)
			if maks == match:
				move[i][j].append('diag')
			if maks == delete:
				move[i][j].append('up')
			if maks == insert:
				move[i][j].append('left')
			tab[i][j] = maks

# backtracking na podstawie tablicy move, idziemy od konca wyrazow, zbieramy je w akumulatorach
# acc1 i acc2, gdy dochodzimy do 'ramki' od gory lub lewej - pustych miejsc w move - to wypisujemy
# wynik. tutaj tez nieladne if-y, ale mozemy miec wiele optymalnych rozwiazan (np. dla "AA" i "AAAA")
def backtrack2(str1, str2, move, i, j, acc1, acc2):
	x = move[i][j]
	if x.count('diag') > 0: #match
		backtrack2(str1, str2, move, i-1, j-1, str1[i-1]+acc1, str2[j-1]+acc2)
	if x.count('up') > 0: #delete
		backtrack2(str1, str2, move, i-1, j, str1[i-1]+acc1, "-"+acc2)
	if x.count('left') > 0: #insert
		backtrack2(str1, str2, move, i, j-1, "-"+acc1, str2[j-1]+acc2)
	if len(x) == 0:
		print 'best match:'
		print "1: " + acc1
		print "2: " + acc2

#opakowuje backtrack2 dla wygody testowania
def backtrack(str1, str2, move):
	backtrack2(str2, str1, move, len(str2), len(str1), "", "")

#glowna metoda, inicjalizuje tablice, wykonuje algorytm, wypisuje wynik(i)
def nw(str1, str2):
	tab = init(str1, str2)
	move = gen_array(len(str1)+1, len(str2)+1)
	fill(str1, str2, tab, move)
	print 'best score: ', tab[len(str2)][len(str1)]
	backtrack(str1, str2, move)

#pobiera przez entrez sekwencje aminokwasow o podanym id
def getSequence(gi):
	handle = Entrez.efetch(db="protein", id=gi, rettype="gb", retmode="text")
	record = SeqIO.read(handle, "genbank")
	return record.seq

#main
def main():
	print 'starting...'
	Entrez.email = "<EMAIL>"
	print 'fetching data...'
	str1 = getSequence("40886941") # hemoglobina czlowieka
	str2 = getSequence("34849618") # szczura
	print 'matching...'
	nw(str1, str2)
	print 'end'

if __name__ == "__main__":
	main()

<file_sep>from Bio.Blast import NCBIWWW, NCBIXML

seq = """ >Lookup Sequence (in FASTA format)
MKSILDGLADTTFRTITTDLLGSPFQEKMTAGDNPQLVPADQVNITEFYNKSLSSFKENEENIQCGENFMDIECFMVLNPSQQLAIAVLSLTLGTFTVLENLLVLCVILHSRSLRCRPSYHFIGSLAVADLLGSVIFVYSFIDFHVFHRKDSRNVFLFKLGGVTASFTASVGSLFLTAIDRYISIHRPLAYKRIVTRPKAVVAFCLMWTIAIVIAVLPLLGWNCEKLQSVCSDIFPHIDETYLMFWIGVTSVLLLFIVYAYMYILWKAHSHAVRMIQRGTQKSIIIHTSEDGKVQVTRPDQARMDIRLAKTLVLILVVLIICWGPLLAIMVYDVFGKMNKLIKTVFAFCSMLCLLNSTVNPIIYALRSKDLRHAFRSMFPSCEGTAQPLDNSMGDSDCLHKHANNAASVHRAAESCIKSTVKIAKVTMSVSTDTSAEAL

"""

def main():
	print 'querying...'
	qblast_output = NCBIWWW.qblast("blastp", "nr", seq, hitlist_size=50) #zapytanie
	blast_records = NCBIXML.parse(qblast_output) #parsowanie
	blast_record = blast_records.next() #bylo tylko jedno zapytanie
	print 'results: '
	ile = 0
	len_sum = 0
	e_ile = 0
	e_sum = 0

	for a in blast_record.alignments: #dla kazdego z wynikow
		ile += 1
		print 'Title: ', a.title
		print 'Length:   ', a.length
		len_sum += a.length
		for hsp in a.hsps:
			e_sum += hsp.expect
			e_ile += 1
	if ile > 0:
		print 'Average length: ', len_sum/ile # s<NAME>
	else:
		print 'Average length: ', 0
	if e_sum > 0:
		print 'Average E: ', e_sum/e_ile #srednie e
	else:
		print 'Average E: ', 0

if __name__ == "__main__":
	main()
<file_sep>Various bioinformatics projects from 2014.<file_sep># Sekwencje DNA - bioinformatyka lab 1 zadanie domowe
# <NAME>, python 3.4
# wywolanie: $ python Izabela.Orlowska.1.py <input file>
# przyklad: $ python Izabela.Orlowska.1.py hemoglobin.txt
def count(sequence):
        return {'A': sequence.count('A'), 'T': sequence.count('T'), 'C': sequence.count('C'), 'G': sequence.count('G')}

compl = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}
def complement(sequence):
	com = ""
	for x in sequence:
		com += compl[x]
	return com

gencode = { 'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
	'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
	'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',
	'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
	'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',
	'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
	'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',
	'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
	'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',
	'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
	'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',
	'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
	'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',
	'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
	'TAC':'Y', 'TAT':'Y', 'TAA':'*', 'TAG':'*',
	'TGC':'C', 'TGT':'C', 'TGA':'*', 'TGG':'W' }

def translate(sequence):
	return translate2(sequence, "", [])

def translate2(sequence, currstr="", all=[]):
	if (len(sequence) < 3):
		return all
	else:
		curr = gencode.get(sequence[0:3])
		if curr == '*':
			if currstr != "":
				all.append(currstr)
			return translate2(sequence[3:], "", all)
		else:
			return translate2(sequence[3:], (currstr + curr), all)

def readFromFile(fileName):
	f = open(fileName, 'r')
	str = ""
	for line in f:
		str = str + line.rstrip()
	print ("\ncount:")
	print (count(str))
	print ("\ncomplement:")
	print (complement(str))
	print ("\ntranslate:")
	print (translate(str))
	print ("\ntranslate from 2nd:")
	print (translate(str[1:]))
	print ("\ntranslate from 3rd:")
	print (translate(str[2:]))
	print ("\nfinished")

if __name__ == "__main__":
    import sys
    readFromFile(sys.argv[1])
<file_sep>from collections import Counter
import re
import sys
# how to: python Izabela.Orlowska.2.py hemoglobin_amino_acid.txt hemoglobin.txt amino_acid_sequences.txt

#czesc1:
#gencode = { 'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
#    'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
#    'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',
#    'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
#    'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',
#    'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
#    'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',
#    'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
#    'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',
#    'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
#    'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',
#    'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
#    'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',
#    'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
#    'TAC':'Y', 'TAT':'Y', 'TAA':'*', 'TAG':'*',
#    'TGC':'C', 'TGT':'C', 'TGA':'*', 'TGG':'W' }
REGEX_ORG = "G{1,3}.[^P]{2}[RGI]*L+V"

# G=GGA, GGC, GGG, GGT = GG.
# P=CCA, CCC, CCG, CCT = CC.
# R=AGA, AGG, CGA, CGC, CGG, CGT = AG[AG] | CG.
# I=ATA, ATC, ATT = AT[^G]
# L=CTA, CTC, CTG, CTT, TTA, TTG = CT. | TT[AG]
# V=GTA, GTC, GTG, GTT = GT.
REGEX_TRAN = '(GG.){1,3}...([^C][^C].){2}(AG[AG]|CG.|GG.|AT[^G])*(CT.|TT[AG])+GT.'

#czesc2:
#group(0) - calosc, group(1) - fragment pasujacy, group(2) - Q, group(3) - ILM
AMINO_ACID_REGEX = "(([^.{0,3}]| Q).[^FHWY]([ILM])[^P][^FHILVWYP][DHFM][FMY])"

#try matching
def try_match(filename, regex, print_most_common=False):
    counter = Counter()
    i = 0
    for line in open(filename).readlines():
        match = re.search(regex, line)
        if match:
            print 'line ', i, 'matches pattern'
            if print_most_common:
                ilm = match.group(3)
                counter[ilm] += 1
        else:
            print 'line ', i, 'does not match pattern'
        i += 1
    if print_most_common:
        print 'Most common: ', counter.most_common()

#main
if __name__ == "__main__":
    print 'Czesc 1:'
    print '\t1.a'
    print 'regex=', REGEX_TRAN
    try_match(sys.argv[1], REGEX_TRAN) # hemoglobin_amino_acid.txt
    print '\t1.b'
    print 'regex=', REGEX_ORG
    try_match(sys.argv[2], REGEX_ORG) # hemoglobin.txt
    print
    print 'Czesc 2:'
    filename3 = sys.argv[3]
    try_match(filename3, AMINO_ACID_REGEX, print_most_common=True) # amino_acid_sequences.txt
<file_sep>from Bio import Entrez, SeqIO

def part1(term):
	handle = Entrez.esearch(db="gene", term=term)
	result = Entrez.read(handle)
	ids = result['IdList']
	foundid = 0
	print "{:>12} {:>10} {:>11} {:>10}".format('Name', 'Chromosome', 'MapLocation', 'Description')
	for id in ids:
		handle = Entrez.esummary(db="gene", id=id)
		r = Entrez.read(handle)[0]
		print "{:>12} {:>10} {:>11} {:>10}".format(r['Name'], r['Chromosome'], (r['MapLocation'] or 'none'), r['Description'])
		if r['Name'] == "BRCA1":
			foundid = id
	return foundid

def part2(id):
	if id == 0:
		print "\nCouldn't find BRCA1\n"
	else:
		print "\nFound BRCA1 gene id = ", id, "\n"

def part3(term):
	handle = Entrez.esearch(db="omim", term=term)
	result = Entrez.read(handle)
	ids = result['IdList']
	print 'OMIM results\' titles:'
	for id in ids:
		handle = Entrez.esummary(db="omim", id=id)
		r = Entrez.read(handle)[0]
		print r['Title']

def part4(id):
	handle = Entrez.elink(dbfrom="gene", db="protein", id=id)
	result = Entrez.read(handle)
	ids = result[0]['LinkSetDb'][0]['Link']
	print '\nProtein Gi\'s:'
	for id in ids:
		handle = Entrez.esummary(db="protein", id=id['Id'])
		r = Entrez.read(handle)
		print r[0]['Gi']

def part5():
	handle = Entrez.efetch(db="protein", id="121949022", rettype="gb", retmode="text")
	record = SeqIO.read(handle, "genbank")
	print "\nFound protein in genbank, details:"
	print "name: " + record.name
	print "seq: " + record.seq

def part6(term):
	handle = Entrez.esearch(db="snp", term="Homo sapiens AND " + term)
	result = Entrez.read(handle)
	ids = result['IdList'][:50]
	print "\nSNP results:"
	print "{:>10} {:>10} {:>10} {:>30}".format('SNP ID', 'SNP CLASS', 'GENE', 'CONTIGPOS')
	for id in ids:
		handle = Entrez.esummary(db="snp", id=id)
		r = Entrez.read(handle)[0]
		print "{:>10} {:>10} {:>10} {:>30}".format(r['SNP_ID'], r['SNP_CLASS'], (r['GENE'] or 'empty'), r['CONTIGPOS'])

def main():
	term = "BRCA1"
	Entrez.email = "<EMAIL>"
	BRCA1_gene_id = part1(term)
	part2(BRCA1_gene_id)
	part3(term)
	part4(BRCA1_gene_id)
	part5()
	part6(term)

if __name__ == "__main__":
	main()

# part7
# Entrez jest bardzo przydatnym narzedziem, przydalaby sie jednak mozliwosc latwego cachowania
# czesci danych (gdy brakuje dostepu do sieci).
# Ze wzgledu na prostote kodu i wygode stosowanie rettype genbank i retmode text wydaje sie
# ladniejsza alternatywa niz XML (record.name vs result['Name'] i duze prawdopodobienstwo
# wystapienia literowek).
# Wygodnym narzedziem przy uzywaniu Entrez wydaje sie interpreter ipython, poniewaz bledy
# zwracane same z siebie z blednego uzywania Entrez sa malo intuicyjne.
#

languages: Markdown Python

repo_name: imorlowska/Bioinformatics


text:
<repo_name>fuzzychin/cars<file_sep>/README.md
a quick practice using Spring

repo_name: fuzzychin/cars


text:
<file_sep># 个人博客

#### Hello world!

#### 基于 hexo + next主题


text:
<repo_name>PedroAssaf/ExercicioAppGasolina<file_sep>/settings.gradle
include ':app'
rootProject.name = "AppGasolina"

repo_language: Gradle

repo_name: PedroAssaf/ExercicioAppGasolina


text:
<file_sep>using System;
using System.Activities.Expressions;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Contact_Tracing
{
    public partial class ContactTracing : Form
    {
        public ContactTracing()
        {
            InitializeComponent();
        }

        private void bttnSave_Click(object sender, EventArgs e)
        {
            Save();
            StreamReader inputfile;
            inputfile = File.OpenText("output.txt");
            MessageBox.Show(inputfile.ReadToEnd());
            inputfile.Close();
        }

        private void txtboxContactNumber_KeyPress(object sender, KeyPressEventArgs e)
        {
            char ch = e.KeyChar;

            if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
            {
                e.Handled = true;
            }
        }

        private void txtboxAge_KeyPress(object sender, KeyPressEventArgs e)
        {
            char ch = e.KeyChar;

            if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
            {
                e.Handled = true;
            }
        }

        private void txtboxTemperature_KeyPress(object sender, KeyPressEventArgs e)
        {
            char ch = e.KeyChar;

            if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
            {
                e.Handled = true;
            }
        }

        private void Save()
        {
            StreamWriter outputfile = File.AppendText("output.txt");
            outputfile.WriteLine(txtboxFirstName.Text);
            outputfile.WriteLine(txtboxLastName.Text);
            outputfile.WriteLine(txtboxAddress.Text);
            outputfile.WriteLine(txtboxContactNumber.Text);
            outputfile.WriteLine(txtboxAge.Text);
            outputfile.WriteLine(txtboxTemperature.Text);
            outputfile.Close();
        }
    }
}

repo_name: thisismic/Contact-Tracing


text:
<file_sep>// Learn more about F# at http://fsharp.net
// See the 'F# Tutorial' project for more help.
open Chapter1

[<EntryPoint>]
let main argv =
//    do Chapter1.BallSimulation_extended.simulation()
//    do Chapter1.BallSimulation.simulation()
    do Chapter2.RocketSimulation.simulation()
    0 // return an integer exit code
<file_sep>namespace Chapter5
  module PoliceChase =
    open System
    open System.Threading
    open Chapter2.Math
//    open Chapter5.Math
    open Chapter5.Coroutines

    [<Measure>]
    type Life

    type Ship =
      {
        mutable Position      : Vector2<m>
        mutable Velocity      : Vector2<m/s>
        DryMass               : float<kg>
        mutable Fuel          : float<kg>
        MaxFuel               : float<kg>
        Thrust                : float<N/s>
        FuelBurn              : float<kg/s>
        mutable Force         : Vector2<N>
        mutable Integrity     : float<Life>
        MaxIntegrity          : float<Life>
        Damage                : float<Life/s>
        WeaponsRange          : float<m>
        mutable AI            : Coroutine<Unit>
      }

      member this.Mass = this.DryMass + this.Fuel

    type Station =
      {
        Position              : Vector2<m>
        mutable Integrity     : float<Life>
        MaxIntegrity          : float<Life>
      }

    type PoliceChase =
      {
        PoliceStation : Station
        Patrol        : Ship
        Pirate        : Ship
        Cargo         : Ship
        DemonPortal   : Station
        Demons        : Ship
      }

    let dt = 180.0<s>
    let field_size = 3.8e7<m>

    let impulse (self:Ship) (dir:Vector2<1>) (engine_power:float) =
      if self.Fuel > self.FuelBurn * engine_power * dt then
        do self.Force <- self.Thrust * dir * engine_power * dt
        do self.Fuel <- self.Fuel - self.FuelBurn * engine_power * dt

    let attack (self:Ship) (target:Ship) =
      co{
        do! yield_
        let dir = Vector2<_>.Normalize(target.Position - self.Position)
        let dist = (target.Position - self.Position).Length
        if dist > self.WeaponsRange * 0.8 then
          if self.Velocity.Length > 0.01<_> then
            let v_norm = self.Velocity.Normalized
            let dot = Vector2.Dot(dir,v_norm)
            if dot <= 0.0 then
              do impulse self (-self.Velocity.Normalized) 1.0
            elif dot < 0.5 then
              do impulse self (Vector2<_>.Normalize((-(self.Velocity.Normalized - dir * dot)))) 0.3
            else
              do impulse self dir 0.1
            do! wait 1.0
          else
            do impulse self dir 1.0
            do! wait 1.0
        return ()
      }

    let reach_station (station:Station) (self:Ship) (s:PoliceChase) =
      co{
        do! yield_
        let dir = Vector2<_>.Normalize(station.Position - self.Position)
        if Vector2<_>.Distance(station.Position, self.Position) <= field_size * 1.0e-1 then
          let zero_velocity =
            co{
              do! yield_
              return self.Velocity <- Vector2<_>.Zero
            }
          do! wait_doing (fun _ -> zero_velocity) 5.0
          do self.Integrity <- self.MaxIntegrity
          do self.Fuel <- self.MaxFuel
        elif self.Velocity.Length > 0.01<_> then
          let dot = Vector2<1>.Dot(self.Velocity.Normalized,dir)
          if dot <= 0.0 then
            do impulse self (-self.Velocity.Normalized) 1.0
          elif dot < 0.5 then
            do impulse self (Vector2<_>.Normalize((-(self.Velocity.Normalized - dir * dot)))) 0.3
          else
            do impulse self dir 0.2
          do! wait 1.0
        else
          do impulse self dir 1.0
          do! wait 1.0
        return ()
      }

    let patrol_ai (s:PoliceChase) =
      let self = s.Patrol
      let healthy_and_fueled =
        co{
          do! yield_
          return self.Integrity > self.MaxIntegrity * 0.4 && self.Fuel > self.MaxFuel * 0.4
        }
      let need_docking =
        co{
          do! yield_
          let! h = healthy_and_fueled
          return not h
        }
      repeat_ ((healthy_and_fueled => attack self (s.Pirate)) .||>
               (need_docking       => reach_station s.PoliceStation self s))

    let demons_ai (s:PoliceChase) =
      let self = s.Demons
      let evil_and_powered =
        co{
          do! yield_
          return self.Integrity > self.MaxIntegrity * 0.1 && self.Fuel > self.MaxFuel * 0.1
        }
      let need_more_power =
        co{
          do! yield_
          let! p = evil_and_powered
          return not p
        }
      repeat_ ((evil_and_powered => (attack (s.Demons) (s.Pirate))) .||>
               (need_more_power  => reach_station s.DemonPortal self s))

    let pirate_ai (s:PoliceChase) =
      let self = s.Pirate
      let patrol_near =
        co{
          do! yield_
          return Vector2<_>.Distance(self.Position,s.Patrol.Position) < s.Patrol.WeaponsRange
        }
      let patrol_far =
        co{
          let! n = patrol_near
          return not n
        }
      repeat_ ((patrol_near => (attack (s.Pirate) (s.Patrol))) .||>
               (patrol_far  => (attack (s.Pirate) (s.Cargo))))

    let cargo_ai (s:PoliceChase) =
      let self = s.Cargo
      co{
        do! yield_
        do! reach_station s.PoliceStation self s
      } |> repeat_

    let s0() =
      let s =
        {
          PoliceStation =
            {
              Position = { X = field_size; Y = field_size } * 0.25
              Integrity          = 100.0<_>
              MaxIntegrity       = 100.0<_>
            }
          Patrol        =
            {
              Position        = { X = field_size; Y = field_size } * 0.25
              Velocity        = Vector2<_>.Zero
              DryMass         = 4.5e4<_>
              Fuel            = 2.2e6<_>
              MaxFuel         = 2.2e6<_>
              FuelBurn        = 2.2e6<_> / (50.0 * 180.0)
              Thrust          = 5.0e6<_> / 180.0
              Force           = Vector2<_>.Zero
              Integrity       = 100.0<_>
              MaxIntegrity    = 100.0<_>
              Damage          = 1.0e-1<_> / 180.0
              WeaponsRange    = field_size * 0.1
              AI              = co{ return () }
            }
          Pirate        =
            {
              Position        = { X = field_size; Y = field_size } * 0.75
              Velocity        = Vector2<_>.Zero
              DryMass         = 3.0e4<_>
              Fuel            = 2.2e6<_>
              MaxFuel         = 2.2e6<_>
              FuelBurn        = 2.2e6<_> / (30.0 * 180.0)
              Thrust          = 5.0e5<_> / 180.0
              Force           = Vector2<_>.Zero
              Integrity       = 75.0<_>
              MaxIntegrity    = 75.0<_>
              Damage          = 2.0e-1<_> / 180.0
              WeaponsRange    = field_size * 0.15
              AI              = co{ return () }
            }
          Cargo        =
            {
              Position        = { X = field_size; Y = field_size  * 0.7 } * 0.7
              Velocity        = Vector2<_>.Zero
              DryMass         = 2.3e6<_>
              Fuel            = 3.5e8<_> * 0.3
              MaxFuel         = 3.5e8<_>
              FuelBurn        = 3.5e6<_> / 180.0
              Thrust          = 3.4e6<_> / 180.0
              Force           = Vector2<_>.Zero
              Integrity       = 300.0<_>
              MaxIntegrity    = 300.0<_>
              Damage          = 1.0e-3<_> / 180.0
              WeaponsRange    = field_size * 0.1
              AI              = co{ return () }
            }
          DemonPortal =
            {
              Position = { X = field_size * 0.6; Y = field_size } * 0.75
              Integrity          = 100.0<_>
              MaxIntegrity       = 100.0<_>
            }
          Demons      =
            {
              Position        = { X = field_size; Y = field_size * 0.8 } * 0.65
              Velocity        = Vector2<_>.Zero
              DryMass         = 4.5e4<_>
              Fuel            = 2.2e6<_>
              MaxFuel         = 2.2e6<_>
              FuelBurn        = 2.2e6<_> / (50.0 * 180.0)
              Thrust          = 5.0e6<_> / 180.0
              Force           = Vector2<_>.Zero
              Integrity       = 100.0<_>
              MaxIntegrity    = 100.0<_>
              Damage          = 1.0e-1<_> / 180.0
              WeaponsRange    = field_size * 0.2
              AI              = co{ return () }

            }
        }

      do s.Patrol.AI <- patrol_ai s
      do s.Pirate.AI <- pirate_ai s
      do s.Cargo.AI  <- cargo_ai s
      do s.Demons.AI <- demons_ai s
      s

    let co_step =
      function
      | Return x          -> co{ return x }
      | Yield k           -> k
      | ArrowYield k      -> k

    let ship_step (s:Ship) =
        do s.Position <- s.Position + s.Velocity * dt
        do s.Velocity <- s.Velocity + dt * s.Force / s.Mass
        do s.Force    <- Vector2<_>.Zero
        do s.AI       <- co_step (s.AI())

    let simulation_step (s:PoliceChase) =
      do ship_step s.Patrol
      do ship_step s.Pirate
      do ship_step s.Cargo
      do ship_step s.Demons
      if Vector2<_>.Distance(s.Patrol.Position, s.Pirate.Position) < s.Patrol.WeaponsRange then
        do s.Pirate.Integrity <- s.Pirate.Integrity - s.Patrol.Damage * dt
      if Vector2<_>.Distance(s.Cargo.Position, s.Pirate.Position) < s.Cargo.WeaponsRange then
        do s.Pirate.Integrity <- s.Pirate.Integrity - s.Cargo.Damage * dt
      if Vector2<_>.Distance(s.Patrol.Position, s.Pirate.Position) < s.Pirate.WeaponsRange then
        do s.Patrol.Integrity <- s.Patrol.Integrity - s.Pirate.Damage * dt
      elif Vector2<_>.Distance(s.Cargo.Position, s.Pirate.Position) < s.Pirate.WeaponsRange then
        do s.Cargo.Integrity <- s.Cargo.Integrity - s.Pirate.Damage * dt

      if Vector2<_>.Distance(s.Demons.Position, s.Pirate.Position) < s.Demons.WeaponsRange then
        do s.Pirate.Integrity <- s.Pirate.Integrity - s.Demons.Damage * dt
      if Vector2<_>.Distance(s.Demons.Position, s.Cargo.Position) < s.Demons.WeaponsRange then
        do s.Pirate.Integrity <- s.Cargo.Integrity - s.Demons.Damage * dt
      if Vector2<_>.Distance(s.Demons.Position, s.Patrol.Position) < s.Demons.WeaponsRange then
        do s.Patrol.Integrity <- s.Patrol.Integrity - s.Demons.Damage * dt

    let print(s:PoliceChase) =
      do Console.Clear()
      let set_cursor (v:Vector2<_>) =
        Console.SetCursorPosition((((v.X / field_size) * 79.0) |> int) - 1 |> max 0 |> min 79, ((v.Y / field_size) * 23.0) |> int |> max 0 |> min 23)
      let set_cursor_on_ship (s:Ship) = set_cursor (s.Position)
      let set_cursor_on_station (s:Station) = set_cursor (s.Position)
      do set_cursor_on_station (s.PoliceStation)
      do Console.Write("¤")
      do set_cursor_on_station (s.DemonPortal)
      do Console.Write("O")
      do set_cursor_on_ship (s.Patrol)
      let ship_fuel (s:Ship) =
        (9.0 * s.Fuel / s.MaxFuel).ToString("#.")
      let ship_integrity (s:Ship) =
        (9.0 * s.Integrity / s.MaxIntegrity).ToString("#.")
      do Console.Write((ship_fuel s.Patrol) + "∆" + (ship_integrity s.Patrol))
      do set_cursor_on_ship (s.Pirate)
      do Console.Write((ship_fuel s.Pirate) + "†" + (ship_integrity s.Pirate))
      do set_cursor_on_ship (s.Cargo)
      do Console.Write((ship_fuel s.Cargo) + "•" + (ship_integrity s.Cargo))
      do set_cursor_on_ship (s.Demons)
      do Console.Write((ship_fuel s.Demons) + "S" + (ship_integrity s.Demons))
      do Console.SetCursorPosition(0,0)
      do Thread.Sleep(10)

    let simulation() =
      let s = s0()
      let rec simulation() =
        do print s
        if s.Patrol.Integrity > 0.0<_> && s.Pirate.Integrity > 0.0<_> && s.Cargo.Integrity > 0.0<_> then
          do simulation (simulation_step s)
      do simulation()

//    [<EntryPoint>]
//    let main args =
//      do simulation()
//      0
<file_sep>namespace Chapter1
    module BallSimulation =
        open System
        let dt = 0.1
        let g = -9.81

        let simulation_step (y,v) =
            let y',v' = (y+v*dt, v+g*dt)
            if y' < 0.0 then
                (0.0, -v'*0.7)
            else
                (y',v')

        let print_scene (y1,v1,y2,v2) =
            do Console.Clear()
            let y1,v1,y2,v2 = int y1, int v1, int y2, int v2
            for j = 10 downto 0 do
                for i = 0 to 30 do
                    if ((y1+1) = j && i = 10) || ((y2+1) = j && i = 20) then
                        Console.Write("b")
                    elif j = 0 || i = 0 || j = 10 || i = 30 then
                        Console.Write("*")
                    else
                        Console.Write(" ")
                Console.Write("\n")
            ignore(Console.ReadKey())

        let simulation () =
            let rec simulation (y1,v1,y2,v2) =
                do print_scene (y1,v1,y2,v2)
                let y1',v1' = simulation_step (y1,v1)
                let y2',v2' = simulation_step (y2,v2)
                if abs v1' > 0.1 || abs v2' > 0.1 then
                    do simulation (y1',v1',y2',v2')
            do simulation (5.0,-2.0,7.0,-3.0)

    module BallSimulation_extended =
        open System
        let dt = 0.1
        let g = -9.81

        let simulation_step(x,y,dx) =
            let x',y',dx' = (x+dx*dt, y+dx*dt, dx+g*dt)
            if y' < 0.0 then
                (x', 0.0, -dx'*0.7)
            elif x' < 0.0 then
                (0.0, y', -dx'*0.7)
            else
                (x',y',dx')

        let print_scene(x1,y1,x2,y2,x3,y3,x4,y4) =
            do Console.Clear()
            let x1,y1,x2,y2,x3,y3,x4,y4 = int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4
            for j = 30 downto 0 do
                for i = 0 to 30 do
                    if ((y1) = j && (x1) = i) || ((y2) = j && (x2) = i) || ((y3) = j && (x3) = i) || ((y4) = j && (x4) = i) then
                        Console.Write("b")
                    elif j = 0 || i = 0 || j = 30 || i = 30 then
                        Console.Write("*")
                    else
                        Console.Write(" ")
                Console.Write("\n")
            ignore(Console.ReadKey())

        let simulation() =
            let rec simulation(x1,y1,v1, x2,y2,v2, x3,y3,v3, x4,y4,v4) =
                do print_scene(x1,y1,x2,30.0-y2,30.0-x3,y3,30.0-x4,30.0-y4)
                let x1',y1',v1' = simulation_step(x1,y1,v1)
                let x2',y2',v2' = simulation_step(x2,y2,v2)
                let x3',y3',v3' = simulation_step(x3,y3,v3)
                let x4',y4',v4' = simulation_step(x4,y4,v4)
                if abs v1' > 0.1 || abs v2' > 0.1 || abs v3' > 0.1 || abs v4' > 0.1 then
                    do simulation(x1',y1',v1', x2',y2',v2', x3',y3',v3', x4',y4',v4')
            do simulation(15.0,15.0,-0.5, 15.0,15.0,-1.0, 15.0,15.0,-1.5, 15.0,15.0,-2.0)<file_sep># sad_minor_0806963
personal assignments
<file_sep>open System

type option<'a> =
  | Just of 'a
  | None

let ret a = match a with | Just a -> a | None -> 0

type OptionBuilder() =
  member this.Bind(o,f) =
    match o with
    | Just x -> f x
    | None -> None
  member this.Return x = Just x
  member this.Zero = None

let opt = OptionBuilder()

let sum (a:option<'a>) (b:option<'a>) =
  opt{
    let! a_v = a
    let! b_v = b
    return a_v + b_v
  }

let doFunc f a:option<'a> =
  match a with
  | Just x -> Just(f (ret a))
  | None -> None

let add a b =
  b + a

let i = Just 1
let j = doFunc (add 1) i

let x = sum i j

// printf "%A" (ret x)
// Console.ReadKey()

// type list<'a> =
//   | Full of 'a * list<'a>
//   | Empty

type ListBuilder() =
  member this.Bind (o:list<'a>, f:'a->list<'b>) :list<'b> =
    match o:list<'a> with
    | x::xs -> (f x) @ this.Bind (xs,f)
    | [] -> []
  member this.Return x = x
  member this.Zero = []

// let lst = ListBuilder()

// let addToList (a:int) (b:list<'a>) =
//   lst{
//     return a :: b

//   }

type State<'a,'s> = 's -> ('a * 's)

type StateBuilder() =
  member this.Bind (o:State<'a,'s>, f:'a -> State<'b,'s>):State<'b,'s> =
    fun s ->
      let (a,s') = o s
      f a s'
  member this.Return x  = fun (s:'s) -> x,s
  // member this.Zero = (),o

let sb = StateBuilder()

let getState = fun(s:'s) -> s,s
let setState newState = fun(s:'s) -> (),newState

let createState i =
  sb{
    let! x = getState
    do! setState (x + i)
    return x
  }

//----------------------------------------------
type Result<'a> = Done of 'a | Crash of string

type MaybeBuilder() =
  member this.Bind (a:Result<'a>, b: 'a -> Result<'b>) : Result<'b>=
    match a with
      | Done c -> b c
      | Crash e -> Crash e
    // member this.Return a:'a = Done a
    member this.ReturnFrom a:'a = a
    // member this.zero = Crash "haha grapjas"
    member this.zero = ()

let mb = MaybeBuilder()

//----------------------------------------------
type MaybeState<'a,'s> = 's -> Result<'a * 's>
type MaybeStateBuilder() =
  member this.Bind (o:MaybeState<'a,'s>, f:'a -> MaybeState<'b,'s>) : MaybeState<'b,'s> =
    fun (s:'s) ->
      mb{
        let! a,s' = o s
        return! f a s'
      }
  member this.ReturnFrom x  = x
  member this.Return x  = fun s -> Done (x s)
  member this.Zero = Crash

let ms = MaybeStateBuilder()

let getMaybeState = fun(s:'s) -> Done(s,s)
let setMaybeState newState = fun(s:'s) -> s,newState

let createMaybeState(i) =
  ms{
    let! x = getMaybeState
    let y = setMaybeState (x + i)
    return y
  }

//----------------------------------------------
// type MaybeStateList<'a,'s> = 's -> (List<'a>,'s)

//----------------------------------------------
// type ListMaybeState<list<'a,'s>> = list<> ->

[<EntryPoint>]
let main argv =
  // printfn "%A" argv
  // let hal = createState f1
  // let hol = maybeStateTest2 f1 hal 7
  let hel = createState 3
  let hal = createMaybeState 3
  // printfn "%A" (hal)
  printfn "%A" (hel)
  printfn "%A" (hel 8)
  printfn "%A" (hal)
  printfn "%A" (hal 8)
  // printfn "%A" (maybeStateTest2 hal 7)
  // printfn "%A" (maybeStateTest2 hol 8)
  // printfn "%A" (maybeStateTest 9)
  0 // return an integer exit code

languages: Markdown F#


text:
<repo_name>GreenValleySolutions/artWalk-core<file_sep>/Sources/ArtWalkCore/APIModels/Hours.swift

import Foundation

public struct Hour: Codable {
    public let day: Int
    public let open: String
    public let close: String
}
<file_sep>/Sources/ArtWalkCore/APIModels/Location.swift

import Foundation

public struct Location: Codable {
    public let address1: String
    public let address2: String?
    public let city: String
    public let state: String
    public let zipcode: String

    enum CodingKeys: String, CodingKey {
        case address1 = "address_1"
        case address2 = "address_2"
        case city, state, zipcode
    }
}
<file_sep>/Sources/ArtWalkCore/APIModels/User.swift

import Foundation

public enum UserRole: String, Codable, CaseIterable {
    case admin
    case galleryAdmin
    case customer
    case undefined
}

public struct User: Codable {
    public let id: UUID?
    public let first_name: String
    public let last_name: String
    public let email: String
    public let username: String
    public let password: String?
    public let role: UserRole

    public init(
        id: UUID? = nil,
        first_name: String,
        last_name: String,
        email: String,
        username: String,
        password: String? = nil,
        role: UserRole
    ) {
        self.id = id
        self.first_name = first_name
        self.last_name = last_name
        self.email = email
        self.username = username
        self.password = <PASSWORD>
        self.role = role
    }
}
<file_sep>/Sources/ArtWalkCore/APIModels/PaginatedRequestResponse.swift

import Foundation

public protocol PaginatedRequestResponse: Decodable {
    associatedtype Model: Codable
    var items: [Model] { get }
    var metadata: MetaData { get }
}

public struct MetaData: Decodable {
    public let numberOfItemsPerPage: Int
    public let totalQueryableItems: Int
    public let currentPage: Int

    public init(numberOfItemsPerPage: Int, totalQueryableItems: Int, currentPage: Int) {
        self.numberOfItemsPerPage = numberOfItemsPerPage
        self.totalQueryableItems = totalQueryableItems
        self.currentPage = currentPage
    }

    enum CodingKeys: String, CodingKey {
        case numberOfItemsPerPage = "per"
        case totalQueryableItems = "total"
        case currentPage = "page"
    }

    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        numberOfItemsPerPage = try container.decode(Int.self, forKey: .numberOfItemsPerPage)
        totalQueryableItems = try container.decode(Int.self, forKey: .totalQueryableItems)
        currentPage = try container.decode(Int.self, forKey: .currentPage)
    }
}

<file_sep>/Sources/ArtWalkCore/APIModels/Artist.swift

import Foundation

public struct Artist: Codable {
    public let id: UUID?
    public let first_name: String
    public let last_name: String
    public let alias: String?
    public let bio: String?
    public let email: String?
    public let phone_number: String?
    public let studio: Studio?
    public let social_media: [SocialMedia]?

    public init(
        id: UUID? = nil,
        first_name: String,
        last_name: String,
        alias: String? = nil,
        bio: String? = nil,
        email: String? = nil,
        phone_number: String? = nil,
        studio: Studio? = nil,
        social_media: [SocialMedia]? = nil
    ) {
        self.id = id
        self.first_name = first_name
        self.last_name = last_name
        self.alias = alias
        self.bio = bio
        self.email = email
        self.phone_number = phone_number
        self.studio = studio
        self.social_media = social_media
    }
}
<file_sep>/Sources/ArtWalkCore/APIModels/ArtPiece.swift

import Foundation

public struct ArtPiece: Codable {
    public let id: UUID?
    public let title: String
    public let description: String
    public let artistID: UUID
    public let available_for_sale: Bool
    public let price: Double
    public let images: [[String: String]]?
    public let thumbnail: String
    public let ar_models: [ArtPieceARModel]?

    public init(
        id: UUID? = nil,
        title: String,
        description: String,
        artistID: UUID,
        available_for_sale: Bool,
        price: Double,
        images: [[String: String]]? = nil,
        thumbnail: String,
        ar_models: [ArtPieceARModel]? = nil
    ) {
        self.id = id
        self.title = title
        self.description = description
        self.artistID = artistID
        self.available_for_sale = available_for_sale
        self.price = price
        self.images = images
        self.thumbnail = thumbnail
        self.ar_models = ar_models
    }
}

public struct ArtPieceARModel: Codable {
    public let id: String
    public let name: String
    public let description: String
    public let url: String
    public let scene_planes: ARModelPlaneDetectionOptions

    public init(
        id: String,
        name: String,
        description: String,
        url: String,
        planes: ARModelPlaneDetectionOptions
    ) {
        self.id = id
        self.name = name
        self.description = description
        self.url = url
        self.scene_planes = planes
    }
}

public struct ARModelPlaneDetectionOptions: OptionSet, Codable {
    public let rawValue: Int

    public static let horizontal = ARModelPlaneDetectionOptions(rawValue: 1 << 0)
    public static let vertical = ARModelPlaneDetectionOptions(rawValue: 1 << 1)

    public static let all: ARModelPlaneDetectionOptions = [.horizontal, .vertical]

    public init(rawValue: Int) {
        self.rawValue = rawValue
    }
}
<file_sep>/Sources/ArtWalkCore/APIModels/SocialMedia.swift

import Foundation

public struct SocialMedia: Codable {
    public let platform, handle: String
    public let link: String
}
<file_sep>/README.md
# ArtWalkCore

A description of this package.
<file_sep>/Sources/ArtWalkCore/APIModels/StoreInfo.swift

import Foundation

public struct StoreInfo: Codable {
    public var shipping: Bool = false
    public var framing: Bool = false
    public var taxId: String = ""
}
<file_sep>/Tests/LinuxMain.swift
import XCTest

import ArtWalkCoreTests

var tests = [XCTestCaseEntry]()
tests += ArtWalkCoreTests.allTests()
XCTMain(tests)
<file_sep>/Sources/ArtWalkCore/APIModels/Exhibition.swift

import Foundation

public struct Exhibition: Codable {
    public let id: UUID?
    public let name: String
    public let description: String
    public let galleryID: UUID
    public let open_date: Date
    public let close_date: Date

    public init(
        id: UUID? = nil,
        name: String,
        description: String,
        galleryID: UUID,
        open_date: Date,
        close_date: Date
    ) {
        self.id = id
        self.name = name
        self.description = description
        self.galleryID = galleryID
        self.open_date = open_date
        self.close_date = close_date
    }
}
<file_sep>/Sources/ArtWalkCore/APIModels/Theme.swift

import Foundation

public struct Theme: Codable {

    public private(set) var hex: String

    public init(withHexColor hex: String) {
        self.hex = hex
    }
}
<file_sep>/Sources/ArtWalkCore/APIModels/Gallery.swift

import Foundation

public struct Gallery: Codable {
    public let id: UUID?
    public let name: String
    public let about: String
    public let address: Location
    public let phone: String?
    public let website: String?
    public let hours: [Hour]?
    public let theme: Theme
    public let social_media: [SocialMedia]?
    public let store_info: StoreInfo?
    public let has_past_exhibitions: Bool
    public let has_active_exhibition: Bool

    public init(
        id: UUID? = nil,
        name: String,
        about: String,
        address: Location,
        phone: String? = nil,
        website: String? = nil,
        hours: [Hour]? = nil,
        theme: Theme,
        social_media: [SocialMedia]? = nil,
        store_info: StoreInfo? = nil,
        has_past_exhibitions: Bool = false,
        has_active_exhibition: Bool = false
    ) {
        self.id = id
        self.name = name
        self.about = about
        self.address = address
        self.phone = phone
        self.website = website
        self.hours = hours
        self.theme = theme
        self.social_media = social_media
        self.store_info = store_info
        self.has_past_exhibitions = has_past_exhibitions
        self.has_active_exhibition = has_active_exhibition
    }
}
<file_sep>/Sources/ArtWalkCore/APIModels/Studio.swift

import Foundation

public struct Studio: Codable {
    public let name: String
    public let address: Location
    public let website: String?
    public let email: String?
    public let phone_number: String?
}

languages: Swift Markdown

repo_language: Swift

repo_name: GreenValleySolutions/artWalk-core


text:
<repo_name>gabog/ProactiveSample<file_sep>/ProactiveBot/Controllers/NotifyController.cs
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Concurrent;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Integration.AspNet.Core;
using Microsoft.Bot.Schema;
using Microsoft.Extensions.Configuration;

namespace ProactiveBot.Controllers
{
    [Route("api/notify")]
    [ApiController]
    public class NotifyController : ControllerBase
    {
        private readonly IBotFrameworkHttpAdapter _adapter;
        private readonly string _appId;
        private readonly ConcurrentDictionary<string, ConversationReference> _conversationReferencesStore;

        public NotifyController(IBotFrameworkHttpAdapter adapter, IConfiguration configuration, ConcurrentDictionary<string, ConversationReference> conversationReferencesStore)
        {
            _adapter = adapter;
            _conversationReferencesStore = conversationReferencesStore;
            _appId = configuration["MicrosoftAppId"] ?? string.Empty;
        }

        public async Task<IActionResult> Get(string user, string message)
        {
            // Try to get a conversation reference for that user from the conversation reference store.
            _conversationReferencesStore.TryGetValue(user, out var continuationParameters);

            // Sample: this is how you would manually create a conversation reference for ACS to send an SMS to the user:
            // Note that this is only possible for SMS, for the other channels, the user needs to talk to the channel at least
            // once so we can store a conversation reference for that user.
            //var continuationParameters = new ConversationReference
            //{
            //    User = new ChannelAccount(userSmsNumber),
            //    Bot = new ChannelAccount(config.GetSection("acsSmsAdapterSettings")["AcsPhoneNumber"], "bot"),
            //    Conversation = new ConversationAccount(false, null, userSmsNumber),
            //    ChannelId = "ACS_SMS"
            //};

            if (continuationParameters == null)
            {
                // We didn't find a conversation reference to the user.
                return new ContentResult
                {
                    Content = $"
No messages sent

There are no conversations registered to receive proactive messages for {user}.",
                    ContentType = "text/html",
                    StatusCode = (int)HttpStatusCode.OK,
                };
            }

            Exception exception = null;
            try
            {
                // This anonymous function will be called from ContinueConversationAsync
                async Task ContinuationBotCallback(ITurnContext context, CancellationToken cancellationToken)
                {
                    await context.SendActivityAsync($"Got proactive message \"{message}\" for user: {user}", cancellationToken: cancellationToken);
                }

                // Continue the conversation with the proactive message
                await ((BotAdapter)_adapter).ContinueConversationAsync(_appId, continuationParameters, ContinuationBotCallback, default);
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            // Let the caller know a proactive messages have been sent
            return new ContentResult
            {
                Content = $"
Proactive messages have been sent

 Timestamp: {DateTime.Now}
 Exception: {exception}",
                ContentType = "text/html",
                StatusCode = (int)HttpStatusCode.OK,
            };
        }
    }
}<file_sep>/ProactiveBot/Bots/ProactiveBot.cs
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Schema;

namespace ProactiveBot.Bots
{
    public class ProactiveBot : ActivityHandler
    {
        // Message to send to users when the bot receives a Conversation Update event
        private const string WelcomeMessage = "Welcome to the Proactive Bot sample";
        private const string NotifyMessage = "Navigate to {0}api/notify?user={1}&message=Test to proactively message the user.";

        // Dependency injected dictionary for storing ConversationReference objects used in NotifyController to proactively message users
        private readonly ConcurrentDictionary<string, ConversationReference> _conversationReferencesStore;

        private readonly Uri _serverUrl;

        public ProactiveBot(IHttpContextAccessor httpContextAccessor, ConcurrentDictionary<string, ConversationReference> conversationReferencesStore)
        {
            _conversationReferencesStore = conversationReferencesStore;
            _serverUrl = new Uri($"{httpContextAccessor.HttpContext.Request.Scheme}://{httpContextAccessor.HttpContext.Request.Host.Value}");
        }

        protected override Task OnConversationUpdateActivityAsync(ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
        {
            AddConversationReference(turnContext.Activity as Activity);

            return base.OnConversationUpdateActivityAsync(turnContext, cancellationToken);
        }

        protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
        {
            foreach (var member in membersAdded)
            {
                // Greet anyone that was not the target (recipient) of this message.
                if (member.Id != turnContext.Activity.Recipient.Id)
                {
                    // Remember the conversation reference so we can send proactive messages to the user.
                    AddConversationReference(turnContext.Activity as Activity);

                    // Greet the user and render message with continuation link.
                    await turnContext.SendActivityAsync(MessageFactory.Text(WelcomeMessage), cancellationToken);
                    await turnContext.SendActivityAsync(MessageFactory.Text(string.Format(NotifyMessage, _serverUrl, turnContext.Activity.From.Id)), cancellationToken);
                }
            }
        }

        protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            // Echo back what the user said and render message with continuation link.
            await turnContext.SendActivityAsync(MessageFactory.Text($"You sent '{turnContext.Activity.Text}'"), cancellationToken);
            await turnContext.SendActivityAsync(MessageFactory.Text(string.Format(NotifyMessage, _serverUrl, turnContext.Activity.From.Id)), cancellationToken);
        }

        ///
        /// Store the conversation reference for that user so we send a proactive message.
        ///
        private void AddConversationReference(Activity activity)
        {
            var conversationReference = activity.GetConversationReference();
            _conversationReferencesStore.AddOrUpdate(conversationReference.User.Id, conversationReference, (key, newValue) => conversationReference);
        }
    }
}

repo_name: gabog/ProactiveSample


text:
<repo_name>xhrbtk/react-test<file_sep>/redeme.md

## react  https://www.bootcdn.cn/

## 虚拟dom 是一个对象

## jsx 就是用html的方式写js

## 有副作用的函数 如果你在看一个函数 发现了一个东西不知道从哪儿来的 这就是又副作用的函数

## react 的生命周期
- 创建app
- componentWillMount 将要mount app
- render  填充/更新 app 的内容
- componentDidMount mount app 完毕
- componentWillUpdate update app之前
- componentDidUpdate update app 之后
- componentWillunmount app要死了
- componentWillReceiveProps  初始化 render 的时候不执行 在component 接收到新的状态时出发 一般用于父组件状态更新世
自组建的重新渲染
-  shouldcomponentupdate 的作用 允许我们手动的判定是否要进行组件更新 根据组建的应用场景设置函数的合理返回值能够帮我吗避免不必要的更新

-- react 使用clasename插件  https://github.com/JedWatson/classnames
-- css in js https://github.com/MicheleBertoli/css-in-js
--  如果是写ui库 就直接使用原生的 如果是写一个app 商城之类的可以选择使用 css-in-js
-- css-in-js： styled-components：  https://github.com/styled-components/styled-components

-- code sandbox --- https://codesandbox.io/s/dawn-wave-vt28c<file_sep>/使用redux 实现通信.js
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

let createStore = Redux.createStore
let reducers = (state = 0, action) => {
  state = state || {
    money: { amount: 10000 }
  }
  switch (action.type) {
    case '我想花钱':
      return {
        money: {
          amount: state.money.amount - action.payload
        }
      }
    default:
      return state
  }
}
const store = createStore(reducers)

store.subscribe(render)
class App extends React.Component{
  constructor(){
    super()

  }

  render(){
    return (

        hi
        <BigPapa money={this.props.store.money} />
        <YoungPapa money={this.props.store.money} />

    )
  }
}

class BigPapa extends React.Component{
  constructor(){
    super()
  }

  render(){
    return (

        大爸{this.props.money.amount}
        <Son1 money={this.props.money}  />
        <Son2 money={this.props.money}  />

    )
  }
}

class YoungPapa  extends React.Component{

 constructor(){
    super()
  }
  render(){
    return (

        二爸{this.props.money.amount}
        <Son3 money={this.props.money}  />
        <Son4 money={this.props.money}  />

    )
  }
}

class Son1  extends React.Component{
  constructor(){
    super()
  }
  render(){
    return (

儿子1 {this.props.money.amount}

    )
  }
}
class Son2  extends React.Component{
  constructor(){
    super()
  }
  x(){
    store.dispatch({ type: '我想花钱', payload: 100 })
  }

  render(){
    return (

       儿子2 {this.props.money.amount}
       <button onClick={() => this.x()}>消费</button>

    )
  }
}
class Son3  extends React.Component{
 constructor(){
    super()

  }
  render(){
    return (

儿子3{this.props.money.amount}

    )
  }
}
class Son4  extends React.Component{
 constructor(){
    super()

  }
  render(){
    return (

儿子4{this.props.money.amount}

    )
  }
}

function render(){
  ReactDOM.render(<App store={store.getState()}></App>, document.querySelector('#root'))
}
render()<file_sep>/react-demo/my-app/README.md

## index 是用来做入口的  主要逻辑写在app里<file_sep>/demo-react-redux-1/src/App.js

// 使用react 和 redux
// import React, { Component } from 'react'

// class App extends Component {
//   add1(){
//     this.props.onAdd1()
//   }
//   add2(){
//     this.props.onAdd2()
//   }
//   addIf(){
//     this.props.onAddIf()
//   }
//   add1After2sec(){
//     this.props.add1After2sec()
//   }
//   render(){
//     return (
//

//         你点击了{this.props.value}次
//

//           <button id="add1" onClick={this.add1.bind(this)}>+1</button>
//           <button id="add2"  onClick={this.add2.bind(this)}>+2</button>
//           <button id="add1IfOdd"  onClick={this.addIf.bind(this)}>如果是单数就+1</button>
//           <button id="add1After2sec" onClick={this.add1After2sec.bind(this)}>两秒钟后+1</button>
//

//

//     )
//   }
// }

// export default App;

// 使用react 和 react-redux

import React, { Component } from 'react';
import { connect } from "react-redux";

class App extends Component {
  render() {
    return (

        你点击了 {this.props.n} 次

          <button id="add1" onClick={()=> this.props.add1()}>+1</button>
          <button id="add2">+2</button>
          <button id="add1IfOdd">如果是单数就+1</button>
          <button id="add1After2Sec">两秒钟后+1</button>

    );
  }
}

function mapStateToProps(state){
  return {
    n: state.n
  }
}
function mapDispatchToProps(dispatch) {
  return {
    add1: ()=> dispatch({type:'add', payload: 1})
  }
}

export default connect(mapStateToProps,mapDispatchToProps)(App);<file_sep>/使用eventhub 实现通信.js

var money = {
    amount: 10000
  }

  var fnLists = {}
  var eventHub = {
    trigger(eventName, data){
      let fnList = fnLists[eventName]
      if(!fnList) return
      for(let i = 0; i < fnList.length; i++){
        fnList[i](data)
      }
    },
    on(eventName, fn){
      if(!fnLists[eventName]){
        fnLists[eventName] = []
      }
      fnLists[eventName].push(fn)
    }
  }

  var x = {
    init(){
      eventHub.on('我想花钱了', function(data){
        money.amount -= data
        render()
      })
    }
  }
  x.init()
  class App extends React.Component{
    constructor(){
      super()
      this.state = {
        money: money
      }
    }

    render(){
      return (

          hi
          <BigPapa money={this.state.money} />
          <YoungPapa money={this.state.money} />

      )
    }
  }

  class BigPapa extends React.Component{
    constructor(){
      super()
    }

    render(){
      return (

          大爸{this.props.money.amount}
          <Son1 money={this.props.money}  />
          <Son2 money={this.props.money}  />

      )
    }
  }

  class YoungPapa  extends React.Component{

   constructor(){
      super()
    }
    render(){
      return (

          二爸{this.props.money.amount}
          <Son3 money={this.props.money}  />
          <Son4 money={this.props.money}  />

      )
    }
  }

  class Son1  extends React.Component{
    constructor(){
      super()
    }
    render(){
      return (

儿子1 {this.props.money.amount}

      )
    }
  }
  class Son2  extends React.Component{
    constructor(){
      super()
    }
    x(){
      eventHub.trigger('我想花钱了', 100)

    }
    render(){
      return (

         儿子2 {this.props.money.amount}
         <button onClick={() => this.x()}>消费</button>

      )
    }
  }
  class Son3  extends React.Component{
   constructor(){
      super()

      eventHub.on('我花钱了', (data)=>{
         this.setState({
           money: money
         })
      })
    }
    render(){
      return (

儿子3{this.props.money.amount}

      )
    }
  }
  class Son4  extends React.Component{
   constructor(){
      super()

    }
    render(){
      return (

儿子4{this.props.money.amount}

      )
    }
  }

  function render(){
    ReactDOM.render(<App></App>, document.querySelector('#root'))
  }
  render()

languages: Markdown JavaScript

repo_name: xhrbtk/react-test


text:
<file_sep># quizzler-deployment
This repository contains the deployment manifests of the Quizzler Application

The main application code can be found at [ Quizzler ](https://github.com/themmyloluwaa/quizzler).

This deployment repository is monitored by ArgoCD and deployed to the cluster upon changes in the repository.

repo_name: themmyloluwaa/quizzler-deployment


text:
<file_sep>module Pwb
  class Api::V1::CmsPageResource < JSONAPI::Resource
    model_name 'Comfy::Cms::Page'
    # model_hint model: Pwb::Prop, resource: :lite_properties

    attributes :label, :slug, :full_path,
      :blocks, :tags, :categories,
      :locale, :content_cache

    filters :label, :full_path
    has_many :cms_blocks

    def locale
      # return @model.site.locale
      return @model.slug
    end

  end
end

repo_language: Ruby


text:
<repo_name>fabiorafaelsalvioli/jogo-da-velha<file_sep>/README.md
# Jogo da Velha
Jogo da Velha criado em HTML, CSS e Javascript

Projeto para o curso DIO Javascript Game Developer
<file_sep>/script.js
let numberOfPlays = 0;
let player = "X";
let square = document.querySelectorAll(".square");
let status = document.querySelector("#game-status");
let resetGame = document.querySelector("#button-reset");

// Check Winner Function
function checkGame(square, numberOfPlays){

	//Check Lines
	for (let i=0; i<=6; i+=3){
		if (square[i].innerText == square[i+1].innerText &&
		    square[i].innerText == square[i+2].innerText &&
		   (square[i].innerText === "X" || square[i].innerText === "O")){
			alert(`The winner is "${square[i].innerText}"`);
			reset();
			return;
		}

	}
	//Check Columns
	for (let i=0; i<=2; i++){
		if (square[i].innerText == square[i+3].innerText &&
			square[i].innerText == square[i+6].innerText &&
		   (square[i].innerText === "X" || square[i].innerText === "O")){
			alert(`The winner is "${square[i].innerText}"`);
			reset();
			return;
		}

	}
	//Check Diagonal1
	let i = 0;
	if (square[i].innerText == square[i+4].innerText &&
		square[i].innerText == square[i+8].innerText &&
	   (square[i].innerText === "X" || square[i].innerText === "O")){
		alert(`The winner is "${square[i].innerText}"`);
		reset();
		return;
	}

	//Check Diagonal2
	i = 2;
	if (square[i].innerText == square[i+2].innerText &&
		square[i].innerText == square[i+4].innerText &&
	   (square[i].innerText === "X" || square[i].innerText === "O")){
		alert(`The winner is "${square[i].innerText}"`);
		reset();
		return;
	}

	if (numberOfPlays == 9){
		alert(`Draw Game!!`);
		reset();
		return;
	}
};

// Change Player Function
let activePlayer = (currentPlayer) => {
	if (/X/.test(currentPlayer))
		return "O";
	else
		return "X";
};

// Reset Game Function
let reset = ()=>{
	square.forEach(item =>{
		item.innerText = "";
		item.classList.remove("active");
	})
	numberOfPlays = 0;
	player = "X";
	status.innerText = `Player "${player}" turn`;
};

// Event Listener for Squares Click
status.innerText = `Player "${player}" turn`;
square.forEach((item)=>{
 	item.addEventListener("click", ()=>{
 		item.classList.add("active");
     	numberOfPlays += 1;
     	if (item.innerText === ""){
     		item.innerText = player;
     	}
     	player = activePlayer(player);
     	status.innerText = `Player "${player}" turn`;
     	checkGame(square, numberOfPlays);
 	});
});

resetGame.addEventListener("click", reset);

repo_name: fabiorafaelsalvioli/jogo-da-velha


text:
<repo_name>kial917/techtask16<file_sep>/main.html
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Техническое задание №16</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">

Массив из элементов, каждый из элементов которого у с рейтингом 92 и более %, цена (cost) увеличилась в два раза

Массив из элементов, каждый из элементов которого у с рейтингом менее 90 c помощью filter

repo_language: HTML


text:
<file_sep>theme: jekyll-theme-minimal
title: analisaR
description: Análise e visualização de dados no R
logo: "analisaR_logomarca.png"
show_downloads: false
<file_sep>## Sobre a empresa

A analisaR é um empresa recém-criada para a prestação de serviços em análise e visualização de dados socioambientais e de biodiversidade. A empresa tem nome de mulher e a letra R foi acrescentada para indicar que trabalhamos exclusivamente com o R, uma linguagem de código aberto que garante a transparência e a reprodutibilidade nos resultados gerados. A tipografia da nossa logo mistura caracteres que simbolizam o ambiente de trabalho dentro do R. As cores cinza e azul também são as mesmas encontradas na paleta de cores da logomarca do R. A engrenagem significa "análises rodando", uma gíria utilizada na modelagem estatística.

## Serviços oferecidos

- Estruturação de banco de dados

- Gerenciamento de base de dados

- Análises exploratórias

- Análises quantitativas e qualitativas

- Modelagem estatística

- Assessoria, mentoria e treinamento em análise de dados

## Nossos clientes

#### Grupo NSC (FIP Avaliação)

Por meio do Grupo Natureza, Conservação e Sociedade (Grupo NSC), vamos analisar os indicadores de resultados, desempenho e impacto de oito mega projetos no Cerrado que fazem parte do [PIB/FIP (Plano de Investimentos do Brasil para o Fundo de Investimento Florestal)](http://fip.mma.gov.br). Um grande oportunidade para avaliarmos o sucesso das ações de conservação promovidas por essa iniciativa do governo federal e que faz parte de um programa internacional de longo prazo.

Confira a primeira [reunião online](http://fip.mma.gov.br/projetos-do-fundo-de-investimento-florestal-passam-por-avaliacao-de-impactos/?fbclid=IwAR0vfrFKP9KaiYg08k-AHv5AxHh_lixam-xD4G3TCxfTDpviXUojWry8dIs) entre o FIP Avaliação, o FIP Coordenação representado pela [Funatura](https://www.funatura.org.br) e os gestores dos oito projetos do programa. Trabalharemos com nove camadas de análise e mais de dez interações entre modalidades e componentes de avaliação.

## Mídias sociais

[Twitter](https://twitter.com/analisaR_dados)

[Instagram](https://www.instagram.com/analisar_dados)

[Facebook](https://www.facebook.com/analisaR.dadosambientais)

## Contato

A analisaR é um empresa idealizada por [<NAME>](mailto:<EMAIL>), uma mistura de bióloga de campo e de computador com mais de vinte anos de experiência em atividades de pesquisa, ensino e extensão.

Website: [fblpalmeira.github.io](https://fblpalmeira.github.io)

Email: [<EMAIL>](mailto:<EMAIL>)

## Suporte

A manutenção desta página também é feita por [<NAME>](mailto:<EMAIL>).

languages: Markdown YAML