text:
<repo_name>ADEV-00/post-maker<file_sep>/src/Assets/Icons/retweet.js
import * as React from 'react';
import Svg, {Path} from 'react-native-svg';
import {TouchableOpacity} from 'react-native';

function Retweet(props) {
  const normal = '#687684';
  const active = '#59bc6c';
  const [btnActive, setBtnActive] = React.useState(false);
  return (
    <TouchableOpacity onPress={() => setBtnActive(!btnActive)}>
      <Svg
        width={22}
        height={15}
        viewBox="0 0 22 15"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
        {...props}>
        <Path
          d="M4.281.17a.644.644 0 00-.87 0L.225 3.16c-.3.283-.3.74 0 1.022.3.282.788.282 1.088 0l1.764-1.656v8.658c0 1.995 1.722 3.612 3.846 3.612h4.923c.425 0 .77-.324.77-.723 0-.399-.345-.722-.77-.722H6.923c-1.274 0-2.308-.97-2.308-2.167V2.526L6.38 4.182c.3.282.788.282 1.088 0 .3-.282.3-.74 0-1.021L4.281.169zM17.719 14.83c.24.226.63.226.87 0l3.186-2.99c.3-.283.3-.74 0-1.022a.805.805 0 00-1.088 0l-1.764 1.656V3.816c0-1.995-1.722-3.612-3.846-3.612h-4.923c-.425 0-.77.324-.77.723 0 .399.345.722.77.722h4.923c1.274 0 2.308.97 2.308 2.167v8.658l-1.764-1.656a.805.805 0 00-1.088 0c-.3.282-.3.74 0 1.021l3.186 2.992z"
          fill={btnActive ? active : normal}
        />
      </Svg>
    </TouchableOpacity>
  );
}

export default Retweet;
<file_sep>/src/helper.js
import React from 'react';
import {PermissionsAndroid} from 'react-native';

export const checkAndroidPermission = async () => {
  try {
    const permission = PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE;
    await PermissionsAndroid.request(permission);
    Promise.resolve();
  } catch (error) {
    Promise.reject(error);
  }
};
<file_sep>/src/Assets/Icons/ar_down.js
import * as React from 'react';
import Svg, {Path} from 'react-native-svg';

function Ar_Down(props) {
  return (
    <Svg
      width={15}
      height={10}
      viewBox="0 0 11 6"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      {...props}>
      <Path
        d="M10 1L5.854 5.146a.5.5 0 01-.708 0L1 1"
        stroke="#BDC5CD"
        strokeWidth={1.25}
        strokeLinecap="round"
      />
    </Svg>
  );
}

export default Ar_Down;
<file_sep>/src/screens/PostCreateScreen.js
import React, {useRef} from 'react';
import {
  View,
  Text,
  StyleSheet,
  Platform,
  Alert,
  TouchableOpacity,
  Dimensions,
  TextInput,
  ScrollView,
  Image,
  Button,
  Pressable,
  PermissionsAndroid,
} from 'react-native';
import {checkAndroidPermission} from '../helper';
import ViewShot, {captureRef} from 'react-native-view-shot';
import CameraRoll from '@react-native-community/cameraroll';
import LinearGradient from 'react-native-linear-gradient';
import DateTimePickerModal from 'react-native-modal-datetime-picker';
import RNPickerSelect from 'react-native-picker-select';
import NumericInput from 'rn-numeric-input';
import Icon from 'react-native-vector-icons/FontAwesome';
import Share from 'react-native-share';
import CheckBox from '@react-native-community/checkbox';
//API
import {getRandomQuote} from '../Api/randomQuote';

//Style
import {title, bgGray, mainBlue, shadow, activeGreen} from '../Assets/colors';

//Icons
import Ar_Down from '../Assets/Icons/ar_down.js';
import Comment from '../Assets/Icons/comment';
import Retweet from '../Assets/Icons/retweet';
import Like from '../Assets/Icons/like';
import ShareIcon from '../Assets/Icons/share';

//Components
import ProfileImg from '../Ui/profileImg';
import ProfileName from '../Ui/profileName';
import MainText from '../Ui/mainTxt';
import DataTime from '../Ui/dataAndTime';
import Client from '../Ui/client';
import Stats from '../Ui/stats';
import PostImage from '../Ui/image';

const {width, height} = Dimensions.get('screen');

const PostCreateScreen = () => {
  const viewRef = useRef();
  const [isTimePickerVisible, setTimePickerVisibility] = React.useState(false);
  const [isDatePickerVisible, setDatePickerVisibility] = React.useState(false);
  const [name, setName] = React.useState('Random name');
  const [mainText, setMainText] = React.useState('This is the main text');
  const [time, setTime] = React.useState('06:15');
  const [date, setDate] = React.useState('6/6/20');
  const [client, setClient] = React.useState();
  const [retweet, setRetweet] = React.useState(0);
  const [like, setLike] = React.useState(0);
  const [textAlign, setTextAlign] = React.useState('justify');
  const [dataTimeCheckbox, setDateTimeCheckbox] = React.useState(true);
  const [displayIcons, setDisplayIcons] = React.useState(true);
  const handleDisplayIcons = displayIcons ? 'flex' : 'none';
  const [displayStats, setDisplayStats] = React.useState(true);
  //handle Time and Datepicker
  const showTimePicker = () => {
    setTimePickerVisibility(true);
  };
  const hideTimePicker = () => {
    setTimePickerVisibility(false);
    setDatePickerVisibility(false);
  };
  const handleConfirm = (date) => {
    const time = date.toLocaleTimeString();
    setTime(time.substring(0, 5));
    hideTimePicker();
  };
  const handleConfirmDate = (date) => {
    setDate(date.toLocaleDateString());
    hideTimePicker();
  };
  const showDatePicker = () => {
    setDatePickerVisibility(true);
  };

  const getPermission = async () => {
    await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
      {
        title: 'Cool Photo App Camera Permission',
        message:
          'Cool Photo App needs access to your camera ' +
          'so you can take awesome pictures.',
        buttonNeutral: 'Ask Me Later',
        buttonNegative: 'Cancel',
        buttonPositive: 'OK',
      },
    );
  };

  //Save image to Device
  const downloadImage = async () => {
    try {
      if (Platform.OS === 'android') {
        await checkAndroidPermission();
      }
      // react-native-view-shot caputures component
      const uri = await captureRef(viewRef, {
        format: 'png',
        quality: 0.8,
      });

      // cameraroll saves image
      const image = CameraRoll.save(uri, 'Photo');
      if (image) {
        Alert.alert(
          '',
          'Image saved successfully.',
          [{text: 'OK', onPress: () => {}}],
          {cancelable: false},
        );
      }
    } catch (error) {
      console.log('error', error);
    }
  };

  const shareImage = async () => {
    try {
      // capture component
      const uri = await captureRef(viewRef, {
        format: 'png',
        quality: 0.8,
      });
      // share
      const shareResponse = await Share.open({url: uri});
    } catch (err) {
      console.log(err);
    }
  };

  const setRadnomQuote = async () => {
    const quote = await getRandomQuote();
    setMainText(quote);
  };

  return (
    <ScrollView style={styles.container} showsVerticalScrollIndicator={false}>
      <View style={styles.header}>
        <LinearGradient
          colors={['#292B4D', '#545671']}
          style={styles.headerWrapper}
          start={{x: 1, y: 0}}
          end={{x: 0, y: 0}}>
          <Text style={styles.headerText}>Post Maker</Text>
          <View></View>
        </LinearGradient>
      </View>
      <View style={styles.mainWrapper}>
        <ViewShot style={styles.postWrapper} ref={viewRef}>
          <View style={styles.postHeader}>
            <ProfileImg />
            <ProfileName name={name} />
            <View style={{marginLeft: 'auto'}}>
              <Ar_Down />
            </View>
          </View>
          <View style={styles.mainPostWrapper}>
            <MainText contentTxt={mainText} align={textAlign} />
          </View>
          <PostImage />
          <View style={styles.details}>
            <DataTime time={time} date={date} display={dataTimeCheckbox} />
            <Client client={client} />
          </View>
          {displayStats ? <Stats retweet={retweet} like={like} /> : null}

          <View style={[styles.actionIcons, {display: handleDisplayIcons}]}>
            <Comment />
            <Retweet />
            <Like />
            <ShareIcon />
          </View>
        </ViewShot>
        <View style={styles.optionsWrapper}>
          <View style={styles.inputWrapper}>
            <Text style={styles.label}>Name:</Text>
            <View style={styles.input}>
              <TextInput
                placeholder="Type name here..."
                onChangeText={(name) => setName(name)}
                maxLength={20}
              />
            </View>
          </View>
          <View style={styles.inputWrapper}>
            <Text style={styles.label}>Main content:</Text>
            <View style={styles.input}>
              <TextInput
                placeholder="Type main content here..."
                onChangeText={(text) => setMainText(text)}
                multiline={true}
                value={mainText}
              />
            </View>
          </View>
          <View style={styles.inputWrapper}>
            <TouchableOpacity
              style={styles.btnTimeDate}
              onPress={setRadnomQuote}>
              <Text
                style={{
                  color: mainBlue,
                  fontWeight: 'bold',
                  fontSize: 18,
                  textAlign: 'center',
                }}>
                Get random qoute
              </Text>
            </TouchableOpacity>
          </View>
          <View style={styles.inputWrapper}>
            <Text style={styles.label}>Main text align</Text>

            <View
              style={{flexDirection: 'row', justifyContent: 'space-around'}}>
              <Pressable onPress={() => setTextAlign('left')}>
                <View style={styles.btnTimeDate}>
                  <Icon name="align-left" size={22} color={mainBlue} />
                </View>
              </Pressable>
              <Pressable onPress={() => setTextAlign('center')}>
                <View style={styles.btnTimeDate}>
                  <Icon name="align-center" size={22} color={mainBlue} />
                </View>
              </Pressable>
              <Pressable onPress={() => setTextAlign('justify')}>
                <View style={styles.btnTimeDate}>
                  <Icon name="align-justify" size={22} color={mainBlue} />
                </View>
              </Pressable>
              <Pressable onPress={() => setTextAlign('right')}>
                <View style={styles.btnTimeDate}>
                  <Icon name="align-right" size={22} color={mainBlue} />
                </View>
              </Pressable>
            </View>
          </View>
          <View style={styles.inputWrapper}>
            <Text style={styles.label}>Time and Date</Text>
            <View style={{flexDirection: 'row', alignItems: 'center'}}>
              <View style={{marginRight: 10}}>
                <TouchableOpacity
                  style={styles.btnTimeDate}
                  onPress={showTimePicker}>
                  <Text
                    style={{fontSize: 18, color: mainBlue, fontWeight: 'bold'}}>
                    Set Time
                  </Text>
                </TouchableOpacity>
                <DateTimePickerModal
                  isVisible={isTimePickerVisible}
                  mode="time"
                  onConfirm={handleConfirm}
                  onCancel={hideTimePicker}
                />
              </View>
              <View style={{marginRight: 10}}>
                <TouchableOpacity
                  style={styles.btnTimeDate}
                  onPress={showDatePicker}>
                  <Text
                    style={{fontSize: 18, color: mainBlue, fontWeight: 'bold'}}>
                    Set Date
                  </Text>
                </TouchableOpacity>
                <DateTimePickerModal
                  isVisible={isDatePickerVisible}
                  mode="date"
                  onConfirm={handleConfirmDate}
                  onCancel={hideTimePicker}
                  locale="en_GB"
                />
              </View>
              <View>
                <CheckBox
                  value={dataTimeCheckbox}
                  onValueChange={(newValue) => setDateTimeCheckbox(newValue)}
                  onCheckColor={mainBlue}
                />
              </View>
            </View>
          </View>
          <View style={styles.inputWrapper}>
            <Text style={styles.label}>Choose a Client</Text>
            <RNPickerSelect
              style={{
                ...pickerSelectStyles,
                viewContainer: {
                  width: '70%',
                  backgroundColor: bgGray,
                  borderRadius: 10,
                  ...shadow,
                },
              }}
              onValueChange={(value) => setClient(value)}
              placeholder={{
                label: 'Select a client...',
                value: null,
              }}
              items={[
                {label: 'Twitter Web App', value: 'Twitter Web App'},
                {label: 'Twitter for iPhone', value: 'Twitter for iPhone'},
                {label: 'Twitter for Android', value: 'Twitter for Android'},
              ]}
            />
          </View>
          <View style={styles.inputWrapper}>
            <Text style={styles.label}>Retweets</Text>
            <NumericInput
              onChange={(value) => setRetweet(value)}
              totalWidth={160}
              totalHeight={50}
              iconSize={25}
              valueType="real"
              rounded
              textColor={mainBlue}
              iconStyle={{color: 'white'}}
              rightButtonBackgroundColor={mainBlue}
              leftButtonBackgroundColor={mainBlue}
              containerStyle={{
                backgroundColor: bgGray,
              }}
            />
          </View>
          <View style={styles.inputWrapper}>
            <Text style={styles.label}>Likes</Text>
            <NumericInput
              onChange={(value) => setLike(value)}
              totalWidth={160}
              totalHeight={50}
              iconSize={25}
              valueType="real"
              rounded
              textColor={mainBlue}
              iconStyle={{color: 'white'}}
              rightButtonBackgroundColor={mainBlue}
              leftButtonBackgroundColor={mainBlue}
              containerStyle={{
                backgroundColor: bgGray,
              }}
            />
          </View>
          <View style={styles.inputWrapper}>
            <View style={{flexDirection: 'row', alignItems: 'center'}}>
              <Text style={styles.label}>Display Likes and Retweets:</Text>
              <CheckBox
                value={displayStats}
                onValueChange={(newValue) => setDisplayStats(newValue)}
              />
            </View>
          </View>
          <View style={styles.inputWrapper}>
            <View style={{flexDirection: 'row', alignItems: 'center'}}>
              <Text style={styles.label}>Display Icons:</Text>
              <CheckBox
                value={displayIcons}
                onValueChange={(newValue) => setDisplayIcons(newValue)}
              />
            </View>
          </View>
          <View
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              marginTop: 20,
              justifyContent: 'space-around',
            }}>
            <TouchableOpacity
              onPress={() => downloadImage()}
              style={styles.btnSave}>
              <Text
                style={{
                  color: activeGreen,
                  fontSize: 18,
                  fontWeight: 'bold',
                }}>
                Save
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => shareImage()}
              style={styles.btnShare}>
              <Icon name="share" size={22} color={mainBlue} />
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  btnSave: {
    backgroundColor: '#FDFDFD',
    width: 100,
    minHeight: 40,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 5,
    ...shadow,
    borderWidth: 0.3,
    borderColor: activeGreen,
  },
  btnShare: {
    backgroundColor: '#fdfdfd',
    width: 60,
    height: 60,
    borderRadius: 50,
    ...shadow,
    justifyContent: 'center',
    alignItems: 'center',
  },
  btnTimeDate: {
    backgroundColor: '#FDFDFD',
    paddingHorizontal: 10,
    paddingVertical: 12,
    borderRadius: 5,
    ...shadow,
  },
  label: {
    fontSize: 18,
    fontWeight: 'bold',
    color: title,
    marginBottom: 5,
  },
  input: {
    width: '100%',
    backgroundColor: bgGray,
    paddingHorizontal: 5,
    borderRadius: 10,
  },
  inputWrapper: {
    marginBottom: 10,
  },
  optionsWrapper: {
    padding: 20,
  },
  actionIcons: {
    flexDirection: 'row',
    marginTop: 13,
    justifyContent: 'space-around',
  },

  details: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 15,
  },
  mainPostWrapper: {
    width: '100%',
    flexDirection: 'column',
    marginBottom: 37,
  },

  postHeader: {
    width: '100%',
    height: 55,
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 23,
  },
  postWrapper: {
    width: '100%',
    marginTop: 40,
    borderRadius: 20,
    overflow: 'hidden',
    padding: 20,
    backgroundColor: 'white',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
  },
  container: {
    flex: 1,
    width: width,
    height: height,
    flexDirection: 'column',
  },
  header: {
    width: '100%',
    height: height / 4,
    backgroundColor: 'red',
  },
  headerWrapper: {
    width: '100%',
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
    paddingBottom: 20,
  },
  headerText: {
    fontWeight: 'bold',
    textTransform: 'uppercase',
    color: 'white',
    fontSize: 40,
  },
  mainWrapper: {
    width: width,
    transform: [
      {
        translateY: -40,
      },
    ],
    minHeight: height / 2,
    backgroundColor: 'white',
    borderTopRightRadius: 40,
    borderTopLeftRadius: 40,
  },
});

const pickerSelectStyles = StyleSheet.create({
  inputIOS: {
    fontSize: 16,
    paddingVertical: 12,
    paddingHorizontal: 10,
    borderWidth: 1,
    borderColor: 'gray',
    borderRadius: 4,
    color: 'black',
    paddingRight: 30,
  },
  inputAndroid: {
    fontSize: 16,
    paddingHorizontal: 10,
    paddingVertical: 8,
    borderWidth: 1,
    borderColor: 'purple',
    borderRadius: 8,
    color: 'black',
    paddingRight: 30,
  },
});

export default PostCreateScreen;
<file_sep>/README.md
# Post maker / Fake Tweet Generator

Simple post maker App made in React Native

<img src="https://user-images.githubusercontent.com/53909124/106955128-15b45700-6735-11eb-9d85-80d000adcdc3.jpg" width="400">
<file_sep>/src/Ui/profileImg.js
import React from 'react';
import {View, Text, Image, StyleSheet} from 'react-native';

const ProfileImg = () => {
  return (
    <View style={styles.profileImg}>
      <Image
        style={{width: '100%', height: '100%'}}
        source={require('../Assets/Images/default_profile.png')}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  profileImg: {
    width: 55,
    height: 55,
    borderRadius: 50,
    backgroundColor: 'gray',
    marginRight: 8,
    overflow: 'hidden',
  },
});

export default ProfileImg;
<file_sep>/src/Ui/image.js
import React from 'react';
import {View, Text, StyleSheet, Image} from 'react-native';

const test = {display: 'none'};
const PostImage = () => {
  return (
    <View style={styles.wrapper}>
      <Image style={StyleSheet.absoluteFillObject} />
    </View>
  );
};

const styles = StyleSheet.create({
  wrapper: {
    width: '100%',
    height: 200,
    backgroundColor: 'red',
    marginBottom: 20,
    borderRadius: 10,
    overflow: 'hidden',
    ...test,
  },
});

export default PostImage;
<file_sep>/src/Ui/mainTxt.js
import React from 'react';
import {View, Text, StyleSheet} from 'react-native';

const MainText = ({contentTxt, align}) => {
  return (
    <View>
      <Text style={[styles.mainPostText, {textAlign: `${align}`}]}>
        {contentTxt}
      </Text>
    </View>
  );
};

const styles = StyleSheet.create({
  mainPostText: {
    fontSize: 22,
    color: 'black',
  },
});

export default MainText;
<file_sep>/src/Assets/colors.js
export const defaultGray = '#687684';
export const mainBlue = '#4c9eeb';
export const activeGreen = '#59BC6c';
export const activeRed = '#CE395f';
export const bgGray = '#E7ECF0';
export const title = '#303030';
export const shadow = {
  shadowColor: '#000',
  shadowOffset: {
    width: 0,
    height: 4,
  },
  shadowOpacity: 0.2,
  shadowRadius: 4.65,
  elevation: 4,
};
<file_sep>/src/Api/randomQuote.js
const API_URL = 'https://type.fit/api/quotes';

export const getRandomQuote = async () => {
  const ress = await fetch(API_URL).then((x) => x.json());
  const randomQuote = ress[Math.floor(Math.random() * ress.length)];
  return randomQuote.text;
};
<file_sep>/src/Ui/profileName.js
import React from 'react';
import {View, Text, StyleSheet} from 'react-native';
import {defaultGray} from '../Assets/colors';

const ProfileName = ({name}) => {
  const tagName = name.replace(/\s/g, '_');
  return (
    <View>
      <Text style={{fontWeight: 'bold', color: 'black', fontSize: 18}}>
        {name}
      </Text>
      <Text style={styles.tagName}>@{tagName}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  tagName: {
    fontWeight: '200',
    color: defaultGray,
    textTransform: 'lowercase',
  },
});

export default ProfileName;
<file_sep>/src/Ui/textInput.js
import React from 'react';
import {View, TextInput, Text, StyleSheet} from 'react-native';
import {defaultGray} from '../Assets/colors';

const TextInput = () => {
  return (
    <View>
      <TextInput placeholder="Enter you main content..." />
    </View>
  );
};

export default TextInput;
<file_sep>/src/Assets/Icons/share.js
import * as React from 'react';
import Svg, {Path} from 'react-native-svg';
import {TouchableOpacity} from 'react-native';

function ShareIcon(props) {
  return (
    <TouchableOpacity>
      <Svg
        width={18}
        height={18}
        viewBox="0 0 18 18"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
        {...props}>
        <Path
          fillRule="evenodd"
          clipRule="evenodd"
          d="M8.583.178a.578.578 0 01.834 0l4.236 4.364a.776.776 0 010 1.075.723.723 0 01-1.043 0l-2.872-2.96v9.11c0 .42-.33.76-.738.76a.75.75 0 01-.738-.76v-9.11L5.39 5.618a.722.722 0 01-1.043 0 .776.776 0 010-1.075L8.583.178zM.738 9.792a.75.75 0 01.737.76v4.864c0 .587.463 1.064 1.033 1.064h12.984c.57 0 1.033-.477 1.033-1.064v-4.864c0-.42.33-.76.737-.76a.75.75 0 01.738.76v4.864C18 16.843 16.877 18 15.492 18H2.508C1.123 18 0 16.843 0 15.416v-4.864c0-.42.33-.76.738-.76z"
          fill="#687684"
        />
      </Svg>
    </TouchableOpacity>
  );
}

export default ShareIcon;
<file_sep>/App.js
import React from 'react';
import PostCreateScreen from './src/Screens/PostCreateScreen';

export default function App() {
  return <PostCreateScreen />;
}

languages: Markdown JavaScript


text:
<file_sep>{% extends "base.html.twig" %}

{% block body %}

Agence lorem ipsum

Le lorem ipsum est, en imprimerie, une suite de mots sans signification utilisée à titre
																																																									        provisoire pour calibrer une mise en page, le texte définitif venant remplacer le faux-texte dès qu'il est prêt ou que la mise en page est achevée.

Les dernies biens

			{% for property in properties %}

									{{ property.title}}

{{ property.city}}
									({{ property.postalCode}})

{{ property.formatedPrice}}
									€

			{% endfor %}

{% endblock %}
<file_sep><?php
namespace App\Controller;

use App\Entity\Option;
use App\Entity\Property;
use App\Form\PropertyType;

use App\Repository\PropertyRepository;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class AdminPropertyController extends AbstractController {

    private $propertyRepository;

 public function __construct(PropertyRepository $propertyRepository)
      {
          $this->propertyRepository = $propertyRepository;

      }

/**
 * @Route("/admin", name="admin.property.index")
 *
 */
    public function index()
    {
     $properties =  $this->propertyRepository->findAll();
     return $this->render('admin/index.html.twig', compact('properties'));
    }

     /**
     * @Route("/admin/create", name="admin.property.new")
     */
    public function new(Request $request)
    {
        $property = new Property();
        $form = $this->createForm(PropertyType::class,   $property);
        $form->handleRequest($request);

        if($form->isSubmitted() && $form->isValid()){
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($property);
            $entityManager->flush();
            $this->addFlash("success", "Bien crée avec succés");
            return $this->redirectToRoute('admin.property.index');

        }
        return $this->render('/admin/new.html.twig', [
            'property' => $property,
            'form' => $form->createView()
        ]);
       }

    /**
     * @Route("/admin/{id}", name="admin.property.edit",  methods="GET|POST")
     *
     *
     */
    public function edit(Property $property, Request $request)
    {

        //$option = new Option();
        //$property->addOption($option);

    $form = $this->createForm(PropertyType::class, $property);
    $form->handleRequest($request);

    if($form->isSubmitted() && $form->isValid()){
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->flush();
        $this->addFlash("success", "Bien modifié avec succés");
        return $this->redirectToRoute('admin.property.index');

    }

     return $this->render('admin/edit.html.twig', [
         'property' => $property,
         'form' => $form->createView()
     ]);
    }
      /**
     * @Route("/admin/property/{id}", name="admin.property.delete", methods="DELETE")
     *
     */
    public function delete(Property $property, Request $request)
    {
        if($this->isCsrfTokenValid('delete' . $property->getId(), $request->get('_token'))){
              $entityManager = $this->getDoctrine()->getManager();
                $entityManager->remove($property);
                $entityManager->flush();
                $this->addFlash("success", "Bien supprimé avec succés");
               // return new Response('Suppression');

        }

        return $this->redirectToRoute('admin.property.index');
    }
}

branch_name: refs/heads/master

languages: Twig PHP

repo_language: Twig

repo_name: mouctare/annonces-immo


text:
<repo_name>gregoriushari/ushop<file_sep>/controller/manager_delete.php
<?php
include '../include/config.php';
// menyimpan data id kedalam variabel
$id   = $_POST['Delete'];
// query SQL untuk insert data
$query="DELETE from item where item_id='$id'";
mysqli_query($db, $query);
// mengalihkan ke halaman index.php
header("location:../view/Manager.php");
?><file_sep>/controller/login.php
<?php
session_start();
include '../include/config.php';

$username = $_POST['username'];
$password = md5($_POST['password']);

// menyeleksi data user dengan username dan password yang sesuai
$login = mysqli_query($db,"SELECT  *  from user JOIN role on role.role_id = user.role_id where  user_id= '$username' and password='$<PASSWORD>'");

// menghitung jumlah data yang ditemukan
$cek = mysqli_num_rows($login);

// cek apakah username dan password di temukan pada database
if($cek > 0){

	$data = mysqli_fetch_assoc($login);
	$nama = $data['first_name'];

	// cek jika user login sebagai admin
	if($data['role_name']=="Admin"){

		// buat session login dan username
		$_SESSION['username'] = $username;
		$_SESSION['role_name'] = "Admin";
		// alihkan ke halaman dashboard admin
		header("location:../view/Admin.php");

	// cek jika user login sebagai pegawai
	}else if($data['role_name']=="Manager"){
		// buat session login dan username
		$_SESSION['username'] = $username;
		$_SESSION['role_name'] = "Manager";
		$_SESSION['first_name']=$nama;
		// alihkan ke halaman dashboard pegawai
		header("location:../view/Manager.php");

	// cek jika user login sebagai pengurus
	}else if($data['role_name']=="Kasir"){
		// buat session login dan username
		$_SESSION['username'] = $username;
		$_SESSION['role_name'] = "Kasir";
		$_SESSION['first_name']= $nama;
		// alihkan ke halaman dashboard pengurus
		header("location:../view/Kasir.php");

	}else if($data['role_name']=="Pembeli"){
		// buat session login dan username
		$_SESSION['username'] = $username;
		$_SESSION['role_name'] = "Pembeli";
		$_SESSION['first_name']= $nama;
		// alihkan ke halaman dashboard pengurus
		header("location:../view/Pembeli.php");

	}else {

		// alihkan ke halaman login kembali
		header("location:../index.php?pesan=gagal");
	}
}else{
	header("location:../index.php?pesan=gagal");
}
?>
<file_sep>/readme.txt
Cara kerja web
link web https://rimowa26.000webhostapp.com/

jika kita login dengan username 1000 dan password <PASSWORD>, kita bisa melihatt user yg terdaftar dan
dapat mengakses website ini. tugas seorang admin itu dapat menambahkan user baru, mengedit user, dan
juga bisa menghapus user yang di inginkan. jika ingin menambahkan user baru, admin di meski mengisi, user id,
nama user, role user, alamat dan password. setelah selesai, user yang di input akan tersimpan di database

jika kita login dengan username 1001 dan password <PASSWORD>. kita bisa melihat barang apa saja yang di jual
di dalam toko, stok dan harga barang yang tersedia. hak yang di miliki oleh manager yaitu dapat menambahkan barang,
mengedit barang dan juga menghapus barang yang di anggap tidak sesuai. jika ingin menambahkan barang, managar di haruskan
mengisi id barang, nama barang, stok barang, harga barang dan juga deskripsi barang tersebut. setelah selesai, barang
yang di input akan tersimpan di database

jika kita login dengan username 1002/1003 dengan password <PASSWORD>. kita mendapatkan sebuah hak untuk melihat dan
mengedit jumlah barang dan harga barang

jika kita login dengan username 1004/1005 dengan password <PASSWORD>. kita dapat melihat ketersediaan barang
dan detail barang<file_sep>/view/add_manager.php
<!DOCTYPE html>

    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap.min.css">

		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <title>Tambah Barang</title>

ADD NEW BARANG

        <form action="../controller/insert_manager.php" method="post" id="myform">

            ID BARANG
            <input type="text" class="form-control" placeholder="" name="id" id="id" required>
            Nama Barang
            <input type="text" class="form-control" placeholder="" name="n" id="nama" required>
            Stok Barang
            <input type="text" class="form-control" placeholder="" name="st" id="stock" required>
            Harga Barang

            <input type="text" class="form-control" placeholder="" name="h" id="harga" required>
            Deskripsi
            <textarea class="form-control" name="c" id="desc"required></textarea>
            <input type="submit" class="btn btn-primary" style="margin-top:2em;">
            <input type="button" value="Cancel" class="btn btn-danger" style="margin-top:2em;"></button>
        </form>

<file_sep>/view/edit_admin.php
<!DOCTYPE html>

	<title>Data User</title>
	<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap.min.css">

		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

DATA USER

	<?php
	include '../include/config.php';
    $id = $_POST['Update'];
    $data = mysqli_query($db,"SELECT  *  from user where user_id='$id'");
	while($d = mysqli_fetch_assoc($data)){
		?>

		<form action="../controller/update_admin.php" method="post" name="form1">

            ID
            <input type="number" class="form-control" name="id"  required value="<?php echo $d['user_id']; ?>">

            <NAME>
            <input type="text" class="form-control" name="fn" required value="<?php echo $d['first_name']; ?>">

            <NAME>
            <input type="text" class="form-control" name="ln"  value="<?php echo $d['last_name']; ?>">

            Role
            <input  type="text" class="form-control" name="role" required value="<?php echo $d['role_id']; ?>">

            Alamat
            <input  type="text" class="form-control " name="alamat" required value="<?php echo $d['address']; ?>">

            Password

            <input type="<PASSWORD>" class="form-control"  required name="pass" >

        <button name="Submit" type="submit" class="btn btn-primary" style="margin-top:2em;">Update</button>
		<input type="button" value="Back" class="btn btn-danger" style="margin-top:2em;"></button>
    </form>
	<?php
	}
	?>

<file_sep>/view/add_admin.php
<!DOCTYPE html>

        <link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap.min.css">

		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <title>Tambah User</title>

ADD NEW USER

        <form action="../controller/insert_admin.php" method="post" id="myform" onSubmit="return validasi()">

            ID
            <input type="text" class="form-control" placeholder="" name="id" required>
            Nama Depan
            <input type="text" class="form-control" placeholder="" name="nd"  required>
            Nama belakang
            <input type="text" class="form-control" placeholder="" name="nb" >
            Role

            <select name="role" id="role">
            <option value="2">Manager</option>
            <option value="3">Kasir</option>
            <option value="4">Pembeli</option>
            </select>

            Address
            <input type="text" class="form-control" placeholder="" name="add" id="add" required>
            Password
            <input type="password" class="form-control" placeholder="" name="psw" id="psw" required>
            <input type="submit" class="btn btn-primary" style="margin-top:2em;">
            <input type="button" value="Cancel" class="btn btn-danger" style="margin-top:2em;"></button>
        </form>

<file_sep>/controller/admin_delete.php
<?php
include '../include/config.php';
// menyimpan data id kedalam variabel
$id   = $_POST['Delete'];
// query SQL untuk insert data
$query="DELETE from user where user_id='$id'";
mysqli_query($db, $query);
// mengalihkan ke halaman index.php
header("location:../view/Admin.php");
?><file_sep>/index.php
<!DOCTYPE html>

    <?php
    session_start();
	?>
	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

	<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta/css/bootstrap.css" rel="stylesheet">
	<link href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css" rel="stylesheet">

	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>TOKOSEDIA</title>
	<link rel="stylesheet" type="text/css" href="view/style.css">

 TOKOSEDIA

					About Me

    <meta charset="UTF-8">

Login System

		<form action="controller/login.php" method="post" onSubmit="return validasi()" >
			Username
			<input type="text" name="username" class="form_login" id="username" placeholder="Username ..">

			Password
			<input type="<PASSWORD>" name="password" class="form_login" id="password" placeholder="<PASSWORD> ..">

			<input type="submit" class="tombol_login" value="LOGIN">

		</form>
		<?php
	            if(isset($_GET['pesan'])){
		        if($_GET['pesan']=="gagal"){
                echo "

                    Username dan Password tidak sesuai !

";
		}
	}
	?>

<file_sep>/controller/insert_admin.php
<?php
include "../include/config.php";

    $id = $_POST['id'];
    $fnama =$_POST['nd'];
    $lnama = $_POST['nb'];
    $role= $_POST['role'];
    $add =$_POST['add'];
    $pass =$_POST['psw'];

    $query = "INSERT INTO user VALUES('$id','".md5($pass)."','$fnama','$lnama','$role','$add' );";
    $result =mysqli_query($db, $query);

    header('location:../view/Admin.php');

?><file_sep>/controller/update_admin.php
<?php
        include '../include/config.php';
        // menyimpan data kedalam variabe
        $id             = $_POST['id'];
        $fnama           = $_POST['fn'];
        $lnama           = $_POST['ln'];
        $role           = $_POST['role'];
        $alamat         = $_POST['alamat'];
        $pass           = md5($_POST['pass']);
        // query SQL untuk insert data
        $query= "UPDATE user SET
        user_id ='$id',
        password='<PASSWORD>',
        first_name ='$fnama',
        last_name ='$lnama',
        role_id ='$role',
        address = '$alamat'

        where user_id ='$id'";

        mysqli_query($db, $query);
        // mengalihkan ke halaman index.php
        header("location:../view/Admin.php");
?>
<file_sep>/controller/update_kasir.php
<?php
        include '../include/config.php';
        // menyimpan data kedalam variabe
        $stok           = $_POST['stok'];
        $harga           = $_POST['harga'];
        // query SQL untuk insert data
        $query= "UPDATE item SET item_stock='$stok', item_price ='$harga'
        where  item_stock='$stok'or item_price ='$harga'";

        mysqli_query($db, $query);
        // mengalihkan ke halaman index.php
        header("location:../view/Kasir.php");
?>
<file_sep>/controller/update_manager.php
<?php
        include '../include/config.php';
        // menyimpan data kedalam variabe
        $nama           = $_POST['nama'];
        $stok           = $_POST['stok'];
        $harga           = $_POST['harga'];
        $komen             =$_POST['desc'];
        // query SQL untuk insert data
        $query= "UPDATE item SET  item_name ='$nama', item_stock='$stok', item_price ='$harga', item_desc='$komen'
        where  item_name ='$nama'or item_stock='$stok'or item_price ='$harga'or item_desc='$komen'";

        mysqli_query($db, $query);
        // mengalihkan ke halaman index.php
        header("location:../view/Manager.php");
?>
<file_sep>/view/show_beli.php
<?php
session_start();
?>

<!DOCTYPE html>

	<title>Lihat Barang</title>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap.min.css">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

 TOKOSEDIA

                        <?php
                            echo "Hello, " . $_SESSION['role_name'];
                        ?>

DATA BARANG

	<?php
	include '../include/config.php';
	$id = $_POST['Update'];
	$data = mysqli_query($db,"SELECT  *  from item where item_id='$id'");
	while($d = mysqli_fetch_assoc($data)){
		?>

		<form action="../controller/update_kasir.php" method="post" name="form1">

            ID Barang
            <input type="text" class="form-control" name="id" disabled value="<?php echo $d['item_id']; ?>">

            Nama Barang
            <input type="text" class="form-control" name="nama" disabled value="<?php echo $d['item_name']; ?>">

            Stock Barang
            <input  type="text" class="form-control" name="stok" disabled value="<?php echo $d['item_stock']; ?>">

            Harga Barang
            <input  type="text" class="form-control " name="harga" disabled value="<?php echo $d['item_price']; ?>">

             Deskripsi Barang
            <input  type="text" class="form-control " name="harga" disabled value="<?php echo $d['item_desc']; ?>">

		<input type="button" value="Back"  class="btn btn-danger" style="margin-top:2em;"></button>
		</form>
	<?php
	}
	?>

<file_sep>/controller/insert_manager.php
<?php
include "../include/config.php";

    $id = $_POST['id'];
    $nama =$_POST['n'];
    $stok= $_POST['st'];
    $harga =$_POST['h'];
    $desc =$_POST['c'];

    $query = "INSERT INTO item VALUES('$id','$nama','$stok','$harga','$desc' );";
    $result =mysqli_query($db, $query);

    header('location:../view/Manager.php');

?>

languages: Hack Text PHP

repo_language: Hack

repo_name: gregoriushari/ushop


text:
<repo_name>vrajdattani/weather<file_sep>/src/Services/CountryService.js
import Axios from "axios"

export const CountryService = (name) =>{
    return Axios.get(`https://restcountries.eu/rest/v2/name/${name}`);
}<file_sep>/src/Actions/weatherAction.js
import {WeatherType} from './WeatherType'
import {weatherService} from '../Services/weatherService';
export const weatherAction=(name)=>{
    return async(dispatch)=>{
        const details = await weatherService(name);
        dispatch({type:WeatherType,payload:details.data})
    }
}<file_sep>/src/Actions/WeatherType.js
export const WeatherType = 'WEATHER';<file_sep>/src/App.js
import logo from './logo.svg';
import './App.css';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import Countries from './Component/Countries';
import CountryDetails from './Component/CountryDetails';
import CheckWeather from './Component/CheckWeather';

function App() {
  return (
    <div className="App">
      <BrowserRouter>
      <Switch>
        <Route exact path='/' component={Countries}/>
        <Route path='/CountryDetails' component={CountryDetails}/>
        <Route path='/CheckWeather' component={CheckWeather}/>
      </Switch>
      </BrowserRouter>
    </div>
  );
}

export default App;
<file_sep>/src/Actions/CountryType.js
export const  CountryType = 'COUNTRY';<file_sep>/src/Actions/countryAction.js
import { CountryService } from "../Services/CountryService"
import { CountryType } from './CountryType';
export const countryAction = (name) =>{
    return async (dispatch) =>{
        const details = await CountryService(name);
        dispatch({type:CountryType,payload:details.data[0]});
    }
}<file_sep>/src/Services/weatherService.js
import Axios from "axios"

export const weatherService = async(name) =>{
    return (Axios.get(`http://api.weatherstack.com/current?access_key=<KEY>&query=${name}`))
}

repo_language: JavaScript

repo_name: vrajdattani/weather


text:
<repo_name>tonipikkarainen/Ohjelmointi2Paivakirja<file_sep>/src/paivakirja/TranskriptioTest.java
package paivakirja;
// Generated by ComTest BEGIN
import static org.junit.Assert.*;
import org.junit.*;
import paivakirja.*;
// Generated by ComTest END

/**
 * Test class made by ComTest
 * @version 2016.04.14 13:36:15 // Generated by ComTest
 *
 */
public class TranskriptioTest {

  // Generated by ComTest BEGIN
  /** testRekisteroi143 */
  @Test
  public void testRekisteroi143() {    // Transkriptio: 143
    Transkriptio badmama1 = new Transkriptio();
    assertEquals("From: Transkriptio line: 145", 0, badmama1.getIdNumero());
    badmama1.rekisteroi();
    Transkriptio badmama2 = new Transkriptio();
    badmama2 .rekisteroi();
    int a = badmama1.getIdNumero();
    int b = badmama2 .getIdNumero();
    assertEquals("From: Transkriptio line: 151", 1, b - a);
    badmama1.asetaKentat("  4|Eye of the Tiger|Rocky  ");
    assertEquals("From: Transkriptio line: 153", true, badmama1.toString().equals("4|Eye of the Tiger|Rocky"));
  } // Generated by ComTest END
}<file_sep>/src/paivakirja/Transkriptiot.java
package paivakirja;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

/**
 * Luokka huolehtii joukosta transkriptioita
 * @author tonipikkarainen
 * @version 29.2.2016
 *
 */
public class Transkriptiot implements Iterable<Transkriptio>{

    private final Collection<Transkriptio> alkiot = new ArrayList<Transkriptio>();
    private String tiedostonPerusNimi = "transkriptiot";
    /**
     * Lisätään transkriptio listaan
     * @param transkriptio lisättävä
     */
    public void lisaa(Transkriptio transkriptio){
        alkiot.add(transkriptio);
    }

    /**
     * Haetaan tallennettujen alkioiden lukumäärä
     * @return lukumäärä kokonaislukuna
     */
    public int getLukumaara(){
        return alkiot.size();
    }

    /**
     * Palauttaa kaikki transkriptiot
     * @return kaikki transkriptiot
     */
    public List<Transkriptio> getAlkiot(){
        List<Transkriptio> kaikki = new ArrayList<Transkriptio>();
        for(Transkriptio trans : alkiot){
            kaikki.add(trans);
        }
        return kaikki;
    }

    /**
     * Haetaan tiettyä id:tä vastaava transkriptio
     * @param idNumero mitä id:tä haetaan
     * @return transkriptio joka vastaa tiettyä id:t
     */
    public Transkriptio anna(int idNumero){
        for( Transkriptio vastaa : alkiot){
            if (vastaa.getIdNumero() == idNumero) return vastaa;
        }
        return null;
    }

    /**
     * Iteraattori transkriptioiden läpi käymiseen
     * @return iteraattori
     * @example
     *

     * #PACKAGEIMPORT
     * #import java.util.*;
     * Transkriptiot trans = new Transkriptiot();
     * Transkriptio t1 = new Transkriptio(); t1.rekisteroi(); trans.lisaa(t1);
     * Transkriptio t2 = new Transkriptio(); t2.rekisteroi(); trans.lisaa(t2);
     * Transkriptio t3 = new Transkriptio(); t3.rekisteroi(); trans.lisaa(t3);
     * Transkriptio t4 = new Transkriptio(); t4.rekisteroi(); trans.lisaa(t4);
     *
     * Iterator<Transkriptio> transi = trans.iterator();
     * transi.next() === t1;
     * transi.next() === t2;
     * transi.next() === t3;
     * transi.next() === t4;
     *
     * int[] taulukko = {1, 2, 3, 4};
     * int i = 0;
     *
     * for ( Transkriptio t : trans){
     *     t.getIdNumero() === taulukko[i];
     *     i++;
     *  }
     *
     * trans.anna(1) === t1;
     * trans.anna(5) === null;
     *
     * List<Transkriptio> kaikki = trans.getAlkiot();
     * kaikki.size() === 4;
     *
     *

     */
    @Override
    public Iterator<Transkriptio> iterator() {
        return alkiot.iterator();
    }

    /**
     * Asetetaan tiedoston nimi
     * @param nimi tiedoston nimi
     */
    public void setTiedostonPerusNimi(String nimi) {
        tiedostonPerusNimi = nimi;

    }

    /**
     * Hakee transkriptiot tiedostosta
     * @param nimi tiedoston nimi
     * @throws SailoException Jos ei aukea
     * @example
     *

     * #THROWS SailoException
     * #import java.io.File;
     * Transkriptiot transtesti = new Transkriptiot();
     * Transkriptio t1 = new Transkriptio();
     * Transkriptio t2 = new Transkriptio();
     * t1.vastaaBad();
     * t2.vastaaBad();
     * String hakemisto = "pvktranstesti";
     * String tnimi = hakemisto+"/transkriptiot";
     * File dir = new File(hakemisto);
     * File tiedosto = new File(tnimi+".dat");
     * dir.mkdir();
     * tiedosto.delete();
     * transtesti.haeTranskriptiot(tnimi); #THROWS SailoException
     * transtesti.lisaa(t1);
     * transtesti.lisaa(t2);
     * transtesti.tallenna();
     * transtesti = new Transkriptiot();
     * transtesti.haeTranskriptiot(tnimi);
     *
     * Iterator<Transkriptio> i1 = transtesti.iterator();
     * i1.next().toString().equals(t1.toString()) === true;
     * i1.next().toString().equals(t2.toString()) === true;
     *
     * tiedosto.delete() === true;
     * dir.delete() === true;
     *
     *

     */
    public void haeTranskriptiot(String nimi) throws SailoException {
        setTiedostonPerusNimi(nimi);
        try(Scanner fi = new Scanner(new FileInputStream(new File(getTiedostonNimi())))){
            while(fi.hasNext()){
                String rivi = fi.nextLine();
                rivi = rivi.trim();
                Transkriptio trans = new Transkriptio();
                trans.asetaKentat(rivi);
                lisaa(trans);
            }
        }catch (FileNotFoundException e) {
            throw new SailoException("Tiedosto ei aukea.");
        }
    }

    /**
     * Hakee tiedoston nimeä vastaavat harjoitukset
     * @throws SailoException jos liikaa jäseniä
     */
    public void haeTranskriptiot() throws SailoException{
        haeTranskriptiot(getTiedostonPerusnimi());
    }

    /**
     * Palauttaa tiedoston nimen, jota käytetään tallennukseen
     * @return tallennustiedoston nimi
     */
    public String getTiedostonNimi() {
        return tiedostonPerusNimi + ".dat";
    }

    /**
     * Kysyy tallennustiedoston nimen ilman päätettä
     * @return nimi
     */
    public String getTiedostonPerusnimi(){
        return tiedostonPerusNimi;
    }

    /**
     * @throws SailoException jos epäonnistuu
     */
    public void tallenna()throws SailoException {
        File tiedNimi = new File(getTiedostonNimi());
        try( PrintWriter fo = new PrintWriter(new FileWriter(tiedNimi.getCanonicalPath()))) {
            for(Iterator<Transkriptio> i = alkiot.iterator(); i.hasNext();){
                fo.println( i.next());
            }
        }
        catch ( FileNotFoundException ex){
            System.err.println("Tiedosto ei aukea: " + ex.getMessage());
        } catch (IOException e) {
            System.err.println(e.getMessage());
        }

    }

    /**
     * kokeilupääohjelma
     * @param args ei käytössä
     */
    public static void main(String[] args) {
        Transkriptiot transkriptiot = new Transkriptiot();

        Transkriptio badmama1 = new Transkriptio();
        Transkriptio badmama2 = new Transkriptio();

        badmama1.vastaaBad();
        badmama2.vastaaBad();

        badmama1.rekisteroi();
        badmama2.rekisteroi();

        transkriptiot.lisaa(badmama1);
        transkriptiot.lisaa(badmama2);

        System.out.println("===== transkriptiot-testi(iteraattori) =====");
        for(Iterator<Transkriptio> i = transkriptiot.iterator(); i.hasNext();){
            Transkriptio t = i.next();
            System.out.println(t);
        }
    }

}
<file_sep>/src/paivakirja/SailoException.java

package paivakirja;

/**
 * @author tonipikkarainen
 * @version 23.2.2016
 *
 */
public class SailoException extends Exception {
    private static final long serialVersionUID = 1L;

    /**
     * Poikkeuksen muodostaja
     * @param viesti viesti, joka halutaan näyttää
     */
    public SailoException(String viesti){
        super(viesti);
    }

}
<file_sep>/src/paivakirja/HarjoitusTest.java
package paivakirja;
// Generated by ComTest BEGIN
import paivakirja.*;
import static org.junit.Assert.*;
import org.junit.*;
// Generated by ComTest END

/**
 * Test class made by ComTest
 * @version 2016.04.14 10:54:18 // Generated by ComTest
 *
 */
public class HarjoitusTest {

  // Generated by ComTest BEGIN
  /** testRekisteroi102 */
  @Test
  public void testRekisteroi102() {    // Harjoitus: 102
    Harjoitus harj1 = new Harjoitus();
    assertEquals("From: Harjoitus line: 105", 0, harj1.getIdNumero());
    harj1.rekisteroi();
    Harjoitus harj2 = new Harjoitus();
    harj2.rekisteroi();
    int a = harj1.getIdNumero();
    int b = harj2.getIdNumero();
    assertEquals("From: Harjoitus line: 111", 1, b - a);
    harj1.asetaKentat("  3|1.1.2013|sointu|test|testi|110  ");
    assertEquals("From: Harjoitus line: 113", true, harj1.toString().equals("3|1.1.2013|sointu|test|testi|110"));
  } // Generated by ComTest END
}

repo_language: Java


text:
<repo_name>tanookiben/chronos<file_sep>/test/models/photo_test.exs
defmodule Chronos.PhotoTest do
  use Chronos.ModelCase

  alias Chronos.Photo

  @valid_attrs %{event_id: "some content", s3_path: "some content", uploader: "some content"}
  @invalid_attrs %{}

  test "changeset with valid attributes" do
    changeset = Photo.changeset(%Photo{}, @valid_attrs)
    assert changeset.valid?
  end

  test "changeset with invalid attributes" do
    changeset = Photo.changeset(%Photo{}, @invalid_attrs)
    refute changeset.valid?
  end
end
<file_sep>/web/models/event.ex
defmodule Chronos.Event do
  use Chronos.Web, :model

  @primary_key {:id, :binary_id, autogenerate: true}
  @derive {Phoenix.Param, key: :id}

  schema "events" do
    field :name, :string
    field :start_date, :date
    field :end_date, :date
    field :description, :string
    field :location, :string

    timestamps()
  end

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:name, :start_date, :end_date, :description, :location])
    |> validate_required([:name, :start_date, :end_date, :description, :location])
  end
end
<file_sep>/web/models/user.ex
defmodule Chronos.User do
  use Chronos.Web, :model

  @primary_key {:id, :binary_id, autogenerate: true}
  @derive {Phoenix.Param, key: :id}

  schema "users" do
    field :email, :string
    field :password, :string

    timestamps()
  end

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:email, :password])
    |> validate_required([:email, :password])
    |> encrypt_password()
  end

  def encrypt_password(changeset) do
    raw = changeset.changes[:password]
    if is_nil(raw) do
      changeset
    else
      change(changeset, %{password: <PASSWORD>(raw)})
    end
  end

  def authenticate(user, password) do
    Comeonin.Bcrypt.checkpw(password, <PASSWORD>)
  end
end
<file_sep>/test/controllers/photo_controller_test.exs
defmodule Chronos.PhotoControllerTest do
  use Chronos.ConnCase

  alias Chronos.Photo
  # @valid_attrs %{s3_path: "some content", uploader: "some content", event_id: "11111111-1111-1111-1111-111111111111"}
  # @invalid_attrs %{uploader: 1234}

  test "renders form for new resources", %{conn: conn} do
    {:ok, user} = Chronos.Repo.insert(Chronos.User.changeset(%Chronos.User{email: "email", password: "<PASSWORD>"}))
    conn = guardian_login(user) |> get(photo_path(conn, :new))
    assert html_response(conn, 200) =~ "New photo"
  end

  # test "creates resource and redirects when data is valid", %{conn: conn} do
  #   {:ok, user} = Chronos.Repo.insert(Chronos.User.changeset(%Chronos.User{email: "email", password: "<PASSWORD>"}))
  #   conn = guardian_login(user) |> post(photo_path(conn, :create), photo: @valid_attrs)
  #   assert redirected_to(conn) == photo_path(conn, :index)
  #   assert Repo.get_by(Photo, @valid_attrs)
  # end

  # test "does not create resource and renders errors when data is invalid", %{conn: conn} do
  #   {:ok, user} = Chronos.Repo.insert(Chronos.User.changeset(%Chronos.User{email: "email", password: "<PASSWORD>"}))
  #   conn = guardian_login(user) |> post(photo_path(conn, :create), photo: @invalid_attrs)
  #   assert html_response(conn, 200) =~ "New photo"
  # end

  test "shows chosen resource", %{conn: conn} do
    {:ok, user} = Chronos.Repo.insert(Chronos.User.changeset(%Chronos.User{email: "email", password: "<PASSWORD>"}))
    photo = Repo.insert! %Photo{s3_path: "some content", uploader: "some content", event_id: "11111111-1111-1111-1111-111111111111"}
    conn = guardian_login(user) |> get(photo_path(conn, :show, photo))
    assert html_response(conn, 200) =~ "Show photo"
  end

  test "deletes chosen resource", %{conn: conn} do
    {:ok, user} = Chronos.Repo.insert(Chronos.User.changeset(%Chronos.User{email: "email", password: "<PASSWORD>"}))
    photo = Repo.insert! %Photo{s3_path: "some content", uploader: "some content", event_id: "11111111-1111-1111-1111-111111111111"}
    conn = guardian_login(user) |> delete(photo_path(conn, :delete, photo))
    assert redirected_to(conn) == event_path(conn, :index)
    refute Repo.get(Photo, photo.id)
  end
end
<file_sep>/test/views/layout_view_test.exs
defmodule Chronos.LayoutViewTest do
  use Chronos.ConnCase, async: true
end
<file_sep>/web/views/page_view.ex
defmodule Chronos.PageView do
  use Chronos.Web, :view
end
<file_sep>/web/controllers/photo_controller.ex
defmodule Chronos.PhotoController do
  use Chronos.Web, :controller

  plug Guardian.Plug.EnsureAuthenticated, handler: Chronos.AuthHandler

  alias Chronos.Photo

  def new(conn, _params) do
    changeset = Photo.changeset(%Photo{})
    render(conn, "new.html", changeset: changeset)
  end

  def create(conn, %{"photo" => photo_params}) do
    upload = photo_params["upload"]
    case File.read(upload.path) do
      {:ok, bin} ->
        path = "photos/#{UUID.uuid4(:hex)}#{Path.extname(upload.filename)}"
        case ExAws.S3.put_object("chronos-timeline", path, bin, acl: :public_read) |> ExAws.request() do
          {:ok, _} ->
            photo = %Photo{uploader: Guardian.Plug.current_resource(conn).email, s3_path: path}
            changeset = Photo.changeset(photo, photo_params)
            case Repo.insert(changeset) do
              {:ok, _photo} ->
                conn
                |> put_flash(:info, "Photo created successfully.")
                |> redirect(to: event_path(conn, :index))
              {:error, changeset} ->
                render(conn, "new.html", changeset: changeset)
            end
          _ ->
            conn
            |> put_flash(:error, "Unable to put object to S3")
            |> render("new.html", changeset: Photo.changeset(%Photo{}))
        end
      _ ->
        conn
        |> put_flash(:error, "Unable to read file")
        |> render("new.html", changeset: Photo.changeset(%Photo{}))
    end
  end

  def show(conn, %{"id" => id}) do
    photo = Repo.get!(Photo, id)
    render(conn, "show.html", photo: photo)
  end

  def delete(conn, %{"id" => id}) do
    photo = Repo.get!(Photo, id)

    # Here we use delete! (with a bang) because we expect
    # it to always work (and if it does not, it will raise).
    Repo.delete!(photo)

    conn
    |> put_flash(:info, "Photo deleted successfully.")
    |> redirect(to: event_path(conn, :index))
  end
end
<file_sep>/web/router.ex
defmodule Chronos.Router do
  use Chronos.Web, :router

  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_flash
    plug :protect_from_forgery
    plug :put_secure_browser_headers

    plug Guardian.Plug.VerifySession
    plug Guardian.Plug.LoadResource
  end

  pipeline :api do
    plug :accepts, ["json"]
  end

  scope "/", Chronos do
    pipe_through :browser

    get "/", PageController, :index
    resources "/users", UserController
    resources "/events", EventController
    resources "/photos", PhotoController, only: [:new, :create, :show, :delete]
  end

  scope "/auth", Chronos do
    pipe_through :browser

    get "/login", AuthController, :login
    post "/login", AuthController, :login_callback

    get "/signup", AuthController, :signup
    post "/signup", AuthController, :signup_callback

    post "/logout", AuthController, :logout
  end

  # Other scopes may use custom stacks.
  # scope "/api", Chronos do
  #   pipe_through :api
  # end
end
<file_sep>/web/controllers/page_controller.ex
defmodule Chronos.PageController do
  use Chronos.Web, :controller

  plug Guardian.Plug.EnsureAuthenticated, handler: Chronos.AuthHandler

  def index(conn, _params) do
    render conn, "index.html", user: Guardian.Plug.current_resource(conn)
  end
end
<file_sep>/test/models/event_test.exs
defmodule Chronos.EventTest do
  use Chronos.ModelCase

  alias Chronos.Event

  @valid_attrs %{description: "some content", end_date: Ecto.Date.cast!("2017-01-02"), location: "some content", name: "some content", start_date: Ecto.Date.cast!("2017-01-01")}
  @invalid_attrs %{}

  test "changeset with valid attributes" do
    changeset = Event.changeset(%Event{}, @valid_attrs)
    assert changeset.valid?
  end

  test "changeset with invalid attributes" do
    changeset = Event.changeset(%Event{}, @invalid_attrs)
    refute changeset.valid?
  end
end
<file_sep>/web/views/auth_view.ex
defmodule Chronos.AuthView do
  use Chronos.Web, :view
end
<file_sep>/web/controllers/auth_controller.ex
defmodule Chronos.AuthController do
  use Chronos.Web, :controller

  plug Guardian.Plug.EnsureNotAuthenticated, handler: Chronos.AuthHandler, except: [:logout]

  alias Chronos.User

  def login(conn, _params) do
    changeset = User.changeset(%User{})
    action = auth_path(conn, :login_callback)
    render(conn, "login.html", changeset: changeset, action: action)
  end

  def login_callback(conn, %{"user" => %{"email" => email, "password" => password}}) do
    changeset = User.changeset(%User{email: email})
    query = User |> where([u], u.email == ^email)
    user = Repo.one(query)
    if is_nil(user) || !User.authenticate(user, password) do
      conn
      |> put_flash(:error, "Sorry, we weren't able to log you in")
      |> render("login.html", changeset: changeset, action: auth_path(conn, :login_callback))
    else
      conn
      |> Guardian.Plug.sign_in(user)
      |> put_flash(:info, "You have successfully logged in")
      |> redirect(to: "/")
    end
  end

  def signup(conn, _params) do
    changeset = User.changeset(%User{})
    action = auth_path(conn, :signup_callback)
    render(conn, "signup.html", changeset: changeset, action: action)
  end

  def signup_callback(conn, %{"user" => user_params}) do
    changeset = User.changeset(%User{}, user_params)

    case Repo.insert(changeset) do
      {:ok, _user} ->
        conn
        |> put_flash(:info, "Please sign in with your new account")
        |> redirect(to: "/auth/login")
      {:error, changeset} ->
        action = auth_path(conn, :signup_callback)
        render(conn, "signup.html", changeset: changeset, action: action)
    end
  end

  def logout(conn, _params) do
    conn
    |> Guardian.Plug.sign_out
    |> put_flash(:info, "You have successfully logged out")
    |> redirect(to: "/")
  end
end
<file_sep>/web/models/photo.ex
defmodule Chronos.Photo do
  use Chronos.Web, :model

  @primary_key {:id, :binary_id, autogenerate: true}
  @derive {Phoenix.Param, key: :id}

  schema "photos" do
    field :event_id, :binary_id
    field :uploader, :string
    field :s3_path, :string

    timestamps()
  end

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:event_id, :uploader, :s3_path])
    |> validate_required([:event_id, :uploader, :s3_path])
  end
end
<file_sep>/test/views/page_view_test.exs
defmodule Chronos.PageViewTest do
  use Chronos.ConnCase, async: true
end
<file_sep>/web/views/event_view.ex
defmodule Chronos.EventView do
  use Chronos.Web, :view
end
<file_sep>/test/test_helper.exs
ExUnit.start

Ecto.Adapters.SQL.Sandbox.mode(Chronos.Repo, :manual)

<file_sep>/config/config.exs
# This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
use Mix.Config

# General application configuration
config :chronos,
  ecto_repos: [Chronos.Repo]

# Configures the endpoint
config :chronos, Chronos.Endpoint,
  url: [host: "localhost"],
  secret_key_base: "<KEY>",
  render_errors: [view: Chronos.ErrorView, accepts: ~w(html json)],
  pubsub: [name: Chronos.PubSub,
           adapter: Phoenix.PubSub.PG2]

# Configures Elixir's Logger
config :logger, :console,
  format: "$time $metadata[$level] $message\n",
  metadata: [:request_id]

# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env}.exs"

config :guardian, Guardian,
  allowed_algos: ["HS512"],
  verify_module: Guardian.JWT,
  issuer: "Chronos",
  ttl: {7, :days},
  allowed_drift: 2000,
  verify_issuer: true,
  secret_key: "<KEY>",
  serializer: Chronos.GuardianSerializer
<file_sep>/test/controllers/page_controller_test.exs
defmodule Chronos.PageControllerTest do
  use Chronos.ConnCase
end
<file_sep>/priv/repo/migrations/20170516053425_create_photo.exs
defmodule Chronos.Repo.Migrations.CreatePhoto do
  use Ecto.Migration

  def change do
    create table(:photos, primary_key: false) do
      add :id, :binary_id, primary_key: true
      add :event_id, :binary_id, null: false
      add :uploader, :string, null: false
      add :s3_path, :string, null: false

      timestamps()
    end

  end
end
<file_sep>/web/controllers/auth_handler.ex
defmodule Chronos.AuthHandler do
  use Chronos.Web, :controller

  def unauthenticated(conn, _params) do
    conn
    |> put_flash(:error, "You must be logged in to do that")
    |> redirect(to: "/auth/login")
  end

  def already_authenticated(conn, _params) do
    conn
    |> put_flash(:error, "You must be logged out to do that")
    |> redirect(to: "/")
  end
end
<file_sep>/test/controllers/event_controller_test.exs
defmodule Chronos.EventControllerTest do
  use Chronos.ConnCase

  alias Chronos.Event
  @valid_attrs %{description: "some content", end_date: Ecto.Date.cast!("2017-01-02"), location: "some content", name: "some content", start_date: Ecto.Date.cast!("2017-01-01")}
  @invalid_attrs %{name: 1234}

  test "lists all entries on index", %{conn: conn} do
    {:ok, user} = Chronos.Repo.insert(Chronos.User.changeset(%Chronos.User{email: "email", password: "<PASSWORD>"}))
    conn = guardian_login(user) |> get(event_path(conn, :index))
    assert html_response(conn, 200) =~ "Listing events"
  end

  test "renders form for new resources", %{conn: conn} do
    {:ok, user} = Chronos.Repo.insert(Chronos.User.changeset(%Chronos.User{email: "email", password: "<PASSWORD>"}))
    conn = guardian_login(user) |> get(event_path(conn, :new))
    assert html_response(conn, 200) =~ "New event"
  end

  test "creates resource and redirects when data is valid", %{conn: conn} do
    {:ok, user} = Chronos.Repo.insert(Chronos.User.changeset(%Chronos.User{email: "email", password: "<PASSWORD>"}))
    conn = guardian_login(user) |> post(event_path(conn, :create), event: @valid_attrs)
    assert redirected_to(conn) == event_path(conn, :index)
    assert Repo.get_by(Event, @valid_attrs)
  end

  test "does not create resource and renders errors when data is invalid", %{conn: conn} do
    {:ok, user} = Chronos.Repo.insert(Chronos.User.changeset(%Chronos.User{email: "email", password: "<PASSWORD>"}))
    conn = guardian_login(user) |> post(event_path(conn, :create), event: @invalid_attrs)
    assert html_response(conn, 200) =~ "New event"
  end

  test "shows chosen resource", %{conn: conn} do
    {:ok, user} = Chronos.Repo.insert(Chronos.User.changeset(%Chronos.User{email: "email", password: "<PASSWORD>"}))
    event = Repo.insert! %Event{description: "some content", end_date: Ecto.Date.cast!("2017-01-02"), location: "some content", name: "some content", start_date: Ecto.Date.cast!("2017-01-01")}
    conn = guardian_login(user) |> get(event_path(conn, :show, event))
    assert html_response(conn, 200) =~ "Show event"
  end

  test "renders form for editing chosen resource", %{conn: conn} do
    {:ok, user} = Chronos.Repo.insert(Chronos.User.changeset(%Chronos.User{email: "email", password: "<PASSWORD>"}))
    event = Repo.insert! %Event{description: "some content", end_date: Ecto.Date.cast!("2017-01-02"), location: "some content", name: "some content", start_date: Ecto.Date.cast!("2017-01-01")}
    conn = guardian_login(user) |> get(event_path(conn, :edit, event))
    assert html_response(conn, 200) =~ "Edit event"
  end

  test "updates chosen resource and redirects when data is valid", %{conn: conn} do
    {:ok, user} = Chronos.Repo.insert(Chronos.User.changeset(%Chronos.User{email: "email", password: "<PASSWORD>"}))
    event = Repo.insert! %Event{description: "some content", end_date: Ecto.Date.cast!("2017-01-02"), location: "some content", name: "some content", start_date: Ecto.Date.cast!("2017-01-01")}
    conn = guardian_login(user) |> put(event_path(conn, :update, event), event: @valid_attrs)
    assert redirected_to(conn) == event_path(conn, :show, event)
    assert Repo.get_by(Event, @valid_attrs)
  end

  test "does not update chosen resource and renders errors when data is invalid", %{conn: conn} do
    {:ok, user} = Chronos.Repo.insert(Chronos.User.changeset(%Chronos.User{email: "email", password: "<PASSWORD>"}))
    event = Repo.insert! %Event{description: "some content", end_date: Ecto.Date.cast!("2017-01-02"), location: "some content", name: "some content", start_date: Ecto.Date.cast!("2017-01-01")}
    conn = guardian_login(user) |> put(event_path(conn, :update, event), event: @invalid_attrs)
    assert html_response(conn, 200) =~ "Edit event"
  end

  test "deletes chosen resource", %{conn: conn} do
    {:ok, user} = Chronos.Repo.insert(Chronos.User.changeset(%Chronos.User{email: "email", password: "<PASSWORD>"}))
    event = Repo.insert! %Event{description: "some content", end_date: Ecto.Date.cast!("2017-01-02"), location: "some content", name: "some content", start_date: Ecto.Date.cast!("2017-01-01")}
    conn = guardian_login(user) |> delete(event_path(conn, :delete, event))
    assert redirected_to(conn) == event_path(conn, :index)
    refute Repo.get(Event, event.id)
  end
end
<file_sep>/web/templates/photo/show.html.eex

Show photo

    Event:
    <%= @photo.event_id %>

    Uploader:
    <%= @photo.uploader %>

    S3 path:
    <%= @photo.s3_path %>

<file_sep>/web/views/photo_view.ex
defmodule Chronos.PhotoView do
  use Chronos.Web, :view
end
<file_sep>/web/views/user_view.ex
defmodule Chronos.UserView do
  use Chronos.Web, :view
end
<file_sep>/web/templates/layout/app.html.eex
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="">

  <title>The God of Time</title>
  <link rel="stylesheet" href="<%= static_path(@conn, "/css/app.css") %>">

      <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

      </button>
      Chronos

        <%= form_for @conn, auth_path(@conn, :logout), [as: :logout],  fn _ -> %>
          <%= submit "Log Out", class: "btn btn-primary btn-sm align-middle" %>
        <% end %>

        <%= if !is_nil(get_flash(@conn, :info)) do %>

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
              ×
            </button>
            <%= get_flash(@conn, :info) %>

        <% end %>

        <%= if !is_nil(get_flash(@conn, :error)) do %>

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
              ×
            </button>
            <%= get_flash(@conn, :error) %>

        <% end %>

        <%= render @view_module, @view_template, assigns %>

<file_sep>/lib/chronos/repo.ex
defmodule Chronos.Repo do
  use Ecto.Repo, otp_app: :chronos
end
<file_sep>/web/views/layout_view.ex
defmodule Chronos.LayoutView do
  use Chronos.Web, :view
end

languages: Elixir HTML+EEX

repo_language: Elixir

repo_name: tanookiben/chronos


text:
<repo_name>AbhayPai/covid19-stats<file_sep>/README.md
# CoronaVirus (covid-19) Statistics

* [Live update](https://abhaypai.github.io/covid19-stats/)

[![Desktop](https://abhaypai.github.io/covid19-stats/docs/desktop.png)](https://abhaypai.github.io/covid19-stats/)

[![Mobile](https://abhaypai.github.io/covid19-stats/docs/mobile.png)](https://abhaypai.github.io/covid19-stats/)

repo_language: Markdown


text:
<repo_name>Fredpwol/MiCOIN<file_sep>/README.md
# MiCoin

Micoin is a minimalistic implementation of a decentralize blockchain system it's was created for educational purpose and is not production ready although it has all the core blockchain features like :
- proof of work
- cocensus
- block hashing
- Node peer network
- Transaction signature

In the future I'd like to make nodes websockets and store blockchain data in a  noSQL database like mongoDB.

## Usage
To get started clone this repo using ` git clone ` after that install the dependecies using `pip install -r requiment.txt`. After all the dependecies have been installed, spawn a node using `python node.py -p [port_num]` to start a node server on your localhost:port_num.

![start node server](assets/node_start.png)

Navigate on your browser to `localhost:port_num` on the page create a wallet. your public key is what will be used for transactions you can mine to earn coin, if another node server is created navigate to the network page and add that server as a peer node so that all nodes can sync their data. node data are stored locally so next time you open start a server with the same port name click on the load wallet button to load wallet data of that port value.

## license
Usage of this project is by regulated by [MIT](LICENSE)

repo_name: Fredpwol/MiCOIN


text:
<file_sep><template>

	    <router-link v-if="this.$route.path !== '/'" class="btn btn-default" :to="{ name: 'login' }">Kembali Ke Halaman Login</router-link>
	    <router-link v-if="this.$route.path !== '/register'" class="btn btn-default" :to="{ name: 'register' }">Form Pendaftaran</router-link>

</template><file_sep><template>

There was an error, unable to sign in with those credentials.

            <form autocomplete="off" @submit.prevent="login"  class="form-signin" method="post">

Login

                    E-mail
                    <input type="email" id="email" class="form-control" placeholder="<EMAIL>" v-model="email" required>

                    Password
                    <input type="<PASSWORD>" id="password" class="form-control" v-model="password" required>

                      <button class="btn btn-primary" type="submit">Login</button>

                    <MenuLogin />

            </form>

</template>

<file_sep><template>

There was an error, unable to complete registration.

Registration completed. You can now <router-link :to="{name:'login'}">sign in.</router-link>

            <form autocomplete="off" class="form-signin" @submit.prevent="register" v-if="!success" method="post">

Pendaftaran

                    Name
                    <input type="text" id="name" class="form-control" v-model="name" required>
                    {{ errors.name }}

                    E-mail
                    <input type="email" id="email" class="form-control" placeholder="<EMAIL>" v-model="email" required>
                    {{ errors.email }}

                    Password
                    <input type="<PASSWORD>" id="password" class="form-control" v-model="password" required>
                    {{ errors.password }}

                      <button class="btn btn-primary" type="submit">Daftar</button>

                    <MenuLogin />

            </form>

</template>

repo_language: Vue

repo_name: rabkawork/laravel-vuejs-auth


text:
<file_sep>import os
import re
import linecache
import fileinput
from os.path import basename

#values i want from UnitBalance.slk
kvdict_bal = {
'X23': '"StatusHealth"',
'X25': '"StatusHealthRegen"',
'X27': '"StatusMana"',
'X30': '"StatusManaRegen"',
'X31': '"ArmorPhysical"',
'X35': '"MovementSpeed"',
'X40': '"VisionDaytimeRange"',
'X41': '"VisionNighttimeRange"',
'X42': '"AttributeBaseStrength"',
'X43': '"AttributeBaseIntelligence"',
'X44': '"AttributeBaseAgility"',
'X45': '"AttributeStrengthGain"',
'X46': '"AttributeIntelligenceGain"',
'X47': '"AttributeAgilityGain"',
'X49': '"AttributePrimary"',
}

kvdict_data = {'X15': '"MovementTurnRate"'}

kvdict_weapons = {
'X6': '"AttackAcquisitionRange"',
'X19': '"AttackRange"',
'X22': '"CombatClassAttack"',
'X23': '"AttackCapabilities"',
'X24': '"AttackRate"',
'X30': '"AttackDamageMin"',
'X32': '"AttackDamageMax"',
'X33': '"AttackAnimationPoint"',
'X0': '"AbilityUnitDamageType"'
}

fileout = open("npc_units_custom.txt", 'a')

__location__ = os.path.realpath(
    os.path.join(os.getcwd(), os.path.dirname(__file__)))

namedict = {}
unitNames = {}
slks = []

#dictionary cointaining position of all 'y' columns
#in unitbalance.slk, *data, *weapons
#bravery

bCols = {}
dCols = {}
uCols = {}
wCols = {}

#gets the proper unit names to replace 4 char wc3 unit ids
for sf in os.listdir(os.getcwd()):
    if 'UnitStrings' in basename(sf):
        f = open(sf)
        for line in f:
            if '[' in line[0]:
                unitID = line[1:-2]
                namedict[unitID] = re.sub("[^a-zA-Z 0-9]", "", next(f)[5:])
    if '.slk' in basename(sf):
        slks.append(sf)

unitIndex = 0

#find how many units total
unitMax = int(linecache.getline("UnitBalance.slk", 2).split('Y')[1].split(';')[0])

text = ''

#gets the line number of each new row for unitbalance, unitdata, unitweapons.
f = open("UnitBalance.slk")
for num, line in enumerate(f):
    k, temp, v = line[2:].partition(';')
    if 'PWXL' in v:
        continue
    if 'Y' in k or 'Y' and ';K' in v or 'Y2;'in v:
        bCols[unitIndex] = num
        unitIndex = unitIndex + 1

unitIndex = 0

f = open("UnitData.slk")
for num, line in enumerate(f):
    k, temp, v = line[2:].partition(';')
    if 'PWXL' in v:
        continue
    if 'Y' in k or 'Y' and ';K' in v or 'Y2;'in v:
        dCols[unitIndex] = num
        unitIndex = unitIndex + 1

f = open("UnitUI.slk")
for line in f:
    k, temp, v = line[2:].partition(';')
    if 'PWXL' in v:
        continue
    if 'X8' in k:
        uCols[unitIndex] = num
        unitIndex = unitIndex + 1

unitIndex = 0

f = open("UnitWeapons.slk")
for num, line in enumerate(f):
    k, temp, v = line[2:].partition(';')
    if 'PWXL' in v:
        continue
    if 'Y' in k or 'Y' and ';K' in v or 'Y2;'in v:
        wCols[unitIndex] = num
        unitIndex = unitIndex + 1

unitIndex = 1

#make a dict of all unit names and their corresponding ids
f = open("UnitBalance.slk")
for num, line in enumerate(f):
    k, temp, v = line[2:].partition(';')
    if re.sub("[^a-zA-Z 0-9]", "", v)[1:] in namedict and num > 64:
       # print(k)
        v = namedict[((re.sub("[^a-zA-Z 0-9]", "", v))[1:])]
        unitNames[unitIndex] = v
        unitIndex = unitIndex + 1

#for each unit, currently limited at 5 for testing, use unitMax if you want all of them
for i in range (1, unitMax - 2):
   # print("Writing unit " + str(i) + "/" + str(unitMax - 2))

    fileout.write('"' + re.sub(" ", "_", unitNames[i]) + '"' + '\n' + '{' + '\n')
    #for each possible value
    for num in range(bCols[i], bCols[i + 1]):

            #get the line from bCols, which stores the occurence of each new row after the first lot of
            #definitions and other crap, print bCols to see them
            k, temp, v = linecache.getline("UnitBalance.slk", num)[2:].partition(';')

            #if its a stat change the v/value to correct in dota kv style
            if k == 'X49':
                if '_' in v:
                    k = 'NO'
                if 'INT' in v:
                    v = ' DOTA_ATTRIBUTE_INTELLECT'
                if 'STR' in v:
                    v = ' DOTA_ATTRIBUTE_STRENGTH'
                if 'AGI' in v:
                    v = ' DOTA_ATTRIBUTE_AGILITY'
            #if the key is one we are looking for, as defined in kvdict_bal
            if k in kvdict_bal:
                v = v.lstrip ('K')
                #print("num is " + str(num) + " k is " + k + " v is " + v + " bCols[i] is " + str(bCols[i]) + "num + bcols / line is " + str(bCols[i] + num))
                #forgot what this regex does exactly lmao think it tabs it twice, writes the key,
                #puts a " then wirte the value then another " then removes the new line, since
                #i think write makes one anyway
                text = ('\t\t' + kvdict_bal[k] + '\t' + '\"' + v.strip("\r\n") + '\"' + '\n')
                fileout.write(text)
                linecache.clearcache()

    for num in range(dCols[i], dCols[i + 1]):

            k, temp, v = linecache.getline("UnitData.slk", num)[2:].partition(';')

            if k in kvdict_data:
                v = v.lstrip('K')
                text = ('\t\t' + kvdict_data[k] + '\t' + '\"' + v.strip("\r\n") + '\"' + '\n')
                fileout.write(text)
                linecache.clearcache()

    for num in range(wCols[i], wCols[i + 1]):

            k, temp, v = linecache.getline("UnitWeapons.slk", num)[2:].partition(';')

            if k == 'X22':
                if 'hero' in v:
                    v = 'DOTA_COMBAT_CLASS_ATTACK_HERO'
                if 'pierce' in v:
                    v = 'DOTA_COMBAT_CLASS_ATTACK_PIERCE'
                if 'normal' in v:
                    v = 'DOTA_COMBAT_CLASS_ATTACK_BASIC'
                if 'magic' in v:
                    k = 'X0'
                    v = 'DAMAGE_TYPE_MAGICAL'
                if 'siege' in v:
                    v = 'DOTA_COMBAT_CLASS_ATTACK_SIEGE'
                if 'chaos' in v:
                    k = 'X0'
                    v = 'DAMAGE_TYPE_PURE'

            if k == 'X23':
                if '_' in  v:
                    v = 'DOTA_UNIT_CAP_NO_ATTACK'
                elif 'normal' in v:
                    v = 'DOTA_UNIT_CAP_MELEE_ATTACK'
                elif 'missile' or 'artillery' in  v:
                    v = 'DOTA_UNIT_CAP_RANGED_ATTACK'

            if k in kvdict_weapons:
                v = v.lstrip('K')
                text = ('\t\t' + kvdict_weapons[k] + '\t' + '\"' + v.strip("\r\n") + '\"' + '\n')
                fileout.write(text)
                linecache.clearcache()
    fileout.write('}' + '\n')

repo_language: Python


text:
<repo_name>yanislav-igonin/websockets-example<file_sep>/src/client/actions/dataActions.js
export const dataActions = {

    dataUpdate(data) {
        const payload = data;

        return {
            type: 'DATA_UPDATE',
            payload,
        };
    },
};
<file_sep>/src/server/routes/api.js
const path = require('path');

const dataMethods = require('../api/db/dataMethods');

module.exports = (app, db) => {
    app.get('/api/data', (req, res) => {
        dataMethods
        .getData(db)
        .then(data => res.send(data));
    });
};<file_sep>/src/client/reducers/index.js
import { combineReducers } from 'redux';

import data from './dataReducer';

const combinedReducer = combineReducers({
    data
});

export default combinedReducer;<file_sep>/src/server/index.js
const express = require('express');
const path = require('path');
const url = require('url');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const WebSocket = require('ws');
const http = require('http');

const MongoClient = require('mongodb').MongoClient,
    assert = require('assert');

const db_url = 'mongodb://localhost:27017/express-template';

const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
const port = process.env.NODE_ENV === 'production' ? process.env.PORT : 8080;

// ///////////////////////////////////
// SERVER CONFIGURATION
// ///////////////////////////////////
if (process.env.NODE_ENV === 'production') {} else {
    const webpack = require('webpack');
    const config = require(path.join(__dirname, '../../webpack.config'));
    const compiler = webpack(config);

    app
        .use(require('webpack-dev-middleware')(compiler, {
            publicPath: config.output.publicPath,
            noInfo: true
        }))
        .use(require('webpack-hot-middleware')(compiler));
}

app
    .use(bodyParser.json())
    .use(bodyParser.urlencoded({extended: true}))
    .use(morgan('dev'));

app.use('/assets', express.static(path.join(__dirname, '../../dist/client')));

// ///////////////////////////////////
// SERVER INITIALIZATION
// ///////////////////////////////////
MongoClient.connect(db_url, (err, db) => {
    assert.equal(null, err);
    console.log("Database connected correctly to server");

    require('./routes/index')(app);
    require('./routes/api')(app, db);

    wss.on('connection', function connection(ws, req) {
        const location = url.parse(req.url, true);
        // You might use location.query.access_token to authenticate or share sessions
        // or req.headers.cookie (see http://stackoverflow.com/a/16395220/151312)
        console.log('connection');

        ws.on('message', function incoming(message) {
            console.log('received: %s', message);
        });

        const something = setInterval(() => {
            try {
                ws.send('something-' + Date.now());
            } catch (error) {
                console.log(error);
                clearTimeout(something);
            }
        }, 1000);
    });

    server.listen(port, () => {
        console.log('Server listening port %d', port);
    });
});

repo_name: yanislav-igonin/websockets-example


text:
<repo_name>sanfengAndroid/service-configure<file_sep>/README.md
# service-configure
Write the configuration of other projects.

branch_name: refs/heads/main

repo_name: sanfengAndroid/service-configure


text:
<repo_name>elozev/birdie-test<file_sep>/backend/src/config/db.ts
const Sequelize = require('sequelize');

const connection = new Sequelize('birdietest', 'test-read', 'xnxPp6QfZbCYkY8', {
    host: 'birdie-test.cyosireearno.eu-west-2.rds.amazonaws.com',
    dialect: 'mysql',
    port: 3306,
    define: {
        timestamps: false
    }
});

connection
    .authenticate()
    .then(() => {
        console.log("Successful connection to the DB!");
    })
    .catch((err: any) => {
        console.log("Error connecting to the DB: ", err);
    });

interface dbInstance {
    [x: string]: any;
    Sequelize: any,
    instance: any
}

const dbInstance : dbInstance = {
    Sequelize: Sequelize,
    instance: connection
};

dbInstance.events = require('../model/event')(Sequelize, connection);

export const db = dbInstance;<file_sep>/backend/src/model/event.ts
module.exports = (Sequelize: any, instance: any) => {

    const Event = instance.define('events', {
        payload: {
            type: Sequelize.JSON,
            allowNull: false,
            default: null
        },
        alert_id: Sequelize.UUID,
        task_instance_id: Sequelize.STRING(255),
        visit_id: Sequelize.UUID,
        caregiver_id: Sequelize.UUID,
        payload_as_text: Sequelize.TEXT,
        rejected_event_id: Sequelize.STRING(255),
        observation_event_id: Sequelize.STRING(255),
        timestamp: Sequelize.DATE,
        id: {
            type: Sequelize.UUID,
            primaryKey: true
        },
        event_type: Sequelize.STRING(50),
        care_recipient_id: Sequelize.UUID
    });

    return Event;
}<file_sep>/front-end/src/util/Fetcher.ts
import { API_URL } from './Constants';

class Fetcher {
    static async getRecipients() {
        const fetchURL = API_URL + '/recipient';
        const request = new Request(fetchURL, this.getOptionsAndHeaders());
        const response = await fetch(request);

        if (response.status === 200) {
            return await response.json();
        }
        return null;
    }

    static async getEvents(recipient: string, date: Date) {
        const fetchURL = API_URL + '/recipient/' + recipient +
            '?startDate=' + date + '&endDate=' + new Date(date.getTime() + 1000 * 60 * 60 * 24);
        const request = new Request(fetchURL, this.getOptionsAndHeaders());
        const response = await fetch(request);

        if (response.status === 200) {
            const body = await response.json();
            console.log(body);
            return body;
        }
        return null;
    }

    private static getOptionsAndHeaders() {
        const headers = new Headers();
        headers.append('Content-Type', 'application/json');

        const options = {
            method: 'GET',
            headers: headers,
        };
        return options;
    }
}

export default Fetcher;<file_sep>/front-end/src/components/DropdownList.tsx
import * as React from 'react';
import * as PropTypes from 'prop-types';
import { DropdownButton, Dropdown } from 'react-bootstrap';

interface DropdownListProps {
    recipients: Array<any>;
    changeHandler: any;
    listValue: string;
}

const DropdownList = (props: DropdownListProps) => {
    return (
        <DropdownButton
            id="dropdown-basic-button"
            title="Select Recipient"
            onSelect={props.changeHandler}
        >
            {props.recipients.map((recipient: any, index: number) => {
                return (
                    <Dropdown.Item
                        key={index}
                        eventKey={recipient.DISTINCT}
                    >
                        {recipient.DISTINCT}
                    </Dropdown.Item>);
            })}
        </DropdownButton>
    );
};

DropdownList.propTypes = {
    recipients: PropTypes.array.isRequired,
    changeHandler: PropTypes.func.isRequired,
    listValue: PropTypes.string.isRequired,
};

export default DropdownList;<file_sep>/backend/src/controllers/ping.ts
import * as express from "express";
const db = require('../config/db').db;
export const pingController = express.Router();

pingController.get('/hello', (_, res) => {
  res.status(200).json({
    greetings: 'Thank you for spending some time on this test. All the best 🙌'
  });
});

// Code for Birdie test begins here

/**
 * Retrieves all the unique recipients from the database
 */
pingController.get('/recipient', (_, res, next) => {
  db.events.aggregate('care_recipient_id', 'DISTINCT', { plain: false })
    .then((dbResult: any) => {
      res.json(dbResult);
    })
    .catch((err: any) => {
      next(err);
    });
});

const Op = db.Sequelize.Op;

/**
 * Retrieve care recipient events for particular day
 */
pingController.get('/recipient/:recipient_id', (req, res, next) => {
  console.log(`startDate = ${req.query.startDate}`);

  db.events.findAll({
    attributes: ['timestamp', 'event_type', 'payload'],
    where: {
      care_recipient_id: req.params.recipient_id,
      timestamp: {
        [Op.gt]: new Date(req.query.startDate),
        [Op.lt]: new Date(req.query.endDate)
      }
    }
  })
  .then((dbResult: any) => {
    res.status(200).json(dbResult);
  })
  .catch((err: any) => {
    next(err);
  });
});<file_sep>/backend/src/application.ts
import * as express from "express";
import * as cors from "cors";
import {pingController} from "./controllers/ping";
const app = express();

app.use(cors());
app.use(pingController);

// error handler
app.use(function (err: any, req: any, res: any) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.json({err: err.message});
});

export default app;
<file_sep>/backend/__tests__/ping.spec.ts
import app from '../src/application'
import * as request from 'supertest';

describe('We are grateful to you for doing this it.', () => {
  it('thanks you', async () => {
    await request(app)
      .get('/hello')
      .expect(200)
      .expect(function (res) {
        expect(res.body.greetings).toContain('Thank you');
      });
  })
});

describe('recipients', () => {
  it('get recipients', async () => {
    await request(app)
      .get('/recipient')
      .expect(200)
      .expect(function (res) {
        expect(res.body).toContainEqual({ "DISTINCT": "df50cac5-293c-490d-a06c-ee26796f850d" });
        expect(res.body).toContainEqual({ "DISTINCT": "e3e2bff8-d318-4760-beea-841a75f00227" });
        expect(res.body).toContainEqual({ "DISTINCT": "ad3512a6-91b1-4d7d-a005-6f8764dd0111" });
      })
  });
});

describe('events', () => {
  it('get a recipient events by a date range', async () => {
    await request(app)
      .get('/recipient/df50cac5-293c-490d-a06c-ee26796f850d?startDate=2019-05-08 01:00:01.000'
        + '&endDate=2019-05-09 01:00:00.000')
      .expect(200)
      .expect(function (res) {
        expect(res.body.length).toBeGreaterThan(2);
      });
  });
});

languages: TypeScript TSX

repo_language: TypeScript

repo_name: elozev/birdie-test


text:
<file_sep>var readlineSync = require("readline-sync");

function welcome() {
 var userName = readlineSync.question("What's your name? ");

  console.log("Welcome "+ userName + " to F.R.I.E.N.D.S. Quiz  ");
  game(userName);
}

var score = 0;

var highScores = {
    name: "Anshika",
    score: 3,
}
// array of objects
var questions = [{
  question: "Which character has a twin? ",
  options: {
    a: "Monica",
    b: "Chandler",
    c: "Phoebe"
  },
  answer: "c"
},
{
  question: "How many sisters does Joey have? ",
  options: {
    a: "8",
    b: "7",
    c: "9"
  },
  answer: "b"
},
{
  question: "What nickname did Monica’s dad give her? ",
  options: {
    a: "<NAME>monica",
    b: "Little Electronica",
    c: "Little Harmoica"
  },
  answer: "c"
},
{
  question: "What's the name of the dancer Joey lived with? ",
  options: {
    a: "Janice",
    b: "Janine",
    c: "Chandler"
  },
  answer: "b"
},
{
  question: "What’s Phoebe’s sister’s name? ",
  options: {
    a: "Ariel",
    b: "Ursula",
    c: "Janine"
  },
  answer: "b"
},
];

// play function
function play(question, answer, options) {
  console.log(question);

  for(const key in options){
    console.log(`${key}  : ${options[key]}`);
  }

  var userAnswer = readlineSync.question("Choose you option: ");

  if (userAnswer.toUpperCase() === answer.toUpperCase()) {
    console.log("right!");
    score = score + 1;
  }
  else {
    console.log("wrong!");
  }

  console.log("*--------------------------*")
  console.log("current score: ", score);
  console.log("*--------------------------*")
}

function game(userName) {
  for (var i=0; i<questions.length; i++) {
    var currentQuestion = questions[i];
    play(currentQuestion.question, currentQuestion.answer, currentQuestion.options)
  }
  showScores(userName);
}

function showScores(userName) {
  console.log("YAY! You SCORED: ", score);

  if(highScores.score <= score)
  {
    highScores.name = userName;
    highScores.score = score;
  }
  console.log("Check out the high scores!");
  console.log(highScores.name, " : ", highScores.score);
}

welcome();<file_sep># Simple Quiz Using JavaScript

- [GitHub Pages Link - Go ahead and try it out](https://anshikag0219.github.io/js-quiz/)
- [Repl Link - for terminal execution](https://replit.com/@AnshikaG0219/js-quiz)

## Challenges
#### I have multiple challenges for you this time, So go ahead and try implementing any of the following:
- Add time limit for the quiz
- Implement pagination (i.e. displaying one question at a time)
- Add different styles for results, Quiz presentation or for wrong and correct answer.
- Adding Progress Bar
- Create custom message for each level of results. For eg. 1-5 better luck next time

------------- Happy Learning ----------------------

## Resources
- [JS Array by mdn](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
- [JS Objects by mdn](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects)
- [All the event listeners by mdn](https://developer.mozilla.org/en-US/docs/Web/Events)
- [Quiz video tutorial by Thapa Technical](https://youtu.be/rGhH70KUTuk)
- [Quiz video tutorial by <NAME> (Advanced)](https://youtu.be/f4fB9Xg2JEY)<file_sep>const quizContainer = document.getElementById("quiz");
const resultsContainer = document.getElementById("results");
const submitButton = document.getElementById("submit");
const userName = document.getElementById("userName");
const welcomeText = document.querySelector("span");
const restartGame = document.getElementById("newGame");

const questions = [
  {
    question: "Which character has a twin? ",
    options: {
      a: "Monica",
      b: "Chandler",
      c: "Phoebe",
    },
    answer: "c",
  },
  {
    question: "How many sisters does Joey have? ",
    options: {
      a: "8",
      b: "7",
      c: "9",
    },
    answer: "b",
  },
  {
    question: "What nickname did Monica’s dad give her? ",
    options: {
      a: "<NAME>",
      b: "Little Electronica",
      c: "Little Harmoica",
    },
    answer: "c",
  },
  {
    question: "What's the name of the dancer Joey lived with? ",
    options: {
      a: "Janice",
      b: "Janine",
      c: "Chandler",
    },
    answer: "b",
  },
  {
    question: "What’s Phoebe’s sister’s name? ",
    options: {
      a: "Ariel",
      b: "Ursula",
      c: "Janine",
    },
    answer: "b",
  },
];

function buildQuiz() {
  // variable to store the HTML output
  const output = [];

  // for each question...
  questions.forEach((currentQuestion, questionNumber) => {
    // variable to store the list of possible answers
    const answers = [];

    // and for each available answer...
    for (key in currentQuestion.options) {
      // ...add an HTML radio button
      answers.push(
        `
            <input type="radio" name="question${questionNumber}" value="${key}">
            ${key} :
            ${currentQuestion.options[key]}
          `
      );
    }

    console.log(answers);

    // add this question and its answers to the output
    output.push(
      `
 ${currentQuestion.question}

 ${answers.join("")}
`
    );
  });

  // finally combine our output list into one string of HTML and put it on the page
  quizContainer.innerHTML = output.join("");
  console.log(output);
}

function showResults() {
  // gather answer containers from our quiz
  resultsContainer.style.height = "20vh";
  const answerContainers = quizContainer.querySelectorAll(".answers");

  // keep track of user's answers
  let score = 0;

  // for each question...
  questions.forEach((currentQuestion, questionNumber) => {
    // find selected answer
    const answerContainer = answerContainers[questionNumber];
    const selector = `input[name=question${questionNumber}]:checked`;
    const userAnswer = (answerContainer.querySelector(selector) || {}).value;

    // if answer is correct
    if (userAnswer === currentQuestion.answer) {
      // add to the number of correct answers
      score++;

      // color the answers green
      answerContainers[questionNumber].style.color = "lightgreen";
    }
    // if answer is wrong or blank
    else {
      // color the answers red
      answerContainers[questionNumber].style.color = "red";
    }
  });

  // show number of correct answers out of total
  resultsContainer.innerHTML = `Wooho! You got ${score} out of ${questions.length} correct!`;
}
buildQuiz();

// Event listeners
submitButton.addEventListener("click", showResults);
userName.addEventListener("input", () => {
  welcomeText.innerText = userName.value;
});
restartGame.addEventListener("click", () => {
  window.location.reload();
});