text:
<repo_name>flaviochess/mongofly<file_sep>/mongofly-core/src/main/java/com/github/mongofly/core/commands/utils/GetBodyFromCommand.java
package com.github.mongofly.core.commands.utils;

public class GetBodyFromCommand {

    private static final String PARENTHESES_OPEN = "(";
    private static final String PARENTHESES_CLOSE = ")";

    /**
     * Returns the body of a valid command,
     *
     * Samples:
     * <pre>
     * * db.user.find({name: "<NAME>", age: 10})                         -> returns: {name: "<NAME>", age: 10}
     * * db.otherCollection.update([{name: "<NAME>", age: 10}, {...}])   -> returns: [{name: "<NAME>", age: 10}, {...}]
     * * db.otherCollection.update([{...}, {...}],{...})                   -> returns: [{...}, {...}],{...}
     * </pre>
     *
     * @param command - a valid mongodb shell command
     * @return the body of command
     */
    public static String get(String command) {

        int firstParenthesesOpenPosition = command.indexOf(PARENTHESES_OPEN);
        int lastParenthesesClosePosition = command.lastIndexOf(PARENTHESES_CLOSE);
        String commandBody = command.substring(firstParenthesesOpenPosition + 1, lastParenthesesClosePosition);

        return commandBody;
    }
}
<file_sep>/mongofly-core/src/test/java/com/github/mongofly/core/commands/strictmode/ConvertNumberIntTest.java
package com.github.mongofly.core.commands.strictmode;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class ConvertNumberIntTest {

    ConvertNumberInt convertNumberInt;

    @Before
    public void initClass() {

        convertNumberInt = new ConvertNumberInt();
    }

    @Test
    public void shouldSuccess_whenGive_formattedCommand_replaceNumberIntFunction_toStrictMode() {

        String command = "db.character.insert(\n" +
                "{\n" +
                    "\t\"name\" : \"<NAME>\",\n" +
                    "\t\"season\" : NumberInt(5),\n" +
                    "\t\"codename\" : \"The girl who waited\"\n" +
                "});";

        String expectedCommand = "db.character.insert(\n" +
                "{\n" +
                "\t\"name\" : \"<NAME>\",\n" +
                "\t\"season\" : {\"$numberInt\": \"5\"},\n" +
                "\t\"codename\" : \"The girl who waited\"\n" +
                "});";

        String strictModeCommand = convertNumberInt.toStrictMode(command);

        Assert.assertEquals("convert NumberInt to strict mode", expectedCommand, strictModeCommand);
    }

    @Test
    public void shouldSuccess_whenGive_formattedCommandWithManyNumberInt_replaceAllNumberIntFunction_toStrictMode() {

        String command = "db.newseasons.insert(\n" +
                "{\n" +
                "    \"season\": NumberInt(1),\n" +
                "    \"data\" : {\n" +
                "        \"year\": NumberInt(2015),\n" +
                "        \"Incarnation\": \"ninth doctor\"\n" +
                "    }\n" +
                "});";

        String expectedCommand = "db.newseasons.insert(\n" +
                "{\n" +
                "    \"season\": {\"$numberInt\": \"1\"},\n" +
                "    \"data\" : {\n" +
                "        \"year\": {\"$numberInt\": \"2015\"},\n" +
                "        \"Incarnation\": \"ninth doctor\"\n" +
                "    }\n" +
                "});";

        String strictModeCommand = convertNumberInt.toStrictMode(command);

        Assert.assertEquals("convert NumberInt functions to strict mode", expectedCommand, strictModeCommand);
    }

    @Test
    public void shouldSuccess_whenGive_commandWithManyNumberInt_replaceAllNumberIntFunction_toStrictMode() {

        String command = "db.newseasons.insert({\"season\": NumberInt(2),\"data\" : {\"year\": NumberInt(2016),\"Incarnation\": \"tenth doctor\"}});";

        String expectedCommand = "db.newseasons.insert({\"season\": {\"$numberInt\": \"2\"},\"data\" : {\"year\": {\"$numberInt\": \"2016\"},\"Incarnation\": \"tenth doctor\"}});";

        String strictModeCommand = convertNumberInt.toStrictMode(command);

        Assert.assertEquals("convert NumberInt functions to strict mode", expectedCommand, strictModeCommand);
    }
}
<file_sep>/mongofly-core/src/main/java/com/github/mongofly/core/commands/createindex/CreateIndexObject.java
package com.github.mongofly.core.commands.createindex;

import com.mongodb.client.model.IndexOptions;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.bson.Document;

import java.util.Optional;

@Getter
@AllArgsConstructor
public class CreateIndexObject {

    private Document keys;

    private Optional<IndexOptions> indexOptions;
}
<file_sep>/mongofly-core/src/main/java/com/github/mongofly/core/commands/RunMongoCommand.java
package com.github.mongofly.core.commands;

import com.github.mongofly.core.commands.strictmode.ConvertToStrictMode;
import com.github.mongofly.core.exceptions.MongoflyException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RunMongoCommand {

    private static final String COMMAND_PREFIX = "db.";

    private final RunCommandFactory runCommandFactory;

    private final ConvertToStrictMode convertToStrictMode;

    public RunMongoCommand(RunCommandFactory runCommandFactory, ConvertToStrictMode convertToStrictMode) {
        this.runCommandFactory = runCommandFactory;
        this.convertToStrictMode = convertToStrictMode;
    }

    public void run(String command) {

        log.debug("Trying to execute: " + command);

        if (!command.startsWith(COMMAND_PREFIX)) {
            throw new MongoflyException("It's not a valid command. This does not start with \"db...\": " + command);
        }

        String convertedCommand = convertToStrictMode.convert(command);

        try {

            runCommandFactory.factory(convertedCommand).run(convertedCommand);

        } catch (RuntimeException ex) {

            log.error("Error trying to execute the command: " + command);
            throw ex;
        }

    }

}
<file_sep>/README.md
# MongoFly

Mongofly é um starter do Spring Boot para executar scripts do MongoDB. Ele é inspirado na forma de funcionamento do Flyway.

## Como utilizar

Atualmente o projeto encontra-se apenas no repositório JitPack e funciona em projetos já configurados com o Spring Data MongoDB.

### Pré requisitos

* Spring Boot 2.x
* Spring Data MongoDB

Esse starter utiliza o MongoDB já configurado no projeto para executar os scripts. Por isso é necessário que você já tenha configurado o Spring Data MongoDB no projeto informando qual é o banco e outras informações que forem relevantes ao seu projeto.

### Configurando o Mongofly em seu projeto

Atualmente o Mongofly encontra-se no repostório de projetos JitPack, por isso é necessário ensinar ao seu gerenciador de dependencias que deve buscar bibliotecas de lá também.

No caso do Maven ficará assim:

```
    <repositories>
        <repository>
            <id>jitpack.io</id>
            <url>https://jitpack.io</url>
        </repository>
    </repositories>
```

E no Gradle

```
    allprojects {
		repositories {
			...
			maven { url 'https://jitpack.io' }
		}
	}
```

Para outros gerenciadores de dependencias consultar a página do projeto no JitPack: [https://jitpack.io/mongofly](https://jitpack.io/#flaviochess/mongofly)

Também é necessário criar uma pasta chamada `mongofly` no seu classpath (por exemplo `src/main/resources/mongofly`), onde ficarão armazenados os scripts do MongoDB que devem ser executados. Assim que o projeto for iniciado, o Mongofly irá verificar na collection também chamada `mongofly` os arquivos que ainda não foram executados com sucesso e executar-los.

## Criando os scripts

Os scripts ficarão dentro da pasta `mongofly`. A seguir as indicações de como o Mongofly espera estes arquivos.

### Formato do arquivo

Os scripts devem ser arquivos do tipo json. Dentro de cada json pode ter um ou muitos comandos do MongoDB.

O nome do arquivo deve seguir a nomeclatura: versao__nome_de_sua_preferencia.json, onde a versão deve sempre iniciar com a letra "v" e seguir com dois underscore `_` após a versão. Exemplos de nomes de arquivos válidos seriam:

```
v1__meu_primeiro_script.json

v2__meu-segundo-script.json

v3__meuTerceiroScript.json
```

Os arquivos serão executados em ordem crescente de versão e por isso as versões não devem ser repetidas para evitar que sejam executados em uma ordem indesejada.

Apenas são aceitos comandos que utilizam a nomeclatura padrão do MongoDB, as que normalmente se iniciam por "db.collection.operation", por exemplo: `db.users.insert(...);`

Todo commando deve encerrar com ponto e virgula `;`.

Os comandos podem ser separados dentro do arquivo por linhas em branco se assim preferir. Também é permitido usar quebras de linha em um commando para identar o mesmo, não há restrições quanto a formatação dos arquivos.

A seguir um exemplo de conteúdo de um arquivo válido, o arquivo se chama v1__add_users_and_change_felipe_password.json:

```
db.users.insert({
    "name": "Flavio",
    "login": "flaviochess",
    "password": "123",
    "age": 28
});

db.users.insert({
    "name": "Jairo",
    "login": "jairovsky",
    "password": "!@#",
    "age": 24
});

db.users.update(
    {"login" : "Felipe"},
    {$set:
        {"password": "<PASSWORD>"}
    }
);
```

## Comandos aceitos

Este projeto teve como ideia inicial atender uma demanda pessoal, por isso não foram incluídos todos os comandos existentes no MongoDB até o momento, mas acredito que a cobertura desta biblioteca já atenda uma necessidade em geral. Na versão atual o projeto aceita basicamente `insert`, `insertOne`, `insertMany`, `update`, `updateOne`, `updateMany`, `remove`, `deleteOne`, `deleteMany` e `createIndex`. Veja a seguir a documentação oficial dos comandos do MongoDB e alguns detalhes extras:

### Documentação do MongoDB

* [insert](https://docs.mongodb.com/manual/reference/method/db.collection.insert/)
* [insertOne](https://docs.mongodb.com/manual/reference/method/db.collection.insertOne/)
* [insertMany](https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/)
* [update](https://docs.mongodb.com/manual/reference/method/db.collection.update/)
* [updateOne](https://docs.mongodb.com/manual/reference/method/db.collection.updateOne/)
* [updateMany](https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/)
* [remove](https://docs.mongodb.com/manual/reference/method/db.collection.remove/)
* [deleteOne](https://docs.mongodb.com/manual/reference/method/db.collection.deleteOne/)
* [deleteMany](https://docs.mongodb.com/manual/reference/method/db.collection.deleteMany/)

## Como funciona o Mongofly

Sempre que o projeto for inciado o Mongofly irá verificar os arquivos da pasta `mongofly` e verificar quais ainda não foram executados, olhando a *collection* também de nome `mongofly` (criada automaticamente). Ao termino da execução de cada arquivo é criado ou atualizado um documento na *collection* `mongofly` informando se o arquivo executou com sucesso ou não. Um exemplo seria:

```
{
    "version": 1,
    "script": "v1__add_users_and_change_felipe_password.json",
    "executedOn": "2019-04-24 16:27:21",
    "success": true
}
```

Se ocorrer um erro, será lançado uma exceção que interromperá o start da aplicação e inserido um documento com o campo `success` como `false`. Nestes casos é possível corrigir o script e executar a aplicação novamente. Neste momento o Mongofly irá ignorar os scritps que estão como `success = true` pois já foram executados com exito e continuará a partir do `success = false`. Caso agora o script esteja correto, o documento será atualizado para `true` e continuará a execução dos demais arquivos, se houver.

A *collection* `mongofly` será criada apenas após a execução do primeiro arquivo.

## Principais Tecnologias

* [Java 8](https://www.oracle.com/technetwork/pt/java/javase/downloads/jdk8-downloads-2133151.html) - Linguagem de programação
* [Spring Boot 2](https://spring.io/projects/spring-boot) - Framework de desenvolvimento
* [Maven](https://maven.apache.org/) - Gerenciador de dependencias

## Contribuição

Para contribuir com este projeto por favor leio o [CONTRIBUTING.md](https://gist.github.com/PurpleBooth/b24679402957c63ec426) para mais detalhes de como o projeto está estruturado, do nosso código de conduta e os processos de como nos enviar pull requests.

## Versionamento

Utilizamos [SemVer](http://semver.org/) para o versionamento. Para verificiar as versões disponíveis, veja as [releases deste repositório](https://github.com/flaviochess/mongofly/releases).

## Autores

* **<NAME>** - *Initial work* - [flaviochess](https://github.com/flaviochess)

Veja também a lista de [contribuidores](https://github.com/your/project/contributors) que participaram deste projeto.

## Licença

Este projeto possui a licença Apache License 2.0 - veja o arquivo [LICENSE.md](LICENSE.md) para mais detalhes.

## Agradecimentos

* As pessoas que criaram e mantém o driver de MongoDB para Java, cujo é muito bem feito.
* Aos criadores do FlyWay cujo a maneira fácil de gerenciar scripts de banco inspirou este projeto.
* Ao [PurpleBooth](https://github.com/PurpleBooth) por [seu READEME-Template](https://gist.github.com/PurpleBooth/109311bb0361f32d87a2).

<file_sep>/mongofly-autoconfigure/src/main/java/com/github/mongofly/autoconfigure/MongoflyAutoConfiguration.java
package com.github.mongofly.autoconfigure;

import com.github.mongofly.core.ExecuteScripts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;

@Configuration
public class MongoflyAutoConfiguration {

    @Autowired
    MongoTemplate mongoTemplate;

    @Bean
    @ConditionalOnMissingBean
    public ExecuteScripts executeScripts() {

        return new ExecuteScripts(mongoTemplate.getDb());
    }

    @Bean
    @ConditionalOnMissingBean
    public MongoflyStarter mongoflyStarter() {

        return new MongoflyStarter(executeScripts());
    }
}
<file_sep>/mongofly-core/src/main/java/com/github/mongofly/core/commands/insert/InsertObject.java
package com.github.mongofly.core.commands.insert;

import com.mongodb.WriteConcern;
import com.mongodb.client.model.InsertManyOptions;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.bson.Document;

import java.util.List;
import java.util.Optional;

@Getter
@AllArgsConstructor
public class InsertObject {

    private List<Document> documents;

    private Optional<InsertManyOptions> insertOptions;

    private Optional<WriteConcern> writeConcern;

}
<file_sep>/mongofly-core/src/main/java/com/github/mongofly/core/ExecuteScripts.java
package com.github.mongofly.core;

import com.github.mongofly.core.commands.RunCommandFactory;
import com.github.mongofly.core.commands.RunMongoCommand;
import com.github.mongofly.core.commands.strictmode.ConvertToStrictMode;
import com.github.mongofly.core.domains.Mongofly;
import com.github.mongofly.core.domains.MongoflyRepository;
import com.github.mongofly.core.exceptions.MongoflyException;
import com.github.mongofly.core.scripts.GetScriptFiles;
import com.github.mongofly.core.scripts.GetScriptsFromClasspath;
import com.mongodb.client.MongoDatabase;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;

import java.io.*;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Stream;

@Slf4j
public class ExecuteScripts {

    private GetScriptsFromClasspath getScriptsFromClasspath;

    private MongoflyRepository mongoflyRepository;

    private MongoDatabase mongoDatabase;

    private RunCommandFactory runCommandFactory;

    private RunMongoCommand runMongoCommand;

    public ExecuteScripts(MongoDatabase mongoDatabase) {

        this.mongoDatabase = mongoDatabase;
        this.mongoflyRepository = new MongoflyRepository(mongoDatabase);
        this.getScriptsFromClasspath = new GetScriptsFromClasspath();
        this.runCommandFactory = new RunCommandFactory(this.mongoDatabase);
        this.runMongoCommand = new RunMongoCommand(runCommandFactory, new ConvertToStrictMode());
    }

    public void execute() {

        log.info("Starting Mongofly");

        getScriptsFromClasspath.get().stream()
            .filter(this::isUnexecutedScripts)
            .sorted(Comparator.comparing(Resource::getFilename))
            .forEach(this::fileProcess);

        log.info("Finish Mongofly");
    }

    private boolean isUnexecutedScripts(Resource resource) {

        String version = getFileVersion(resource.getFilename());
        Optional<Mongofly> execution = mongoflyRepository.findByVersion(version);

        log.debug("Script " + version + " executed: " + execution.isPresent());

        return !execution.isPresent() || !execution.get().isSuccess();
    }

    private void fileProcess(Resource resource) {

        String version = getFileVersion(resource.getFilename());
        Mongofly mongofly = mongoflyRepository.findByVersion(version).orElse(newMongofly(resource));

        List<String> commands = extractCommands(resource);

        try {

            for (String command : commands) {

                runMongoCommand.run(command);
            }

            mongofly.setExecutedOn(new Date());
            mongofly.setSuccess(true);

        } catch (RuntimeException exception) {

            mongofly.setExecutedOn(new Date());
            mongofly.setSuccess(false);
            throw new MongoflyException(exception);

        } finally {

            mongoflyRepository.save(mongofly);
        }

    }

    private Mongofly newMongofly(Resource resource) {

        Mongofly mongofly = new Mongofly();
        mongofly.setScript(resource.getFilename());
        mongofly.setVersion(getFileVersion(resource.getFilename()));

        return mongofly;
    }

    private String getFileName(Path path) {

        return path.getFileName().toString();
    }

    private String getFileVersion(String filename) {
        return filename.split("__")[0].toUpperCase().replace("V", "");
    }

    private List<String> extractCommands(Resource resource) {

        List<String> commands = new ArrayList<>();

        StringBuilder command = new StringBuilder();

        try (BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()))) {

            String line;
            while ((line = br.readLine()) != null) {

                line = line.trim();

                if (line.isEmpty()) {
                    continue;
                }

                command.append(line);

                if (line.endsWith(";")) {
                    commands.add(command.toString());
                    command = new StringBuilder();
                }
            }

            if (command.length() > 0) {

                throw new MongoflyException("Command don't finish with \";\" - " + command.toString());
            }

        } catch (IOException ioe) {

            throw new RuntimeException();
        }

        return commands;
    }

}
<file_sep>/mongofly-core/src/main/java/com/github/mongofly/core/commands/utils/GetWriteConcern.java
package com.github.mongofly.core.commands.utils;

import com.github.mongofly.core.exceptions.MongoflyException;
import com.mongodb.WriteConcern;
import org.bson.Document;

import java.util.Optional;
import java.util.OptionalInt;

public class GetWriteConcern {

    public static final String WRITE_CONCERN = "writeConcern";
    public static final String W_PARAM = "w";
    public static final String W_TIMEOUT = "wtimeout";

    public static Optional<WriteConcern> get(Document options) {

        if(!isWriteConcern(options)) {
            return Optional.empty();
        }

        Document writeConcern = options.get("writeConcern", Document.class);

        return Optional.of(convertWriteConcern(writeConcern));
    }

    private static boolean isWriteConcern(Document document) {
        return document.containsKey(WRITE_CONCERN);
    }

    private static WriteConcern convertWriteConcern(Document writeConcern) {

        OptionalInt w = OptionalInt.empty();
        OptionalInt wTimeoutMS = OptionalInt.empty();

        if(writeConcern.containsKey(W_PARAM)) {
            w = OptionalInt.of(writeConcern.getInteger(W_PARAM));

            if(writeConcern.containsKey(W_TIMEOUT)) {
                wTimeoutMS = OptionalInt.of(writeConcern.getInteger(W_TIMEOUT));
            }
        }

        if(w.isPresent()) {

            if(wTimeoutMS.isPresent()) {
                return new WriteConcern(w.getAsInt(), wTimeoutMS.getAsInt());
            } else {
                return new WriteConcern(w.getAsInt());
            }
        }

        throw new MongoflyException("Invalid writeConcern, w parameter not found");
    }
}
<file_sep>/mongofly-core/src/main/java/com/github/mongofly/core/scripts/GetScriptFiles.java
package com.github.mongofly.core.scripts;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class GetScriptFiles {

    private final static String SCRIPTS_CONFIGURATION_PATH = "mongofly";

    public List<Path> get() {

        Path folder = Paths.get(SCRIPTS_CONFIGURATION_PATH);

        if(!isValidDirectory(folder)) {

            log.error("Invalid path configuration files: {}", SCRIPTS_CONFIGURATION_PATH);
            return new ArrayList();
        }

        DirectoryStream<Path> configurationPaths;

        try {

            configurationPaths = Files.newDirectoryStream(folder, p -> p.getFileName().toString().endsWith(".json"));

        } catch (IOException iOException) {

            log.error("Fail to find files in the folder {}", SCRIPTS_CONFIGURATION_PATH, iOException);
            return new ArrayList();
        }

        List<Path> scripts = new ArrayList();
        configurationPaths.forEach(scripts::add);

        log.debug("{} script files found", scripts.size());

        return scripts;
    }

    private boolean isValidDirectory(Path path) {

        return Files.exists(path) && Files.isDirectory(path);
    }
}
<file_sep>/mongofly-core/src/main/java/com/github/mongofly/core/commands/update/RunUpdateCommand.java
package com.github.mongofly.core.commands.update;

import com.github.mongofly.core.commands.utils.GetMongoCollection;
import com.github.mongofly.core.commands.RunCommand;
import com.github.mongofly.core.commands.utils.GetCollectionNameFromCommand;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

public class RunUpdateCommand implements RunCommand {

    private MongoDatabase db;

    public RunUpdateCommand(MongoDatabase db) {

        this.db = db;
    }

    @Override
    public void run(String command) {

        UpdateObject updateObject = UpdateConvert.convert(command);

        String collectionName = GetCollectionNameFromCommand.get(command);

        MongoCollection<Document> collection = GetMongoCollection.get(db, collectionName, updateObject.getWriteConcern());

        if (updateObject.isMulti()) {

            if (updateObject.getUpdateOptions().isPresent()) {

                collection.updateMany(updateObject.getQuery(), updateObject.getUpdate(), updateObject.getUpdateOptions().get());

            } else {

                collection.updateMany(updateObject.getQuery(), updateObject.getUpdate());
            }

        } else {

            if (updateObject.getUpdateOptions().isPresent()) {

                collection.updateOne(updateObject.getQuery(), updateObject.getUpdate(), updateObject.getUpdateOptions().get());

            } else {

                collection.updateOne(updateObject.getQuery(), updateObject.getUpdate());
            }
        }
    }

}
<file_sep>/mongofly-core/src/main/java/com/github/mongofly/core/commands/remove/DeleteObject.java
package com.github.mongofly.core.commands.remove;

import com.mongodb.WriteConcern;
import com.mongodb.client.model.DeleteOptions;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.bson.Document;

import java.util.Optional;

@Getter
@AllArgsConstructor
public class DeleteObject {

    private Document query;

    private Optional<DeleteOptions> deleteOptions;

    private Optional<WriteConcern> writeConcern;

    private boolean justOne;
}
<file_sep>/mongofly-core/src/main/java/com/github/mongofly/core/commands/remove/RunDeleteCommand.java
package com.github.mongofly.core.commands.remove;

import com.github.mongofly.core.commands.utils.GetMongoCollection;
import com.github.mongofly.core.commands.RunCommand;
import com.github.mongofly.core.commands.utils.GetCollectionNameFromCommand;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

public class RunDeleteCommand implements RunCommand {

    private final MongoDatabase db;

    public RunDeleteCommand(MongoDatabase db) {

        this.db = db;
    }

    @Override
    public void run(String command) {

        DeleteObject deleteObject = RemoveConvert.convert(command);

        String collectionName = GetCollectionNameFromCommand.get(command);

        MongoCollection<Document> collection = GetMongoCollection.get(db, collectionName, deleteObject.getWriteConcern());

        if (deleteObject.isJustOne()) {

            if (deleteObject.getDeleteOptions().isPresent()) {

                collection.deleteOne(deleteObject.getQuery(), deleteObject.getDeleteOptions().get());

            } else {

                collection.deleteOne(deleteObject.getQuery());
            }

        } else {

            if (deleteObject.getDeleteOptions().isPresent()) {

                collection.deleteMany(deleteObject.getQuery(), deleteObject.getDeleteOptions().get());

            } else {

                collection.deleteMany(deleteObject.getQuery());
            }

        }
    }
}

repo_name: flaviochess/mongofly


text:
<repo_name>stefanalexlupu/alpha-cluj<file_sep>/components/AboutSection.vue
<template>

          Ce sunt întâlnirile Alpha?

          O serie de 15 sesiuni interactive pe parcursul a 11 săptămâni, în cadrul cărora vom aborda diferite teme legate de viața și credința creștină. Acestea vor fi discutate într-un mediu prietenos, deschis și informal în care participanții sunt încurajați să își expună liber părerea, să pună întrebări și să caute răspunsuri.

          Cum aproape orice eveniment social reușit este concentrat în jurul mâncării, la fel și noi începem întâlnirile Alpha cu o mica gustare, timp în care ne cunoaștem mai bine și ne familiarizăm unii cu alții. Vom avea momente de ice-breaking, video-uri și multe discuții libere.

          Toată lumea este binevenită, dar întâlnirile Alpha sunt gândite în special pentru persoanele care nu se descriu ca fiind creștini sau credincioși practicanți.

          Pe scurt, scopul întâlnirilor Alpha e să abordăm aceste teme, să luăm în calcul informațiile existente, să dezbatem și să-L lăsăm pe Dumnezeu să se prezinte singur.

          Nu există nicio taxă de participare – cursul Alpha este gratuit!

          Ce teme abordează întâlnirile Alpha?

La fiecare întâlnire se vor dezbate diferite teme, precum:

            Oare viața nu e mai mult decât pare?

            Cine este Isus?

            De ce să citesc Biblia?

            De ce să mă rog?

            Cum pot avea credință?

            Ce e și cu biserica?

</template>

<file_sep>/components/AlphaCarousel.vue
<template>
  <VueSlickCarousel
    dots
    autoplay
    :autoplay-speed="15000"
    :slides-to-show="3"
    :responsive="settings"
  >
    <slot />
  </VueSlickCarousel>
</template>

<file_sep>/components/TheSocialMediaSidebar.vue
<template>

      <FontAwesomeIcon :icon="['fab', 'instagram']" />

      <FontAwesomeIcon :icon="['fab', 'facebook']" />

</template>

<file_sep>/plugins/fontawesome.js
import Vue from 'vue'
import { library } from '@fortawesome/fontawesome-svg-core'
import { faFacebook, faInstagram } from '@fortawesome/free-brands-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'

library.add(faFacebook, faInstagram)

Vue.component('FontAwesomeIcon', FontAwesomeIcon)
<file_sep>/components/TheFooter.vue
<template>

      Powered by <NAME>

    Acord de confidențialitate privind protecția datelor

</template>

<file_sep>/components/TestimonialCard.vue
<template>

{{ name }}

      <slot />

</template>

<file_sep>/components/TheNavBar.vue
<template>

          Despre Alpha

          Testimoniale

          Înscriere

</template>

<file_sep>/plugins/components.js
import Vue from 'vue'
import AlphaButton from '../components/AlphaButton.vue'

Vue.component('AlphaButton', AlphaButton)
<file_sep>/pages/index.vue
<template>

      <TheHeader />

      <q class="block font-bold text-2xl md:text-3xl lg:text-4xl mb-4">
        Fie există Dumnezeu, fie nu. Ambele posibilități sunt înspăimântătoare. Dacă există Dumnezeu, am face bine să aflăm cine e El, să aflăm ce vrea El și să facem ceea ce zice El. Dacă nu există Dumnezeu, avem o problemă, pentru că noi gonim prin spațiu cu 66000 de mile pe oră și nimeni nu e în control.
      </q>

        [un astronom rus]

    <AboutSection />

    <client-only>

          Alții ce spun despre grupurile
          Alpha?

        <AlphaCarousel>

            <TestimonialCard
              image="cristina-turda.jpeg"
              name="<NAME>"
            >

                Alpha pentru mine a reprezentat într-un cuvânt "luminare". Umblam de multi ani la Biserică, însă la Alpha, la fiecare sesiune simțeam că mi se conectează toate informațiile pe care le-am acumulat peste ani și se creau noi legături, noi perspective.

La Alpha am înțeles că, creștinii de pretudindeni vorbesc aceeași limbă.

Alpha este o comunitate de oameni foarte faini din care iți dorești să nu mai pleci și să nu se termine niciodată sesiunile.

                Iar mancarea are alt gust atunci când o mănânci cu prietenii din Alpha! 😍😇

            </TestimonialCard>

            <TestimonialCard
              image="amalia-osan.jpeg"
              name="<NAME>"
            >

                Eram în căutarea unei relații cu Dumnezeu dar nu știam de unde sa încep. În urma sesiunilor Alpha am început să fac pași mici spre un Dumnezeu care știu că e acolo, mă așteaptă și mă iubește.

            </TestimonialCard>

            <TestimonialCard
              image="paul-albu.jpeg"
              name="<NAME>"
            >

                Pentru mine cursul Alpha reprezintă un “safe space” în care am  povestit despre Dumnezeu, Cristos sau Biblie.

                E locul în care am reușit să adresez toate întrebările inconfortabile și la care să imi și găsesc răspuns.

Dar Alpha e mai mult decât atât, sunt oameni cu diferite experiențe de viață și diferite credințe (ortodocși, catolici, agnostici, atei etc), fiecare venind cu ideile și convingerile sale pe care ulterior le dezbatem.

Pentru mine este o comunitate de prieteni care încearcă să cunoască adevărul și unde orice opinie e acceptată.

            </TestimonialCard>

            <TestimonialCard
              image="stefania-rosu.jpeg"
              name="<NAME>"
            >

                Pentru mine cursul Alpha a însemnat revitalizarea relației mele cu Dumnezeu, fundația căsuței pe care de această dată o voi construi pe stâncă.

            </TestimonialCard>

        </AlphaCarousel>

    </client-only>

      <client-only>
        <RegistrationForm />
      </client-only>

</template>

<file_sep>/components/TheHeader.vue
<template>

          Ai întrebări despre viață?

          Fiecare om ar trebui să fie un căutător al adevărului. Trăim într-o lume care promovează ideea că viața de aici e tot ceea ce este, că te naști, trăiești, mori și atât. Dar dacă nu se termina totul aici? Dacă ceea ce se vede nu e tot? Dacă exista Cineva peste toate lucrurile pe care noi le putem observa și înțelege?

          Alpha explorează această posibilitate.

          Dacă te întrebi și tu aceste lucruri, atunci întâlnirile Alpha sunt pentru tine!

          Te provocăm să te înscrii!

        Înregistrează-te acum!

</template>

<file_sep>/components/AlphaButton.vue
<template>
  <component :is="as" type="submit" v-bind="classOptions">
    <slot />
  </component>
</template>

<file_sep>/formulate.config.js
export default {
  rules: {
    phone: ({ value }) => {
      const isPhone = /^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/
      return Promise.resolve(value === '' || isPhone.test(value))
    }
  },
  classes: {
    outer: 'mb-4',
    wrapper (context) {
      switch (context.classification) {
        case 'box':
          return 'flex'
        default:
          return ''
      }
    },
    input (context) {
      switch (context.classification) {
        case 'box':
          return 'mr-1'
        default:
          return 'px-3 py-2 mb-1 border border-gray-400 rounded outline-none w-full'
      }
    },
    label: 'font-medium text-sm',
    error: 'mb-1 text-red-700 text-xs '
  }
}
<file_sep>/components/RegistrationForm.vue
<template>

      Formular

      Se pare că a apărut o eroare la trimiterea înscrierii tale. Te rugăm să verifici conexiunea ta la internet, sau sa încerci din nou mai târziu.

      Felicitări pentru că ai acceptat provocarea Alpha! Te vom contacta în cel mai scurt timp posibil pentru a-ți oferi detalii despre data și locația următoarei serii de întâlniri.

    <FormulateForm v-else @submit="submitRegistrationForm">
      <FormulateInput
        label-class="is-required"
        type="text"
        label="Nume și prenume"
        name="name"
        validation="required"
        :validation-messages="{
          required: 'Câmpul este obligatoriu',
        }"
      />
      <FormulateInput
        label-class="is-required"
        type="number"
        label="Vârsta"
        name="age"
        validation="required"
        :validation-messages="{
          required: 'Câmpul este obligatoriu',
        }"
      />
      <FormulateInput
        label-class="is-required"
        type="text"
        label="Telefon"
        name="phone"
        validation="required|phone"
        placeholder="0700000000"
        :validation-messages="{
          required: 'Câmpul este obligatoriu',
          phone: 'Introduceți un număr valid de telefon (fără spații)'
        }"
      />
      <FormulateInput
        type="textarea"
        label="Cum ai aflat despre întâlnirile Alpha?"
        name="info"
      />
      <FormulateInput
        id="form-gdpr"
        label-class="is-required"
        type="checkbox"
        name="gdpr"
        validation="required"
        :validation-messages="{
          required: 'Câmpul este obligatoriu',
        }"
      >
        <template #label="{id}">

            Am citit si sunt de acord cu politica de protecție a datelor

        </template>
      </FormulateInput>
      <AlphaButton as="FormulateInput" type="submit" target-class-attribute="input-class">
        Trimite
      </AlphaButton>
    </FormulateForm>

</template>

branch_name: refs/heads/main

languages: Vue JavaScript

repo_language: Vue

repo_name: stefanalexlupu/alpha-cluj


text:
<repo_name>yanghedong/yanghedong.github.com<file_sep>/_posts/2012-08-25-first-post.md
---
layout: default
title: 渐行渐远
---
##{{ page.title }}

似乎太沉溺于所谓科研了，跟整个IT行业越来越隔。不是没有关注这里面的消息，只没有了那种感同身受的心跳与自然。思考的快乐，有时会遮挡具体的生活，久了以后越发有一种渐行渐远的感觉。

{{ page.date | date_to_string }}

branch_name: HEAD

repo_language: Markdown


text:
<repo_name>LucasArtel33/todo_react<file_sep>/src/components/TasksEpic/TaskForm.js
import React, { useState } from "react";
import { View, TextInput, StyleSheet, Button } from "react-native";
import { useDispatch } from "react-redux";

import { addTask } from "../../redux/actions";

const TaskForm = ({}) => {
  const [title, setTitle] = useState("");

  const dispatch = useDispatch();

  const _onChangeText = (value) => {
    setTitle(value);
  };

  const _onPressButton = () => {
    if (title.length > 0) {
      dispatch(addTask(title));
      setTitle("");
    }
  };
  return (
    <View style={styles.container}>
      <View style={styles.inputContainer}>
        <TextInput value={title} onChangeText={_onChangeText} />
      </View>
      <Button onPress={_onPressButton} title="Add" color="grey" />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 15,
  },
  inputContainer: {
    borderWidth: 1,
    borderColor: "grey",
    borderRadius: 4,
    paddingLeft: 10,
    width: "80%",
  },
});

export default TaskForm;
<file_sep>/src/redux/actions.js
import { ADD_TASK, TOGGLE_TASK, DELETE_TASK } from "./actionsType";

export const addTask = (title) => ({
  type: ADD_TASK,
  payload: {
    id: new Date().getTime(),
    title,
    isCompleted: false,
  },
});

export const toggleTask = (id) => ({
  type: TOGGLE_TASK,
  payload: {
    id,
  },
});

export const deleteTask = (id) => ({
  type: DELETE_TASK,
  payload: {
    id,
  },
});
<file_sep>/src/redux/reducers/index.js
import { combineReducers } from "redux";
import { tasksList } from "./tasksList";

export default combineReducers({
  tasksList,
});
<file_sep>/src/redux/reducers/tasksList.js
import { ADD_TASK, DELETE_TASK, TOGGLE_TASK } from "../actionsType";

const defaultState = [{ id: 1, title: "Example Task", isCompleted: false }];
export const tasksList = (state = defaultState, action) => {
  // action = {type: NOM_ACTTION, payload}
  switch (action.type) {
    case ADD_TASK:
      return [...state, action.payload];
    case TOGGLE_TASK:
      return state.map((task) => {
        if (task.id === action.payload.id) {
          return {
            id: task.id,
            title: task.title,
            isCompleted: !task.isCompleted,
          };
        } else {
          return task;
        }
      });
    case DELETE_TASK:
      return state.filter((task) => task.id != action.payload.id);
    default:
      return state;
  }
};
<file_sep>/src/components/TasksEpic/CountersContainers.js
import React from "react";
import { View, Text, StyleSheet } from "react-native";

import Counter from "../_Shared/Counter";

const CountersContainer = ({ nbTasks, nbTasksCompleted }) => {
  return (
    <View style={styles.container}>
      <Counter nb={nbTasks} title={"Created tasks"} />
      <Counter
        nb={nbTasksCompleted()}
        title={"Completed tasks"}
        style={{ alignItems: "flex-end" }}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flexDirection: "row",
    justifyContent: "space-between",
    marginBottom: 20,
  },
});

export default CountersContainer;

branch_name: refs/heads/master

repo_language: JavaScript


text:
<file_sep>const columns = [
  {
    column: 1,
    getter: op => op.date
  },
  {
    column: 2,
    getter: op => op.account
  },
  {
    column: 3,
    getter: op => op.description
  },
  {
    column: 4,
    getter: op => op.category
  },
  {
    column: 5,
    getter: op => op.income
  },
  {
    column: 6,
    getter: op => op.outcome
  },
  {
    column: 7,
    getter: op => op.currency
  },
  {
    column: 8,
    getter: op => op.exchRate
  },
  {
    column: 9,
    getter: op => op.total
  },
  {
    column: 10,
    getter: op => op.addedAt
  }
];

function mapRow(row) {
  return {
    date: row[0],
    account: row[1],
    description: row[2],
    category: row[3],
    income: row[4],
    outcome: row[5],
    currency: row[6],
    exchRate: row[7]
  };
}

function mapOperationToRow(operation) {
  return [
    operation.date,
    operation.account,
    operation.description,
    operation.category,
    operation.income,
    operation.outcome,
    operation.currency,
    operation.exchRate
  ];
}

class Operations {
  constructor(sheet) {
    this.sheet = sheet;
    this.rowToInsert = 2;
  }

  updateOperationByRow(row, operation) {
    columns.forEach(column => {
      if (column.getter(operation)) {
        const range = this.sheet.getRange(row, column.column);
        range.setValue(column.getter(operation));
        range.activate();
      }
    });
  }

  updateUperationsBatch(rows) {
    rows.forEach(r => {
      this.sheet
        .getRange(r.rowNum, 1, 1, 8)
        .setValues([mapOperationToRow(r.operation)])
        .activate();
    });
  }

  putOperations(operations) {
    const skipped = 0;
    const added = operations.length;

    this.sheet.insertRowsBefore(this.rowToInsert, operations.length);
    this.sheet
      .getRange(this.rowToInsert, 1, operations.length, 8)
      .setValues(
        operations.map(operation => [
          operation.date,
          operation.account,
          operation.description,
          operation.category,
          operation.income,
          operation.outcome,
          operation.currency,
          operation.exchRate
        ])
      );

    return {
      skipped,
      added
    };
  }

  getOperationByRow(rowIndex) {
    const row = this.sheet.getRange(rowIndex, 1, 1, 10).getValues()[0];
    return mapRow(row);
  }

  getOperaions() {
    return this.sheet
      .getDataRange()
      .getValues()
      .map(row => mapRow(row));
  }
}

export default Operations;
<file_sep>class CallbacksService {
  constructor() {
    this.callbacks = {};
  }

  register(id, fn) {
    this.callbacks[id] = fn;
    return id;
  }

  handle(id, args) {
    if (!this.callbacks[id]) {
      throw Error(`Callback ${id} not found in ${JSON.stringify(this.callbacks)}`);
    }
    return this.callbacks[id](args);
  }
}

export default CallbacksService;
<file_sep>class Pattern {
  constructor(data) {
    this.pattern = data.pattern;
    this.operationType = data.operationType;
    this.category = data.category;
  }

  matches(operation) {
    if (
      this.operationType !== 'Любой' &&
      ((this.operationType === 'Доход' && operation.income === 0) ||
        (this.operationType === 'Расход' && operation.outcome === 0))
    ) {
      return false;
    }

    return operation.description.indexOf(this.pattern) !== -1;
  }
}

class CategoryPatterns {
  constructor(sheet) {
    this.sheet = sheet;
    this.patterns = sheet
      .getDataRange()
      .getValues()
      .slice(1)
      .map(
        row =>
          new Pattern({
            pattern: row[0],
            operationType: row[1],
            category: row[2]
          })
      );
  }

  findCategory(operation) {
    return this.patterns.filter(p => p.matches(operation)).map(p => p.category)[0];
  }
}

function autoAssignCategories(categoriesSheet, operations, rows) {
  const patterns = new CategoryPatterns(categoriesSheet);

  const updatedRows = rows.map(rowNum => {
    const operation = operations.getOperationByRow(rowNum);
    const category = patterns.findCategory(operation) || operation.category;
    return { rowNum, operation: { ...operation, category } };
  });

  operations.updateUperationsBatch(updatedRows);
}

export default autoAssignCategories;
<file_sep>class ImportApplication {
  constructor(callbacks, operations, accounts) {
    this.ui = SpreadsheetApp.getUi();
    this.operations = operations;
    this.accounts = accounts;
    this.uploadCallbackId = callbacks.register('handleImportUpload', this.upload.bind(this));
  }

  start() {
    const template = HtmlService.createTemplateFromFile('import.html');
    template.data = {
      uploadCallbackId: this.uploadCallbackId,
      accounts: this.accounts.getAccounts()
    };
    this.ui.showSidebar(template.evaluate());
  }

  upload(form) {
    const { account } = form;

    const lines = form.file.getDataAsString('windows-1251').split('\n');
    const operations = lines
      .slice(1) // skip header line
      .filter(line => line) // skip empty lines
      .map(line => line.split(';'))
      .map(item => ({
        date: item[3],
        account,
        description: item[5],
        category: 'Неизвестно',
        income: item[6],
        outcome: item[7],
        currency: item[2],
        exchRate: 1
      }));

    const result = this.operations.putOperations(operations);
    return { totalRows: lines.length, addedRows: result.added };
  }
}

export default ImportApplication;

repo_name: avalarin/family-finances-gapp


text:
<repo_name>gildean/fsexists<file_sep>/index.js
'use strict';
var fs = require('fs');

function exists(path, callback) {
    fs.access(path, function (err) {
        if (err) return callback(false);
        return callback(true);
    });
}

function existsSync(path) {
    try {
        fs.accessSync(path);
        return true;
    } catch (e) {
        return false;
    }
}

module.exports = { exists: exists, existsSync: existsSync };
<file_sep>/README.md
fsexists
========

Wraps `fs.access` and  `fs.accessSync` to provide `fsexists.exists` and `fsexists.existsSync`

install
-------

`npm install fsexists`

use
---

```
require('fsexists').exists('/some/path', function(exists) {
    console.log('file', (exists ? 'exists' : 'does not exist'));
});
```

license
-------
ISC

languages: Markdown JavaScript

repo_name: gildean/fsexists


text:
<repo_name>CBradshawDataStructures/Assignment3<file_sep>/main.cpp
//<NAME>
#include<iostream>
#include "GenStack.cpp"
#include<fstream>

using namespace std;

int checkDelimiters(GenStack<char> s){
    int parCounter=0;
    int curlyCounter=0;
    int squareCounter=0;
    int remainder;
    char tempVal;
    for(int i=0; i<s.getSize(); ++i){
        tempVal = s.pop();
        if(tempVal=='(' || tempVal==')'){
            ++parCounter;
        }
        if(tempVal=='{' || tempVal=='}'){
            ++curlyCounter;
        }
        if(tempVal=='[' || tempVal==']'){
            ++squareCounter;
        }
    }

    //this block decides if there is the correct number of delimters, if not the program ends

    remainder = parCounter%2;
    if (remainder==0){
        cout<<"Parenthesis correct"<<endl;
    }
    else{
        cout<<"Incorrect parenthesis! Program will now exit"<<endl;
        return 2;
    }

    remainder = curlyCounter%2;
    if (remainder==0){
        cout<<"Curly brackets correct"<<endl;
    }
    else{
        cout<<"Incorrect curly brackets! Program will now exit"<<endl;
        return 2;
    }

    remainder = squareCounter%2;
    if(remainder==0){
        cout<<"Square brackets correct"<<endl;
    }
    else{
        cout<<"Incorrect square brakets! Program will now exit"<<endl;
        return 2;
    }
    cout<<"code correct"<<endl;
    return 1;
}

int main(){
    int userChoice = 1;
    string fileName = "";

    GenStack<char> stack;

    //GenStack stack = new GenStack(128);

    while (userChoice == 1){
        cout<<"Enter 1 to read file. Enter 2 to end program"<<endl;
        cin>>userChoice;
        if(userChoice==1){
            cout<<"Enter file name to read: "<<endl;
            cin>>fileName;

            char ch;
            fstream fin(fileName, fstream::in);
            //https://stackoverflow.com/questions/12240010/how-to-read-from-a-text-file-character-by-character-in-c

            while (fin >> noskipws >> ch) {
                //cout << ch <<endl;
                if(ch=='[' || ch==']' || ch=='{' || ch=='}' || ch=='(' || ch==')'){
                    stack.push(ch);
                    //cout<<"push complete"<<endl;
                }
            }
            //cout<<"PRINTING: "<<endl;
            //stack.print();
            //cout<<"POPPING: "<<endl;
            userChoice=checkDelimiters(stack);
            //checkCode(stack);

        }
    }
}
<file_sep>/README.txt
 <NAME>
002317872
<EMAIL>
CPSC350
Assignment 3

GenStack.cpp
GenStack.h
main.cpp

Program compiles.
g++ main.cpp
./a.out

Program prompts user to enter file name, reads from file, stores delimiters is stack.  Stack is implemented using code given in class in combination
with original code to create the GenStack.cpp and GenStack.h files.  Limitations: program does not tell user where (if found) the error line is.
Program will sometimes print a double free/corruption error into console upon termination.  This does not affect the functionality of the program as it
only occurs during the programs termination.

http://www.cplusplus.com/doc/tutorial/arrays/
https://stackoverflow.com/questions/12240010/how-to-read-from-a-text-file-character-by-character-in-c
https://stackoverflow.com/questions/3687074/segmentation-fault-c-templates
https://stackoverflow.com/questions/34730270/redefinition-of-int-main-c
<file_sep>/GenStack.h
//<NAME>
#include <iostream>

using namespace std;

template<typename t>
class GenStack{
public:
    //variables
    int size;
    int top;
    t*myArray;

    //constructors & destructor
    GenStack();
    GenStack(int maxSize);
    ~GenStack();

    //methods
    int getTop();
    void push(t d);
    char pop();
    char peek();
    bool isFull();
    bool isEmpty();
    void print();
    int getSize();
};
<file_sep>/GenStack.cpp
//<NAME>
#include <iostream>
#include <array>
#include "GenStack.h"

using namespace std;

//constructor
template<typename t>
GenStack<t>::GenStack(){
    myArray = new t[128];
    size = 128;
    top = -1;

    //initializes all elements to 0

    for (int i=0; i<size; ++i){
        myArray[i]='0';
    }
}

//parameter constructor
template<typename t>
GenStack<t>::GenStack(int maxSize){
    myArray = new t[maxSize];
    size = maxSize;
    top = -1;
}

//destructor
template<typename t>
GenStack<t>::~GenStack(){
    delete[]myArray;
}

//returns top value of stack
template<typename t>
int GenStack<t>::getTop(){
    return top;
}

template<typename t>
void GenStack<t>::push(t d){
    //if stack is not full
    if (isFull()==false){
        for(int i = 0; i<size; ++i){
            if (myArray[i]=='0'){
                myArray[i]=d;
                break;
            }
        }
    }
    else{
        //creates new array with increased size
        t*newArray = new t[size+128];
        //sets new values in larger array to 0
        for (int i=size; i<size+128; ++i){
            myArray[i]=0;
        }
        //corrects size value
        size = size+128;
        //coppies over
        for (int i = 0; i < size; ++i){
            newArray[i] = myArray[i];
        }
    }
}

template<typename t>
char GenStack<t>::pop(){
    char tempValue;
    //error checking, make sure its not isEmpty
    if (isEmpty()==false){
        //finds & saves value
        for (int i=0; i<size; ++i){
            if(myArray[i]=='0'){
                //saves value
                tempValue = myArray[i-1];
                //removes from array
                myArray[i-1]=0;
                break;
            }
        }
        //returns
        //cout<<"TEMPVAL: "<<tempValue<<endl;
        return tempValue;
    }
}

template<typename t>
char GenStack<t>::peek(){
    //check if isEmpty
    if (isEmpty()==false){
        return myArray[top];
    }
    else{
        cout<<"stack is empty"<<endl;
    }
}

template<typename t>
bool GenStack<t>::isFull(){
    return (top == size-1);
}
template<typename t>
bool GenStack<t>::isEmpty(){
    if (myArray[0]=='0'){
        //cout<<"TRUE"<<endl;
        return true;
    }
    else{
        return false;
    }
}

template<typename t>
void GenStack<t>::print(){
    for (int i = 0; i<size; ++i){
        cout<<myArray[i]<<endl;
    }
}

template<typename t>
int GenStack<t>::getSize(){
    return size;
}

languages: Text C++

repo_language: Text


text:
<file_sep>var animationObjects = [];

(function($) { //as to not rely on $ being interpreted

    $.fn.animationObject = function ( opts ) { //initialise the plugin

        var

        self = this;

        config = $.extend({}, { //default configuration of plugin
            defaultAnimationTime: 1000
        }, opts );

        self.css({
            "position": "absolute"
        });

        self.init.prototype.addAnimationPath = function(animationData) {
                self.data('animationData', animationData);
                return self;
            }
        self.init.prototype.animate = function(node) {

            if(!self.data('animationData')) {
                console.warn('Warning: no animation data associated with this animation object when the animate method was called.');
                return self;
            }
            //node refers to which of the JSON objects to animate. If it is null, then animate them all. it is 0 indexed
            if(!node) {

                var
                animations = self.data('animationData'),
                numberOfAnimations = animations.length,
                beginningAnimationProperties = [];

                for(var i = 0; i < numberOfAnimations; i++) {
                    var

                    thisAnimationSet = animations[i],
                    numberOfProperties = Object.keys(thisAnimationSet).length,
                    tempAnimObject = {};
                    //need to create an alias holding the current css info of the object

                    for(var j = 0; j < numberOfProperties; j++) {
                        var

                        thisProperty = Object.keys(thisAnimationSet)[j];
                        if(thisProperty != 'duration') {
                            if(self.css(thisProperty).indexOf('px') > 0) {
                                tempAnimObject[thisProperty] = parseInt(self.css(thisProperty).substr(0, self.css(thisProperty).length - 2));
                            } else {
                                tempAnimObject[thisProperty] = parseInt(self.css(thisProperty));
                            }
                            //if i > 0, if this property exists in the previous final animation and it exists in the next final animation, set the value of this property to the value of the previous final animation
                            if(i) {
                                var
                                previousAnimationSet = animations[i - 1];
                                if(previousAnimationSet[thisProperty]) {
                                    tempAnimObject[thisProperty] = previousAnimationSet[thisProperty];
                                }
                            }
                        } else {
                            //TODO doesn't even work lol
                            if(!thisAnimationSet["duration"]) {
                                tempAnimObject.duration = config.defaultAnimationTime;
                            } else {
                                tempAnimObject.duration = thisAnimationSet["duration"];
                            }

                        }
                    }

                    beginningAnimationProperties.push(tempAnimObject);
                }
                console.log(beginningAnimationProperties);
                //calculate the next value for each property, then set that value

                for(var i = 0; i < numberOfAnimations; i++) {
                    var isAnimFinished = false,
                    startingTime = new Date().getTime();
                    console.log(startingTime);
                //    while(!isAnimFinished) {}
                }

            } else {
                console.warn("Node-specific animations is not supported yet.");
                return self;
            }
            //get how many properties to animate, add to an array, then for each value of time passed, animate the properties syncronously
            return self;
        }
        return self; //enable chaining of plugin

    };
})(jQuery);


text:
<file_sep>## 3D Maze Exploration Game
#####COMP SCI 3GC3 - COMPUTER GRAPHICS : Final Project

Group: <NAME>, <NAME>, <NAME>, <NAME>

Maze exploration game created in C++ and OpenGL. The objective of the game is to leave the maze before your flashlight runs out. As you go through the maze, there are FIVE small keys(boxes, these keys will increase the battery life on your flashlight. Most of the maze will be dark as you walk through it, with only a flashlight to light the way, which eventually runs out.

Tested on Arch Linux, ElementaryOS (Ubuntu 14.04), OS X 10.10, and Windows 10

### Compilation Instructions
OpenGL, FreeGLUT 3, g++, and the make utility are required to be installed for the makefile to properly compile.
````
make
```
Make will automatically execute the compiled binary.

To clean up the directory, run
```
make clean
```

### Implemented Bonus Features:
  * All the basic parts of a game, object loading, first person camera, surface normals and texture coordinates.
  * Texturing (on the walls, the floor, and the keys)
  * Lighting (The flashlight moves with the player and points in the direction the player faces)
  * Particle Systems(There is a particle system for rain, which spawns 2000 particles max)
  * Picking (ray picking was implemented to pick up items, RIGHT CLICK must be used to ray pick)
  * Advanced Camera Control (A quaternion based camera was created to navigate around the maze using the mouse and keyboard)

### Known Issues:
* Camera sometimes DOES NOT start at the right position
  * To fix this, all you have to do is LEFT CLICK inside the window to fix it.
  * On OSX this problem can be fixed by rotating the camera until you are viewing the right spot_direction by clicking and re-adjusting your current position


text:
<file_sep>@import "/css/bootstrap";<file_sep>GruntProjectTemplate
==================

Template project structure for quick start with grunt.

Used grunt plugins:

- grunt-autoprefixer
- grunt-contrib-less
- grunt-contrib-cssmin
- grunt-contrib-concat
- grunt-contrib-jshint
- grunt-contrib-uglify
- grunt-contrib-watch

#Usage

1. Clone this repository

2. Edit `package.json` file to match your project

3. In a commandline, navigate to your project folder

4. Run `npm install`

5. Run `grunt` or `grunt dev` (for running with watch enabled)

6. When complete, you should have the processed files in a new folder named 'dist'<file_sep>@import "master.less";

@color: #bada55;
body{
    background-color:@color;
    transform:rotate(10deg);
}

languages: Markdown Less

repo_name: mikkelrom/grunt-project-template


text:
<file_sep>public class Transportadora {
    private String nomeEmpresa;
    private String telefone;
    private String endereco;
    private String cidade;
    private String estado;

    public Transportadora(String nomeEmpresa, String telefone, String endereco, String cidade, String estado) {
        this.nomeEmpresa = nomeEmpresa;
        this.telefone = telefone;
        this.endereco = endereco;
        this.cidade = cidade;
        this.estado = estado;
    }

    public String getNomeEmpresa() {
        return nomeEmpresa;
    }

    public String getTelefone() {
        return telefone;
    }

    public void setTelefone(String telefone) {
        this.telefone = telefone;
    }

    public String getEndereco() {
        return endereco;
    }

    public void setEndereco(String endereco) {
        this.endereco = endereco;
    }

    public String getCidade() {
        return cidade;
    }

    public String getEstado() {
        return estado;
    }

}<file_sep>
public class Estoque {
    private String filial;
    private String tipoProduto;
    private String status;

    public Estoque(String filial, String tipoProduto, String status) {
        this.filial = filial;
        this.tipoProduto = tipoProduto;
        this.status = status;
    }

    public String getFilial() {
        return filial;
    }

    public String getTipoProduto() {
        return tipoProduto;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

}

repo_language: Java

repo_name: amdjr/lojadevarejo


text:
<repo_name>doomlab/Addie-Thesis<file_sep>/README.md
# Addie-Thesis
<file_sep>/analysis.R
library(ggplot2)
library(papaja) #devtools::install_github("crsh/papaja")

##set working directory to where file is saved
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))

master = read.csv("MasterDataset.csv", stringsAsFactors = F)
options(scipen = 999)

##summary
summary(master)

#Descriptives
#ravens
mean(master$Ravens.Score, na.rm = TRUE)
sd(master$Ravens.Score, na.rm = TRUE)

#Typing
mean(master$TTScore, na.rm = TRUE)
sd(master$TTScore, na.rm = TRUE)

#OSPAN
mean(master$Letter.Recall, na.rm = TRUE)
sd(master$Letter.Recall, na.rm = TRUE)

#Math Acc
mean(master$Math.Acc, na.rm = TRUE)
sd(master$Math.Acc, na.rm = TRUE)

##Dataset to get means for those ONLY above 85%
OSPAN = subset(master, Math.Acc >=85)

#Ravens
mean(OSPAN$Ravens.Score, na.rm = T)
sd(OSPAN$Ravens.Score, na.rm = T)

#OSPAN
mean(OSPAN$Letter.Recall, na.rm = TRUE)
sd(OSPAN$Letter.Recall, na.rm = TRUE)

#Math Acc
mean(OSPAN$Math.Acc, na.rm = TRUE)
sd(OSPAN$Math.Acc, na.rm = TRUE)

##cor.test

##ravens + ospan
cor.test(master$Ravens.Score, master$Letter.Recall)

ggplot(master, aes(Ravens.Score, Letter.Recall)) +
  geom_point() +
  xlab("Ravens Score") +
  ylab("OSPAN Score") +
  theme_apa()

##ravens + tt
cor.test(master$Ravens.Score, master$TTScore)

ggplot(master, aes(Ravens.Score, TTScore)) +
  geom_point() +
  xlab("Ravens Score") +
  ylab("Typing Speed") +
  theme_apa()

##ospan + tt
cor.test(master$Letter.Recall, master$TTScore)

ggplot(master, aes(Letter.Recall, TTScore)) +
  geom_point() +
  xlab("OSPAN Score") +
  ylab("Typing Speed") +
  theme_apa()

#power test
library(pwr)
pwr.r.test(n = 41, r = .22, alternative = "two.sided")
pwr.r.test(n = NULL, r = .22, alternative = "two.sided",
           power = .80)

##regression
model = lm(Ravens.Score ~ Letter.Recall + Math.Acc,  data = master)
summary(model)

library(lm.beta)
summary.lm.beta(model) #to get standardized coefficients
lm.beta(model)

library(ppcor)
pcor(na.omit(master[ , c("Letter.Recall", "Math.Acc", "Ravens.Score")]))

model2 = lm(TTScore ~ Letter.Recall + Math.Acc, data = master)
summary(model2)
summary.lm.beta(model2)
pcor(na.omit(master[ , c("Letter.Recall", "Math.Acc", "TTScore")]))

model3 = lm(TTScore ~ Letter.Recall + Ravens.Score + Math.Acc, data = master)
summary(model3)
summary.lm.beta(model3)
pcor(na.omit(master[ , c("Letter.Recall", "Math.Acc", "Ravens.Score", "TTScore")]))

# model6 = lm(TTScore ~ Letter.Recall * Ravens.Score + Math.Acc, data = master)
# summary(model6)
# summary.lm.beta(model6)

# without poor participants ------------------------------------------------------

##cor.test

##ravens + ospan
cor.test(OSPAN$Ravens.Score, OSPAN$Letter.Recall)

ggplot(OSPAN, aes(Ravens.Score, Letter.Recall)) +
  geom_point() +
  xlab("Ravens Score") +
  ylab("OSPAN Score") +
  theme_apa()

##ravens + tt
cor.test(OSPAN$Ravens.Score, OSPAN$TTScore)

ggplot(OSPAN, aes(Ravens.Score, TTScore)) +
  geom_point() +
  xlab("Ravens Score") +
  ylab("Typing Speed") +
  theme_apa()

##ospan + tt
cor.test(OSPAN$Letter.Recall, OSPAN$TTScore)

ggplot(OSPAN, aes(Letter.Recall, TTScore)) +
  geom_point() +
  xlab("OSPAN Score") +
  ylab("Typing Speed") +
  theme_apa()

<file_sep>/Qualtrics/score_ravens.R

##set working directory to where file is saved
#setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
setwd("~/Documents/GitHub/Addie-Thesis/Qualtrics/All Data from Qualtrics Before 5:15")

master <- read.csv("Ravens_May15_edited.csv", stringsAsFactors = F)

##function
scorer <- function(column, answer) {

  temp <- as.numeric(master[ , column] == answer)

  for (i in 1:length(temp)){
    if(is.na(temp[i])){
      temp[i] = 0
    }
  }

  return(temp)

  }

#add stuff up
master$total = (scorer("Q5", 5) + scorer("Q6", 1) + scorer("Q7", 7) + scorer("Q8", 4) + scorer("Q9", 3)
                + scorer("Q10",1) + scorer("Q11", 6) + scorer("Q12", 1) + scorer("Q13", 8)
                + scorer("Q14", 4) + scorer("Q15", 5) + scorer("Q16", 6) + scorer("Q17", 2)
                + scorer("Q18", 1) + scorer("Q19", 2) + scorer("Q20", 4) + scorer("Q21", 6)
                + scorer("Q22", 7) + scorer("Q23", 3) + scorer("Q24", 8) + scorer("Q25", 8)
                + scorer("Q26", 7) + scorer("Q27", 6) + scorer("Q28", 3) + scorer("Q29", 7)
                + scorer("Q30", 2) + scorer("Q31", 7) + scorer("Q32", 5) + scorer("Q33", 6)
                + scorer("Q34", 5) + scorer("Q35", 4) + scorer("Q36", 8) + scorer("Q37", 5)
                + scorer("Q38", 1) + scorer("Q39", 3) + scorer("Q40", 2))

##print out the useful part

write.csv(master[ , c("Q44", "total", "StartDate", "EndDate", "Q_TotalDuration") ], "ravens_scores.csv", row.names = F)
View(master)

languages: Markdown R

repo_name: doomlab/Addie-Thesis


text:
<file_sep># clearing the environment
rm(list=ls())

# setting the working directory
setwd("D:/R and PYTHON files/data set/project 1")

# checking the working directory
getwd()

#Load Libraries
install.packages (c("ggplot2", "corrgram", "DMwR", "caret", "randomForest", "unbalanced", "C50", "dummies", "e1071", "Information",
                    "MASS", "rpart", "gbm", "ROSE", 'sampling', 'DataCombine', 'inTrees'))

# loading the data in environment (in object bike_df)
bike_df=read.csv("day.csv",header=TRUE)

# missing value anlysis
sum(is.na(bike_df))      # there is no missing value in this dataset.

# exploring the data
str(bike_df)

# converting the variables in their respective datatype.
bike_df$season=as.factor(bike_df$season)
bike_df$yr=as.factor(bike_df$yr)
bike_df$mnth=as.factor(bike_df$mnth)
bike_df$holiday=as.factor(bike_df$holiday)
bike_df$weekday=as.factor(bike_df$weekday)
bike_df$workingday=as.factor(bike_df$workingday)
bike_df$weathersit=as.factor(bike_df$weathersit)

# seperating the numerical variables and categorical variables.
numeric_index=sapply(bike_df,is.numeric)
numeric_data=bike_df[,numeric_index]
cnames=colnames(numeric_data) #numerical variables.

factor_index=sapply(bike_df,is.factor)
factor_data=bike_df[,factor_index]
pnames=colnames(factor_data)  #categorical variables.

#outlier dedection and deletion.
library("scales")
library("psych")
library("ggplot2")
library("gplot")
for (i in 1:length(cnames))
{
  assign(paste0("gn",i), ggplot(aes_string(y = (cnames[i]), x = "cnt"), data = subset(bike_df))+
           stat_boxplot(geom = "errorbar", width = 0.5) +
           geom_boxplot(outlier.colour="red", fill = "blue" ,outlier.shape=18,
                        outlier.size=1, notch=FALSE) +
           theme(legend.position="bottom")+
           labs(y=cnames[i],x="cnt")+
           ggtitle(paste("Box plot of cnt for",cnames[i])))
}
# Plotting plots together
gridExtra::grid.arrange(gn1,gn2,gn3,ncol=3)
gridExtra::grid.arrange(gn4,gn5,ncol=2)
gridExtra::grid.arrange(gn6,gn7,gn8,ncol=2)

# removing outlier
for (i in cnames){
  print(i)
  value=bike_df[,i][bike_df[,i]%in%boxplot.stats(bike_df[,i])$out]
}
bike_df=bike_df[which(!bike_df[,i]%in%value),]

# correlation plot for numerical variables.
library(corrgram)
corrgram(bike_df[,cnames],order=F,upper.panel=panel.pie,text.panel=panel.txt,mean="correlation plot")

# chi^2 test for categorical variables.
for(i in 1:8 ){

  print(names(factor_data)[i])
  print(chisq.test(table(factor_data[,i])))
}

# deleting the features which are not wanting.
bike_del= subset(bike_df,select=-c(atemp,dteday,instant,season,yr,mnth,weekday))

# preparing the data for forecast and predict
str(bike_del)
train.index = sample(1:nrow(bike_del), 0.8 * nrow(bike_del))
train = bike_del[ train.index,]
test  = bike_del[-train.index,]

#defining the function (to find the error percentage)
mape=function(av,pv){
  mean(abs((av-pv)/av))*100 #av=actual value and pv= predicted value
}

#decision tree regression model
library(rpart)
data1=rpart(cnt~.,data=train,method="anova")
predictions_tree=predict(data1,test[,-9])
summary(data1)
mape(test[,9],predictions_tree)
#error rate=13.00%
#accuracy =87.00 %

#random forest
library(randomForest)
random_model = randomForest(cnt~ ., train, importance = TRUE, ntree = 2000)

#Extract rules fromn random forest
#transform rf /object to an inTrees' format
library(inTrees)
treeList = RF2List(random_model)

#Extract rules
rules= extractRules(treeList, train[,-14])

#Visualize some rules
rules[1:2,]
#Make rules more readable:
readrules = presentRules(rules, colnames(train))
readrules[1:2,]

#Predict test data using random forest model
RF_Predictions = predict(random_model, test[,-9])

# accuracy check
mape((test[,9]),RF_Predictions)
#error=7.5 %
#accuracy=93.5

# EDA
qqnorm(bike_df$cnt)
hist(bike_df$cnt)# visualizing few graphs.

# writing the output to hard disk
write(capture.output(predictions_tree),"DTPR.txt")

#freezing the model random forest with high accuracy.

repo_language: R


text:
<repo_name>Hanamant-Kadlimatti/hrkapp<file_sep>/modules/events/client/controllers/events-list.client.controller.js
'use strict';

var eventsApp = angular.module('events');

eventsApp.controller('EventsController', ['$scope', '$googleCalendar', '$uibModal', '$log', '$mdSidenav',
    function ($scope, $googleCalendar, $uibModal, $log, $mdSidenav) {

        //================================================================================
        // Variables
        //================================================================================

        $scope.events = [];
        $scope.calEvents = [];
        $scope.eventSources = [];
        $scope.isCalendarView = true;
        $scope.isTableView = false;
        $scope.isSidenavOpen = false;

        /* config object */
        $scope.uiConfig = {
            calendar: {
                schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source',
                editable: false,

                aspectRatio: 1.5,

                header: {
                    left: 'month,agendaWeek,agendaDay,verticalResourceView',
                    center: 'title',
                    right: 'today prev,next'
                },
                eventLimit: true,
                navLinks: true,
                views: {
                    verticalResourceView: {
                        type: 'timeline',
                        duration: { days: 1 },
                        buttonText: 'day by doctor',

                    },
                    agendaDay: {
                        resources: false
                    }
                },
                minTime: '8:00',
                maxTime: '21:00',

                resourceAreaWidth: '20%',
                resourceLabelText: 'Doctors',

                resources: [
                    { id: 'Dr. <NAME>', title: 'Dr. <NAME>', eventColor: 'green' },
                    { id: 'Dr. <NAME>', title: 'Dr. <NAME>', eventColor: 'brown' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#FF00FF' },
                    // { id: 'Dr. <NAME>', title: 'Dr. <NAME>', eventColor: 'orange' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: 'red' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: 'lime' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: 'purple' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#9ACD32' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: 'maroon' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: 'black' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#FF00FF' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#0000FF' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#00FFFF' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#FFC0CB' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#BDB76B' },
                    // { id: 'Name: Dr <NAME>', title: 'Name: Dr <NAME>', eventColor: '#00BFFF' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#9ACD32' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#FFFFE0' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#B8860B' },

                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: 'maroon' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: 'green' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#FF00FF' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: 'orange' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: 'red' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: 'lime' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: 'purple' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#9ACD32' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: 'maroon' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: 'black' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#FF00FF' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#0000FF' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#00FFFF' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#FFC0CB' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#BDB76B' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#00BFFF' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#9ACD32' },
                    // { id: 'Dr.<NAME>', title: 'Dr.<NAME>', eventColor: '#FFFFE0' },
                    // { id: '<NAME>', title: '<NAME>', eventColor: '#B8860B' },

                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: 'maroon' },
                    // { id: 'Dr Akshay', title: 'Dr Akshay', eventColor: 'green' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#FF00FF' },
                    // { id: 'Dr Sunil & Team', title: 'Dr Sunil & Team', eventColor: 'orange' },
                    // { id: 'Dr. Rajesh', title: 'Dr. Rajesh', eventColor: 'red' },
                    // { id: 'Dr Preeti', title: 'Dr Preeti', eventColor: 'lime' },
                    // { id: 'Dr Avinash', title: 'Dr Avinash', eventColor: 'purple' },
                    // { id: 'Dr. <NAME>', title: 'Dr. <NAME>', eventColor: '#9ACD32' },
                    // { id: 'Dr Khushboo', title: 'Dr Khushboo', eventColor: 'maroon' },
                    // { id: 'Dr. Vishwanath', title: 'Dr. Vishwanath', eventColor: 'black' },
                    // { id: 'Dr. <NAME>', title: 'Dr. <NAME>', eventColor: '#FF00FF' },
                    // { id: 'Dr Varsha', title: 'Dr Varsha', eventColor: '#0000FF' },
                    // { id: 'Dr nagraj p g optom', title: 'Dr nagraj p g optom', eventColor: '#00FFFF' },
                    // { id: 'Dr Pooja', title: 'Dr Pooja', eventColor: '#FFC0CB' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#BDB76B' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#00BFFF' },
                    // { id: '<NAME>', title: 'Dr Apoorva', eventColor: '#9ACD32' },
                    // { id: 'Dr.<NAME>', title: 'Dr.<NAME>', eventColor: '#FFFFE0' },
                    // { id: 'Dr.<NAME>', title: 'Dr.<NAME>', eventColor: '#B8860B' },

                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#9ACD32' },
                    // { id: 'Dr <NAME>', title: 'Dr <NAME>', eventColor: '#FFFFE0' },
                    // { id: 'Dr.<NAME>', title: 'Dr.<NAME>', eventColor: '#B8860B' },
                ],

                eventRender: function (event, element) {

                    var view = $('#calendar').fullCalendar('getView');

                    if (view.name === 'verticalResourceView') {
                        element.find('.fc-title').empty();
                        element.find('.fc-title').append(event.description.split('\n')[0]);
                    }
                    else {
                        element.find('.fc-title').empty();

                        if (event.description === 'On Vacation') {
                            element.find('.fc-title').append('On Vacation - ' + event.title);
                        } else {
                            element.find('.fc-title').append(event.title);
                        }

                    }

                    // to cancel the events
                    //          element.append( "X" );
                    // element.find(".closeon").click(function() {
                    //    $('#calendar').fullCalendar('removeEvents',event._id);
                    // });

                },
                eventClick: $scope.alertOnEventClick
            }

        };

        this.toggleview = function () {
            if ($scope.isCalendarView === true) {
                $scope.isCalendarView = false;
                $scope.isTableView = true;
            }
            else {
                $scope.isCalendarView = true;
                $scope.isTableView = false;
            }
        };

        /* alert on eventClick calendar*/
        $scope.alertOnEventClick = function (date, jsEvent, view) {
            $scope.currentEvent = date;
            $mdSidenav('right').toggle();
        };

        //================================================================================
        // Scope Functions
        //================================================================================

        $scope.getEvents = function () {
            $googleCalendar.getEvents().then(function (events, eventRender) {

                $scope.events = events;

                for (var index = 0; index < events.length; index++) {
                    var event = events[index];

                    $scope.calEvents[index] = {
                        'title': event.summary,
                        'start': event.start.dateTime,
                        'end': event.end.dateTime,
                        'description': event.description,
                        'resourceId': event.summary,
                        'stick': 'true',
                    };
                    console.log(event.summary);
                }

            });
            console.log($googleCalendar);
        };

        $scope.eventSources = [$scope.calEvents];

        $scope.setCurrentEvent = function (event) {
            $scope.currentEvent = event;
        };

        $scope.myFilter = function (event) {
            return event.description !== 'On Vacation';
        };

       // delete events
         $scope.remove=function(calendarId, eventId){
            console.log(calendarId);
                console.log(eventId);
            //var currentId = id;
            $googleCalendar.deleteEvent(calendarId, eventId).then(function () {
                refresh();
            });

            //$scope.deleteEvent= id;
		};
        // delete ends

    }]);

<file_sep>/modules/feedbacks/server/controllers/feedbacks.server.controller.js
'use strict';

/**
 * Module dependencies.
 */
var  path = require('path'),
    mongoose = require('mongoose'),
    Feedback = mongoose.model('Feedback'),
    errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));
/**
 * Create a patient
 */
exports.create = function(req, res) {
    var feedback = new Feedback(req.body);
    feedback.user = req.user

    feedback.save(function(err) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            res.json(feedback);
            console.log("Success");
        }
    });
};

/**
 * Show the current patient
 */
exports.read = function(req, res) {
    res.json(req.feedback);
};

/**
 * Update a patient
 */
exports.update = function(req, res) {
    var feedback = req.feedback;

   feedback.patName = req.body.patName;
    feedback.feedbackHyegine = req.body.feedbackHyegine;
    feedback.feedbackAmbience = req.body.feedbackAmbience;
    feedback.feedbackExperience = req.body.feedbackExperience;
    feedback.feedbackHandling = req.body.feedbackHandling;
    feedback.feedbackManners = req.body.feedbackManners;
    feedback.feedbackCommunication = req.body.feedbackCommunication;

    feedback.save(function(err) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            res.json(feedback);
        }
    });
};

/**
 * Delete an patient
 */
exports.delete = function(req, res) {
    var feedback = req.feedback;

    feedback.remove(function(err) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            res.json(feedback);
        }
    });
};

/**
 * List of Patients
 */
exports.list = function(req, res) {
    Feedback.find().sort('-created').populate('user', 'displayName').exec(function(err, feedbacks) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
           res.json(feedbacks);
        }
    });
};

/**
 * Patient middleware
 */
exports.feedbackByID = function(req, res, next, id) {

    if (!mongoose.Types.ObjectId.isValid(id)) {
        return res.status(400).send({
            message: 'Feedback is invalid'
        });
    }

    Feedback.findById(id).populate('user', 'displayName').exec(function(err, feedback) {
        if (err) {
            return next(err);
        } else if (!feedback) {
            return res.status(404).send({
                message: 'No Feedback with that identifier has been found'
            });
        }
        req.feedback = feedback;
        next();
    });
};

repo_name: Hanamant-Kadlimatti/hrkapp


text:
<file_sep>import React from 'react';
import { dissoc } from 'ramda';
import PropTypes from 'prop-types';
import { List } from '~/components/list';
import classnames from 'classnames';

export const HorizontalMenuRaw = ({
  children,
  className,
  classes,
  ...rest
}) => (
  <List
    className={classnames(className, classes.list)}
    {...dissoc('theme', rest)}
  >
    {children}
  </List>
);

HorizontalMenuRaw.propTypes = {
  children: PropTypes.any,
  as: PropTypes.string,
  className: PropTypes.string,
  classes: PropTypes.object,
  theme: PropTypes.any,
};
<file_sep>export const styles = {
  paragraph: {
    fontSize: '1rem',
  },
  primary: {
    fontSize: '1.2rem',
  },
  light: {
    opacity: '0.7',
  },
};
<file_sep>export { themeContext, ThemeProvider } from './context';
<file_sep>import chroma from 'chroma-js';

export const styles = (theme) => ({
  input: {
    background: 'transparent',
    height: theme.sizes.elementHeight,
    border: `1px solid ${chroma(theme.colors.contrast).brighten(3)}`,
    borderRadius: '27px',
    padding: '0 1rem',
    fontSize: '.9rem',
    outline: 'none',
    transition: '.2s all ease-in-out',
    '&:focus': {
      borderColor: theme.colors.contrast,
      '&::placeholder': {
        color: chroma(theme.colors.contrast).brighten(2),
      },
    },
  },
  fluid: {
    width: '100%',
  },
  invalid: {
    borderColor: chroma(theme.colors.danger).darken(1),
    color: chroma(theme.colors.danger).darken(1),
    '&:focus': {
      color: theme.colors.contrast,
    },
  },
});
<file_sep>export const styles = {
  h1: {
    fontSize: '3rem',
    '&$mega': {
      fontSize: '4rem',
    },
  },
  h2: {
    fontSize: '2.4rem',
    '&$mega': {
      fontSize: '3.2rem',
    },
  },
  h3: {
    fontSize: '1.8rem',
    '&$mega': {
      fontSize: '2.6rem',
    },
  },
  h4: {
    fontSize: '1.5rem',
    '&$mega': {
      fontSize: '2.25rem',
    },
  },
  h5: {
    fontSize: '1.25rem',
    '&$mega': {
      fontSize: '1.6rem',
    },
  },
  h6: {
    fontSize: '1rem',
    '&$mega': {
      fontSize: '1.2rem',
    },
  },
  mega: {
    fontWeight: '300',
  },
};
<file_sep>export const styles = {
  verticalMenu: {
    listStyleType: 'none',
    padding: 0,
    margin: 0,
    display: 'flex',
    flexFlow: 'column',
    alignItems: 'flex-start',
  },
};
<file_sep>export const styles = {
  text: {
    fontSize: '1rem',
  },
  light: {
    opacity: '0.7',
  },
};
<file_sep>import { themeContext, ThemeProvider } from './theme-provider';

export const providers = {
  theme: {
    themeContext,
    ThemeProvider,
  },
};
<file_sep>import React from 'react';

import { addDecorator } from '@storybook/react';
import { ThemeProvider } from '~/providers/theme-provider';
import { injectHelvetica } from '~/business/helvetica-injector';
import { App } from '~/fixtures/app';
import { defaultTheme } from '~/themes/default';

addDecorator((createStories) => (
  <ThemeProvider
    defaultTheme="default"
    onMount={() => {
      injectHelvetica();
    }}
    themes={{
      default: defaultTheme,
    }}
  >
    <App>{createStories()}</App>
  </ThemeProvider>
));
<file_sep>export const styles = {
  list: {
    fontSize: '1rem',
  },
};
<file_sep>import React from 'react';
import classnames from 'classnames';
import { dissoc } from 'ramda';
import PropTypes from 'prop-types';

export const ButtonRaw = ({
  children,
  classes,
  className,
  icon,
  arrowed,
  accent,
  ghost,
  ...rest
}) => {
  return (
    <button
      className={classnames(
        classes.button,
        className,
        {
          [classes.accent]: accent,
        },
        { [classes.ghost]: ghost },
      )}
      {...dissoc('theme', rest)}
    >
      {icon && {icon}}
      {children}
      {arrowed && →}
    </button>
  );
};

ButtonRaw.propTypes = {
  children: PropTypes.any.isRequired,
  classes: PropTypes.object,
  accent: PropTypes.bool,
  icon: PropTypes.any,
  arrowed: PropTypes.bool,
  ghost: PropTypes.bool,
  className: PropTypes.string,
};
<file_sep>import { colors } from './colors';
import { typography } from './typography';
import { globalStyles } from './global-styles';
import { sizes } from './sizes';

export const defaultTheme = {
  colors,
  typography,
  sizes,
  globalStyles,
};
<file_sep>export const styles = {
  list: {
    listStyleType: 'none',
    padding: 0,
    margin: 0,
    display: 'flex',
    flexFlow: 'row wrap',
    '& > * + *': {
      marginLeft: '1rem',
    },
  },
};
<file_sep>import React from 'react';
import { dissoc } from 'ramda';
import PropTypes from 'prop-types';
import classnames from 'classnames';

export const CodeRaw = ({ children, className, classes, ...rest }) => {
  return (

      {children}

  );
};

CodeRaw.propTypes = {
  children: PropTypes.any,
  as: PropTypes.string,
  className: PropTypes.string,
  classes: PropTypes.object,
  theme: PropTypes.any,
};
<file_sep>export { components } from './components';
export { themes } from './themes';
export { providers } from './providers';
export { assets } from './assets';
<file_sep>export { components } from './src';
export { business } from './business';
export { providers } from './providers';
export { themes } from './themes';
export { assets } from './assets';
<file_sep>import React from 'react';
import { dissoc } from 'ramda';
import PropTypes from 'prop-types';
import classnames from 'classnames';

export const ListRaw = ({
  numbered,
  children,
  className,
  classes,
  ...rest
}) => {
  const element = numbered ? 'ol' : 'ul';

  return React.createElement(
    element,
    {
      className: classnames(className, classes.list),
      ...dissoc('theme', rest),
    },
    children,
  );
};

ListRaw.propTypes = {
  children: PropTypes.any,
  as: PropTypes.string,
  className: PropTypes.string,
  classes: PropTypes.object,
  theme: PropTypes.any,
  numbered: PropTypes.bool,
};


text:
<file_sep>This is a simple typing test project using html, css and javascript.
It's show correct words which you write and also show error words.
<file_sep>const setWords = ["hello how are you hope you doing well", "i am <NAME> this is speed testing game", "check you speed, what is your speed see it"];

const addBtn = document.getElementById('btn');
const addTxt = document.getElementById('write');
const type = document.getElementById('txt');
let startTime, endTime;

const gamePlay = () => {
    const random = Math.floor(Math.random()*setWords.length);
    type.innerText = setWords[random];
    let date = new Date();
    startTime = date.getTime();
    addBtn.innerText = "Done";
}

const gameEnd = () =>{
    let date = new Date();
    endTime = date.getTime();
    const totalTime = ((endTime - startTime)/1000);

    let fast = "your time "+" " +totalTime + " seconds ";

    let totalStr = addTxt.value;
    let wordcount = wordCounter(totalStr);
    fast += compareText(type.innerText, totalStr);
    type.innerText = fast;
}
const compareText = (str1, str2) => {
    let a1 = str1.split(" ");
    let a2 = str2.split(" ");
    let count = 0;

    a1.forEach(function(item, index){
        if(item == a2[index]){
            count++
        }

    });

    let errorCount = ( a1.length - count );
    return (count + " correct word, " +" error words are " +errorCount);

}

const wordCounter = (str) => {
    let words = str.split(" ").length;
    console.log(words);
    return words;
}

addBtn.addEventListener('click', function(){
    if(this.innerText == "Start"){
        addTxt.disabled = false;
        gamePlay();
    }else if(this.innerText == "Done"){
        addTxt.disabled = true;
        addBtn.innerText = "Start";
        gameEnd();
    }
})