text:
<repo_name>deepikavashishtha/SignalApp<file_sep>/src/main/resources/data.sql
INSERT INTO TRAFFIC_HOUR (ID, name, RED_DURATION, GREEN_DURATION, AMBER_DURATION ) VALUES (1, 'OFF_PEAK', 10, 30, 10);
INSERT INTO TRAFFIC_HOUR (ID, name, RED_DURATION, GREEN_DURATION, AMBER_DURATION ) VALUES (2, 'NORMAL', 15, 30, 5);
INSERT INTO TRAFFIC_HOUR (ID, name, RED_DURATION, GREEN_DURATION, AMBER_DURATION ) VALUES (3, 'HEAVY', 15, 15, 2);
INSERT INTO TRAFFIC_HOUR (ID, name, RED_DURATION, GREEN_DURATION, AMBER_DURATION ) VALUES (4, 'MEDIUM', 20, 20, 5);

--SUNDAY Schedule
INSERT INTO TRAFFIC_LIGHT_SCHEDULE (ID, day_of_week, traffic_hours_id, fromHour, endHour) VALUES (101, 'SUNDAY', 1, 0000, 1100);
INSERT INTO TRAFFIC_LIGHT_SCHEDULE (ID, day_of_week, traffic_hours_id, fromHour, endHour) VALUES (102, 'SUNDAY', 2, 1100, 1900);
INSERT INTO TRAFFIC_LIGHT_SCHEDULE (ID, day_of_week, traffic_hours_id, fromHour, endHour) VALUES (103, 'SUNDAY', 1, 1900, 2359);

--MONDAY Schedule
INSERT INTO TRAFFIC_LIGHT_SCHEDULE (ID, day_of_week, traffic_hours_id, fromHour, endHour) VALUES (201, 'MONDAY', 1, 0000, 600);
INSERT INTO TRAFFIC_LIGHT_SCHEDULE (ID, day_of_week, traffic_hours_id, fromHour, endHour) VALUES (202, 'MONDAY', 3, 600, 1100);
INSERT INTO TRAFFIC_LIGHT_SCHEDULE (ID, day_of_week, traffic_hours_id, fromHour, endHour) VALUES (203, 'MONDAY', 1, 1100, 1600);
INSERT INTO TRAFFIC_LIGHT_SCHEDULE (ID, day_of_week, traffic_hours_id, fromHour, endHour) VALUES (204, 'MONDAY', 3, 1600, 2000);
INSERT INTO TRAFFIC_LIGHT_SCHEDULE (ID, day_of_week, traffic_hours_id, fromHour, endHour) VALUES (205, 'MONDAY', 2, 2000, 2359);

--TUESDAY Schedule
INSERT INTO TRAFFIC_LIGHT_SCHEDULE (ID, day_of_week, traffic_hours_id, fromHour, endHour) VALUES (301, 'TUESDAY', 1, 0000, 1100);
INSERT INTO TRAFFIC_LIGHT_SCHEDULE (ID, day_of_week, traffic_hours_id, fromHour, endHour) VALUES (302, 'TUESDAY', 2, 1100, 1900);
INSERT INTO TRAFFIC_LIGHT_SCHEDULE (ID, day_of_week, traffic_hours_id, fromHour, endHour) VALUES (303, 'TUESDAY', 3, 1900, 2359);

--WEDNESDAY Schedule
INSERT INTO TRAFFIC_LIGHT_SCHEDULE (ID, day_of_week, traffic_hours_id, fromHour, endHour) VALUES (401, 'WEDNESDAY', 1, 0000, 1100);
INSERT INTO TRAFFIC_LIGHT_SCHEDULE (ID, day_of_week, traffic_hours_id, fromHour, endHour) VALUES (402, 'WEDNESDAY', 2, 1100, 1900);
INSERT INTO TRAFFIC_LIGHT_SCHEDULE (ID, day_of_week, traffic_hours_id, fromHour, endHour) VALUES (403, 'WEDNESDAY', 3, 1900, 2359);

--THURSDAY Schedule
INSERT INTO TRAFFIC_LIGHT_SCHEDULE (ID, day_of_week, traffic_hours_id, fromHour, endHour) VALUES (501, 'THURSDAY', 1, 0000, 1100);
INSERT INTO TRAFFIC_LIGHT_SCHEDULE (ID, day_of_week, traffic_hours_id, fromHour, endHour) VALUES (502, 'THURSDAY', 2, 1100, 1900);
INSERT INTO TRAFFIC_LIGHT_SCHEDULE (ID, day_of_week, traffic_hours_id, fromHour, endHour) VALUES (503, 'THURSDAY', 3, 1900, 2359);

--FRIDAY Schedule
INSERT INTO TRAFFIC_LIGHT_SCHEDULE (ID, day_of_week, traffic_hours_id, fromHour, endHour) VALUES (601, 'FRIDAY', 1, 0000, 1100);
INSERT INTO TRAFFIC_LIGHT_SCHEDULE (ID, day_of_week, traffic_hours_id, fromHour, endHour) VALUES (602, 'FRIDAY', 2, 1100, 1900);
INSERT INTO TRAFFIC_LIGHT_SCHEDULE (ID, day_of_week, traffic_hours_id, fromHour, endHour) VALUES (603, 'FRIDAY', 3, 1900, 2359);

--SATURDAY Schedule
INSERT INTO TRAFFIC_LIGHT_SCHEDULE (ID, day_of_week, traffic_hours_id, fromHour, endHour) VALUES (701, 'SATURDAY', 1, 0000, 1100);
INSERT INTO TRAFFIC_LIGHT_SCHEDULE (ID, day_of_week, traffic_hours_id, fromHour, endHour) VALUES (702, 'SATURDAY', 2, 1100, 1900);
INSERT INTO TRAFFIC_LIGHT_SCHEDULE (ID, day_of_week, traffic_hours_id, fromHour, endHour) VALUES (703, 'SATURDAY', 3, 1900, 2359);
<file_sep>/src/main/java/com/traffic/light/trafficlightApplication/TrafficlightApplication.java
package com.traffic.light.trafficlightApplication;

import com.traffic.light.trafficlightApplication.common.TrafficLightEvent;
import com.traffic.light.trafficlightApplication.common.TrafficLightState;
import com.traffic.light.trafficlightApplication.workflow.TrafficLightConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Profile;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.statemachine.StateMachine;

@SpringBootApplication
@Import({ TrafficLightConfiguration.class })
@EnableJpaRepositories
@Slf4j
@Profile("!test")
public class TrafficlightApplication implements ApplicationListener<ApplicationReadyEvent> {

	@Autowired
	private StateMachine<TrafficLightState, TrafficLightEvent> signalSystem;

	public static void main(String[] args) {
		SpringApplication.run(TrafficlightApplication.class, args);
	}

	@Override
	public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
		log.info("STARTING: Signal Light System");
		signalSystem.start();
		signalSystem.sendEvent(TrafficLightEvent.KICK_OFF);
	}
}

<file_sep>/src/test/resources/application.yml
logging:
  level:
    org.springframework: ERROR
    com.traffic: INFO
  pattern:
    console: "%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"
    file: "%d %p %c{1.} [%t] %m%n"
  file: app.log

trafficlight.timer.interval: 2000

spring:
  datasource:
    url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
    username: sa
    password:
    driver-class-name: org.h2.Driver
    platform: h2

  h2:
    console:
      enabled: true
      path: /console

<file_sep>/src/main/java/com/traffic/light/trafficlightApplication/common/TrafficLightEvent.java
package com.traffic.light.trafficlightApplication.common;

public enum TrafficLightEvent {
	KICK_OFF, SLOW, STOP, GO, SHUT_DOWN;
}
<file_sep>/src/main/java/com/traffic/light/trafficlightApplication/repo/TrafficLightRepository.java
package com.traffic.light.trafficlightApplication.repo;

import com.traffic.light.trafficlightApplication.entity.TrafficLightSchedule;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface TrafficLightRepository extends JpaRepository<TrafficLightSchedule, Long>{
	List<TrafficLightSchedule> findAllByDayOfWeek(String dayOfWeek);
}
<file_sep>/README.md
# SignalApp
This is a repo for Traffic Signal Application
<file_sep>/src/test/java/com/traffic/light/trafficlightApplication/workflow/TrafficSignalTimerTest.java
package com.traffic.light.trafficlightApplication.workflow;

import com.traffic.light.trafficlightApplication.common.TrafficLightEvent;
import com.traffic.light.trafficlightApplication.common.TrafficLightState;
import com.traffic.light.trafficlightApplication.entity.TrafficHour;
import com.traffic.light.trafficlightApplication.entity.TrafficLightSchedule;
import com.traffic.light.trafficlightApplication.repo.TrafficLightRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.statemachine.StateContext;
import org.springframework.statemachine.state.State;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class TrafficSignalTimerTest {

    @Mock
    TrafficLightRepository repository;
    @Mock
    TrafficHour trafficHour;

    @Mock
    TrafficLightSchedule trafficLightSchedule;

    @Mock
    StateContext<TrafficLightState, TrafficLightEvent> context;

    @Mock
    State<TrafficLightState, TrafficLightEvent> state;

    @InjectMocks
    TrafficSignalTimer timer;

    @Before

    public void setup() {
        when(trafficLightSchedule.getTrafficHour()).thenReturn(trafficHour);
        LocalDateTime now = LocalDateTime.now();
        int currentTime = now.getHour()* 100 + now.getMinute();

        when(trafficLightSchedule.getFromHour()).thenReturn(currentTime - 100);
        when(trafficLightSchedule.getEndHour()).thenReturn(currentTime + 100);

        when(repository.findAllByDayOfWeek(anyString())).thenReturn(Arrays.asList(trafficLightSchedule));
        when(context.getSource()).thenReturn(state);
    }

    @Test
    public void test_Red_timer() throws InterruptedException {
        when(trafficHour.getRedDuration()).thenReturn(5);
        when(state.getId()).thenReturn(TrafficLightState.RED);

        timer.execute(context);

        CountDownLatch completedThreadCounter = new CountDownLatch(1);
        completedThreadCounter.await(5, TimeUnit.SECONDS);
    }

    @Test
    public void test_Green_timer() throws InterruptedException {
        //WHEN
        when(trafficHour.getGreenDuration()).thenReturn(2);
        when(state.getId()).thenReturn(TrafficLightState.GREEN);

        //THEN
        timer.execute(context);

        //VERIFY
        CountDownLatch completedThreadCounter = new CountDownLatch(1);
        completedThreadCounter.await(2, TimeUnit.SECONDS);
    }

    @Test
    public void test_Amber_timer() throws InterruptedException {
        when(trafficHour.getAmberDuration()).thenReturn(2);
        when(state.getId()).thenReturn(TrafficLightState.AMBER);

        timer.execute(context);

        CountDownLatch completedThreadCounter = new CountDownLatch(1);
        completedThreadCounter.await(2, TimeUnit.SECONDS);
    }
}
<file_sep>/src/main/java/com/traffic/light/trafficlightApplication/workflow/TrafficLightConfiguration.java
package com.traffic.light.trafficlightApplication.workflow;

import com.traffic.light.trafficlightApplication.common.TrafficLightEvent;
import com.traffic.light.trafficlightApplication.common.TrafficLightState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import org.springframework.statemachine.config.EnableStateMachine;
import org.springframework.statemachine.config.EnumStateMachineConfigurerAdapter;
import org.springframework.statemachine.config.builders.StateMachineConfigurationConfigurer;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;

@EnableStateMachine(name = "SignalSystem")
@Configuration
public class TrafficLightConfiguration extends EnumStateMachineConfigurerAdapter<TrafficLightState, TrafficLightEvent>{
	@Autowired
	private TrafficSignalTimer timerAction;

	@Override
	public void configure(StateMachineConfigurationConfigurer<TrafficLightState, TrafficLightEvent> config) throws Exception {
		super.configure(config);
		config.withConfiguration()
				.taskScheduler(new ConcurrentTaskScheduler());
	}

	@Override
	public void configure(StateMachineStateConfigurer<TrafficLightState, TrafficLightEvent> states) throws Exception {
		super.configure(states);
		states
				.withStates()
				.initial(TrafficLightState.CLEAR)
				.state(TrafficLightState.RED)
				.state(TrafficLightState.AMBER)
				.state(TrafficLightState.GREEN)
				.end(TrafficLightState.CLEAR);
	}

	@Override
	public void configure(StateMachineTransitionConfigurer<TrafficLightState, TrafficLightEvent> transitions) throws Exception {
		super.configure(transitions);

		transitions.withExternal()
				.source(TrafficLightState.CLEAR)
				.target(TrafficLightState.RED)
				.event(TrafficLightEvent.KICK_OFF)
				.and()
				.withExternal()
				.source(TrafficLightState.RED)
				.target(TrafficLightState.GREEN)
				.action(timerAction)
				.and()
				.withExternal()
				.source(TrafficLightState.GREEN)
				.target(TrafficLightState.AMBER)
				.action(timerAction)
				.and()
				.withExternal()
				.source(TrafficLightState.AMBER)
				.target(TrafficLightState.RED)
				.action(timerAction)
				.and()
				.withExternal()
				.event(TrafficLightEvent.SHUT_DOWN)
				.target(TrafficLightState.CLEAR);
	}

}

languages: Java Markdown SQL YAML

repo_name: deepikavashishtha/SignalApp


text:
<file_sep># Java_Asst-7.4-Solutions
This is the location of Java Assignment 7.4-Solutions of Acadgild course

branch_name: refs/heads/master

repo_language: Markdown


text:
<repo_name>abdelghanilejba/abdelghanilejba.github.io<file_sep>/README.md
# abdelghanilejba.github.io


text:
<file_sep>#!/bin/bash

echo "IMG_NAME='IntensoboxRaspbianStretch'" > config
touch stage3/SKIP stage4/SKIP stage5/SKIP
touch stage4/SKIP_IMAGES stage5/SKIP_IMAGES

mkdir -p stage2/03-intensobox
cp -r ~/intensobox/deps/ stage2/03-intensobox/
cp ~/intensobox/deps/install.sh stage2/03-intensobox/00-run.sh

repo_language: Shell

repo_name: schoettl/pi-gen


text: <file_sep>## progressive web app tests

repo_name: androdlang/pwa


text:
<repo_name>Ben2669/backtothefuture<file_sep>/index.php
<?php

$presentTime = new DateTimeImmutable("now");
$presentTimeBis = $presentTime->format("M-d-Y A h:i");

$destinationTime = new DateTimeImmutable("2015-10-21 10:30");

$timeInterval = $presentTime->diff($destinationTime);

$timeIntervalMinutes = (($timeInterval->format("%a")) * 24 * 60) + ($timeInterval->h * 60) + $timeInterval->i;

function quantityNeeded(float $nbMinutes): float
{
    return round($nbMinutes / 10000, 2);
}

?>

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Back to the Future</title>
    <link rel="stylesheet" href="style.css">

                MONTH

                DAY

                YEAR

                <?= $presentTime->format("A");?>

                HOUR

                MIN

                <?= $presentTime->format("M");?>

                <?= $presentTime->format("d");?>

                <?= $presentTime->format("Y");?>

                <?= $presentTime->format("h");?>

                <?= $presentTime->format("i");?>

                PRESENT TIME

                MONTH

                DAY

                YEAR

                <?= $destinationTime->format("A");?>

                HOUR

                MIN

                <?= $destinationTime->format("M");?>

                <?= $destinationTime->format("d");?>

                <?= $destinationTime->format("Y");?>

                <?= $destinationTime->format("h");?>

                <?= $destinationTime->format("i");?>

                DESTINATION TIME

    Il y a <?= $timeInterval->y;?> années, <?= $timeInterval->m;?> mois, <?= $timeInterval->d;?> jours, <?= $timeInterval->h;?> heures et <?= $timeInterval->i;?> minutes qui séparent ces deux dates !

    On a donc besoin de <?= quantityNeeded($timeIntervalMinutes);?>L de carburant pour effectuer ce voyage. Allons voler l'almanach Marty ! xD

repo_language: PHP


text:
<repo_name>FakeDok/first-project<file_sep>/style.css
*{
    box-sizing: border-box;
}
.conteiner {
    margin: 0 auto;
    width: 80%;
}
.first-screen {
    position: fixed;
    overflow: hidden;
    width: 100%;
    top: 0;
    left: 0;
    right: 0;
    background-color: #eeeff1;
  }
  .wd {
    padding-top: 60px;
    float: left;
    width: 50%;
  }
  .home {
    width: 50%;
    float: left;
  }
  .home-text {
    padding-top: 70px;
    float: left;
    text-align: right;
    width: 20%;
    font-size: 16px;
  }
  .main-layout {
    background: #EEEFF1;;
    overflow: hidden;
    padding-top: 271px;
    padding-bottom: 143px;
  }
.main-layout-left {
    width: 50%;
    float: left;
    text-align: center;
}
.laptop-png{
    text-align: center;
}
.main-layout-right {
    width: 50%;
    float: left;
}
.main-layout-title{
    font-size: 48px;
    margin-bottom: 20px;
    color: #000000;
    line-height: 1;
    margin-top: 0;
}
.main-layout-discribtion{
    font-size: 16px;
    margin-bottom: 20px;
    color: #727272;
}
.main-layout-buton {
    text-align: center;
    width: 222px;
    background-color: #34547a;
    color: #ffffff;
    padding-bottom: 28px;
    padding-top: 28px;
}
.about-us {
    margin: 0 auto;
    width: 100%;
    text-align: center;
}
.about-us-title {
    text-align: center;
    font-size: 32px;
    color: #000000;

}
.about-us-discribtion {
    text-align: center;
    font-size: 16px;
    color: #727272;
    width: 60%;
    margin: 0 auto;
    padding-top: 10px;
    padding-bottom: 45px;

}
.advantage {
    background: #34547A;;
    padding-top: 50px;
    padding-bottom: 50px;
    text-align: center;
    overflow: hidden;
}

.advantage-item {
    width: 15%;
    float:left;

}
.advantage-item-col{
float:left;
text-align: center;

}
.numberproject {
    font-size: 21px;
    color: white;

}
.project {
    font-size: 16px;
    color: white;
    text-align: left;
}
.my-skills  {
    overflow: hidden;
    padding-top: 100px;
    padding-bottom: 100px;
    }
.skills-list{
    float: left;
    width: 50%;
}
.title-my-skills {
    font-size: 32px;
    color: #000000;
    padding-bottom: 50px;
}
.my-skills-adobe{
font-size: 16px;
color: #727272;
padding-top: 30px;
padding-bottom: 20px;
}
.bottom-line{
    width: 445px;
    height: 4px;
    background: #C4C4C4;
}
.top-line{
    width: 349.36px;
    height: 4px;
    background: #34547A;
}
.my-photo{
    width: 50%;
    float: left;
    text-align: center;
}
.size-photo{
    width: 555px;
}
.video {
    background: #EEEFF1;
    padding-top: 30px;
    padding-bottom: 60px;
    overflow: hidden;
}
.how-work {
    font-size: 32px;
    color: #000000;
    text-align: center;

}
.lorem-how-work {
  font-size: 16px;
  text-align: center;
  color: #727272;
  width: 60%;
  margin: 0 auto;
  padding-top: 50px;
  padding-bottom: 55px;
}

.image-video {
    background-image: url(img/video.png);
    background-size: cover;
    text-align: center;
    padding-top: 245px;
    padding-bottom: 245px;
}
.plan{
    overflow: hidden;
}
.image-text{
    background-image: url(img/checklist.png);
    background-size: cover;
    width: 25%;
    height: 480px;
    float: left;
    transition: 1s all linear;
}
.image-two-laptop{
    background-image: url(img/two-laptop.png);
    background-size: cover;
    width: 25%;
    height: 480px;
    float: left;
    transition: 1s all linear;
}
.image-two-laptop:hover{
    box-shadow: inset 0 0 0 1000px rgba(52, 84, 122, 0.8);
}
.image-text:hover{
    box-shadow: inset 0 0 0 1000px rgba(52, 84, 122, 0.8);
}
.clients{
    overflow: hidden;
    text-align: center;
    padding-bottom: 20px;
    padding-top: 20px;
}
.block-microsoft{
    width: 25%;
    float: left;
}

.microsoft-image{
    width: 255px;
}

.form{
    background-color: #eeeff1;
    overflow: hidden;
    padding-top: 20px;
    padding-bottom: 20px;
}
.hotite-web-site{
    font-size: 32px;
    color: #000000;
    text-align: center;
}

.lorem-hotite-web-site{
    font-size: 16px;
    text-align: center;
    color: #727272;
    width: 60%;
    margin: 0 auto;
    padding-top: 50px;
    padding-bottom: 60px;

}

.form-name-email{
    text-align: center;
    overflow: hidden;
    width: 540px;
    margin: 0 auto;
}
.form-name{
    width: 250px;
    height: 50px;
    background: #ffffff;
    color: #5f5d5d;
    margin-right: 40px;
    float: left;
}
.form-email{
    width: 250px;
    height: 50px;
    background: #ffffff;
    color: #5f5d5d;
    float: left;
}

.form-massange{
    text-align: center;
    padding-bottom: 50px;
    padding-top: 20px;

}

.form-text{
    width: 540px;
    height: 175px;
    background: #ffffff;
}

.form-knopka{
    text-align: center;
}

.knopka{
    width: 190px;
    height: 55px;
    background: #34547A;
    color: #FFFFFF;

}
.footer{
    background: #34547A;
    text-align: center;
    overflow: hidden;

}
.name-prava{
    float: left;
    padding-top: 50px;
    padding-bottom: 50px;

}

.footer-name{
    font-size: 21px;
    color: #FFFFFF;
}
.footer-prava{
    font-size: 13px;
    color:#FFFFFF;
}
.image-vk{
    padding-top: 64.59px;
    padding-bottom: 63.59px;
    text-align: right;
}
@media (max-width:1024px){
    .wd{
        width: 30%;
    }
    .home {
        width: 70%;
    }
    .main-layout-buton{
        width: 46%;
    }
    .bottom-line{
        width: 90%;
    }
    .top-line{
        width: 90%;
    }
    .image-text{
        height: 250px;
    }
    .image-two-laptop{
        height: 250px;
    }
    .block-microsoft{
        width: 25%;
    }
    .microsoft-image{
        width: 60%;
    }
    .image-video{
        padding-top: 150px;
        padding-bottom: 150px;
    }
}
@media (max-width:768px){
    .wd{
        width: 20%;
    }
    .home {
        width: 80%;
    }
    .main-layout {
        padding-top: 150px;
        padding-bottom: 40px;
    }
    .main-layout-left{
        width: 40%;
    }
    .laptop-png {
        width: 200px;
    }
    .main-layout-right{
        width: 60%;
    }
    .main-layout-title {
        font-size: 30px;
        margin-bottom: 10px;
    }
    .main-layout-discribtion{
        font-size: 12px;
        margin-bottom: 10px;
    }
    .main-layout-buton {
        width: 140px;
        padding-bottom: 10px;
        padding-top: 10px;
    }
    .about-us-title{
        font-size: 25px;
    }
    .about-us-discribtion {
        font-size: 12px;
        padding-top: 0px;
        padding-bottom: 15px;
    }
    .advantage{
        padding-top: 15px;
        padding-bottom: 15px;
    }
    .advantage-item {
        width: 33%;
        padding-top: 15px;
        padding-left: 30px;
    }
    .advantage-item-col{
        padding-left: 20px;
    }
    .my-skills {
        padding-top: 50px;
        padding-bottom: 50px;
    }
    .skills-list{
        width: 40%;
    }
    .title-my-skills{
        font-size: 30px;
        padding-bottom: 10px;
    }
    .size-photo {
        width: 400px;
    }
    .video{
        padding-top: 10px;
        padding-bottom: 40px;
    }
    .lorem-how-work{
        padding-top: 30px;
        padding-bottom: 40px;
    }
    .lorem-hotite-web-site{
        padding-top: 20px;
        padding-bottom: 40px;
    }
    .image-vk {
        padding-top: 25px;
        padding-bottom: 0px;
    }
    .name-prava {
        padding-top: 0px;
        padding-bottom: 0px;
    }
    .form-massange{
        padding-bottom: 20px;
    }
    .knopka {
        width: 150px;
        height: 40px;
    }
}
@media (max-width:426px){
    .home{
        display: none;
    }
    .main-layout{
        padding-bottom: 20px;
    }
    .main-layout-left {
        width: 100%;
    }
    .main-layout-right {
        width: 100%;
    }
    .main-layout-title {
        text-align: center;
        margin: 10px;
    }
    .main-layout-discribtion {
        text-align: center;
        font-size: 14px;
    }
    .main-layout-buton {
        width: 100%;
    }
    .about-us-discribtion {
        font-size: 14px;
    }
    .advantage-item {
        width: 50%;
    }
    .title-my-skills {
        font-size: 20px;
        padding-bottom: 5px;
    }
    .my-skills-adobe {
        font-size: 10px;
        padding-top: 20px;
        padding-bottom: 15px;
    }
    .top-line {
        width: 80%;
    }
    .bottom-line {
        width: 70%;
    }
    .size-photo {
        width: 170%;
    }
    .how-work {
        font-size: 20px;
    }
    .lorem-how-work {
        padding-top: 10px;
        padding-bottom: 20px;
        font-size: 10px;
    }
    .image-video {
        padding-top: 50px;
        padding-bottom: 50px;
    }
    .image-text {
        height: 100px;
    }
    .image-two-laptop {
        height: 100px;
    }
    .form {
        padding-top: 5px;
        padding-bottom: 15px;
    }
    .hotite-web-site {
        font-size: 25px;
    }
    .lorem-hotite-web-site {
        font-size: 10px;
        padding-top: 5px;
        padding-bottom: 20px;
    }
    .form-name {
        width: 135px;
        height: 30px;
        margin-right: 30px;
        margin-left: 15px;
    }
    .form-email {
            width: 135px;
            height: 30px;
    }
    .form-text {
        width: 300px;
        height: 100px;
    }
    .knopka {
        width: 130px;
        height: 30px;
    }
    .footer-name {
        font-size: 10px;
    }
    .name-prava {
        padding-top: 8px;
    }
    .footer-prava {
        font-size: 8px;
    }
    .vk-png{
        width: 10%;
    }
    .image-vk {
        padding-top: 15px;
    }
}
@media (max-width:321px){
    .my-skills {
        padding-top: 20px;
        padding-bottom: 20px;
    }
    .my-skills-adobe{
        padding-top: 5px;
    }
    .form-name {
        width: 110px;
        height: 30px;
        margin-right: 25px;
        margin-left: 0px;
    }
    .form-email {
        width: 110px;
    }
    .form-text {
        width: 245px;
    }
}

repo_language: CSS

repo_name: FakeDok/first-project


text:
<file_sep>canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
backgroundimage = "canvas_bkg.jpg";
car1image = "car1.png";
car2image = "car2.png";

car1width = 120;
car1height = 70;

car2width = 120;
car2height = 70;

car1_x = 10;
car1_y = 10;

car2_x = 10;
car2_y = 100;

function add(){
    backgroundimgtag = new Image();
    backgroundimgtag.onload = uploadracefunction;
    backgroundimgtag.src = backgroundimage;

    car1imgtag = new Image();
    car1imgtag.onload = uploadcar1function;
    car1imgtag.src = car1image;

    car2imgtag = new Image();
    car2imgtag.onload = uploadcar2function;
    car2imgtag.src = car2image;
}

function uploadracefunction() {
    ctx.drawImage(backgroundimgtag, 0, 0, canvas.width, canvas.height);
}

function uploadcar1function() {
    ctx.drawImage(car1imgtag,car1_x,car1_y,car1width, car1height);
}

function uploadcar2function() {
    ctx.drawImage(car2imgtag,car2_x,car2_y,car2width, car2height);
}

window.addEventListener("keydown", my_keydown);

function my_keydown(e)
{
    keyPressed = e.keyCode;
console.log(keyPressed);
if(keyPressed == '38'){

car1_up();
console.log("car1-up");
}
if(keyPressed == '40')
{
car1_down();
console.log("car1-down");
}
if(keyPressed == '37')
{
car1_left();
console.log("car1-left");
}
if(keyPressed == '39')
{
car1_right();
console.log("car1-right");
}
if(keyPressed == '87'){

    car2_up();
    console.log("car2-up");
    }
    if(keyPressed == '83')
    {
    car2_down();
    console.log("car2-down");
    }
    if(keyPressed == '65')
    {
    car2_left();
    console.log("car2-left");
    }
    if(keyPressed == '68')
    {
    car2_right();
    console.log("car2-right");
    }

    if(car1_x > 700)
    {
        console.log("car1 won");
        document.getElementById('game_status').innerHTML = "Car 1 Won!!";
    }

    if(car2_x > 700)
    {
        console.log("car2 won");
        document.getElementById('game_status').innerHTML = "Car 2 Won!!";
    }
}

function car1_up()
{
    if(car1_y>=0)
    {
        car1_y = car1_y - 10;
        console.log("When up arrow is pressed, x =" + car1_x + " | y =" +car1_y);
        uploadracefunction();
        uploadcar1function();
        uploadcar2function();
    }
}

function car1_down()
{
    if(car1_y<=500)
    {
        car1_y = car1_y + 10;
        console.log("When down arrow is pressed, x =" + car1_x + " | y =" +car1_y);
        uploadracefunction();
        uploadcar1function();
        uploadcar2function();
    }
}

function car1_left()
{
    if(car1_x>=0)
    {
        car1_x = car1_x - 10;
        console.log("When left arrow is pressed, x =" + car1_x + " | y =" +car1_y);
        uploadracefunction();
        uploadcar1function();
        uploadcar2function();
    }
}

function car1_right()
{
    if(car1_x<=700)
    {
        car1_x = car1_x + 10;
        console.log("When right arrow is pressed, x =" + car1_x + " | y =" +car1_y);
        uploadracefunction();
        uploadcar1function();
        uploadcar2function();
    }
}

function car2_up()
{
    if(car2_y>=0)
    {
        car2_y = car2_y - 10;
        console.log("When up arrow is pressed, x =" + car2_x + " | y =" +car2_y);
        uploadracefunction();
        uploadcar1function();
        uploadcar2function();
    }
}

function car2_down()
{
    if(car2_y<=500)
    {
        car2_y = car2_y + 10;
        console.log("When down arrow is pressed, x =" + car2_x + " | y =" +car2_y);
        uploadracefunction();
        uploadcar1function();
        uploadcar2function();
    }
}

function car2_left()
{
    if(car2_x>=0)
    {
        car2_x = car2_x - 10;
        console.log("When left arrow is pressed, x =" + car2_x + " | y =" +car2_y);
        uploadracefunction();
        uploadcar1function();
        uploadcar2function();
    }
}

function car2_right()
{
    if(car2_x<=700)
    {
        car2_x = car2_x + 10;
        console.log("When right arrow is pressed, x =" + car2_x + " | y =" +car2_y);
        uploadracefunction();
        uploadcar1function();
        uploadcar2function();
    }
}

branch_name: refs/heads/main

repo_language: JavaScript


text:
<file_sep>export default {
  API_ENDPOINT: 'https://infinite-temple-03033.herokuapp.com/api'
}
<file_sep># Noteful Client

Deployed here https://yulia-noteful.now.sh/

languages: Markdown JavaScript

repo_name: jennifrmarie/noteful-client-master


text:
<repo_name>Sangeeths11/Sangeeths_Chandrakumar_Modul_226B<file_sep>/src/AirportScheduler/Flugzeug.java
package AirportScheduler;

import java.util.ArrayList;

public class Flugzeug {

    public static final int PROP = 0;
    public static final int JET = 1;

    public int typ;
    public String nachtankzeit;
    public int kapazitaet;

    public Flugzeug(int typ, String nachtankzeit, int kapazitaet) {
        this.typ = typ;
        this.nachtankzeit = nachtankzeit;
        this.kapazitaet = kapazitaet;
    }
}
<file_sep>/src/AirportScheduler/Flughafen.java
package AirportScheduler;

public class Flughafen {

    private Gate[] gates;
    private String name;

    public Flughafen() {
        this.name = "Gatwick";
        this.gates = new Gate[10];

        //nationale Gates
        gates[0] = new NationalesGate(1);
        gates[0].setFlug(new Flug(1, "13:00", "14:00", new Flugzeug(Flugzeug.PROP, "14:15", 150)));

        gates[1] = new NationalesGate(2);
        gates[1].setFlug(new Flug(2, "14:00", "15:00", new Flugzeug(Flugzeug.PROP, "15:15", 180)));

        gates[2] = new NationalesGate(3);
        gates[2].setFlug(new Flug(3, "15:00", "16:00", new Flugzeug(Flugzeug.PROP, "16:15", 100)));

        gates[3] = new NationalesGate(4);
        gates[3].setFlug(new Flug(4, "16:00", "17:00", new Flugzeug(Flugzeug.PROP, "17:15", 120)));

        //2 kleine internationale Gates
        gates[4] = new InternationalesGate(5, InternationalesGate.KLEIN);
        gates[4].setFlug(new Flug(1001, "17:00", "18:00", new Flugzeug(Flugzeug.PROP, "18:15", 200)));

        gates[5] = new InternationalesGate(6, InternationalesGate.KLEIN);
        gates[5].setFlug(new Flug(1002, "18:00", "19:00", new Flugzeug(Flugzeug.PROP, "19:15", 200)));

        //vier grosse internationale Gates
        gates[6] = new InternationalesGate(7, InternationalesGate.GROSS);
        gates[6].setFlug(new Flug(1003, "19:00", "20:00", new Flugzeug(Flugzeug.JET, "20:15", 200)));

        gates[7] = new InternationalesGate(8, InternationalesGate.GROSS);
        gates[7].setFlug(new Flug(1004, "20:00", "21:00", new Flugzeug(Flugzeug.JET, "21:15", 250)));

        gates[8] = new InternationalesGate(8, InternationalesGate.GROSS);
        gates[8].setFlug(new Flug(1005, "21:00", "22:00", new Flugzeug(Flugzeug.JET, "22:15", 250)));

        gates[9] = new InternationalesGate(8, InternationalesGate.GROSS);
        gates[9].setFlug(new Flug(1006, "22:00", "23:00", new Flugzeug(Flugzeug.JET, "23:15", 300)));

    }

    public int landen(Flug flug) {

        for (int i = 0; i < 10; i++) {
            if (gates[i].istFrei()) {       //Schleife über alle Gates
                if (flug.istNational()) {   //nur freie Gates
                    gates[i].landen(flug);  //nationaler Flug passt immer
                    return i + 1;
                } else {                    //internationaler Flug
                    if (gates[i] instanceof InternationalesGate && (gates[i]).getGroesse() == InternationalesGate.GROSS) {
                        gates[i].landen(flug);
                        return i + 1;
                    }
                }
            }
        }
        return -1;
    }

    public void starten(int gateNr) {

        if (!gates[gateNr - 1].istFrei()) {
            gates[gateNr - 1].starten();
        } else {
            System.out.println("Das Gate " + gateNr + " ist frei!\n");
        }

    }

    public void gateStatus(int gateNr) {

        Gate gate = gates[gateNr - 1];

        if (!gate.istFrei()) {
            String typ;
            String groesse;

            if (gate instanceof InternationalesGate) {
                typ = "Internationaler Gate";

                if (gate.getGroesse() == InternationalesGate.GROSS) {
                    groesse = "Grosser Gate";
                } else {
                    groesse = "Kleiner Gate";
                }

            } else {
                typ = "Nationaler Gate";
                groesse = "Kleiner Gate";
            }

            System.out.println("Nummer: " + gate.getNummer() + "\nGroesse: " + groesse + "\nTyp: " + typ);
        } else {
            System.out.println("Das Gate " + gateNr + " ist frei!\n");
        }
    }

    public Gate[] getGates() {
        return gates;
    }
}
<file_sep>/README.md
# Sangeeths_Chandrakumar_Modul_226B
Modul 226B Waldvogel Java Projekte

languages: Java Markdown

repo_language: Java


text: <file_sep># Gitpod-Web-Development-Example

repo_name: nestorevany/Testing


text:
<repo_name>alexjhannan/breadcrumbs<file_sep>/firebase/database.js
import firebase from 'firebase';
import GLOBAL_CONFIG from '~/config.js';

const config = {
  apiKey: GLOBAL_CONFIG.firebaseAPIKey,
  authDomain: GLOBAL_CONFIG.firebaseAuthDomain,
  databaseURL: GLOBAL_CONFIG.firebaseDatabaseURL
};

firebase.initializeApp(config);
const database = firebase.database();

export default database;
<file_sep>/constants/action_types.js
const ACTION_TYPES = {
  GetInviteRequested: 'GET_INVITE_REQUESTED',
  GetInviteRejected: 'GET_INVITE_REJECTED',
  GetInviteFulfilled: 'GET_INVITE_FULFILLED',
  AddToInviteRequested: 'ADD_TO_INVITE_REQUESTED',
  AddToInviteRejected: 'ADD_TO_INVITE_REJECTED',
  AddToInviteFulfilled: 'ADD_TO_INVITE_FULFILLED',
  GuestAdded: 'GUEST_ADDED_EVENT'
};

export default ACTION_TYPES;
<file_sep>/firebase/watchAuthentication.js
import firebase from 'firebase';

export default function watchAuthentication () {
  firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
      var isAnonymous = user.isAnonymous;
      var uid = user.uid;
      console.log('logged in!');
      console.log('logged in!');
      console.log('logged in!');
      console.log('logged in!');
    } else {
      console.log('not logged in!');
      console.log('not logged in!');
      console.log('not logged in!');
      console.log('not logged in!');
    }
  });
};
<file_sep>/reducers/invite.js
import ACTION_TYPES from '~/constants/action_types'

export default function invite(state = {}, action) {
  switch(action.type) {
    case ACTION_TYPES.AddToInviteFulfilled: {
      const newState = Object.assign({}, state, {
        inProgress: false,
        success: 'Added guest.'
      });
      return newState;
    }
    case ACTION_TYPES.GuestAdded: {
      const newState = Object.assign({}, state);
      newState.guests = newState.guests || [];
      newState.guests = newState.guests.slice();
      newState.guests.push(action.guest);
      return newState;
    }
    default:
      return state;
  }
}
<file_sep>/index.js
// react imports
import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';
// redux imports
import { createStore, applyMiddleware, combineReducers } from 'redux';
import { Provider } from 'react-redux';
// redux middleware & reducer imports
import thunk from 'redux-thunk';
import { createLogger } from "redux-logger";
import rootReducer from '~/reducers/root';
// react-router imports
import { BrowserRouter as Router, Route } from 'react-router-dom'
import createHistory from 'history/createBrowserHistory';

import App from './App';

const history = createHistory();
const logger = createLogger();

const store = createStore(
  rootReducer,
  applyMiddleware(thunk, logger)
);

const Root = () => (
  <Provider store={ store }>
    <Router history={ history }>
      <App />
    </Router>
  </Provider>
);

ReactDOM.render(Root(), document.getElementById('appContainer'));

repo_name: alexjhannan/breadcrumbs


text:
<repo_name>gregfurman/textbook_finder<file_sep>/credentials.py
username = "admin"
password = "<PASSWORD>/?"<file_sep>/model.py
from mysql.connector import connect, Error
from getpass import getpass
import credentials

class Database:

    def __init__(self,**kwargs):
        self._connection = connect(user = credentials.username, password = <PASSWORD>, **kwargs)
        self._cursor = self._connection.cursor()

    def __enter__(self):
        return self

    def __exit__(self):
        self.close()

    @property
    def connection(self):
        return self._connection

    @property
    def cursor(self):
        return self._cursor

    def commit(self):
        self._connection.commit()

    def close(self,commit=True):
        if commit:
            self.commit()
        self._connection.close()

    def execute(self,query,params=None):
        self._cursor.execute(query,params or ())

    def fetchall(self):
        return self._cursor.fetchall()

    def fetchone(self):
        return self._cursor.fetchone()

    def query(self, sql, params=None):
        self._cursor.execute(sql, params or ())
        return self.fetchall()

    def rows(self):
        return self.cursor.rowcount

    def create_database(self,name,use=True):
        self.execute(f"SHOW DATABASES LIKE '{name}'")
        if not self.fetchone():
            self.execute(f"CREATE DATABASE {name}")

            if use:
                self.execute(f"USE {name}")
        else:
            print(f"Database {name} already exists.")

    def create_table(self,name,schema=""):
        self.execute(f"SHOW TABLES LIKE '{name}'")
        if not self.fetchone() and schema:
            self.execute(f"CREATE TABLE {name}({schema})")
        else:
            print(f"Table {name} already exists or schema is empty.")

def initialise_database():
    model = Database(host="localhost")

    model.create_database("scraped_data")

    model.create_table("prog_textbooks","""
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(150),
    publish_year YEAR(4),
    prog_language VARCHAR(30),
    frequency INT
    """)

def load_database(name):
    model = Database(host="localhost",database=name)

if __name__ == "__main__":
    load_database("scraped_data")

<file_sep>/scraper.py
import requests
import asyncio
import aiohttp
import time
import re
import difflib

from urllib.parse import urlencode, urlunparse,urlparse,parse_qs
from urllib.request import urlopen,Request
from bs4 import BeautifulSoup
from itertools import chain, dropwhile
from collections import Counter

class Trie(object):
    def __init__(self):
        self.child = {}
        self._pattern = re.compile('[\W_]+')

    def insert(self,title,index):
        node = self.child
        for term in title.split(" "):
            term = self._pattern.sub('', term)
            if term not in node:
                node[term] = {"id" : index}
            node = node[term]
        node['#'] = '#'

    def ratio(self,title_prefix):
        node = self.child
        for depth,term in enumerate(title_prefix.split(" ")):
            term = self._pattern.sub('', term)
            if term not in node:
                return depth/len(title_prefix),node.get("id",None)
            node = node[term]

            if '#' in node:
                return 1,node["id"]

        return 1,node["id"]

    def startsWith(self,title_prefix):
        node = self.child
        for term in title_prefix.split(" "):
            term = self._pattern.sub('', term)
            if term not in node:
                return False
            node = node[term]
        return True

    def search(self, title):
        node = self.child
        for term in title.split(" "):
            term = self._pattern.sub('', term)
            if term not in node:
                return False
            node = node[term]
        return '#' in node

class Scraper(object):

    def __init__(self,language,pages):
        self.headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0",
        "Accept-Encoding":"gzip, deflate",
        "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
        "Accept-Language" : "en-US,en;q=0.5",
        "Content-Type": "application/json"}

        self.language = language
        self.pages = pages
        self.titles = []
        self.trie = Trie()

    def main(self):
        self.get_amazon_data(self.pages,language=self.language)

        loop = asyncio.get_event_loop()
        response = loop.run_until_complete(self.scrape_urls())

        return self.count_instances(response) + Counter()

    def count_instances(self,scraped_headings):
        scraped_headings = filter(lambda x: len(x) > 1,scraped_headings)
        counter = Counter()

        for scraped_heading in chain.from_iterable(scraped_headings):
            ratio,index = self.trie.ratio(scraped_heading)

            if ratio > 0.8:
                counter.update({self.titles[index] : 1})

            else:
                continue
        return counter

    async def scrape_urls(self):
        tasks = []
        urls = set()
        async with aiohttp.ClientSession(headers=self.headers) as session:
            for url in self.get_search_data(pages=self.pages,query=f"best {self.language} textbooks"):
                if url not in urls and (res:=self.fetch(session,url)):
                    tasks.append(res)
                urls.add(url)

            scraped_headings = await asyncio.gather(*tasks)

        return scraped_headings

    async def fetch(self,session,url):

        try:
            async with session.get(url) as response:
                text = await response.text(encoding="utf-8")
                headers = await self.search_page(text)
                return headers
        except Exception as e:
            print(e,url)
            return []

    async def search_page(self,text):
        soup = BeautifulSoup(text,'html.parser')
        headings = soup.find_all(["h1", "h2", "h3"])
        res = set()

        if headings:
            for ele in headings:
                cleaned_ele_text = ele.text.strip().lower()
                if bool(cleaned_ele_text) and cleaned_ele_text != (len(cleaned_ele_text) * cleaned_ele_text[0]):
                    if (match := re.match(r"^(?:#?(?:[a-z]|\d+)(?:\)|\.))?(.*)$",cleaned_ele_text)):
                        res.add(match.group(1).strip())
                    else:
                        res.add(cleaned_ele_text)

        return list(res)

    def get_search_data(self,pages=5,query="best python textbooks"):
        next_page = "/search?"+ urlencode({"q":query})
        base_url = "https://www.google.com"

        for _ in range(pages):

            req = requests.get( base_url + next_page ,headers=self.headers)

            soup = BeautifulSoup(req.text,'html.parser')
            results = soup.select("a > h3")

            for elem in results:

                if 'pdf' not in elem.parent.attrs["href"].split('.')[-1]:
                    yield elem.parent.attrs["href"]

                if (next_button := soup.find('a',attrs={'id':'pnnext'})):
                    next_page = next_button["href"]
                else:
                    print("Could not find 'Next' button.")

    def _clean_response_text(self,response):
        return response.getText().lower().strip()

    def get_amazon_data(self,pages=1,language="python"):

        next_page = f"s?k={language.lower().strip()}&rh=n%3A3839&ref=nb_sb_noss" #"https://www.amazon.com/Programming-Computers-Internet-Books/b?ie=UTF8&node=3839"
        base_url = "https://www.amazon.com/"

        for page in range(pages+1):

            req = requests.get( base_url + next_page ,headers=self.headers)
            content = req.text
            soup = BeautifulSoup(content,features="html.parser")

            for result in soup.find_all('a',attrs={'class':'a-link-normal a-text-normal'}):

                self.trie.insert(result.getText().lower().strip(),len(self.titles))
                self.titles.append(self._clean_response_text(result))

            if (soup_find :=soup.find('li',attrs={'class':'a-last'})) != None:
                next_page = soup_find.find('a')['href']
            else:
                print("Error in finding Amazon details.")
                break

if __name__ == "__main__":
    s = Scraper(language="python",pages=1)

    for key,count in s.main().most_common(10):
        print(f"{key}: {count}")

repo_language: Python


text:
<repo_name>Santhosh25/cordova-angular<file_sep>/README.md
# cordova-angular
Cordova + Angular 1 - scaffolding


text:
<repo_name>sudo-sunil/BCE-EFFECTS-OF-CYBER-CRIME<file_sep>/README.md
# BCE-EFFECTS-OF-CYBER-CRIME

repo_name: sudo-sunil/BCE-EFFECTS-OF-CYBER-CRIME


text:
<repo_name>orug8m/nodeapi<file_sep>/README.md
# Firebase Admin を Node Express TypeScript ES2020 で試す

Firebase から Admin SDK で users 一覧を取ってくるサンプルアプリケーション

## 動作

1. Firebase / 設定 / サービスアカウント / Firebase Admin SDK / 新しい秘密鍵の生成
   で json ファイルを取得し、プロジェクト内に置く（serviceAccountKey.json など変更）
2. TypeScript で静的型付けしているのでエラー=>解消（json ファイル内の全ての情報が必要ではない）

```
  interface ServiceAccount {
    projectId?: string;
    clientEmail?: string;
    privateKey?: string;
  }
```

```

$ yarn start

# localhost:3456/secret/userinfoにアクセス
# consoleにFirebaseプロジェクト/Authenticate/Users上のuserが表示されれば実験成功
```
<file_sep>/src/index.ts
import express from "express";
import * as admin from "firebase-admin";
import serviceAccount from "../serviceAccountKey.json";
export type ServiceAccount = typeof serviceAccount;

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
});

const app: express.Express = express();

// CORSの許可
app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

// body-parserに基づいた着信リクエストの解析
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Firebase adminでusers一覧を表示
app.get("/secret/userinfo", async () => {
  admin
    .auth()
    .listUsers(1000)
    .then((listUsersResult) => {
      console.log(listUsersResult);
    })
    .catch(function (error) {
      console.log("Error listing users:", error);
    });
});

const router: express.Router = express.Router();

// sample: Get
router.get("/api/get", (req: express.Request, res: express.Response) => {
  res.send(req.query);
});

// sample: Post
router.post("/api/post", (req: express.Request, res: express.Response) => {
  res.send(req.body);
});

app.use(router);

// 3456番ポートでAPIサーバ起動
app.listen(3456, () => {
  console.log("Example app listening on port 3456!");
});

languages: Markdown TypeScript


text:
<repo_name>webz-kay/Attendance-Android<file_sep>/app/src/main/java/com/example/nanoatt/CustomAdapter.java
package com.example.nanoatt;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class CustomAdapter extends BaseAdapter {
    private  Context context;
    private ArrayList<Item> items;
    LayoutInflater inflater;

    public CustomAdapter(Context context, ArrayList<Item> items) {
        this.context = context;
        this.items = items;
        this.inflater=(LayoutInflater.from(context));
    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Object getItem(int i) {
        return items.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view=inflater.inflate(R.layout.list_item, null);
        TextView txtName = view.findViewById(R.id.txtName);
        TextView txtDate = view.findViewById(R.id.txtDate);
        TextView txtTimeIn = view.findViewById(R.id.txtTimeIn);
        TextView txtTimeOut = view.findViewById(R.id.txtTimeOut);
        Item item =items.get(i);
        txtName.setText(item.getUser());
        txtDate.setText(item.getDate());
        txtTimeIn.setText(item.getTime_in());
        txtTimeOut.setText(item.getTime_out());
        return view;
    }
}
<file_sep>/settings.gradle
rootProject.name='NanoAtt'
include ':app'
<file_sep>/app/src/main/java/com/example/nanoatt/Item.java
package com.example.nanoatt;

public class Item {
    String user;
    String date;
    String time_in;
    String time_out;

    public Item(String user, String date, String time_in, String time_out) {
        this.user = user;
        this.date = date;
        this.time_in = time_in;
        this.time_out = time_out;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getTime_in() {
        return time_in;
    }

    public void setTime_in(String time_in) {
        this.time_in = time_in;
    }

    public String getTime_out() {
        return time_out;
    }

    public void setTime_out(String time_out) {
        this.time_out = time_out;
    }
}

languages: Java Gradle

repo_name: webz-kay/Attendance-Android


text:
<repo_name>SeokHunPark/commit-test<file_sep>/sub-dir/install-server.sh
#!/bin/bash

echo hello

DATE=`date --date '1 days ago' +%Y%m%d`
SERVER="172.16.58.3"

USER="norion"
PASS="<PASSWORD>!"

DOWNLOAD_DIR="/home/ftp"
LOCAL_DIR="/home/norion"
TARGET_FILE="README.tar"

cd $LOCAL_DIR
ftp -n $SERVER << End-Of-Session
user $USER $PASS
bin
cd $DOWNLOAD_DIR
get $TARGET_FILE
bye
End-Of-Session

FILE_PATH=$LOCAL_DIR/$TARGET_FILE
PATH_SIZE=$(expr ${#FILE_PATH[*]})

echo $FILE_PATH

case $FILE_PATH in
	*.zip) unzip $FILE_PATH -d ${FILE_PATH%%.*}
	;;
	*.tar*)
	if [ -d ${FILE_PATH%%.*} ]; then
		echo "${FILE_PATH%%.*} is exist"
		echo "server stop"
	else
		echo "${FILE_PATH%%.*} is not exist"
		mkdir ${FILE_PATH%%.*}
	fi

	tar -xvf $FILE_PATH -C ${FILE_PATH%%.*}
	echo "server start"
	;;
esac

exit 0

repo_name: SeokHunPark/commit-test


text:
<repo_name>VeraManuel/nodejs-sequelize-jwt<file_sep>/README.md
# nodejs-sequelize-jwt
<file_sep>/app/config/auth.config.js
'use strict'

module.exports = {
    secret: "rezegal-secret-key"
};
<file_sep>/app/middlewares/verifySignUp.js
'use strict'

var db = require('../models');
var ROLES = db.ROLES;
var User = db.user;

function checkDuplicateUsernameOrEmail(req, res, next) {
    // Username

    User.findOne({
        where: {
            username: req.body.username
        }
    }).then(user => {
        if (user) {
            res.status(400).send({
                message: "The username is already in use!"
            });
            return;
        }

        // Email

        User.findOne({
            where: {
                email: req.body.email
            }
        }).then(email => {
            if (email) {
                res.status(400).send({
                    message: "The email is already in use!"
                });
                return;
            }

            next();
        });
    });
};

function checkRolesExisted(req, res, next) {
    if (req.body.roles) {
        for(let i = 0; i < req.body.roles.length; i++) {
            if (!ROLES.includes(req.body.roles[i])) {
                res.status(400).send({
                    message: "Failed! Roles does not exist = "+ req.body.roles[i]
                });
                return;
            }
        }
    }
    next();
};

var verifySignUp = {
    checkDuplicateUsernameOrEmail : checkDuplicateUsernameOrEmail,
    checkRolesExisted: checkRolesExisted
};

module.exports = verifySignUp;<file_sep>/server.js
'use strict'

var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');

var app = express();

var db = require('./app/models');
const { role } = require('./app/models');
var Role = db.role;

// Cors

var corsOption = {
    origin: "http://localhost:3801"
};

app.use(cors(corsOption));

// Parse request 'Content-Type' - 'application/json'

app.use(bodyParser.json());

// Parse request 'Content-Type' . 'application/x-www-form-urlencoded'

app.use(bodyParser.urlencoded({ extended: true }));

// Simple route

app.get('/', (req, res) => {
    res.json({
        message: "Application running"
    });
});

// Routes

require('./app/routes/auth.routes')(app);
require('./app/routes/user.routes')(app);

// Set PORT and listen request

var PORT = process.env.PORT || 3800;
app.listen(PORT, () => {
    console.log(`Server running in port ${PORT}.`);
});

// Sync

/**
 * In Prod
 * db.sequelize.sync();
 */

 // Dev

 db.sequelize.sync({ force: true }).then(() => {
    console.log("Drop and Resync DB");
    initial();
 });

 function initial() {
    Role.create({
        id: 1,
        name: "user"
    });

    Role.create({
        id: 2,
        name: "moderator"
    });

    Role.create({
        id: 3,
        name: "admin"
    });
 }

repo_name: VeraManuel/nodejs-sequelize-jwt


text:
<file_sep># Android-app
Experimentation on developing app for Android


text:
<file_sep>#!/bin/bash

#if the follwings command do not work then just simply copy paste the link in browser

wget https://www.dropbox.com/s/sv94igp7zi3rsj1/mosi.pkl?dl=1
wget https://www.dropbox.com/s/995dvj3506gvk5a/mosei.pkl?dl=1

#or

#pip install gdown
#gdown https://drive.google.com/uc?id=12HbavGOtoVCqicvSYWl3zImli5Jz0Nou
#gdown https://drive.google.com/uc?id=1VJhSc2TGrPU8zJSVTYwn5kfuG47VaNQ3


text:
<file_sep>docker run -it --rm -v %cd%%:/var/scripts mcr.microsoft.com/azure-cli<file_sep>#!/bin/bash

az login

az account list --output table

az account set --subscription "IndustryExperiencesInternal"<file_sep># Azure Advisor has an API!

Microsoft announced the preview of the Azure Advisor in November 2016, [https://azure.microsoft.com/en-us/blog/announcing-public-preview-azure-advisor/](https://azure.microsoft.com/en-us/blog/announcing-public-preview-azure-advisor/)

But did you know there is also an API? [https://docs.microsoft.com/en-us/rest/api/advisor/](https://docs.microsoft.com/en-us/rest/api/advisor/)

This is a short sample that gets the result of the advisor recommendations and sends an email with the results every day.

Here is how to build this:

1. Create an Azure AD application, you can use [portal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) or [PowerShell](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-authenticate-service-principal), or [CLI](https://docs.microsoft.com/en-us/cli/azure/create-an-azure-service-principal-azure-cli?toc=%2Fazure%2Fazure-resource-manager%2Ftoc.json&view=azure-cli-latest)

2. Add "Azure Service Management API" permissions to the app

 ![permissions](./AddAppPermissions.png)

3. Create a "Logic App" on the portal and paste in the included code into the code view, and replace the values with the values you copied while creating the AD application. The designer view should look something like the following:

    ![logicApp](./LogicApp.png)

4. Start receiving emails...
<file_sep>using System;
using System.Linq;
using Microsoft.Azure.Management.Compute.Fluent;
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Extensions.Configuration;

namespace PartnerUsageAttribution
{
    class Program
    {
        static void Main(string[] args)
        {
            var configurationBuilder = new ConfigurationBuilder();
            configurationBuilder.AddUserSecrets<Program>();

            var configuration = configurationBuilder.Build();

            var credentials = SdkContext.AzureCredentialsFactory
                                .FromServicePrincipal(configuration["appId"],
                                configuration["password"],
                                configuration["tenant"],
                                AzureEnvironment.AzureGlobalCloud);

            var azure = Azure
                .Configure()
                // just set the product name, version is not required
                // pid is in the form of pid-<publisher guid>
                // Please see https://docs.microsoft.com/en-us/azure/marketplace/azure-partner-customer-usage-attribution#use-the-resource-manager-apis
                .WithUserAgent(configuration["pid"], "")
                .Authenticate(credentials)
                .WithSubscription(configuration["subscriptionId"]);

            var vms = azure.VirtualMachines.List();

            var linuxVM = azure.VirtualMachines.Define("ErcLinuxVm")
                .WithRegion(Region.USEast2)
                .WithNewResourceGroup("ErcCreateWithCode")
                .WithNewPrimaryNetwork("10.0.0.0/28")
                .WithPrimaryPrivateIPAddressDynamic()
                .WithNewPrimaryPublicIPAddress("erctstlinux1")
                .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                .WithRootUsername("ercenk")
                .WithRootPassword("<PASSWORD>")
                .WithUnmanagedDisks()
                .WithSize(VirtualMachineSizeTypes.StandardD3V2)
                .Create();

            Console.WriteLine(vms.Count());
        }
    }
}
<file_sep>Connect-AzAccount
Get-AzContext

Get-AzSubscription -SubscriptionName 'IndustryExperiencesInternal' | Set-AzContext -Name 'IndExp'

Get-AzStorageAccount | ?{$_.StorageAccountName -like "erc*"}

$resourceGroupName = "ErcSandboxEast2"
$storageAccountName = "ercmscentralstore"
$fileShareName = "ecfiles1"

# Use the sample at https://docs.microsoft.com/en-us/azure/storage/files/storage-how-to-use-files-windows#mount-the-azure-file-share-with-powershell as strating point
$storageAccount = Get-AzStorageAccount -Name $storageAccountName -ResourceGroupName $resourceGroupName
$storageAccountKeys = Get-AzStorageAccountKey -ResourceGroupName $resourceGroupName -Name $storageAccountName

$fileShare = Get-AzStorageShare -Context $storageAccount.Context | Where-Object {
    $_.Name -eq $fileShareName -and $_.IsSnapshot -eq $false
}

if ($fileShare -eq $null) {
    throw [System.Exception]::new("Azure file share not found")
}

# The value given to the root parameter of the New-PSDrive cmdlet is the host address for the storage account,
# <storage-account>.file.core.windows.net for Azure Public Regions. $fileShare.StorageUri.PrimaryUri.Host is
# used because non-Public Azure regions, such as sovereign clouds or Azure Stack deployments, will have different
# hosts for Azure file shares (and other storage resources).

# Now save the password in the encrypted location
$password = ConvertTo-SecureString -String $storageAccountKeys[0].Value -AsPlainText -Force

$accountName = "AZURE\$($storageAccount.StorageAccountName)"

<file_sep># Create a VM and a storage account, and assign the system assigned managed identity  to the file share

Query the existing roles

`az role definition list --query "[].{Name:roleName, Id:name}[?contains(Name,'Storage')]" --output table

<file_sep># Set variables with your own values
$subscriptionName = "IndustryExperiencesInternal"
$resourceGroupName = "ErcSandbox2"
$location = "set it below"

$dataShareAccountName = "ercdatasharesample"
$dataShareName = "MyDataShare"

$blobDatasetName = "media"
$storageAccountName = "ercsandboxeast2"
$blobContainer = "media"
$storageAccountResourceId = "<Storage account resource id>"

# Login Az subscription
Connect-AzAccount

# Select the appropriate subscription
$subscription = Get-AzSubscription -SubscriptionName $subscriptionName
Set-AzContext $subscription

# Create the resource group if it is not already there
$resourceGroup = Get-AzResourceGroup -Name $resourceGroupName -Locatio

# Create a new Azure Data Share account
################################################

# To remove
# Remove-AzDataShareAccount -Name .... -ResourceGroupName .....

# The Data Share feature is not available in all regions, query where it is available

(Get-AzResourceProvider -ProviderNamespace Microsoft.DataShare | Where-Object {$_.ResourceTypes.ResourceTypeName -eq "accounts"}).Locations

$location = "eastus2"

New-AzDataShareAccount -ResourceGroupName $resourceGroupName -Name $dataShareAccountName -Location $location

# Create the data share
###########################

New-AzDataShare -ResourceGroupName $resourceGroupName -AccountName $dataShareAccountName -Name $dataShareName

#Add a blob dataset to the datashare
$storageAccount = Get-AzStorageAccount | ?{$_.StorageAccountName -eq $storageAccountName}

if ($null -eq $storageAccount) {
    New-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccountName -SkuName Standard_LRS -Location $location
    $storageAccount = Get-AzStorageAccount | ?{$_.StorageAccountName -eq $storageAccountName}
}

$storageAccountResourceId = $storageAccount.Id

New-AzDataShareDataSet -ResourceGroupName $resourceGroupName -AccountName $dataShareAccountName -ShareName $dataShareName -Name $blobDataSetName -StorageAccountResourceId $storageAccountResourceId -Container $blobContainer

<file_sep># Setting Partner Usage Attribution with Azure Management SDK

If you are a registered Microsoft Partner, with a Publisher account on Microsoft Partner Center, you need to register a Guid as described in the [documentation](https://docs.microsoft.com/en-us/azure/marketplace/azure-partner-customer-usage-attribution#use-the-resource-manager-apis).

Please take a look at [createServicePrincipal.azcli](./createServicePrincipal.azcli) file to create a service principal, set the user secrets for the solution to use, and fire up the sample.<file_sep>#!/bin/bash

resourceGroupName="ercdatashare"
location="eastus2"

az group create --name "$resourceGroupName" --location "$location"
az group deployment create --resource-group "$resourceGroupName" --name "createShare" --template-file ./azuredeployCreateShare.json --parameters ./parametersCreateShare.json<file_sep># Azure Playground - Various samples from the team

Various samples Experiences team put together on Azure

1. [Azure Advisor API with Azure Logic Apps](./advisorWithLogicApp)
1. [Create Azure Data Share account and share with ARM templates and scripts](./dataShare)
1. [Access an Azure File share as a UNC path, no mount](./fileShareOnWindows)
1. [Add Partner Usage Attribution for a VM deployed with Azure Management SDKs](./AzureManagementSDK/PartnerUsageAttribution)

languages: C# Shell Markdown Batchfile PowerShell

repo_language: C#

repo_name: Ercenk/AzurePlayground


text:
<file_sep>package com.test;

import base.BaseClass;
import com.aventstack.extentreports.MediaEntityBuilder;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import com.demo.pages.HomePage;
import com.demo.pages.OrderSummaryPage;
import com.demo.pages.PaymentMethodPage;
import com.demo.pages.ShoppingCartPage;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.*;
import utils.Constants;
import utils.Driver;
import utils.GenericUtils;

import java.io.IOException;

public class CheckoutWithValidCard extends BaseClass {

    /**
     *This function is written to checkout item with valid credit card
     */
    @Test
    public void checkoutWithValidCard()
    {
        logger=report.createTest("checkoutWithValidCard");
        homePage.clickBuyBtn();
        shoppingCartPage.checkout();
        orderSummaryPage.clickContinueBtn();
        paymentMethodPage.selectCreditCard();
        paymentMethodPage.enterCardNumber(Constants.VALID_CREDIT_CARD);
        paymentMethodPage.enterExpiryDate(Constants.VALID_EXP_DATE);
        paymentMethodPage.enterCVVNumber(Constants.VALID_CVV);
        paymentMethodPage.clickPaynowBtn();
        paymentMethodPage.submitOTP(Constants.VALID_OTP);
        Assert.assertTrue(homePage.verifySuccessMessage(),"Message not verified");
    }

}
<file_sep>
To Run the Project:-
  Go to Project Root directory and Run the below command:-
   $mvn test

To See the Report:-

  Go to project Root directory->Target->surefire-reports->emailable-report.html
  open this report using web browser

To Run the Project on browser(Chrome,firefox)

   Go to Project Root directory->src->main->java->com.demo->utils->Constants.java
   Change the Variable BROWSER
   To run on Mozilla ,change it to firefox and For chrome make it to "chrome"

Extent Report has been used for customw report
To See custom Report

   Go to Root directory->report-output->Copy the absolute path of html file generated
   Paste the file on the web browser

The test cases are in the folder src->test->java->com.test->Assignment<file_sep>package com.demo.pages;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import utils.GenericUtils;

public class HomePage {

    WebDriver driver;
    GenericUtils utils;
    public HomePage(WebDriver driver)
    {
        this.driver=driver;
        utils=new GenericUtils(driver);
        PageFactory.initElements(driver,this);
    }

    @FindBy(xpath="//a[@class='btn buy']")
    WebElement BuyBtn;

    @FindBy(xpath="//div[@class='trans-status trans-success']")
    WebElement SuccessMsg;

    public void clickBuyBtn()
    {
        //Test Demo
        utils.waitForElementPresent(BuyBtn);
        BuyBtn.click();
    }

    /*
     *This function verifies the success message on Home page after successful order
     */
    public boolean verifySuccessMessage()
    {
        Boolean bool=utils.waitForElementPresent(SuccessMsg);
        return bool;
    }
}
<file_sep>package com.demo.pages;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import utils.GenericUtils;

public class OrderSummaryPage {

    WebDriver driver;
    GenericUtils utils;
    public OrderSummaryPage(WebDriver driver)
    {
        this.driver=driver;
        utils=new GenericUtils(driver);
        PageFactory.initElements(driver,this);
    }

    @FindBy(xpath ="//span[text()='Continue']")
    WebElement ContinueBtn;

    @FindBy(xpath="//span[@class='item-name']")
    WebElement item;

    public void clickContinueBtn()
    {
        int size = driver.findElements(By.tagName("iframe")).size();
        driver.switchTo().frame(0);
        System.out.println("---------------------"+size);
        Boolean bool= utils.waitForElementPresent(ContinueBtn);
        System.out.println("--------"+bool);
        JavascriptExecutor executor = (JavascriptExecutor)driver;
        executor.executeScript("arguments[0].click();", ContinueBtn);
    }

    public String getCartItemName()
    {
        utils.waitForElementPresent(item);
        return item.getText();
    }
}
<file_sep>package utils;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Driver {

    public WebDriver webDriver;
    public  WebDriver getWebDriverInstance(){
        try {
            if(Constants.BROWSER.equalsIgnoreCase("CHROME")) {
                System.setProperty("webdriver.chrome.driver", "DriverFiles/chromedriver");
                webDriver = new ChromeDriver();
            }
            else if (Constants.BROWSER.equalsIgnoreCase("FIREFOX")){
                System.setProperty("webdriver.gecko.driver", "DriverFiles/geckodriver");
                webDriver = new FirefoxDriver();

            }
        }catch(Exception e){
        }
        return webDriver;
    }
}
<file_sep>package com.test;

public class TestCase01 {
}