text:
<file_sep>[tox]
envlist = py{27,34,35,36}-django{18,19}

[testenv]
changedir={toxinidir}/codemirror2
usedevelop=True
commands=
    py.test --junitxml=junit.xml --cov-report xml --cov-report html --cov-report term --cov=codemirror2 {posargs}
    - flake8 . --output-file=pep8.txt
passenv=
    DISPLAY
    DJANGO_LIVE_TEST_SERVER_ADDRESS
deps=
    django18: django>=1.8, <1.9
    django19: django>=1.9, <1.10
    -rrequirements.txt

[testenv:devenv]
envdir=devenv
basepython=python3.5
usedevelop=True
setenv=
    PYTHONPATH={toxinidir}/examples
    DJANGO_SETTINGS_MODULE=examples.settings
commands=
    django-admin migrate
    django-admin createsuperuser
deps=
    django<2
    pip-tools
    twine
    wheel
<file_sep>SECRET_KEY = "<PASSWORD>"
STATIC_URL = "/static/"
INSTALLED_APPS = ["codemirror2"]
<file_sep># -*- encoding: utf-8 -*-
from django.contrib import admin
from codemirror2.widgets import CodeMirrorEditor
from testapp.models import TestCss, TestHTML

class TestCssAdmin(admin.ModelAdmin):
    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.attname == "css":
            kwargs['widget'] = CodeMirrorEditor(options={'mode': 'css', 'lineNumbers': True})
        return super(TestCssAdmin, self).formfield_for_dbfield(db_field, **kwargs)

class TestHTMLAdmin(admin.ModelAdmin):
    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.attname == "html":
            kwargs['widget'] = CodeMirrorEditor(options={'mode': 'htmlmixed', 'lineNumbers': True},
                                                modes=['css', 'xml', 'javascript', 'htmlmixed'])
        return super(TestHTMLAdmin, self).formfield_for_dbfield(db_field, **kwargs)

admin.site.register(TestCss, TestCssAdmin)
admin.site.register(TestHTML, TestHTMLAdmin)
<file_sep>Django widgets for replacing textareas with CodeMirror, an in-browser code editor.
Tested on Django 1.6+, support Python 2.7 and Python 3.4+.

.. image:: https://travis-ci.org/sk1p/django-codemirror2.svg?branch=master
    :target: https://travis-ci.org/sk1p/django-codemirror2

Installing
==========

1. run ``pip install django-codemirror2``
2. Add ``codemirror2`` to INSTALLED_APPS
3. Collect static files: ``python manage.py collectstatic``

To use django-codemirror2 directly from git, you need to initialize
the Codemirror submodule by running ``git submodule init && git submodule update``.

Usage
=====

::

    from django import forms
    from codemirror2.widgets import CodeMirrorEditor

    class TestForm(forms.Form):
        css = forms.Charfield(widget=CodeMirrorEditor(options={'mode': 'css'}))

The ``options`` argument will be passed as JSON to ``CodeMirror.fromTextArea``, see
http://codemirror.net/manual.html#config for possible values. Do not pass user-controlled
data as options, as this can lead to an XSS vulnerability.

If you want to use a mode that depends on other modes, for example ``htmlmixed``, you
need to load the dependencies, too, by passing the ``modes`` parameter:

::

    html = forms.Charfield(widget=CodeMirrorEditor(modes=['css', 'xml', 'javascript', 'htmlmixed'],
                options={'mode': 'htmlmixed'}))

If you want to customize the Javascript used to initialize the CodeMirror editor, use ``script_template``::

    foo = forms.Charfield(widget=CodeMirrorEditor(options={'mode': 'xml'},
                script_template='some/template.html'))

You can base your script template on the included template ``codemirror_script.html``.

Example app
===========

There is a simple example app included. To run it:

1. run ``tox -e devenv``
2. run ``./run_example_server.sh``
3. visit http://localhost:8000/admin/testapp/ in your browser.
<file_sep>from itertools import chain
from django.contrib.staticfiles.finders import find
import pytest
from codemirror2.widgets import CodeMirrorEditor

@pytest.fixture
def w():
    """
    construct a CodeMirrorEditor widget with default settings
    """
    return CodeMirrorEditor()

def test_dont_share_options(settings):
    settings.CODEMIRROR_DEFAULT_OPTIONS = {"default": "option"}
    w1 = CodeMirrorEditor(options={"w1": "opt1"})
    w2 = CodeMirrorEditor(options={"w2": "opt2"})

    assert w1.options != w2.options
    assert w1.options == {"w1": "opt1", "default": "option"}
    assert w2.options == {"w2": "opt2", "default": "option"}

def test_mode_populated_from_options():
    w = CodeMirrorEditor(options={"mode": "python"})
    assert w.modes == ["python"]

def test_mode_populated_w_modelist(w):
    assert len(w.modes) == 16

def test_pass_modes():
    modes = ["python", "css", "xml", "javascript", "htmlmixed"]
    w = CodeMirrorEditor(options={"mode": "python"},
                         modes=modes)
    assert w.modes == modes
    assert w.options == {"mode": "python"}

def test_default_theme(w):
    assert w.themes == ["default"]

def test_themes_populated_from_options():
    w = CodeMirrorEditor(options={"theme": "dark"})
    assert w.themes == ["dark"]

def test_themes_populated_from_args():
    themes = ["light", "dark", "default"]
    w = CodeMirrorEditor(themes=themes)
    assert w.themes == themes

def test_render_widget(w):
    html = w.render("code", "")
    assert 'name="code"' in html
    assert 'document.getElementById("id_code")' in html

def test_media_w_mode():
    w = CodeMirrorEditor(options={"mode": "python"})
    js, css = w.media._js, w.media._css
    assert js == [
        "codemirror2/lib/codemirror.js",
        "codemirror2/addon/mode/overlay.js",
        "codemirror2/mode/python/python.js",
    ]
    assert css == {
        "screen": [
            "codemirror2/lib/codemirror.css"
        ]
    }
    for f in chain(js, css["screen"]):
        assert find(f)

def test_mode_extra_css():
    w = CodeMirrorEditor(options={"mode": "tiki"})
    js, css = w.media._js, w.media._css
    assert "codemirror2/mode/tiki/tiki.css" in css["screen"]
    for f in chain(js, css["screen"]):
        assert find(f)

def test_staticfiles_exist():
    """
    in default configuration (with "all" modes), the static files should exist
    """
    w = CodeMirrorEditor()
    js, css = w.media._js, w.media._css
    for f in chain(js, css["screen"]):
        assert find(f)
<file_sep>#!/bin/bash
. devenv/bin/activate
examples_path="$(pwd)/examples"
export PYTHONPATH=$examples_path
export DJANGO_SETTINGS_MODULE=examples.settings
django-admin migrate
django-admin runserver "$@"
<file_sep>from setuptools import setup

setup(
    name="django-codemirror2",
    version="0.2.1.dev1",
    author_email="<EMAIL>",
    author="<NAME>",
    url="https://github.com/sk1p/django-codemirror2",
    description="Django widgets for replacing textareas with CodeMirror2,"
                " an in-browser code editor",
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Framework :: Django :: 1.8',
        'Framework :: Django :: 1.9',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: JavaScript',
        'Topic :: Text Editors',
    ],
    include_package_data=True,
    packages=[
        "codemirror2",
        "codemirror2.tests",
    ],
)
<file_sep># -*- encoding: utf-8 -*-
from django.forms import widgets
from django.conf import settings
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
import json
import copy
from django.contrib.admin import widgets as admin_widgets

class CodeMirrorEditor(widgets.Textarea):
    def __init__(self, modes=None, themes=None, options=None,
                 script_template="codemirror2/codemirror_script.html", *args, **kwargs):
        """
        options: will be json-encoded and passed to ``CodeMirror.fromTextArea``

        modes: list of mode files to load, example: ["xml", "css", "python"].

        themes: list of themes to load, example: ["default", "neat", "elegant", "night"]
        """
        super(CodeMirrorEditor, self).__init__(*args, **kwargs)
        def_options = copy.deepcopy(getattr(settings, "CODEMIRROR_DEFAULT_OPTIONS", {}))
        if options is not None:
            def_options.update(options)
        self.options = def_options
        if modes is None:
            if 'mode' in self.options:
                modes = [self.options['mode']]
            else:
                modes = ["clike", "diff", "htmlmixed", "lua", "sql", "rst", "smalltalk", "xml",
                        "css", "haskell", "javascript", "php", "python", "scheme", "stex", "yaml"]
        self.modes = modes
        if themes is None:
            if 'theme' in self.options:
                themes = [self.options['theme']]
            else:
                themes = ["default"]
        self.themes = themes
        self.script_template = script_template

    def render(self, name, value, attrs=None, **kwargs):
        rendered = super(CodeMirrorEditor, self).render(name, value, attrs, **kwargs)
        context = {
            'name': name,
            'options': json.dumps(self.options),
        }
        return rendered + mark_safe(
            render_to_string(self.script_template, context)
        )

    @property
    def media(self):
        js_files = ["codemirror2/lib/codemirror.js"]
        js_files += ["codemirror2/addon/mode/overlay.js"]
        js_files += [("codemirror2/mode/%s/%s.js" % (mode, mode)) for mode in self.modes]
        css_files = ["codemirror2/lib/codemirror.css"]
        css_files += [("codemirror2/theme/%s.css" % theme) for theme in self.themes
                      if theme != "default"]  # default theme is included in codemirror.css
        # some modes have extra css files, too:
        # TODO: autodetect
        need_css = ["tiki", "tiddlywiki"]
        for mode in need_css:
            if mode in self.modes:
                css_files.append("codemirror2/mode/%s/%s.css" % (mode, mode))
        return widgets.Media(js=js_files, css={'screen': css_files})

class AdminCodeMirrorEditor(CodeMirrorEditor, admin_widgets.AdminTextareaWidget):
    pass
<file_sep>from django.db import models
from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class TestCss(models.Model):
    title = models.CharField(max_length=255)
    css = models.TextField()

    def __str__(self):
        return self.title

@python_2_unicode_compatible
class TestHTML(models.Model):
    title = models.CharField(max_length=255)
    html = models.TextField()

    def __str__(self):
        return self.title

languages: reStructuredText Shell INI Python

repo_language: reStructuredText


text:
<repo_name>FernandoRidam/teste_tdsa<file_sep>/src/components/AppBar/index.js
import React, {
  useState,
} from 'react';

import {
  AppBar,
  Toolbar,
  Typography,
  FormGroup,
  FormControlLabel,
  Switch,
} from '@material-ui/core';

import { useTranslation } from 'react-i18next';

import styles from '../../styles';

export function ApplicationBar({ title }) {
  const { t, i18n } = useTranslation();

  const stylesClass = styles();

  const [ translate, setTranslate ] = useState( false );

  function changeLang( value ) {
    setTranslate( value );

    i18n.changeLanguage( value ? 'en' : 'pt');
  };

  return (
    <AppBar position="absolute" className={ stylesClass.appBar }>
      <Toolbar className={ stylesClass.toolbar }>
        <Typography variant="h6">{ title }</Typography>

        <FormGroup row className={ stylesClass.checks }>
          <Typography variant="body1">{ t('header.langLabel')}</Typography>
          <FormControlLabel
            control={
              <Switch checked={ translate } onChange={ event => changeLang( event.target.checked )}/>
            }
            label={ t('header.lang')}
          />
        </FormGroup>
      </Toolbar>
    </AppBar>
  );
};
<file_sep>/src/pages/Main/index.js
import React, {
  useState,
  useEffect,
  useCallback,
} from 'react';

import {
  Container,
  Paper,
  Grid,
  Select,
  MenuItem,
  Typography,
  Snackbar,
  LinearProgress,
  TextField,
  Zoom ,
  IconButton,
  InputAdornment,
} from '@material-ui/core';

import {
  Close,
} from '@material-ui/icons';

import { useTranslation } from 'react-i18next';

import {
  ApplicationBar,
  ModalPost,
  TableListPost,
} from '../../components';

import {
  useStore,
} from '../../store';

import styles from '../../styles';

export function Main() {
  const stylesClass = styles();

  const { t, i18n } = useTranslation();
  const { alert, users, posts } = useStore();

  const [ openModal, setOpenModal ] = useState( false );

  const [ selectedUser, setSelectedUser ] = useState( 0 );

  const [ search, setSearch ] = useState('');

  const getUsers = useCallback( async () => {
    const { success } = await users.getUsers();

    if (!success) {
      alert.showAlert('error', t('alerts.failureGetUsers'));
    }
  }, [ users ]);

  const getPosts = useCallback( async () => {
    if( selectedUser !== 0 ) {
      const { success } = await posts.getPostsByUser( selectedUser );

      if (!success) {
        alert.showAlert('error', t('alerts.failureGetPosts'));
      }
    } else {
      const { success } = await posts.getPosts();

      if (!success) {
        alert.showAlert('error', t('alerts.failureGetPosts'));
      }
    }
  }, [ posts, selectedUser ]);

  useEffect(() => {
    getPosts();
  }, [ selectedUser ]);

  useEffect(() => {
    getUsers();
  }, []);

  return (
    <>
      <ApplicationBar title={ t('header.title')} />

      <Container className={ stylesClass.container }>
        <Grid container spacing={ 3 }>
          <Grid item xs={ 12 } md={ 4 } lg={ 4 }>
            <Paper className={ stylesClass.paper }>
              <Typography variant="body1" className={ stylesClass.paperTitle }>{ t('body.quickSearch')}</Typography>

              <TextField
                placeholder={ t('body.labelSearch')}
                className={ stylesClass.textField }
                variant="outlined"
                color="primary"
                value={ search }
                onChange={ event => setSearch( event.target.value )}
                InputProps={{
                  endAdornment:
                    <InputAdornment position="end">
                      <Zoom in={ search !== ''} >
                        <IconButton edge="end" color="primary" onClick={() => setSearch('')}>
                          <Close />
                        </IconButton>
                      </Zoom >
                    </InputAdornment>,
                }}
              />
            </Paper>
          </Grid>

          <Grid item xs={ 12 } md={ 4 } lg={ 4 }>
            <Paper className={ stylesClass.paper }>
              <Typography variant="body1" className={ stylesClass.paperTitle }>{ t('body.user')}</Typography>

              <Select
                className={ stylesClass.select }
                variant="outlined"
                color="primary"
                value={ selectedUser }
                onChange={ event => setSelectedUser( event.target.value )}
              >
                <MenuItem value={ 0 }>
                  {
                    users?.loading
                      ? <>
                          Carregando...

                          <LinearProgress className={ stylesClass.linearProgress }/>
                        </>
                      : t('body.all')
                  }
                </MenuItem>
                {
                  users?.data.length > 0 && users?.data.map( user => <MenuItem key={ user.id } value={ user.id }>{ user.name }</MenuItem>)
                }
              </Select>
            </Paper>
          </Grid>

          <Grid item xs={12}>
            <Paper className={ stylesClass.paper }>
              <TableListPost
                title={ t('tablePosts.titleTable')}
                search={ search.toLowerCase()}
                openModalPost={() => setOpenModal( true )}
              />
            </Paper>
          </Grid>
        </Grid>
      </Container>

      <ModalPost open={ openModal } close={() => setOpenModal( false )} />
    </>
  );
};
<file_sep>/src/components/LoadingButton/index.js
import React from 'react';

import {
  Button,
  LinearProgress,
} from '@material-ui/core';

import styles from '../../styles';

export function LoadingButton({ children, loading, ...props }) {
  const stylesClass = styles();

  return (
    <Button
      data-testid="loading-button"
      {...props }
    >
      { children }

      { loading && <LinearProgress className={ stylesClass.linearProgress} />}
    </Button>
  );
};
<file_sep>/src/store/index.js
import React, { createContext, useContext } from 'react';

import {
  useAlert,
  useUser,
  usePost,
  useComment,
} from './hooks';

export const store = createContext({
  alert: {
    showAlert: ( type, message ) => {},
    closeAlert: () => {},
  },

  users: {
    loading: false,
    data: [],
    getUsers: () => ({ success: true, data: []}),
  },

  posts: {
    loading: false,
    saving: false,
    data: [],
    post: {},
    savePost: () => ({ success: true, data: []}),
    updatePost: () => ({ success: true, data: []}),
    getPosts: () => ({ success: true, data: []}),
    getPostsByUser: () => ({ success: true, data: []}),
    selectPost: () => {},
  },

  comments: {
    loading: false,
    saving: false,
    data: [],
    saveComment: () => ({ success: true, data: []}),
    getCommentsByPost: () => ({ success: true, data: []}),
  },
});

const { Provider } = store;

export const useStore = () => useContext( store );

export function StateProvider({ children }) {
  const alert = useAlert();
  const users = useUser();
  const posts = usePost();
  const comments = useComment();

  return (
    <Provider
      value={{
        alert,
        users,
        posts,
        comments,
      }}
    >
      { children }
    </Provider>
  );
};
<file_sep>/src/components/RowComment/index.js
import React, {
  useState,
} from 'react';

import {
  TableRow,
  TableCell,
  IconButton,
  Collapse,
  Box,
  Container,
  Typography,
} from '@material-ui/core';

import {
  KeyboardArrowUp,
  KeyboardArrowDown,
} from '@material-ui/icons';

import { useTranslation } from 'react-i18next';

import styles from '../../styles';

export function RowComment({ comment }) {
  const { t, i18n } = useTranslation();
  const stylesClass = styles();

  const [ open, setOpen ] = useState( false );

  return (
    <>
      <TableRow className={ stylesClass.row }>
        <TableCell className={ stylesClass.tableNameColumn }>
          <Typography variant="body1">{ comment?.name }</Typography>
        </TableCell>

        <TableCell className={ stylesClass.tableEmailColumn }>
          <Typography variant="body1">{ comment?.email }</Typography>
        </TableCell>

        <TableCell className={ stylesClass.tableCollapseColumn } align="right">
          <IconButton aria-label="expand row" size="small" onClick={() => setOpen(!open)}>
            {open ? <KeyboardArrowUp /> : <KeyboardArrowDown />}
          </IconButton>
        </TableCell>
      </TableRow>

      <TableRow className={ stylesClass.collapseRow }>
        <TableCell colSpan={ 3 } className={ !open ? stylesClass.closedCollapse : {}}>
          <Collapse in={ open } timeout="auto" unmountOnExit>
            <Box className={ stylesClass.box }>
              <Typography variant="h6">{ t('modal.subTitleComment')}</Typography>

              <Container className={ stylesClass.messageView }>
                <Typography variant="body2">{ comment?.body }</Typography>
              </Container>
            </Box>
          </Collapse>
        </TableCell>
      </TableRow>
    </>
  );
};
<file_sep>/src/components/index.js
export * from './Alert';
export * from './AppBar';
export * from './TableListPost';
export * from './ModalPost';
export * from './HelperText';
export * from './LoadingButton';
<file_sep>/src/components/Alert/index.js
import React from 'react';

import {
  Snackbar,
} from '@material-ui/core';

import MuiAlert from '@material-ui/lab/Alert';

import {
  useStore,
} from '../../store';

import styles from '../../styles';

function AlertMui(props) {
  return <MuiAlert elevation={ 6 } variant="filled" {...props} />;
}

export function Alert() {
  const stylesClass = styles();

  const { alert } = useStore();

  return (
    <Snackbar className={ stylesClass.snackbar } anchorOrigin={{ horizontal: 'right', vertical: 'top'}} open={ alert.open } autoHideDuration={ 6000 } onClose={ alert.closeAlert }>
      <AlertMui onClose={ alert.closeAlert } severity={ alert.type }>{ alert.message }</AlertMui>
    </Snackbar>
  );
};
<file_sep>/src/index.js
import React, { Suspense } from 'react';
import ReactDOM from 'react-dom';

import CssBaseline from '@material-ui/core/CssBaseline';
import {
  ThemeProvider,
} from '@material-ui/core/styles';

import App from './App';

import theme from './theme';

import './styles.css';

import './config/i18n';

ReactDOM.render(
  <Suspense fallback="Loading...">
    <ThemeProvider theme={ theme }>
      <CssBaseline />
      <App />
    </ThemeProvider>
  </Suspense>
, document.getElementById('root'));
<file_sep>/src/components/LoadingButton/loading_button.test.js
import React from 'react';

import { render } from '@testing-library/react';

import {
  LoadingButton
} from './index';

test('Should add row the table de posts in document', () => {
  const { getByTestId } = render(
    <LoadingButton
      variant="contained"
      loading={ false }
    >
      Teste
    </LoadingButton>
  );

  expect( getByTestId('loading-button')).toBeInTheDocument();
});
<file_sep>/src/routes.js
import React from 'react';

import {
  BrowserRouter,
  Switch,
  Route,
} from 'react-router-dom';

import {
  Main,
} from './pages';

export default function Routes() {
  return (
    <BrowserRouter>
      <Switch>
        <Route path="/" exact component={ Main } />
      </Switch>
    </BrowserRouter>
  );
};
<file_sep>/src/store/hooks/alert.js
import { useState, useCallback, useMemo } from 'react';

export function useAlert() {
  const [ open, setOpen ] = useState( false );
  const [ type, setType ] = useState('');
  const [ message, setMessage ] = useState('');

  const showAlert = useCallback(( type, message ) => {
    setType( type );
    setMessage( message );

    setOpen( true );
  }, []);

  const closeAlert = useCallback(() => {
    setOpen( false );

    setType('');
    setMessage('');
  }, []);

  return useMemo(() => {
    return {
      open,
      type,
      message,
      showAlert,
      closeAlert,
    }
  }, [
    open,
    type,
    message,
    showAlert,
    closeAlert,
  ]);
};
<file_sep>/src/components/RowPost/index.js
import React, {
  useState,
} from 'react';

import {
  TableRow,
  TableCell,
  IconButton,
  Collapse,
  Box,
  Container,
  Typography,
} from '@material-ui/core';

import {
  Edit,
  Delete,
  KeyboardArrowUp,
  KeyboardArrowDown,
} from '@material-ui/icons';

import { useTranslation } from 'react-i18next';

import {
  useStore,
} from '../../store';

import styles from '../../styles';

export function RowPost({ post, openModalPost }) {
  const { t, i18n } = useTranslation();

  const stylesClass = styles();

  const { users, posts } = useStore();

  const [ open, setOpen ] = useState( false );

  function getUserName() {
    return users?.data.find( user => post.userId === user.id )?.name;
  };

  function handleEditPost() {
    posts.selectPost( post );

    openModalPost();
  };

  return (
    <>
      <TableRow className={ stylesClass.row }>
        <TableCell className={ stylesClass.tableIdColumn }>
          <Typography variant="body1">{ post?.id }</Typography>
        </TableCell>

        <TableCell className={ stylesClass.tableTitleColumn }>
          <Typography variant="body1">{ post?.title }</Typography>
        </TableCell>

        <TableCell className={ stylesClass.tableUserColumn }>
          <Typography variant="body1">{ getUserName()}</Typography>
        </TableCell>

        <TableCell className={ stylesClass.tableActionsColumn } align="center">
          <IconButton
            className={ stylesClass.icon }
            color="primary"
            onClick={ handleEditPost }
          >
            <Edit />
          </IconButton>

          <IconButton className={ stylesClass.iconDelete } onClick={() => {}}>
            <Delete />
          </IconButton>
        </TableCell>

        <TableCell className={ stylesClass.tableCollapseColumn } align="right">
          <IconButton aria-label="expand row" size="small" onClick={() => setOpen(!open)}>
            {open ? <KeyboardArrowUp /> : <KeyboardArrowDown />}
          </IconButton>
        </TableCell>
      </TableRow>

      <TableRow className={ stylesClass.collapseRow }>
        <TableCell colSpan={ 5 } className={ !open ? stylesClass.closedCollapse : {}}>
          <Collapse in={open} timeout="auto" unmountOnExit>
            <Box className={ stylesClass.box }>
              <Typography variant="h6">{ t('tablePosts.columnMessage')}</Typography>

              <Container className={ stylesClass.messageView }>
                <Typography variant="body2">{ post.body }</Typography>
              </Container>
            </Box>
          </Collapse>
        </TableCell>
      </TableRow>
    </>
  );
};
<file_sep>/src/components/ModalPost/index.js
import React, {
  useState,
  useEffect,
} from 'react';

import {
  Modal,
  Toolbar,
  Paper,
  Typography,
  Container,
  Button,
  FormControl,
  InputLabel,
  TextField,
  Select,
  MenuItem,
  Divider,
  LinearProgress,
} from '@material-ui/core';

import {
  useForm,
  Controller,
} from "react-hook-form";

import { useTranslation } from 'react-i18next';

import {
  FormComment,
} from '../FormComment';

import {
  HelperText,
} from '../HelperText';

import {
  useStore,
} from '../../store';

import styles from '../../styles';
import { LoadingButton } from '../LoadingButton';

export function ModalPost({ open, close }) {
  const { t, i18n } = useTranslation();
  const stylesClass = styles();

  const { register, handleSubmit, getValues, setValue, control, errors, formState, } = useForm();

  const { isDirty } = formState;

  const { users, posts, alert } = useStore();

  const [ post, setPost ] = useState( null );
  const [ stayOpen, setStayOpen ] = useState( null );

  const onSubmit = async ( data ) => {
    if( !post ) {
      const { success, data: postData } = await posts.savePost( JSON.stringify( data ));

      setPost( postData.id );

      const type = success ? 'success' : 'error';
      const message = success ? t('alerts.successNewPost') : t('alerts.failureNewPost');

      alert.showAlert( type, message );
    } else {
      const { success } = await posts.updatePost( post.id, JSON.stringify( data ));

      const type = success ? 'success' : 'error';
      const message = success ? t('alerts.successEditPost') : t('alerts.failureEditPost');

      alert.showAlert( type, message );
    }

    if( !stayOpen ) {
      close();
    } else {
      setValue('title', '');
      setValue('body', '');
      setValue('userId', 1 );
    }
  };

  useEffect(() => {
    if( posts?.post?.id ) {
      setPost( posts.post );
    }
  }, [ posts?.post ]);

  useEffect(() => {
    if( post?.id ) {
      setValue('title', post?.title, { shouldValidate: true });
      setValue('body', post?.body, { shouldValidate: true });
      setValue('userId', post?.userId, { shouldValidate: true });
    }
  }, [ post ]);

  return (
    <Modal
      open={ open }
      onClose={ close }
      className={ stylesClass.modal }
    >
      <Paper className={ stylesClass.modalView }>
        <Toolbar className={ stylesClass.modalToolbar }>
          <Typography className={ stylesClass.modalTitle } variant="h6" id="usuarios">
            {
              post
                ? t('modal.titleEdit')
                : t('modal.titleNew')
            }
          </Typography>
        </Toolbar>

        <Container className={ stylesClass.bodyModal }>
          <form
            className={ stylesClass.form }
            onSubmit={ handleSubmit( onSubmit )}
          >
            <Typography variant="h6">{ t('modal.subTitlePost')}</Typography>

            <TextField
              label={ t('tablePosts.columnTitle')}
              variant="outlined"
              inputRef={ register({ required: true })}
              color="primary"
              name="title"
              className={ stylesClass.textField }
              helperText={ errors.title?.type === 'required' && <HelperText name={ t('tablePosts.columnTitle')} />}
              error={ !!errors.title }
            />

            <TextField
              label={ t('tablePosts.columnMessage')}
              variant="outlined"
              multiline
              rows={ 3 }
              rowsMax={ 3 }
              inputRef={ register({ required: true })}
              color="primary"
              name="body"
              className={ stylesClass.textField }
              helperText={ errors.body?.type === 'required' && <HelperText name={ t('tablePosts.columnMessage')} />}
              error={ !!errors.body }
            />

            <FormControl
              className={ stylesClass.select }
              name="userId"
              variant="outlined"
            >
              <InputLabel htmlFor="user-select" id="user-select-label">{ t('tablePosts.columnUser')}</InputLabel>
              <Controller
                as={
                  <Select
                    id="user-select"
                    labelId="user-select-label"
                    name="userId"
                  >
                    {
                      users?.data.map( user => <MenuItem key={ user.id } value={ user.id }>{ user.name }</MenuItem>)
                    }
                  </Select>
                }
                name="userId"
                control={ control }
                defaultValue={ 1 }
              />
            </FormControl>

            <Container className={ stylesClass.actions }>
              <LoadingButton
                variant="contained"
                color="primary"
                type="submit"
                onClick={() => setStayOpen( true )}
                className={ stylesClass.action }
                disabled={ posts.saving || ( post && !isDirty )}
                loading={ posts.saving }
              >
                { t('buttons.saveAndContinue')}
              </LoadingButton>

              <LoadingButton
                variant="contained"
                color="primary"
                type="submit"
                onClick={() => setStayOpen( false )}
                className={ stylesClass.action }
                disabled={ posts.saving || ( post && !isDirty )}
                loading={ posts.saving }
              >
                { t('buttons.save')}
              </LoadingButton>

              <Button
                variant="outlined"
                color="primary"
                className={ stylesClass.action }
                onClick={ close }
              >
                { t('buttons.exit')}
              </Button>
            </Container>
          </form>

          <Divider
            className={ stylesClass.divider }
            orientation="vertical"
            flexItem
          />

          <FormComment
            postValues={() => getValues()}
          />
        </Container>
      </Paper>
    </Modal>
  );
};
<file_sep>/src/components/FormComment/index.js
import React, { useEffect } from 'react';

import {
  Typography,
  TextField,
  Container,
  Button,
  LinearProgress,
} from '@material-ui/core';

import {
  useForm,
} from "react-hook-form";

import { useTranslation } from 'react-i18next';

import {
  useStore,
} from '../../store';

import {
  TableListComment,
} from '../TableListComment';

import {
  HelperText,
} from '../HelperText';

import styles from '../../styles';
import { LoadingButton } from '../LoadingButton';

export function FormComment({ postValues, postIsValid }) {
  const { t, i18n } = useTranslation();
  const stylesClass = styles();

  const {
    posts,
    comments,
    alert,
  } = useStore();

  const { register, handleSubmit, setValue, control, errors } = useForm();

  const onSubmit = async ( newComment ) => {
    let successPost = true;

    if( !posts.post?.id ) {
      const { success, data } = await posts.savePost( JSON.stringify( postValues()));

      successPost = success;

      const type = successPost ? 'success' : 'error';
      const message = successPost ? t('alerts.successNewPost') : t('alerts.failureNewPost');

      alert.showAlert( type, message );

      if( successPost ) {
        posts.selectPost( data );
      }
    }

    if( successPost ) {
      const { success } = await comments.saveComment( JSON.stringify({ ...newComment, post: posts.post?.id }));

      const type = success ? 'success' : 'error';
      const message = success ? t('alerts.successNewComment') : t('alerts.failureNewComment');

      alert.showAlert( type, message );
    }

    setValue('name', '');
    setValue('email', '');
    setValue('body', '');
  };

  useEffect(() => {
    if( posts.post?.id )
      comments.getCommentsByPost( posts.post?.id );
  }, [ posts.post ]);

  return (
    <Container className={ stylesClass.form }>
      <form
        onSubmit={ handleSubmit( onSubmit )}
      >
        <Typography variant="h6">{ t('modal.subTitleComment')}</Typography>

        <TextField
          label={ t('fields.fieldName')}
          variant="outlined"
          inputRef={ register({ required: true })}
          color="primary"
          name="name"
          className={ stylesClass.textField }
          helperText={ errors.name?.type === 'required' && <HelperText name={ t('fields.fieldName')} />}
          error={ !!errors.name }
        />

        <TextField
          label={ t('fields.fieldEmail')}
          variant="outlined"
          inputRef={ register({ required: true })}
          color="primary"
          name="email"
          type="email"
          className={ stylesClass.textField }
          helperText={ errors.email?.type === 'required' && <HelperText name={ t('fields.fieldEmail')} />}
          error={ !!errors.email }
        />

        <TextField
          label={ t('fields.fieldComment')}
          variant="outlined"
          multiline
          rows={ 3 }
          rowsMax={ 3 }
          inputRef={ register({ required: true })}
          color="primary"
          name="body"
          className={ stylesClass.textField }
          helperText={ errors.body?.type === 'required' && <HelperText name={ t('fields.fieldComment')} />}
          error={ !!errors.body }
        />

        <Container className={ stylesClass.actionsComment }>
          <LoadingButton
            variant="contained"
            color="primary"
            type="submit"
            disabled={ comments.saving || postIsValid }
            loading={ comments.saving }
          >
            { t('buttons.save')}
          </LoadingButton>
        </Container>
      </form>

      <TableListComment
        title={ t('modal.subTitleComments')}
        comments={ comments?.data }
      />
    </Container>
  );
};
<file_sep>/src/components/TableListComment/index.js
import React, {
  useState,
  useEffect,
} from 'react';

import {
  Typography,
  Table,
  TableHead,
  TableRow,
  TableBody,
  TableCell,
  Container,
  CircularProgress,
  Button,
} from '@material-ui/core';

import { useTranslation } from 'react-i18next';

import {
  RowComment,
} from '../RowComment';

import styles from '../../styles';

export function TableListComment({ title, comments }) {
  const { t, i18n } = useTranslation();
  const stylesClass = styles();

  return (
    <Container className={ stylesClass.comments }>
      <Typography variant="h6">{ title }</Typography>

      <Container className={ stylesClass.tableCommentsView }>
        <Table size="small" className={ stylesClass.table }>
          <TableHead>
            <TableRow>
              <TableCell className={ stylesClass.tableNameColumn }>{ t('fields.fieldName')}</TableCell>
              <TableCell className={ stylesClass.tableEmailColumn }>{ t(('fields.fieldEmail'))}</TableCell>
              <TableCell className={ stylesClass.tableCollapseColumn } />
            </TableRow>
          </TableHead>

          <TableBody>
            {
              comments?.length > 0
                ? comments.map( comment => <RowComment key={ comment?.id } comment={ comment }/>)
                : <TableRow>
                    <TableCell colSpan={ 5 } align="center">
                      <Typography variant="subtitle1">{ t('modal.emptyData')}</Typography>
                    </TableCell>
                  </TableRow>
            }
          </TableBody>
        </Table>
      </Container>
    </Container>
  );
};
<file_sep>/src/services/api.js
const API_URL = 'https://jsonplaceholder.typicode.com';
const GET = 'GET';
const POST = 'POST';
const PUT = 'PUT';
const PATCH = 'PATCH';
const DELETE = 'DELETE';

module.exports = {
  async get( path ) {
    return await apiCall( path, GET );
  },

  async post( path, data ) {
    return await apiCall( path, POST, data );
  },

  async put( path, data ) {
    return await apiCall( path, PUT, data );
  },

  async patch( path, data ) {
    return await apiCall( path, PATCH, data );
  },

  async delete( path ) {
    return await apiCall( path, DELETE );
  },
};

async function apiCall( path, method, body ) {
  const data = await fetch(`${ API_URL }${ path }`, {
    method,
    body,
    headers: {
      'Content-type': 'application/json; charset=UTF-8',
    },
  });

  return {
    success: data.ok,
    data: await data.json(),
  };
};

<file_sep>/src/theme.js
import {
  createMuiTheme,
} from '@material-ui/core/styles';

// A custom theme for this app
const theme = createMuiTheme({
  palette: {
    primary: {
      main: '#3889C7',
    },

    secondary: {
      main: '#FFF',
    },

    error: {
      main: '#FF2020',
    },

    background: {
      default: '#FFF',
    },
  },

  overrides: {
    MuiInputLabel: {
      outlined: {
        backgroundColor: '#FFF',
        paddingLeft: 2,
        paddingRight: 2
      }
    }
  },
});

export default theme;
<file_sep>/src/store/hooks/user.js
import { useState, useCallback, useMemo } from 'react';

import api from '../../services/api';

export function useUser() {
  const [ loading, setLoading ] = useState( false );
  const [ data, setData ] = useState([]);

  const getUsers = useCallback( async () => {
    setLoading( true );

    const { success, data } = await api.get('/users');

    setData( data );

    setLoading( false );

    return { success, data };
  }, []);

  return useMemo(() => {
    return {
      loading,
      data,
      getUsers,
    }
  }, [ loading, data, getUsers ]);
};
<file_sep>/src/store/hooks/comment.js
import { useState, useCallback, useMemo } from 'react';

import api from '../../services/api';

export function useComment() {
  const [ getting, setGetting ] = useState( false );
  const [ saving, setSaving ] = useState( false );
  const [ data, setData ] = useState([]);

  const saveComment = useCallback( async ( newComment ) => {
    setSaving( true );

    const { success, data: newCommentData } = await api.post('/comments', newComment );

    setData([ ...data, newCommentData ]);

    setSaving( false );

    return { success, data: newCommentData };
  }, [ data ]);

  const getCommentsByPost = useCallback( async ( id ) => {
    setGetting( true );

    const { success, data } = await api.get(`/posts/${ id }/comments`);

    setData( data );

    setGetting( false );

    return { success, data };
  }, []);

  return useMemo(() => {
    return {
      getting,
      saving,
      data,
      saveComment,
      getCommentsByPost,
    }
  }, [
    getting,
    saving,
    data,
    saveComment,
    getCommentsByPost,
  ]);
};
<file_sep>/src/components/TableListPost/index.js
import React, {
  useState,
  useEffect,
} from 'react';

import {
  Typography,
  Table,
  TableHead,
  TableRow,
  TableBody,
  TableCell,
  Container,
  CircularProgress,
  Button,
} from '@material-ui/core';

import { useTranslation } from 'react-i18next';

import {
  RowPost,
} from '../RowPost';

import {
  useStore,
} from '../../store';

import styles from '../../styles';

export function TableListPost({ title, search, openModalPost }) {
  const { t, i18n } = useTranslation();
  const stylesClass = styles();

  const { posts, users } = useStore();

  const [ postsList, setPostsList ] = useState( null );

  useEffect(() => {
    if( search !== '') {
      let postsFiltered = [];

      postsFiltered = posts?.data.filter( post => post.title.toLowerCase().includes( search ) || post.body.toLowerCase().includes( search ));

      if( postsFiltered.length === 0 ) {
        const usersIds = users?.data.filter( user => user.name.toLowerCase().includes( search )).map( user => user.id );

        console.log( usersIds );

        postsFiltered = posts?.data.filter( post => usersIds.includes( post.userId ));
      }

      setPostsList( postsFiltered );
    } else {
      setPostsList( posts?.data );
    }
  }, [ search ]);

  useEffect(() => {
    setPostsList( posts?.data );
  }, [ posts?.data ]);

  return (
    <>
      <Container className={ stylesClass.titleView } >
        <Typography variant="h6" className={ stylesClass.tableTitle }>{ title }</Typography>

        <Button
          variant="outlined"
          color="secondary"
          onClick={ openModalPost }
        >
          { t('tablePosts.addButton')}
        </Button>
      </Container>

      <Container className={ stylesClass.tableView }>
        <Table size="small" className={ stylesClass.table }>
          <TableHead>
            <TableRow>
              <TableCell className={ stylesClass.tableIdColumn }>ID</TableCell>
              <TableCell className={ stylesClass.tableTitleColumn }>{ t('tablePosts.columnTitle')}</TableCell>
              <TableCell className={ stylesClass.tableUserColumn }>{ t('tablePosts.columnUser')}</TableCell>
              <TableCell align="center" className={ stylesClass.tableUserColumn }>{ t('tablePosts.columnActions')}</TableCell>
              <TableCell className={ stylesClass.tableCollapseColumn } />
            </TableRow>
          </TableHead>

          <TableBody>
            {
              !posts?.getting
                ? postsList?.length > 0
                  ? postsList.map( post => <RowPost key={ post?.id } post={ post } openModalPost={ openModalPost }/>)
                  : <TableRow>
                      <TableCell colSpan={ 5 } align="center">
                        <Typography variant="subtitle1">{ t('tablePosts.emptyData')}</Typography>
                      </TableCell>
                    </TableRow>
                : <TableRow>
                    <TableCell colSpan={ 5 } align="center">
                      <CircularProgress />
                    </TableCell>
                  </TableRow>
            }
          </TableBody>
        </Table>
      </Container>
    </>
  );
};

branch_name: refs/heads/main

repo_language: JavaScript


text:
<repo_name>isvargas/Dicas-Truques<file_sep>/serializar-formulario.js
function cadastrar() {
        var dados = new FormData( $("#frmCadastro") );
        //obs: o form deve estar com enctype="multipart/form-data"

        $.ajax({
            url: 'exemplo.php',
            //dataType: 'html',
            type: 'POST',
            data: dados,
            processData: false,
            contentType: false,
            beforeSend: function() {
                $('#alerta').html('Aguarde...');
            },
            complete: function() {
                //$('#alerta').html('Concluído');
            },
            success: function(data, textStatus) {
                var obj = JSON.parse(data); //ou data = (typeof data === 'string') ? JSON.parse(data) : data;
                obj.forEach(function(v, index) {
                    console.log(v.propriedade);
                });
            },
            error: function(xhr,er) {
                $('#alerta').html('
Error ' + xhr.status + ' - ' + xhr.statusText + '
Tipo de erro: ' + er + '
')
            }
        });
    }
<file_sep>/README.md
"# Dicas-Truques"

branch_name: refs/heads/master

languages: Markdown JavaScript

repo_language: Markdown

repo_name: isvargas/Dicas-Truques


text:
<repo_name>little-hoge/UnityBreakOut<file_sep>/README.md
# 操作方法
#### 操作方法
- 左右：移動

# デモ
[UnityBreakOut](https://little-hoge.github.io/UnityBreakOut/)
[![43g214](https://user-images.githubusercontent.com/3638785/90319929-77aab580-df77-11ea-8088-d00934104093.gif)
](https://little-hoge.github.io/UnityBreakOut/)

# 開発環境
- Windows10 64bit
- unity2019.2.0f1  unity日本語化(https://www.sejuku.net/blog/56333)
- Visual C# 2019

# 追加実装
- WebGL出力
- プレイヤー壁抜け修正

# 参考リンク
- 今日からはじめるUnity
https://qiita.com/nmxi/items/7950fb12ef925efa276d

# LICENSE
MIT
<file_sep>/Assets/Scripts/DataSender.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class DataSender {
    public static string resultMessage;
}

languages: C# Markdown

repo_language: C#

repo_name: little-hoge/UnityBreakOut


text:
<repo_name>nginxinc/helm-charts<file_sep>/CONTRIBUTING.md
At this point we are not accepting contributions for this repository - thank you.

Your NGINX team<file_sep>/README.md
# NGINX - Helm Charts

This repository contains packaged Helm charts provided by NGINX:

- [NGINX Ingress Controller](#nginx-ingress-controller)
- [NGINX Service Mesh](#nginx-service-mesh)
- [NGINX App Protect DoS Arbitrator](#nginx-app-protect-dos-arbitrator)
- [NGINX Management Suite](#nginx-management-suite)
- [NGINX ACM Developer Portal](#nginx-acm-developer-portal)

## Add Repository

```sh
$ helm repo add nginx-stable https://helm.nginx.com/stable
$ helm repo update
```

## Install Packages

### NGINX Ingress Controller

```sh
$ helm install my-release nginx-stable/nginx-ingress [--version 0.17.1]
```

#### Documentation

https://docs.nginx.com/nginx-ingress-controller/installation/installation-with-helm/

### NGINX Service Mesh

```sh
$ helm install my-release nginx-stable/nginx-service-mesh --namespace nginx-mesh --create-namespace
```

#### Documentation

https://docs.nginx.com/nginx-service-mesh/get-started/install-with-helm/

### NGINX App Protect DoS Arbitrator

```sh
$ helm install my-release nginx-stable/nginx-appprotect-dos-arbitrator [--version 0.1.0]
```

#### Documentation

https://docs.nginx.com/nginx-ingress-controller/installation/installation-with-helm/

### NGINX Management Suite

```sh
$ helm install nms nginx-stable/nms [--version 1.1.1]
```

#### Documentation

https://docs.nginx.com/nginx-management-suite/admin-guides/installation/kubernetes/nms-helm/

### NGINX ACM Developer Portal

```sh
$ helm install nms nginx-stable/nginx-devportal [--version 1.4.0]
```

#### Documentation

https://docs.nginx.com/nginx-management-suite/admin-guides/installation/kubernetes/devportal-helm-chart/

repo_name: nginxinc/helm-charts


text:
<repo_name>Hotrung2311/M2_W3_BT_CalNextDay<file_sep>/src/calNextDay/NextDay.java
package calNextDay;

import java.util.Arrays;

public class NextDay {
    public static void main(String[] args) {
        int[] date = new int[]{30, 2, 2020};
        int[] next;
        next = calNext(date[0],date[1],date[2]);
        System.out.println(Arrays.toString(date));
        System.out.println(Arrays.toString(next));
    }
    public static int[] calNext(int day, int month, int year){

        int daysCount = dayInMonth(month, year);
        int[] result = new int[3];

        if (day>daysCount){
            System.out.println("Nhập sai ngày");
            result[0]= 0;
            result[1]= month;
            result[2]= year;
            return result;
        }
        if (month > 12 && month < 1){
            System.out.println("Nhập sai tháng");
            result[0]= day;
            result[1]= 0;
            result[2]= year;
            return result;
        }
        if (year<0){
            System.out.println("Nhập sai năm");
            result[0]= day;
            result[1]= month;
            result[2]= 0;
            return result;
        }
        if (day < daysCount){
            day = day + 1;
        }
        if (day == daysCount){
            day = 1;
            if (month == 12){
                month = 1;
                year++;
            }else {
                month = month + 1;
            }
        }
        result[0]= day;
        result[1]= month;
        result[2]= year;
        return result;
    }

    private static int dayInMonth(int month, int year) {
        int daysCount = 0;
        switch (month){
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                daysCount = 31;
                break;
            case 2:
                if (isLeapYear(year)){
                    daysCount = 29;
                }else daysCount = 28;
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                daysCount = 30;
                break;
        }
        return daysCount;
    }

    public static boolean isLeapYear(int year){
        boolean leapYear = false;
        boolean isDivisibleBy4 = year % 4 == 0;
        boolean isDivisibleBy100 = year % 100 == 0;
        boolean isDivisibleBy400 = year % 400 == 0;

        if(isDivisibleBy4) {
            if (isDivisibleBy100) {
                if (isDivisibleBy400) {
                    leapYear = true;
                }
            } else {
                leapYear = true;
            }
        }

        return leapYear;
    }
}

repo_language: Java


text:
<repo_name>AngelinesYG/SalamViaje<file_sep>/public/js/app.js

class App extends React.Component {
  state = {
    place: [],
    name: "",
    image: "",
    city: "",
    country: "",
    description: "",
    rating: 0
  }

  findWeather = (event) => {
    event.preventDefault();
    axios
    .get("https://api.openweathermap.org/data/2.5/weather?q="+this.state.name+"&appid=cb62c3b0bbf4bc98a92507bb71fa55d5&units=imperial")
    .then(
      (response) => {
          let temp = Math.ceil(Math.round(response.data.main.feels_like));
        this.setState({
        weatherLike: temp,
        weather: response.data.main.humidity
         })
      }
    )
  }

/* ----- HANDLE CHANGE: ------  */

  handleChange = (event) => {
    this.setState({
      [event.target.id]: event.target.value
    })
  }

/* ------ HANDLE SUBMIT: ------  */

  handleSubmit = (event) => {
    event.preventDefault()
    axios.post('/place', this.state).then(
      (response) => {
        this.setState({
          place: response.data,
          name: "",
          image: "",
          city: "",
          country: "",
          description: "",
          rating: 0
        })
      }
    )
  }

/* ------------- UPDATE PLANT -------------  */

updatePlace = (event) => {
  event.preventDefault()
  const id = event.target.id
  console.log(event.target.id);
  axios.put('/place/' + id, this.state).then(
    (response) => {
      this.setState({
        place: response.data,
        name: "",
        image: "",
        city: "",
        country: "",
        description: "",
        rating: 0
      })
    }
  )
}

/* ------------- DELETE PLANT -------------  */

deletePlace = (event) => {
  axios.delete('/place/' + event.target.value).then(
    (response) => {
      this.setState({
        place: response.data
      })
    }
  )
}

/* ----- MOUNT DATA ON LOAD FUNCTION: ------  */
  componentDidMount = () => {
    axios.get('/place').then(response => {
      this.setState({
        place: response.data
      })
    })
  }

changeCityName = () => {
  this.setState(
    {
      name: event.target.value
    }
  )
}
decreaseRating = () =>{
   this.setState({
      star: (this.state.star -= 1)
   })
}
increaseRating = () =>{
   this.setState({
      star: (this.state.star += this.state.rating.value)
   })
}
/*  ------ END COMPONENT DID MOUNT -----  */

  render = () => {
    return (

🌴 Jalan-Jalan 🌴

            Wheather Check
            <form onSubmit={this.findWeather}>
                <input type="text" onKeyUp={this.changeCityName}/>

                <input className="btn btn-warning mb-5" type="submit" value = "City Destination" />
            </form>

 City Name:

{this.state.name}

 Temperature:

{this.state.weatherLike}

 Humidity:

{this.state.weather}

         Add New Place
        <form className="form-group col-sm-5" onSubmit={this.handleSubmit}>
          Name:

          <input
            className="form-control"
            type="text"
            id="name"
            onChange={this.handleChange}
            value={this.state.place.name}
          />

          Image
          <input
            className="form-control"
            type="text"
            id="image"
            onChange={this.handleChange}
            value={this.state.place.image}
          />

          City:
          <input
            className="form-control"
            type="text"
            id="city"
            onChange={this.handleChange}
            value={this.state.place.city}
          />

          Country:
          <input
            className="form-control"
            type="text"
            id="country"
            onChange={this.handleChange}
            value={this.state.place.country}
          />
          Description:
          <input
            className="form-control"
            type="text"
            id="description"
            onChange={this.handleChange}
            value={this.state.place.description}
          />
          Rating:
          <input
            className="form-control"
            type="number"
            id="rating"
            onChange={this.handleChange}
            value={this.state.place.rating}
          />

          <input className="btn btn-success mb-5" type="submit" id="Add Place" />

        </form>

         {this.state.place.map(place => {
            return (

{place.name}

                    Description

City: {place.city}

Country: {place.country}

Description: {place.description}

Rating: {place.rating}⭐

                    Edit
                    <form id={place._id} onSubmit={this.updatePlace}>

                      Name:

                      <input
                        type="text"
                        id="name"
                        onChange={this.handleChange}
                      />

                      Image

                      <input
                        type="text"
                        id="image"
                        onChange={this.handleChange}
                      />

                      City:

                      <input
                        type="text"
                        id="city"
                        onChange={this.handleChange}
                      />

                      Country:

                      <input
                        type="text"
                        id="country"
                        onChange={this.handleChange}
                      />

                      Description:

                      <input
                        type="text"
                        id="description"
                        onChange={this.handleChange}
                      />

                      Rating:

                      <input
                        type="number"
                        id="rating"
                        onChange={this.handleChange}
                      />

                      <input className="btn btn-primary mb-1" type="submit" id="Submit Edits" />
                    </form>

                  <button value={place._id} onClick={this.deletePlace} className="btn btn-danger">Delete</button>

            )
          })}

Project 3, "SalamViaje", by <NAME> & <NAME>

Created using Express, REACT, Bootstrap, and Open Weather API

    )
  }
}

ReactDOM.render(
  <App></App>,
  document.querySelector('main')
)
<file_sep>/server.js
/*============ DEPENDENCIES =============*/

const express = require('express')
const mongoose = require('mongoose')

/*============ CONFIGURATION =============*/

const app = express()
require('dotenv').config()
const PORT = process.env.PORT
const MONGODB_URI = process.env.MONGODB_URI

/*============= MIDDLEWARE ==============*/

//Use this middleware to return JSON data, rather than res.send/urlencoded which returns HTML:
const placesController = require('./controllers/places_controller.js')
app.use(express.static('public'))
app.use(express.json())
app.use('/place', placesController)

// app.get('/', (req, res) =>{
//    res.send('hello wold')
// })

/*============== LISTENER ================*/
app.listen (PORT, ()=>{
   console.log('listening on port' + PORT);
})

mongoose.connect(MONGODB_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useFindAndModify: false
})

/*============ MONGOOSE ERR/SUCCESS =============*/

mongoose.connection.on('error', err =>
  console.log(
    err.message,
    ' is Mongod not running?/Problem with Atlas Connection?'
  )
)
mongoose.connection.on('connected', () =>
  console.log('mongo connected: ', MONGODB_URI)
)
mongoose.connection.on('disconnected', () => console.log('mongo disconnected'))
<file_sep>/models/place_seed.js
module.exports = [
   {
      name: 'Scape Park',
      image: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRf-cNUdwTAJWmIeMxSCeGbPAtYz640_aCJ0w&usqp=CAU',
      city: 'Punta Cana',
      country: 'Dominican Republic',
      description: 'Beautifull cristal clear waters, surrounded by nature for the most enjoyable, relaxing experience.',
   },
   {
      name: 'Bali Beach',
      image: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQfSm5Z3FBsfRnpeS_UIMKUY4egrV7sm8CI5A&usqp=CAU',
      city: 'Bali',
      country: 'Indonesia',
      description: 'Enjoy the relaxing sun while the nice beach breeze careses you.',
   },
   {
      name: 'Puerto Plata Resort',
      image: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQIC8xmSPIha2XcoqJr9MjCGVGq5RR7E_44rA&usqp=CAU',
      city: 'Puerto Plata',
      country: 'Dominican Republic',
      description: 'Palm trees, coconuts, sun, and waves. Can you think of a more relaxing place? Visti DR!',
   },
   {
      name: 'Bali Vacation',
      image: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRmyjsznYTGqcw71Ia_-1hKjXpH81wFdoAcCQ&usqp=CAU',
      city: 'Bali',
      country: 'Indonesia',
      description: 'What best way to travel the world than to visit Indonesia. One of the most beautiful places in the world.',
   },
   {
      name: 'Vacation in Maldives',
      image: 'https://i.imgur.com/AEljghP.jpg',
      city: 'Maldives',
      coutry: 'Maldives',
      description: 'Dare to dine with the sharks? What best way to enjoy your dish while enjoying the perfect view!',
   },
]
<file_sep>/README.md
# Project3

Project 3 by <NAME> and <NAME>

About the app:
This app is created with a traveller's ideas in mind. Thinking that travellers often don't really know or can't decide on where to take their next vacation. So this could be something to look at that will help make a decision by looking at what others have to say about the different places.

This Travel blog allows people to post, share and edit their travel by posting pictures, adding a description, and even adding a rating.

This app also has a weather checker capability, where the user can type the city of choice and it will show the current weather & humidity, which is pulling from a from 3rd party API (Open weather)

Some of the styling are done using bootstrap.

Future Improvement:
1. Log in function where user can leave message and it will show who left the message and only can delete their own post.
2. 7 days forecast weather instead of current weather only. As well as other weather features, like air quality, wind speeds, etc.
3. Google map where you can see the location in the app.
4. A real rating system where you can drag the rating from 1 - 5.

Workflow:
We divided the back end between the two of us, each working on a different file for the back end. Chris worked on the routes, while Angie worked on the seed file and schema.
For the front end, we both felt we needed more practice with REACT, so both came together and agreed to pair-program the REACT portion. One person driving the keyboard and the other dictating/researching. We also took turns in the programming and bug hunting so that both of us had the chance to practice the logic, researching ways of improvement as well as problem solving, and mostly the coding itself.
For the CSS we pair programmed it at as well. It just seemed more logical to do it that way because we left it for last and both wanted to contribute and arrive at a design that we both liked. So it made more sense to do it together while on a zoom call so that we could see the page as each style changed and give feedback on what may or may not look better.

Additionally, we did face a lot of error and even conflicts. That probably was one of the biggest learning experiences for both of us because some errors didn't make any sense while others were very clear, yet hard to fix. We both were extra proud of ourselves because we were able to fix all our bugs and conflicts on our own. The only time we asked for help was once with the API because for some reason it wasn't letting up pull the temperature from it. This was extremely weird because the temperature key was in an object and we were able to pull the other keys in the same object, but for some odd reason, not the temperature. In the end we ended up using the "feels_like" key because we just could not figure out why it wasn't letting us access the "temp".

Lastly, we enjoyed working together and had a good flow and understanding of what we were doing and dividing the tasks, even when we were peer programing. We were able to work effectively and maintain a lot of communication throughout the process and making sure that each or our ideas and styles were reflected in this project.
<file_sep>/models/place.js
const mongoose = require('mongoose')

const placeSchema = new mongoose.Schema({
   name: String,
   image: {type: String, default: 'https://via.placeholder.com/150'},
   city: String,
   country: String,
   description: String,
   rating: Number,
})

const Place = mongoose.model('Place', placeSchema)

module.exports = Place

repo_name: AngelinesYG/SalamViaje


text:
<repo_name>blaisep-vgs/testing.cloudposse.co<file_sep>/.github/aws-nuke.yaml
regions:
#- us-east-1
- us-east-2
#- us-west-1
#- us-west-2

account-blacklist:
- "999999999999" # production

resource-types:
  # only nuke these resources
  targets:
  - IAMRole
  - S3Object
  - S3Bucket
  - EC2Address
  - ElasticBeanstalkApplication
  - ElasticBeanstalkEnvironment
  - EC2VPC
  - EC2Instance
  - EC2Volume
  - EC2Subnet
  - EC2RouteTable
  - EC2NATGateway
  - EC2InternetGateway
  - EC2InternetGatewayAttachment
  - EC2NetworkACL
  - EC2SecurityGroup
  - EC2NetworkInterface
  - ECSService
  - ECSCluster
  - ELBLoadBalancer
  - ELBv2
  - ELBv2TargetGroup
  - LambdaFunction
  - LambdaEventSourceMapping

  # don't nuke IAM users
  excludes:
  - IAMUser

accounts:
# testing account
  126450723953:
    presets:
    - defaults
    - cpco

presets:
  defaults:
    filters:
      ECSCluster:
      - type: "regex"
        value: ".*cluster/fargate"
      ECSService:
      - type: "regex"
        value: ".*service/atlantis"
      EC2InternetGateway:
      - property: "tag:Name"
        type: "regex"
        value: "^$"
      EC2InternetGatewayAttachment:
      - property: "tag:igw:Name"
        type: "regex"
        value: "^$"
      EC2RouteTable:
      - property: "tag:Name"
        type: "regex"
        value: "^$"
      EC2Subnet:
      - property: "DefaultForAz"
        value: "true"
      EC2VPC:
      - property: "IsDefault"
        value: "true"
      IAMRole:
      - "OrganizationAccountAccessRole"
      EC2SecurityGroup:
      - property: "Name"
        type: "regex"
        value: "^fargate-default$"
      EC2NetworkInterface:
      - property: "tag:Name"
        type: "regex"
        value: "^$"

  cpco:
    filters:
      S3Bucket:
      - property: "Name"
        type: "regex"
        value: "^cpco-.*"
      S3Object:
      - property: "Bucket"
        type: "regex"
        value: "^cpco-.*"
      EC2VPC:
      - property: "tag:Name"
        type: "regex"
        value: "^cpco-.*"
      EC2Volume:
      - property: "tag:Name"
        type: "regex"
        value: "^cpco-.*"
      EC2SecurityGroup:
      - property: "Name"
        type: "regex"
        value: "^cpco-.*"
      - property: "tag:Name"
        type: "regex"
        value: "^fargate-default$"
      EC2Instance:
      - property: "tag:Name"
        type: "regex"
        value: "^cpco-.*"
      EC2NetworkInterface:
      - property: "tag:Name"
        type: "regex"
        value: "^cpco-.*"
      EC2InternetGateway:
      - property: "tag:Name"
        type: "regex"
        value: "^cpco-.*"
      EC2NATGateway:
      - property: "tag:Name"
        type: "regex"
        value: "^cpco-.*"
      EC2InternetGatewayAttachment:
      - property: "tag:igw:Name"
        type: "regex"
        value: "^cpco-.*"
      EC2Subnet:
      - property: "tag:Name"
        type: "regex"
        value: "^cpco-.*"
      EC2RouteTable:
      - property: "tag:Name"
        type: "regex"
        value: "^cpco-.*"
      EC2NetworkACL:
      - property: "tag:Name"
        type: "regex"
        value: "^cpco-.*"
      ECSService:
      - property: "tag:Name"
        type: "regex"
        value: "^cpco-.*"
      ECSCluster:
      - property: "tag:Name"
        type: "regex"
        value: "^cpco-.*"
      ELBLoadBalancer:
      - property: "tag:Name"
        type: "regex"
        value: "^cpco-.*"
      ELBv2:
      - type: "regex"
        value: "^cpco-.*"
      - type: "regex"
        value: "^atlantis$"
      ELBv2TargetGroup:
      - type: "regex"
        value: "^cpco-.*"
      - type: "regex"
        value: ".*atlantis.*"

repo_language: YAML


text:
<file_sep># GeekBrains_JS_1
Обучение JavaScript поток 1


text:
<file_sep># Docker image for [ansible-lint](https://github.com/willthames/ansible-lint)

### Build
`docker build -t prontopro/ansible-lint:TAG .`

### Usage
`docker run --rm -v $(pwd):/ansible prontopro/ansible-lint`
<file_sep>pipeline:
  publish-image:
    image: plugins/docker
    repo: prontopro/ansible-lint
    dockerfile: Dockerfile
    secrets:
      - docker_username
      - docker_password
    tags:
      - latest
      - ${DRONE_TAG}
    when:
      event:
        - tag

  notify:
    image: plugins/slack
    channel: tech-feed
    username: drone
    secrets:
      - slack_webhook
    template: "Docker image for ansible-lint:${DRONE_TAG} has been published."
    when:
      event:
        - tag
<file_sep>#!/bin/bash

find ${1:-.} -iname "*.yml" ! -iname "vault.yml" | xargs -r ansible-lint --force-color ${@:2}
<file_sep>FROM python:3.7-slim-stretch

RUN pip install --upgrade pip && \
    pip install ansible && \
    pip install ansible-lint==4.1.0

ADD docker-entrypoint.sh /opt

WORKDIR /ansible

ENTRYPOINT ["/opt/docker-entrypoint.sh"]

languages: Markdown Shell Dockerfile YAML

repo_name: ProntoPro/docker-ansible-lint


text:
<file_sep># Demo

## Setup

- Install Node and Docker locally
- Install and configure AWS CLI V2: https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html
- Setup IAM and ECR: https://docs.aws.amazon.com/AmazonECR/latest/userguide/get-set-up-for-amazon-ecr.html

## Push to Container Registry

1. Login to ECR via Docker `aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin <account id>.dkr.ecr.us-east-1.amazonaws.com`
2. Create Repository `aws ecr create-repository --repository-name my-test-app --image-scanning-configuration scanOnPush=true --region us-east-1`
3. Build image with `docker build -t my-test-app .`
4. Tag image `docker tag my-test-app:latest <account id>.dkr.ecr.us-east-1.amazonaws.com/my-test-app:latest`
5. Push image `docker push <account id>.dkr.ecr.us-east-1.amazonaws.com/my-test-app:latest`

## Setup Elastic Beanstalk

- Install EB CLI: https://github.com/aws/aws-elastic-beanstalk-cli-setup
- Create Project `eb create`. Set Load Balancer type to network
- Add aws-elasticbeanstalk-ec2-role permissions: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_docker_ecs.html#create_deploy_docker_ecs_role

## Other Docker Commands

- View images `docker images`
- Run image `docker run -p 49160:8080 -d my-test-app`
- View running containers `docker ps`
- View container logs `docker logs <container id>`
- Enter container `docker exec -it <container id> /bin/bash`

repo_name: dragosrotaru/aws-elasticbeanstalk-demo