language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
PHP
UTF-8
2,721
2.953125
3
[]
no_license
<?php /* Database credentials. Assuming you are running MySQL server with default setting (user 'root' with no password) */ /*define('DB_SERVER', 'localhost'); define('DB_USERNAME', 'root'); define('DB_PASSWORD', ''); define('DB_NAME', 'demo');*/ define('DB_SERVER', 'localhost'); define('DB_USERNAME', 'testuser'); define('DB_PASSWORD', 'password'); /* Attempt to connect to MySQL database */ $link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD); // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } echo 'Administrate data base <br/>'; // Create database $query = "create database if not exists registration_db;"; if(mysqli_query($link, $query)) { echo "<br/> Database created successfully <br/>"; } else { echo "<br/> Error creating database: " . $link->error; } //set schema usages $query = "use registration_db;"; if(mysqli_query($link, $query)) { echo "<br/> registration_db is in use <br/>"; } else { echo "<br/> Error registration_db can not be used: " . $link->error; } //create users table $query ="CREATE TABLE users ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, username VARCHAR(50) NOT NULL UNIQUE, password VARCHAR(255) NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP );"; if(mysqli_query($link, $query)) { echo "<br/> TABLE users is created <br/>"; } else { echo "<br/> Error TABLE users can not be create: " . $link->error; } /* //set schema usages $query = "use registration_db;"; if(mysqli_query($link, $query)) { echo "<br/>registration_db is in use <br/>"; } else { echo "<br/>Error registration_db can not be used: " . $link->error; }*/ //create images table $query ="CREATE TABLE images( image_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, user_id INT, image_description VARCHAR(150), image LONGBLOB NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users(id) );"; if(mysqli_query($link, $query)) { echo "<br/>TABLE images is created <br/>"; } else { echo "<br/>Error TABLE images can not be create: " . $link->error; } //create likes table $query ="CREATE TABLE likes( image_id INT NOT NULL, user_id INT NOT NULL, FOREIGN KEY (image_id) REFERENCES images(image_id), FOREIGN KEY (user_id) REFERENCES users(id) );"; if(mysqli_query($link, $query)) { echo "<br/>TABLE likes is created <br/>"; } else { echo "<br/>Error TABLE likes can not be create: " . $link->error; } $link->close(); ?>
Markdown
UTF-8
1,767
3.109375
3
[ "MIT" ]
permissive
# How To Check Your Balance ## Goal Check your token balance. ## Steps The operation can be performed in two ways - using the site `golos.io` and using explorer `cyberway.io`. ### Way 1: Check your balance using the site golos.io #### Step 1.1 Go to the page `https://golos.io/<account name>`. Let the account name is *golos*. #### Step 1.2 Open *wallet* tab. The types of tokens available on account balance will be shown in the left menu. ![](./images/wallet_menu.png) The fields at the top of menu indicate actions that can be performed by your account. *Golos* and *CYBER* fields are types of tokens that are on your account balance. *Golos Power * and *CYBER STAKE* fields are number of staked tokens of *Golos* and *CYBER* respectively. *Awaiting* field is number and type of tokens in the state of illiquid. ### Way 2: Check your balance using explorer cyberway.io #### Step 2.1 Go to the page `https://explorer.cyberway.io/`and specify account name. Please note that different names may be assigned to accounts depending on dApps. Let it i *andreypf*. ![](./images/explorer_cyberway.png) #### Step 2.2 In window that opens, all information about this account will be displayed, including balance. ![](./images/explorer_balance.png) You can see the following information: * `CYBER` Tokens: 804.0000 * `GOLOS` Tokens: 0.188 * `GOLOS` Tokens in the state of illiquid: 0.754 Also, you can see status of the steak: `Own` field shows amount of tokens that are available for conversion to` CYBER`. This field is updated after each account action. Please note that the explorer does not show `Golos Power` balance, since this type of token is specific and applicable only to dApp Golos. Therefore, explorer it is not available.
C++
UTF-8
2,368
2.875
3
[]
no_license
# include <math.h> # include <stdio.h> # include "glutapp.h" # include "draw.h" void draw_triangle(Vec v1, Vec v2, Vec v3) { glEnable(GL_COLOR_MATERIAL); if(App->wireframe){glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);} else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glColor3f(1.0, 1.0, 1.0); if(App->smooth) { glBegin(GL_POLYGON); glNormal3f(v1.x, v1.y, v1.z); glVertex3f(v1.x, v1.y, v1.z); glNormal3f(v1.x, v1.y, v1.z); glVertex3f(v2.x, v2.y, v2.z); glNormal3f(v1.x, v1.y, v1.z); glVertex3f(v3.x, v3.y, v3.z); glEnd(); } if(!App->smooth) { Vec norm, u, v; u = v1 - v2; v = v2 - v3; norm = cross(u, v); norm.normalize(); glBegin(GL_POLYGON); glNormal3f(norm.x, norm.y, norm.z); glVertex3f(v1.x, v1.y, v1.z); glVertex3f(v2.x, v2.y, v2.z); glVertex3f(v3.x, v3.y, v3.z); glEnd(); } } void divide(Vec v1, Vec v2, Vec v3, int divs) { Vec v12, v23, v31; if(divs == 0) { draw_triangle(v1, v2, v3); return; } v12 = v1 + v2; v23 = v2 + v3; v31 = v3 + v1; v12.normalize(); v23.normalize(); v31.normalize(); divide(v1, v12, v31, divs - 1); divide(v2, v23, v12, divs - 1); divide(v3, v31, v23, divs - 1); divide(v12, v23, v31, divs - 1); } void enable_lights() { //Enable Lighting glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); //Components GLfloat ambient[] = { 0.0, 0.0, 0.0, 10.0 }; GLfloat diffuse[] = { .3, .3, .3, 1.0}; GLfloat specular[] = { 1.0, 1.0, 1.0, 1.0}; GLfloat position[] = {5.0, 5.0, 5.0, 1.0 }; //Create lighting glLightfv(GL_LIGHT0, GL_AMBIENT, ambient); glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, specular); glLightfv(GL_LIGHT0, GL_POSITION, position); } void draw_axis ( double r ) { glDisable(GL_LIGHTING); double d=r/20.0; glBegin ( GL_LINES ); glColor3f ( 1, 0, 0 ); glVertex3d ( -r, 0, 0 ); glVertex3d ( r, 0, 0 ); glVertex3d ( r-d, -d, 0 ); glVertex3d ( r, 0, 0 ); glVertex3d ( r-d, d, 0 ); glVertex3d ( r, 0, 0 ); glColor3f ( 0, 1, 0 ); glVertex3d ( 0, -r, 0 ); glVertex3d ( 0, r, 0 ); glVertex3d ( 0, r-d, -d ); glVertex3d ( 0, r, 0 ); glVertex3d ( 0, r-d, d ); glVertex3d ( 0, r, 0 ); glColor3f ( 0, 0, 1 ); glVertex3d ( 0, 0, -r ); glVertex3d ( 0, 0, r ); glVertex3d ( 0, -d, r-d ); glVertex3d ( 0, 0, r ); glVertex3d ( 0, d, r-d ); glVertex3d ( 0, 0, r ); glEnd(); }
JavaScript
UTF-8
1,945
2.75
3
[ "LicenseRef-scancode-proprietary-license", "MIT" ]
permissive
const fs = require('fs') const path = require('path') const os = require('os') const exec = require('./exec').exec const skipOnWindows = (fn) => { if (os.platform() !== 'win32') { fn() } } describe('exec', () => { it('should be able to create and delete files', async () => { const fileName = 'this-is-a-test-file.txt' const filePath = path.join(__dirname, fileName) expect(fs.existsSync(filePath)).toBe(false) await exec(`touch ${fileName}`, { cwd: __dirname }) expect(fs.existsSync(filePath)).toBe(true) await exec(`rm ${fileName}`, { cwd: __dirname }) expect(fs.existsSync(filePath)).toBe(false) }) it('should provide an output from stdout', async () => { const outputParts = [] await exec('echo hello', {}, output => outputParts.push(output.toString())) expect(outputParts[0].trim()).toEqual('hello') }) skipOnWindows(() => { it('should error when a command fails', async () => { let catchCalled = false await exec('sadflkajsdfoiewflkjsadf') .catch(() => { catchCalled = true }) expect(catchCalled).toBe(true) }) it('should provide the error code and message', async () => { let catchCalled = false await exec('which asldfkj') .catch((e) => { catchCalled = true expect(e.code).toBe(1) expect(e.message).toBe('Exit code was 1') expect(e.errorOutput).not.toBeDefined() }) expect(catchCalled).toBe(true) }) it('should provide the error code and message', async () => { let catchCalled = false await exec('echo >&2 "this is the error message"; exit 4') .catch((e) => { catchCalled = true expect(e.code).toBe(4) expect(e.message).toBe('Exit code was 4') expect(e.errorOutput).toBe('this is the error message\n') }) expect(catchCalled).toBe(true) }) }) })
C++
UTF-8
11,200
2.640625
3
[]
no_license
#include "SinglePlayer.h" #include <iostream> void SinglePlayer::draw(const sf::Time dt) { //this->game->window.clear(sf::Color::Red); this->game->window.draw(background); for (size_t i = 0; i < playerCards.size(); i++) { playerCards[i].sprite.setPosition(sf::Vector2f(0 + 40 * i, 152)); this->game->window.draw(playerCards[i].sprite); } for (size_t i = 0; i < dealerCards.size(); i++) { dealerCards[i].sprite.setPosition(sf::Vector2f(0 + 40 * i, 0)); this->game->window.draw(dealerCards[i].sprite); } if (turnNumber == 2) { this->game->window.draw(cards.backofcard); } if (turnNumber < 3) { this->game->window.draw(hit); this->game->window.draw(stay); if (cardDrawn == false) { this->game->window.draw(betDouble); this->game->window.draw(surrender); } } if (turnNumber == 4) { this->game->window.draw(losewin); this->game->window.draw(reset); this->game->window.draw(dealerScoreText); } this->game->window.draw(playerScoreText); this->game->window.draw(playerCashText); } void SinglePlayer::update(const sf::Time dt) { if (turnNumber == 1) // set up { playerDraw(); dealerDraw(); turnNumber++; } else if (turnNumber == 2) { if (playerScore == 21 && playerCards.size() == 2) { turnNumber = 4; blackjack = true; } } else if (turnNumber == 3) // 2 is player turn but simple handled in handelInput { dealerAi(); turnNumber++; } else if (turnNumber > 3) { if (dealerScore > playerScore && dealerScore < 22) { drawLose(); won = false; } else if (playerScore > dealerScore && playerScore < 22) { drawWin(); won = true; } else if (dealerScore > 21 && playerScore < 22) { drawWin(); won = true; } else if (playerScore == dealerScore) { drawTie(); tie = true; } else if (playerScore > 21) { drawLose(); won = false; } } //TODO insta win if you have ace and face updateCash(); } void SinglePlayer::handleInput() { sf::Event event; hit.setColor(sf::Color(255, 255, 255)); stay.setColor(sf::Color(255, 255, 255)); reset.setColor(sf::Color(255, 255, 255)); betDouble.setColor(sf::Color(255, 255, 255)); surrender.setColor(sf::Color(255, 255, 255)); for (size_t i = 0; i < playerCards.size(); i++) { playerCards[i].sprite.setColor(sf::Color(255, 255, 255)); } // get the current mouse position in the window sf::Vector2i pixelPos = sf::Mouse::getPosition(game->window); // convert it to world coordinates sf::Vector2f worldPos = game->window.mapPixelToCoords(pixelPos); if (hit.getGlobalBounds().contains(worldPos)) hit.setColor(sf::Color(200, 100, 0)); else if (stay.getGlobalBounds().contains(worldPos)) stay.setColor(sf::Color(200, 100, 0)); else if (reset.getGlobalBounds().contains(worldPos)) reset.setColor(sf::Color(200, 100, 0)); else if (betDouble.getGlobalBounds().contains(worldPos)) betDouble.setColor(sf::Color(200, 100, 0)); else if (surrender.getGlobalBounds().contains(worldPos)) surrender.setColor(sf::Color(200, 100, 0)); for (size_t i = 0; i < playerCards.size(); i++) // bad code for the win :) grid would be better but its good enough { if (playerCards[i].sprite.getGlobalBounds().contains(worldPos)) playerCards[i].sprite.setColor(sf::Color(200, 100, 0)); } while (this->game->window.pollEvent(event)) { //button logic if (event.type == sf::Event::MouseButtonPressed)// left click... { if (hit.getGlobalBounds().contains(worldPos)) { cardDrawn = true; playerDraw(); //turnNumber++; } else if (stay.getGlobalBounds().contains(worldPos)) { turnNumber++; //TODO do something good now? } else if (reset.getGlobalBounds().contains(worldPos)) { resetGame(); //TODO do something good now? } else if (betDouble.getGlobalBounds().contains(worldPos)) { cardDrawn = true;//shhhhhh you didnt see this betDoubleCash(); playerDraw(); turnNumber++; } else if (surrender.getGlobalBounds().contains(worldPos)) { surrendered = true; surrenderRound(); } for (size_t i = 0; i < playerCards.size(); i++) { if (playerCards[i].sprite.getGlobalBounds().contains(worldPos) && playerCards[i].values[0] == 1) { if (playerCards[i].flipped == false) { playerScore += 10; //TODO make reversable playerCards[i].flipped = true; } else { playerCards[i].flipped = false; playerScore -= 10; } updateScores(); } } } switch (event.type) { /* Close the window */ case sf::Event::Closed: { this->game->window.close(); break; } /* Resize the window */ case sf::Event::Resized: { break; } case sf::Event::KeyPressed: { if (event.key.code == sf::Keyboard::Escape) this->game->window.close(); break; } default: break; } } return; } SinglePlayer::SinglePlayer(Game* game) : cards(game->texmgr) { this->game = game; surrendered = false; won = false; tie = false; blackjack = false; cardDrawn = false; betSize = 10; playerCash = 100; dealerScore = 0; playerScore = 0; cards.backofcard.setPosition(40, 0); cards.shufflecards(); this->game->texmgr.loadTexture("playbuttons", "Textures/playbuttons.png"); this->game->texmgr.loadTexture("backgroundgame", "Textures/backgroundgame.png"); this->game->texmgr.loadTexture("losewin", "Textures/losewin.png"); losewin.setTexture(this->game->texmgr.getRef("losewin")); hit.setTexture(this->game->texmgr.getRef("playbuttons")); stay.setTexture(this->game->texmgr.getRef("playbuttons")); reset.setTexture(this->game->texmgr.getRef("playbuttons")); surrender.setTexture(this->game->texmgr.getRef("playbuttons")); betDouble.setTexture(this->game->texmgr.getRef("playbuttons")); background.setTexture(this->game->texmgr.getRef("backgroundgame")); hit.setTextureRect(sf::IntRect(0, 0, 32, 16)); //TODO could implement file load way( too much work though :/ ) stay.setTextureRect(sf::IntRect(32, 0, 32, 16)); reset.setTextureRect(sf::IntRect(64, 0, 32, 16)); betDouble.setTextureRect(sf::IntRect(0, 16, 32, 16)); surrender.setTextureRect(sf::IntRect(32, 16, 32, 16)); //position never changes hit.setPosition(32, 100); stay.setPosition(32 * 2 + 10, 100); betDouble.setPosition(32 * 3 + 10 * 2, 100); surrender.setPosition(32 * 4 + 10 * 3, 100); reset.setPosition(192 - 16, 216 - 32); cash = 50; //starting cash //cards.shufflecards(); turnNumber = 1; font.loadFromFile("Font/font.ttf"); playerCashText.setFont(font); dealerScoreText.setFont(font); playerScoreText.setFont(font); playerCashText.setCharacterSize(13); playerScoreText.setCharacterSize(13); dealerScoreText.setCharacterSize(13); playerCashText.setPosition(250, 125); dealerScoreText.setPosition(5, 74); playerScoreText.setPosition(5, 125); playerCashText.setFillColor(sf::Color::Black); playerScoreText.setFillColor(sf::Color::Black); dealerScoreText.setFillColor(sf::Color::Black); } void SinglePlayer::dealerDraw() { //dealerScore = 0; if (turnNumber == 1) //TODO fix the showing dealer points { dealerCards.push_back(cards.getCard()); dealerCards.push_back(cards.getCard()); dealerScore = dealerCards[0].values[0]; dealerScore += dealerCards[1].values[0]; } else { dealerCards.push_back(cards.getCard()); dealerScore += dealerCards.back().values[0]; } updateScores(); std::cout << "Cards Left: " << cards.cards.size() << std::endl; } void SinglePlayer::playerDraw() { if (turnNumber == 1) { //playerScore = 0; playerCards.push_back(cards.getCard()); // card 1 playerCards.push_back(cards.getCard()); // card 2 playerScore = playerCards[0].values[0]; playerScore += playerCards[1].values[0]; } else { playerCards.push_back(cards.getCard()); playerScore += playerCards.back().values[0]; } updateScores(); std::cout << "Cards Left: " << cards.cards.size() << std::endl; } void SinglePlayer::updateScores() { //update player score playerScoreText.setString("Player score: " + std::to_string(playerScore)); //update dealer score dealerScoreText.setString("Dealer score: " + std::to_string(dealerScore)); } void SinglePlayer::resetGame() { if (tie == true) { //do nothing } else if (blackjack == true) { playerCash = playerCash + betSize * 3; } else if (surrendered == true) { playerCash = playerCash - betSize / 2; } else if (won == true) { playerCash += betSize; } else { playerCash -= betSize; } cardDrawn = false; surrendered = false; won = false; tie = false; blackjack = false; betSize = 10; playerCards.clear(); dealerCards.clear(); turnNumber = 1; playerScore = 0; dealerScore = 0; } void SinglePlayer::dealerAi() { int scorechoice1 = 0; int scorechoice2 = 0; bool flippedOnce = false; //duplicated, i know flippedOnce == false; //reset scorechoice1 = 0; scorechoice2 = 0; for (size_t i = 0; i < dealerCards.size(); i++) // dont have to rescan but meh, easier { scorechoice1 += dealerCards[i].values[0]; } for (size_t i = 0; i < dealerCards.size(); i++) { if (dealerCards[i].values[0] == 1 && flippedOnce == false) { scorechoice2 += 11; flippedOnce == true; } else scorechoice2 += dealerCards[i].values[0]; } while (scorechoice1 < 22 || scorechoice2 < 22) { if (scorechoice1 < 17 || scorechoice2 < 17) { dealerDraw(); } scorechoice1 = 0; scorechoice2 = 0; flippedOnce == false; //reset for (size_t i = 0; i < dealerCards.size(); i++) // dont have to rescan but meh, easier { scorechoice1 += dealerCards[i].values[0]; } for (size_t i = 0; i < dealerCards.size(); i++) { if (dealerCards[i].values[0] == 1 && flippedOnce == false) { scorechoice2 += 11; flippedOnce == true; } else { scorechoice2 += dealerCards[i].values[0]; } } if (scorechoice1 > 16 && scorechoice1 < 22) { if (scorechoice1 > scorechoice2 && scorechoice2 < 21) { dealerScore = scorechoice1; break; } if (scorechoice2 > 21) { dealerScore = scorechoice1; break; } } if (scorechoice2 > 16 && scorechoice2 < 22) { if (scorechoice2 > scorechoice1 && scorechoice1 < 21) { dealerScore = scorechoice2; break; } if (scorechoice1 > 21) { dealerScore = scorechoice2; break; } } if (scorechoice1 > 16 && scorechoice1 == scorechoice2) { break; } } updateScores(); } void SinglePlayer::updateCash() { //update player cash playerCashText.setString("Cash: $" + std::to_string(playerCash)); } void SinglePlayer::betDoubleCash() { betSize = betSize * 2; } void SinglePlayer::surrenderRound() { resetGame(); } void SinglePlayer::outOfCards() { if (cards.cards.empty() == true) { game->popState(); } } //TODO setting rect everytime not effecient but whatevs void SinglePlayer::drawLose() { losewin.setTextureRect(sf::IntRect(0, 0, 384, 216)); this->game->window.draw(losewin); } void SinglePlayer::drawWin() { losewin.setTextureRect(sf::IntRect(0 + 384, 0, 384, 216)); this->game->window.draw(losewin); } void SinglePlayer::drawTie() { losewin.setTextureRect(sf::IntRect(0 + 384 * 2, 0, 384, 216)); this->game->window.draw(losewin); } SinglePlayer::~SinglePlayer() { }
Java
UTF-8
10,914
3.03125
3
[]
no_license
/////////////////////////////////////////////////////////////////////////////// // ALL STUDENTS COMPLETE THESE SECTIONS // Title: (PokemonGo.java) // Files: (list of source files) // Semester: (CS 367: Introduction to Data Structures) Fall 2016 // // Author: (Nhialee Yang) // Email: (nyang5@wisc.edu) // CS Login: (nhialee) // Lecturer's Name: (Alexander Brooks) // //////////////////// PAIR PROGRAMMERS COMPLETE THIS SECTION //////////////////// // // CHECK ASSIGNMENT PAGE TO see IF PAIR-PROGRAMMING IS ALLOWED // If pair programming is allowed: // 1. Read PAIR-PROGRAMMING policy (in cs302 policy) // 2. choose a partner wisely // 3. REGISTER THE TEAM BEFORE YOU WORK TOGETHER // a. one partner creates the team // b. the other partner must join the team // 4. complete this section for each program file. // // Pair Partner: (name of your pair programming partner) // Email: (email address of your programming partner) // CS Login: (partner's login name) // Lecturer's Name: (name of your partner's lecturer) // //////////////////// STUDENTS WHO GET HELP FROM OTHER THAN THEIR PARTNER ////// // must fully acknowledge and credit those sources of help. // Instructors and TAs do not have to be credited here, // but tutors, roommates, relatives, strangers, etc do. // // Persons: Identify persons by name, relationship to you, and email. // Describe in detail the the ideas and help they provided. // // Online sources: avoid web searches to solve your problems, but if you do // search, be sure to include Web URLs and description of // of any information you find. //////////////////////////// 80 columns wide ////////////////////////////////// import java.util.Arrays; import java.util.ArrayList; import java.util.Iterator; import java.util.InputMismatchException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; /** * A menu is displayed to the console prompting the user to enter in a name. * If the user is an existing player, his or her progress will be retrieved. * Various prompts will allow the user to interact with Pokemon he or she * encounters, which he or she can capture and/or transfer to the professor for * candy. At the end of the game, if the user selects q, his or her progress * will be written to file, using the name that was entered in at the beginning * of the game. * * <p>Bugs: no known bugs. * * @author (Nhialee Yang) */ /** * The main class. Provides the main method which is responsible for game play. * Also provides assistance for gameplay with functions to generate Pokemon, and * save a player's progress. */ public class PokemonGO { public static final int NEW_POKEMON_CANDIES = 3; public static final int TRANSFER_POKEMON_CANDIES = 1; /** * The game begins here! The set of Pokemon that the player will encounter * must be provided as the first and only command-line argument which will * be loaded into the {@link PokemonDB} * <p> * Players are prompted to enter their name which will be used to save their * progress. Players are then prompted with a set of menu options which can * be selected by entering a single character e.g. 's' for "search". Options * include search for Pokemon, display encountered Pokemon, display caught Pokemon, * transfer caught Pokemon, and quit. * * @param args the command line arguments. args[0] must be a file which is loaded * by {@link PokemonDB} */ public static void main(String[] args) throws FileNotFoundException { // Interpret command-line arguments and use them to load PokemonDB if(args.length != 1) { System.err.println("Invalid arguments"); System.exit(1); } PokemonDB db = new PokemonDB(args[0]); // Start System.out.println(Config.WELCOME); // Prompt user to enter player name System.out.println(Config.USER_PROMPT); // Take name of Pokemon trainer String playerName = Config.getNextLine(); // Provide a name for a txt file which will be used to save the player's progress String playerFileName = playerName + ".txt"; Pokedex pokedex = new Pokedex(); try { pokedex.loadFromFile(playerFileName); } catch (FileNotFoundException e) { // then the player has not saved any progress yet, start a new game! } PokemonTrainer pokemonTrainer = new PokemonTrainer(playerName, pokedex); System.out.println("Hi " + playerName); // main menu for the game. accept commands until the player enters 'q' to quit String option = null; while ((!"Q".equals(option)) && (!"q".equals(option))) { // Ask user to choose // [C] display caught Pokemon // [D]isplay encountered Pokemon // [S]earch for Pokemon // [T]ransfer Pokemon to the Professor // [Q]uit System.out.println(Config.MENU_PROMPT); option = Config.getNextLine(); switch(option) { case "C": case "c": System.out.println(pokemonTrainer.getPokedex().caughtPokemonMenu()); break; case "D": case "d": System.out.println(pokemonTrainer.getPokedex().seenPokemonMenu()); break; case "S": case "s": Pokemon wildPokemon = encounterPokemon(db); // Provide alternative guessing options int[] pokedexNumbers = new int[Config.DIFFICULTY]; pokedexNumbers[0] = wildPokemon.getPokedexNumber(); for(int i = 1; i < pokedexNumbers.length; i++) { pokedexNumbers[i] = db.generatePokedexNumber(); } Arrays.sort(pokedexNumbers); // Prompt user for input System.out.println(String.format( Config.ENCOUNTERED_POKEMON, wildPokemon.getSpecies(), wildPokemon.getCombatPower(), Arrays.toString(pokedexNumbers))); int guessedId = 0; while(guessedId < 1 || guessedId > 151) { // then prompt is invalid try { guessedId = Config.getNextInteger(); if(guessedId < 1 || guessedId > 151) { throw new RuntimeException(Config.INVALID_INT_INPUT); } } catch (InputMismatchException e) { System.out.println(Config.INVALID_INT_INPUT); Config.getNextLine(); } catch (RuntimeException e) { System.out.println(Config.INVALID_INT_INPUT); } } if (guessedId == wildPokemon.getPokedexNumber()) { // guessed correctly, pokemon is captured pokemonTrainer.capturePokemon(wildPokemon); System.out.println(String.format( Config.SUCCESSFUL_CAPTURE, playerName, wildPokemon.getSpecies(), wildPokemon.getCombatPower())); } else { // guessed incorrectly, pokemon escapes pokemonTrainer.seePokemon(wildPokemon); System.out.println(String.format( Config.FAILED_CAPTURE, playerName, wildPokemon.getSpecies())); } break; case "T": case "t": // Select Pokemon species to transfer System.out.println(Config.TRANSFER_PROMPT); pokedex = pokemonTrainer.getPokedex(); String speciesName = Config.getNextLine(); if(speciesName.toLowerCase().equals("cancel")) { break; } try { db.lookupPokedexNumber(speciesName); } catch (PokedexException e) { System.out.println(e.toString()); break; } // Begin transfer of selected species PokemonSpecies species = null; try { species = pokedex.findCaughtSpeciesData(speciesName); } catch (PokedexException e) { System.out.println(e.toString()); break; } String transferPokemonName = species.getSpeciesName(); // Select Pokemon of that species to transfer System.out.println(String.format( Config.TRANSFER_CP_PROMPT, transferPokemonName, species.caughtPokemonToString())); int transferPokemonCp = -1; while(transferPokemonCp == -1) { try { transferPokemonCp = Config.getNextInteger(); if(transferPokemonCp < 0) { System.out.println(Config.INVALID_CP_INPUT); transferPokemonCp = -1; } } catch (InputMismatchException e) { System.out.println(Config.INVALID_CP_INPUT); transferPokemonCp = -1; Config.getNextLine(); } catch (RuntimeException e) { System.out.println(Config.INVALID_CP_INPUT); transferPokemonCp = -1; } } if(transferPokemonCp == 0) { break; } try { // Call transfer function; should throw exceptions within transfer but are to be caught here pokemonTrainer.transferPokemon(transferPokemonName, transferPokemonCp); System.out.println(String.format( Config.SUCCESSFUL_TRANSFER, transferPokemonName, transferPokemonCp)); } catch (PokedexException pokedexException) { System.out.println (pokedexException.toString()); } break; case "Q": case "q": break; default: System.out.println(Config.INVALID_RESPONSE); } } // Save the game when the player quits File outFile = new File(playerFileName); saveGame(outFile, pokemonTrainer); System.out.println(String.format( Config.QUIT_MESSAGE, playerName)); } /** * A wild <pokemon> has appeared! ~*~ battle music plays ~*~ * * @param db the PokemonDB to generate a Pokemon from * @return a Pokemon for the encounter */ public static Pokemon encounterPokemon(PokemonDB db) { // random number to pick pokemon int pokedexNumber = db.generatePokedexNumber(); String species = db.lookupSpeciesName(pokedexNumber); // random number to decide CP int cp = Config.CP_GENERATOR.nextInt(Config.MAX_CP-1)+1; // adjustments for origin 0/1 Pokemon wildPokemon = new Pokemon(pokedexNumber, species, cp); return wildPokemon; } /** * Save the game by writing the Pokedex into a file. The game can be loaded again * by functions provided by the {@link Pokedex} class * * @param outFile the file handle to write the game progress to * @param pokemonTrainer the player whose game we are saving */ public static void saveGame(File outFile, PokemonTrainer pokemonTrainer) throws FileNotFoundException { try { //writes the game to file with the player's name as the filename File outFile1 = new File(pokemonTrainer.getName() + ".txt"); PrintWriter output = new PrintWriter(outFile1); output.println(pokemonTrainer.getPokedex().toString().trim()); output.close(); } catch(FileNotFoundException e) { } } }
Markdown
UTF-8
12,944
3.203125
3
[ "Apache-2.0" ]
permissive
# Chained Verifiable Credentials This is an experimental implementation of using Verifiable Credential (VC) for delegation. It uses the following information and dependencies: * [Chained Credentials](https://github.com/hyperledger/aries-rfcs/tree/master/concepts/0104-chained-credentials) * [Indirect Control](https://github.com/hyperledger/aries-rfcs/tree/master/concepts/0103-indirect-identity-control) * [Simple Grant Language](https://github.com/evernym/sgl) ## Motivation In many real-world scenarios, there's often a need to delegate the ability for an entity to `act on the behalf` of another. This usually implies granting a subset of permissions to the delegatee. Many of today's systems use some form of role-based authentication/authorization to accomplish this, often via a some form of a centrally managed database. The purpose of this work is to answer the question: Can VCs be used for delegation? ## Approach ### Simple Grant Language Building off some of the original ideas and work from Daniel Hardman (see links above) we chose to explore embedding the Simple Grant Language (SGL) into a VC as part of the delegation mechanism. SGL is a JSON based language. It allows you to assert what `permission(s)` are granted IF the given conditions are satified. For example: ```json { "grant": ["rent", "drive"], "when": {"roles": "dealer"}, } ``` This rule says: `grant` the requestor `rent` and `drive` permissions, `when` the requestor has the role of `dealer`. The language is expressive enough to be able to create more sophisticated rules: ```json { "grant": ["rent", "drive"], "when": { "any": [ {"roles": "regional_manager", "n": 2}, {"roles": "board_member"}, ]} } ``` Here `rent` and `drive` are granted IF the requestors are either 2 `regional_manager` OR 1 `board_member`. The keyword `any` in the syntax is an OR clause Another example: ```json { "grant": ["rent", "drive"], "when": { "all": [ {"roles": "regional_manager", "n": 2}, {"roles": "board_member"}, ]} } ``` In this example, we change the `any` to an `all. Now the requestors must fullfil `all` the roles. The keyword `all` = AND Once the rules are defined, you can pass the rules and a list of `prinicpals` to the SGL engine to determine if the rules are satified. A prinicipal is simply a JSON object containing the `id` of the user and the `roles` they have: ```json {"id": "bob", "roles": ["dealer", "manager"]} ``` How the principals are determined is based on the application. SGL by itself is just a generic rules engine. An example (pseudo code) ```python # Single principal (bob) principals = [{"id": "bob", "roles": ["dealer", "manager"]}] rule = { "grant": ["rent", "drive"], "when": {"roles": "dealer"}, } # Returns true sgl.satisfies(principals, rule) ``` For more information on the SGL language see: https://github.com/evernym/sgl For more examples of using it see [SGL tests](tests/test_sql.py) ### Adding SGL rules to a Verifiable Credential (VC) The flexibility of the VC format allows us to include SGL rules for processing a VC by a verifier. This begins to form the basis for simple delegation. You can think of this as a capability transfer: In the example below, Bob issues the role of dealer to carol. Giving carol the right to perform the granted permissions against some resource. Here's an abbreviated credential with SGL rules: ```javascript { "id": "bob", "type": ["VerifiableCredential"], "credentialSubject.proxied.permissions": { "grant": ["rent", "sell"], "when": {"roles": "dealer"} } "credentialSubject.holder.role": "dealer", "credentialSubject.holder.id": "carol", "proof":{ "type": "Ed25519Signature2018", "jws": "eyJhbGciOiJSUzI1NiIsImI2NCI6ZmFsc2UsImNyaXQiOlsiYjY0Il19..." } } ``` Note the permissions grant and the `holder.role` specify the same thing. This seems redundant, why not just specify the permissions? The role can provide more context, especially if matched against an organizations trust framework. In addition, keeping to this structure allows us to use the additional features of the SGL language for `aggregate` checks: * Carol can act as dealer if granted by at least 2 `regional managers` * Carol can act as dealer if granted by 2 regional managers OR 1 corporate board member This gives us the ability to use VCs as authentication/authorization tools. And the VC also provides the information needed to generate the validated `principals` needed to check the rules. Using the example above we know that `bob` is the issuer and we can check that he signed the VC via the `proof`. And, we know that `carol` is the subject of the credential and she has been granted the role `dealer`. This results in 2 principals: ```json [ {"id": "bob", "roles": [...]}, {"id": "carol", "roles": ["dealer"]}, ] ``` This provides the principal set needed to pass to the SGL engine to evaluate it against the rule embedded in the VC. ### Provenance The example above shows `bob` issuing a credential to `carol` with the given rules. But how do we know `bob` is authorized to do that? Somehow we need to show the chain of claims that granted the capability to Carol`. One way to do that is to embed parent credentials the can prove the ability to delegate. Again, the flexibility of the VC format allows us to extend the format to support provenance. For example: ```javascript { "id": "bob", "type": ["VerifiableCredential"], "provenanceProofs": [ [BOBS CREDENTIAL] ], "credentialSubject.proxied.permissions": { "grant": ["rent", "sell"], "when": {"roles": "dealer"} } "credentialSubject.holder.role": "dealer", "credentialSubject.holder.id": "carol", "proof":{ "type": "Ed25519Signature2018", "jws": "eyJhbGciOiJSUzI1NiIsImI2NCI6ZmFsc2UsImNyaXQiOlsiYjY0Il19..." } } ``` Here we extended the credential to include the field `provenanceProofs` which may contain 1 or more credentials that prove the capability. In this example, it would include `bob`'s credential showing he has the ability to `delegate` permissions/role. By embedding the provenance credential, we can form a "self-certifying" chain of credentials. This forms a nested structured of `linked` credentials. Where the `leaf` credential (`carol`'s) in this case, contains `bob`s, which may contain the credential of whoever delegated to `bob`, and on and on... For example, say Carol's credential is a result of the following delegation chain: ``` Acme - delegated -> Frank - delegated -> Bob - delegated -> Carol. ``` Carol's credential would contain the entire chain. The root of the chain (`acme`) would not have any provenanced credentials: ```text Carol.provenance[ Bob.provenance[ Frank.provenance[ Acme.provenance[] ] ] ] ``` For simplicity, we base64 encode each embedded credential. To extract the chain, we start at Carol's and decode each parent credential forming a chain of credentials. The chain is linked by the following rule: The `subject id` of an embedded provenance credential should equal the `issuer id` of the current credential. For example, in our case, `bob` (issuer ID) is issuing a credential to `carol` (subject ID). The provenance credential in carol's credential must be a credential showing `bob` as the `credentialSubject.holder.id` This forms the chain via the links formed by `issuer -> subject`: ```text carol -> bob -> frank -> Acme ``` Note that Acme has no provenanced credential. The denotes it as the root. For this work we assume the `root` is someone/thing that's trusted in the context of this application. In a delegation scenario an empty provenanceProof signifies the `root of trust`. To confirm that in code, a `root of trust` is issued via a self-certified credential: The issuer and subject are the same `id` (issuer == acme, subject == acme). Now with all of this, Carol can present her credential to a verifier using a Verifiable Presentiaton and the logic of the verifier would need to check each credential in the chain. ### Verifier Logic Given a single verifiable credential, we evaluate it and check the provenance chain. Feature: It'll all self-contained! First, extract the chain into a graph of credentials, walking up, from the leaf credential all the way to the root of trust: ```text Carol.provenance[ Bob.provenance[ Frank.provenance[ Acme.provenance[] ] ] ] ``` Then, starting from the root (acme), walk forward and apply the following logic to each credential: For each credential in the chain: 1. Check the cryptographic signature: Did the issuer sign it? 2. Check the credential has not been revoked. 3. If this is the root credential make sure it's self-issued: `issuer == subject` 4. Checked the parent (issuer) and child (subject) are linked. Forming a Directed Acyclic Graph (DAG) 5. Check the credential rules (grants) are a subset of the parents grants. No grant amplification 6. Check the rules against the current principal See [tests](tests/test_chain.py) This works well for simple `linear` chains, but is limited when the rules related to granting permissions get complicated. When a verifier requests proof of 'claim' from a requestor, the requestor will assemble all credentials they feel are relevant to form the proof and submit them via a [Verifiable Presentation](https://www.w3.org/TR/vc-data-model/#presentations) (VP). Using a VP we can allow the verifier to use more complex rules. For example, if carol requests accesses, the verifier could respond with the following rule: ```json { "grant": ["rent", "drive"], "when": { "all": [ {"roles": "manager"}, {"roles": "dealer"}, ]} } ``` This says, I'll grant you `rent` and `drive` if you can show proof that: you're a `dealer` and 1 `manager` has confirmed it as well: The graph might look something like this: ```text acme ____ | ____ | | manager manager | | | | dealer | | | |___ | ___| | [o o] 2 credentials presentation ``` The VP would contain 2 credentials. Carol's showing she a dealer, and another from a manager, proving they are a manager. Both would sign the VP, and the provenance chain of each would need to be evaluated. But, what if you have rules that may require aggregate claims further up the chain? For example (see below), what if the role of `manager` requires the approval of 2 `regional manager`s? The problem is determining *who* the issuer is for the claim granting a manager. This could work if the `id` field of a VC could contain more than 1 issuer, but the current specification doesn't support that. ```text acme ______|______ | | regional regional <--- who's the issuer? manager manager | | ------------- | manager | dealer ``` ## Key points: * VCs can be used for simple delegation. But additional VC fields will need to be designed and ideally become part of the specification * There is no standard way to determine *who* the issuer is when using aggregate rules for delegation at higher levels in a delegation graph. The current VC specification only allows a single field. One potential solution would be to use a multi-signature approach where 1 or more parties share a common identifier. * The SGL language is powerful but can be confusing sometimes in the context of VCs. For example, simple rules have redundant fields: `granted role` and `subject role` are the same. But more complex may not, making it hard to understand the proper way to assemble rules. Overall it feels like SGL is often overkill for simple rules. * It's difficult to build a good set of rules and conditions that may be applied deterministically at the machine level. Role based rules are the norm in the Enterprise, and are constructed by humans. In complex systems, this may introduce subtle gaps that can lead to "leaking" permissions (grant amplification). More research is needed to explore machine approaches to building complex rules. For example, using something like directed graphs to validate the flow of rules/grants * Complex delegation models can result in large (digital size) credentials as each parent credential is embedded in the child * Validating a chain of credentials may require at least 2 network connections PER credential: * 1 to get the public key to check a signature * another to check the revocation status of the current credential ## Revocation This [code](./revoke/__init__.py) also includes an experimental Python implementation of the RevocationList 2020 specification. You can read more about it here: https://w3c-ccg.github.io/vc-status-rl-2020/
C#
UTF-8
776
3
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Text; namespace Hotel { public class Room { public Hotel hotel; public int roomNumber; public bool tv; public string roomType; public int numberOfBeds; public bool balcony; public int roomID; public string roomName; public int roomSize; public int hotelID; public decimal price; public Room(int RoomID, string RoomName, int RoomSize, int HotelID, decimal Price) { roomID = RoomID; roomName = RoomName; roomSize = RoomSize; hotelID = HotelID; price = Price; Console.WriteLine("Room is Created"); } } }
Go
UTF-8
918
2.671875
3
[ "MIT" ]
permissive
package resolvers import ( "context" "fmt" "github.com/GibJob-ai/GObjob/handler" "github.com/GibJob-ai/GObjob/model" ) // GetUser resolver func (r *Resolvers) GetUser(ctx context.Context) (*UserResponse, error) { userID := ctx.Value(handler.ContextKey("userID")) if userID == nil { return nil, &getUserError{Code: "NotAuth", Message: "Not Authorized"} } user := model.User{} if err := r.DB.First(&user, userID).Error; err != nil { return nil, &getUserError{Code: "NotFound", Message: "User not found"} } return &UserResponse{u: &user}, nil } // user exists error type getUserError struct { Code string `json:"code"` Message string `json:"message"` } func (e getUserError) Error() string { return fmt.Sprintf("error [%s]: %s", e.Code, e.Message) } func (e getUserError) Extensions() map[string]interface{} { return map[string]interface{}{ "code": e.Code, "message": e.Message, } }
Markdown
UTF-8
1,082
2.828125
3
[ "Apache-2.0" ]
permissive
# AI-Utility-Based-Markov-Decision-Process By using of utility approach for path finding in AI, the script prints the optimal states to follow with arrows UP, DOWN, RIGHT or LEFT. WALL is wall (you can type any word less than 10 length instead of |), . is empty space, +1 positive reward and -1 negative reward Map Matrix [ [".", ".", ".", ".", "+1"], [".", ".", ".", ".", "-1"], [".", "|", ".", ".", "."], [".", ".", ".", ".", "."] ] getUtilityCalculatedMap() Output is like for given map matrix printArrowMap() RIGHT RIGHT RIGHT RIGHT +1 RIGHT RIGHT UP UP -1 UP | UP UP DOWN UP RIGHT UP UP DOWN printUtilityMap() 0.3210 0.4388 0.5860 0.7700 1.0000 0.3251 0.4038 0.4874 0.4860 -1.0000 0.2301 0.0000 0.3955 0.3558 -0.0300 0.1760 0.2193 0.3116 0.2516 -0.0300 ## Map Trip Map trip is just a console simulation of moving agent without learning to see the time of travel depending on full randomness
JavaScript
UTF-8
224
2.671875
3
[]
no_license
const name = "Ernest Nnamdi" const hng_id = "HNG-03858" const email = "ernestnamdi66@gmail.com" const language = "javascript" console.log("Hello world, this is " + name + " with HNGi7 ID " + hng_id + " using " + language + " for stage 2 task");
C#
UTF-8
6,287
2.71875
3
[ "MIT" ]
permissive
using System; using WpdMtpLib.DeviceProperty; namespace WpdMtpLib { public class DevicePropDesc { public MtpDevicePropCode DevicePropCode { get; private set; } public DataType DataType { get; private set; } public byte GetSet { get; private set; } public dynamic FactoryDefaultValue { get; private set; } public dynamic CurrentValue { get; private set; } public byte FormFlag { get; private set; } public dynamic Form { get; private set; } public DevicePropDesc(byte[] data) { int pos = 0; DevicePropCode = (MtpDevicePropCode)BitConverter.ToUInt16(data, pos); pos += 2; DataType = (DataType)BitConverter.ToUInt16(data, pos); pos += 2; GetSet = data[pos]; pos++; FactoryDefaultValue = getValue(data, ref pos, DataType); CurrentValue = getValue(data, ref pos, DataType); FormFlag = data[pos]; pos++; if (FormFlag == 0x02) { // 配列 Form = getForm(data, ref pos, DataType); } else if (FormFlag == 0x01) { // 範囲 Form = getRangeForm(data, ref pos, DataType, 3); } } private static dynamic getRangeForm(byte[] data, ref int pos, DataType type, ushort arraySize) { dynamic value = null; switch (type) { case DataType.INT8: value = new sbyte[arraySize]; for (int i = 0; i < arraySize; i++) { value[i] = (sbyte)data[pos]; pos++; } break; case DataType.UINT8: value = new byte[arraySize]; for (int i = 0; i < arraySize; i++) { value[i] = (byte)data[pos]; pos++; } break; case DataType.INT16: value = new short[arraySize]; for (int i = 0; i < arraySize; i++) { value[i] = BitConverter.ToInt16(data, pos); pos += 2; } break; case DataType.UINT16: value = new ushort[arraySize]; for (int i = 0; i < arraySize; i++) { value[i] = BitConverter.ToUInt16(data, pos); pos += 2; } break; case DataType.INT32: value = new int[arraySize]; for (int i = 0; i < arraySize; i++) { value[i] = BitConverter.ToInt32(data, pos); pos += 4; } break; case DataType.UINT32: value = new uint[arraySize]; for (int i = 0; i < arraySize; i++) { value[i] = BitConverter.ToUInt32(data, pos); pos += 4; } break; case DataType.INT64: value = new long[arraySize]; for (int i = 0; i < arraySize; i++) { value[i] = BitConverter.ToInt64(data, pos); pos += 8; } break; case DataType.UINT64: value = new ulong[arraySize]; for (int i = 0; i < arraySize; i++) { value[i] = BitConverter.ToUInt64(data, pos); pos += 8; } break; case DataType.STR: value = new string[3]; for (int i = 0; i < arraySize; i++) { value[i] = Utils.GetString(data, ref pos); } break; default: break; } return value; } /// <summary> /// 型に応じた配列を取得します /// </summary> /// <param name="data"></param> /// <param name="pos"></param> /// <param name="type"></param> /// <returns></returns> private static dynamic getForm(byte[] data, ref int pos, DataType type) { ushort arraySize = BitConverter.ToUInt16(data, pos); pos += 2; return getRangeForm(data, ref pos, type, arraySize); } /// <summary> /// 型に応じて値を取得する /// </summary> /// <param name="data"></param> /// <param name="pos"></param> /// <param name="type"></param> /// <returns></returns> private static dynamic getValue(byte[] data, ref int pos, DataType type) { dynamic value = null; switch (type) { case DataType.INT8: value = (char)data[pos]; pos++; break; case DataType.UINT8: value = data[pos]; pos++; break; case DataType.INT16: value = BitConverter.ToInt16(data, pos); pos += 2; break; case DataType.UINT16: value = BitConverter.ToUInt16(data, pos); pos += 2; break; case DataType.INT32: value = BitConverter.ToInt32(data, pos); pos += 4; break; case DataType.UINT32: value = BitConverter.ToUInt32(data, pos); pos += 4; break; case DataType.INT64: value = BitConverter.ToInt64(data, pos); pos += 8; break; case DataType.UINT64: value = BitConverter.ToUInt64(data, pos); pos += 8; break; case DataType.STR: value = Utils.GetString(data, ref pos); break; default: break; } return value; } } }
Java
UTF-8
1,795
2.09375
2
[ "MIT" ]
permissive
package com.sensorberg.sdk.receivers; import com.sensorberg.sdk.Logger; import com.sensorberg.sdk.SensorbergService; import android.content.Context; import android.content.Intent; import android.os.Bundle; import static com.sensorberg.SensorbergSdk.blocked; public class GenericBroadcastReceiver extends SensorbergBroadcastReceiver{ public static void setManifestReceiverEnabled(boolean enabled, Context context) { SensorbergBroadcastReceiver.setManifestReceiverEnabled(enabled, context, GenericBroadcastReceiver.class); } @Override public void onReceive(Context context, Intent intent) { if (blocked()) return; Intent service = new Intent(context, SensorbergService.class); service.putExtras(intent.getExtras()); try { context.startService(service); } catch (RuntimeException e) { // so apparently devices that fail to launch your service. // even if everything is configured correctly // https://chromium.googlesource.com/android_tools/+/master/sdk/sources/android-23/android/app/ContextImpl.java?autodive=0%2F%2F#1256 // https://sensorberg.atlassian.net/browse/AND-248 Logger.log.logError("System bug throwing error.", e); } } @SuppressWarnings("ConstantConditions") private String toString(Intent intent) { StringBuilder builder = new StringBuilder("action:" + intent.getAction()); Bundle extras = intent.getExtras(); for (String key : extras.keySet()) { Object value = extras.get(key); builder.append("\nextra key:\"").append(key).append("\" value:\"").append(value).append("\" of type: ").append(value.getClass().getName()); } return builder.toString(); } }
JavaScript
UTF-8
263
3.15625
3
[ "MIT" ]
permissive
function Calc () {} /** * Agora adicionamos a nossa Calculadora uma * função de Soma. * * Ela irá receber dois parâmetros (a, b) e * então retornar a soma dos mesmos. */ Calc.prototype.soma = function(a, b) { return a + b; }; module.exports = Calc;
Python
UTF-8
1,726
4
4
[]
no_license
""" We must split nums into k groups. Every group has at least one element, and it is made by adjacent elements. If we have to create at most k groups. let best_avg[index][k] a matrix containing the best average of k groups of nums[i: ]. The answer of the problem is best_avg[0][k]. Base case: k = 1, the answer is the avg of the numbers in nums[i:] Otherwise, we have to try all the possibilities: from the current index, try to create a group of 1 element and recurse, then a group of 2 elements and recurse, keep doing so until the index is <= len(nums) - k. Choose the one that maximizes the result. We are not forced to split in k parts, we can use even less than k splits Since the recursive formula uses only the previous k, we can build the dynamic programming matrix bottom up, using only O(N) space. Another optimization is creating an array sums, where sums[i] is the sum of nums[:i included]. This allows us to compute all the avg in constant time O(N^2 * k) time, O(N) space """ class Solution: def largestSumOfAverages(self, nums: List[int], k: int) -> float: sums = [0] for n in nums: sums.append(sums[-1] + n) # at the beginning, no splits. The best we can get is the avg of nums[i:] best_avg = [(sums[-1] - sums[i]) / (len(nums) - i) for i in range(len(nums))] # we split in group groups, from 2 to k inclusive for groups in range(2, k + 1): for i in range(len(nums)): for j in range(i + 1, len(nums)): # i is the start of the group, j is the end (exclusive) best_avg[i] = max(best_avg[i], best_avg[j] + (sums[j] - sums[i]) / (j - i)) return best_avg[0]
C#
UTF-8
589
2.984375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary1 { public class VeblenGood : Product { public VeblenGood() { } public VeblenGood(string id, string name, double costPrice):base(id, name, costPrice) { Id = id; Name = name; CostPrice = costPrice; } public override double RetailPrice { get { return 5 * CostPrice; } } } }
Java
UTF-8
506
1.703125
2
[]
no_license
package oicq.wlogin_sdk.tlv_type; public class tlv_tc extends tlv_t { public tlv_tc() { this._cmd = 12; } public void get_tlv_tc(byte[] paramArrayOfByte, int paramInt) { set_buf(paramArrayOfByte, paramInt); } public Boolean verify() { if (this._body_len < 14) return Boolean.valueOf(false); return Boolean.valueOf(true); } } /* Location: D:\rm_src\classes_dex2jar\ * Qualified Name: oicq.wlogin_sdk.tlv_type.tlv_tc * JD-Core Version: 0.6.0 */
C++
UTF-8
1,400
2.71875
3
[]
no_license
#ifndef TIMERFD_H #define TIMERFD_H #include <unistd.h> #include <sys/timerfd.h> #include <functional> #include <core/coresynchronize.h> class TimerFD : public iot::core::Synchronizer::Callback { public: typedef std::function<void(void) > VoidCallback; TimerFD() { _timerfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK); } ~TimerFD() { ::close(_timerfd); } int fd() { return _timerfd; } void setTime(int timeout_ms, bool periodic = false) { struct itimerspec newVal; newVal.it_interval.tv_sec = 0; if (periodic) { newVal.it_interval.tv_nsec = 1e6 * timeout_ms; } else { newVal.it_interval.tv_nsec = 0; } newVal.it_value.tv_sec = 0; newVal.it_value.tv_nsec = 1e6 * timeout_ms; timerfd_settime(_timerfd, 0, &newVal, NULL); } void setCallback(VoidCallback cb) { _cb = cb; } public: void read() { uint64_t v; ssize_t r; while ((r = ::read(_timerfd, &v, sizeof (v))) > 0); if (_cb) _cb(); } bool wantRead() const { return true; } void write() { } bool wantWrite() const { return false; } void timeout() { } protected: int _timerfd; VoidCallback _cb; }; #endif /* TIMERFD_H */
Ruby
UTF-8
985
3.546875
4
[]
no_license
suma1=0 #suma de los divisores del numero a suma2=0 #suma de los divisores del numero b i=1 d1=1 #divisores de a d2=1 #divisores de b for i in 1...1000000 while d1 <= i/2 #se divide entre dos porque los divisores de un numero "a" no son mayores que de que la mitad de este numero (a) (sin contarse a si mismo) ej:los divisores de 8 son 1,2,4 if i%d1==0 suma1=suma1+d1 end d1=d1+1 end while d2 <= suma1/2 #se divide entre dos porque los divisores de un numero "a" no son mayores que de que la mitad de este numero (a) (sin contarse a si mismo) ej:los divisores de 8 son 1,2,4 if suma1%d2==0 suma2=suma2+d2 end d2=d2+1 end if i== suma2 && i== suma1 puts "#{i} y #{suma1} son numeros perfectos" elsif i== suma2 && i != suma1 puts "#{i} y #{suma1} son numeros amigos" end suma1=0 #se debe reiniciar suma2=0 #se debe reiniciar d1=1 #se debe reiniciar d2=1 #se debe reiniciar end
Java
UTF-8
331
1.945313
2
[ "Apache-2.0" ]
permissive
package com.softpian.redditvm.network; import com.softpian.redditvm.model.RedditNewsResponse; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; public interface RedditApi { @GET("top.json") Call<RedditNewsResponse> getTopPosts(@Query("after") String after, @Query("limit") String limit); }
Markdown
UTF-8
5,246
2.890625
3
[ "MIT" ]
permissive
# Milestones Package A common practice in MDW workflows is to modularize by designing processes to invoke subprocesses (see the [Invoke Subprocess](https://centurylinkcloud.github.io/mdw/docs/help/InvokeSubProcessActivity.html) and [Invoke Multiple Subprocesses](https://centurylinkcloud.github.io/mdw/docs/help/InvokeMultipleSubprocesses.html) activities. These subprocesses can go on to invoke sub-subprocesses and so on to create a hierarchy of chained subprocess calls. This represents good practice because allows reuse of common functionality contained in the subflows. In MDWHub you can drill in to a spawned subflow from the calling process instance. However, a high degree of modularization can make it difficult to envision the entire end-to-end picture. This is one of the problems addressed by milestones. A process hierarchy can be further complicated by the need to contain housekeeping steps like activities for building a REST adapter request body, and other steps that are important to the workflow designer but don't have much business meaning. Identifying certain key activities as milestones allows MDWHub to represent a higher-level visualization of the overall workflow. It also facilitates reporting against these milestones to make sure that workflows are progressing at a healthy rate. The images below depict the end-to-end flow for a [milestones autotest](https://github.com/CenturyLinkCloud/mdw/tree/master/mdw-workflow/assets/com/centurylink/mdw/tests/milestones). Even for this relatively simple process hierarchy, you can see how the overall flow on the left can be boiled down by identifying milestone activities (on the right). <p float="left"> <img width="40%" src="https://raw.githubusercontent.com/CenturyLinkCloud/mdw/master/mdw-workflow/assets/com/centurylink/mdw/tests/milestones/e2e.png" alt="e2e"> <img width="13%" style="vertical-align:top" src="https://raw.githubusercontent.com/CenturyLinkCloud/mdw/master/mdw-workflow/assets/com/centurylink/mdw/tests/milestones/milestones.png" alt="milestones"> </p> <div style="clear:both"></div> ## Dependencies - [com.centurylink.mdw.base](https://github.com/CenturyLinkCloud/mdw/blob/master/mdw-workflow/assets/com/centurylink/mdw/base/readme.md) - [com.centurylink.mdw.node](https://github.com/CenturyLinkCloud/mdw/blob/master/mdw-workflow/assets/com/centurylink/mdw/node/readme.md) - [com.centurylink.mdw.react](https://github.com/CenturyLinkCloud/mdw/blob/master/mdw-workflow/assets/com/centurylink/mdw/react/readme.md) ## Configuring Milestones To include the milestones feature in your MDW app, first [discover and import](https://centurylinkcloud.github.io/mdw/docs/guides/mdw-studio/#4-discover-and-import-asset-packages) package `com.centurylink.mdw.milestones` into your project. In [MDW Studio](https://centurylinkcloud.github.io/mdw/docs/guides/mdw-studio/) activities are marked as milestones on the Configurator Monitoring tab. A [Monitor](https://centurylinkcloud.github.io/mdw/docs/help/monitoring.html) is MDW's way of tracking lifecycle stages for activities, processes, or other workflow elements. To understand how Milestones are specified, consider this illustration from a subflow in the same milestones autotest illustrated above. <img width="80%" src="https://raw.githubusercontent.com/CenturyLinkCloud/mdw/master/mdw-workflow/assets/com/centurylink/mdw/milestones/monitor.png" alt="monitor"> On Spellbinding's Monitoring tab we've enabled the Milestone monitor, and we've also entered a value for options. Because the activity name ("Spellbinding") may not be business-descriptive, under Options we've entered something else ("Custom Label") which will be displayed in the Milestones view in MDWHub. If nothing is entered under Options, the activity name will be displayed for the milestone label. ## Label Expressions Milestone labels entered under Options may also contain [expressions](https://centurylinkcloud.github.io/mdw/docs/help/bindingExpressions.html) that reference runtime values. For example: ```$xslt Order ${order.id}\nCompleted ``` Here `order` is a process variable whose `id` property is included in the milestone label. Notice also that we've added a line break in the label, and that the newline character is escaped as `\n`. ## Milestone Groups If the milestones package is present, in MDWHub milestones can be viewed on the Workflow tab by clicking the Milestones nav link. Milestone activities are also indicated when viewing a process instance or definition in MDWHub or MDW Studio. By default milestones are highlighted with a blue background. However, in [mdw.yaml](https://centurylinkcloud.github.io/mdw/docs/guides/configuration/#mdwyaml) you can designate milestone groups like so: ```yaml milestone: groups: # list of milestone groups 'Group One': color: '#990099' 'Group Two': color: '#ff9900' description: 'Describe me' ``` This way you can color-code milestones according to business categories. On the Milestones configurator tab under Options, you specify a milestone group in square brackets after the label: ```Very Important Step[Group One]```. Groups are listed in MDWHub by clicking the Info button on the milestone view.
Python
UTF-8
231
3.09375
3
[]
no_license
def root2(n): if n<0: return 'number should be natural.' else: from math import sqrt return round(sqrt(n), 4) def root3(n): return round(-((-n) ** (1/3)), 4) if n < 0 else round(n ** (1/3), 4)
Java
UTF-8
1,357
2.40625
2
[]
no_license
package com.appspot.splitbill.client.widgets.table; import java.util.Arrays; import java.util.Comparator; import java.util.List; import com.google.gwt.user.client.ui.Widget; public abstract class EntryTableModel<E extends Entry<E,C>, C extends Column> extends AbstractTableModel<E> { private E entryInstance; private List<C> columns; public EntryTableModel(E entryInstance){ this.entryInstance = entryInstance; columns = Arrays.asList(entryInstance.getColumns()); } @Override protected Comparator<E> getAscendingSorter(int column) { return entryInstance.getComparator(columns.get(column)); } @Override public EntryEditor getAdder() { return getEditor(entryInstance.getCopy(), true); } @Override public EntryEditor getEditor(int row) { return getEditor(getEntry(row).getCopy(), false); } protected abstract EntryEditor getEditor(E entry, boolean forAdder); @Override public EntryViewer getViewer(int row) { return new DefaultEntryViewer<E, C>(getEntry(row)); } @Override public int getColumnCount() { return columns.size(); } @Override public String getColumnTitle(int col) { return columns.get(col).getColumnTitle(); } @Override public Widget getWidget(int row, int col) { return getEntry(row).getWidget(columns.get(col)); } }
JavaScript
UTF-8
1,023
2.578125
3
[]
no_license
const Engine = Matter.Engine; const World = Matter.world; const Bodies = Matter.World; const Canstraint = Matter.Canstraint; var tanker,ground,shootingball,bubble; var world,engine; function setup() { createCanvas(400,400) engine = Engine.create(); world = engine.world; ground = new Ground(400,50,20); tanker = new Tanker(400,50,20); ball1 = new Ball(400,50,20); ball2 = new Ball(500,100,20); ball3 = new Ball(600,150,20); cannonBall = new CanonBall(20,20); shot = new ShootBall(20,20); } function draw() { background("red") Engine.update(engine) ground.display(); tanker.display(); cannonBall.display(); shot.display(); ball1.display(); ball2.display(); ball3.display(); if (keyIsDown(UP_ARROW)){ shot.attach(cannonBall.body) } } function keyReleased() { if (keyCode === DOWN_ARROW){ gamestate = "launch"; shot.shoot() } }
PHP
UTF-8
2,415
2.65625
3
[]
no_license
<?php // Query filters and template includes at bottom of page /** * Create new CPT - Events */ class Gallery_CPT extends CPT_Core { /** * Register Custom Post Types. See documentation in CPT_Core, and in wp-includes/post.php */ public function __construct() { $this->post_type = 'gallery'; // Register this cpt // First parameter should be an array with Singular, Plural, and Registered name parent::__construct( array( __( 'Gallery', '_s' ), // Singular __( 'Galleries', '_s' ), // Plural $this->post_type // Registered name/slug ), array( 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'query_var' => true, 'capability_type' => 'page', 'has_archive' => 'photo-gallery', 'hierarchical' => false, 'show_ui' => true, 'show_in_menu' => true, 'show_in_nav_menus' => false, 'exclude_from_search' => false, 'rewrite' => array('slug'=> 'photo-gallery/%gallery_cat%', 'with_front' => false ), 'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail', 'page-attributes', 'revisions' ), ) ); add_filter('pre_get_posts', array( $this, 'query_filter' ) ); add_filter( 'post_type_link', array( $this, 'show_permalinks' ), 1, 2 ); } function show_permalinks( $post_link, $post ){ if ( is_object( $post ) && $post->post_type == 'gallery' ){ $terms = wp_get_object_terms( $post->ID, 'gallery_cat' ); if( $terms ){ return str_replace( '%gallery_cat%' , $terms[0]->slug , $post_link ); } } return $post_link; } function query_filter($query) { if ( $query->is_main_query() && !is_admin() && is_tax( 'gallery_cat' ) ) { // get_option( 'posts_per_page' ) $query->set('posts_per_page', 24 ); // Order By $query->set( 'orderby', 'menu_order' ); $query->set( 'order', 'ASC' ); } return $query; } } new Gallery_CPT(); $gallery_categories = array( __( 'Gallery Category', '_s' ), // Singular __( 'Gallery Categories', '_s' ), // Plural 'gallery_cat' // Registered name ); register_via_taxonomy_core( $gallery_categories, array( 'hierarchical' => true, 'rewrite' => array('hierarchical' => true, 'slug'=> 'galleries', 'with_front' => false ) ), array( 'gallery' ) );
PHP
UTF-8
810
3.375
3
[]
no_license
<html> <head> <title>Sum of digits</title> </head> <body> <form action="" method="post"> <label for="input">Input string:</label> <input type="text" name="input" id="input"/> <input type="submit" value="Submit"/> </form> </body> </html> <?php if(isset($_POST['input'])) : ?> <table border="1"> <?php $nums = explode(", ", $_POST['input']); foreach($nums as $n): if(!is_numeric($n)) : ?> <tr><td><?= $n ?></td><td>I cannot sum that</td></tr> <?php continue; endif; $sum = array_sum(str_split($n)); ?> <tr><td><?= $n ?></td><td><?= $sum ?></td></tr> <?php endforeach; ?> </table> <?php endif; ?>
Java
UTF-8
1,084
2.234375
2
[]
no_license
package com.example.myapplication.Network; import com.example.myapplication.Models.MovieTrailerModel; import com.example.myapplication.Models.MoviesModel; import com.example.myapplication.Models.ReviewModel; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; public interface apiInterface { @GET("/3/movie/{category}") Call<MoviesModel> getMoviesJson( @Path("category") String category, @Query("api_key") String api_key, @Query("language") String language, @Query("page") int page ); @GET("/3/movie/{movie_id}/videos") Call<MovieTrailerModel> getTrailerJson( @Path("movie_id") int id, @Query( "api_key" )String apikey, @Query( "language" )String language ); @GET("/3/movie/{movie_id}/reviews") Call<ReviewModel> getReviewJson( @Path("movie_id") int id, @Query( "api_key" )String apikey, @Query( "language" )String language, @Query( "page" )int page ); }
Python
UTF-8
1,933
2.609375
3
[]
no_license
#!/usr/bin/env python import sys, argparse, tempfile, subprocess, shutil, os, string, errno class Git( object ): def __init__( self, repository, path=None ): self._repository = repository self._path = path or tempfile.mkdtemp( '_nav_git' ) def __enter__( self ): p = subprocess.call([ 'git', 'clone', self._repository, self._path ]) return Repository( self._path ) def __exit__( self, type, value, traceback ): shutil.rmtree( self._path ) class Repository( object ): def __init__( self, path ): self._path = path def walk( self ): for root, dirnames, filenames in os.walk( self._path ): for filename in filenames: yield root, filename def mkdir( self, subdirectories ): subdirectories = [ self._sanitzePathname( d ) for d in subdirectories ] path = '%s/%s' % ( self._path, '/'.join( subdirectories )) self._mkdir_p( path ) return path def commitAllChanges( self, msg ): p = subprocess.Popen([ 'git', 'add', '.' ], cwd=self._path ) p.wait() p = subprocess.Popen([ 'git', 'commit', '-m', msg ], cwd=self._path ) p.wait() def pullAndPush( self ): self.pull() self.push() def pull( self ): p = subprocess.Popen([ 'git', 'pull', 'origin', 'master' ], cwd=self._path ) p.wait() def push( self ): p = subprocess.Popen([ 'git', 'push', 'origin', 'master' ], cwd=self._path ) p.wait() def _sanitzePathname( self, path ): valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits) return ''.join( c for c in path if c in valid_chars ) def _mkdir_p( self, path ): try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise
Markdown
UTF-8
1,065
3.15625
3
[]
no_license
# resource_scheduling The INPUTS for the model are: • Employee ID • Start Date • End Date • Project • Shift 1. Morning 2. Evening 3. Night Constraints • Not more than 40 hours worked per day. • If worker work that morning, cannot work that day. • If worker working that evening, until next evening. • If worker working in night, until next night. Objective Function • To pass the list of workers for the optimal solution. • To build a week table for the workers. • Swapping the shifts; the morning shift to night, evening to morning & night to evening. Results The mixed integer programming is chosen for the scheduling the resources(workers) because the MIP gives the integer values in return at the optimal solution. In our case, the objective function is defining such that the number of workers required for a particular shift should not work in a consecutive shift and every worker work should be allocated. MIP is the best method to solve this problem and it is practice everywhere for solving resource scheduling problems.
Python
UTF-8
1,338
3.859375
4
[]
no_license
"""https://www.codewars.com/kata/spelling-bee/train/python""" """v2 - Using cool short rotate logic""" def how_many_bees(hive): bee_count = 0 if hive: hive_rotated = list(zip(*hive[::-1])) for lst in (hive, hive_rotated): for row in lst: for step in (1, -1): bee_count += ''.join(row[::step]).count('bee') return bee_count """v1 - Long rotating logic + workaround to get rows as strings""" # def how_many_bees(hive): # hive = [''.join(row) for row in hive] # hive_rotated = [] # for x in range(len(hive[0])): # column = '' # for y in range(len(hive)): # column += hive[y][x] # hive_rotated.append(column) # # bee_count = 0 # for lst in (hive, hive_rotated): # for row in lst: # bee_count += row.count('bee') # bee_count += row[::-1].count('bee') # # return bee_count """Top CW solution - turns search string around rather than search area""" # def count(it): # return sum(''.join(x).count('bee') + ''.join(x).count('eeb') for x in it) # # def how_many_bees(hive): # return count(hive) + count(zip(*hive)) if hive else 0 # TESTS hive = [list("bee.bee"), list(".e..e.."), list(".b..eeb")] print(how_many_bees(hive)) # 5 hive = [list("bee.bee"), list("e.e.e.e"), list("eeb.eeb")] print(how_many_bees(hive)) # 8
C++
UTF-8
1,020
2.859375
3
[]
no_license
#include <iostream> #include <list> #include "../SharedPtr.h" #include <ctime> using namespace std; using namespace ds; // const int maxn = 2000; // template <typename L> // void test() // { // L *l2; // { // clock_t beg = clock(); // L lst; // for (int i = 0; i < maxn; ++i) // lst.push_back(i); // cout << clock() - beg << endl; // } // getchar(); // } struct A { static int cnt; int _cnt_; double x; virtual void foo() const { cout << "A\n"; } virtual ~A() { ++cnt; cout << "A destroy\n"; } }; int A::cnt = 0; struct B : A { double xx; void foo() const override { cout << "B\n"; } ~B() override { cout << "B destroy\n"; } }; int main() { { SharedPtr<A> pa(new B); pa->foo(); auto pa1 = pa; auto pa2 = move(pa); SharedPtr<A> pa3 = nullptr; if (!pa3) pa3 = pa2; swap(pa1, pa2); pa1 = makeShared<A>(); pa2 = pa3 = pa1; //此时之前的B应该析构 pa3->foo(); } cout << A::cnt; }
Java
UTF-8
690
1.890625
2
[]
no_license
package xyz.youjieray.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.quartz.SchedulerFactoryBean; /** * created by IntelliJ IDEA * * @author leihz * @date 2017/7/5 16:54 */ @Configuration public class SchedulerConfig { @Bean public SchedulerFactoryBean schedulerFactoryBean(){ SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean(); schedulerFactoryBean.setSchedulerName("test-Scheduler"); schedulerFactoryBean.setApplicationContextSchedulerContextKey("applicationContext"); return schedulerFactoryBean; } }
Java
UTF-8
363
1.648438
2
[]
no_license
package com.sda.shop.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/gameswebgl") public class GamesController { @GetMapping() public String gameSite() { return "game"; } }
C
UTF-8
631
3.671875
4
[]
no_license
#include<stdio.h> #include<stdlib.h> #define size 10 int binary_search(int *input,int target){ int L = 0; int R = size - 1; while (L <= R){ int M; M = (L + R) / 2; if(input[M]==target){ return M;} else if(input[M]>target) R = M - 1; else L = M + 1; } return -1; } int main(){ int input[size] = {1, 2, 3, 4, 5, 45, 67, 89, 99, 101}; int target; printf("plz enter target:"); scanf("%d", &target); int index = binary_search(input, target); printf("Target is %d and index is at %d", target, index); }
Markdown
UTF-8
1,386
2.875
3
[ "Apache-2.0" ]
permissive
Flatdata Usage Examples ======================= This folder contains examples of flatdata usage. Those are meant to show how to use serialization/deserialization APIs and different resource types available. Binary Layout Example --------------------- This example writes a simple not aligned data structure (23 bits long) to a flatdata vector. The structure is filled with ones and zeroes to make it easier to see how different fields are stored. Two structures are written to the output to show the structure alignment and padding. Coappearances ------------- This examples converts a graph of coappearances from json to flatdata. A graph of coappearances is an undirected graph where the vertices are characters from a book. An edge between two characters represents their appearance in the same scene. The idea of this example to show how to convert a nested data format to a flat representation. Further, the example introduces * all available data structures in flatdata, * a technique how to represent ranges with sentinels, and * representation of strings as raw blocks. The examples also contains a simple reader which dumps the flatdata archive to terminal. The data [karenina.json](coappearances/karenina.json) is based on characters coappearance in Leo Tolstoy's "_Anna Karenina_", compiled by [Donald Knuth][1]. [1]: https://www-cs-faculty.stanford.edu/~knuth/sgb.html
Markdown
UTF-8
3,360
2.703125
3
[ "MIT" ]
permissive
# Pilotes macOS pour le nouveau clavier AZERTY normalisé Utilisez votre clavier existant pour tester la nouvelle disposition des symboles. Vous pouvez l’apprendre en vous aidant du clavier virtuel de macOS ou du site <https://norme-azerty.fr>. Une transcription de la norme NF Z 71‐300 A est utilisée pour générer le pilote: [kbdrefs/nf_z71_300.md](kbdrefs/nf_z71_300.md). ## Installation Pour utiliser un nouveau clavier externe : - Brancher le clavier avant d’installer le pilote. - Vérifier que le type de clavier détecté est bien européen « ISO/IEC 9995 ». - Si ce n’est pas le cas, revenir à l’étape précédente. Au moment d’appuyer sur la touche à côté de Shift, appuyer sur une ou plusieurs autres touches jusqu’à ce que l’assistant vous informe qu’il ne parvient pas à détecter le type de clavier. Choisir le clavier européen « ISO/IEC 9995 ». ![Keyboard Setup Assistant ISO/IEC 9995](https://cyril.lugan.fr/assets/misc/fix-mac-inverted-keys/select-iso-keyboard.png) Pour installer le pilote : - Télécharger le dernier pilote publié sur la page [Releases](https://github.com/cyril-L/normalized-azerty/releases) - Décompresser le fichier `.zip` - Déplacer le fichier `French NF.bundle` dans la bibliothèque : - Depuis le *Finder* → `Aller` → `Aller au dossier` - Pour installer le pilote uniquement pour votre utilisateur, entrez `~/Library/Keyboard Layouts` - Pour installer le pilote pour tous les utilisateurs, entrez `/Library/Keyboard Layouts` (vous devez disposer des droits d’administration) - Déplacer le fichier `French NF.bundle` dans le dossier `Keyboard Layouts` - Activer la disposition depuis les *Préférences Système* → `Clavier` → `Méthodes et saisie` → `+` → `Français normalisé (AZERTY)` - Redémarrer la session ## Mise à jour Pour mettre à jour le pilote, remplacer le fichier `.bundle` existant et redémarrer la session. ## Touches @ et &lt; inversées Si les touches <kbd>@</kbd> et <kbd>&lt;</kbd> sont inversées, il est possible que macOS n’ai pas correctement identifié le clavier. Voir [Issue #9](https://github.com/cyril-L/normalized-azerty/issues/9) ou [Fix inverted keys on a Mac](https://cyril.lugan.fr/misc/fix-mac-inverted-keys.html). ## Build Pour faire une nouvelle release: - Générer le fichier [French - NF.keylayout](https://github.com/cyril-L/normalized-azerty/blob/master/French%20NF.bundle/Contents/Resources/French%20-%20NF.keylayout). Ce fichier est également versionné, il est possible de le modifier avec le logiciel [Ukelele](http://scripts.sil.org/ukelele). ``` ./make_macos_keylayout.py > French\ NF.bundle/Contents/Resources/French\ -\ NF.keylayout ``` - Mettre à jour le fichier [Info.plist](https://github.com/cyril-L/normalized-azerty/blob/master/French%20NF.bundle/Contents/Info.plist) manuellement. - Compresser `French NF.bundle` ``` zip -r normalized-azerty-v0.0.7.zip French\ NF.bundle/ ``` ## Contribution - Rapportez un problème ou une suggestion sur la page [Issues](https://github.com/cyril-L/normalized-azerty/issues) - La disposition suit la description présentée sur le site <https://norme-azerty.fr>. - Les caractères Unicode ont principalement été récupérés sur : - <https://bepo.fr/wiki/Touches_mortes> - <https://github.com/marcbal/Printable-AZERTY-NF>
TypeScript
UTF-8
1,262
2.65625
3
[ "MIT" ]
permissive
import { execSync, StdioOptions } from "child_process"; export const getPRNumber = (msg: string) => { const num = / \(#(?<prNumber>[0-9]+)\)$/m.exec(msg)?.groups?.prNumber; return num ? parseInt(num, 10) : undefined; }; const chunks = <T>(commits: T[]): T[][] => { const batches: T[][] = []; for (let i = 0; i < commits.length; i += 50) { const batch = commits.slice(i, i + 50); batches.push(batch); } return batches; }; export const batchMap = <I, O>(f: (_: I[]) => Promise<O[]>, commits: I[]) => Promise.all(chunks(commits).map((batch) => f(batch))).then((x) => x.flat()); export const isKey = <T extends string>( obj: Record<T, unknown>, key?: string | null ): key is T => typeof key === "string" && key in obj; export const exit = (error: unknown) => { console.error(error); process.exit(1); }; export const exec = (command: string, stdio?: StdioOptions) => execSync(command, { maxBuffer: 10 * 1024 * 1024, // 10MB encoding: "utf-8", stdio, })?.trimEnd(); const colors = { error: "\x1b[31m", success: "\x1b[32m", warning: "\x1b[33m", none: "\x1b[0m", }; export const log = (t: string, type?: "success" | "warning" | "error") => process.stdout.write(colors[type ?? "none"] + t + colors.none);
C#
UTF-8
19,323
3.0625
3
[]
no_license
/* Program: COIS 3020 Assignment 2 * Author: Ryland Whillans * SN: 0618437 * Date: 2019-03-06 * Purpose: * Implements and tests an InRange function for augmented treap * Implements/Augments and tests treap to support MinGap function and * Implements and tests rope data structure * Software/Language: * C# */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace COIS_3020_Assignment_2 { public class Program { static Random V = new Random(); static void Main(string[] args) { // Add comments before test functions to test structures individually RangeTests(); MinGapTests(); RopeTests(); Console.ReadLine(); } // Tests the functionality of the InRange function static void RangeTests() { Console.WriteLine(new string('-', 100)); Console.WriteLine("Testing Augmented Treap Range Functionality"); AugmentedTreapRange<int> range = new AugmentedTreapRange<int>(); // Generate/Display sample tree int[] values = new int[] { 50, 20, 70, 8, 33, 22, 49, 61, 57, 12, 30, 18, 89, 105, 76, 21 }; foreach (int val in values) range.Add(val); range.Print(); // Both bounds included Console.WriteLine("Items in range [22-61]: " + range.InRange(22, 61)); // only right bound included Console.WriteLine("Items in range [9-50]: " + range.InRange(9, 50)); // only left bound included Console.WriteLine("Items in range [57-71]: " + range.InRange(57, 71)); // neither bound included Console.WriteLine("Items in range [25-35]: " + range.InRange(25, 35)); // no items in range Console.WriteLine("Items in range [62-69]: " + range.InRange(62, 69)); // no items in range, both bounds < all items Console.WriteLine("Items in range [1-5]: " + range.InRange(1, 5)); // no items in range, both bounds > all items Console.WriteLine("Items in range [110-120]: " + range.InRange(110, 120)); // same bounds Console.WriteLine("Items in range [8-8]: " + range.InRange(8, 8)); // same bounds no item Console.WriteLine("Items in range [9-9]: " + range.InRange(9, 9)); // bounds reverse order Console.WriteLine("Items in range [50-20]: " + range.InRange(50, 20)); // negative bound Console.WriteLine("Items in range [50-20]: " + range.InRange(-10, 20)); Console.WriteLine(new string('-', 100)); } // Tests functionality of the MinGap function and the ability of the tree to maintain augmented data static void MinGapTests() { Console.WriteLine(new string('-', 100)); Console.WriteLine("Testing Augmented Treap MinGap Functionality"); MinGapTreap minGap = new MinGapTreap(); // Generate/Display sample tree int[] values = new int[] { 50, 20, 70, 8, 33, 22, 48, 61, 57, 12, 30, 18, 89, 105, 76, 27 }; foreach (int val in values) minGap.Add(val); minGap.Print(); Console.WriteLine("Minimum Gap: " + minGap.MinGap()); Console.WriteLine(new string('-', 100)); // Remove no change MinGap minGap.Remove(50); Console.WriteLine("Removing 50"); minGap.Print(); Console.WriteLine("Minimum Gap: " + minGap.MinGap()); Console.WriteLine(new string('-', 100)); // Remove increase MinGap minGap.Remove(20); Console.WriteLine("Removing 20"); minGap.Print(); Console.WriteLine("Minimum Gap: " + minGap.MinGap()); Console.WriteLine(new string('-', 100)); // Remove increase MinGap minGap.Remove(30); Console.WriteLine("Removing 30"); minGap.Print(); Console.WriteLine("Minimum Gap: " + minGap.MinGap()); Console.WriteLine(new string('-', 100)); // Add no change MinGap minGap.Add(99); Console.WriteLine("Adding 99"); minGap.Print(); Console.WriteLine("Minimum Gap: " + minGap.MinGap()); Console.WriteLine(new string('-', 100)); // Add reduce MinGap minGap.Add(68); Console.WriteLine("Adding 68"); minGap.Print(); Console.WriteLine("Minimum Gap: " + minGap.MinGap()); Console.WriteLine(new string('-', 100)); // Add reduce MinGap minGap.Add(28); Console.WriteLine("Adding 28"); minGap.Print(); Console.WriteLine("Minimum Gap: " + minGap.MinGap()); Console.WriteLine(new string('-', 100)); MinGapTreap minGap2 = new MinGapTreap(); // Only a single element Console.WriteLine("Single element treap:"); minGap2.Add(50); minGap2.Print(); Console.WriteLine(new string('-', 100)); // Only 2 elements Console.WriteLine("Two element treap:"); minGap2.Add(10); minGap2.Print(); Console.WriteLine(new string('-', 100)); } // Tests various functionality of ropes static void RopeTests() { Console.WriteLine(new string('-', 100)); Console.WriteLine("Testing Rope Functionality"); // Constructor for long string Rope rope = new Rope("aaaaabbbbbcccccdddddeeeeefffffggggghhhhhiiiiijjjjjkkkkklllllmmmmmnnnnnooooopppppqqqqqrrrrrssssstttttuuuuuvvvvvwwwwwxxxxxyyyyyzzzzz"); Console.Write("Rope Value: "); rope.Print(); Console.WriteLine("Rope Structure: "); rope.PrintStructure(); Console.WriteLine(new string('-', 100)); // Concatenation normal case Rope rope2 = Rope.Concatenate(new Rope("abcdefghijklmnopqrstuvwxyz"), new Rope("zyxwvutsrqponmlkjihgfedcba")); Console.Write("Rope Value: "); rope2.Print(); Console.WriteLine("Rope Structure: "); rope2.PrintStructure(); Console.WriteLine(new string('-', 100)); // Concatenation 2 small ropes Rope rope3 = Rope.Concatenate(new Rope("12345"), new Rope("54321")); Console.Write("Rope Value: "); rope3.Print(); Console.WriteLine("Rope Structure: "); rope3.PrintStructure(); Console.WriteLine(new string('-', 100)); // Concatenation, rope with small right child + small rope Rope rope4 = Rope.Concatenate(new Rope("123456789012345"), new Rope("abcd")); Console.Write("Rope Value: "); rope4.Print(); Console.WriteLine("Rope Structure: "); rope4.PrintStructure(); Console.WriteLine(new string('-', 100)); Console.Write("Rope Value: "); rope.Print(); // Substring overlapping nodes Console.WriteLine("\nSubstring [23,47]: " + rope.Substring(23, 47)); // substring single node Console.WriteLine("Substring [23,25]: " + rope.Substring(23, 25)); // substring single char Console.WriteLine("Substring [99,99]: " + rope.Substring(99, 99)); // substring index 0 bound Console.WriteLine("Substring [0,32]: " + rope.Substring(0, 32)); // substring max index bound Console.WriteLine("Substring [0,32]: " + rope.Substring(102, 129)); // substring index < 0 Console.WriteLine("Substring [-1,10]: " + (rope.Substring(-1, 10) == null ? "No substring found" : "Substring found")); // substring > max Console.WriteLine("Substring [50,150]: " + (rope.Substring(50, 150) == null ? "No substring found" : "Substring found")); // start index > end index Console.WriteLine("Substring [20,10]: " + (rope.Substring(20, 10) == null ? "No substring found" : "Substring found")); // ChatAt index within range Console.WriteLine("\nChar at index 25: " + rope.CharAt(25)); // ChatAt index 0 Console.WriteLine("Char at index 25: " + rope.CharAt(0)); // ChatAt max index Console.WriteLine("Char at index 25: " + rope.CharAt(129)); // ChatAt index < 0 Console.WriteLine("Char at index 25: " + (rope.CharAt(130) == '\0' ? "No char found" : "char found")); // ChatAt index > max Console.WriteLine("Char at index 25: " + (rope.CharAt(-1) == '\0' ? "No char found" : "char found")); // Find string accross multiple nodes Console.WriteLine("\nFind string \"dddee\" index: " + rope.Find("dddee")); // Find string in single node Console.WriteLine("Find string \"dddee\" index: " + rope.Find("ggghh")); // find string not in rope Console.WriteLine("Find string \"dddee\" index: " + rope.Find("xxxxxx")); // find empty string Console.WriteLine("Find string \"dddee\" index: " + rope.Find("")); // find string exceeding rope capacity Console.WriteLine("Find string \"dddee\" index: " + rope.Find(new string('a', 200))); // Splitting rope at end node Console.WriteLine(new string('-', 100)); Console.WriteLine("Splitting rope at index 69"); Rope rope5 = rope.Split(69); Console.Write("Left Split Rope Value: "); rope.Print(); Console.WriteLine("Left Split Rope Structure: "); rope.PrintStructure(); Console.Write("Right Split Rope Value: "); rope5.Print(); Console.WriteLine("Right Split Rope Structure: "); rope5.PrintStructure(); // splitting rope mid node Console.WriteLine(new string('-', 100)); Console.WriteLine("Splitting rope at index 48"); rope5 = rope.Split(48); Console.Write("Left Split Rope Value: "); rope.Print(); Console.WriteLine("Left Split Rope Structure: "); rope.PrintStructure(); Console.Write("Right Split Rope Value: "); rope5.Print(); Console.WriteLine("Right Split Rope Structure: "); rope5.PrintStructure(); // splitting rope at end of rope Console.WriteLine(new string('-', 100)); Console.WriteLine("Splitting rope at index 48"); rope5 = rope.Split(48); Console.Write("Left Split Rope Value: "); rope.Print(); Console.WriteLine("Left Split Rope Structure: "); rope.PrintStructure(); Console.Write("Right Split Rope Value: "); rope5.Print(); Console.WriteLine("Right Split Rope Structure: "); rope5.PrintStructure(); // splitting rope at start of rope (index - 1) Console.WriteLine(new string('-', 100)); Console.WriteLine("Splitting rope at index -1"); rope5 = rope.Split(-1); Console.Write("Left Split Rope Value: "); rope.Print(); Console.WriteLine("Left Split Rope Structure: "); rope.PrintStructure(); Console.Write("Right Split Rope Value: "); rope5.Print(); Console.WriteLine("Right Split Rope Structure: "); rope5.PrintStructure(); rope = rope5; // splitting rope at index > rope length Console.WriteLine(new string('-', 100)); Console.WriteLine("Splitting rope at index 100"); rope5 = rope.Split(100); Console.Write("Left Split Rope Value: "); rope.Print(); Console.WriteLine("Left Split Rope Structure: "); rope.PrintStructure(); Console.WriteLine("Right Split Rope Value: " + (rope5 == null ? "null" : " not null")); // splitting rope at index < start Console.WriteLine(new string('-', 100)); Console.WriteLine("Splitting rope at index -10"); rope5 = rope.Split(-10); Console.Write("Left Split Rope Value: "); rope.Print(); Console.WriteLine("Left Split Rope Structure: "); rope.PrintStructure(); Console.WriteLine("Right Split Rope Value: " + (rope5 == null ? "null" : " not null")); Console.WriteLine(new string('-', 100)); rope = new Rope("aaaaabbbbbcccccdddddeeeeefffffggggghhhhhiiiiijjjjjkkkkklllllmmmmmnnnnnooooopppppqqqqqrrrrrssssstttttuuuuuvvvvvwwwwwxxxxxyyyyyzzzzz"); Console.Write("Rope Value: "); rope.Print(); Console.WriteLine("Rope Structure: "); rope.PrintStructure(); // deleting from center of rope crossing multiple nodes Console.WriteLine(new string('-', 100)); if (rope.Delete(30, 65)) Console.WriteLine("Deleted substring [30,65]"); else Console.WriteLine("Failed to delete substring [30,65]"); Console.Write("Rope Value: "); rope.Print(); Console.WriteLine("Rope Structure: "); rope.PrintStructure(); Console.WriteLine(new string('-', 100)); // deleting single character if (rope.Delete(90, 90)) Console.WriteLine("Deleted substring [90,90]"); else Console.WriteLine("Failed to delete substring [90,90]"); Console.Write("Rope Value: "); rope.Print(); Console.WriteLine("Rope Structure: "); rope.PrintStructure(); Console.WriteLine(new string('-', 100)); // deleting from middle of string if (rope.Delete(50, 68)) Console.WriteLine("Deleted substring [50,68]"); else Console.WriteLine("Failed to delete substring [50,68]"); Console.Write("Rope Value: "); rope.Print(); Console.WriteLine("Rope Structure: "); rope.PrintStructure(); Console.WriteLine(new string('-', 100)); // deleting from end of string if (rope.Delete(48, 73)) Console.WriteLine("Deleted substring [48,73]"); else Console.WriteLine("Failed to delete substring [48,73]"); Console.Write("Rope Value: "); rope.Print(); Console.WriteLine("Rope Structure: "); rope.PrintStructure(); Console.WriteLine(new string('-', 100)); // deleting from start of string if (rope.Delete(0, 15)) Console.WriteLine("Deleted substring [0,15]"); else Console.WriteLine("Failed to delete substring [0,15]"); Console.Write("Rope Value: "); rope.Print(); Console.WriteLine("Rope Structure: "); rope.PrintStructure(); Console.WriteLine(new string('-', 100)); // deleting with second bound exceding string size if (rope.Delete(25, 100)) Console.WriteLine("Deleted substring [25,100]"); else Console.WriteLine("Failed to delete substring [25,100]"); Console.Write("Rope Value: "); rope.Print(); Console.WriteLine(new string('-', 100)); // deleting with first bound exceding string size if (rope.Delete(-10, 10)) Console.WriteLine("Deleted substring [-10,10]"); else Console.WriteLine("Failed to delete substring [-10,10]"); Console.Write("Rope Value: "); rope.Print(); Console.WriteLine(new string('-', 100)); // inserting at center of rope if (rope.Insert("ABCDEFGHIJKLMNO", 11)) Console.WriteLine("Inserted \"ABCDEFGHIJKLMNO\" at index 11"); else Console.WriteLine("Failed to insert at index 11"); Console.Write("Rope Value: "); rope.Print(); Console.WriteLine("Rope Structure: "); rope.PrintStructure(); Console.WriteLine(new string('-', 100)); // inserting samll string inside other string if (rope.Insert("QRS", 28)) Console.WriteLine("Inserted \"QRS\" at index 28"); else Console.WriteLine("Failed to insert at index 28"); Console.Write("Rope Value: "); rope.Print(); Console.WriteLine("Rope Structure: "); rope.PrintStructure(); Console.WriteLine(new string('-', 100)); // inserting at start of rope if (rope.Insert("TUVW", 0)) Console.WriteLine("Inserted \"TUVM\" at index 0"); else Console.WriteLine("Failed to insert at index 0"); Console.Write("Rope Value: "); rope.Print(); Console.WriteLine("Rope Structure: "); rope.PrintStructure(); Console.WriteLine(new string('-', 100)); // inserting at end of rope if (rope.Insert("XYZ", 54)) Console.WriteLine("Inserted \"XYZ\" at index 54"); else Console.WriteLine("Failed to insert at index 54"); Console.Write("Rope Value: "); rope.Print(); Console.WriteLine("Rope Structure: "); rope.PrintStructure(); Console.WriteLine(new string('-', 100)); // inserting before start of rope if (rope.Insert("AAAAA", -10)) Console.WriteLine("Inserted \"AAAA\" at index -10"); else Console.WriteLine("Failed to insert at index -10"); Console.Write("Rope Value: "); rope.Print(); // inserting after end of rope if (rope.Insert("ZZZZZ", 100)) Console.WriteLine("Inserted \"ABCDEFGHIJKLMNO\" at index 100"); else Console.WriteLine("Failed to insert at index 100"); Console.Write("Rope Value: "); rope.Print(); /* Console.WriteLine(rope.CharAt(89)); Console.WriteLine(rope.Substring(20, 55)); Console.WriteLine(rope.Find("aaaaabbbbbbb")); //Rope split = rope.Split(25); rope.Insert("123456789012345", 0); rope.PrintStructure(); rope.Delete(0, 170); rope.PrintStructure(); rope.Print(); rope.Insert("123456789012345", 0); rope.PrintStructure(); //split.PrintStructure(); */ } } }
Markdown
UTF-8
733
2.703125
3
[]
no_license
# Vertis Timesheet ## [View here](https://vertis-time-sheet.herokuapp.com/) ## Stack Used + **Server Framework & Environment**: Express & Node + **Authentication and Authorization**: JSON Web Tokens + **Database**: MongoDb (hosted on [mLab](https://mlab.com/)) + **Frontend Framework**: React ## Other libraries used + [Axios](https://www.npmjs.com/package/axios) to handle api requests + [Materialize CSS](https://materializecss.com/) for UI styling + [Duration](https://www.npmjs.com/package/duration) for calculating duration on tasks + [React Moment](https://www.npmjs.com/package/react-moment) for datetime formatting on frontend + [Serve](https://www.npmjs.com/package/serve) to serve the application remotely on heroku
PHP
UTF-8
2,850
3.078125
3
[]
no_license
<?php /** * Landing Page Engine * * @package Gm\LandingPageEngine * @subpackage Form\Validator * @link https://bitbucket.org/sudtanadevteam/landing-page-engine * @copyright Copyright (c) 2016 */ namespace Gm\LandingPageEngine\Form\Validator; class StringLength extends AbstractValidator { const STRING_LENGTH_MIN = 'string-length-min'; const STRING_LENGTH_MAX = 'string-length-max'; /** * @var int */ protected $min = 5; /** * @var int */ protected $max = 10; /** * @var array */ public static $messageTemplates = [ 'en' => [ self::STRING_LENGTH_MIN => 'The input must be at least %s characters', self::STRING_LENGTH_MAX => 'The input must be shorter than %s characters' ], 'th' => [ self::STRING_LENGTH_MIN => 'ต้องกรอกข้อความอย่างน้อย %s ตัวอักษร', self::STRING_LENGTH_MAX => 'ข้อความต้องน้อยกว่า %s ตัวอักษร' ] ]; public function __construct() { } /** * Set the minimal string length * * @param int $min the minimal string length in character * @return StringLength */ public function setMin($min) { $this->min = (int) $min; return $this; } /** * Get the minimal string length * * @return int the minimal string length */ public function getMin() { return $this->min; } /** * Set the maximum string length * * @param int $max maximum string length in characters * @return StringLength */ public function setMax($max) { $this->max = (int) $max; return $this; } /** * Get the maximum string length * * @return int the maximum string length */ public function getMax() { return $this->max; } public function isValid($value, $context = null) { if (!is_string($value)) { throw new Exception\InvalidArgumentException(sprintf( '%s expects a string value', __METHOD__ )); } $this->setValue($value); if (mb_strlen($value) < $this->min) { $this->messages[self::STRING_LENGTH_MIN] = sprintf( self::$messageTemplates[$this->lang][self::STRING_LENGTH_MIN], $this->min ); return false; } if (mb_strlen($value) > $this->max) { $this->messages[self::STRING_LENGTH_MAX] = sprintf( self::$messageTemplates[$this->lang][self::STRING_LENGTH_MAX], $this->max ); return false; } return true; } }
Markdown
UTF-8
581
3.046875
3
[ "Apache-2.0" ]
permissive
# Else & Elif Er is ook een `else` clausule die gebruikt wordt telkens dat de eerste conditie niet waar is. Dit is een handig hulpmiddel als je overal op wilt reageren maar een aparte handeling wilt uitvoeren voor één ding: ```python land = 'Engeland' if land == 'England': parapluNodig = True else: parapluNodig = False ``` De `else` clausule kan ook worden samengevoegd met nog een `if`, zoals deze versie van het vorige onderdeel: ```python land = 'Engeland' if land == 'England': # etc elif land == 'France': # etc elif land == 'Germany': # etc ```
C#
UTF-8
1,979
3.65625
4
[]
no_license
using System; namespace Lemonade_Stand{ public class Weather{ public int weatherNumber; public int currentTemp; public int tempratureNumber; public string currentWeather; public string currentTemprature; public void SetWeather(){ //Generate a number between 1 and 5 Random weatherNum = new Random(); weatherNumber = weatherNum.Next(1, 5); //Assign a weather to each number if (weatherNumber == 5){ currentWeather = "Sunny"; } else if (weatherNumber == 4){ currentWeather = "Partly sunny/cloudy"; } else if (weatherNumber == 3) { currentWeather = "Hazy"; } else if (weatherNumber == 2) { currentWeather = "Cloudy"; } else if (weatherNumber == 1) { currentWeather = "Rainy"; } } public void SetTemp(){ //Generate a number between 50 and 100 Random tempGen = new Random(); currentTemp = tempGen.Next(50, 100); //Assign a description to each temprature bracket if (currentTemp > 50 && currentTemp < 60){ currentTemprature = "Cold"; tempratureNumber = currentTemp; } else if (currentTemp > 60 && currentTemp < 70){ currentTemprature = "Mild"; tempratureNumber = currentTemp; } else if (currentTemp > 70 && currentTemp < 80){ currentTemprature = "Warm"; tempratureNumber = currentTemp; } else if (currentTemp > 80 && currentTemp < 90){ currentTemprature = "Hot"; tempratureNumber = currentTemp; } else if (currentTemp > 90 && currentTemp < 100){ currentTemprature = "Burning"; tempratureNumber = currentTemp; } } } }
JavaScript
UTF-8
3,486
2.65625
3
[]
no_license
$(document).ready(function() { $('form.single-task-form div.switch input').change(function(){ var task_id = $(this).parent().parent().data('task-id'); var finished_value = $(this).attr('value'); $.ajax({ type: 'POST', url: '/edit/' + task_id, data: { finished: finished_value }, success: function( msg ) { var original_div = $('div[data-task-id="' + task_id + '"]'); if ( finished_value === 'true' ) { //console.log("EVALUATED TRUE!" + finished_value); appendMessage( original_div, task_id, msg ); setTimeout( function(){ moveMessage( original_div, '#finished_tasks' ) }, 900 ); } else if ( finished_value === 'false' ) { console.log("EVALUATED FALSE" + finished_value); //appendMessage( original_div, task_id, msg ); setTimeout( function(){ moveMessage( original_div, '#open_tasks') }, 900); } else { console.log('Couldn\'t Move Task!'); } } }); }); /* $('button.edit_task'.click() { var task_id = $(this).parent().data('task-id'); $.ajax({ type: 'POST', url: '' + task_id, data: '', success: function( msg ) { $('div[data-task-id="' + task_id + '"]'). } }) } */ $('button.archive_task').click( function() { var task_id = $(this).parent().parent().data('task-id'); var original_div = $('div[data-task-id="' + task_id + '"]'); $.ajax({ type: 'POST', url: '/archive/' + task_id, data: '', success: function( msg ) { appendMessage( original_div, task_id, msg ); setTimeout( function() { $('div[data-task-id="' + task_id + '"]').fadeOut().remove(); }, 3000 ); } }); } ); $('button.delete_task').click( function(){ var task_id = $(this).parent().parent().data('task-id'); var original_div = $('div[data-task-id="' + task_id + '"]'); $.ajax({ type: 'POST', url: '/delete/' + task_id, data: '', success: function( msg ) { appendMessage( original_div, task_id, msg ); setTimeout( function() { $('div[data-task-id="' + task_id + '"]').fadeOut().remove(); }, 3000 ); } }) } ); $('div.task_options').hide(); $('i.settings_icon').click( function() { $(this).siblings('div.task_options').slideToggle(); $(this).toggleClass('activated'); } ); $('div.new_task_drawer').hide(); $('button.drawer_button').click( function() { $(this).siblings('div.new_task_drawer').slideToggle(); } ); toggleLinks('show_open', 'open_tasks'); toggleLinks('show_finished', 'finished_tasks'); function toggleLinks( link_class, div_id ) { $('div#'+ div_id).hide(); $('a.' +link_class).click( function(event) { event.preventDefault(); if ( $(this).text() == '+' ) { $(this).text('-'); $('div#'+ div_id).slideToggle(); } else if ( $(this).text() == '-') { $(this).text('+'); $('div#'+ div_id).slideToggle(); } } ); } function moveMessage( original_div, div ) { var div var original_div $(original_div).parent() .fadeOut( 500, function() { $(this) .detach() .appendTo(div) .fadeIn( 300 ); }); } function appendMessage( original_div, task_id, msg ) { $(original_div).append( '<button class="success" data-task-id="' + task_id + '">' + msg + '</button>' ); setTimeout( function() { $('button[data-task-id="' + task_id + '"]').fadeOut( 300 ) }, 2000 ); } });
Markdown
UTF-8
19,813
2.515625
3
[]
no_license
# Observability demo for Sumo Logic Using Telegraf ![topn](docs/linux-dash-topn.png) ![linuxdash1](docs/linux-dash-1-cpumem.png) <!-- vscode-markdown-toc --> * 1. [Overview](#Overview) * 1.1. [highlights](#highlights) * 2. [Design Considerations](#DesignConsiderations) * 2.1. [collection](#collection) * 2.2. [sumo metadata in the telegraf.conf](#sumometadatainthetelegraf.conf) * 2.3. [Tagging As a Basic of Hierarchy In Explore](#TaggingAsaBasicofHierarchyInExplore) * 2.3.1. [global tags](#globaltags) * 2.3.2. [input level tags](#inputleveltags) * 2.4. [Hierarchy](#Hierarchy) * 2.5. [Data Points Per Minute (DPM) and Credits Consumption](#DataPointsPerMinuteDPMandCreditsConsumption) * 2.6. [Process level metrics procstat plugin](#Processlevelmetricsprocstatplugin) * 3. [Setup](#Setup) * 3.1. [Collection](#Collection) * 3.2. [telegraf install](#telegrafinstall) * 4. [telegraf configuration](#telegrafconfiguration) * 4.1. [output url](#outputurl) * 4.2. [tags](#tags) * 5. [importing demo app](#importingdemoapp) * 6. [build a hierarchy](#buildahierarchy) * 6.1. [Custom hierarchy by component tag](#Customhierarchybycomponenttag) * 6.2. [Custom hierarchy by business tags: service/environment/component](#Customhierarchybybusinesstags:serviceenvironmentcomponent) * 6.1. [Stack Linking](#StackLinking) * 6.1.1. [stack linking to entities](#stacklinkingtoentities) * 6.1.2. [stack linking to higher level nodes such as environment.](#stacklinkingtohigherlevelnodessuchasenvironment.) * 7. [Integrating Existing Content Into the New Hierarchy Tree](#IntegratingExistingContentIntotheNewHierarchyTree) * 7.1. [Walkthrough - convert the redis overview dasbhoard to work with the new hierarchy](#Walkthrough-converttheredisoverviewdasbhoardtoworkwiththenewhierarchy) * 7.1.1. [fix up the stack linking.](#fixupthestacklinking.) * 7.2. [Creating a redis _sourcehost node dashboard](#Creatingaredis_sourcehostnodedashboard) <!-- vscode-markdown-toc-config numbering=true autoSave=true /vscode-markdown-toc-config --> <!-- /vscode-markdown-toc --> ## 1. <a name='Overview'></a>Overview This is a very rough demo project to show how we can: - use telegraf to collect and forward base level linux metrics to sumo for disk, cpu, mem - monitor per linux process with procstat plugin - [docker image](./docker) for plugins such as ping/ http-response synthetic checks - create a custom [Explore](https://help.sumologic.com/Visualizations-and-Alerts/Explore) hierarchy using telegraf metrics or custom metric tag dimensions such as environment or service name. - add custom stack linked dashboards to the explore tree - create example alerts. ### 1.1. <a name='highlights'></a>highlights - example linux telegraf host config [here](./config/linux.telegraf.conf). The template includes key plugins for linux with some config tweaks to provide a good OOTB starting config that balances metric choices vs DPM. You can also find in here an example of per process metrics collection with procstat. - [docker image](./docker) for plugins such as ping/ http_response / statsd inputs - a [script to create a custom heirarchy by telegraf component](explore/new-hr-os-nginx-redis.py) - a [script to create a custom hierarchy by custom tags](explore/new-hr.py) - a [linux host level dashboard](dashboards/1-linux-host.json) for telegraf template - a [process monitoring dashbboard](dashboards/3-linux-processes.json) for the procstat plugin - a l[inux overview showing top n disk, cpu, memory](dashboards/2-linux-top-n.json) for the telegraf metrics. this is stack linked to a custom hierarchy (service, environment,component) ## 2. <a name='DesignConsiderations'></a>Design Considerations ### 2.1. <a name='collection'></a>collection Metrics will be streamed in prometheus format to sumo HTTPS source using the sumologic output plugin. This is standard to [integrating telegraf into Sumo](https://help.sumologic.com/03Send-Data/Collect-from-Other-Data-Sources/Collect_Metrics_Using_Telegraf). ### 2.2. <a name='sumometadatainthetelegraf.conf'></a>sumo metadata in the telegraf.conf - _collector and _source will represent the hosted collection endpoints - sourcecategory: set to 'metrics/telegraf'. A real world telegraf implmentation could have many sources included in a telegraf.conf file, so by keeping the sourcecategory generic we ensure telegraf sourced metrics are easily identified in sumo. - sourceHost: telegraf sends a 'host' tag but we will also send _sourcehost correctly for consistency on sumo side. ``` source_host = "${HOSTNAME}" source_category = "metrics/telegraf" ``` ### 2.3. <a name='TaggingAsaBasicofHierarchyInExplore'></a>Tagging As a Basic of Hierarchy In Explore We need a consistent and generic metric tag scheme to enable reporting in sumo by key dimensions, and to build a custom heirarchy in explore. Each metric set sent should have a 'component' tag set that will be the primary method to group telegraf metrics sent. The actual tags used could vary between customer environments but should include things like: - environment - application / service name - datacenter or cloud provider - technical/business or budget owners. #### 2.3.1. <a name='globaltags'></a>global tags This example has hardcoded tags but best practice would be to set these as environment variables instead. See the user row as an example: ``` [global_tags] component="os-linux" environment="test" datacenter="us-east-2" service="myservice" user = "${USER}" ``` #### 2.3.2. <a name='inputleveltags'></a>input level tags example using redis input ``` [inputs.redis.tags] environment="prod" component="database" db_system="redis" db_cluster="redis_prod_cluster01" ``` ### 2.4. <a name='Hierarchy'></a>Hierarchy [Explore](https://help.sumologic.com/Visualizations-and-Alerts/Explore) is a navigation tool that provides an intuitive visual hierarchy of your environment. Use Explore to facilitate successful monitoring, managing, and troubleshooting. OOTB sumo provides explore integrations for AWS, Kubentetes & distributed tracing. This can be extended to have a cusotm hierarchy but this must be done via API - but we need a tagging scheme that is consistent (see tags prior topic!) as a base for the hierarchy. We can use the explorer API to create one or more custom heirarchies for example: - environment / service / component - service / environment / component - telegraf by component and so on. So for example the 'component' level might include things like: - os-linux - database - nginx and any other telegraf plugins we want to integrate into sumo and the heirarchy tree. ![component hierarchy](docs/telegraf-components-hr.png "component hierarchy") Note: users could additionally use the filters feature in explore to search by any tags applied see [filter explore](https://help.sumologic.com/Visualizations-and-Alerts/Explore/Filter_Explore). ### 2.5. <a name='DataPointsPerMinuteDPMandCreditsConsumption'></a>Data Points Per Minute (DPM) and Credits Consumption Sumo metrics is a volume based charging model on DPM (Data Points Per Minute) which might say consume 3 credits per 1000 DPM averaged over 1 day. This means more DPM will consume more credits - so choosing more telegraf metrics, polling more often and more fields combinations will increase the DPM count. Let's look at this in more detail: 1. more frequent data points generate more DPM. To configure use the interval/flush interval. Pay close attentin to what settings you are using for interval = "15s" flush_interval = "15s" More frequent metrics will result in higher granulaity but higher DPM consumption per host. Less frequent metric data poinst (say every 1m or 2m) will reduce DPM consumption per host. 2. number of metric series/tag/fields. Use namepass / fieldpass / fielddrop etc to restrict collected metrics to only useful ones. You will find many examples of this in the linux template for example: ``` [[inputs.diskio]] fieldpass = ["*_time","*bytes"] ``` 3. tag cardinality: be careful of tags that introduce higher cardinality as this will result in more DPM if there are many permutations over a short time range. ### 2.6. <a name='Processlevelmetricsprocstatplugin'></a>Process level metrics procstat plugin procstat plugin provides per host metrics. It's recommended to monitor only specific processes this way as you will get multiple dpm per process per host, and there can be **hundreds of running processes** on a single host! The template includes an example config to monitor java processes on a host. The config below: - includes processes with java in the regex pattern - does not include cmdline tag (this will be too long in many cases for the sumo tag character limit) - pid - is added as a tag to make it easier to distinguish on sumo side per instance/process - fieldpass limits metrics collected to a sensible middle ground for DPM. ``` [[inputs.procstat]] pattern = "java" cmdline_tag = false pid_tag = true fieldpass = ["cpu_usage","cpu_time","memory_usage","pid","memory_swap","*bytes","num_threads"] ``` ## 3. <a name='Setup'></a>Setup ### 3.1. <a name='Collection'></a>Collection Create a hosted collector and HTTPS Source as per [configure sumo output plugin](https://help.sumologic.com/03Send-Data/Collect-from-Other-Data-Sources/Collect_Metrics_Using_Telegraf/05_Configure_Telegraf_Output_Plugin_for_Sumo_Logic) and note the url for later! ### 3.2. <a name='telegrafinstall'></a>telegraf install See: https://help.sumologic.com/03Send-Data/Collect-from-Other-Data-Sources/Collect_Metrics_Using_Telegraf/03_Install_Telegraf#install-telegraf-in-a-non-kubernetes-environment ## 4. <a name='telegrafconfiguration'></a>telegraf configuration Use the supplied [config/linux.telegraf.conf](config/linux.telegraf.conf)] example as a start point. This includes the typical linux host plugins to get us coverage of: - disk - cpu - memory - swap - diskio - system (uptime etc) - process count - procstat - provides example of per process montioring. You can also find some examples for nginx or redis plugins. You can add any other plugins just consider up from what component value you will use and how stack linking might be achieved. ### 4.1. <a name='outputurl'></a>output url Make sure to set SUMO_URL environment variable to match the https source you created earlier. for example: ``` export SUMO_URL="https://abcdefg" ``` ### 4.2. <a name='tags'></a>tags Note that we have a global tag component="os-linux" Set global and/or input level tags to match the hierarchy levels that you want to use in your organization. It's recommended to use environment variables or a code pipeline to parameterize these to avoid hardcoding them in your configuration file. Such as: ``` component="os-linux" environment="test" datacenter="us-east-2" service="myservice" user = "${USER}" ``` ## 5. <a name='importingdemoapp'></a>importing demo app You can find a complete demo app set of dashboards [here](complete-app/telegraf.json) This includes examples of generic dashboards for base components as well as stack linked higher level dashboards to link to a service/environment/component hierarchy. See this article if you are not familiar with how to [import content](https://help.sumologic.com/05Search/Library/Export-and-Import-Content-in-the-Library). ## 6. <a name='buildahierarchy'></a>build a hierarchy Once you have decided on a heirarchy and made sure the metrics collected have matching tag dimensions configured we can build one more heirarchies using the explore API. There are various ways to structure a heirarchy you can see examples of different approaches in this file [hr-all.demo.json](./explore/hr-all-demo.json) This is a get of all standard sumo hierarchy types from a demo org. #### 6.1. <a name='Customhierarchybycomponenttag'></a>Custom hierarchy by component tag We can build a hierarchy 1 level deep to show content for each telgraf plugin that is integrated. If you refer to [telegraf-components](explore/telegraf-components) you will see we can show each new component as a level, then have a dynamic list of all nodes in the that level with something like this: ``` { "name": "telegraf-components", "level": { "entityType": "component", "nextLevelsWithConditions": [ { "condition": "os-linux", "level": { "entityType": "_sourcehost", "nextLevelsWithConditions": [], "nextLevel": null } }, ``` Use a API call to upload the new hierarchy similar to the new-hr.py scripts in ./explore. ![component hierarchy](docs/telegraf-components-hr.png "component hierarchy") #### 6.2. <a name='Customhierarchybybusinesstags:serviceenvironmentcomponent'></a>Custom hierarchy by business tags: service/environment/component If you refer to the [hr-example.json](./explore/hr-example.json) you will see we can create a heirarchy that includes some of our business level tags (such as application or environment), then split out the compoents with a node for each component type such as os-linux. ![Business tag hierarchy](docs/telegraf-service-explore.png "Business tag hierarchy") ### 6.1. <a name='StackLinking'></a>Stack Linking Once you have built your hierarchy you can work on stack linking custom content. Two example hierarchies and upload scripts can be found in the ./explore folder. #### 6.1.1. <a name='stacklinkingtoentities'></a>stack linking to entities Ideally we would start with base level node home dashbaord say for a linux host or database instance. This should be stack linked to the lowest level such as _sourcehost. Here is an example [linux home page](dashboards/1-linux-host-overview.json) for any os-linux component instance. Next you can create more high level views to stack to higher levels of the hierarchy. For example the [topn](dashboards/2-linux-top-n.json) will show just the highest cpu nodes , fullest disk volumes etc. This can then be [stack linked](https://help.sumologic.com/Visualizations-and-Alerts/Dashboard_(New)/Link_a_dashboard_to_Explore) to the component level. An example is this dashboard: [dashboards/1-linux-host.json](dashboards/1-linux-host.json) which is a generic linux host dashboard to use as a home page for a single os-linux entity. #### 6.1.2. <a name='stacklinkingtohigherlevelnodessuchasenvironment.'></a>stack linking to higher level nodes such as environment. You can then build and stack link higher level views that might show say per service or per environment summaries for all components you are deploying. At higher levels of the tree we can stack link other custom dashboards such as at the 'top n' dashboard linked to os-linux component level that shows top usage of disk cpu etc across all os-linux nodes. [dashboards/2-linux-top-n.json](dashboards/2-linux-top-n.json) Stack linking is done via the UI or by updating the JSON for the dashboard. ![Stack link base node](docs/stacklink-hostlevel.png "Stack link base node") ![higher level stack link](docs/stacklink.png "higher level stack link") Note - you can't always stack link a single type of dashboard to multiple levels of a multi level hierarchy so you might need to create duplicates of the same dashboard with different stack link values. ## 7. <a name='IntegratingExistingContentIntotheNewHierarchyTree'></a>Integrating Existing Content Into the New Hierarchy Tree Some sumo apps already exist for various telegraf plugins but they might not work out of the box with our new hierarchy. This is because the template parameters have to match exactly the names we use to map out each hierarchy level. So for example for redis if we are using this: ``` { "condition": "database", "level": { "entityType": "db_system", "nextLevelsWithConditions": [{ "condition": "redis", "level": { "entityType": "_sourcehost", "nextLevelsWithConditions": [], "nextLevel": null } }], "nextLevel": null } } ``` We need to modify the sumo app dashboards to use these template variables: - component=redis - db_system=redis - _sourcehost Let's work through fixing up some of the redis content. ### 7.1. <a name='Walkthrough-converttheredisoverviewdasbhoardtoworkwiththenewhierarchy'></a>Walkthrough - convert the redis overview dasbhoard to work with the new hierarchy First go to app catalog and import the app into your library folder as a new version with a new name. On the import screen make surce to use ```component=database db_system=redis``` as the filter. Now export the json of a dashbooard you want to fix up and let's get to work! #### fixing host to _sourcehost param metrics have a host value but logs have a _sourcehost. Earlier you might have noticed we tweaked the template to also send a _sourcehost value so we have a common host name across both. in the redis-overview we start with this ``` { "id": null, "name": "host", "displayName": "host", "defaultValue": "*", "sourceDefinition": { "variableSourceType": "MetadataVariableSourceDefinition", "filter": "metric=redis* db_system=redis component=database db_cluster={{db_cluster}}", "key": "host" }, "allowMultiSelect": false, "includeAllOption": true, "hideFromUI": false } ``` update this to: ``` { "id": null, "name": "_sourcehost", "displayName": "_sourcehost", "defaultValue": "*", "sourceDefinition": { "variableSourceType": "MetadataVariableSourceDefinition", "filter": "_sourcecategory=metrics/telegraf metric=redis*", "key": "_sourcehost" }, "allowMultiSelect": false, "includeAllOption": true, "hideFromUI": false } ``` #### fixing sourcehost in panels Right now the query panels would be something like this: ``` "queryString": " db_cluster={{db_cluster}} host={{host}} component=database db_system=redis metric=redis_keyspace_hitrate | avg by host", ``` do a global replace to replace in all panels ```host={{host}} ``` with ```_sourcehost={{_sourcehost}} ``` #### 7.1.1. <a name='fixupthestacklinking.'></a>fix up the stack linking. Say we want this overview to appear at the componet redis level in the tree we would update the ``` "topologyLabelMap": { "data": { "component": [ "database" ], "db_system": [ "redis" ] } }, ``` ### 7.2. <a name='Creatingaredis_sourcehostnodedashboard'></a>Creating a redis _sourcehost node dashboard We also need a host level redis home page dashboard for metrics. Let's pick the 'Redis - Cluster Operations' dash and convert that. Once again: - update the host to _sourcehost parameter block - do a global replace to replace in all panels ```host={{host}} ``` with ```_sourcehost={{_sourcehost}} ``` this time stack link to the specific lowerlevel of the tree for any sourcehost. ``` "topologyLabelMap": { "data": { "component": [ "database" ], "db_system": [ "redis" ], "_sourcehost": [ "*" ] } }, ```
Java
UTF-8
607
1.570313
2
[ "MIT" ]
permissive
package com.springboot.demo.shiro_redis_token.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.springboot.demo.shiro_redis_token.entity.RolePermission; import com.springboot.demo.shiro_redis_token.mapper.RolePermissionMapper; import com.springboot.demo.shiro_redis_token.service.RolePermissionService; import org.springframework.stereotype.Service; /** * @Author: zjhan * @Date: 2021/6/9 10:59 * @Description: **/ @Service public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements RolePermissionService { }
Java
UTF-8
892
2.328125
2
[]
no_license
package com.tideseng.springbootquick._8_starter; import com.tideseng.format.starter.FormatTemplate; import com.tideseng.springbootquick.User; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.ComponentScan; @ComponentScan(basePackageClasses=User.class) // 引入其它包下的User类 @SpringBootApplication public class StarterMain { public static void main(String[] args) { ConfigurableApplicationContext applicationContext = SpringApplication.run(StarterMain.class, args); FormatTemplate formatTemplate = applicationContext.getBean(FormatTemplate.class); User user = applicationContext.getBean(User.class); System.out.println(formatTemplate.doFormat(user)); } }
Python
UTF-8
729
3.96875
4
[]
no_license
from math import factorial """ Going from the top left vertex to another, counting how many paths exist, I noticed it resembled a Pascal's triangle in the form 1 1 1 1 1 1 1 1 2 3 4 5 6 1 3 6 10 15 1 4 10 20 1 5 15 1 6 1 The bottom right vertex is at the level 2n where n is numbers of rows and columns in the nxn grid """ def binomial_coeficient(n, k): """ n over k :return: """ return int(factorial(n)/(factorial(k)*factorial(n-k))) def lattice_paths(grid_size): n = grid_size * 2 max_value = 0 for k in range(n+1): max_value = max(binomial_coeficient(n, k), max_value) return max_value def solution(): print(lattice_paths(20))
Shell
UTF-8
420
2.984375
3
[ "Unlicense" ]
permissive
#!/usr/bin/env bats RHOST="$(fxy rhost | cut -d' ' -f 4)" @test "fxy ping 1" { # save rhost RHOST="$(fxy rhost | cut -d' ' -f 4)" build/fxy r 127.0.0.1 result="$(build/fxy ping 1)" # restore previous rhost build/fxy r "$RHOST" [[ "$result" =~ "1 packets transmitted" ]] } @test "fxy ping 123invalid" { result="$(build/fxy ping 123invalid)" [[ "$result" =~ "Not a number!" ]] }
JavaScript
UTF-8
1,141
2.84375
3
[]
no_license
var env = process.env.NODE_ENV || 'development'; //Note that these statements are only for local environments : 'development' and 'test' //Heroku environment has PORT and MONGODB_URI set automatically, although we have to provide it with JWT_SECRET through command line //heroku config//heroku config:set JWT_SECRET=erjg88902jmUBF8HUggHQUPQRrtd020//heroku config:get JWT_SECRET if(env === 'development' || env === 'test'){ var config = require('./config.json'); //For referencing properties of an object, dot notation is replaced by [] notation when referencing a variable (env) //env is a variable -- it could take the value 'development' or 'test', and hence is under [] brackets. var envConfig = config[env]; //The Object.keys() method returns an array of a given object's keys. Object.keys(envConfig).forEach((key) => { process.env[key] = envConfig[key]; }); } // if(env === 'development'){ // process.env.PORT = 3000; // process.env.MONGODB_URI = 'mongodb://localhost:27017/TodoApplication'; // }else if (env === 'test') { // process.env.PORT = 3000; // process.env.MONGODB_URI = 'mongodb://127.0.0.1:27017/TodoApplicationTest'; // }
Python
UTF-8
2,546
2.703125
3
[]
no_license
# Standard imports import cv2 import numpy import constants from algos import algo1 low = constants.low_red high = constants.high_red def callback(val): n = cv2.getTrackbarPos('Image', 'Control') img1 = cv2.imread("../output/output" + str(8*n) + ".png") img2 = cv2.imread("../output/output" + str(8*n+1) + ".png") img3 = cv2.imread("../output/output" + str(8*n+3) + ".png") img8 = cv2.imread("../output/output" + str(8*n+7) + ".png") low = (cv2.getTrackbarPos('LowH', 'Control'), cv2.getTrackbarPos('LowS', 'Control'), cv2.getTrackbarPos('LowV', 'Control')) high = (cv2.getTrackbarPos('HighH', 'Control'), cv2.getTrackbarPos('HighS', 'Control'), cv2.getTrackbarPos('HighV', 'Control')) multiplier = cv2.getTrackbarPos('Mul', 'Control') / 2.0 (img1, blur1, center1) = algo1.run(img1, low, high, cv2.COLOR_BGR2HSV) blur1 = cv2.cvtColor(blur1, cv2.COLOR_GRAY2BGR) cv2.circle(img1, center1, 5, (0, 255, 0), 2); imgc1 = cv2.add(img1, blur1) (img2, blur2, center2) = algo1.run(img2, low, high, cv2.COLOR_BGR2HSV) blur2 = cv2.cvtColor(blur2, cv2.COLOR_GRAY2BGR) offset = [q-p for (p, q) in zip(center1, center2)] center3 = (multiplier*offset[0]+center2[0], multiplier*offset[1]+center2[1]) center3 = (int(center3[0]), int(center3[1])) cv2.circle(img2, center1, 5, (0, 255, 0), 2); cv2.circle(img2, center2, 5, (255, 150, 150), 2); cv2.circle(img2, center3, 5, (0, 255, 255), 2); imgc2 = cv2.add(img2, blur2) #cv2.circle(img3, center1, 5, (0, 255, 0), 2); #cv2.circle(img3, center2, 5, (255, 150, 150), 2); #cv2.circle(img3, center3, 5, (0, 255, 255), 2); imgc3 = cv2.add(img3, blur1, blur2) img = numpy.concatenate((imgc1, imgc2, imgc3, img8), axis=1) cv2.imshow("Control", img) #mouse.shoot(new_center, constants.screen, constants.window) cv2.namedWindow("Control") cv2.createTrackbar("Image", "Control", 1, 200, callback); #Hue (0 - 179) cv2.createTrackbar("Mul", "Control", 5, 20, callback); #Hue (0 - 179) #Create trackbars in "Control" window cv2.createTrackbar("LowH", "Control", low[0], 255, callback); #Hue (0 - 179) cv2.createTrackbar("HighH", "Control", high[0], 179, callback); cv2.createTrackbar("LowS", "Control", low[1], 254, callback); #Saturation (0 - 255) cv2.createTrackbar("HighS", "Control", high[1], 255, callback); cv2.createTrackbar("LowV", "Control", low[2], 254, callback);#Value (0 - 255) cv2.createTrackbar("HighV", "Control", high[2], 255, callback); callback(0) cv2.waitKey()
Python
UTF-8
161
3.140625
3
[]
no_license
def fib(n): if n <= 1: return n return fib(n-1) + fib(n-2) # Returns no. of ways to # reach sth stair def climbStairs(s): return fib(s + 1)
Markdown
UTF-8
817
2.984375
3
[]
no_license
Simple format for new item: * Year, Company or Product Name, Article title, The link to the article If there is a link to Hacker News, please add them at the end * Year, Company or Product Name, Article title, The link to the article, The link to Hacker New post If possible please use the official link/article of the company. In the commit subject, please use the simple format: `Year, Company/Product, Short title.` This is not a strict rule though. Using https://web.archive.org/ to have a snapshot of the original site is also a very good option. ## Notes The second field (`Company/Product Name`) is more about the subject in the article, not an object. For example, when an engineer `Mr. X` left a company `Y`, we would expect the new item as below ``` * 2020, Mr. X, Why I left company Y ```
Markdown
UTF-8
1,791
2.8125
3
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
--- languages: - csharp products: - power-platform - power-apps page_type: sample description: "This sample shows how to perform a bulk deletion of records that were previously exported from Microsoft Dataverse by using the Export to Excel option. [SOAP]" --- # Bulk delete exported records This sample shows how to perform a bulk deletion of records that were previously exported from Dynamics 365 by using the **Export to Excel** option. ## How to run this sample See [How to run samples](https://github.com/microsoft/PowerApps-Samples/blob/master/cds/README.md) for information about how to run this sample. ## What this sample does The `BulkDeleteRequest` message is intended to be used in a scenario where it contains data that is needed to create the bulk delete request. ## How this sample works In order to simulate the scenario described in [What this sample does](#what-this-sample-does), the sample will do the following: ### Setup 1. Checks for the current version of the org. 2. Query for a system user to send an email after bulk delete request operation completes. 3. The `BulkDeleteRequest` creates the bulk delete process and set the request properties. 4. The `CheckSuccess` method queries for the `BulkDeleteOperation` until it has been completed or until the designated time runs out. It then checks to see if the operation is complete. ### Demonstrate The `PerformBulkDeleteBackup` method performs the main ulk delete operation on inactive opportunities and activities to remove them from the system. ### Clean up Display an option to delete the sample data that is created in [Setup](#setup). The deletion is optional in case you want to examine the entities and data created by the sample. You can manually delete the records to achieve the same result.
JavaScript
UTF-8
6,309
3.359375
3
[]
no_license
function getForecastByID(cityId) { //const cityId = 5604473; const apiKey = "7947d641816320463b620644081ccc3f"; const cityForecastUrl = "https://api.openweathermap.org/data/2.5/weather?units=imperial&id=" + cityId + "&appid=" + apiKey; const cityFiveDayForecastUrl = "https://api.openweathermap.org/data/2.5/forecast?units=imperial&id=" + cityId + "&appid=" + apiKey; const list_of_days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] fetch(cityForecastUrl) .then((response) => response.json()) .then((jsObject) => { document.getElementById('currentCondition').innerHTML = jsObject.weather[0].main; document.getElementById('currentTemperature').innerHTML = Math.round(jsObject.main.temp); document.getElementById('currentHumidity').innerHTML = jsObject.main.humidity; document.getElementById('currentWindSpeed').innerHTML = Math.round(jsObject.wind.speed); let temperature = Math.round(jsObject.main.temp); let speed = Math.round(jsObject.wind.speed); let factor = windChill(temperature, speed); if ((temperature <= 50) && (speed > 3)) { document.getElementById("currentWindChill").innerHTML = factor + " ºF"; } else { document.getElementById("currentWindChill").innerHTML = "N/A"; } function windChill(t, s) { let f = 35.74 + 0.6215 * t - 35.75 * (s ** 0.16) + 0.4275 * t * (s ** 0.16); return Math.round(f); } }); fetch(cityFiveDayForecastUrl) .then((response) => response.json()) .then((jsObject) => { var forecast_div = document.getElementById('forecast'); for (let index = 0; index < jsObject.list.length; index++) { if (jsObject.list[index].dt_txt.substring(11) == "18:00:00") { let imagesrc = 'https://openweathermap.org/img/wn/' + jsObject.list[index].weather[0].icon + '@2x.png'; let date = new Date(jsObject.list[index].dt_txt); let day = date.getDay(); let day_container = document.createElement('div'); let day_name = document.createElement('p'); let day_icon = document.createElement('img'); let day_temp = document.createElement('p'); day_name.innerHTML = list_of_days[day]; day_icon.setAttribute('src', imagesrc); day_icon.setAttribute('alt', 'weather icon'); day_name.setAttribute('class', 'name-day'); day_temp.setAttribute('class', 'day-temperature'); day_temp.innerHTML = Math.round(jsObject.list[index].main.temp) + '&deg; F'; day_container.appendChild(day_name); day_container.appendChild(day_icon); day_container.appendChild(day_temp); forecast_div.appendChild(day_container); } } }); } function getForecastByCoordinates(lat, lon) { //const cityId = 5604473; const apiKey = "7947d641816320463b620644081ccc3f"; const cityForecastUrl = "https://api.openweathermap.org/data/2.5/weather?units=imperial&appid=" + apiKey + "&lat=" + lat + "&lon=" + lon; const cityFiveDayForecastUrl = "https://api.openweathermap.org/data/2.5/forecast?units=imperial&appid=" + apiKey + "&lat=" + lat + "&lon=" + lon; const list_of_days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] fetch(cityForecastUrl) .then((response) => response.json()) .then((jsObject) => { document.getElementById('currentCondition').innerHTML = jsObject.weather[0].main; document.getElementById('currentTemperature').innerHTML = Math.round(jsObject.main.temp); document.getElementById('currentHumidity').innerHTML = jsObject.main.humidity; document.getElementById('currentWindSpeed').innerHTML = Math.round(jsObject.wind.speed); let temperature = Math.round(jsObject.main.temp); let speed = Math.round(jsObject.wind.speed); let factor = windChill(temperature, speed); if ((temperature <= 50) && (speed > 3)) { document.getElementById("currentWindChill").innerHTML = factor + " ºF"; } else { document.getElementById("currentWindChill").innerHTML = "N/A"; } function windChill(t, s) { let f = 35.74 + 0.6215 * t - 35.75 * (s ** 0.16) + 0.4275 * t * (s ** 0.16); return Math.round(f); } }); fetch(cityFiveDayForecastUrl) .then((response) => response.json()) .then((jsObject) => { var forecast_div = document.getElementById('forecast'); for (let index = 0; index < jsObject.list.length; index++) { if (jsObject.list[index].dt_txt.substring(11) == "18:00:00") { let imagesrc = 'https://openweathermap.org/img/wn/' + jsObject.list[index].weather[0].icon + '@2x.png'; let date = new Date(jsObject.list[index].dt_txt); let day = date.getDay(); let day_container = document.createElement('div'); let day_name = document.createElement('p'); let day_icon = document.createElement('img'); let day_temp = document.createElement('p'); day_name.innerHTML = list_of_days[day]; day_icon.setAttribute('src', imagesrc); day_icon.setAttribute('alt', 'weather icon'); day_name.setAttribute('class', 'name-day'); day_temp.setAttribute('class', 'day-temperature'); day_temp.innerHTML = Math.round(jsObject.list[index].main.temp) + '&deg; F'; day_container.appendChild(day_name); day_container.appendChild(day_icon); day_container.appendChild(day_temp); forecast_div.appendChild(day_container); } } }); }
JavaScript
UTF-8
2,184
2.546875
3
[]
no_license
// const initState = { // count:0, // loading:false, // messages:[] // }; const initState = { messages:null, //这个是临时传送的消息 currentChatter:null, unReadCount:0, cacheMessages:{}, //缓存初始信息,用户不用每次加载,大于1000则清空 cacheMessagesCount:{} }; const reducer = (state=initState,action)=>{ switch (action.type){ case 'RECEIVE_MESSAGE_INTIME': return {...state,messages:action.payload,unReadCount:state.unReadCount+1}; case 'RECEIVE_MESSAGE_INTIME_NOUNREAD': return {...state,messages:action.payload}; case 'CLEAR_UNREAD': return {...state,unReadCount:0}; case 'READ_SPECIAL_MESSAGE': return {...state,messages:null}; case 'SET_CHATTER': return {...state,currentChatter:action.payload}; case 'CLEAR_CHATTER': return {...state,currentChatter:null}; case 'SET_CACHE_MESSAGES': if(action.payload.ifClear){ const newCacheMessages = delete state.cacheMessages[Object.keys(state.cacheMessages)[0]]; const newCacheMessagesCount = delete state.cacheMessagesCount[Object.keys(state.cacheMessagesCount)[0]]; return {...state,cacheMessages:{...newCacheMessages,[action.payload.sender]:action.payload.messages},cacheMessagesCount:{...newCacheMessagesCount,[action.payload.sender]:action.payload.count}} } else { return {...state,cacheMessages:{...state.cacheMessages,[action.payload.sender]:action.payload.messages},cacheMessagesCount:{...state.cacheMessagesCount,[action.payload.sender]:action.payload.count}} } // case 'SEND_MESSAGE': // return {...state,messages:[...state.messages,action.payload],count:state.count+1}; // case 'LOADING_MORE': // return {...state,loading:action.loading}; // case 'GET_HISTORY_MESSAGE': // return {...state,messages:[...action.payload.data,...state.messages],count:state.count+action.payload.count,loading:false}; default: return state; } }; export default reducer;
Markdown
UTF-8
611
2.90625
3
[]
no_license
##多币种货币实例 测试驱动开发 需要在WyCash系统创建多币种对象,生成多币种报表 单币种 | 股票 | 数量 | 股价 |总计 | | ------ | ------ | ------ | ------ | | IBM | 1000 | 25 | 25000 | | GE | 400 | 100 | 40000 | | | | 总计 | 65000 | 美元、瑞郎 | 股票 | 数量 | 股价 |总计 | | ------ | ------ | ------ | ------ | | IBM | 1000 | 25USD(美元) | 25000 USD(美元)| | Novartis | 400 | 150CHF(瑞郎) | 60000CHF(瑞郎) | | | | 总计 | 65000USD (美元)| 汇率 |主币 | 兑换币种 | 汇率 | | ------ | ------ | ------ | | CHF | USD | 1.5|
Java
UTF-8
887
3.171875
3
[]
no_license
package cars; import java.util.ArrayList; public class Car { private String brand; private String model; private short year; private ArrayList<Part> parts = new ArrayList<Part>(); public Car(String brand, String model, short year) { setBrand(brand); setModel(model); setYear(year); } public String getBrand() { return brand; } public void setBrand(String brand) { if(brand != null) this.brand = brand; } @Override public String toString() { return "Car [brand=" + brand + ", model=" + model + ", year=" + year+"]"; } public String getModel() { return model; } public void setModel(String model) { if(model != null) this.model = model; } public short getYear() { return year; } public void setYear(short year) { if(year > 1900 && year < 2015 ) this.year = year; } }
Java
UTF-8
4,051
2.875
3
[]
no_license
package edu.wm.cs.cs301.amazebytheochambers.gui; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.SeekBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import edu.wm.cs.cs301.amazebytheochambers.R; // Arrow shaped buttons taken from - https://looksok.wordpress.com/2013/08/24/android-triangle-arrow-defined-as-an-xml-shape/ /** * First State - AMazeActivity * Here is the title screen of the application * We initiate a maze_builder,seekbar,textview,skill level, driver, and room. * When calling create, we instantiate the seekBar to receive a skill input from the user (that one can slide). * We then create two different buttons, one to explore the maze, one to revisit a previous maze state. * For now, the revisit button will have the same function as the explorer. * When the user clicks on explore, we pass the strings and information received from the spinners to the next activity. * We then go to the generating state. */ public class AMazeActivity extends AppCompatActivity { String maze_builder; SeekBar seekBar; TextView textView; int skill_level; String driver; String room; /** * We take in the initial state, and set the content view to the title screen. * We collect the desired skill level and set the corresponding textview to show the users skill level. * @param savedInstanceState */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.amaze_activity); textView = (TextView) findViewById(R.id.MazeSkillLeveltext); seekBar = (SeekBar)findViewById(R.id.seekBar); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { textView.setText("Skill Level " + String.valueOf(progress)); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } /** * Here we create a method for the explorer button to use (and for now the revisit button). * We use Log.v to ensure we have the right information passed in the method. * We then create a new intent and add the users inputs to the intent. * The next activity is generating. * @param view */ public void explore_click(View view) { Spinner mySpinner = (Spinner) findViewById(R.id.builder_spinner); Spinner spinner2 = (Spinner) findViewById(R.id.driver_spinner); Spinner spinner3 = (Spinner) findViewById(R.id.room_spinner); maze_builder = mySpinner.getSelectedItem().toString(); skill_level = seekBar.getProgress(); driver = spinner2.getSelectedItem().toString(); room = spinner3.getSelectedItem().toString(); Log.v("maze_generator",maze_builder); Log.v("skill_level",String.valueOf(skill_level)); Log.v("driver",driver); Log.v("room",room); Intent intent = new Intent(AMazeActivity.this,Generating.class); intent.putExtra("maze_builder",maze_builder); intent.putExtra("skill_level",skill_level); intent.putExtra("driver",driver); intent.putExtra("room",room); startActivity(intent); } /** * This method is used to skip to the end if desired. Currently no button for this operation as I use it later. * @param view */ public void go_finish(View view) { Intent intent = new Intent(this, FinishActivity.class); Toast.makeText(this, "skipped to end", Toast.LENGTH_SHORT).show(); startActivity(intent); } }
TypeScript
UTF-8
742
2.90625
3
[]
no_license
// declare var $: any import { PI, add } from './math'; import axios from 'axios'; console.log(PI); let sum:number = add(12, 24); console.log(sum); type ServerOutput = { exchange: string, value: number }; $().ready(() => { $('#sensexbutton').on("click", () => { axios .get<ServerOutput>("/sensex") .then(response => { let { exchange, value } = response.data; let message = `Exchange: ${exchange} - Price: ${value}`; $("#message").text(message); }); }); $('#randombutton').on("click", () => { let randomNum: number = Math.random() * 100; console.log(randomNum); $('#randomOutput').text(randomNum); }); });
Python
UTF-8
489
3.984375
4
[ "MIT" ]
permissive
import random x = random.randint(0, 2) # Version 1: # 1. Player one input: rock | paper | scissors # 2. Player two input: rock | paper | scissors # rock vs paper: paper # scissors vs rock: rock # scissors vs paper: paper # Who is the winner? Player 1 or Player 2 Version 2: rock Play against the computer Enter Input: rock | paper | scissors Take Computer Input: randint rock vs paper: paper scissors vs rock: rock scissors vs paper: paper Who is the winner? Player or Computer
Java
UTF-8
1,127
2.453125
2
[]
no_license
/** * <pre> * 1. 패키지명 : config.security3_1 * 2. 타입명 : MUser.java * 3. 작성일 : 2017. 12. 16. 오후 7:39:42 * 4. 저자 : 최준호 * * </pre> * */ package config.security_sample_3_1; import java.util.Collection; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.User; public class MUser extends User{ private boolean active; /** * @param username * @param password * @param enabled * @param accountNonExpired * @param credentialsNonExpired * @param accountNonLocked * @param authorities */ public MUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) { super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); } public boolean getActive() { return active; } public void setActive(boolean active) { this.active = active; } /** * @return */ public Object getRoles() { return null; } }
C++
UTF-8
2,142
2.703125
3
[]
no_license
//#include <opencv2/core.hpp> //#include <opencv2/imgcodecs.hpp> //#include <opencv2/highgui.hpp> #include "opencv2/opencv.hpp" #include <iostream> #include <string> using namespace cv; using namespace std; int main(int argc, char** argv) { //Windows Environment, OPENCV_OPENCL_DEVICE="Intel:GPU:0" /* //Check devices ocl::setUseOpenCL(true); if (!ocl::haveOpenCL()) { cout << "OpenCL is not available..." << endl; //return; } cv::ocl::Context context; if (!context.create(cv::ocl::Device::TYPE_GPU)) { cout << "Failed creating the context..." << endl; //return; } cout << context.ndevices() << " GPU devices are detected." << endl; //This bit provides an overview of the OpenCL devices you have in your computer for (int i = 0; i < context.ndevices(); i++) { cv::ocl::Device device = context.device(i); cout << "name: " << device.name() << endl; cout << "available: " << device.available() << endl; cout << "imageSupport: " << device.imageSupport() << endl; cout << "OpenCL_C_Version: " << device.OpenCL_C_Version() << endl; cout << endl; } //set device cv::ocl::Device(context.device(1)); */ //main Mat image, frame, edges; float e1, e2, time; String imageName; //load image if (argc > 1) imageName = argv[1]; else imageName = "lena.jpg"; // by default image = imread(imageName, IMREAD_COLOR); // Read the file if (image.empty()) // Check for invalid input { cout << "Could not open or find the image" << std::endl; return -1; } //Processing e1 = getTickCount(); cvtColor(image, edges, COLOR_BGR2GRAY); GaussianBlur(edges, edges, Size(7, 7), 1.5, 1.5); Canny(edges, edges, 0, 30, 3); e2 = getTickCount(); time = (e2 - e1) / getTickFrequency(); cout << "Elapsed time: " << time << " seconds" << std::endl; //Display namedWindow("edges", WINDOW_AUTOSIZE); // Create a window for display. imshow("edges", edges); // Show our image inside it. //wait waitKey(0); // Wait for a keystroke in the window return 0; }
Swift
UTF-8
307
2.65625
3
[]
no_license
// // Books.swift // BooksApp // // Created by 市村健太 on 2018/06/01. // Copyright © 2018年 GeekSalon. All rights reserved. // import UIKit struct Book { var title: String var imagePath: String? var author: String? init(title: String) { self.title = title } }
Markdown
UTF-8
1,669
3.25
3
[]
no_license
# liri-node-app (LIRI Bot) ### Overview LIRI Bot is a command line application using Node.js and several modules installed using NPM. [![Liri Bot](http://img.youtube.com/vi/k4QeRQAnSho/0.jpg)](https://www.youtube.com/watch?v=k4QeRQAnSho) 1. LIRI was created to perform searches: Bands in Town for concerts, and OMDB for movies, Spotify for song tracks 2. The application uses the `axios` package to connect to the various APIs, as well as other modules for various tasks: * [Node-Spotify-API](https://www.npmjs.com/package/node-spotify-api) * [Axios](https://www.npmjs.com/package/axios) * [Bands In Town API](http://www.artists.bandsintown.com/bandsintown-api) * [Moment](https://www.npmjs.com/package/moment) * [DotEnv](https://www.npmjs.com/package/dotenv) ### The instructions are as follows: 1. `node liri.js concert-this <artist/band name here>` - This will return: * Name of the venue * Venue location * Date of the Event 2. `node liri.js spotify-this-song '<song name here>'` - This will return: * Artist(s) * Song Name * A preview link of the son * The album * If no song is provided the default is "The Sign" by Ace of Base. 3. `node liri.js movie-this '<movie name here>'` - This will return: * Title. * Year of release. * IMDB Rating. * Rotten Tomatoes Rating. * Country where the movie was produced. * Language of the movie. * Plot of the movie. * Actors in the movie. * If a movie isn't provided, a default movie, 'Mr. Nobody', will be used. 4. `node liri.js do-what-it-says` * LIRI use the commands listed in random.txt and then call one of LIRI's functions.
Python
UTF-8
2,066
3.9375
4
[]
no_license
# !/usr/bin/python # -*- coding: utf-8 -*- # author : Tao Qitian # email : taoqt@mail2.sysu.edu.cn # datetime : 2021/3/22 23:19 # filename : solution.py # description : LC 300 最长递增子序列 class Solution: def lengthOfLIS(self, nums: List[int]) -> int: """ 动态规划 """ n = len(nums) # 假设 dp[i] 为 nums[i] 为结尾的最长递增子序列的长度 # 初始化子序列长度为 1 dp = [1] * len(nums) for i in range(n): for j in range(i): # dp[j] 是以 nums[j] 为结尾的最长递增子序列的长度,其中 i < j # 若 nums [i] 严格大于 nums[j],长度加一 if nums[j] < nums[i]: # 这里注意要取到 i 位置的最大值,满足状态的定义 dp[i] = max(dp[j] + 1, dp[i]) # 以最后的元素作为结尾的子序列不一定是最长,需选出最大值 return max(dp) def lengthOfLISGreedy(self, nums: List[int]) -> int: """ 贪心 + 二分查找 """ n = len(nums) if n < 2: return 1 # 创建数组保存最长递增子序列 array = [nums[0]] for num in nums[1:]: # 如果 num 严格大于数组中的元素,那么插到最后 if num > array[-1]: array.append(num) continue # 这里二分查找+插入的操作非常巧妙 # 用 num 覆盖掉数组中比 num 大但最小的元素,让后续元素有更大可能加入到递增子序列中 # 一旦覆盖,有可能跟真实的最长递增子序列不同,但长度一致 # 比如 [10, 9, 2, 5, 7, 3] => array = [2, 3, 7] left, right = 0, len(array) - 1 while left < right: mid = left + (right - left) // 2 if array[mid] < num: left = mid + 1 else: right = mid array[left] = num return len(array)
PHP
UTF-8
401
2.53125
3
[]
no_license
<?php namespace user; include_once('user/Authentication.php'); include_once('user/User.php'); $auth = new Authentication(); $auth->prepare($_POST); $userexits = $auth->isUserExisted(); if (!$userexits){ $user = new \user\User(); $user->prepare($_POST); $user->insertNewUserIntoDB(); }else{ $json['success'] = 0; $json['message'] = 'user exists'; echo json_encode($json); } ?>
Python
UTF-8
5,516
2.578125
3
[]
no_license
''' # Author: Tamara Ouspenskaia # Date: 01/14/2020 # Objective: This script calculates the sequencing coverage at variant sites ''' # This script requires: <br> # - a BAM file of aligned reads # - the .annot file generated by the variant_to_protein.sh script # - the analysis.tab file generated by the variant_analysis.sh script # # # The output of this script is: <br> # - Read coverage at the variant # - Mean and median coverage at the variant +/- 20 region # - Coverage and identity of the WT and the mutant alleles import argparse import pysam from collections import Counter import statistics import pandas as pd import numpy as np parser = argparse.ArgumentParser() #Inputs parser.add_argument("--bam", required = True, help = "Path to BAM file with aligned reads") parser.add_argument("--mut_annot", required = True, help = "Path to annot file generated by variant_to_protein script") parser.add_argument("--analysis_tab", required = True, help = "Path to analysis.tab file genereated by variant_analysis script") #Outputs parser.add_argument("--read_counts", required = True, help = "Path to the output file of read counts per SNV") parser.add_argument("--over3_all", required = True, help = "Path to output file with number of ORFs per type with at least 3 reads at SNV") parser.add_argument("--over3_pass", required = True, help = "Path to output file with number of ORFs per type with at least 3 reads at SNVs that PASS filter") args = parser.parse_args() print("Starting the snv_coverage script") #Load inputs: bam = pysam.AlignmentFile(args.bam, "rb" ) annot = pd.read_csv(args.mut_annot, header=0, sep='\t') analysis_tab = pd.read_csv(args.analysis_tab, header=0, sep='\t') print("All inputs are loaded") #Get read counts across the SNV locus def variant_metrics(row): surround_cov = [] all_pos_counts = [] variant_nt = [] for pileupcolumn in bam.pileup(str(row['mut_chr']), row['mut_location']-20, row['mut_location']+20, stepper='nofilter', truncate=True): surround_cov.append(pileupcolumn.n) if pileupcolumn.pos == row['mut_location']-1: row['variant_cov'] = pileupcolumn.n for pileupread in pileupcolumn.pileups: if not pileupread.is_del and not pileupread.is_refskip: # query position is None if is_del or is_refskip is set. variant_nt.append(pileupread.alignment.query_sequence[pileupread.query_position]) row['variant_nt_counts'] = dict(Counter(variant_nt)) if pileupcolumn.pos != row['mut_location']-1: pass #index = pileupcolumn.n #counter = 0 #nt = [] #for pileupread in pileupcolumn.pileups: #if not pileupread.is_del and not pileupread.is_refskip: # query position is None if is_del or is_refskip is set. #counter += 1 #nt.append(pileupread.alignment.query_sequence[pileupread.query_position]) #nt_counts = dict(Counter(nt)) #if counter == index: #all_pos_counts.append(nt_counts) #else: #continue if not surround_cov: row['median_surround_cov'] = 0 row['mean_surround_cov'] = 0 else: row['median_surround_cov'] = statistics.median(surround_cov) row['mean_surround_cov'] = statistics.mean(surround_cov) return(row) # Extract the # of reads supporting wt vs. mut: def count_reads(row): if isinstance(row['variant_nt_counts'], dict): if row['wt'] in row['variant_nt_counts']: row['wt_cov'] = row['variant_nt_counts'][row['wt']] else: row['wt_cov'] = 0 if row['mut'] in row['variant_nt_counts']: row['mut_cov'] = row['variant_nt_counts'][row['mut']] else: row['mut_cov'] = 0 else: row['wt_cov'] = 0 row['mut_cov'] = 0 return row annot_out = annot.apply(variant_metrics, axis=1) print('BAM file is processed') annot_out_count = annot_out.apply(count_reads, axis=1) print('Variant coverage is calculated') count_subset = annot_out_count[['ORF_ID', 'mean_surround_cov', 'median_surround_cov', 'mut', 'trans_strand', 'variant_ORF_id', 'variant_cov', 'variant_id', 'variant_nt_counts', 'variant_qc', 'wt', 'wt_cov', 'mut_cov']] annot_keep = analysis_tab[['variant_ORF_id', 'ORF_type', 'header', 'mut_len', 'mut_seq', 'wt_len', 'wt_seq']] merged = annot_keep.merge(count_subset, on='variant_ORF_id', how='left') merged = merged.drop_duplicates(subset='mut_seq') merged[['ORF_ID', 'mean_surround_cov', 'median_surround_cov', 'mut', 'trans_strand', 'variant_ORF_id', 'variant_cov', 'variant_id', 'variant_nt_counts', 'variant_qc', 'wt', 'wt_cov', 'mut_cov', 'ORF_type', 'header','mut_len', 'wt_len']].to_csv(args.read_counts, header=True, index=False, sep='\t') # For SNVs supported by at least 3 reads, get the # of ORF_types. Do it for all and for PASS filter. over3_snvs = merged[(merged['mut_cov'] > 3) & (merged['mut_cov']/merged['mut_cov'] > 0.1)] over3_snvs.groupby('ORF_type').count()['variant_ORF_id'].to_csv(args.over3_all, sep='\t', header=None, index=True) over3_snvs_pass = over3_snvs[over3_snvs['variant_qc'] == 'PASS'] over3_snvs_pass.groupby('ORF_type').count()['variant_ORF_id'].to_csv(args.over3_pass, sep='\t', header=None, index=True)
Java
UTF-8
4,116
2.015625
2
[]
no_license
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flume.sink.hdfs; import SequenceFile.CompressionType.BLOCK; import com.google.common.base.Charsets; import com.google.common.collect.Lists; import java.io.File; import java.io.FileInputStream; import java.nio.ByteBuffer; import java.nio.charset.CharsetDecoder; import java.util.List; import java.util.zip.GZIPInputStream; import org.apache.avro.file.DataFileStream; import org.apache.avro.generic.GenericRecord; import org.apache.avro.io.DatumReader; import org.apache.flume.Context; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.compress.CompressionCodecFactory; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestHDFSCompressedDataStream { private static final Logger logger = LoggerFactory.getLogger(TestHDFSCompressedDataStream.class); private File file; private String fileURI; private CompressionCodecFactory factory; // make sure the data makes it to disk if we sync() the data stream @Test public void testGzipDurability() throws Exception { Context context = new Context(); HDFSCompressedDataStream writer = new HDFSCompressedDataStream(); writer.configure(context); writer.open(fileURI, factory.getCodec(new Path(fileURI)), BLOCK); String[] bodies = new String[]{ "yarf!" }; writeBodies(writer, bodies); byte[] buf = new byte[256]; GZIPInputStream cmpIn = new GZIPInputStream(new FileInputStream(file)); int len = cmpIn.read(buf); String result = new String(buf, 0, len, Charsets.UTF_8); result = result.trim();// BodyTextEventSerializer adds a newline Assert.assertEquals("input and output must match", bodies[0], result); } @Test public void testGzipDurabilityWithSerializer() throws Exception { Context context = new Context(); context.put("serializer", "AVRO_EVENT"); HDFSCompressedDataStream writer = new HDFSCompressedDataStream(); writer.configure(context); writer.open(fileURI, factory.getCodec(new Path(fileURI)), BLOCK); String[] bodies = new String[]{ "yarf!", "yarfing!" }; writeBodies(writer, bodies); int found = 0; int expected = bodies.length; List<String> expectedBodies = Lists.newArrayList(bodies); GZIPInputStream cmpIn = new GZIPInputStream(new FileInputStream(file)); DatumReader<GenericRecord> reader = new org.apache.avro.generic.GenericDatumReader<GenericRecord>(); DataFileStream<GenericRecord> avroStream = new DataFileStream<GenericRecord>(cmpIn, reader); GenericRecord record = new org.apache.avro.generic.GenericData.Record(avroStream.getSchema()); while (avroStream.hasNext()) { avroStream.next(record); CharsetDecoder decoder = Charsets.UTF_8.newDecoder(); String bodyStr = decoder.decode(((ByteBuffer) (record.get("body")))).toString(); expectedBodies.remove(bodyStr); found++; } avroStream.close(); cmpIn.close(); Assert.assertTrue(((((((("Found = " + found) + ", Expected = ") + expected) + ", Left = ") + (expectedBodies.size())) + " ") + expectedBodies), ((expectedBodies.size()) == 0)); } }
Python
UTF-8
4,827
2.84375
3
[ "BSD-3-Clause" ]
permissive
from unittest import TestCase from nose.tools import assert_equal from nose.tools import assert_false try: from nose.tools import assert_count_equal except ImportError: from nose.tools import assert_items_equal as assert_count_equal from nose.tools import assert_true from nose.tools import raises import networkx as nx from networkx import is_eulerian, eulerian_circuit class TestIsEulerian(TestCase): def test_is_eulerian(self): assert_true(is_eulerian(nx.complete_graph(5))) assert_true(is_eulerian(nx.complete_graph(7))) assert_true(is_eulerian(nx.hypercube_graph(4))) assert_true(is_eulerian(nx.hypercube_graph(6))) assert_false(is_eulerian(nx.complete_graph(4))) assert_false(is_eulerian(nx.complete_graph(6))) assert_false(is_eulerian(nx.hypercube_graph(3))) assert_false(is_eulerian(nx.hypercube_graph(5))) assert_false(is_eulerian(nx.petersen_graph())) assert_false(is_eulerian(nx.path_graph(4))) def test_is_eulerian2(self): # not connected G = nx.Graph() G.add_nodes_from([1, 2, 3]) assert_false(is_eulerian(G)) # not strongly connected G = nx.DiGraph() G.add_nodes_from([1, 2, 3]) assert_false(is_eulerian(G)) G = nx.MultiDiGraph() G.add_edge(1, 2) G.add_edge(2, 3) G.add_edge(2, 3) G.add_edge(3, 1) assert_false(is_eulerian(G)) class TestEulerianCircuit(TestCase): def test_eulerian_circuit_cycle(self): G = nx.cycle_graph(4) edges = list(eulerian_circuit(G, source=0)) nodes = [u for u, v in edges] assert_equal(nodes, [0, 3, 2, 1]) assert_equal(edges, [(0, 3), (3, 2), (2, 1), (1, 0)]) edges = list(eulerian_circuit(G, source=1)) nodes = [u for u, v in edges] assert_equal(nodes, [1, 2, 3, 0]) assert_equal(edges, [(1, 2), (2, 3), (3, 0), (0, 1)]) G = nx.complete_graph(3) edges = list(eulerian_circuit(G, source=0)) nodes = [u for u, v in edges] assert_equal(nodes, [0, 2, 1]) assert_equal(edges, [(0, 2), (2, 1), (1, 0)]) edges = list(eulerian_circuit(G, source=1)) nodes = [u for u, v in edges] assert_equal(nodes, [1, 2, 0]) assert_equal(edges, [(1, 2), (2, 0), (0, 1)]) def test_eulerian_circuit_digraph(self): G = nx.DiGraph() nx.add_cycle(G, [0, 1, 2, 3]) edges = list(eulerian_circuit(G, source=0)) nodes = [u for u, v in edges] assert_equal(nodes, [0, 1, 2, 3]) assert_equal(edges, [(0, 1), (1, 2), (2, 3), (3, 0)]) edges = list(eulerian_circuit(G, source=1)) nodes = [u for u, v in edges] assert_equal(nodes, [1, 2, 3, 0]) assert_equal(edges, [(1, 2), (2, 3), (3, 0), (0, 1)]) def test_multigraph(self): G = nx.MultiGraph() nx.add_cycle(G, [0, 1, 2, 3]) G.add_edge(1, 2) G.add_edge(1, 2) edges = list(eulerian_circuit(G, source=0)) nodes = [u for u, v in edges] assert_equal(nodes, [0, 3, 2, 1, 2, 1]) assert_equal(edges, [(0, 3), (3, 2), (2, 1), (1, 2), (2, 1), (1, 0)]) def test_multigraph_with_keys(self): G = nx.MultiGraph() nx.add_cycle(G, [0, 1, 2, 3]) G.add_edge(1, 2) G.add_edge(1, 2) edges = list(eulerian_circuit(G, source=0, keys=True)) nodes = [u for u, v, k in edges] assert_equal(nodes, [0, 3, 2, 1, 2, 1]) assert_equal(edges[:2], [(0, 3, 0), (3, 2, 0)]) assert_count_equal(edges[2:5], [(2, 1, 0), (1, 2, 1), (2, 1, 2)]) assert_equal(edges[5:], [(1, 0, 0)]) @raises(nx.NetworkXError) def test_not_eulerian(self): f = list(eulerian_circuit(nx.complete_graph(4))) class TestEulerize(TestCase): @raises(nx.NetworkXError) def test_disconnected(self): G = nx.from_edgelist([(0, 1), (2, 3)]) nx.eulerize(G) @raises(nx.NetworkXPointlessConcept) def test_null_graph(self): nx.eulerize(nx.Graph()) @raises(nx.NetworkXPointlessConcept) def test_null_multigraph(self): nx.eulerize(nx.MultiGraph()) @raises(nx.NetworkXError) def test_on_empty_graph(self): nx.eulerize(nx.empty_graph(3)) def test_on_eulerian(self): G = nx.cycle_graph(3) H = nx.eulerize(G) assert_true(nx.is_isomorphic(G, H)) def test_on_eulerian_multigraph(self): G = nx.MultiGraph(nx.cycle_graph(3)) G.add_edge(0, 1) H = nx.eulerize(G) assert_true(nx.is_eulerian(H)) def test_on_complete_graph(self): G = nx.complete_graph(4) assert_true(nx.is_eulerian(nx.eulerize(G))) assert_true(nx.is_eulerian(nx.eulerize(nx.MultiGraph(G))))
JavaScript
UTF-8
735
2.875
3
[]
no_license
import { useEffect, useState } from 'react'; export default function useHexToRgb(hex) { const [rgb, setRgb] = useState(''); const [isError, setIsError] = useState(false); const hexToRgb = (hex) => { return hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i , (m, r, g, b) => '#' + r + r + g + g + b + b) .substring(1).match(/.{2}/g) .map(x => parseInt(x, 16)).toString() }; useEffect(() => { if (hex.length >= 7) { const pattern = new RegExp('^#[a-fA-F0-9]{6}$'); if (pattern.test(hex)) { setRgb(hexToRgb(hex)); setIsError(false) } else { setIsError(true); setRgb('') } } else { setRgb('') } }, [hex]) return {rgb, isError} }
C++
UTF-8
301
3.125
3
[]
no_license
#include "Tracing.h" #include <iostream> void sum(int& a, double& b); int main() { std::string str("Hello"); double num = 0.8932; int n = 8; doTrace(n + num) doTrace(str) sum(n,num); doTrace(n) doTrace(num) return 0; } void sum(int& a, double& b) { a = 9; b = 0.9999; doTrace(a + b) }
Java
UTF-8
639
3.453125
3
[]
no_license
package fr.diginamic.operations; public class CalculMoyenne { double[] moyenne; public CalculMoyenne(double[] moyenne) { this.moyenne = moyenne; } @Override public String toString() { return "a pour moyenne :"+ this.calcul(); } public float calcul(){ System.out.println("Le tableau :"); for (double nombre:moyenne) { System.out.print("[ "+nombre + " ]"); } int somme = 0; for(int i = 0; i < moyenne.length; i++){ somme += moyenne[i]; } float moy = (float) somme / moyenne.length; return moy; } }
PHP
UTF-8
1,382
2.5625
3
[]
no_license
<?php require_once 'libraries/database.php'; require_once 'libraries/utils.php'; require_once 'libraries/security.php'; $task = $_GET['task']; switch($task){ case 'orderForm': showOrderForm(); break; case 'saveOrder': saveOrder(); break; case 'confirmOrder': showConfirmOrder(); break; } function showOrderForm() { display('views/order.phtml'); } function saveOrder() { // 2) Récupération des données dans le POST (envoi du formulaire) $lastName = $_POST['lastname']; $firstName = $_POST['firstname']; $phone = $_POST['phoneNumber']; $email = $_POST['email']; $address = $_POST['address']; $postalCode = $_POST['postalCode']; $city = $_POST['city']; $review = $_POST['review']; $id = addOrder($lastName, $firstName, $email, $phone, $address, $postalCode, $city, $review); // Pour chaque produit du panier ($_SESSION['panier']) // On veut insérer une ligne dans la table order_meal // [1, 2, 1, 3] foreach(getCart() as $mealId) { addMealToOrder($mealId, $id); } emptyCart(); redirect('order_confirm.php'); // Redirection vers page de remerciement : // redirect('orderController.php?task=confirmOrder'); } /* function showConfirmOrder() { require_once('views/remerciements.phtml'); }*/
C++
UTF-8
534
2.75
3
[]
no_license
#ifndef GEOMETRY_H #define GEOMETRY_H class PointArray { int size; Point *points; void resize( int size); public : PointArray(); PointArray( const Point pts[], const int size); PointArray( const PointArray &pv); ~PointArray(); void clear(); int getSize() const { return size;} void push_back( const Point &p); void insert( const int pos, const Point &p); void remove( const int pos); Point *get( const int pos); const Point *get( const int pos) const ; }; #endif // GEOMETRY_H
Java
UTF-8
299
3.03125
3
[]
no_license
package prog01; import java.util.Scanner; public class sumnum { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("enter value of n"); int n=sc.nextInt(); int sum=0; for(int i=1;i<=n ;i++) { sum+=i; } System.out.println(sum); sc.close(); } }
Markdown
UTF-8
6,651
2.828125
3
[]
no_license
# Authentication Management ## Check Username Authentication Information ### URI GET /auth_username ### Request Message None ### Response Message | Name | Type | Description | | :------------------- | :--------------- | :-------------------------------------- | | code | Integer | 0 | | data | Array of Objects | All authentication data | | data[].username | String | Login Username | | meta | Object | Paging information | | meta.page | Integer | Page number | | meta.limit | Integer | Number of data items displayed per page | | meta.count | Integer | Total number of data | ### Request Example ```bash $ curl -u app_id:app_secret -X GET {api}/auth_username ``` ### Response Example ```JSON { "meta": { "page": 1, "limit": 10, "count": 3 }, "data": [ { "username": "api_user2" }, { "username": "api_user1" }, { "username": "test" } ], "code": 0 } ``` ## Check the Authentication Information for the specified username ### URI GET /auth_username/{username} #### Parameter | Name | Type | Description | | :------------------- | :--------------- | :-------------------------------------- | | username | String | username | ### Request Message None ### Response Message | Name | Type | Description | | :------------------- | :--------------- | :-------------------------------------- | | code | Integer | 0 | | data | Array of Objects | All authentication data | | data[].username | String | Login Username | | data[].password | String | Use sha256 encrypted password | ### Request Example ```bash $ curl -u app_id:app_secret -X GET {api}/auth_username/user1 ``` ### Response Example ```JSON { "data": { "password": "7\\�ce8268d18e3ba8f5ffba3786b95f3f323e6d7f499ce9cb92f0fc9f54eb8e0316", "clientid": "user1" }, "code": 0 } ``` ## Create Username Authentication Information ### URI POST /auth_username ### Request Message | Name | Type | Description | | :------------------- | :--------------- | :-------------------------------------- | | username | String | Authenticated username | | password | String | Authenticated password | ### Response Message | Name | Type | Description | | :------------------- | :--------------- | :-------------------------------------- | | code | Integer | 0 | ### Request Example ```bash $ curl -u app_id:app_secret -X POST {api}/auth_username ``` ```JSON { "username": "user_test", "password": "password" } ``` ### Response Example ```JSON { "code": 0 } ``` ## Batch Create Username Authentication Information ### URI POST /auth_username ### Request Message | Name | Type | Description | | :------------------- | :--------------- | :-------------------------------------- | | [].username | String | Authenticated username | | [].password | String | Authenticated password | ### Response Message | Name | Type | Description | | :------------------- | :--------------- | :-------------------------------------- | | code | Integer | 0 | | data | Array of Objects | Create result, key means username, value means request result, ok means create successfully | ### Request Example ```bash $ curl -u app_id:app_secret -X POST {api}/auth_username ``` ```JSON [ { "username": "api_user1", "password": "password" }, { "username": "api_user2", "password": "password" } ] ``` ### Response Example ```JSON { "data": { "api_user1": "ok", "api_user2": "ok" }, "code": 0 } ``` ## Update the Username Authentication Password ### URI PUT /auth_username/{username} #### Parameter | Name | Type | Description | | :------------------- | :--------------- | :-------------------------------------- | | username | String | Updated username | ### Request Message | Name | Type | Description | | :------------------- | :--------------- | :-------------------------------------- | | password | String | Authentication password | ### Response Message | Name | Type | Description | | :------------------- | :--------------- | :-------------------------------------- | | code | Integer | 0 | ### Request Example ```bash $ curl -u app_id:app_secret -X PUT {api}/auth_username/api_user1 ``` ```JSON { "password": "password" } ``` ### Response Example ```JSON { "code": 0 } ``` ## Delete Username Authentication Information ### URI DELETE /auth_username/{username} #### Parameter | Name | Type | Description | | :------------------- | :--------------- | :-------------------------------------- | | username | String | Deleted username | ### Request Message None ### Response Message | Name | Type | Description | | :------------------- | :--------------- | :-------------------------------------- | | code | Integer | 0 | ### Request Example ```bash $ curl -u app_id:app_secret -X DELETE {api}/auth_username/api_user1 ``` ### Response Example ```JSON { "code": 0 } ```
JavaScript
UTF-8
5,482
2.625
3
[]
no_license
//TODO: Add pods for displaying images. //TODO: Look into AJAX calls. //TODO: Add lightbox viewer. $(document).ready(function(){ //Intial page rendering instructions $('.vline').height(0); //Retract animation duration (ms). var animationLength = 700; //Tracks tree depth during recursive calls of checkChildren var depth = 0; //Percentages for animating the wrapper bar appropriately, beginning from the centre of the vline that extends to it. var margins = { a:'6.55%', b:'23.8%', c:'41.17%', d:'58.55%', e:'75.8%', f:'93.17%', //i and j are for the master nodes position at columns two and seven respectively. i: '36.88%', j: '80.2%' }; //Terminal node click function to open photo/video pod. $('.terminal').click(function(){ }); //General click function for nodes that are not already active. $('.node').click(function(){ //Deactives node click function to prevent a new animation from starting before the current one is complete. $('.node').not('.terminal').css("pointer-events", "none"); //Parse id of new branch in preparation for animation $(this).addClass('active'); var nodeId = this.id; var extendDetails = parseId(nodeId); //Check for active tree branches and retract them before forming a new branch. //extend is the callback to extend branch once animation is complete checkSiblings(this, extendDetails); }); //Checking for active sibling branch function checkSiblings(clickedNode, extendDetails){ var hasActiveSibling = $(clickedNode).parent().siblings().children().hasClass('active'); if(hasActiveSibling){ var activeSiblingId = $(clickedNode).parent().siblings().children('.active').attr('id'); var siblingDetails = parseId(activeSiblingId); //Check if active sibling has active children checkChildren(activeSiblingId, siblingDetails, extendDetails); setTimeout(function(){extend(extendDetails);}, animationLength*depth); } else { extend(extendDetails); } //Restore click function. setTimeout(function(){$('.node').css("pointer-events", "auto");},1000+(animationLength*depth)); depth = 0; } //Check if an active node has active child function checkChildren(activeParentId, parentDetails, extendDetails){ //Sets target child var targetDetails = parseId(activeParentId); targetDetails[1] = parseInt(targetDetails[1])+1; //adding 1 to treeLevel targets children nodes. targetDetails[0] = targetDetails[1]+ 'a'; //updating coordinate at targetDetails[0] to reflect the new level. Default column target set to 'a'. var targetChild = "#n"+ targetDetails[0]; var hasActiveChild = $(targetChild).parent().parent().children().children().hasClass('active'); //Recursive flow to retract children branches before parent branches. if(hasActiveChild){ var activeChildId = $(targetChild).parent().parent().children().children('.active').attr('id'); var childDetails = parseId(activeChildId); var isTerminal = $('#'+activeChildId).hasClass('terminal'); //Terminal nodes have no children. if(isTerminal){ $("#"+activeChildId).removeClass('active'); retract(parentDetails); ++depth; return; } //If active and not terminal, check children of the new node. else{ checkChildren(activeChildId, childDetails, extendDetails); setTimeout(function(){retract(parentDetails);}, animationLength*depth); ++depth; return; } } //If no active children. else{ retract(parentDetails); ++depth; return; } } function extend(details){ branchOutAnimation("#l"+details[0],"#w"+details[1],".v"+details[1]); } function parseId(id){ var treeCoordinate = id.substring(1,3); //gets exact coordinate of the node: eg. 2c var treeLevel = id.substring(1,2); //gets only the level or row of the node in the tree: eg. 2 return [treeCoordinate,treeLevel]; } function retract(details) { retractAnimation("#l"+details[0],"#w"+details[1],".v"+details[1]); $('#n'+details[0]).removeClass('active'); } //Branching Out animation occurs over 1000 ms function branchOutAnimation(linker, wrapper, vline){ if ($(wrapper).hasClass('active') === false) { $(linker).addClass('active'); $(wrapper).addClass('active'); $(vline).addClass('active'); //Check if wrapper is already active or not, and adjust margin if latter. var treeCol = linker.substring(3,4); var wrapperPosition = margins[treeCol]; $(wrapper).css({"margin-left":wrapperPosition}); //Animation sequence $(linker).animate({height:"100%"}, 300); setTimeout(function(){$(wrapper).animate({"margin-left": "0", "width": "100%"}, 450);}, 300); setTimeout(function(){$(vline).animate({height:"100%"}, 250);}, 750); } } //Retracting animation occurs over 700 ms function retractAnimation(linker, wrapper, vline){ $(linker).removeClass('active'); $(wrapper).removeClass('active'); $(vline).removeClass('active'); var treeCol = linker.substring(3,4); var wrapperPosition = margins[treeCol]; $(vline).animate({height:"0%"}, 200); setTimeout(function(){$(wrapper).animate({"margin-left":wrapperPosition, "width": "0"}, 350);}, 200); setTimeout(function(){$(linker).animate({height:"0"}, 150);}, 550); } });
C++
UTF-8
1,143
3.75
4
[]
no_license
#include <iostream> #include <vector> #include <stack> using namespace std; vector<int> getNSL(vector<int> in) { stack<int> s; vector<int> out; for(auto v : in) { if(s.empty()) { out.push_back(-1); } else if(s.top() < v) { out.push_back(s.top()); } else { // we need to keep popping until stack is empty // OR we find a smaller element while(!s.empty() && s.top() >= v){ s.pop(); } // repeat above 2 steps since we woudl have landed in one of // them if(s.empty()) { out.push_back(-1); } else if(s.top() < v) { out.push_back(s.top()); } } s.push(v); } return out; } int main() { cout << "Print the next smaller element to the left" << endl; vector<int> in = {-5, 4, 3, 2 ,1}; //{1, 2, 3, 4, 5}; // {4, 1, 2, 5, 3}; vector<int> out = getNSL(in); for(auto v : in) cout << v << " " ; cout << endl; for(auto v : out) cout << v << " " ; cout << endl; return 0; }
Markdown
UTF-8
1,342
3.421875
3
[ "BSD-2-Clause" ]
permissive
In Flash all DisplayObjects share the the same stage. With dartflash you can use multiple layers of stages. The advantage with this approach is that you can add your DisplayObjects to different stages (and therefore display lists). You will get better performance as soon as you can suspend the render loop on one of those stages (eg. the background of a game). ### Details ### Use two canvas elements on top of each other. One for the background of your game, the other for the foreground. <div style="position: relative; "> <canvas id="bg" width="800" height="600" style="position: absolute"></canvas> <canvas id="fg" width="800" height="600" style="position: absolute"></canvas> </div> Now create two Stages out of those 2 canvas elements and set the "renderMode" property: var bg = new Stage(querySelector('#bg')); var fg = new Stage(querySelector('#fg'), color: Color.Transparent); bg.renderMode = StageRenderMode.STOP; fg.renderMode = StageRenderMode.AUTO; In this sample the render loop will NOT render the background. Only the foreground will be rendered on every frame. If you want to change the content of the background you just set the "renderMode" to ONCE and the render loop will render the background on the next frame - but just once :) stageBackground.renderMode = StageRenderMode.ONCE;
C
UTF-8
686
3.984375
4
[]
no_license
#include <stdio.h> #include <stdlib.h> void ary_copy(int a[], const int b[], int n); int main() { int num; int *x, *y; printf("要素数は:"); scanf("%d", &num); x = malloc(sizeof(int)); y = malloc(sizeof(int)); printf("%d個の整数を入力してください。\n", num); for (int i = 0; i < num; i++) { printf("x[%d]:", i); scanf("%d", &x[i]); } ary_copy(y, x, num); printf("yの配列の場合\n"); for (int i = 0; i < num; i++) { printf("y[%d]:%d\n", i, y[i]); } } void ary_copy(int a[], const int b[], int n) { for (int i = 0; i < n; i++) { a[i] = b[i]; } }
Python
UTF-8
118
3.09375
3
[]
no_license
import math def array_shift(arr, val): half = math.ceil( len(arr) / 2 ) return arr[:half] + [val] + arr[half:]
JavaScript
UTF-8
4,436
3.203125
3
[]
no_license
var minMaxFilterEditor = function (cell, onRendered, success, cancel, editorParams) { var end; var container = document.createElement("span"); var start = document.createElement("input"); start.setAttribute("type", "number"); start.setAttribute("placeholder", "Min"); start.setAttribute("min", 0); start.setAttribute("max", 100); start.style.padding = "4px"; start.style.width = "50%"; start.style.boxSizing = "border-box"; start.value = cell.getValue(); function buildValues() { success({ start: start.value, end: end.value, }); } function keypress(e) { if (e.keyCode == 13) { buildValues(); } if (e.keyCode == 27) { cancel(); } } end = start.cloneNode(); start.addEventListener("change", buildValues); start.addEventListener("blur", buildValues); start.addEventListener("keydown", keypress); end.addEventListener("change", buildValues); end.addEventListener("blur", buildValues); end.addEventListener("keydown", keypress); container.appendChild(start); container.appendChild(end); return container; } function minMaxFilterFunction(headerValue, rowValue, rowData, filterParams) { //headerValue - the value of the header filter element //rowValue - the value of the column in this row //rowData - the data for the row being filtered //filterParams - params object passed to the headerFilterFuncParams property if (rowValue) { if (headerValue.start != "") { if (headerValue.end != "") { return rowValue >= headerValue.start && rowValue <= headerValue.end; } else { return rowValue >= headerValue.start; } } else { if (headerValue.end != "") { return rowValue <= headerValue.end; } } } return false; } var dateEditor = function (cell, onRendered, success, cancel) { //cell - the cell component for the editable cell //onRendered - function to call when the editor has been rendered //success - function to call to pass the successfuly updated value to Tabulator //cancel - function to call to abort the edit and return to a normal cell //create and style input var cellValue = moment(cell.getValue(), "DD/MM/YYYY").format("YYYY-MM-DD"), input = document.createElement("input"); input.setAttribute("type", "date"); input.style.padding = "4px"; input.style.width = "100%"; input.style.boxSizing = "border-box"; input.value = cellValue; onRendered(function () { input.focus(); input.style.height = "100%"; }); function onChange() { if (input.value != cellValue) { success(moment(input.value, "YYYY-MM-DD").format("DD/MM/YYYY")); } else { cancel(); } } //submit new value on blur or change input.addEventListener("change", onChange); input.addEventListener("blur", onChange); //submit new value on enter input.addEventListener("keydown", function (e) { if (e.keyCode == 13) { onChange(); } if (e.keyCode == 27) { cancel(); } }); return input; }; //create autocomplete editor (example of using jquery code to create an editor) var autocompEditor = function (cell, onRendered, success, cancel) { //create and style input var input = $("<input type='text'/>"); //setup jquery autocomplete input.autocomplete({ source: ["United Kingdom", "Germany", "France", "USA", "Canada", "Russia", "India", "China", "South Korea", "Japan"] }); input.css({ "padding": "4px", "width": "100%", "box-sizing": "border-box", }) .val(cell.getValue()); onRendered(function () { input.focus(); input.css("height", "100%"); }); //submit new value on blur input.on("change blur", function (e) { if (input.val() != cell.getValue()) { success(input.val()); } else { cancel(); } }); //submit new value on enter input.on("keydown", function (e) { if (e.keyCode == 13) { success(input.val()); } if (e.keyCode == 27) { cancel(); } }); return input[0]; };
Java
UTF-8
792
2.078125
2
[]
no_license
package br.cin.ufpe.dass.matchers.core; /** * Created by diego on 08/03/17. */ public class PerformanceMetrics { private long executionTimeInMillis; private long memoryUsed; private long diskSpaceUsed; public long getExecutionTimeInMillis() { return executionTimeInMillis; } public void setExecutionTimeInMillis(long executionTimeInMillis) { this.executionTimeInMillis = executionTimeInMillis; } public long getMemoryUsed() { return memoryUsed; } public void setMemoryUsed(long memoryUsed) { this.memoryUsed = memoryUsed; } public long getDiskSpaceUsed() { return diskSpaceUsed; } public void setDiskSpaceUsed(long diskSpaceUsed) { this.diskSpaceUsed = diskSpaceUsed; } }
Java
UTF-8
910
1.789063
2
[]
no_license
/* * Decompiled with CFR 0_100. */ package com.google.android.gms.drive.metadata.internal; import android.os.Bundle; import com.google.android.gms.common.data.DataHolder; import com.google.android.gms.drive.metadata.a; public class f extends a<Integer> { public f(String string, int n) { super(string, n); } @Override protected void a(Bundle bundle, Integer n) { bundle.putInt(this.getName(), n); } @Override protected /* synthetic */ Object c(DataHolder dataHolder, int n, int n2) { return this.g(dataHolder, n, n2); } protected Integer g(DataHolder dataHolder, int n, int n2) { return dataHolder.b(this.getName(), n, n2); } @Override protected /* synthetic */ Object g(Bundle bundle) { return this.j(bundle); } protected Integer j(Bundle bundle) { return bundle.getInt(this.getName()); } }
Java
UTF-8
9,179
1.507813
2
[]
no_license
package com.google.android.gms.common.api; import android.app.Activity; import android.content.Context; import android.os.Handler; import android.os.Looper; import com.google.android.gms.c.f; import com.google.android.gms.c.g; import com.google.android.gms.common.api.a; import com.google.android.gms.common.api.a.C0065a; import com.google.android.gms.common.api.internal.al; import com.google.android.gms.common.api.internal.an; import com.google.android.gms.common.api.internal.av; import com.google.android.gms.common.api.internal.bg; import com.google.android.gms.common.api.internal.bi; import com.google.android.gms.common.api.internal.bk; import com.google.android.gms.common.api.internal.bo; import com.google.android.gms.common.api.internal.bt; import com.google.android.gms.common.api.internal.bx; import com.google.android.gms.common.api.internal.cb; import com.google.android.gms.common.api.internal.cl; import com.google.android.gms.common.api.internal.co; import com.google.android.gms.common.api.internal.cp; import com.google.android.gms.common.api.internal.cu; import com.google.android.gms.common.api.internal.h; import com.google.android.gms.common.internal.ap; public class e<O extends a.C0065a> { /* renamed from: a reason: collision with root package name */ protected final al f2738a; /* renamed from: b reason: collision with root package name */ private final Context f2739b; private final a<O> c; private final O d; private final cp<O> e; private final Looper f; private final int g; private final f h; private final bx i; public static class a { public static final a zzfmj = new r().zzagq(); public final bx zzfmk; public final Looper zzfml; private a(bx bxVar, Looper looper) { this.zzfmk = bxVar; this.zzfml = looper; } /* synthetic */ a(bx bxVar, Looper looper, byte b2) { this(bxVar, looper); } } public e(Activity activity, a<O> aVar, O o, a aVar2) { ap.checkNotNull(activity, "Null activity is not permitted."); ap.checkNotNull(aVar, "Api must not be null."); ap.checkNotNull(aVar2, "Settings must not be null; use Settings.DEFAULT_SETTINGS instead."); this.f2739b = activity.getApplicationContext(); this.c = aVar; this.d = o; this.f = aVar2.zzfml; this.e = cp.zza(this.c, this.d); this.h = new av(this); this.f2738a = al.zzcj(this.f2739b); this.g = this.f2738a.zzais(); this.i = aVar2.zzfmk; h.zza(activity, this.f2738a, this.e); this.f2738a.zza((e<?>) this); } @Deprecated public e(Activity activity, a<O> aVar, O o, bx bxVar) { this(activity, aVar, o, new r().zza(bxVar).zza(activity.getMainLooper()).zzagq()); } protected e(Context context, a<O> aVar, Looper looper) { ap.checkNotNull(context, "Null context is not permitted."); ap.checkNotNull(aVar, "Api must not be null."); ap.checkNotNull(looper, "Looper must not be null."); this.f2739b = context.getApplicationContext(); this.c = aVar; this.d = null; this.f = looper; this.e = cp.zzb(aVar); this.h = new av(this); this.f2738a = al.zzcj(this.f2739b); this.g = this.f2738a.zzais(); this.i = new co(); } @Deprecated public e(Context context, a<O> aVar, O o, Looper looper, bx bxVar) { this(context, aVar, (a.C0065a) null, new r().zza(looper).zza(bxVar).zzagq()); } public e(Context context, a<O> aVar, O o, a aVar2) { ap.checkNotNull(context, "Null context is not permitted."); ap.checkNotNull(aVar, "Api must not be null."); ap.checkNotNull(aVar2, "Settings must not be null; use Settings.DEFAULT_SETTINGS instead."); this.f2739b = context.getApplicationContext(); this.c = aVar; this.d = o; this.f = aVar2.zzfml; this.e = cp.zza(this.c, this.d); this.h = new av(this); this.f2738a = al.zzcj(this.f2739b); this.g = this.f2738a.zzais(); this.i = aVar2.zzfmk; this.f2738a.zza((e<?>) this); } @Deprecated public e(Context context, a<O> aVar, O o, bx bxVar) { this(context, aVar, o, new r().zza(bxVar).zzagq()); } private final <TResult, A extends a.c> f<TResult> a(int i2, cb<A, TResult> cbVar) { g gVar = new g(); this.f2738a.zza(this, i2, cbVar, gVar, this.i); return gVar.getTask(); } private final <A extends a.c, T extends cu<? extends m, A>> T a(int i2, T t) { t.zzahi(); this.f2738a.zza(this, i2, (cu<? extends m, a.c>) t); return t; } /* JADX WARNING: Removed duplicated region for block: B:11:0x0030 */ /* Code decompiled incorrectly, please refer to instructions dump. */ private final com.google.android.gms.common.internal.bm a() { /* r3 = this; com.google.android.gms.common.internal.bm r0 = new com.google.android.gms.common.internal.bm r0.<init>() O r1 = r3.d boolean r2 = r1 instanceof com.google.android.gms.common.api.a.C0065a.b if (r2 == 0) goto L_0x0018 com.google.android.gms.common.api.a$a$b r1 = (com.google.android.gms.common.api.a.C0065a.b) r1 com.google.android.gms.auth.api.signin.GoogleSignInAccount r1 = r1.getGoogleSignInAccount() if (r1 == 0) goto L_0x0018 android.accounts.Account r1 = r1.getAccount() goto L_0x0026 L_0x0018: O r1 = r3.d boolean r2 = r1 instanceof com.google.android.gms.common.api.a.C0065a.C0066a if (r2 == 0) goto L_0x0025 com.google.android.gms.common.api.a$a$a r1 = (com.google.android.gms.common.api.a.C0065a.C0066a) r1 android.accounts.Account r1 = r1.getAccount() goto L_0x0026 L_0x0025: r1 = 0 L_0x0026: com.google.android.gms.common.internal.bm r0 = r0.zze((android.accounts.Account) r1) O r1 = r3.d boolean r2 = r1 instanceof com.google.android.gms.common.api.a.C0065a.b if (r2 == 0) goto L_0x003d com.google.android.gms.common.api.a$a$b r1 = (com.google.android.gms.common.api.a.C0065a.b) r1 com.google.android.gms.auth.api.signin.GoogleSignInAccount r1 = r1.getGoogleSignInAccount() if (r1 == 0) goto L_0x003d java.util.Set r1 = r1.zzabb() goto L_0x0041 L_0x003d: java.util.Set r1 = java.util.Collections.emptySet() L_0x0041: com.google.android.gms.common.internal.bm r0 = r0.zze((java.util.Collection<com.google.android.gms.common.api.Scope>) r1) return r0 */ throw new UnsupportedOperationException("Method not decompiled: com.google.android.gms.common.api.e.a():com.google.android.gms.common.internal.bm"); } public final Context getApplicationContext() { return this.f2739b; } public final int getInstanceId() { return this.g; } public final Looper getLooper() { return this.f; } public final f<Boolean> zza(bi<?> biVar) { ap.checkNotNull(biVar, "Listener key cannot be null."); return this.f2738a.zza(this, biVar); } public final <A extends a.c, T extends bo<A, ?>, U extends cl<A, ?>> f<Void> zza(T t, U u) { ap.checkNotNull(t); ap.checkNotNull(u); ap.checkNotNull(t.zzajo(), "Listener has already been released."); ap.checkNotNull(u.zzajo(), "Listener has already been released."); ap.checkArgument(t.zzajo().equals(u.zzajo()), "Listener registration and unregistration methods must be constructed with the same ListenerHolder."); return this.f2738a.zza(this, (bo<a.c, ?>) t, (cl<a.c, ?>) u); } public final <TResult, A extends a.c> f<TResult> zza(cb<A, TResult> cbVar) { return a(0, cbVar); } public a.f zza(Looper looper, an<O> anVar) { return this.c.zzage().zza(this.f2739b, looper, a().zzgf(this.f2739b.getPackageName()).zzgg(this.f2739b.getClass().getName()).zzald(), this.d, anVar, anVar); } public final <L> bg<L> zza(L l, String str) { return bk.zzb(l, this.f, str); } public bt zza(Context context, Handler handler) { return new bt(context, handler, a().zzald()); } public final <A extends a.c, T extends cu<? extends m, A>> T zza(T t) { return a(0, t); } public final a<O> zzagl() { return this.c; } public final O zzagm() { return this.d; } public final cp<O> zzagn() { return this.e; } public final f zzago() { return this.h; } public final <TResult, A extends a.c> f<TResult> zzb(cb<A, TResult> cbVar) { return a(1, cbVar); } public final <A extends a.c, T extends cu<? extends m, A>> T zzb(T t) { return a(1, t); } public final <A extends a.c, T extends cu<? extends m, A>> T zzc(T t) { return a(2, t); } }
Markdown
UTF-8
5,343
2.671875
3
[ "BSD-3-Clause" ]
permissive
# Moduled Nano MIDI controlled modular LED synthesizer (8 hp). Setup LED animations using MIDI data on your modular rack. <p align="center"><img src="assets/img/moduled/moduled-nano-front.png" width="100"></p> ## DIY ## Hardware ### What you need - 1x Arduino Nano - 1x 8x8 LED matrix - 1x Neopixel LED ring (8 LEDs) - 1x MIDI female jack - 2x buttons - 1x 2-way toggle switch - 2x 10K Potentiometers - 2x 220 ohm resistor - 1x 4.7k resistor - 3x 10k resistor - 1x 1N914 diode - 1x 6N138 Optocoupler - Protoboard, wires, soldering iron ### Case I designed the case using `Blender` 3D rendering software and exported an `stl` file and printed the case using Lulzbot TAZ 6 3D printer. The `.blend` and `stl` file for the case can be found [here](https://github.com/kbsezginel/polycule/tree/master/moduled). ## Software ### moduled_nano.ino [Moduled Nano Arduino script.](https://github.com/kbsezginel/polycule/blob/master/moduled/moduled_nano.ino) ### Setting up custom LED animations Using this [online LED matrix editor](https://xantorohara.github.io/led-matrix-editor/) you can setup a sequence of images to be added as an animation. ## Usage <p align="center"><img src="assets/img/moduled/moduled-nano-usage.png" width="800"></p> ## Shapes 8x8 LED matrix shapes that change size ### [Empty circles | 4 sizes](https://xantorohara.github.io/led-matrix-editor/#0000001818000000|0000182424180000|003c424242423c00|3c4281818181423c) ``` const uint64_t IMAGES[] = { 0x0000001818000000, 0x0000182424180000, 0x003c424242423c00, 0x3c4281818181423c }; ``` ### [Filled circles | 4 sizes](https://xantorohara.github.io/led-matrix-editor/#0000001818000000|0000183c3c180000|003c7e7e7e7e3c00|3c7effffffff7e3c) ``` const uint64_t IMAGES[] = { 0x0000001818000000, 0x0000183c3c180000, 0x003c7e7e7e7e3c00, 0x3c7effffffff7e3c }; ``` ### [Diagonal lines (symmetric) | 4 sizes](https://xantorohara.github.io/led-matrix-editor/#4080000000000102|50a040800102050a|54a851a2458a152a|55aa55aa55aa55aa) ``` const uint64_t IMAGES[] = { 0x4080000000000102, 0x50a040800102050a, 0x54a851a2458a152a, 0x55aa55aa55aa55aa }; ``` ### [Diagonal lines (non-symmetric) | 7 sizes](https://xantorohara.github.io/led-matrix-editor/#4080000000000000|50a0408000000000|54a850a040800000|55aa54a850a04080|55aa55aa54a850a0|55aa55aa55aa54a8|55aa55aa55aa55aa) ``` const uint64_t IMAGES[] = { 0x4080000000000000, 0x50a0408000000000, 0x54a850a040800000, 0x55aa54a850a04080, 0x55aa55aa54a850a0, 0x55aa55aa55aa54a8, 0x55aa55aa55aa55aa }; ``` ## Animations ### [Growing cross | 12 frames]() ``` 0xffc3a59999a5c3ff, 0x8142241818244281, 0x0042241818244200, 0x0000241818240000, 0x0000001818000000, 0x0000000810000000, 0x0000001008000000, 0x0000001818000000, 0x0000241818240000, 0x0042241818244200, 0x8142241818244281, 0xffc3a59999a5c3ff ``` ### [Circling box | 28 frames](https://xantorohara.github.io/led-matrix-editor/#0100000000000000|0101000000000000|0101010000000000|0101010100000000|0101010101000000|0101010101010000|0101010101010100|0101010101010101|0101010101010103|0101010101010107|010101010101010f|010101010101011f|010101010101013f|010101010101017f|01010101010101ff|01010101010181ff|01010101018181ff|01010101818181ff|01010181818181ff|01018181818181ff|01818181818181ff|81818181818181ff|c1818181818181ff|e1818181818181ff|f1818181818181ff|f9818181818181ff|fd818181818181ff|ff818181818181ff) ``` const uint64_t IMAGES[] = { 0x0100000000000000, 0x0101000000000000, 0x0101010000000000, 0x0101010100000000, 0x0101010101000000, 0x0101010101010000, 0x0101010101010100, 0x0101010101010101, 0x0101010101010103, 0x0101010101010107, 0x010101010101010f, 0x010101010101011f, 0x010101010101013f, 0x010101010101017f, 0x01010101010101ff, 0x01010101010181ff, 0x01010101018181ff, 0x01010101818181ff, 0x01010181818181ff, 0x01018181818181ff, 0x01818181818181ff, 0x81818181818181ff, 0xc1818181818181ff, 0xe1818181818181ff, 0xf1818181818181ff, 0xf9818181818181ff, 0xfd818181818181ff, 0xff818181818181ff }; ``` ### [Pharmacy | 16 frames](https://xantorohara.github.io/led-matrix-editor/#0000001818000000|0000182424180000|0018186666181800|181818e7e7181818|991818e7e7181899|dbdb18e7e718dbdb|ffffffe7e7ffffff|ffffffffffffffff|ffffffffffffffff|ffffffe7e7ffffff|dbdb18e7e718dbdb|991818e7e7181899|181818e7e7181818|0018186666181800|0000182424180000|0000001818000000) ``` const uint64_t IMAGES[] = { 0x0000001818000000, 0x0000182424180000, 0x0018186666181800, 0x181818e7e7181818, 0x991818e7e7181899, 0xdbdb18e7e718dbdb, 0xffffffe7e7ffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffe7e7ffffff, 0xdbdb18e7e718dbdb, 0x991818e7e7181899, 0x181818e7e7181818, 0x0018186666181800, 0x0000182424180000, 0x0000001818000000 }; ``` ### [Filling circles | 11 frames](https://xantorohara.github.io/led-matrix-editor/#0000001818000000|0000182424180000|003c424242423c00|7e8181818181817e|7e8181999981817e|7e8181999981817e|7e8199a5a599817e|7ebdc3c3c3c3bd7e|7ebdc3dbdbc3bd7e|7ebddbe7e7dbbd7e|7ebddbffffdbbd7e) ``` const uint64_t IMAGES[] = { 0x0000001818000000, 0x0000182424180000, 0x003c424242423c00, 0x7e8181818181817e, 0x7e8181999981817e, 0x7e8181999981817e, 0x7e8199a5a599817e, 0x7ebdc3c3c3c3bd7e, 0x7ebdc3dbdbc3bd7e, 0x7ebddbe7e7dbbd7e, 0x7ebddbffffdbbd7e }; ```
Java
UTF-8
1,597
2.703125
3
[]
no_license
package com.ipartek.formacion.ejemplofinal.entidades; import java.io.Serializable; import java.math.BigDecimal; import java.time.LocalDate; import java.util.HashSet; import java.util.Set; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.ToString; /** * Representa el recibo de la compra realizada * * @author Jorge Gutierrez * @version 1.0 */ @Data @NoArgsConstructor @AllArgsConstructor public class Factura implements Serializable { private static final long serialVersionUID = 2396176411731906644L; private static final BigDecimal IVA = new BigDecimal("0.21"); private Long id; private String codigo; private LocalDate fecha; private Cliente cliente; //1 factura puede tener 1 cliente @ToString.Exclude @EqualsAndHashCode.Exclude private Set<DetalleFactura> detallesFactura = new HashSet<>(); //1 cliente puede tener muchas facturas /** * Calcula el precio total de la compra * @return precio total de la compra */ public BigDecimal getTotal() { BigDecimal total = BigDecimal.ZERO; for(DetalleFactura detalle: detallesFactura) { total = total.add(detalle.getTotal()); } return total; } /** * Calcula y añade el IVA al precio total * @return precio con el IVA añadido */ public BigDecimal getIva() { return getTotal().multiply(IVA); } /** * Calcula el IVA total * @return precio total con el IVA añadido */ public BigDecimal getTotalConIva() { return getTotal().add(getIva()); } }
Java
UTF-8
6,609
1.929688
2
[ "MIT" ]
permissive
package com.ameron32.apps.demo.codegen.messaging; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.*; import com.ameron32.apps.demo.codegen.R; import com.backendless.Backendless; import com.backendless.BackendlessCollection; import com.backendless.messaging.*; import com.backendless.persistence.BackendlessDataQuery; import java.util.ArrayList; import java.util.List; public class SelectUserActivity extends Activity { private Button previousPageButton, nextPageButton; private ListView usersList; private ArrayAdapter adapter; private BackendlessCollection<ChatUser> users; private ChatUser companion; private int totalPages; private int currentPageNumber; @Override public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); setContentView( R.layout.select_user ); currentPageNumber = 1; initUI(); Backendless.Persistence.of( ChatUser.class ).find( new DefaultCallback<BackendlessCollection<ChatUser>>( this, "Getting chat users" ) { @Override public void handleResponse( BackendlessCollection<ChatUser> response ) { super.handleResponse( response ); totalPages = (int) Math.ceil( (double) response.getTotalObjects() / response.getCurrentPage().size() ); initList( response ); initButtons(); } } ); } private void initUI() { usersList = (ListView) findViewById( R.id.usersList ); previousPageButton = (Button) findViewById( R.id.previousButton ); nextPageButton = (Button) findViewById( R.id.nextButton ); usersList.setOnItemClickListener( new AdapterView.OnItemClickListener() { @Override public void onItemClick( AdapterView<?> parent, View view, int position, long id ) { onListItemClick( position ); } } ); previousPageButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick( View v ) { users.previousPage( new DefaultCallback<BackendlessCollection<ChatUser>>( SelectUserActivity.this ) { @Override public void handleResponse( BackendlessCollection<ChatUser> response ) { super.handleResponse( response ); initList( response ); currentPageNumber--; initButtons(); } } ); } } ); nextPageButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick( View v ) { users.nextPage( new DefaultCallback<BackendlessCollection<ChatUser>>( SelectUserActivity.this ) { @Override public void handleResponse( BackendlessCollection<ChatUser> response ) { super.handleResponse( response ); initList( response ); currentPageNumber++; initButtons(); } } ); } } ); } private void onListItemClick( int position ) { String companionNickname = usersList.getItemAtPosition( position ).toString(); String whereClause = "nickname = '".concat( companionNickname ).concat( "'" ); BackendlessDataQuery backendlessDataQuery = new BackendlessDataQuery(); backendlessDataQuery.setWhereClause( whereClause ); Backendless.Persistence.of( ChatUser.class ).find( backendlessDataQuery, new DefaultCallback<BackendlessCollection<ChatUser>>( this ) { @Override public void handleResponse( BackendlessCollection<ChatUser> response ) { super.handleResponse( response ); companion = response.getCurrentPage().iterator().next(); onCompanionFound(); } } ); } private void onCompanionFound() { PublishOptions publishOptions = new PublishOptions(); publishOptions.putHeader( PublishOptions.ANDROID_TICKER_TEXT_TAG, String.format( DefaultMessages.CONNECT_DEMAND, ChatUser.currentUser().getNickname() ) ); publishOptions.putHeader( PublishOptions.ANDROID_CONTENT_TITLE_TAG, getResources().getString( R.string.app_name ) ); publishOptions.putHeader( PublishOptions.ANDROID_CONTENT_TEXT_TAG, String.format( DefaultMessages.CONNECT_DEMAND, ChatUser.currentUser().getNickname() ) ); DeliveryOptions deliveryOptions = new DeliveryOptions(); deliveryOptions.setPushPolicy( PushPolicyEnum.ONLY ); deliveryOptions.addPushSinglecast( companion.getDeviceId() ); final String message_subtopic = ChatUser.currentUser().getNickname().concat( "_with_" ).concat( companion.getNickname() ); Backendless.Messaging.publish( Defaults.DEFAULT_CHANNEL, message_subtopic, publishOptions, deliveryOptions, new DefaultCallback<MessageStatus>( this, "Sending push message" ) { @Override public void handleResponse( MessageStatus response ) { super.handleResponse( response ); PublishStatusEnum messageStatus = response.getStatus(); if( messageStatus == PublishStatusEnum.SCHEDULED ) { Intent chatIntent = new Intent( SelectUserActivity.this, ChatActivity.class ); chatIntent.putExtra( "owner", true ); chatIntent.putExtra( "subtopic", message_subtopic ); chatIntent.putExtra( "companionNickname", companion.getNickname() ); startActivity( chatIntent ); finish(); } else { Toast.makeText( SelectUserActivity.this, "Message status: " + messageStatus.toString(), Toast.LENGTH_SHORT ).show(); } } } ); } private void initList( BackendlessCollection<ChatUser> response ) { users = response; String[] usersArray = removeNulls( response ); adapter = new ArrayAdapter<String>( this, R.layout.list_item_with_arrow, R.id.itemName, usersArray ); usersList.setAdapter( adapter ); } private void initButtons() { previousPageButton.setEnabled( currentPageNumber != 1 ); nextPageButton.setEnabled( currentPageNumber != totalPages ); } private String[] removeNulls( BackendlessCollection<ChatUser> users ) { List<String> result = new ArrayList<String>(); for( int i = 0; i < users.getCurrentPage().size(); i++ ) { ChatUser chatUser = users.getCurrentPage().get( i ); if( chatUser.getNickname() != null && chatUser.getDeviceId() != null && !chatUser.getDeviceId().isEmpty() && !chatUser.getNickname().isEmpty() ) { result.add( chatUser.getNickname() ); } } return result.toArray( new String[ result.size() ] ); } }
Java
UTF-8
1,923
3.90625
4
[]
no_license
package com.example.redisdemo.arithAndData; /** * 求两个数的最大公约数 * @author wc * @date 2020/10/15 14:05 */ public class MaxCommonDivisor { /** * 辗转相除法求最大公约数 * @param lawNumber 小得数 * @param upperNumber 大一点的数 * @return 最大公约数 */ public static Integer mod(int lawNumber,int upperNumber){ if(upperNumber % lawNumber == 0 ){ return lawNumber; } return mod(upperNumber%lawNumber , lawNumber); } /** * 更相减损数算最大公约数 * @param numberA 数字一 * @param numberB 数字二 * @return 最大公约数 */ public static Integer count(int numberA,int numberB){ if(numberA == numberB){ return numberA; } if(numberA > numberB){ return count(numberA - numberB,numberB); }else { return count(numberB - numberA,numberA); } } /** * 中和更相减损数和辗转相除法的两个优势 * @param numberA 数一 * @param numberB 数二 * @return 最大公约数 */ public static Integer prefect(int numberA,int numberB){ if(numberA == numberB){ return numberA; } if(numberA % 2 == 0 && numberB % 2 == 0){ return 2 * prefect(numberA >> 1,numberB >> 1); } if(numberA % 2 == 0){ numberA = numberA >> 1; } if(numberB % 2 == 0){ numberB = numberB >> 1; } if(numberA == numberB){ return numberA; } if(numberA > numberB){ return prefect(numberA - numberB,numberB); }else { return prefect(numberB - numberA,numberA); } } public static void main(String[] args) { Integer mod = prefect(8, 10); System.out.println(mod); } }
C
UTF-8
576
3.03125
3
[]
no_license
#ifndef _MY_H_ #define _MY_H_ void out(port, val) { asm(LL,8); asm(LBL,16); asm(BOUT); } void putchar(char ch) { out(1, ch); } void puts(char *s) { int i = 0; while (s[i] != 0) { putchar(s[i++]); } } void printinteger(int n) { // All variables must be defined up front, or there'll be error. int bs = 1000000000; if (n == 0) { putchar('0'); return; } while (n / bs == 0) { bs /= 10; } while (bs > 0) { putchar('0' + n / bs); n %= bs; bs /= 10; } } #endif
Go
UTF-8
653
3.65625
4
[]
no_license
package models import ( "fmt" "sort" "strings" ) // Ingredients represents many ingredients in the domain model. type Ingredients []string const maxIngredientsAllowed = 3 // ParseIngredients parses a comma separeted list of strings // into a sorted slice of ingredients (Ingredients). func ParseIngredients(ingredients string) (Ingredients, error) { parsed := strings.Split(ingredients, ",") if len(parsed) > maxIngredientsAllowed { return nil, fmt.Errorf("Please, provide at most %d ingredients", maxIngredientsAllowed) } for i := range parsed { parsed[i] = strings.TrimSpace(parsed[i]) } sort.Strings(parsed) return parsed, nil }
C
UTF-8
372
3.40625
3
[]
no_license
#include<stdio.h> int sum(int a,int b){ return a+b; } int sub(int a,int b) { return a-b; } int evalute(int (*operation)(int,int),int a,int b ) { return (operation)(a,b); } int main(){ int a=10,b=20; int (*p_opr)(int,int)=NULL; p_opr=&sum; printf("\nThe Sum is : %d",evalute(p_opr,a,b)); p_opr=&sub; printf("\nThe Sub is : %d",evalute(p_opr,a,b)); return 0; }
Java
UTF-8
357
1.976563
2
[]
no_license
package com.lti.core.daos; import java.util.*; import com.lti.core.entities.Employee; import com.lti.core.exception.EmpException; public interface EmpDao { public List<Employee> getAllEmps() throws EmpException; //public Employee getEmpOnId(int empId) throws EmpException; //public int insertNewEmployee(Employee emp) throws EmpException; }
Java
UTF-8
1,074
2.8125
3
[]
no_license
package parser.node.statement; import exceptions.AlreadyDeclaredException; import exceptions.IncorrectTypeException; import exceptions.ReturnTypeMismatchException; import exceptions.UndeclaredException; import parser.node.ASTNode; import parser.node.expression.identifier.ASTAbstractIdentifier; import parser.node.expression.identifier.ASTIdentifier; import visitor.Visitor; /** * Class for formal param node */ public class ASTFormalParam implements ASTNode { //identifier private ASTAbstractIdentifier identifier; /** * Constructor * @param identifier identifier to set */ public ASTFormalParam(ASTAbstractIdentifier identifier) { this.identifier = identifier; } /** * Getter for identifier * @return identifier */ public ASTAbstractIdentifier getIdentifier() { return identifier; } @Override public void accept(Visitor visitor) throws AlreadyDeclaredException, UndeclaredException, IncorrectTypeException, ReturnTypeMismatchException { visitor.visit(this); } }
C++
UTF-8
745
3
3
[ "Apache-2.0" ]
permissive
#ifndef NTRP_CONTEXT_ASSIGNMENT_H #define NTRP_CONTEXT_ASSIGNMENT_H /** * @file Assignment.h Definition of parsed context::Assignment class */ #include "Statement.h" #include "Value.h" #include <boost/shared_ptr.hpp> #include <string> namespace context { /** * @brief Assignment statement, encapsulating id=value */ class Assignment : public Statement { public: Assignment(const std::string& id, Value* val) : id_(id), val_(val) { } const std::string& getId() const { return id_; } const Value& getValue() const { return *val_; } virtual void accept(Processor& proc) const { proc.process(*this); } private: std::string id_; boost::shared_ptr<Value> val_; }; } // namespace context #endif // NTRP_CONTEXT_ASSIGNMENT_H
Java
UTF-8
854
3.4375
3
[]
no_license
import java.util.ArrayList; public class Player { private String name; private ArrayList<Card> hands; public Player(String name){ this.name = name; this.hands = new ArrayList<>(); } public int totalHand(){ return this.hands.size(); } public void addCardtoPlayer(Deck deck){ Card result = deck.removeCard(); this.hands.add(result); } public void getCardFromDeckToHand(Deck deck){ Card result = deck.removeCard(); this.hands.add(result); } public ArrayList<Card> getHands() { return hands; } public int handValue(){ int result = 0; for (Card card : this.hands){ result += card.getValueFromEnum(); } return result; } public void getCard(Card card){ this.hands.add(card); } }
Swift
UTF-8
1,509
3.453125
3
[]
no_license
// // List.swift // H100DaysOfSwiftUI // // Created by MANAS VIJAYWARGIYA on 29/01/21. // import SwiftUI struct Lists: View { let people = ["Finn", "Leia", "Luke", "Rey"] var body: some View { //TODO: 1 type - mix with static and dynamic data // List{ // Section(header: Text("Section 1")) { // Text("Static row 1") // Text("Static row 2") // } // // Section(header: Text("Section 2")) { // ForEach(0..<5) { // Text("Dynamic row \($0)") // } // } // // Section(header: Text("Section 3")) { // Text("Static row 3") // Text("Static row 4") // } // } // .listStyle(GroupedListStyle()) //TODO: 2 type - dynamic data with numbers // List(0..<5) { // Text("Dynamic row \($0)") // } // .listStyle(GroupedListStyle()) //TODO: 3 type - only dynamic data with array of data // List(people, id: \.self) { // Text("\($0)") // } // .listStyle(GroupedListStyle()) //TODO: 4 type - mix with static and dynamic data with array of data List { ForEach(people, id: \.self) { Text("\($0)") } } .listStyle(GroupedListStyle()) } } struct Lists_Previews: PreviewProvider { static var previews: some View { Lists() } }
Java
UTF-8
866
2.203125
2
[]
no_license
package com.sadi.asm2.model.Order; import javax.persistence.*; @Entity @Table(name="irn_detail") public class IRNDetail { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; @ManyToOne @JoinColumn (name="irn_id",referencedColumnName="id",nullable=false,unique=false) private InventoryReceivingNote inventory_receiving_note; @Column private int quantity; public int getId() { return id; } public void setId(int id) { this.id = id; } public InventoryReceivingNote getInventory_receiving_note() { return inventory_receiving_note; } public void setInventory_receiving_note(InventoryReceivingNote inventory_receiving_note) { this.inventory_receiving_note = inventory_receiving_note; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } }
Shell
UTF-8
638
3.078125
3
[ "Apache-2.0" ]
permissive
# This script is used to update the a repository containing the starter kit # https://github.com/carbon-design-system/gatsby-starter-carbon-theme # This project should be located in the same directory as the starter project # Copy all files in the example directory to the starter (except for .DS_Store) find ./packages/example -type f -maxdepth 1 ! -iname '.DS_Store' -exec cp {} ../gatsby-starter-carbon-theme/ \; # delete and copy over directories rm -rf ../gatsby-starter-carbon-theme/{src,static} cp -r ./packages/example/src ../gatsby-starter-carbon-theme/src cp -r ./packages/example/static ../gatsby-starter-carbon-theme/static
PHP
UTF-8
957
2.8125
3
[ "MIT" ]
permissive
<h2>Data Operator</h2> <div class="table table-responsive"> <table class="table table-bordered"> <thead> <tr> <th>No</th> <th>Username</th> <th>Password</th> <th>Email</th> <th>User Level</th> </tr> </thead> <tbody> <!-- Proses menampilkan sekaligus melakukan perulangan (looping) data --> <?php include 'koneksi.php'; //query sql untuk menampilkan SELECT $sql = "SELECT * FROM tbl_admin ORDER BY id_opr ASC"; $query = mysqli_query($konek,$sql) or die (mysqli_error($konek)); $no = 1; //nomer urut //tarik dan looping data while($data = mysqli_fetch_array($query)){?> <tr> <td><?php echo $no;?></td> <td><?php echo $data["username"];?></td> <td><?php echo $data["password"];?></td> <td><?php echo $data["email"];?></td> <td><?php echo $data["user_level"];?></td> </tr> <?php $no++; ?> <?php } ?> </tbody> </table> </div>