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
JavaScript
UTF-8
434
2.546875
3
[]
no_license
export default class Figure extends Object { constructor({ parent, scale, context, dx, dy, ...rest }) { super(rest); this.parent = parent; this.scale = scale; this.context = context; this.x = dx; this.y = dy; } updateXY(x, y) { this.ready = false; this.x = x; this.y = y; } handleResize(x, y, scale) { this.ready = false; this.x = x; this.y = y; this.scale = scale; } }
JavaScript
UTF-8
1,015
4.1875
4
[]
no_license
// Trouvez tous les nombres de Armstrong de moins de 1000. // Nombre de Armstrong: nombre naturel égal à la somme des cubes des chiffres qui le composent. var nombre = 1; var nombreArmstrong = ""; while(nombre < 1000) { var nombreEnMorceaux = nombre.toString().split(""); var positionDansArray = 0; var somme = 0; // Pour chaque nombre séparé en tous les chiffres qui le composent while(nombreEnMorceaux[positionDansArray]) { // Trouver le cube de chaque chiffre le composant var nombreAuCube = Math.pow((nombreEnMorceaux[positionDansArray]), 3); // Ajouter la valeur du cube à la somme des chiffres du nombre somme += nombreAuCube; // Ajouter le nombre à la liste des nombres de Armstrong seulement si la somme est égale au nombre if (somme === nombre) { nombreArmstrong += somme + "<br>"; } positionDansArray++; } // document.write(nombre + "<br>"); nombre++; } document.write(nombreArmstrong);
Java
UTF-8
3,896
2.421875
2
[]
no_license
package api_automation.stepDefinition; import cucumber.api.Scenario; import cucumber.api.java.Before; import cucumber.api.java.en.*; import io.restassured.RestAssured; import io.restassured.response.Response; import static io.restassured.RestAssured.given; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import com.jayway.jsonpath.JsonPath; public class GetWeatherByCityName { static String responseCityName; String responseCityID; Scenario scenario; @Before public void keepScenario(Scenario scenario) { this.scenario=scenario; } @Given("^User gets weather for \"([^\"]*)\" city when flag is \"([^\"]*)\"$") public void user_gets_weather_for_city_when_flag_is(String cityName, String flag) throws Throwable { if(flag.equalsIgnoreCase("true")) { RestAssured.baseURI="https://api.openweathermap.org/data/2.5/weather"; Response response=given(). param("q", cityName). param("appid", "eb42dcaceec223e47753a78413ac3f8b"). when().get(); responseCityName=response.prettyPrint(); // System.out.println(responseCityName); scenario.write(responseCityName); scenario.embed(responseCityName.getBytes(), "application/json"); } } @Then("^User validates response with \"([^\"]*)\"$") public void user_validates_response_with(String jsonPath) throws Throwable { String value=JsonPath.read(responseCityName, jsonPath ).toString(); // System.out.println("***** ******* "+value); scenario.write(value); assertNotNull(value); } @Given("^User gets weather for \"([^\"]*)\" city$") public void user_gets_weather_for_city(String cityName) throws Throwable { RestAssured.baseURI="https://api.openweathermap.org/data/2.5/weather"; Response response=given(). param("q", cityName). param("appid", "eb42dcaceec223e47753a78413ac3f8b"). when().get(); responseCityName=response.prettyPrint(); System.out.println(responseCityName); } @Then("^User validates \"([^\"]*)\" in response with \"([^\"]*)\"$") public void user_validates_in_response_with(String element, String jsonPath) throws Throwable { String value=JsonPath.read(responseCityName, jsonPath ).toString(); System.out.println("***** ******* "+value); assertNotNull(value); } @Given("^User gets weather for \"([^\"]*)\" id$") public void user_gets_weather_for_id(String cityID) throws Throwable { RestAssured.baseURI="https://api.openweathermap.org/data/2.5/weather"; Response response=given(). param("id", cityID). param("appid", "eb42dcaceec223e47753a78413ac3f8b"). when().get(); responseCityID=response.prettyPrint(); } @Then("^User compares \"([^\"]*)\" in byCityName response with \"([^\"]*)\" in ByCityID response$") public void user_compares_in_byCityName_response_with_in_ByCityID_response(String element, String jsonPath) throws Throwable { String valueByID=JsonPath.read(responseCityID, jsonPath).toString(); String valueByName=JsonPath.read(responseCityName, jsonPath).toString(); System.out.println("Element : "+element); System.out.println("ValueByID: "+valueByID); System.out.println("ValuByName: "+valueByName); assertEquals(valueByID, valueByName); } }
C
UTF-8
3,886
2.9375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include "tm4c123gh6pm.h" unsigned char UART_InChar(void); void UART_OutChar(unsigned char data); unsigned char UART_InChar(void); void UART_Init(void); void printString (char * string); uint32_t PortF_Input(void); void printMessage(uint32_t data); uint32_t message; void delayUs(int n); int main(void) { UART_Init(); char myChar; while (1) { for(int i = 0; i< 1000; i++); printString("Enter r or g or b: \n \r"); myChar = UART_InChar(); //read character from PC keyboard input – wait for user input UART_OutChar(myChar);// print on PuTTy console to see what the user typed printString ("\n \r");// New line on PuTTY console // Mapping between UART input and GPIO output switch (myChar) { case 'r': GPIO_PORTF_DATA_R = 0x02; // Red LED ON break; case 'b' : GPIO_PORTF_DATA_R = 0x04; // BLUE LED ON break; case 'g' : GPIO_PORTF_DATA_R = 0x08; // GREEN LED ON break; default: GPIO_PORTF_DATA_R = 0x00; // ALL LEDs OFF } } } void printString (char * string){ while (*string) // until the string is NULL { UART_OutChar(*(string++)); // Read characters from sequentially memory addresses one by one and push them out to PC via UART } } unsigned char UART_InChar(void) { while((UART0_FR_R&0x0010) != 0){ message = PortF_Input(); printMessage(message); } // !=0 means RXFE is 1 (empty); keep //looping, nothing to read // wait until RXFE is 0 (not empty) // Not empty: There is something to read // from buffer return((unsigned char)(UART0_DR_R&0xFF)); }// Wait for buffer to be not full, // then output void UART_OutChar(unsigned char data) { while((UART0_FR_R&0x0020) != 0); //!=0 means TXFF =1, full, no space to //transmit, keep looping (wait) // wait until TXFF is 0, TXFF = 0, not // full, write data to register that goes to //FIFO for transmission UART0_DR_R = data; } // Assumes a 50 MHz bus clock, creates 115200 baud rate void UART_Init(void) { // should be called only once SYSCTL_RCGCUART_R |= 0x0001; // activate UART0 SYSCTL_RCGCGPIO_R |= 0x0001; // activate port A UART0_CTL_R &= ~0x0001; // disable UART UART0_IBRD_R = 104; // IBRD=int(50000000/(16*115,200)) = int(27.1267) UART0_FBRD_R = 11; // FBRD = round(0.1267 * 64) = 8 UART0_LCRH_R = 0x0070; // 8-bit word length, enable FIFO UART0_CTL_R = 0x0301; // enable RXE, TXE and UART GPIO_PORTA_PCTL_R =(GPIO_PORTA_PCTL_R&0xFFFFFF00)+0x00000011; // UART GPIO_PORTA_AMSEL_R &= ~0x03; // disable analog function on PA1-0 GPIO_PORTA_AFSEL_R |= 0x03; // enable alt funct on PA1-0 GPIO_PORTA_DEN_R |= 0x03; // enable digital I/O on PA1-0 SYSCTL_RCGCGPIO_R |= 0x20; GPIO_PORTF_LOCK_R = 0x4C4F434B; GPIO_PORTF_CR_R |= 0x1F; GPIO_PORTF_DIR_R = 0x0E; GPIO_PORTF_PUR_R = 0x11; GPIO_PORTF_DEN_R |= 0x1F; } uint32_t PortF_Input(void){ uint32_t data = GPIO_PORTF_DATA_R & 0x01; data ^= 0x01; return (data); } void printMessage(uint32_t data){ if(data){ printString("Nashville,TN: \n \r"); printString ("\n \r"); printString("Enter r or g or b: \n \r"); delayUs(100000); } } void delayUs(int n) { int i, j; for(i = 0 ; i < n; i++) for(j = 0; j < 3; j++) {} }
PHP
UTF-8
2,776
2.828125
3
[ "MIT" ]
permissive
<?php include_once ($_SERVER["DOCUMENT_ROOT"] . '/shopguns/tp7/model/categoria.php'); class CategoriaDao { public static function ObtenerPorID($id) { $cat = new Categoria(); $params = array ( ":id" => $id ); $DBH = new PDO("mysql:host=127.0.0.1;dbname=sistema", "root", ""); $query = 'SELECT * FROM categorias where idCategoria = :id'; $STH = $DBH->prepare($query); $STH->setFetchMode(PDO::FETCH_ASSOC); $STH->execute($params); if ($STH->rowCount() > 0) { $row = $STH->fetch(); $cat->idCategoria = $row['idCategoria']; $cat->nombreCategoria = $row['nombreCategoria']; } return $cat; } public static function ObtenerTodos() { $cont = 0; $arrayCat = array(); $DBH = new PDO("mysql:host=127.0.0.1;dbname=sistema", "root", ""); $query = 'SELECT * FROM categorias'; $STH = $DBH->prepare($query); $STH->setFetchMode(PDO::FETCH_ASSOC); $STH->execute(); if ($STH->rowCount() > 0) { while($row = $STH->fetch()) { $cat = new Categoria(); $cat->idCategoria = $row['idCategoria']; $cat->nombreCategoria = $row['nombreCategoria']; $arrayCat[$cont] = $cat; $cont++; } } return $arrayCat; } public static function nuevo($categoria) { $params = array( ":nombre" => $categoria->nombreCategoria ); $DBH = new PDO("mysql:host=127.0.0.1;dbname=sistema", "root", ""); $query = 'INSERT INTO categorias (nombreCategoria) VALUES (:nombre)'; $STH = $DBH->prepare($query); $STH->setFetchMode(PDO::FETCH_ASSOC); return $STH->execute($params); } public static function modificar($categoria) { $params = array ( ":id" => $categoria->idCategoria, ":nombre" => $categoria->nombreCategoria ); $DBH = new PDO("mysql:host=127.0.0.1;dbname=sistema", "root", ""); $query = 'UPDATE categorias SET nombreCategoria = :nombre WHERE idCategoria = :id' ; $STH = $DBH->prepare($query); $STH->setFetchMode(PDO::FETCH_ASSOC); return $STH->execute($params); } public static function eliminar($id) { $params = array ( ":id" => $id ); $DBH = new PDO("mysql:host=127.0.0.1;dbname=sistema", "root", ""); $query = 'DELETE FROM categorias where idCategoria = :id' ; $STH = $DBH->prepare($query); $STH->setFetchMode(PDO::FETCH_ASSOC); return $STH->execute($params); } } ?>
Java
UTF-8
1,274
2.109375
2
[ "Apache-2.0" ]
permissive
package me.snowdrop.istio.client; import io.fabric8.kubernetes.api.model.KubernetesResourceList; import io.fabric8.kubernetes.api.model.apiextensions.CustomResourceDefinition; import io.fabric8.kubernetes.client.KubernetesClient; import me.snowdrop.istio.api.model.DoneableIstioResource; import me.snowdrop.istio.api.model.IstioResource; public class KubernetesAdapter implements Adapter { private KubernetesClient client; public KubernetesAdapter(KubernetesClient kubernetesClient) { this.client = kubernetesClient; } @Override @SuppressWarnings("unchecked") public IstioResource createCustomResource(String crdName, IstioResource resource) { final CustomResourceDefinition customResourceDefinition = client.customResourceDefinitions().withName(crdName).get(); if (customResourceDefinition == null) { throw new IllegalArgumentException(String.format("Custom Resource Definition %s is not found in cluster %s", crdName, client.getMasterUrl())); } return client.customResources(customResourceDefinition, IstioResource.class, KubernetesResourceList.class, DoneableIstioResource.class). inNamespace("istio-system") .create(resource); } }
Rust
UTF-8
13,086
2.546875
3
[ "Apache-2.0" ]
permissive
use crate::*; use indoc::indoc; use migration_engine_tests::{test_each_connector, TestResult}; #[test_each_connector] async fn basic_create_migration_works(api: &TestApi) -> TestResult { let dm = r#" model Cat { id Int @id name String } "#; let dir = api.create_migrations_directory()?; api.create_migration("create-cats", dm, &dir) .send() .await? .assert_migration_directories_count(1)? .assert_migration("create-cats", |migration| { let expected_script = match api.sql_family() { SqlFamily::Postgres => { indoc! { r#" -- CreateTable CREATE TABLE "Cat" ( "id" INTEGER NOT NULL, "name" TEXT NOT NULL, PRIMARY KEY ("id") ); "# } } SqlFamily::Mysql => { indoc! { r#" -- CreateTable CREATE TABLE `Cat` ( `id` INTEGER NOT NULL, `name` VARCHAR(191) NOT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; "# } } SqlFamily::Sqlite => { indoc! { r#" -- CreateTable CREATE TABLE "Cat" ( "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "name" TEXT NOT NULL ); "# } } SqlFamily::Mssql => { indoc! { r#" -- CreateTable CREATE TABLE [basic_create_migration_works].[Cat] ( [id] INT NOT NULL, [name] NVARCHAR(1000) NOT NULL, CONSTRAINT [PK__Cat__id] PRIMARY KEY ([id]) ); "# } } }; migration.assert_contents(expected_script) })?; Ok(()) } #[test_each_connector] async fn creating_a_second_migration_should_have_the_previous_sql_schema_as_baseline(api: &TestApi) -> TestResult { let dm1 = r#" model Cat { id Int @id name String } "#; let dir = api.create_migrations_directory()?; api.create_migration("create-cats", dm1, &dir) .send() .await? .assert_migration_directories_count(1)?; let dm2 = r#" model Cat { id Int @id name String } model Dog { id Int @id name String } "#; api.create_migration("create-dogs", dm2, &dir) .send() .await? .assert_migration_directories_count(2)? .assert_migration("create-dogs", |migration| { let expected_script = match api.sql_family() { SqlFamily::Postgres => { indoc! { r#" -- CreateTable CREATE TABLE "Dog" ( "id" INTEGER NOT NULL, "name" TEXT NOT NULL, PRIMARY KEY ("id") ); "# } } SqlFamily::Mysql => { indoc! { r#" -- CreateTable CREATE TABLE `Dog` ( `id` INTEGER NOT NULL, `name` VARCHAR(191) NOT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; "# } } SqlFamily::Sqlite => { indoc! { r#" -- CreateTable CREATE TABLE "Dog" ( "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "name" TEXT NOT NULL ); "# } } SqlFamily::Mssql => { indoc! { r#" -- CreateTable CREATE TABLE [creating_a_second_migration_should_have_the_previous_sql_schema_as_baseline].[Dog] ( [id] INT NOT NULL, [name] NVARCHAR(1000) NOT NULL, CONSTRAINT [PK__Dog__id] PRIMARY KEY ([id]) ); "# } } }; migration.assert_contents(expected_script) })?; Ok(()) } #[test_each_connector] async fn bad_migrations_should_make_the_command_fail_with_a_good_error(api: &TestApi) -> TestResult { use std::io::Write as _; let dm = r#" model Cat { id Int @id name String } "#; let dir = api.create_migrations_directory()?; let migration_directory = dir.path().join("20200916161900_broken-migration"); std::fs::create_dir(&migration_directory)?; let migration_file_path = migration_directory.join("migration.sql"); let script = "this is not valid SQL"; let mut file = std::fs::File::create(&migration_file_path)?; write!(file, "{}", script)?; let error = api.create_migration("create-cats", dm, &dir).send().await.unwrap_err(); assert!(error.to_string().contains("syntax"), error.to_string()); Ok(()) } #[test_each_connector] async fn empty_migrations_should_not_be_created(api: &TestApi) -> TestResult { let dm = r#" model Cat { id Int @id name String } "#; let dir = api.create_migrations_directory()?; api.create_migration("create-cats", dm, &dir) .send() .await? .assert_migration_directories_count(1)?; api.create_migration("create-cats-again", dm, &dir) .send() .await? .assert_migration_directories_count(1)?; Ok(()) } #[test_each_connector] async fn migration_name_length_is_validated(api: &TestApi) -> TestResult { let dm = r#" model Cat { id Int @id name String } "#; let dir = api.create_migrations_directory()?; api.create_migration("a-migration-with-a-name-that-is-way-too-long-a-migration-with-a-name-that-is-way-too-long-a-migration-with-a-name-that-is-way-too-long-a-migration-with-a-name-that-is-way-too-long", dm, &dir) .send() .await? .assert_migration_directories_count(1)?; Ok(()) } #[test_each_connector] async fn empty_migrations_should_be_created_with_the_draft_option(api: &TestApi) -> TestResult { let dm = r#" model Cat { id Int @id name String } "#; let dir = api.create_migrations_directory()?; api.create_migration("create-cats", dm, &dir) .send() .await? .assert_migration_directories_count(1)?; api.create_migration("create-cats-again", dm, &dir) .draft(true) .send() .await? .assert_migration_directories_count(2)? .assert_migration("create-cats-again", |migration| { migration.assert_contents("-- This is an empty migration.") })?; Ok(()) } #[test_each_connector] async fn creating_a_migration_with_a_non_existent_migrations_directory_should_work(api: &TestApi) -> TestResult { let dm = r#" model Cat { id Int @id name String } "#; let dir = api.create_migrations_directory()?; std::fs::remove_dir_all(&dir.path())?; api.create_migration("create-cats", dm, &dir) .send() .await? .assert_migration_directories_count(1)?; Ok(()) } #[test_each_connector(tags("mysql", "postgres"))] async fn create_enum_step_only_rendered_when_needed(api: &TestApi) -> TestResult { let dm = r#" datasource test { provider = "mysql" url = "mysql://root:prisma@127.0.0.1:3306/SelfRelationFilterBugSpec?connection_limit=1" } model Cat { id Int @id mood Mood } enum Mood{ HUNGRY SLEEPY } "#; let dir = api.create_migrations_directory()?; api.create_migration("create-cats", dm, &dir) .send() .await? .assert_migration_directories_count(1)? .assert_migration("create-cats", |migration| { let expected_script = match api.sql_family() { SqlFamily::Postgres => { indoc! { r#" -- CreateEnum CREATE TYPE "Mood" AS ENUM ('HUNGRY', 'SLEEPY'); -- CreateTable CREATE TABLE "Cat" ( "id" INTEGER NOT NULL, "mood" "Mood" NOT NULL, PRIMARY KEY ("id") ); "# } } SqlFamily::Mysql => { indoc! { r#" -- CreateTable CREATE TABLE `Cat` ( `id` INTEGER NOT NULL, `mood` ENUM('HUNGRY', 'SLEEPY') NOT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; "# } } SqlFamily::Sqlite | SqlFamily::Mssql => unreachable!("no enums -.-"), }; migration.assert_contents(expected_script) })?; Ok(()) } #[test_each_connector(tags("postgres"))] async fn create_enum_renders_correctly(api: &TestApi) -> TestResult { let dm = r#" datasource test { provider = "postgresql" url = "postgresql://unreachable:unreachable@example.com/unreachable" } model Cat { id Int @id mood Mood } enum Mood{ HUNGRY SLEEPY } "#; let dir = api.create_migrations_directory()?; api.create_migration("create-cats", dm, &dir) .send() .await? .assert_migration_directories_count(1)? .assert_migration("create-cats", |migration| { let expected_script = match api.sql_family() { SqlFamily::Postgres => { indoc! { r#" -- CreateEnum CREATE TYPE "Mood" AS ENUM ('HUNGRY', 'SLEEPY'); -- CreateTable CREATE TABLE "Cat" ( "id" INTEGER NOT NULL, "mood" "Mood" NOT NULL, PRIMARY KEY ("id") ); "# } } _ => unreachable!(), }; migration.assert_contents(expected_script) })?; Ok(()) } #[test_each_connector(tags("postgres"))] async fn unsupported_type_renders_correctly(api: &TestApi) -> TestResult { let dm = r#" datasource test { provider = "postgresql" url = "postgresql://unreachable:unreachable@example.com/unreachable" } model Cat { id Int @id home Unsupported("point") } "#; let dir = api.create_migrations_directory()?; api.create_migration("create-cats", dm, &dir) .send() .await? .assert_migration_directories_count(1)? .assert_migration("create-cats", |migration| { let expected_script = match api.sql_family() { SqlFamily::Postgres => { indoc! { r#" -- CreateTable CREATE TABLE "Cat" ( "id" INTEGER NOT NULL, "home" point NOT NULL, PRIMARY KEY ("id") ); "# } } _ => unreachable!(), }; migration.assert_contents(expected_script) })?; Ok(()) }
JavaScript
UTF-8
787
3.0625
3
[]
no_license
const BST = require('./2-BinarySearchTree'); checkHeight = (tree) => { let lHeight = 0; let rHeight = 0; this.check = (tree) => { if(!tree || tree.value){ return; } else { // check left if(tree.left && tree.left.key > tree.key){ console.log(tree.left) this.check(tree.left); lHeight++; } //check right if(tree.right && tree.right.key > tree.key){ console.log(tree.right) this.check(tree.right); rHeight++; } } rHeight > lHeight ? console.log('Height: ' +rHeight) : console.log('Height: ' + lHeight); } this.check(tree) } checkHeight(BST);
Markdown
UTF-8
846
2.875
3
[]
no_license
# Retrofit > https://github.com/square/retrofit 这是Retrofit在github上的代码,在idea里面通过maven的方法创建工程,然后将github上的代码复制进入。 可以通过各个模块的test代码,学习Retrofit的各种用法。 ## AtomicReference AtomicReference 用于存放一个可以原子更新的对象引用。 该类包含 get() , set() , compareAndSet() , getAndSet() 等原子方法来获取和更新其代表的对象引用。 ## CountDownLatch CountDownLatch的作用: 等待其他的线程都执行完任务,必要时可以对各个任务的执行结果进行汇总,然后主线程才继续往下执行。 countDown()方法用于使计数器减一,其一般是执行任务的线程调用。 await()方法则使调用该方法的线程处于等待状态,其一般是主线程调用。
PHP
UTF-8
3,402
2.671875
3
[ "MIT" ]
permissive
<?php declare(strict_types = 1); namespace PhpCsFixerCustomFixers\Fixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\Preg; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; final class SingleLineThrowFixer extends AbstractFixer implements DeprecatingFixerInterface { private const REMOVE_WHITESPACE_AFTER_TOKENS = ['[']; private const REMOVE_WHITESPACE_AROUND_TOKENS = ['.', '(', [T_OBJECT_OPERATOR], [T_DOUBLE_COLON]]; private const REMOVE_WHITESPACE_BEFORE_TOKENS = [')', ']', ',', ';']; public function getDefinition(): FixerDefinition { return new FixerDefinition( '`throw` must be single line.', [ new CodeSample("<?php\nthrow new Exception(\n 'Error',\n 500\n);\n"), ] ); } public function getPriority(): int { // must be fun before ConcatSpaceFixer and NoUnneededConcatenationFixer return 1; } public function getPullRequestId(): int { return 4452; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(T_THROW); } public function isRisky(): bool { return false; } public function fix(\SplFileInfo $file, Tokens $tokens): void { for ($index = 0, $count = $tokens->count(); $index < $count; $index++) { if (!$tokens[$index]->isGivenKind(T_THROW)) { continue; } /** @var int $openingBraceCandidateIndex */ $openingBraceCandidateIndex = $tokens->getNextTokenOfKind($index, [';', '(']); while ($tokens[$openingBraceCandidateIndex]->equals('(')) { $closingBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openingBraceCandidateIndex); /** @var int $openingBraceCandidateIndex */ $openingBraceCandidateIndex = $tokens->getNextTokenOfKind($closingBraceIndex, [';', '(']); } $this->trimNewLines($tokens, $index, $openingBraceCandidateIndex); } } /** * @param Tokens $tokens * @param int $startIndex * @param int $endIndex */ private function trimNewLines(Tokens $tokens, int $startIndex, int $endIndex): void { for ($index = $startIndex; $index < $endIndex; $index++) { if (!$tokens[$index]->isGivenKind(T_WHITESPACE)) { continue; } if (Preg::match('/\R/', $tokens[$index]->getContent()) === 0) { continue; } $prevIndex = $tokens->getNonEmptySibling($index, -1); if ($tokens[$prevIndex]->equalsAny(\array_merge(self::REMOVE_WHITESPACE_AFTER_TOKENS, self::REMOVE_WHITESPACE_AROUND_TOKENS))) { $tokens->clearAt($index); continue; } $nextIndex = $tokens->getNonEmptySibling($index, 1); if ($tokens[$nextIndex]->equalsAny(\array_merge(self::REMOVE_WHITESPACE_AROUND_TOKENS, self::REMOVE_WHITESPACE_BEFORE_TOKENS))) { if (!$tokens[$prevIndex]->isGivenKind(T_FUNCTION)) { $tokens->clearAt($index); continue; } } $tokens[$index] = new Token([T_WHITESPACE, ' ']); } } }
Markdown
UTF-8
13,343
2.78125
3
[ "MIT" ]
permissive
--- title: "Customer Identity And Access Management Using Azure AD B2C - Custom Attributes" excerpt: "In this post we are going to talk about how to use custom attributes in Azure AD B2C..." header: overlay_image: /images/code.jpeg date: 2022-05-15 tags: [Azure B2C, Azure, Identity, CIAM] --- In the [previous post]({{ site.baseurl}}/azure-ad-b2c-custom-policy) we spoke about custom policies and how they can be used to create user journeys in Azure AD B2C. We also introduced Hones Bakery, a business that we are using as a case study during this B2C series. After successfully creating a tenant for the business and setting up custom policies for common user journeys, we are going to build onto that and talk about custom attributes. ## Custom Attributes Azure AD B2C has a number of default user attributes that it stores, such as given name, surname, address, phone number, to mention but a few. There are times when these attributes might not be enough to meet your business needs. This is where custom attributes come in. Azure AD B2C allows you to create custom attributes -- up to 100 of them, that you can use to capture and store user information that you need for your business. ### Creating Custom Attributes To create a custom attribute, login to your Azure AD B2C tenant and go to the `User Attributes` menu item. You will see a list of all default attributes and a button to add your own attribute (see _Figure 1_ below). <figure> <img src="{{ site.baseurl }}/images/custom-attributes.png" alt="Custom attributes"> <figcaption>Figure 1: Add custom attributes</figcaption> </figure> ### How It Works In The Background Custom attributes are created and stored using the B2C extension application. This is an application that is automatically created when you create your Azure AD B2C tenant. If you go to your app registration tab and select all applications, you will see an application that called **b2c-extensions-app. Do not modify. Used by AADB2C for storing user data**. You are not supposed to modify or delete this application. When you create a custom attribute, let's call it `LoyaltyCardNumber` it will be stored in Azure AD B2C as `extension_<extension app client id without dashes>_LoyaltyCardNumber`. My extension app client ID is `8f3907cf-cb81-4597-b32a-d719b2b5d3fa` so my custom attribute will be stored as `extension_8f3907cfcb814597b32ad719b2b5d3fa_LoyaltyCardNumber`. However, when you refer to the custom attribute in your custom policies you have to drop the extension app client ID so it will become `extension_LoyaltyCardNumber`.If you want to populate a user's custom attributes using the Graph SDK you will need to reference it using the full name (i.e including the extension app client ID). Your code will look like this: ```csharp graphServiceClient.Users.Request() .AddAsync(new User{ // other user attributes AdditionalData = new Dictionary<string, object> { {"extension_8f3907cfcb814597b32ad719b2b5d3fa_LoyaltyCardNumber", "12345"} } }); ``` Now that we have an understanding of how custom attributes, let's go back to our case study and see how we are going to make use of custom attributes. ## Case Study Hones Bakery, the business we were introduced to in the previous post has loyalty cards for its customers. The owner of the business has requested us to allow users to add the loyalty card numbers to their profiles. We are going to create a custom attribute called `LoyaltyCardNumber` of type `string` and update our custom policies to allow for the capture and store the custom attribute. ## Update Custom Policies Assuming that you have created your custom attribute let's go to our custom policies and get cracking. There are a few steps we are going to follow. ### Add B2C Extension App Metadata If you didn't use the [online tool](https://b2ciefsetupapp.azurewebsites.net/) to set up your custom policy you will need to add the app client ID and the object ID of the B2C extension app to your custom policies. Without this you will not be able to access your custom attributes. Remember they are stored and managed by the extension app. Open the `TrustFrameworkExtensions.xml` file and add the following under the `ClaimsProviders` tag: ```xml <ClaimsProviders> <!-- Other claims providers --> <ClaimsProvider> <DisplayName>Azure Active Directory</DisplayName> <TechnicalProfiles> <TechnicalProfile Id="AAD-Common"> <DisplayName>Azure Active Directory</DisplayName> <Metadata> <Item Key="ApplicationObjectId">b2c-extension-app-object-id</Item> <Item Key="ClientId">b2c-extension-app-client-id</Item> </Metadata> </TechnicalProfile> </TechnicalProfiles> </ClaimsProvider> </ClaimsProviders> ``` What we are doing here is to extend a technical profile with ID `AAD-Common` that's in the `TrustFrameworkBase.xml` policy by adding the B2C extension app metadata. Next, we define the schema for our custom attribute. ### Define Schema For Custom Attribute While still in the `TrustFrameworkExtensions.xml` file, go to the `BuildingBlocks` tag and add the following: ```xml <ClaimsSchema> <!-- Add a claim to capture the loyalty card number --> <ClaimType Id="extension_LoyaltyCardNumber"> <DisplayName>Loyalty card number</DisplayName> <DataType>string</DataType> <UserHelpText>Your loyalty card number</UserHelpText> <UserInputType>TextBox</UserInputType> <Restriction> <Pattern RegularExpression="^\d{10}$" HelpText="Enter 10 digit loyalty card number"/> </Restriction> </ClaimType> </ClaimsSchema> ``` The code snippet above creates the schema for our custom attribute. As you can notice the Id is `extension_LoyaltyCardNumber` which is how we reference it in our custom policies. We also declared the data type, user input type and other UI related data that Azure AD B2C will require to render the UI element to capture the custom attribute. Next we are going to extend the profile update technical profile to allow for the capture of our custom attribute. ### Extend SelfAsserted-ProfileUpdate Technical Profile Still in the `TrustFrameworkExtensions.xml` file add the following in the `ClaimsProviders` tag: ```xml <ClaimsProvider> <DisplayName>Self Asserted</DisplayName> <TechnicalProfiles> <TechnicalProfile Id="SelfAsserted-ProfileUpdate"> <InputClaims> <InputClaim ClaimTypeReferenceId="extension_LoyaltyCardNumber"/> </InputClaims> <OutputClaims> <OutputClaim ClaimTypeReferenceId="extension_LoyaltyCardNumber" Required="true"/> </OutputClaims> </TechnicalProfile> </TechnicalProfiles> </ClaimsProvider> ``` Here were adding our custom claim to the list of input and output claims inside the `SelfAsserted-ProfileUpdate` technical profile. The reason why we have our custom policy in both the input and output claims is that if it's already there (in the input claims) we want to pre-populate the field and once the technical profile has completed executing we save it to the claims bag (output claims). A technical profile is analogous to a function (method) in object oriented programming. It takes in inputs (input claims), execute a given task and then return outputs (output claims). Check out the [documentation](https://docs.microsoft.com/en-us/azure/active-directory-b2c/technicalprofiles) for more information on technical profiles. Next we extend the technical profiles that are responsible of reading and writing user's profile. ### Update Technical Profiles To Read And Write User Data Add the following in the `ClaimsProviders` tag: ```xml <ClaimsProvider> <DisplayName>Azure Active Directory</DisplayName> <TechnicalProfiles> <!-- TP responsible for writing user's profile --> <TechnicalProfile Id="AAD-UserWriteProfileUsingObjectId"> <PersistedClaims> <!-- persist custom claim --> <PersistedClaim ClaimTypeReferenceId="extension_LoyaltyCardNumber"/> </PersistedClaims> </TechnicalProfile> <!-- TP responsible for reading user data by ID--> <TechnicalProfile Id="AAD-UserReadUsingObjectId"> <OutputClaims> <!-- return custom claim as part of user data--> <OutputClaim ClaimTypeReferenceId="extension_LoyaltyCardNumber"/> </OutputClaims> </TechnicalProfile> </TechnicalProfiles> </ClaimsProvider> ``` The comments in the XML speak for themselves. We extended the `AAD-UserWriteProfileUsingObjectId` technical profile so we can persist our custom attribute. We also extended the `AAD-UserReadUsingObjectId` so it can return the custom attribute when it fetches user data. Now let's update our `SignUpOrSignin` user journey. ### Update SignUpOrSignin User Journey The `SignUpOrSignin` user journey is the user journey that the user will go through when they are signing up or signing in to our applications. The change we want to make is as follows: when a user signs in for the second time, that is, if they are not a new user, we want them to fill in their loyalty card number before they are issued a token. This is what is called progressive profiling, where you don't ask the user for all the information you need when they first sign up but rather ask for it in subsequent sign ins. Go to the `TrustFrameworkBase.xml` and copy the user journey with ID `SignUpOrSignin`. Paste it in the `TrustFrameworkExtensions.xml` file and change the ID to `SignUpOrSignInProgressive`. Add the following orchestration step just before the last step (the one with `Type="SendClaims"`): ```xml <OrchestrationStep Order="7" Type="ClaimsExchange"> <Preconditions> <!-- If claim with value extension_LoyaltyCardNumber exists then skip this step--> <Precondition Type="ClaimsExist" ExecuteActionsIf="true"> <Value>extension_LoyaltyCardNumber</Value> <Action>SkipThisOrchestrationStep</Action> </Precondition> <!-- If claim with value newUser exists then skip this step--> <Precondition Type="ClaimsExist" ExecuteActionsIf="true"> <Value>newUser</Value> <Action>SkipThisOrchestrationStep</Action> </Precondition> </Preconditions> <!-- otherwise take user to update profile screen --> <ClaimsExchanges> <ClaimsExchange Id="ProfileUpdateExchange" TechnicalProfileReferenceId="SelfAsserted-ProfileUpdate"/> </ClaimsExchanges> </OrchestrationStep> ``` Please ensure that the `Order` for the orchestration step is 1 more than the one that precedes it. In my example it follows step 6 so I made it step 7. Also make sure that your last step has order of 1 more that this step -- 8 in this example. This orchestration steps checks if a claim with value `extension_LoyaltyCardNumber` exists. If it does then we already have the user's loyalty card number so we skip the step. It also checks if there is a claim with value `newUser` which is issued when a user signs in for the very first time. If it exists then we want to skip the step as well. If both the pre-conditions are not true then we take the user to the edit profile page where they will be asked to enter their loyalty card number. Lastly, we need to update the relying party. ## Update Relying Party Open the `SignUp_SignIn.xml` file and make the following changes: 1. Change the default user journey reference ID to `SignUpOrSignInProgressive`. This will reference the user journey we just modified. 2. Add the following output claim to ensure that out loyalty card number will be added to the issued token: ```xml <OutputClaim ClaimTypeReferenceId="extension_LoyaltyCardNumber" PartnerClaimType="loyalty_card_number"/> ``` Now we upload our updated policies to Azure AD B2C. When uploading policies it is important to follow the inheritance hierarchy so we will start with the `TrustFramworkExtensions.xml` followed by the `SignUp_SignIn.xml`. ## Test Policy Now we test the changes we have made. Let's run the `SignUpOrSignIn` policy and sign up a new user. You will notice that you were not asked for the loyalty card number. Run the policy again, and this time login with the new user's credentials. You will be taken to a screen that asks for your loyalty card number, similar to the one below. <figure> <img src="{{ site.baseurl }}/images/loyalty-number.png" alt="Profile update"> <figcaption>Figure 2: Add loyalty card number</figcaption> </figure> Enter a 10-digit number and you will be redirected to the _jwt.ms_ website where you'll view the token that includes the loyalty card number as shown in _Figure 3_ below. <figure> <img src="{{ site.baseurl }}/images/token.png" alt="Issued token"> <figcaption>Figure 3: JWT issued</figcaption> </figure> ## Conclusion In this post we spoke about custom user attributes in Azure AD B2C. We looked at how to add them in the portal as well as how they are managed in the background. We also updated our custom policies to allow us to capture the users' loyalty card numbers after successfully logging in. In the next post we are going to look at how we can customize our UI instead of using the default UI provided by Azure AD B2C. Once again, thanks so much for reading and don't hesitate to leave a comment below if you have any question, correction or suggestion.
Markdown
UTF-8
1,389
3.890625
4
[]
no_license
# Binary Search ## Classic Application of Binary Search Binary Search finds the position of a target value in a sorted array. The complexity for this algorithm is <pre> - Worst-case performance O(log n) - Best-case performance O(1) - Average performance O(log n) - Worst-case space complexity O(1) </pre> ```python class BinarySearch(object): def search(self, nums, target): low = 0 high = len(nums)-1 while low<=high: mid = (low+high)//2 if nums[mid]==target: return mid if nums[mid]>target: high=mid-1 else: low=mid+1 return -1 ``` ```python print(BinarySearch().search([-1,2,4,6,12,22,34,54,67,76,98,645,896,2342],645)) ``` 11 ```python print(BinarySearch().search([-1,2,4,6,12,22,34,54,67,76,98,645,896,2342],949)) ``` -1 ## Get a Separator in a rotated sorted Array **Modification of Binary search** ```python class SortedSeparator(object): def getSeparator(self,nums): lo=0 hi=int(len(nums)-1) while lo<hi: mid=int((lo+hi)/2) if nums[mid]>nums[hi]: lo=mid+1 else: hi=mid return lo print(SortedSeparator().getSeparator([7,8,9,10,12,23,45,67,1,3,4,5,6])) ``` 8 ```python ```
Python
UTF-8
3,124
2.59375
3
[]
no_license
import os import numpy as np import gym import pybullet_envs from storage import ReplayBuffer from ddpg.ddpg import DDPG class Base: def __init__(self, env, device, model_dir, args): self.env = env self.env_name = args.env_name self.seed = args.seed self.state_dim = self.env.observation_space.shape[0] self.action_dim = self.env.action_space.shape[0] self.max_action = float(self.env.action_space.high[0]) self.batch_size = args.batch_size self.max_timesteps = args.max_timesteps self.gaussian_std = args.gaussian_std self.start_timesteps = args.start_timesteps self.eval_freq = args.eval_freq self.rand_action_p = args.rand_action_p self.model_dir = os.path.join(model_dir, f"{args.env_name}_{args.seed}") self.algo = DDPG( self.state_dim, self.action_dim, self.max_action, device) self.storage = ReplayBuffer( self.state_dim, self.action_dim, device) self.eval_rewards = [] self.total_steps = 0 self.episodes = 0 self.episode_steps = 0 self.episode_rewards = 0 self.state = None def iterate(self): assert self.state is not None self.episode_steps += 1 if self.is_random_action(): action = self.env.action_space.sample() else: action = ( self.algo.select_action(np.array(self.state)) + np.random.normal( 0, self.max_action * self.gaussian_std, size=self.action_dim) ).clip(-self.max_action, self.max_action) next_state, reward, done, _ = self.env.step(action) done_bool = float(done) if self.episode_steps < self.env._max_episode_steps else 0 self.storage.add(self.state, action, next_state, reward, done_bool) self.state = next_state self.episode_rewards += reward if done: print( f"Total T: {self.total_steps + 1} " f"Episode Num: {self.episodes + 1} " f"Episode T: {self.episode_steps} " f"Reward: {self.episode_rewards:.3f}") # Reset environment self.state = self.env.reset() self.episode_rewards = 0 self.episode_steps = 0 self.episodes += 1 self.total_steps += 1 def evaluate(self, eval_episodes=10): eval_env = gym.make(self.env_name) eval_env.seed(self.seed + 100) avg_reward = 0. for _ in range(eval_episodes): state, done = eval_env.reset(), False while not done: action = self.algo.select_action(np.array(state)) state, reward, done, _ = eval_env.step(action) avg_reward += reward avg_reward /= eval_episodes print("---------------------------------------") print(f"Evaluation over {eval_episodes} episodes: {avg_reward:.3f}") print("---------------------------------------") return avg_reward
PHP
UTF-8
618
2.53125
3
[]
no_license
--TEST-- Create an new paradox database --SKIPIF-- <?php if (!extension_loaded("paradox")) print "skip"; ?> --POST-- --GET-- --INI-- --FILE-- <?php $dirname = dirname($_SERVER["SCRIPT_FILENAME"]); $fp = fopen($dirname."/px013.db", "w+"); $pxdoc = new paradox_db(); $fields = array(array("col1", "S"), array("col2", "I")); @$pxdoc->create_fp($fp, $fields); $pxdoc->set_tablename("testtabelle"); for($i=-3; $i<=3; $i++) { $pxdoc->insert_record(array($i, $i)); } print_r($pxdoc->retrieve_record(1)); $pxdoc->close(); fclose($fp); unlink($dirname."/px013.db"); ?> --EXPECT-- Array ( [col1] => -2 [col2] => -2 )
Java
UTF-8
2,198
3.6875
4
[ "MIT" ]
permissive
package edu.sda.parser; import edu.sda.data.Task; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; /** * Parser reads user input and interprets it as a * command and transfers it to objects. Every time it is called, it reads a line from the terminal and * tries to interpret the line as a two-word command. It returns the command * as an object of class Command. * */ public class Parser { private CommandWords commands; private Scanner reader; public Parser() { commands = new CommandWords(); reader = new Scanner(System.in); } /** * @return The next command from the user. */ public Command getCommand() { String inputLine; String word1 = null; String words = null; System.out.print("> "); inputLine = reader.nextLine(); Scanner tokenizer = new Scanner(inputLine); if(tokenizer.hasNext()) { word1 = tokenizer.next(); if (tokenizer.hasNext()) { words = tokenizer.next(); while (tokenizer.hasNext()){ words = words + " " + tokenizer.next(); } } } return new Command(commands.getCommandWord(word1), words); } /** * Method to map string from input to a task object. * @param wordTask * @return and object of task */ public Task mapStringToTask(String wordTask){ String[] parsedTaskString = wordTask.split(";"); String taskTitle = parsedTaskString[0]; Date taskDate = mapStringToDate(parsedTaskString[1]) ; String project = parsedTaskString[2]; return new Task(taskTitle, taskDate, project); } /** * Method to map string to a date object for a task. * @param sDate string date * @return date */ Date mapStringToDate(String sDate){ Date taskDate = null; try { taskDate = new SimpleDateFormat("dd/mm/yyyy").parse(sDate); } catch (ParseException e){ System.out.println("Incorrect date format"); } return taskDate; } }
Java
UTF-8
609
2.28125
2
[ "Unlicense" ]
permissive
/* FantastleReboot: An RPG Copyright (C) 2011-2012 Eric Ahnell Any questions should be directed to the author via email at: products@puttysoftware.com */ package com.puttysoftware.fantastlereboot.battle.map; import com.puttysoftware.fantastlereboot.gui.Prefs; public class MapBattleArrowSpeedConstants { // Constants private static int ARROW_SPEED_FACTOR = 8; // Constructor private MapBattleArrowSpeedConstants() { // Do nothing } // Method public static int getArrowSpeed() { return Prefs.getBattleSpeed() / MapBattleArrowSpeedConstants.ARROW_SPEED_FACTOR; } }
Python
UTF-8
491
3.734375
4
[]
no_license
# セクション4: データ構造 # 20.リストの使い所 # タクシーの乗車ゲーム seat = [] min = 0 max = 5 print(min <= len(seat) < max) seat.append('p') print(min <= len(seat) < max) print(len(seat)) seat.append('p') print(min <= len(seat) < max) print(len(seat)) seat.append('p') print(min <= len(seat) < max) print(len(seat)) seat.append('p') seat.append('p') print(min <= len(seat) < max) print(len(seat)) print(seat.pop(0)) print(min <= len(seat) < max) print(len(seat))
C++
UTF-8
2,869
2.59375
3
[ "MIT" ]
permissive
#include "com_wn518_printer_core_PrinterLib.h" #include <memory.h> #ifdef __cplusplus extern "C" { #endif void intcolor2bitcolorline(int * intcolor,int w,signed char * bitcolor,signed char * header,int headerSize); JNIEXPORT jbyteArray JNICALL Java_com_wn518_printer_core_PrinterLib_getBitmapData(JNIEnv *env, jobject thiz,jintArray bitdata,jint w,jint h) { jint length = env->GetArrayLength(bitdata); jint* inbits = env->GetIntArrayElements(bitdata,0); jsize lineSize =w/8 + ((w%8)?1:0); jsize outBitsCount = lineSize*h; jbyteArray outArray = env->NewByteArray(outBitsCount); jbyte* outbits = env->GetByteArrayElements(outArray,0); for(jint j=0;j<h;j++) { intcolor2bitcolorline(inbits+j*w,w,outbits+lineSize*j,NULL,0); } return outArray; } JNIEXPORT jbyteArray JNICALL Java_com_wn518_printer_core_PrinterLib_getBitmapDataWithHeader(JNIEnv *env, jobject thiz, jintArray bitdata,jint w,jint h,jbyteArray header) { jint length = env->GetArrayLength(bitdata); jint* inbits = env->GetIntArrayElements(bitdata,0); jint headerSize = env->GetArrayLength(header); jbyte* headerbits = env->GetByteArrayElements(header,0); jsize lineSize =w/8 + ((w%8)?1:0); jsize outBitsCount = lineSize*h + headerSize; jbyteArray outArray = env->NewByteArray(outBitsCount); jbyte* outbits = env->GetByteArrayElements(outArray,0); memcpy(outbits,headerbits,headerSize); for(jint j=0;j<h;j++) { intcolor2bitcolorline(inbits+j*w,w,outbits+headerSize+lineSize*j,0,0); } return outArray; } JNIEXPORT jbyteArray JNICALL Java_com_wn518_printer_core_PrinterLib_getBitmapDataWithLineHeader(JNIEnv *env, jobject thiz, jintArray bitdata,jint w,jint h,jbyteArray lineHeader) { jint length = env->GetArrayLength(bitdata); jint* inbits = env->GetIntArrayElements(bitdata,0); jint headerSize = env->GetArrayLength(lineHeader); jbyte* header = env->GetByteArrayElements(lineHeader,0); jsize lineSize =w/8 + ((w%8)?1:0) + headerSize; jsize outBitsCount = lineSize*h; jbyteArray outArray = env->NewByteArray(outBitsCount); jbyte* outbits = env->GetByteArrayElements(outArray,0); for(jint j=0;j<h;j++) { intcolor2bitcolorline(inbits+j*w,w,outbits+lineSize*j,header,headerSize); } return outArray; } void intcolor2bitcolorline(int * intcolor,int w,signed char * bitcolor,signed char * header,int headerSize) { int value = 0; int shiftCount = 7; int bitIndex=0; if(header!=0) { memcpy(bitcolor,header,headerSize); } for(int i=0;i<w;i++) { int color = intcolor[i]; int r = (color >> 16) & 0xff; int g = (color >> 8) & 0xff; int b = color & 0xff; if (r <= 160 || g <= 160 || b <= 160) value |= 1<<shiftCount; shiftCount--; if(shiftCount<0) { shiftCount=7; bitcolor[bitIndex+headerSize] = value; value = 0; bitIndex++; } } if(w%8) { bitcolor[bitIndex+headerSize] = value; } } #ifdef __cplusplus } #endif
Java
GB18030
1,107
3.78125
4
[]
no_license
package edu.whut.enumeration; import org.junit.Test; /** * * @Description:öٳ÷ * * name(): ȡöֵ * ordinal():ȡöֵλ * valueOf():ַתö * values():öֵ */ public class EnumTest3 { @Test public void test(){ System.out.println(stu.A.name()); System.out.println(stu.A.ordinal()); System.out.println("----------------------------"); //ôڿͻύıݶַ͵ģǿԽijЩַתöͣǷǶö,ǣ׳쳣 String str = "B"; stu s = stu.valueOf(stu.class, str); System.out.println(s.name()); System.out.println("----------------------------"); stu[] stus = stu.values(); for(stu S : stus){ System.out.println(S); } } enum stu{ A("90-100"),B("80-89"),C("70-79"),D("60-69"),E("1-59"),F("0"); private String value; private stu(String value){ this.value = value; } public String getvalue(){ return this.value; } } }
C#
UTF-8
721
3.25
3
[ "MIT", "CC-BY-4.0" ]
permissive
// <Snippet15> using System; using System.Globalization; public class Example { public static void Main() { CompareInfo ci = CultureInfo.CurrentCulture.CompareInfo; string searchString = "\u00ADm"; string s1 = "ani\u00ADmal" ; string s2 = "animal"; Console.WriteLine(ci.IndexOf(s1, searchString, 2, CompareOptions.None)); Console.WriteLine(ci.IndexOf(s1, searchString, 2, CompareOptions.Ordinal)); Console.WriteLine(ci.IndexOf(s2, searchString, 2, CompareOptions.None)); Console.WriteLine(ci.IndexOf(s2, searchString, 2, CompareOptions.Ordinal)); } } // The example displays the following output: // 4 // 3 // 3 // -1 // </Snippet15>
C++
UTF-8
1,583
2.9375
3
[ "MIT" ]
permissive
#include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> #define SCREEN_WIDTH 128 // OLED display width, in pixels #define SCREEN_HEIGHT 32 // OLED display height, in pixels // Declaration for an SSD1306 display connected to I2C (SDA, SCL pins) #define OLED_RESET 4 // Reset pin # (or -1 if sharing Arduino reset pin) Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); class screen { private: public: screen(){}; void init(); void homeScreen(char str[], char *code); void lineUpdate(uint8_t interval); void off(); }; void screen::init() { if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32 Serial.println(F("SSD1306 allocation failed")); for (;;) ; // Don't proceed, loop forever } const char text[5] = "home\0"; homeScreen(text, (char *)text); delay(500); } void screen::off() { display.clearDisplay(); display.display(); } void screen ::homeScreen(char str[], char *code) { display.clearDisplay(); display.setCursor(0, 0); display.setTextColor(SSD1306_WHITE); display.setTextSize(1); display.println(str); display.println(); display.setTextSize(2); // Draw 2X-scale text display.println(code); display.display(); } void screen ::lineUpdate(uint8_t interval) { display.drawFastHLine(0, display.height() - 1, (display.width() - 1), SSD1306_BLACK); display.drawFastHLine(0, display.height() - 1, (1 - (((float)interval) / 30)) * (display.width() - 1), SSD1306_WHITE); display.display(); } screen myScreen;
C#
UTF-8
4,013
2.703125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Api.Provagas.Domains; using Api.Provagas.Interfaces; using Api.Provagas.Repositories; namespace ProVagas.Controllers { [Produces("application/json")] [Route("api/[controller]")] [ApiController] public class NiveisEscolaridadesController : ControllerBase { private INivelEscolaridadeRepository _nivelescolaridaderepository { get; set; } public NiveisEscolaridadesController() { _nivelescolaridaderepository = new NivelEscolaridadeRepository(); } /// <summary> /// Listar todos os niveis de escolaridade /// </summary> /// <returns>Retorna uma lista com os niveis de escolaridade</returns> [HttpGet] public IEnumerable<NivelEscolaridade> Get() { return _nivelescolaridaderepository.GetAll(); } /// <summary> /// Listar uma lista de niveis de escolaridade pelo Id /// </summary> /// <param name="id">Id dos niveis de escolaridade que será buscado</param> /// <returns>Retorna uma lista de niveis de escolaridade pelo Id</returns> [HttpGet("{id}")] public IActionResult Get(int id) { if (_nivelescolaridaderepository.GetById(id) != null) { return Ok(_nivelescolaridaderepository.GetById(id)); } else { return BadRequest("Nivel de escolaridade não encontrado."); } } /// <summary> /// Cadastrar um novo nivel de escolaridade /// </summary> /// <param name="nivel"></param> /// <returns>Retorna o cadastro de um novo nivel de escolaridade</returns> [HttpPost] public IActionResult Post(NivelEscolaridade nivel) { try { _nivelescolaridaderepository.Add(nivel); return Ok("Nivel de escolaridade cadastrado com sucesso"); } catch (Exception) { return BadRequest("Nivel não cadastrado"); } } /// <summary> /// Atualizar um nivel de escolaridade pelo Id /// </summary> /// <param name="id">Id dos niveis de escolaridade que será buscado</param> /// <param name="nivelcadastrado"></param> /// <returns>Retorna um nivel de escolaridade atualizado</returns> [HttpPut("{id}")] public IActionResult Put(int id, NivelEscolaridade nivelcadastrado) { try { NivelEscolaridade UPDATE = new NivelEscolaridade { IdNivelEscolaridade = id, Escolaridade = nivelcadastrado.Escolaridade }; _nivelescolaridaderepository.Update(UPDATE); return Ok("Nivel de escolaridade atualizado com sucesso"); } catch (Exception) { return BadRequest("Não foi possivel atualizar esse nivel de escolaridade"); } } /// <summary> /// Deletar um nivel de escolaridade pelo Id /// </summary> /// <param name="id">Id dos niveis de escolaridade que será buscado</param> /// <returns>Retorna vazio</returns> [HttpDelete("{id}")] public IActionResult Delete(int id) { try { NivelEscolaridade nivelbuscado = _nivelescolaridaderepository.GetById(id); _nivelescolaridaderepository.Delete(nivelbuscado); return Ok("Nivel de escolaridade deletado com sucesso"); } catch (Exception) { return BadRequest("Não foi possivel deletar esse nivel de escolaridade"); } } } }
PHP
UTF-8
1,149
3.609375
4
[]
no_license
<?php class XMLAttribute { private $type; // Typ attributu private $argument_order; // Poradi attributu private $value; // Hodnota attributu /** * XMLAttribute constructor. * @param $argument_order Poradi argumentu */ function __construct($argument_order) { $this->argument_order = $argument_order; } /** * Ziskava hodnotu attributu * @return mixed Hodnota attributu */ function get_value() { return $this->value; } /** * Nastaveni hodnoty attributu * @param $value Hodnota attributu */ function set_value($value) { $this->value = $value; } /** * Ziskava poradi argumentu * @return mixed Poradi argumentu */ function get_argument_order() { return $this->argument_order; } /** * Ziskava typ attributu * @return mixed Typ attributu */ function get_type() { return $this->type; } /** * Nastaveni typu attributu * @param $type Typ attributu */ function set_type($type) { $this->type = $type; } } ?>
C++
UTF-8
2,188
2.890625
3
[]
no_license
#pragma once #include <stdexcept> #include "rect.h" #include "icommon.h" #include <list> #include <imath.h> #include <boost/shared_ptr.hpp> class EdgesContainer; /** Oriented edge structure ** /|^\ next / || \ / || \ / || \ * || * [adjacent]----\- >|| / \ || / \ || / \||/ prev ** */ class OrEdge { public: OrEdge(EdgesContainer * container); OrEdge(int o, int d, EdgesContainer * container); // structure int org() const { return org_; } int dst() const { return dst_; } // topology OrEdge * get_adjacent(); const OrEdge * get_adjacent() const; OrEdge * create_adjacent(); void clear_adjacent(); // rotate this & adjacent edges 90 deg CW bool rotate(); OrEdge * next(); OrEdge * prev(); const OrEdge * next() const; const OrEdge * prev() const; // return old 'next' OrEdge * set_next(OrEdge * e); // insert point with index i bool splitTri(int i); bool splitEdge(int i); // get triangle representation Triangle tri() const; // geometry double length() const; Vec3f dir() const; Rect3f rect() const; // data private: void verifyTopology(std::set<const OrEdge*> & verified) const; const OrEdge * findConnection() const; int org_, dst_; OrEdge * next_, * adjacent_; EdgesContainer * container_; }; inline bool intersect(const Rect3f & rc, const OrEdge & e) { return rc.intersecting(e.rect()); } typedef boost::shared_ptr<OrEdge> OrEdge_shared; typedef std::list<OrEdge_shared> OrEdgesList_shared; class EdgesContainer { public: EdgesContainer(Vertices & verts) : verts_(verts) {} OrEdge * new_edge(int o, int d); Vertices & verts() { return verts_; } const Vertices & verts() const { return verts_; } const OrEdgesList_shared & edges() const { return edges_; } OrEdgesList_shared & edges() { return edges_; } private: OrEdgesList_shared edges_; Vertices & verts_; };
PHP
UTF-8
1,072
2.90625
3
[]
no_license
<?php namespace App; use Illuminate\Database\Eloquent\Model; use DB; use Illuminate\Support\Collection; class Book extends Model { /** * Получает все книги у которых N и более авторов * * @param int $count * @return string */ public function getBookWithNAuthors(int $count) : string { $query = " SELECT id, title, book_ids.cnt FROM library.books INNER JOIN (SELECT COUNT(book_id) AS cnt, book_id FROM library.authors GROUP BY book_id HAVING cnt >= $count) AS book_ids ON library.books.id = book_ids.book_id "; $orders = DB::select($query); return json_encode($orders); } /** * Получаем все книги * * @return Collection */ public function getAllBooks() : Collection { return DB::table('books')->select('*')->get(); } }
C++
UTF-8
6,968
2.859375
3
[ "MIT" ]
permissive
#include <iostream> #include <fstream> #include <algorithm> #include <vector> #include <numeric> #include <unordered_map> #include <boost/algorithm/string/find.hpp> #include <cmath> #include <boost/range/algorithm/count.hpp> class Tile { public: Tile() = default; Tile(int _id) : id(_id) {} int id; // up, down, left, right std::vector<std::string> borders = { "", "", "", ""}; std::vector<int> adjecent; int count = 0; std::pair<int, int> match(Tile& other_tile) { std::pair<int, int> match_indices = std::make_pair(-1, -1); for(int i = 0; i < borders.size(); i++) { for(int j = 0; j < other_tile.borders.size(); j++) { if(borders[i] == other_tile.borders[j] && std::find(adjecent.begin(), adjecent.end(), other_tile.id) == adjecent.end()) { adjecent.push_back(other_tile.id); other_tile.adjecent.push_back(id); match_indices = std::make_pair(id, other_tile.id); count++; other_tile.count++; return match_indices; } } } return match_indices; } void add_reversed_borders() { std::vector<std::string> reversed; for(std::string border : borders) { std::reverse(border.begin(), border.end()); reversed.push_back(border); } borders.insert(borders.begin(), reversed.begin(), reversed.end()); } }; class Decoder { public: Decoder() = default; std::vector<Tile> tiles; void add_reversing_combinations() { for(Tile& tile : tiles) { tile.add_reversed_borders(); } } // key - id, value - lines std::unordered_map<int, std::vector<std::string>> tiles_map; Decoder(std::string file_name, bool monster = false) { std::ifstream file(file_name); std::string line; Tile tile; int row = 0; std::vector<std::string> tile_map; if(file.is_open()) { while(std::getline(file, line)) { if(line.find("Tile") < SIZE_MAX) { tile = Tile(std::stoi(line.substr(line.find(" ") + 1, line.find(":") - line.find(" ") - 1))); } else if(line.empty()) { tiles.push_back(tile); tiles_map[tile.id] = tile_map; tile_map.clear(); row = 0; } else { tile_map.push_back(line); if(row == 0) tile.borders[0] = line; if(row == 9) tile.borders[1] = line; tile.borders[2] += line[0]; tile.borders[3] += line[9]; row++; } } tiles.push_back(tile); // add last tile } add_reversing_combinations(); connect_tiles(); if(monster) build_image(); } void connect_tiles() { for(Tile& tile : tiles) { for(Tile& other_tile : tiles) { if(other_tile.id == tile.id) continue; std::pair<int, int> match_ids = tile.match(other_tile); } } } void remove_borders() { // key - id, value - lines std::unordered_map<int, std::vector<std::string>> new_tiles_map; for(auto pair : tiles_map) { int tile_id = pair.first; std::vector<std::string> tile_lines = pair.second; std::vector<std::string> lines_removed_border; for(int i = 1; i < tile_lines.size() - 1; i++) { lines_removed_border.push_back(tile_lines[i].substr(1, tile_lines[i].size() - 2)); } new_tiles_map[tile_id] = lines_removed_border; } tiles_map = new_tiles_map; } std::vector<std::string> image; std::unordered_map<int, std::vector<int>> get_adjecency_map() { std::unordered_map<int, std::vector<int>> adjecency_map; for(Tile tile : tiles) { std::vector<int> adjecent; std::cout << "tile id = " << tile.id << '\n'; for(int adj : tile.adjecent) { std::cout << "adj = " << adj << '\n'; adjecent.push_back(adj); } adjecency_map[tile.id] = adjecent; std::cout << '\n'; } return adjecency_map; } void build_image() { } std::vector<int> get_corner_ids() { std::vector<int> corner_ids; for(Tile tile : tiles) { if(tile.count == 2) corner_ids.push_back(tile.id); } return corner_ids; } long long multiply_corner_tiles_id() { std::vector<int> corner_ids = get_corner_ids(); long long result = std::accumulate(std::begin(corner_ids), std::end(corner_ids), 1LL, [&](const long long previous, int id) { return previous * id; }); return result; } int count_sea_mosters() { // todo return 0; } int count_hashtag() { int count = 0; for(std::string image_row : image) { count += boost::count(image_row, '#'); } return count; } }; void part1(const std::string& file_name) { std::cout << "======\nPart 1\n======\n"; Decoder decoder(file_name); std::cout << "Multiplied IDs of the four corner = " << decoder.multiply_corner_tiles_id() << '\n'; } void part2(const std::string& file_name) { std::cout << "======\nPart 2\n======\n"; Decoder decoder(file_name, true); int sea_mosters = decoder.count_sea_mosters(); constexpr int count_monster_hashtag = 15; std::cout << decoder.count_hashtag() - count_monster_hashtag * sea_mosters << " # are not part of a sea monster\n"; } int main() { const std::string file_name = "/home/daria/Documents/AoC2020/input/day20.txt"; part1(file_name); std::cout << '\n'; part2(file_name); std::cout << '\n'; }
JavaScript
UTF-8
2,830
2.8125
3
[ "MIT" ]
permissive
function plot_time_series(name, id, refresh_interval) { var options = { lines: { show: true }, points: { show: true }, xaxis: { mode: "time" }, series: { shadowSize: 0 } // Drawing is faster without shadows }; // Initiate a recurring data update function start_updating() { var data = []; var plot = $.plot("#plot_window-" + id, data, options); var iteration = 0; function fetchData() { function onDataReceived(series) { data.push( [series.time*1000, series.data] ); if (iteration > 20) { data.shift() }; //console.log(data) plot.setData([data]); plot.setupGrid(); plot.draw(); } if ( $("#pauseIcon-"+id).attr("class").indexOf('pause') > -1 ) { ++iteration; $.ajax({ url: "/get_point", type: "GET", dataType: "json", data: { id : id }, success: onDataReceived }) } setTimeout(fetchData, refresh_interval*1000); } fetchData(); } start_updating(); } function button_ajax(id, status_indicator, extra_args) { var btn = $('#'+id); btn.button('loading'); data = { id: id }; if (extra_args != undefined) { data.extra_args = extra_args }; $.getJSON( "../button_click", data ) .done( function (json) { if (status_indicator) { $("#"+ id + "-Status").text("Status: " + json.state); } }) .fail( function () { alert("Request failed!") }) .always( function () { btn.button('reset'); }); } // return a formated string representation of a float with fiex digits of precision function toFixed(value, precision) { var precision = precision || 0, neg = value < 0, power = Math.pow(10, precision), value = Math.round(value * power), integral = String((neg ? Math.ceil : Math.floor)(value / power)), fraction = String((neg ? -value : value) % power), padding = new Array(Math.max(precision - fraction.length, 0) + 1).join('0'); return precision ? integral + '.' + padding + fraction : integral; } // take a date object and return a string in the format DDMMYYhhmmss function formatDate(d) { var DD = d.getDate() if ( DD < 10 ) DD = '0' + DD var MM = d.getMonth()+1 if ( MM < 10 ) MM = '0' + MM var YY = d.getFullYear() % 100 if ( YY < 10 ) YY = '0' + YY var hh = d.getHours() % 100 if ( hh < 10 ) hh = '0' + hh var mm = d.getMinutes() % 100 if ( mm < 10 ) mm = '0' + mm var ss = d.getSeconds() % 100 if ( ss < 10 ) ss = '0' + ss return DD+MM+YY+hh+mm+ss }
Shell
UTF-8
438
3.15625
3
[ "OFL-1.1", "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
#!/bin/bash colors="red:#cc0000 green:#00cc00 orange:#ddaa00 grey:#cccccc" for res in 16 32 64; do for color in ${colors}; do colname=${color%:*} colspec=${color#*:} convert -background none cf.svg \ +level-colors "${colspec}," \ -colorspace RGB \ -resize "${res}" \ -colorspace sRGB \ "cf-${colname}-${res}.png" done done
Python
UTF-8
350
2.796875
3
[]
no_license
import mysql.connector as mysql mydb = mysql.connect( host="localhost", user="root", passwd="", database="test" ) mycursor = mydb.cursor() sql = "insert into new (sku) values(%s)" val = [("new1001"),("new234234243"),("new12312")] print(sql, val) mycursor.executemany(sql,val) mydb.commit() print(mycursor.rowcount, ' was inserted')
Java
UTF-8
2,146
2.359375
2
[]
no_license
package nyc.c4q.contactsapp; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.makeramen.roundedimageview.RoundedTransformationBuilder; import com.squareup.picasso.Picasso; import com.squareup.picasso.Transformation; import nyc.c4q.contactsapp.model.UserDatabase; /** * A simple {@link Fragment} subclass. */ public class UserDetailFragment extends Fragment { private TextView name, cell, email; private ImageView picture; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view= inflater.inflate(R.layout.fragment_user_detail, container, false); Bundle bundle= getArguments(); UserDatabase user= null; setUpViews(view); Transformation transformation = new RoundedTransformationBuilder() .cornerRadiusDp(30) .oval(true) .build(); if (bundle!=null) { user = (UserDatabase) bundle.getSerializable("user"); String upperString = user.getFirstName().substring(0,1).toUpperCase() + user.getFirstName().substring(1) + " " + user.getLastName().substring(0,1).toUpperCase() + user.getLastName().substring(1); name.setText(upperString); cell.setText(user.getCell()); email.setText(user.getEmail()); Picasso.with(view.getContext()) .load(user.getPicture()) .transform(transformation) .into(picture); } return view; } public void setUpViews(View view) { name= view.findViewById(R.id.user_detail_name); cell= view.findViewById(R.id.user_detail_cell); email= view.findViewById(R.id.user_detail_email); picture= view.findViewById(R.id.user_detail_picture); } }
Python
UTF-8
5,216
2.796875
3
[]
no_license
import numpy as np import os import logging logger = logging.getLogger(__name__) intX = 'int32' floatX = 'float32' class POMDPEnv(object): def __init__(self, confusion_dim, num_actual_states, num_actions, good_terminal_states=9, bad_terminal_states=8, max_steps=1000): self.model = MDPUserModel(confusion_dim, num_actual_states, num_actions, make_confusion_matrix=True) self.state_buffer = self.model.state2obs(0) # current state of the environment (use self.reset) self.turn = 0 if type(good_terminal_states) is int: self.good_terminals = [good_terminal_states] else: self.good_terminals = good_terminal_states if type(bad_terminal_states) is int: self.bad_terminals = [bad_terminal_states] else: self.bad_terminals = bad_terminal_states self.max_steps = max_steps def get_observations(self): return self.state_buffer def step(self, action): self.state_buffer = self.model.step(self.state_buffer, action) self.turn += 1 return self.state_buffer, self.get_reward(), self.is_done(), {} # no additional information def reset(self, init_state=0): self.state_buffer = self.model.state2obs(init_state) self.turn = 0 def is_done(self): state = self.model.obs2state(self.state_buffer) if state in self.good_terminals or state in self.bad_terminals or self.turn >= self.max_steps: return True else: return False def get_reward(self): state = self.model.obs2state(self.state_buffer) if state in self.good_terminals: r = 30. elif state in self.bad_terminals: r = -30. else: r = -1. return r class MDPUserModel(object): def __init__(self, confusion_dim, num_actual_states, num_actions, make_confusion_matrix=False): self.num_states = num_actual_states self.num_actions = num_actions self.confusion_dim = confusion_dim self.transition_table = np.array([ [0, 0, 1], [0, 1, 2], [0, 2, 3], [1, 1, 4], [1, 2, 5], [2, 0, 4], [2, 2, 6], [3, 0, 5], [3, 1, 6], [4, 2, 7], [5, 1, 7], [6, 0, 7], [0, 3, 8], [1, 3, 8], [2, 3, 8], [3, 3, 8], [4, 3, 8], [5, 3, 8], [6, 3, 8], [7, 3, 9]], dtype='int32') if make_confusion_matrix: shape = self.num_states + self.confusion_dim shape = (shape, shape) self.randproj = np.random.uniform(-.1, .1, size=shape) np.fill_diagonal(self.randproj, 1.0) self.invrandproj = np.linalg.inv(self.randproj) np.save('confusion.npz', (self.randproj, self.invrandproj)) else: self.randproj = None self.invrandproj = None def step(self, state, action): state_id = self.obs2state(state) assert state_id < self.num_states and action < self.num_actions next_state_id = state_id for t in self.transition_table: if t[0] == state_id and t[1] == action: next_state_id = t[2] break return self.state2obs(next_state_id) def state2obs(self, s_id): s = np.zeros(self.num_states + self.confusion_dim, dtype='float32') # s[: self.confusion_dim] = numpy.random.randint(0, 2, self.confusion_dim) s[: self.confusion_dim] = np.random.uniform(-.5, .5, size=self.confusion_dim) s[self.confusion_dim + s_id] = 1. s = np.dot(self.randproj, s) return s def obs2state(self, s): s = np.dot(self.invrandproj, s) s1 = s[self.confusion_dim:] return np.argmax(s1) def write_mdp_to_dot(self, file_path='mdp.dot', overwrite=False, init_state=0, good_terminals=9, bad_terminals=8): # To save DOT files as image files use for example: $ dot -T png -O mdp.dot if type(good_terminals) is int: good_terminals = [good_terminals] if type(bad_terminals) is int: bad_terminals = [bad_terminals] if not os.path.isfile(file_path) or overwrite: with open(file_path, 'w') as writer: writer.write('digraph MDP {\n') for tr in self.transition_table: writer.write(str(tr[0]) + ' -> ' + str(tr[2]) + ' [label="a:' + str(tr[1]) + ' ; p:' + str(tr[3]) + '"];\n') writer.write(str(init_state) + " [shape=diamond,color=lightblue,style=filled]\n") for node in good_terminals: writer.write(str(node) + " [shape=box,color=green,style=filled]\n") for node in bad_terminals: writer.write(str(node) + " [shape=box,color=red,style=filled]\n") writer.write('}') else: logger.warning('File "{0}" exists. Call with `overwrite=True` to permit overwrite.'.format(file_path))
Java
UTF-8
934
2.390625
2
[ "Apache-2.0" ]
permissive
package es.tid.pce.computingEngine.algorithms; import java.util.concurrent.Callable; import es.tid.pce.computingEngine.ComputingResponse; import es.tid.pce.parentPCE.ChildPCERequestManager; import es.tid.pce.pcep.messages.PCEPRequest; import es.tid.pce.pcep.messages.PCEPResponse; public class ChildPCERequest implements Callable<ComputingResponse> { private ChildPCERequestManager childPCERequestManager; private PCEPRequest pcreq; private Object domain; public ChildPCERequest(ChildPCERequestManager childPCERequestManager, PCEPRequest pcreq, Object domain){ this.childPCERequestManager=childPCERequestManager; this.pcreq=pcreq; this.domain=domain; } public ComputingResponse call() throws Exception { ComputingResponse compResp = new ComputingResponse(); PCEPResponse p_rep = childPCERequestManager.newRequest(pcreq, domain); compResp.setResponsetList(p_rep.getResponseList()); return compResp; } }
C++
UTF-8
1,043
2.953125
3
[]
no_license
// // pathfinding library // Created by yash on 8/6/19. // #pragma once #include <cstddef> namespace pl::graph { /// pfl_graph will be the standard graph used in this library. /// @tparam Graph template<typename ContainerType, typename DataType> class graph { public: using graph_type = ContainerType; using node_type = typename ContainerType::node_type; /// Func is applied to each adjacent node of the current node /// @tparam Func template<typename Func> void for_each_adjacent_node(const node_type &node, Func &&func) const = delete; /// Func is applied to all the nodes in the graph /// @tparam Func template<typename Func> void for_each_node() const = delete; /// @tparam Tag - Property tag required by the user /// @param node - queried node /// @param tag - property tag for dispatching /// @return value of the property inquired for the node template<typename Tag> typename Tag::type get_node_property(const node_type &node, Tag&& tag) const = delete; }; }
Markdown
UTF-8
13,512
3.140625
3
[ "MIT" ]
permissive
--- layout: post title: 《有效训练你的研究能力》笔记 subtitle: 研究和学习的根本区别在于,学习最核心的部分是重复练习,而研究不是练习,更没有重复,只有不断得获取新东西。所以研究是具有艺术性的。 date: 2018-08-28 author: coding-zen header-img: img/home.jpg catalog: true tags: - 读书笔记 --- acitively making meaning, rather than just absorbing information 1.在学习的时候为了学得更好而更主动进入的对你自身来创造性的探究; 2.研究不是单纯地吸收信息。 研究和学习的根本区别在于,学习最核心的部分是重复练习,而研究不是练习,更没有重复,只有不断得获取新东西。所以研究是具有艺术性的。 ### 研究必备的三种意识 研究是为了”更好“ 这是说的“更好”,有时候是获取更扎实的知识,有时候是掌握更先进的技能。要实现这些”更好“,需要你主动系统地探究和发现。 **作品意识**:研究精神的起点 研究的第一步还不是明确研究目标,而是建立研究的驱动。研究的驱动指的就是研究的主动性,我把它成为作品意识。 一个人在开始研究之前必定会先有强烈的作品意识,这里所说的作品就是希望把一样事物做得更好,做得像个作品。在作品意识的带动之下,才有以后的整个研究。也就是说,作品意识是研究精神的起点。 对于作品意识,有的人可能会把作品这两个字想得太大了。打个比方,作品不一定是一座宏伟的建筑,它有可能是一座宏伟建筑当中一个门把手的握持感。门把手的材质形状和样式,这些都是值得我们去研究的。我举这个例子是告诉你,作品不一定是宏伟的,它也可能关注的是细节。我还想告诉你,研究是一门艺术,艺术的表现中最重要的就是细节。 我给你一个小小的建议,你平时做事的时候给自己一句暗示,告诉自己“我要从事这件事了”,不是做这件事,而是从事。仅凭这样一个词的变化,你的仪式感和作品意识就会被唤起。 **目标意识**:防止研究过程跑偏 研究中必要的第二个意识,是在研究过程中始终都要保持的,它叫目标意识。光有研究精神和作品意识,一个人很可能还会在研究的方向上跑偏,就是因为缺乏清晰的目标意识。 我在网上看到有人说自己写论文,刚写了几行字喝了两口茶,结果就突然打开维基百科认真地去查看茶叶的起源、分类和制作工艺,看了两个多小时。这是很多人在做研究的时候比较常见的分心状态,甚至已经有了拖延症的嫌疑了。你写的论文不是关于茶的起源、分类和制作工艺的,你跑去查这些资料,这叫严重跑题,是你研究的目标意识出现了问题。 怎么保持目标意识?我同样给你一个有效的建议。你在研究的过程当中要时刻盯住自己初始的研究目标,并时刻问自己,我正在做的事情会不会影响研究的主线。我建议你,用一种上帝的视角来俯视整个事情的全貌,你才能守住目标不跑偏。 **研究者一定是局外人**,人们往往容易在自己感兴趣的部分里面过度沉溺。关于这方面,我在这先不展开谈,我会在下一节的内容当中再为你细致地讲解。 **研究需要付出成本** 我为什么在这里要为你强调研究需要付出成本?就是因为如果我不为你指出你付出的研究成本太有限,你还不清楚为什么自己的研究能力差。有的时候你的研究能力差,只是因为你付出的研究成本还远远不够。 人们做研究,尤其是做学术研究需要付出大量的时间精力甚至是金钱。基于科学实验的研究,试错的成本高得很,因为实验会成百上干次的失败,研究的成本就体现在这儿。这也是为什么学习研究都需要有研究经费,一旦没有了研究经费,很多学术研究就会被搁置。从这个层面上来讲,研究的成本比学习的成本高得多。 ### 搜集资料:足量,但节制 主动性是足量的保障 怎么做到资料搜集的足量呢?两个标准。第一看你的主动性,第二看资料的宽泛性。 主动性能让你达到足量,而宽泛性能让你评判足量要足到什么程度。 什么是主动性?很简单,比如你如果问我,在互联网上进行信息搜索有哪些技巧?我倒不是不知道那些搜索的技巧,只不过要是你主动去到搜索引擎里输入关键字“搜索技巧”,或者用英文输入\"How toresearch\",你同样会得到答案,甚至会得到更多更好的答案。 宽泛性:是”有目标“的多 什么是宽泛性?我给它的具体描述是跳出单一的维度,带有目标意识的多。 人的时间精力是有限的,只有在搜集资料足量的基础上做到节制,才能让我们更有针对性地进行研究和完成研究。 要做到节制,就要用我们前面讲过的目标意识和局外意识了。你要注意了,这个节 制分为三种情况: 第一种是避免过度沉溺于文本; 在研究的执行当中,偏离了原始的研究方向这种情况是非常常见的,它不一定是一种错误,你不能说研究者缺乏研究精神。但是如果你在做研究的时候发现自己的执行力很差,可以考虑一下是不是出现了类似的情况。 第二种是对人的研究要去粉丝化; 要避免对我这个人的研究陷入一种粉丝的行为,他们就不应只看我做的东西,听我说的话。还应该跳出来看看别人对我的评价,把我和有类似特点的人进行比较,听听对我的负面评价,想想那些评价有没有道理,这样才能保持客观。 第三种是要避免情绪化。 对于所掌握的信息获得的资料产生了感情,那你的研究结论一定会出现偏差。有一些优秀的研究者往往被人说成是无情的人,而我认为无情恰恰是做研究的高贵品质。 ### 处理资料:运用批判性思维 怎么用批判性思维去处理资料,我们要把握好两个重要的方向,一个是抓本质,另一个就是找规律。 抓本质就是找不同,要找不同就需要做对比; 找规律则是求相似,要求相似就需要做类比。、 那些不同的部分,我们挑出来认清事物的本质;相同的部分,我们拿过来连接不同的事物,找到它们的规律,以求更快地认清它们。 ### 创造输出:督促研究的完成 用写作促进你的研究 好文章要有系统性 好文章要有足够的文本支撑 好文章要有严密的逻辑论证 如果你的研究让你有了新的发现和收获,你应该把它写成一篇系统的、有文本支持的、逻辑论证严密的好文章。这对你和别人都有非常大的价值。 ### 学术论文的写作要点 学术研究的四个特点 学术论文的写作要点有Validity、Reliability、Continuity和Universality。这四个词的意思是讲学术论文的正确性、可靠性、可持续性和普适性。 **增强研究的正确性** 在正式写论文前要向导师提交一个Proposal,也就是论文提案,用意是获得导师对你论文正确性的认可。提案中会呈现你的论文要研究的核心课题、论文的结构框架,以及每一部分的逻辑关系。 如果你的提案中展现的论文各部分逻辑关系有漏洞,甚至只是逻辑有些弱,你的导师就会让你重新提交一份Proposal,以确保整篇论文的Validity,也就是正确性。当获得了导师的认可后,你才可以逐步地展开论文的表述。 虽然不像学术论文的写作需要如此的严谨,但是我们在日常的工作和生活中做研究的时候,也很可能会在一开始就陷入误区。虽说研究中的主动性非常重要,但也请你记得,在研究的套路中少不了与高手探讨,跟行家请教,这样做就是为了增强我们研究的正确性。 **关注研究的可靠性** 你的论文在写作的过程中必伴随着大量的阅读和分析,每一篇正规的学术论文,无论长短,在论文后面都会有一个Reference List,也就是参考资料列表。你说我的论文可不可以不参照别人的书目或资料,单凭自己的主观表达来论述呢?对不起,不可以。 如果你单凭自己的主观表达进行论述,那你的论文的Reliability不是弱的问题,是根本没有。也就是说,在学术体系当中,你不被允许进行主观表达。 什么叫可靠性?可靠性就是你说的话得有出处。在生活中我们当然可以随意地说些自己的想法,但是在学术体系中,你在论文的写作中,几乎每一句话都要有出处。不能只是你自己的想法,而要引用别人的话。 引用到什么程度呢?我给你举个例子,比如你在你的论文中要写一句话,这句话是谁说的,哪年说的,在哪本书或是期刊或是什么其他的资料中说的,在那本书的哪一个版本的哪一页说的,你都要写清楚。所以我们经常看到一篇学术论文的几乎每一句话后面都会给一个这样的出处信息。 你可能会疑惑,如果是这样的话,那还叫我们写什么论文啊,去看他们的啊。即便如此,你做的工作也不可以被抹煞,你做的工作就是把相关课题的学术信息搜集整理起来。 事实上,论文的写作,讲究的是借力打力。因为在庞大的学术体系中,任何一个人都是微不足道的,你要将学术体系的某一个微小的分支进行那么一点点的发展,必须有扎实的根基。这个根基,就是你要有大量的学术阅读,以获得一个学术的背景。 在西方的学术体系中,本科生只是学习,很少研究。因为到了硕士,才叫研究生。跟博士研究生比起来,硕士研究生是更加不能擅自表达自己的观点的,因为你只是一个硕士研究生。硕士研究生的本分,就是把别人的学术观点研究一番,掌握了研究的方法就可以了。表达观点,那是博士研究生才可以干的事。 基于这种可靠性的要求,我们是不是就完全不能表达自己的观点呢?其实不是,但是要注意分寸。 我在英国学习学术写作的时候,老师一开始就跟我们说,在学术论文中,是绝对不可以出现“I”这个词的,就是中文里的“我”。你绝对不可以说“Ithink”或“1believe\"之类的话。如果你这么写,那么你的导师很可能会问你,“你是谁?” 事实上,你基于大量的学术阅读,把符合或者说适合你要表达的观点的内容引用出来,也就相当于我们表达了自己的观点。这就是我之前说的借力打力。 除了写学术论文,在日常的工作和生活的研究中关注可靠性有什么好处呢?这样做 会使我们随时保持警惕,当我们看到某条信息的时候,如果不是“有据可查”的,我们可以对其持怀疑态度。尤其在网上,谣言和不实信息无处不在。同时,我们也被提醒,说话和表达观点的时候,最好时时处处给出信息来源,以增强说服力。 **持续观察趋势变化** 什么叫论文的可持续性?我们阅读很多经济学和传媒学的学术论文,那些论文都是几十年前上百年前的学者写的,放在今天仍然有很强的Validity,还记得这个词吗,就是正确性。这就是论文具有一个很好的Continuity。但如果我们两年前写了一篇论文,两年后的今天看起来这篇论文就站不住脚了,那这篇论文的Continuity,可持续性就很差。 **研究的普适性** 我们在日常的工作和生活中所做的研究,大多是个性化的,凭个人兴趣和要解决的问题而做的研究。学术论文写作中的普适性,可能就不是我们日常的工作和生活中做研究需要考量的标准。 **掌握英文才能做深入研究** 如果学习英文是为了深入地做研究,最重要的是能看懂英文资料。其实简单来讲,对我们的要求就是词汇量。所以你应该从大量地积累学术词汇开始学习英文。英文学术词汇大量出现在GRE考试当中,GRE考试就是北美研究生入学考试。 我在《如何成为有效学习的高手》精品课中讲过,要去到哪里,就从哪里开始。如果你正想研究什么,发现有一些英文资料看不懂,你应该直接硬着头皮去看跟你的研究领域紧密相关的英文资料,边看边学习其中的陌生词汇,在这个环境中你才能记住那些单词。 只有直接上手接触你以为最后才要接触的东西,你才会有一种极强的成就感,才能坚持下来。一方面在研究中让你随时随地提高自己的英文水平;另一方面,这样做也不会影响你随时随地进入研究的状态。你只要翻来覆去地在你要研究的领域中接触那些英文资料,一段时间之后,你再看一篇新的英文资料,应该就不会那么困难了。 “一个具有研究能力的人,才会把事情做好。同时,他获得新机会的可能性要大一点,因为他会不停地去发现。”
JavaScript
UTF-8
1,383
2.71875
3
[]
no_license
function signUp() { var formData = new FormData(); formData.append("userPhoto", document.getElementById("userPhoto").files[0]); $.ajax({ url : '/support/profilePhoto/', data : formData, processData : false, contentType : false, type : 'POST', success : function(photo) { var employee = {}; employee.firstName = $('#firstName').val(); employee.lastName = $('#lastName').val(); employee.contactNumber = $('#contactNumber').val(); employee.email = $('#email').val(); employee.password = $('#password').val(); employee.photo = photo; employee.jobPosition = "kdjsfksdf"; var department = {}; department.id = 1; department.departmentName="1"; employee.department = department; alert(JSON.stringify(employee)); $.ajax({ type : 'POST', contentType : 'application/json', url : "/support/signup/", data : JSON.stringify(employee), success : function(result) { alert("Sucess"); } }) } }); } function signIn() { var employee = { "email" : $('#email').val(), "password" : $('#password').val(), } $.ajax({ type : 'POST', contentType : 'application/json', url : "/support/signin", data : JSON.stringify(employee), success : function(data) { $("#loginForm").attr("action", "/support/" + data); $('#loginForm').submit(); }, error : function() { alert("айайай"); } }) }
Java
UTF-8
472
2.390625
2
[]
no_license
package com.vti.entity; public class ExperienceCandidate extends Candidate{ private int expInYear; private ProSkill proSkill; public enum ProSkill{ DEV,TEST,JAVA,SQL } public ExperienceCandidate(String firstName, String lastName, String phone, String email, String passWord, Category category, int expInYear, ProSkill proSkill) { super(firstName, lastName, phone, email, passWord, category); this.expInYear = expInYear; this.proSkill = proSkill; } }
C#
UTF-8
599
2.71875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Threading.Tasks; using RESTfulWebInterface.Models; namespace RESTfulWebInterface.Tests { public static class ColorHelper { public static string ToDisplayString(this Color color) { var colorType = typeof(Color); var mi = colorType.GetMember(color.ToString()).Single(); var attr = (EnumMemberAttribute)mi.GetCustomAttributes(typeof(EnumMemberAttribute), false).Single(); return attr.Value; } } }
Python
UTF-8
870
3.671875
4
[]
no_license
#!/usr/bin/env python3 def part1(input_list): expenses = sorted(input_list) a = 0 b = len(expenses) - 1 while a < b: val1 = expenses[a] val2 = expenses[b] sum = val1 + val2 if sum == 2020: print("input = {}, val1 = {}, val2 = {}, product = {}".format(input_list, val1, val2, val1 * val2)) return elif sum < 2020: # sum too low - move 1st pointer to next highest a += 1 else: # only possibility here is sum > 2020, so sum is too high - move 2nd pointer to next lowest b -= 1 if __name__ == '__main__': file = open('../main/resources/input.txt', mode="r") ints = [] for s in file: ints.append(int(s)) part1(ints) # part1([1721, 979, 366, 299, 675, 1456]) # part1([10, 20, 1009, 4000, 3000, 1011])
Python
UTF-8
10,149
3.28125
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sat May 30 23:00:22 2020 @author: ISIL """ from preprocess import read_data, create_samples, split_data, read_vectors, read_vocab import numpy as np import datetime import random from scipy.special import expit #OVERWIEV """ hidden_layer_size/2 ≈ input_layer_size + output_layer_size ≈ (50+2)2 ≈ 100 input layer(50 nodes) --W--> hidden layer(100 nodes) --U--> output layer(2 nodes) --TRAINING-- FORWARD PROPOGITON z = Wx+b a = f(z) [tanh] y = (U.transpose)a + b2 h = g(y) [sigmoid function] E = binary cross-entropy error BACK PROPOGATION Gradients ∂E/∂W = ∂E/∂h*∂h/∂y*∂y/∂a*∂a/∂z*∂z/∂W ∂E/∂U = ∂E/∂h*∂h/∂y*∂y/∂U Gradient Descent W <- W - η*(∂E/∂W) U <- U - η*(∂E/∂U) """ # HYPERPARAMETERS input_size = 50 #size of each word vector output_size = 2 #number of classes hidden_layer_size = 100 learning_rate = 0.003 #η number_of_epochs = 100000 C = 3 #window size path = "./data" hidden_layer = np.zeros((1, hidden_layer_size)) output_layer = np.zeros((1, output_size)) #bias of hidden layer (H x 1), filled with ones b1 = np.ones((hidden_layer_size, 1)) #weight of a connection (H x Cn) W = np.random.randn(hidden_layer_size, C*input_size) #logistic regression weights(H x 1) U = np.random.rand(hidden_layer_size, 1) #functions for data isn't included in vocab.txt file def isDate(word): isDate = True try: datetime.datetime.strptime(word, '%Y-%m-%d') except ValueError: isDate = False return isDate def get_date_vector(): #embedded layer for date format data return read_vectors(path,28192) #index is chosen by using random initialization def get_random_vector(): #embedded layer for other format data random_vector = [] for i in range(input_size): random_value = round(random.uniform(-2.000000, 2.000000), 6) random_vector.append(random_value) return random_vector #function that converts strings into word vectors def embedding_layer(samples): x_list = [] for i in range(C): words = read_vocab(path) #index of the word in the file "vocab.txt" word = (samples[i]).lower() if(word == "¡s¿"): #beginning token word = "<s>" elif(word == "¡/s¿"): #end token word = "</s>" if(word in words): index = words.index(word) vector = read_vectors(path,index) x_list += vector #concatenate window elements' vectors else: if(isDate(word)): x_list += get_date_vector() else: x_list += get_random_vector() #input_layer x = np.array(x_list) x = np.reshape(x,(C*input_size,1)) #Cn x 1 return x #add a single 1 to an array def add_one(array): length = len(array) new_array = np.zeros((length+1,1)) new_array[0] = 1 for i in range(length): new_array[i+1] = array[i] #print(new_array) return new_array #f(z) = tanh(z) def activation_function(layer): return np.tanh(layer) #f'(signal) = 1-(tanh(signal)^2) def derivation_of_activation_function(signal): return 1.0 - (np.tanh(signal)**2) #binary cross-entropy error def loss_function(true_labels, probabilities): if(true_labels[0]==1): if(probabilities[0]==0): return 0 else: return -np.log(probabilities[0]) elif(true_labels[1]==1): if(probabilities[1]==0): return 0 else: return -np.log(probabilities[1]) # the derivation should be with respect to the output # -((y/y')+((1-y)/(1-y'))) #∂E/∂h def derivation_of_loss_function(true_labels, probabilities): #return -((true_labels[0]/probabilities[0])-((1-true_labels[0])/(1-probabilities[0]))) if(true_labels[0]==1): if(probabilities[0]==0): return 0 else: return -1/probabilities[0] elif(true_labels[1]==1): if(probabilities[1]==0): return 0 else: return -1/probabilities[1] #g(z) = 1/(1+e^(-z)) def sigmoid_function(z): return expit(z) #to avoid overflow expit is used #g'(z) = g(z)*(1-g(z)) def derivation_of_sigmoid_function(z): return sigmoid_function(z)*(1-sigmoid_function(z)) #W <- W - η*(∂E/∂W) #U <- U - η*(∂E/∂U) def gradient_descent(theta,deriv): # U : theta [100x1] | deriv [100x1] | layers [150x1] # W : theta [100x150] | deriv [150x1] | layers [1x150] theta = theta - (learning_rate*deriv) return theta #∂E/∂U def gradient_U(loss_signals,a): E_h = loss_signals #∂E/∂h y = np.dot((np.transpose(U)),a) #∂h/∂y = g'(y) [1x1] h_y = derivation_of_sigmoid_function(y) #∂y/∂U = a [100x1] y_U = a #∂E/∂U = ∂E/∂h*∂h/∂y*∂y/∂U [100x1] return E_h*h_y*y_U #∂E/∂W def gradient_W(loss_signals,x,a): E_h = loss_signals #∂E/∂h y = np.dot((np.transpose(U)),a) #∂h/∂y = g'(y) [1x1] h_y = derivation_of_sigmoid_function(y) #∂y/∂a = U [1x100] y_a = U z = np.add((W.dot(x)),b1) # n x 1 = (n x Cn).(Cn x 1) + (n x 1) #∂a/∂z = f'(z) [1x100] a_z = derivation_of_activation_function(z) #∂z/∂W = x.transpose [1x150] z_W = np.transpose(x) #∂E/∂W = ∂E/∂h*∂h/∂y*∂y/∂a*∂a/∂z*∂z/∂W [100x150] #∂E/∂y = ∂E/∂h*∂h/∂y [scalar] E_y = E_h*h_y #∂y/∂W = ∂y/∂a*∂a/∂z*∂z/∂W [100x150] y_W = np.dot(np.multiply(y_a,a_z),z_W) #∂E/∂W = ∂E/∂y/∂y/∂W [100x150] return np.multiply(E_y,y_W) #z = Wx+b def forward_pass(data,U,W): predictions = [] x = embedding_layer(data) #Cn x 1 U = add_one(U) #including the bias term b(2) inside U #z = Wx+b z = np.add((W.dot(x)),b1) # n x 1 = (n x Cn).(Cn x 1) + (n x 1) #a = f(z) [tanh] a = activation_function(z) # n x 1 a_1 = add_one(a) # (n+1) x 1 #h = g((U.transpose)a + b2) [sigmoid function] h = sigmoid_function(np.dot((np.transpose(U)),a_1)) # 1 x 1 predictions.append(h[0][0]) predictions.append(1-h[0][0]) return predictions, a def backward_pass(input_layer, hidden_layers , output_layer, loss_signals,U,W): x = embedding_layer(input_layer) #∂E/∂U = ∂E/∂h*∂h/∂y*∂y/∂U deriv_U = gradient_U(loss_signals,hidden_layers) #∂E/∂W = ∂E/∂h*∂h/∂y*∂y/∂a*∂a/∂z*∂z/∂W deriv_W = gradient_W(loss_signals,x,hidden_layers) theta_U = U theta_W = W #Gradient Descent #U <- U - η*(∂E/∂U) theta_U = gradient_descent(theta_U,deriv_U) #[100x1] #W <- W - η*(∂E/∂W) theta_W = gradient_descent(theta_W, deriv_W) #[1x150] return theta_U, theta_W def train(train_data, train_labels, valid_data, valid_labels): theta_U = U theta_W = W for epoch in range(number_of_epochs): index = 0 #for each batch for data, labels in zip(train_data, train_labels): predictions, hidden_layers = forward_pass(data,theta_U,theta_W) loss_signals = derivation_of_loss_function(labels, predictions) theta_U, theta_W = backward_pass(data, hidden_layers, predictions, loss_signals,theta_U,theta_W) loss = loss_function(labels, predictions) if index%20000 == 0: # at each 20000th sample, we run validation set to see our model's improvements accuracy, loss = test(valid_data, valid_labels,theta_U,theta_W) print("Epoch= "+str(epoch)+", Coverage= %"+ str(100*(index/len(train_data))) + ", Accuracy= "+ str(accuracy) + ", Loss= " + str(loss)) index += 1 def test(test_data, test_labels,U,W): avg_loss = 0 predictions = [] labels = [] theta_U = U theta_W = W #for each batch for data, label in zip(test_data, test_labels): prediction, hidden_layers = forward_pass(data,theta_U,theta_W) predictions.append(prediction) labels.append(label) avg_loss += np.sum(loss_function(label, prediction)) #turn predictions into one-hot encoded one_hot_predictions = np.zeros(shape=(len(predictions), output_size)) for i in range(len(predictions)): one_hot_predictions[i][np.argmax(predictions[i])] = 1 predictions = one_hot_predictions accuracy_score = accuracy(labels, predictions) return accuracy_score, avg_loss / len(test_data) def accuracy(true_labels, predictions): true_pred = 0 for i in range(len(predictions)): if np.argmax(predictions[i]) == np.argmax(true_labels[i]): # if 1 is in same index with ground truth true_pred += 1 return true_pred / len(predictions) if __name__ == "__main__": #PROCESS THE DATA words, labels = read_data(path) sentences = create_samples(words, labels) train_x, train_y, test_x, test_y = split_data(sentences) # creating one-hot vector notation of labels. (Labels are given numeric) # [0 1] is PERSON # [1 0] is not PERSON new_train_y = np.zeros(shape=(len(train_y), output_size)) new_test_y = np.zeros(shape=(len(test_y), output_size)) for i in range(len(train_y)): new_train_y[i][int(train_y[i])] = 1 for i in range(len(test_y)): new_test_y[i][int(test_y[i])] = 1 train_y = new_train_y test_y = new_test_y # Training and validation split. (%80-%20) valid_x = np.asarray(train_x[int(0.8*len(train_x)):-1]) valid_y = np.asarray(train_y[int(0.8*len(train_y)):-1]) train_x = np.asarray(train_x[0:int(0.8*len(train_x))]) train_y = np.asarray(train_y[0:int(0.8*len(train_y))]) train(train_x, train_y, valid_x, valid_y) print("Test Scores:") print(test(test_x, test_y,U,W))
C++
UTF-8
8,208
2.671875
3
[]
no_license
#include "PVPathTransform.hh" #include <sstream> #include <exception> #include <stdexcept> #include <algorithm> #include <iterator> #include "G4LogicalVolume.hh" #include "G4VPhysicalVolume.hh" #include "G4PhysicalVolumeStore.hh" #include "globals.hh" #include "G4TransportationManager.hh" #include "G4Navigator.hh" PVPathTransform::Path2Trans PVPathTransform::s_p2t; PVPathTransform::Path2PV PVPathTransform::s_p2pv; std::vector<std::string> PVPathTransform::parsePath(std::string path) { std::vector<std::string> result; if(not path.size()) { return result; } if(path[0] != '/') { return result; } std::stringstream ss(path); std::string item; char c; ss.get(c); while(std::getline(ss, item, '/')) { result.push_back(item); } return result; } std::vector<G4VPhysicalVolume*> PVPathTransform::convertPathToPV(const std::vector<std::string>& path) { std::vector<G4VPhysicalVolume*> result; std::vector<std::string>::const_iterator it=path.begin(), end=path.end(); G4PhysicalVolumeStore* pvs = G4PhysicalVolumeStore::GetInstance(); G4VPhysicalVolume* tmp_pv=NULL; for (; it != end; ++it) { G4cout << *it << G4endl; tmp_pv = pvs->GetVolume(*it); if (tmp_pv) { result.push_back(tmp_pv); } else { // Throw exception throw new std::runtime_error("Can't find the PV: "+*it); } } return result; } G4AffineTransform PVPathTransform::getGTL(const std::vector<G4VPhysicalVolume*>& pv) { G4AffineTransform result; // 0. check size of pv if (not pv.size()) { return result; } // TODO // 1. check the first pv is world G4Navigator* nav = G4TransportationManager::GetTransportationManager() ->GetNavigatorForTracking(); G4VPhysicalVolume* world = nav->GetWorldVolume(); if (pv[0] != world) { throw new std::runtime_error("The '"+pv[0]->GetName()+"' is not world PV"); } // 2. check the relation between pv for (int i=0; i<pv.size()-1; ++i) { G4LogicalVolume* lv = pv[i]->GetLogicalVolume(); // TODO // we can use IsAncestor to skip pvs' name if (lv->IsDaughter(pv[i+1])) { // It's OK } else { throw new std::runtime_error("The '"+pv[i+1]->GetName() +"' is not the daughter of PV " +pv[i]->GetName()); } } // 3. compute the affine transform // From the second PV for (int i=1; i<pv.size(); ++i) { result.InverseProduct(G4AffineTransform(result), // previous G4AffineTransform( // current pv[i]->GetRotation(), pv[i]->GetTranslation() )); } return result; } void PVPathTransform::quick_test() { std::string path = "/expHall/PMTTube_1"; std::vector<std::string> result_path = parsePath(path); std::vector<G4VPhysicalVolume*> result_pv = convertPathToPV(result_path); G4AffineTransform gtl = getGTL(result_pv); // global to local G4cout << "Global to Local:" << G4endl; G4ThreeVector tvg(0,0,10.0*m+68.5*cm/2); G4cout << "Global: "<< tvg << G4endl; gtl.ApplyPointTransform(tvg); G4cout << "Local:" << tvg << G4endl; // local to global G4cout << "Local to Global:" << G4endl; G4ThreeVector tvl(0,0,0); G4cout << "Local:" << tvl << G4endl; gtl.Inverse().ApplyPointTransform(tvl); G4cout << "Global:" << tvl << G4endl; G4ThreeVector tv(0,0,0); G4AffineTransform gtl2 = quick_test_2(path); show_test_info(gtl2, tv); G4AffineTransform gtl3 = quick_test_2(path); show_test_info(gtl3, tv); G4AffineTransform gtl4 = quick_test_2(path); show_test_info(gtl4, tv); std::string path2 = "/expHall/PMTTube_2"; G4AffineTransform gtl5 = quick_test_2(path2); show_test_info(gtl5, tv); G4AffineTransform gtl6 = quick_test_2(path2); show_test_info(gtl6, tv); G4AffineTransform gtl7 = quick_test_2(path2); show_test_info(gtl7, tv); } G4AffineTransform PVPathTransform::GlobalToLocal(const std::string& path) { std::vector<std::string> result_path = parsePath(path); std::vector<G4VPhysicalVolume*> result_pv = convertPathToPV(result_path); G4AffineTransform gtl = getGTL(result_pv); return gtl; } G4AffineTransform PVPathTransform::LocalToGlobal(const std::string& path) { return GlobalToLocal(path).Inverse(); } G4AffineTransform PVPathTransform::quick_test_2(const std::string& path) { //std::string path = "/World/SteelBall/LS/Module_3/PMT_5"; //std::string path = "/expHall/PMTTube_1"; std::string exists_path; std::vector<std::string> residual_path; bool exists = checkInCache(path, exists_path, residual_path); G4cout << "Exists Path: " << exists_path << G4endl; if (residual_path.size()) { std::copy(residual_path.begin(), residual_path.end(), std::ostream_iterator<std::string>(G4cout, " ")); G4cout << std::endl; } // Begin to get the transform G4VPhysicalVolume* volume_start = NULL; G4VPhysicalVolume* tmp_pv = NULL; G4AffineTransform at_start; if (exists) { volume_start = s_p2pv[exists_path]; at_start = s_p2t[exists_path]; } G4PhysicalVolumeStore* pvs = G4PhysicalVolumeStore::GetInstance(); // Loop the residual path while(residual_path.size()) { std::string current_base = residual_path.back(); residual_path.pop_back(); tmp_pv = pvs->GetVolume(current_base); if (volume_start==NULL) { // check tmp_pv is world? } else { // check whether volume_start is the mother of tmp_pv G4LogicalVolume* lv = volume_start->GetLogicalVolume(); // TODO // we can use IsAncestor to skip pvs' name if (lv->IsDaughter(tmp_pv)) { // It's OK } else { throw new std::runtime_error("The '"+tmp_pv->GetName() +"' is not the daughter of PV " +volume_start->GetName()); } } at_start.InverseProduct( G4AffineTransform(at_start), G4AffineTransform( tmp_pv->GetRotation(), tmp_pv->GetTranslation() ) ); exists_path += "/"+current_base; s_p2t[exists_path] = at_start; s_p2pv[exists_path] = tmp_pv; volume_start = tmp_pv; } return at_start; } // return true if find the exists_path in cache // else return false bool PVPathTransform::checkInCache(const std::string& input_path, std::string& exists_path, std::vector<std::string>& residual_path) { bool result = false; std::string path = input_path; std::string base; while(path.size()>1) { // 0. the path starts with '/' // 1. check the path exists in cache if (s_p2t.count(path)) { exists_path = path; result = true; break; } // 2. get the dirname of path unsigned found = path.find_last_of('/'); if (found == std::string::npos or found > path.size()) { // can't find any more break; } base = path.substr(found+1); G4cout << __LINE__ << " BASE: " << base << G4endl; residual_path.push_back(base); path = path.substr(0, found); G4cout << __LINE__ << " PATH: " << path << G4endl; } return result; } void PVPathTransform::show_test_info(const G4AffineTransform& gtl, G4ThreeVector tv) { // local to global G4cout << "Local to Global:" << G4endl; G4cout << "Local:" << tv << G4endl; gtl.Inverse().ApplyPointTransform(tv); G4cout << "Global:" << tv << G4endl; }
Go
UTF-8
839
3.09375
3
[]
no_license
package main import ( "fmt" "html/template" "log" "net/http" ) func index(w http.ResponseWriter, r *http.Request) { t, _ := template.ParseFiles("index.html") t.Execute(w, nil) } func login(w http.ResponseWriter, r *http.Request) { fmt.Println("method:", r.Method) //get request method if r.Method == "GET" { t, _ := template.ParseFiles("login.html") t.Execute(w, nil) } else { r.ParseForm() // logic part of log in fmt.Println("username:", r.Form["user"]) fmt.Println("password:", r.Form["pw"]) } } func main() { http.HandleFunc("/", index) // setting router rule http.HandleFunc("/login", login) err := http.ListenAndServe(":9090", nil) // setting listening port if err != nil { log.Fatal("ListenAndServe: ", err) } }
Python
UTF-8
5,966
2.84375
3
[]
no_license
from typing import List, Dict import numpy from overrides import overrides from spacy.tokens import Doc from allennlp.common.util import JsonDict, sanitize, group_by_count from allennlp.predictors.predictor import Predictor from allennlp.data import DatasetReader, Instance from allennlp.models import Model from allennlp.data.tokenizers import Token from allennlp.data.tokenizers.word_splitter import SpacyWordSplitter from id_nominal.nombank_reader import separate_hyphens @Predictor.register("nombank-id") class NominalIdPredictor(Predictor): """ Predictor for the nominal BERT-based ID model. """ def __init__( self, model: Model, dataset_reader: DatasetReader, language: str="en_core_web_sm" ) -> None: super().__init__(model, dataset_reader) self._tokenizer = SpacyWordSplitter(language=language, pos_tags=True) def predict(self, sentence: str) -> JsonDict: """ Predicts the semantic roles of the supplied sentence, with respect to a nominal, and returns a dictionary with the results: ``` {"words": [...], "nominals": [...]} ``` # Parameters sentence: `str` The sentence to identify nominal predicates from. # Returns A dictionary representation of the nominal identifications of the sentence. """ # TODO replace all parentheses and other brackets? maybe tokenizer already does it? return self.predict_json({"sentence": sentence}) def predict_tokenized(self, tokenized_sentence: List[str]) -> JsonDict: """ # Parameters tokenized_sentence: `List[str]` The sentence tokens to parse. # Returns A dictionary representation of the nominal semantic roles of the sentence. """ spacy_doc = Doc(self._tokenizer.spacy.vocab, words=tokenized_sentence) for pipe in filter(None, self._tokenizer.spacy.pipeline): pipe[1](spacy_doc) tokens = [token for token in spacy_doc] instances = self.tokens_to_instances(tokens) if not instances: return sanitize({"nominals": [], "words": tokens}) return self.predict_instances(instances) @overrides def _json_to_instance(self, json_dict: JsonDict): raise NotImplementedError("The SRL mdel uses a different API for creating instances.") def tokens_to_instances(self, tokens): """ # Parameters tokens: `List[Token]`, required List of tokens of the original sentence, before hyphenated separation. """ words = [token.text for token in tokens] new_sentence, new_indices = separate_hyphens(words) new_tokens = [Token(t) for t in new_sentence] instances: List[Instance] = [] for i, word in enumerate(tokens): instance = self._dataset_reader.text_to_instance(tokens, new_tokens) instances.append(instance) return instances def _sentence_to_srl_instances(self, json_dict: JsonDict) -> List[Instance]: """ Need to run model forward for every detected nominal in the sentence, so for a single sentence, generate a `List[Instance]` where the length of the ilist corresponds to the number of nominals in the sentence. Expects input in the original format, and dehyphenates it to return instances. # Parameters json_dict: `JsonDict`, required This JSON must look like `{"sentence": "... "}`. # Returns instances: `List[Instance]` One instance per nominal. """ sentence = json_dict["sentence"] tokens = self._tokenizer.split_words(sentence) return self.tokens_to_instances(tokens) @overrides def predict_batch_json(self, inputs: List[JsonDict]) -> List[JsonDict]: """ Perform JSON-to-JSON predition. """ batch_size = len(inputs) instances_per_sentence = [self._sentence_to_srl_instances(json) for json in inputs] flattened_instances = [ instance for sentence_instances in instances_per_sentence for instance in sentence_instances ] if not flattened_instances: return sanitize( [{"nominals": [], "words": self._tokenizer.split_words(x["sentence"])} for x in inputs] ) # Batch instances and check last batch for padded elements if number of instances # is not a perfect multiple of the batch size. batched_instances = group_by_count(flattened_instances, batch_size, None) batched_instances[-1] = [ instance for instance in batched_instances[-1] if instance is not None ] outputs: List[Dict[str, numpy.ndarray]] = [] for batch in batched_instances: outputs.extend(self._model.forward_on_instances(batch)) return_dicts: List[JsonDict] = [{"words": output["words"] ,"nominals": output["predicate_indicator"]} for output in outputs] return sanitize(return_dicts) def predict_instances(self, instances: List[Instance]) -> JsonDict: """ Perform prediction on instances of batch. """ outputs = self._model.forward_on_instances(instances) results = {"nominals": outputs[0]["predicate_indicator"], "words": outputs[0]["words"]} return sanitize(results) @overrides def predict_json(self, inputs: JsonDict) -> JsonDict: """ Perform JSON-to-JSON prediction. Mainly just wraps work done by other functions. """ instances = self._sentence_to_srl_instances(inputs) if not instances: return sanitize({"nominals": [], "words": self._tokenizer.split_words(inputs["sentence"])}) return self.predict_instances(instances)
Markdown
UTF-8
2,494
2.546875
3
[ "MIT" ]
permissive
--- author: "Simon Dellicour" date: 2023-01-23T12:00:00+02:00 title: "Our new study about the atypically pathogenic H3N1 avian influenza epidemic that occurred in 2019 in Belgium" --- The high economic impact and zoonotic potential of avian influenza call for detailed investigations of dispersal dynamics of epidemics. We integrated phylogeographic and epidemiologic analyses to investigate the dynamics of an H3N1 low pathogenic avian influenza epidemic that occurred in Belgium during 2019. Virus genomes from 104 clinical samples originating from 85% of affected farms were sequenced. A spatially-explicit phylogeographic analysis confirmed a dominating northeast to southwest dispersal direction and a long-distance dispersal event linked to direct live animal transportation between farms. Spatiotemporal clustering, transport, and social contacts strongly correlated with the phylogeographic pattern of the epidemic. We only detected a limited association between wind direction and direction of viral lineage dispersal. Our results highlight the multifactorial nature of avian influenza epidemics and illustrate the use of genomic analyses of virus dispersal to complement epidemiologic and environmental data, improve knowledge of avian influenza epidemiologic dynamics, and enhance control strategies. ![Figure Map](/images/Figure_H3N1.png) <span style="font-size:0.85em;">**Figure 2: analysis of the phylogenetic signal associated with 3 covariates in study combining phylogeographic analyses and epidemiologic contact tracing to characterize atypically pathogenic H3N1 avian influenza epidemic, Belgium, 2019.** A We assessed the phylogenetic signal associated with 3 covariates: (A) spatiotemporal SaTScan clusters (obtained by using SaTScan, https://www.SaTScan.org), (B) transport contact networks, and (C) social contact networks. Tree tip nodes are colored on the basis of the cluster or network to which they belong. For each covariate, we also report the estimated Blomberg’s K statistic and associated 95% highest posterior density interval (in parentheses) and Bayes factor (BF) support.</span> Reference: Van Borm S\*, Boseret G\*, Dellicour S\*, Steensels M, Roupie V, Vandenbussche F, Mathijs E, Vilain A, Driesen M, Dispas M, Delcloo AW, Lemey P, Mertens I, Gilbert M, Lambrecht B, van den Berg T (2023). Combined phylogeographic analyses and epidemiologic contact tracing to characterize atypically pathogenic avian influenza (H3N1) epidemic, Belgium, 2019. *Emerging Infectious Diseases* 29: 351. (*) denotes equal contribution
Java
UTF-8
1,457
3.265625
3
[]
no_license
package us.costan.watchy.flashcards.dummy; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Helper class for providing sample prompt for user interfaces created by * Android template wizards. * <p/> * TODO: Replace all uses of this class before publishing your app. */ public class FlashCardContent { /** * An array of sample (dummy) items. */ public static List<FlashCard> ITEMS = new ArrayList<FlashCard>(); /** * A map of sample (dummy) items, by ID. */ public static Map<String, FlashCard> ITEM_MAP = new HashMap<String, FlashCard>(); static { // Add 3 sample cards. addItem(new FlashCard("1", "Romania", "Bucharest")); addItem(new FlashCard("2", "America", "Washington DC")); addItem(new FlashCard("3", "Korea", "Seoul")); } private static void addItem(FlashCard item) { ITEMS.add(item); ITEM_MAP.put(item.id, item); } /** * A flash card has a prompt and a correct answer. */ public static class FlashCard { public String id; public String prompt; public String answer; public FlashCard(String id, String prompt, String answer) { this.id = id; this.prompt = prompt; this.answer = answer; } @Override public String toString() { return prompt; } } }
Markdown
UTF-8
1,548
2.515625
3
[]
no_license
# Getting the message across {#getting-the-message-across} _Date posted: 9 June 2010_ Until fairly recently, organisations have relied on a hierarchical approach to communication. The message cascades down through the layers until it hits the bottom. We know that this message usually gets diluted, so we come up with strategies to help, like having centrally controlled online or printed content. However, this approach can't continue. As soon as people were able to connect with each other independently of the organisation, the hierarchy crumbled. The (very) short presentation below illustrates the problem, and suggests a solution. Slide 3 is the interesting one - you could spend some time just looking at the different scenarios that are shown just on that one screen.**[Getting message across](http://www.slideshare.net/berthelemy/getting-message-across)** **Illegal HTML tag removed :** <param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=gettingmessageacross-100609090553-phpapp01&amp;stripped_title=getting-message-across"><param name="allowFullScreen" value="true"><param name="allowScriptAccess" value="always"><embed name="__sse4451972" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=gettingmessageacross-100609090553-phpapp01&amp;stripped_title=getting-message-across" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"> View more [presentations](http://www.slideshare.net/) from [Mark Berthelemy](http://www.slideshare.net/berthelemy).
C#
UTF-8
2,883
2.59375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WordMemory.DAL; using WordMemory.DTO; using WordMemory.Model; namespace WordMemory.BLL { public class PracticeDetailController { PracticeDetailManagement _practiceDetailManagement; public PracticeDetailController() { _practiceDetailManagement = new PracticeDetailManagement(); } //public bool Add(PracticeDetail practiceDetail, PracticeDetailDTO practiceDetailDto) //{ // List<PracticeDetail> practicedetail = _practiceDetailManagement.GetAllPracticeDetails(); // practiceDetail.PracticeID = practiceDetailDto.PracticeID; // practiceDetail.WordPoolID = practiceDetailDto.WordPoolID; // practiceDetail.WordID = practiceDetailDto.WordID; // return _practiceDetailManagement.Insert(practiceDetail) > 0; //} public bool Add(PracticeDetail practiceDetail) { return _practiceDetailManagement.Insert(practiceDetail) > 0; } public PracticeDetail GetPracticeDetailByPracticeDetailID(int practiceDetailID) { return _practiceDetailManagement.GetPracticeDetailsByPracticeDetailID(practiceDetailID); } public List<PracticeDetail> GetPracticeDetailByPracticeID(Guid practiceID) { List<PracticeDetail> practiceDetail = new List<PracticeDetail>(); foreach (var item in _practiceDetailManagement.GetAllPracticeDetails()) { if (practiceID==item.PracticeID) { practiceDetail.Add(item); } } return practiceDetail; } public List<PracticeDetail> GetPracticeDetailByWordPoolID(Guid wordPoolID) { List<PracticeDetail> practiceDetail = new List<PracticeDetail>(); foreach (var item in _practiceDetailManagement.GetAllPracticeDetails()) { if (wordPoolID == item.WordPoolID) { practiceDetail.Add(item); } } return practiceDetail; } public List<PracticeDetail> GetPracticeDetailByUserID(Guid wordID) { List<PracticeDetail> practiceDetail = new List<PracticeDetail>(); foreach (var item in _practiceDetailManagement.GetAllPracticeDetails()) { if (wordID == item.WordID) { practiceDetail.Add(item); } } return practiceDetail; } public List<PracticeDetail> GetAllPracticeDetails() { return _practiceDetailManagement.GetAllPracticeDetails(); } } }
JavaScript
UTF-8
7,086
2.875
3
[]
no_license
let addBtn = document.querySelector(".add-btn"); let removeBtn = document.querySelector(".remove-btn"); let modalCont = document.querySelector(".modal-cont"); let mainCont = document.querySelector(".main-cont"); let textArea = document.querySelector(".textarea-cont"); let allPriorityColors = document.querySelectorAll(".priority-color"); let toolboxColors = document.querySelectorAll(".color"); let colors = ["lightpink" , "lightblue" , "lightgreen" , "black"]; let modalPriorityColor = colors[colors.length - 1]; let addFlag = false; let removeFlag = false; let lockClass = "fa-lock"; let unlockClass = "fa-lock-open"; let ticketsArr = []; // CHECK IF ANY DATA IS PRESENT IN LOCAL STORAGE THEN DISPLAY IT FIRST if(localStorage.getItem("Jira_Tickets")){ // RETRIEVE & DISPLAY TICKETS let newArr = JSON.parse(localStorage.getItem("Jira_Tickets")); newArr.forEach((ticketObj) =>{ createTicket(ticketObj.ticketColor , ticketObj.ticketTask , ticketObj.ticketID); }); } // for filtering colors from toolbox on click and double click for(let i = 0 ; i < toolboxColors.length ; i++){ toolboxColors[i].addEventListener("click" , function(e){ let currentToolboxColor = toolboxColors[i].classList[0]; console.log(currentToolboxColor); let allTicketsCont = document.querySelectorAll(".ticket-cont"); for(let i = 0 ; i < allTicketsCont.length ; i++){ let ticketheadercolor = allTicketsCont[i].querySelector(".ticket-color"); let currentTicketColor = ticketheadercolor.classList[1]; console.log(currentTicketColor); if(currentTicketColor == currentToolboxColor){ allTicketsCont[i].style.display = "block"; }else{ allTicketsCont[i].style.display = "none"; } } }) toolboxColors[i].addEventListener("dblclick" , function(e){ let allTicketsCont = document.querySelectorAll(".ticket-cont"); for(let i = 0 ; i < allTicketsCont.length ; i++){ allTicketsCont[i].style.display = "block"; } }) } // Listener for modal priority coloring for(let i = 0 ; i < allPriorityColors.length ; i++){ allPriorityColors[i].addEventListener("click" , function(e){ for(let j = 0 ; j < allPriorityColors.length ; j++){ allPriorityColors[j].classList.remove("border"); } allPriorityColors[i].classList.add("border"); modalPriorityColor = allPriorityColors[i].classList[0]; }) } // adding a new ticket addBtn.addEventListener("click" , function(e){ // display modal // generate ticket //addFlag -> false -> Modal none //addFlag -> true -> Modal display addFlag = !addFlag; // console.log(addFlag); if(addFlag == true){ modalCont.style.display = "flex"; }else{ modalCont.style.display = "none"; } }) // removing a ticket removeBtn.addEventListener("click" , function(e){ removeFlag = !removeFlag; }) modalCont.addEventListener("keydown" , function(e) { // console.log(e); let key = e.key; if(key === "Shift"){ createTicket(modalPriorityColor , textArea.value , shortid()); setModalToDefault(); addFlag = false; } }) // creating a ticket function createTicket(ticketColor , ticketTask , ticketID) { let ticketCont = document.createElement("div"); ticketCont.setAttribute("class", "ticket-cont"); ticketCont.innerHTML = ` <div class="ticket-color ${ticketColor}"></div> <div class="ticket-id">#${ticketID}</div> <div class="task-area">${ticketTask}</div> <div class="ticket-lock"> <i class="fa-solid fa-lock"></i> </div> `; ticketsArr.push({ticketColor , ticketTask , ticketID}); localStorage.setItem("Jira_Tickets" , JSON.stringify(ticketsArr)); mainCont.appendChild(ticketCont); handleRemove(ticketCont , ticketID); handleLock(ticketCont , ticketID); handleColor(ticketCont , ticketID); } // removing a ticket function handleRemove(ticket , id){ // remove flag -> true -> remove ticket.addEventListener("click" , function(e){ if(removeFlag == true){ // DB REMOVAL let ticketIdx = getTicketIdx(id); ticketsArr.splice(ticketIdx , 1); let strTicketsArr = JSON.stringify(ticketsArr); localStorage.setItem("Jira_Tickets" , strTicketsArr); ticket.remove(); // UI REMOVAL } // removeFlag = false; }) } // handling lock/unlock for a ticket(if unlock -> content edit possible otherwise not) function handleLock(ticket , id){ let ticketlockElem = ticket.querySelector(".ticket-lock"); let ticketLock = ticketlockElem.children[0]; let ticketTaskArea = ticket.querySelector(".task-area"); ticketLock.addEventListener("click" , function(e){ // get ticket idx for local storage let ticketIdx = getTicketIdx(id); if(ticketLock.classList.contains(lockClass)){ ticketLock.classList.remove(lockClass); ticketLock.classList.add(unlockClass); ticketTaskArea.setAttribute("contenteditable" , "true"); }else{ ticketLock.classList.remove(unlockClass); ticketLock.classList.add(lockClass); ticketTaskArea.setAttribute("contenteditable" , "false"); } //Modify data in local storage ticketsArr[ticketIdx].ticketTask = ticketTaskArea.innerText; localStorage.setItem("Jira_Tickets" , JSON.stringify(ticketsArr)); }) } // changing ticket color by clicking on top of ticket container(in ticket color cont. function handleColor(ticket , id){ let ticketColor = ticket.querySelector(".ticket-color"); ticketColor.addEventListener("click" , function(e){ // function tp get ticket idx for local storage let ticketIdx = getTicketIdx(id); let currentTicketColor = ticketColor.classList[1]; let idx = colors.indexOf(currentTicketColor); let nextIdx = (idx + 1) % colors.length; let nextTicketColor = colors[nextIdx]; ticketColor.classList.remove(currentTicketColor); ticketColor.classList.add(nextTicketColor); // modify data in local storage ticketsArr[ticketIdx].ticketColor = nextTicketColor; localStorage.setItem("Jira_Tickets" , JSON.stringify(ticketsArr)); }) } function getTicketIdx(id){ let ticketIdx = ticketsArr.findIndex(function(ticketObj){ return ticketObj.ticketID === id; }) return ticketIdx; } // setting modal to default function setModalToDefault(){ removeFlag = false; modalCont.style.display = "none"; textArea.value = ""; modalPriorityColor = colors[colors.length - 1]; for(let i = 0 ; i < allPriorityColors.length ; i++){ allPriorityColors[i].classList.remove("border"); } allPriorityColors[allPriorityColors.length - 1].classList.add("border"); }
C++
UTF-8
749
2.828125
3
[ "Apache-2.0" ]
permissive
#include "SkTypes.h" #include <stdio.h> #include <stdlib.h> void sk_throw() { SkASSERT(!"sk_throw"); abort(); } void sk_out_of_memory(void) { SkASSERT(!"sk_out_of_memory"); abort(); } void* sk_malloc_throw(size_t size) { return sk_malloc_flags(size, SK_MALLOC_THROW); } void* sk_realloc_throw(void* addr, size_t size) { void* p = realloc(addr, size); if (size == 0) { return p; } if (p == NULL) { sk_throw(); } return p; } void sk_free(void* p) { if (p) { free(p); } } void* sk_malloc_flags(size_t size, unsigned flags) { void* p = malloc(size); if (p == NULL) { if (flags & SK_MALLOC_THROW) { sk_throw(); } } return p; }
Shell
UTF-8
941
3
3
[ "MIT" ]
permissive
#!/bin/bash # source: https://medium.com/@trstringer/create-kubernetes-controllers-for-core-and-custom-resources-62fc35ad64a3 set -e # ROOT_PACKAGE :: the package (relative to $GOPATH/src) that is the target for code generation ROOT_PACKAGE="github.com/dgkanatsios/azuregameserversscalingkubernetes" # CUSTOM_RESOURCE_NAME :: the name of the custom resource that we're generating client code for CUSTOM_RESOURCE_NAME="azuregaming" # CUSTOM_RESOURCE_VERSION :: the version of the resource CUSTOM_RESOURCE_VERSION="v1alpha1" # retrieve the code-generator scripts and bins # go get -u k8s.io/code-generator/... # cd $GOPATH/src/k8s.io/code-generator cd .. dep ensure cd vendor/k8s.io/code-generator # run the code-generator entrypoint script ./generate-groups.sh all "$ROOT_PACKAGE/pkg/client" "$ROOT_PACKAGE/pkg/apis" "$CUSTOM_RESOURCE_NAME:$CUSTOM_RESOURCE_VERSION" # view the newly generated files #tree $GOPATH/src/$ROOT_PACKAGE/client
C#
UTF-8
4,288
2.578125
3
[ "MIT" ]
permissive
#if NETCOREAPP3_0_OR_GREATER using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using X10D.CompilerServices; namespace X10D.Text; /// <summary> /// Text-related extension methods for <see cref="Rune" />. /// </summary> public static class RuneExtensions { /// <summary> /// Returns a value indicating whether this rune constitutes an emoji. /// </summary> /// <param name="value">The rune to check.</param> /// <returns><see langword="true" /> if this rune is an emoji; otherwise, <see langword="false" />.</returns> [Pure] [MethodImpl(CompilerResources.MethodImplOptions)] public static bool IsEmoji(this Rune value) { return value.ToString().IsEmoji(); } /// <summary> /// Returns a string composed of the current rune repeated a specified number of times. /// </summary> /// <param name="value">The rune to repeat.</param> /// <param name="count">The number of times to repeat.</param> /// <returns> /// A <see cref="string" /> composed of <paramref name="value" /> repeated <paramref name="count" /> times. /// </returns> [Pure] [MethodImpl(CompilerResources.MethodImplOptions)] public static string Repeat(this Rune value, int count) { switch (count) { case < 0: throw new ArgumentOutOfRangeException(nameof(count), ExceptionMessages.CountMustBeGreaterThanOrEqualTo0); case 0: return string.Empty; case 1: return value.ToString(); } int length = value.Utf8SequenceLength; // Helpful documentation: https://en.wikipedia.org/wiki/UTF-8 // This probably gonna break interning but whatever. switch (length) { case 1: { // Codepoint 0 to 0x00FF can be directly turn into char value without any conversion. return new string((char)value.Value, count); } // Codepoint 0x0080 to 0x07FF takes 2 UTF-8 bytes, and it can be represented by 1 UTF-16 character (.NET runtime use // UTF-16 encoding). // Source: https://stackoverflow.com/questions/63905684 case 2: // Codepoint 0x0800 to 0xFFFF takes 3 UTF-8 bytes, and can also be represented by 1 UTF-16 character. case 3: { // Codepoint 0x0080 to 0x07FF convert into 1 .NET character string, directly use string constructor. unsafe { Span<byte> bytes = stackalloc byte[length]; value.EncodeToUtf8(bytes); char character; Encoding.UTF8.GetChars(bytes, new Span<char>(&character, 1)); return new string(character, count); } } // Codepoint 0x10000 and beyond will takes **only** 2 UTF-16 character. case 4: { return string.Create(count * 2, value, (span, _) => { unsafe { Span<byte> bytes = stackalloc byte[4]; value.EncodeToUtf8(bytes); int characters; // 2 characters, fit inside 1 32-bit integer. Encoding.UTF8.GetChars(bytes, new Span<char>(&characters, 2)); MemoryMarshal.Cast<char, int>(span).Fill(characters); } }); } // dotcover disable //NOSONAR default: string exceptionFormat = ExceptionMessages.UnexpectedRuneUtf8SequenceLength; string message = string.Format(CultureInfo.CurrentCulture, exceptionFormat, length); #if NET7_0_OR_GREATER throw new UnreachableException(message); #else throw new InvalidOperationException(message); #endif //NOSONAR // dotcover enable } } } #endif
PHP
UTF-8
582
2.515625
3
[]
no_license
<?php namespace App\Controller\PrivateRest; use Cake\Http\Exception\UnauthorizedException; class UsersController extends PrivateRestController { public function view($login) { $loggedUser = $this->Authentication->getIdentity(); if ($loggedUser->username !== $login) { throw new UnauthorizedException(__('No puedes ver el usuario solicitado')); } else { $user = $this->Users->get($login); $this->set(compact('user')); $this->viewBuilder()->setOption('serialize', ['user']); } } } ?>
JavaScript
UTF-8
2,184
2.5625
3
[ "MIT" ]
permissive
import { isObject } from './helpers'; import React from 'react'; export function prepareTag(tag) { prepareStyle(tag); prepareClass(tag); return tag; } function prepareStyle(tag){ var position = getPosition(tag.row, tag.column); if(!position.top){ position.top = 0; } if(!position.left){ position.left = 0; } var style = { top: position.top, left: position.left }; if (isObject(tag.style)) { Object.assign(style, tag.style); } tag.style = style; } function prepareClass(tag){ var className = "tag"; if(Array.isArray(tag.className)){ className= className + ' '+ tag.className.join(' '); }else if(typeof tag.className === "string"){ className= className + ' '+ tag.className; } if(tag.isNew){ className = className + " cant-select"; } tag.className = className; } function getPosition(r, c) { let element = document.getElementById(`carribean_r${r}c${c}`); var position = {}; if (element) { position = element.getBoundingClientRect(); } return position; } export function createTagText(text){ return( <span className="tag-content">{text}</span> ) } export function isHexLight(color) { const hex = color.replace('#', ''); const c_r = parseInt(hex.substr(0, 2), 16); const c_g = parseInt(hex.substr(2, 2), 16); const c_b = parseInt(hex.substr(4, 2), 16); const brightness = ((c_r * 299) + (c_g * 587) + (c_b * 114)) / 1000; return brightness > 155; } export function shadeColor2(color, percent) { var f = parseInt(color.slice(1), 16), t = percent < 0 ? 0 : 255, p = percent < 0 ? percent * -1 : percent, R = f >> 16, G = f >> 8 & 0x00FF, B = f & 0x0000FF; return "#" + (0x1000000 + (Math.round((t - R) * p) + R) * 0x10000 + (Math.round((t - G) * p) + G) * 0x100 + (Math.round((t - B) * p) + B)).toString(16).slice(1); } export function getRandomColor() { var letters = '0123456789ABCDEF'; var color = '#'; for (var i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; }
C++
UTF-8
728
2.734375
3
[]
no_license
#include <iostream> #include <queue> using namespace std; typedef long long ll; int t, n; priority_queue<ll> pq; ll MOD = 1000000007; ll mul(ll a, ll b) { return ((a % MOD) * (b % MOD)) % MOD; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); for(cin >> t; t > 0; t--) { ll ans = 1; if(!pq.empty()) pq.pop(); cin >> n; for(int i = 0; i < n; i++) { ll num; cin >> num; pq.push(-num); } while(pq.size() > 1) { ll first = -pq.top(); pq.pop(); ll second = -pq.top(); pq.pop(); ll newSlime = first * second; ans = mul(ans, newSlime); // cout << first << ' ' << second << ' ' << newSlime << ' ' << ans << '\n'; pq.push(-newSlime); } cout << ans << '\n'; } }
JavaScript
UTF-8
11,759
3.359375
3
[]
no_license
var TEST_ENV = false; var inputValue = ""; var searched = false; var savedCount = 0; var hasFav = false; var valueArr = [null]; var savedItemIdArr = [null]; var favoritesList; var track; // Initialize Favorites section depending on saved data in browser showFavorites(); displayResults(); // if there are no saved items do not show Favorites section function showFavorites() { if (hasFav === false) { document.getElementById("favoritesBody").style.display = "none"; console.log("showFav: SavedCount= " + savedCount); } else { document.getElementById("favoritesBody").style.display = "block"; } } /* 1) check validity of data 2) if there is a null space value in a string then add a '+' 3) call fetchData() to return API values */ function checkData() { //set search value to a var var searchParamater = document.getElementById("searchValue").value; console.log("searchParameter is: " + searchParamater); // check if searchValue has a space in it try { if (searchParamater === " ") { if (TEST_ENV) { console.log("please type something into the search bar"); } } else if (searchParamater != null && searchParamater.indexOf(" ") > -1) { // Search value includes white space // find white space / /g and replace with '+' inputValue = searchParamater.replace(/ /g, "+"); searched = true; fetchData(inputValue); if (TEST_ENV) { console.log("inputValue is: " + inputValue); } } else { inputValue = searchParamater; searched = true; fetchData(inputValue); if (TEST_ENV) { console.log("inputValue is: " + inputValue); } } } catch (err) { console.log("checkData(): " + err); } } /* 1) input param: inputValue / corrected input data 2) GET api data from itunes search link 3) set api JSON response to result array 4) set searched = true 5) Call displayResults() */ function fetchData(inputValue) { let URL = `https://itunes.apple.com/search?term=${inputValue}&limit=10`; searched = true; if (TEST_ENV) { console.log("inputValue is: " + inputValue); console.log(URL); } fetch(URL) .then(function(response) { return response.json(); }) // .then(function(myJson) { // console.log(JSON.stringify(myJson)); // }) .then(function(data) { let responseTypes = data.results; return responseTypes.map(function(responseTypes) { track = responseTypes.trackId; var trackname = responseTypes.trackName; var artistname = responseTypes.artistName; var artwork = responseTypes.artworkUrl100; var genrelink = responseTypes.primaryGenreName; var urllink = responseTypes.previewUrl; valueArr = [track, trackname, artistname, artwork, genrelink, urllink]; searched = true; displayResults(valueArr); if (TEST_ENV) { // let track = console.log("trackId: " + responseTypes.trackId); // let trackname = console.log("trackName: " + responseTypes.trackName); // let artistname = console.log("ArtistName: " + responseTypes.artistName); // let artwork = console.log("artworkUrl: " + responseTypes.artworkUrl30); // let genre = console.log("genre: " + responseTypes.primaryGenreName); // let url = console.log("URL: " + responseTypes.previewUrl); console.log(valueArr); } }); }) .catch(function(err) { console.log("response failed", err); searched = true; }); } // function callResultsAndFavorites() { // displayResults(valueArr); // favoritesResults(); // } /* Type: functions Purpose: 1) check for successful response 2) if no data then show body "please search" 3) if data then iterate through each valueArr and display cards */ /* 1) input param: valueArr / JSON response values from itunes API 2) create dynamic HTML elements for each valueArr instance 3) set api JSON response to result array */ function displayResults(valueArr) { if (TEST_ENV) { console.log("displayresults hit"); } var resultsList = document.getElementById("resultsSection"); if (searched === false) { console.log("searched = false"); //resultsBody.classList.add("") //resultsBody.innerHTML = "<h3>"; // var resultsPromptText = document.createElement("h3"); // resultsPromptText.classList.add("searchPrompt"); // resultsPromptText.innerHTML = "Please search for an artist"; // resultsList.appendChild(resultsPromptText); } else if (searched === true && valueArr != null) { if (TEST_ENV) { console.log("searched = true and arr not null"); } //h3.removeChile(h3.childNodes[0]); //var resultsPromptText = document.getElementsByClassName("searchPrompt"); //resultsPromptText.remove(); //document.getElementByClassName("searchPrompt").style.display = "none"; //var resultsList = document.getElementById("resultsSection"); var uList = document.createElement("ul"); resultsList.appendChild(uList); var listItem = document.createElement("li"); listItem.classList.add("rounded"); var newCard = document.createElement("div"); newCard.classList.add("card"); var newCardBody = document.createElement("div"); newCardBody.classList.add("card-body"); var newH5 = document.createElement("h5"); newH5.classList.add("card-title"); newH5.innerHTML = valueArr[1]; var artistP = document.createElement("p"); artistP.classList.add("card-text"); artistP.innerHTML = valueArr[2]; var trackIDP = document.createElement("p"); trackIDP.classList.add("card-text"); trackIDP.innerHTML = valueArr[0]; var trackImageImg = document.createElement("img"); trackImageImg.classList.add("card-img-top"); trackImageImg.src = valueArr[3]; var genreP = document.createElement("p"); genreP.classList.add("card-text"); genreP.innerHTML = valueArr[4]; var trackViewP = document.createElement("p"); trackViewP.classList.add("card-text"); trackViewP.innerHTML = valueArr[5]; var favoriteButton = document.createElement("span"); favoriteButton.classList.add("badge"); //favoriteButton.onclick = storeFavorites(this.trackIDP); favoriteButton.innerHTML = "favorite"; newCardBody.innerHTML += newH5.outerHTML + artistP.outerHTML + genreP.outerHTML + trackViewP.outerHTML + favoriteButton.outerHTML; newCard.appendChild(trackImageImg); newCard.appendChild(newCardBody); listItem.appendChild(newCard); uList.appendChild(listItem); resultsList.appendChild(uList); } else { var displayAlert = document.createElement("h3"); displayAlert.innerHTML = "Your search failed"; } } /* 1) count number of favorited objects 2) save object items to browser storage 3) call favoritesResults() upon succesful save to browser storage */ function storeFavorites(favTrackID) { if (TEST_ENV) { console.log("storeFavorites: savedCount= " + savedCount); } savedCount = savedCount + 1; try { hasFav = true; savedItemIdArr.push(favTrackID); console.log("savedItem= " + savedItemIdArr); //savedArtistNameArr.push(savedArtistName); localStorage.setItem("savedItems", savedItemIdArr); favoritesResults(); } catch (err) { console.log(err); } } /* 1) SEE API RESULTS METHOD ABOVE */ function favoritesResults() { favoritesList = document.getElementById("favoritesBody"); let saved = localStorage.getItem("saveItems"); // if (savedCount === 0 || hasFav === false) if (saved === null && savedItemIdArr === null) { document.getElementById("favoritesBody").style.display = "none"; } else { document.getElementById("favoritesBody").style.display = "block"; for (var j = 0; j < saved.length; j++) { // var favId = savedItemIdArr[j]; var favId = saved[j]; let URL = `https://itunes.apple.com/lookup?id=${favId}&limit=1`; if (TEST_ENV) { } fetch(URL) .then(function(response) { return response.json(); }) // .then(function(myJson) { // console.log(JSON.stringify(myJson)); // }) .then(function(data) { let favResponseTypes = data.results; return favResponseTypes.map(function(favResponseTypes) { var favTrack = favResponseTypes.trackId; var favTrackName = favResponseTypes.trackName; var favArtistName = favResponseTypes.artistName; var favArtwork = favResponseTypes.artworkUrl100; var favGenrelink = favResponseTypes.primaryGenreName; var favUrllink = favResponseTypes.previewUrl; favValueArr = [ favTrack, favTrackName, favArtistName, favArtwork, favGenrelink, favUrllink ]; displayFavResults(favValueArr); if (TEST_ENV) { // let track = console.log("trackId: " + responseTypes.trackId); // let trackname = console.log("trackName: " + responseTypes.trackName); // let artistname = console.log("ArtistName: " + responseTypes.artistName); // let artwork = console.log("artworkUrl: " + responseTypes.artworkUrl30); // let genre = console.log("genre: " + responseTypes.primaryGenreName); // let url = console.log("URL: " + responseTypes.previewUrl); console.log(favValueArr); } }); }) .catch(function(err) { console.log("response failed", err); }); } if (TEST_ENV) { // console.log(savedItemNameArr); // console.log(savedArtistNameArr); } } } /* 1) see results method above */ function displayFavResults(favValueArr) { if (TEST_ENV) { console.log("displayFavresults hit"); } var favResultsList = document.getElementById("favoritesSection"); if (favValueArr != null) { if (TEST_ENV) { console.log("fav searched = true and arr not null"); } var favUList = document.createElement("ul"); favResultsList.appendChild(favUList); var favListItem = document.createElement("li"); favListItem.classList.add("rounded"); var favNewCard = document.createElement("div"); favNewCard.classList.add("card"); var newCardBody = document.createElement("div"); newCardBody.classList.add("card-body"); var newH5 = document.createElement("h5"); newH5.classList.add("card-title"); newH5.innerHTML = valueArr[1]; var artistP = document.createElement("p"); artistP.classList.add("card-text"); artistP.innerHTML = valueArr[2]; var trackIDP = document.createElement("p"); trackIDP.classList.add("card-text"); trackIDP.innerHTML = valueArr[0]; var trackImageImg = document.createElement("img"); trackImageImg.classList.add("card-img-top"); trackImageImg.src = valueArr[3]; var genreP = document.createElement("p"); genreP.classList.add("card-text"); genreP.innerHTML = valueArr[4]; var trackViewP = document.createElement("p"); trackViewP.classList.add("card-text"); trackViewP.innerHTML = valueArr[5]; newCardBody.innerHTML += newH5.outerHTML + artistP.outerHTML + genreP.outerHTML + trackViewP.outerHTML; favNewCard.appendChild(trackImageImg); favNewCard.appendChild(newCardBody); favListItem.appendChild(favNewCard); favUList.appendChild(favListItem); favResultsList.appendChild(favUList); } else { var displayAlert = document.createElement("h3"); displayAlert.innerHTML = "Your search failed"; } }
Java
UTF-8
178
2.609375
3
[]
no_license
package com.abc33; public class CheckStrings { public boolean stringFound(String s1, String s2) { if (s1.contains(s2)) { return true; } return false; } }
Python
UTF-8
1,190
3.578125
4
[]
no_license
import requests from bs4 import BeautifulSoup # URL to be scraped url = 'https://www.worldometers.info/coronavirus/countries-where-coronavirus-has-spread/' # Get URL HTML page = requests.get(url) soup = BeautifulSoup(page.text, 'html.parser') data = [] data_iterator = iter(soup.find_all('td')) while True: try: country = next(data_iterator).text confirmed = next(data_iterator).text deaths = next(data_iterator).text continents = next(data_iterator).text #convert deaths and confirmed to integers data.append (( country, int(confirmed.replace(',', '')), int(deaths.replace(',', '')), continents )) except StopIteration: break # sort data data.sort(key = lambda row: row[1], reverse = True) # create text table object import texttable as tt table = tt.Texttable() # add empty row at beginning of headers table.add_rows([(None, None, None, None)] + data) # 'l' denotes left, 'c' denotes center, # and 'r' denotes right table.set_cols_align(('c', 'c', 'c', 'c')) table.header((' Country ', ' Number of cases ', ' Deaths ', ' Continent ')) print(table.draw())
C#
UTF-8
3,156
2.828125
3
[]
no_license
using System; namespace KProcess.Presentation.Windows.Controls { /// <summary> /// Defines a model containing informations on a media /// </summary> public class MediaInfo { /// <summary> /// Gets or sets if the media has video. /// </summary> public bool HasVideo { get; set; } /// <summary> /// Gets or sets if the media has audio. /// </summary> public bool HasAudio { get; set; } /// <summary> /// Gets or sets the length of the video. /// </summary> /// <value> /// The length of the video. /// </value> public TimeSpan VideoLength { get; set; } /// <summary> /// Gets or sets the height of the frame (pixels). /// </summary> /// <value> /// The height of the frame. /// </value> public int FrameHeight { get; set; } /// <summary> /// Gets or sets the width of the frame (pixels). /// </summary> /// <value> /// The width of the frame. /// </value> public int FrameWidth { get; set; } /// <summary> /// Gets or sets the video data rate (kbps). /// </summary> /// <value> /// The video data rate. /// </value> public int VideoDataRate { get; set; } /// <summary> /// Gets or sets the video frame rate (frames/seconds). /// </summary> /// <value> /// The video frame rate. /// </value> public double VideoFrameRate { get; set; } /// <summary> /// Gets or sets the audio codec. /// </summary> /// <value> /// The audio codec. /// </value> public string AudioCodec { get; set; } /// <summary> /// Gets or sets the length of the audio. /// </summary> /// <value> /// The length of the audio. /// </value> public TimeSpan AudioLength { get; set; } /// <summary> /// Gets or sets the channels (2 mins stereo). /// </summary> /// <value> /// The channels. /// </value> public int AudioChannels { get; set; } /// <summary> /// Gets or sets the audio sample rate (kbps). /// </summary> /// <value> /// The audio sample rate. /// </value> public int AudioSampleRate { get; set; } /// <summary> /// Gets or sets the video codec. /// </summary> /// <value> /// The video codec. /// </value> public string VideoCodec { get; set; } /// <summary> /// Gets or sets the video bits per pixel. /// </summary> /// <value> /// The video bits per pixel. /// </value> public int VideoBitsPerPixel { get; set; } /// <summary> /// The number of bits per sample in the audio stream /// </summary> /// <value> /// The audio bits per sample. /// </value> public int AudioBitsPerSample { get; set; } } }
Python
UTF-8
734
3.53125
4
[]
no_license
class empleados: def __init__(self,nombre,cargo,salario): self.nombre=nombre self.cargo=cargo self.salario=salario def __str__(self): return "{} que trabaja como {} tiene un salario de {} $".format(self.nombre, self.cargo, self.salario) listaEmpleados=[ empleados("juan","directos",6700), empleados("ana","Presidente",7500), empleados("antonio","administrativo",2100), empleados("sara","Secretaria",2150), empleados("mario","Botones",1800), ] def calculo_comision(empleados): if empleados.salario <= 3000: empleados.salario=empleados.salario*1.03 return empleados lista_empleados=map(calculo_comision,listaEmpleados) for empleado in lista_empleados: print(empleado)
Java
UTF-8
354
2.59375
3
[]
no_license
/* * classe che descrive delle coordinate * */ package autoMag.space; import java.io.Serializable; public class Coord implements Serializable { private String sector; public Coord(String newSector) { sector = newSector; } public String getSector() { return sector; } public String toString() { return "Sector: "+sector; } }
Java
UTF-8
1,150
2.53125
3
[]
no_license
package org.innopolis.javaEE.stat.model.dao; import org.innopolis.javaEE.stat.model.pojo.Top; import org.innopolis.javaEE.utils.DataSourceFactory; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; public class TopDaoImpl implements TopDao { @Override public List<Top> getTop() { List<Top> topList = new ArrayList<>(); String sql = "SELECT * FROM top"; try(Connection connection = DataSourceFactory.getDataSource().getConnection()) { Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM top;"); while (resultSet.next()) { Top top = new Top(); top.setRank(resultSet.getInt("rank")); top.setUsername(resultSet.getString("username")); topList.add(top); } resultSet.close(); statement.close(); connection.close(); } catch (SQLException ignored) { } return topList; } }
Ruby
UTF-8
926
2.59375
3
[]
no_license
# frozen_string_literal: true require 'transaction' describe Transaction do describe '#initialize' do it 'initializes a new transaction' do transaction = Transaction.new expect(transaction).to be_an_instance_of(Transaction) end end describe '#deposit_transaction' do it 'creates a log for a deposit' do log = Transaction.new log.deposit_transaction('02/07/2019', 500, 600) expect(log.transaction_log).to eq( credit: 500.00, debit: ' ', balance: 600.00, date: '02/07/2019' ) end end describe '#withdraw_transaction' do it 'creates a log for a withdraw from the account' do log = Transaction.new log.withdraw_transaction('02/07/2019', 500, 600) expect(log.transaction_log).to eq( credit: ' ', debit: 500.00, balance: 600.00, date: '02/07/2019' ) end end end
Python
UTF-8
145
3.359375
3
[]
no_license
import re text = "In this text-oriented string how can you remove non-hyphen words?" pattern = r'[\w]+-[\w]+' print(re.findall(pattern,text))
Python
UTF-8
656
3.34375
3
[]
no_license
from turtle import Turtle class Scoreboard(Turtle): def __init__(self): super().__init__() self.score_l = 0 self.score_r = 0 self.write_scores() def write_scores(self): self.clear() self.color("white") self.hideturtle() self.penup() self.goto(0, 250) self.write(f"{self.score_l} {self.score_r}", align="center", move=False, font=("Courier", 40, "normal")) def update_score(self, player): if player == "r_paddle": self.score_r += 1 self.write_scores() else: self.score_l += 1 self.write_scores()
Markdown
UTF-8
918
2.609375
3
[]
no_license
# Article R714-3 Dans les établissements où le travail est organisé de façon continue pendant tout ou partie de l'année parce que sont mises en oeuvre des matières susceptibles d'altération très rapide ou parce que toute interruption de travail entraînerait la perte ou la dépréciation du produit en cours de fabrication, le repos hebdomadaire peut être donné par roulement pendant la période correspondante au personnel affecté à ce travail, y compris celui affecté aux opérations mentionnées aux 8° à 11° de l'article R. 714-1. **Liens relatifs à cet article** _Anciens textes_: - Décret n°75-957 du 17 octobre 1975 - art. 1-1 (M) _Codifié par_: - Décret n°2005-368 2005-04-19 _Créé par_: - Décret n°2005-368 2005-04-19 art. 1, annexe JORF 22 avril 2005 - Décret n°2005-368 du 19 avril 2005 - art. 1 (V) JORF 22 avril 2005 _Cite_: - Code rural - art. R714-1 (V)
JavaScript
UTF-8
813
2.546875
3
[]
no_license
/* eslint-disable default-case */ import React from 'react'; const input = (props) => { let inputEl = null; switch(props.elementType) { case ('input'): inputEl = <input {...props.elementConfig} value={props.value} onChange={props.changed} /> break; case('select'): inputEl = <select> {props.elementConfig.options.map(option=>{ return <option value={option}>{option.displayValue}</option> })} </select> break; case('default'): inputEl = <input {...props.elementConfig} /> break; } return( <div> {inputEl} </div> ) } export default input;
C#
UTF-8
628
3.0625
3
[]
no_license
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace MasterMind.Utils { public class ClosedInterval { private int min; private int max; public ClosedInterval(int min, int max) { Debug.Assert(min <= max); this.min = min; this.max = max; } public bool IsIncluded(int value) { return this.min <= value && value <= this.max; } public override string ToString() { return "[" + this.min + ", " + this.max + "]"; } } }
Java
UTF-8
1,154
1.859375
2
[]
no_license
package esiapp.esi.model.retroModel; import java.io.Serializable; /** * Created by Randhir Kumar on 2/17/2017. */ public class IpNumberEligibilityCheckResp implements Serializable { private String IPnumber; private String IsIPEligible; private String ResponseCode; // private String OtpCode; private String Sessionid; public String getIPnumber() { return IPnumber; } public void setIPnumber(String IPnumber) { this.IPnumber = IPnumber; } public String getIsIPEligible() { return IsIPEligible; } public void setIsIPEligible(String isIPEligible) { IsIPEligible = isIPEligible; } public String getResponseCode() { return ResponseCode; } public void setResponseCode(String responseCode) { ResponseCode = responseCode; } // public String getOtpCode() { // return OtpCode; // } // // public void setOtpCode(String otpCode) { // OtpCode = otpCode; // } public String getSessionid() { return Sessionid; } public void setSessionid(String sessionid) { Sessionid = sessionid; } }
C++
UTF-8
459
2.6875
3
[]
no_license
#include"ArrayBST.h" int main() { ArrayBST A; cout<<A.isEmpty()<<endl; A.addBST(30); A.addBST(20); A.addBST(40); A.addBST(15); A.addBST(25); A.addBST(35); A.addBST(14); A.addBST(17); A.addBST(23); A.addBST(27); A.addBST(32); A.addBST(37); A.trasverse(); cout<<endl<<A.searchBST(40)<<endl; A.removeBST(40); A.trasverse(); cout<<endl<<A.searchBST(40)<<endl; return 0; }
Swift
UTF-8
1,757
2.84375
3
[ "MIT" ]
permissive
import RxSwift import RxCocoa import Action import Presentations protocol FoodInfoPresentingViewModel: AnyObject, PresentingViewModel { var foodInfoPresenter: FoodInfoPresenter? { get set } var presentFoodInfo: Action<Bool, FoodInfoViewModel> { get } } extension FoodInfoPresentingViewModel { /// Makes an action that is suitable to be set as the presentFoodInfo action. /// /// This action should be executed with a Bool indicating whether the presentation should be animated. /// /// - Parameter factory: A factory to be used to generate the presented view model. /// - Parameter setupViewModel: This closure will be called with the presented view model when a present action /// is executed. Consumers can use this to observe changes to the presented view model if necessary. func makePresentFoodInfo( withFactory factory: FoodInfoViewModelFactoryProtocol, setupViewModel: ((FoodInfoViewModel) -> Void)? = nil ) -> Action<Bool, FoodInfoViewModel> { return makePresentAction { [weak self] animated -> DismissablePresentationContext<FoodInfoViewModel>? in guard let self = self, let presenter = self.foodInfoPresenter else { return nil } let viewModel = factory.makeFoodInfoViewModel() setupViewModel?(viewModel) let presentation = presenter.foodInfoPresentation(of: viewModel) return DismissablePresentationContext(presentation: presentation, viewModel: viewModel, presentAnimated: animated) } } } protocol FoodInfoPresenter: AnyObject { func foodInfoPresentation(of viewModel: FoodInfoViewModel) -> DismissablePresentation }
Java
UTF-8
1,635
3.703125
4
[]
no_license
package theb.r.i.a.n.system; import java.util.ArrayList; import java.util.List; // Create a class to represent the set data structure. Has the appropriate get // and set methods class Set{ Team homeTeam; Team awayTeam; List<Game> games = new ArrayList<>(); Team winner; public Team getHomeTeam(){ return homeTeam; } public void setHomeTeam(Team team){ homeTeam = team; } public Team getAwayTeam(){ return awayTeam; } public void setAwayTeam(Team team){ awayTeam = team; } public List<Game> getGames(){ return games; } public void setGames(List<Game> games){ this.games = games; } // Calculate the winner by finding out how many games the home team won, and // performing calculations on that number. public void calculateWinner(){ int home = 0; // Calculate how many games the homeTeam has won and set the winner of each game to the appropriate team for(int i = 0; i < 3; i++){ if(games.get(i).homeScore > games.get(i).awayScore){ home++; games.get(i).setWinner(homeTeam); } else{ games.get(i).setWinner(awayTeam); } } // If teh homeTeam has won 2 or more games (e.g. best of 3: winning the set), set them to the set winner, // otherwise, set the set winner to awayTeam if(home >= 2){ winner = homeTeam; } else{ winner = awayTeam; } } public Team getWinner(){ return winner; } }
Python
UTF-8
3,896
2.84375
3
[]
no_license
#!/usr/bin/python # -*- coding: utf-8 -*- import pandas as pd import matplotlib.cm as cm import matplotlib.font_manager import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap, LinearSegmentedColormap plt.rcParams['font.family'] = 'Serif' # Then, just call plt.figure(figsize=(8.5, 8.5)) plt.rcParams.update({'font.size': 23}) def plot_clustered_stacked( dfall, labels=None, title='N-Body Strong Scaling', H='.', **kwargs ): """Given a list of dataframes, with identical columns and index, create a clustered stacked bar plot. labels is a list of the names of the dataframe, used for the legend title is a string for the title of the plot H is the hatch used for identification of the different dataframe""" n_df = len(dfall) n_col = len(dfall[0].columns) n_ind = len(dfall[0].index) axe = plt.subplot(111) for df in dfall: # for each data frame axe = df.plot( # make bar plots kind='bar', linewidth=0, stacked=True, ax=axe, legend=False, grid=False, **kwargs ) (h, l) = axe.get_legend_handles_labels() # get the handles we want to modify for i in range(0, n_df * n_col, n_col): # len(h) = n_col * n_df for (j, pa) in enumerate(h[i:i + n_col]): for rect in pa.patches: # for each index rect.set_x(rect.get_x() + 1 / float(n_df + 1) * i / float(n_col)) rect.set_hatch(H * int(i / n_col)) # edited part rect.set_width(1 / float(n_df + 1)) # axe.set_xticks((np.arange(0, 2 * n_ind, 2) + 1 / float(n_df + 1)) / 2.) axe.set_xticklabels(df.index, rotation=0) axe.set_title(title, fontsize=25.5) # Add invisible data to add another legend n = [] for i in range(n_df): n.append(axe.bar(0, 0, color='lightgrey', hatch=H * i)) l1 = axe.legend( h[:n_col], l[:n_col], ncol=1, fontsize='small', loc=[0.55, 0.85], borderpad=0.5, ) if labels is not None: l2 = plt.legend(n, labels, fontsize='small', loc=[0.55, 0.6]) axe.add_artist(l1) return axe nbodyhs = pd.DataFrame(np.array([[21.13055, 0.0], [9.33885, 0.650429], [3.85851, 0.4817905], [0.7385655, 0.229862]]), index=['1', '2', '4', '8'], columns=['Computation', 'Communication']) nbodykn = pd.DataFrame(np.array([[23.0521, 0.0], [9.92478, 1.76877], [4.79884, 1.1324], [2.16072, 0.878426]]), index=['1', '2', '4', '8'], columns=['Computation', 'Communication']) nbodyr5 = pd.DataFrame(np.array([[15.33635, 0.0], [6.37743, 0.28650], [2.2107, 0.28985], [0.620329, 0.35165]]), index=['1', '2', '4', '8'], columns=['Computation', 'Communication']) nbodyc5 = pd.DataFrame(np.array([[9.85467, 0.0], [7.66376, 0.3513955], [2.81266, 0.31519], [0.719194, 0.3217135]]), index=['1', '2', '4', '8'], columns=['Computation', 'Communication']) plt.ylabel('Time (s)') plt.xlabel('Number of Nodes') # mycmap5 = ListedColormap(["#E8C547", "#30323D", "#4D5061", "#5C80BC", "#CDD1C4", "#F15156", "#38A3A5", "#57CC99", "#DC758F"]) # mycmap6 = ListedColormap(["#30323D", "#4D5061", "#5C80BC", "#CDD1C4", "#F15156", "#38A3A5", "#57CC99", "#DC758F"]) mycmap2 = ListedColormap(['#E8C547', '#F15156']) plot_clustered_stacked([nbodyhs, nbodykn, nbodyr5, nbodyc5], ['Cori-Haswell-32', 'Cori-KNL-64', 'AWS-R5-32', 'AWS-C5-32'], cmap=mycmap2) plt.tight_layout() plt.tight_layout(pad=0.5) plt.savefig('StrongScalingNBody.pdf')
SQL
UTF-8
12,604
3.25
3
[]
no_license
/* Navicat MySQL Data Transfer Source Server : 本机 Source Server Version : 50520 Source Host : localhost:3306 Source Database : center Target Server Type : MYSQL Target Server Version : 50520 File Encoding : 65001 Date: 2017-04-05 15:50:45 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `admin` -- ---------------------------- DROP TABLE IF EXISTS `admin`; CREATE TABLE `admin` ( `Name` varchar(50) NOT NULL, `Pass` varchar(50) DEFAULT NULL, `Type` int(11) DEFAULT '0', `Card1` int(11) DEFAULT '0', `Card2` int(11) DEFAULT '0', `Card3` int(11) DEFAULT '0', `Time` int(11) DEFAULT '0', `Nike` varchar(50) DEFAULT NULL, `Invite` int(11) DEFAULT '0', `Info` varchar(256) DEFAULT '', PRIMARY KEY (`Name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Table structure for `bill` -- ---------------------------- DROP TABLE IF EXISTS `bill`; CREATE TABLE `bill` ( `Id` int(11) NOT NULL AUTO_INCREMENT, `AdminName` varchar(50) DEFAULT NULL, `CardType` int(11) DEFAULT NULL, `CardNum` int(11) DEFAULT NULL, `Time` int(11) DEFAULT NULL, `Flag` int(11) DEFAULT '1' COMMENT ' 1-冲值,2-赠送 ', `Type` int(11) DEFAULT '1' COMMENT ' 1-会员,2-玩家 ', `DesName` varchar(50) DEFAULT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Table structure for `charge` -- ---------------------------- DROP TABLE IF EXISTS `charge`; CREATE TABLE `charge` ( `Id` int(11) NOT NULL AUTO_INCREMENT, `Time` int(11) DEFAULT NULL, `CardType` int(11) DEFAULT NULL, `CardNum` int(11) DEFAULT NULL, `Type` int(11) DEFAULT NULL, `Admin` varchar(50) DEFAULT '', `UserId` int(11) DEFAULT NULL, PRIMARY KEY (`Id`), KEY `UserId` (`UserId`), KEY `Time` (`Time`), KEY `Admin` (`Admin`), KEY `Type` (`Type`) ) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8; -- ------------------------------- -- -- ------------------------------- CREATE TABLE `charge_201709` ( `Id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增主键', `ServerId` int(11) NOT NULL COMMENT '玩家所属区服ID', `UserId` int(11) NOT NULL COMMENT '玩家ID', `Time` int(11) NOT NULL COMMENT '时间', `CardNum` int(11) NOT NULL COMMENT '房卡变动数量', `Type` smallint(6) NOT NULL COMMENT '房卡变动类型', `Balance` int(11) NOT NULL COMMENT '玩家房卡余额', `Operator` varchar(50) NOT NULL DEFAULT '' COMMENT '操作者', `Remark` varchar(50) NOT NULL DEFAULT '' COMMENT '备注', PRIMARY KEY (`Id`), KEY `idx_uid_time` (`UserId`,`Time`) ) ENGINE=InnoDB AUTO_INCREMENT=212 DEFAULT CHARSET=utf8mb4; -- ---------------------------- -- Table structure for `onlinelog` -- ---------------------------- DROP TABLE IF EXISTS `onlinelog`; CREATE TABLE `onlinelog` ( `id` int(11) NOT NULL AUTO_INCREMENT, `DateTime` int(11) NOT NULL, `serverID` int(11) NOT NULL DEFAULT '0', `serverName` varchar(128) NOT NULL DEFAULT '', `onlineCount` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2798 DEFAULT CHARSET=utf8; -- ---------------------------- -- Table structure for `user` -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `Id` int(11) NOT NULL AUTO_INCREMENT, `OpenId` varchar(64) COLLATE utf8mb4_bin NOT NULL, `Nike` varchar(64) COLLATE utf8mb4_bin NOT NULL, `Sex` int(11) DEFAULT '0', `Provice` varchar(64) COLLATE utf8mb4_bin DEFAULT '', `City` varchar(64) COLLATE utf8mb4_bin DEFAULT '', `Country` varchar(64) COLLATE utf8mb4_bin DEFAULT '', `HeadImageUrl` varchar(512) COLLATE utf8mb4_bin DEFAULT '', `UnionId` varchar(64) COLLATE utf8mb4_bin NOT NULL DEFAULT '', `NumsCard1` int(11) DEFAULT '0', `NumsCard2` int(11) unsigned DEFAULT '0', `NumsCard3` int(11) DEFAULT '0', `LastLoginTime` int(11) DEFAULT '0', `RegTime` int(11) DEFAULT '0', `New` int(11) DEFAULT '0', `Gm` int(11) DEFAULT '0', `TotalCardNum` int(11) DEFAULT '0', `TotalPlayNum` int(11) DEFAULT '0', `location` varchar(512) COLLATE utf8mb4_bin DEFAULT '', `last_relief_time` int(11) DEFAULT '0', `phoneNumber` varchar(512) COLLATE utf8mb4_bin DEFAULT '', `serverID` int(11) DEFAULT '33001', PRIMARY KEY (`Id`), KEY `NumsCard1` (`NumsCard1`), KEY `NumsCard2` (`NumsCard2`), KEY `NumsCard3` (`NumsCard3`), KEY `LastLoginTime` (`LastLoginTime`), KEY `RegTime` (`RegTime`), KEY `OpenId` (`OpenId`), KEY `UnionId` (`UnionId`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; -- ---------------------------- -- Table structure for `useractive` -- ---------------------------- DROP TABLE IF EXISTS `useractive`; CREATE TABLE `useractive` ( `DateTime` int(11) NOT NULL, `NewUser` int(11) DEFAULT '0', `ActiveUser` int(11) DEFAULT '0', `PlayCount` int(11) DEFAULT '0', PRIMARY KEY (`DateTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of useractive -- ---------------------------- -- 分享送房卡活动 DROP TABLE IF EXISTS `Activity`; CREATE TABLE `Activity` ( `Id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增长主键ID', `userid` int(11) NOT NULL COMMENT '玩家ID', `fetchCnt` int(11) NOT NULL DEFAULT '0' COMMENT '领取次数', `lastFetchTime` int(11) NOT NULL DEFAULT '0' COMMENT '上一次领取时间', PRIMARY KEY (`Id`), UNIQUE KEY (`userid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin ; --------------------- --随机id --------------------- DROP TABLE IF EXISTS 'user_id_table'; CREATE TABLE `user_id_table` ( `Id` int(11) NOT NULL AUTO_INCREMENT, `UserId` int(11) NOT NULL, PRIMARY KEY (`Id`), UNIQUE KEY `UserId` (`UserId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; ------------------------- ---公会表 ------------------------ CREATE TABLE `team` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `TeamID` int(11) NOT NULL COMMENT '工会ID', `CreaterID` int(11) NOT NULL COMMENT '创建者ID', `adminId` int(11) NOT NULL COMMENT '会主ID', `serverID` int(11) NOT NULL COMMENT '服务器ID', `CreaterName` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT '创建者名称', `TeamName` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT '工会名称', `Cards` int(11) NOT NULL COMMENT '工会房卡', `CardAlert` int(11) NOT NULL DEFAULT '300' COMMENT '工会房卡低于改值报警', `PerDayMemLimit` int(11) NOT NULL DEFAULT '100' COMMENT '成员每天最大可使用工会房卡数量', `CreateTime` int(11) NOT NULL DEFAULT '0' COMMENT '工会创建时间戳', `TeamState` int(11) NOT NULL COMMENT '工会状态', `boardInfo` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT '' COMMENT '公告信息', `DisbandedTime` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`Id`), KEY `TeamID` (`TeamID`), KEY `adminId` (`adminId`) ) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8 COMMENT='存储工会会长创建的工会'; ----------------- ---公会充值表(按月分表) ----------------- CREATE TABLE `team_charge_xxxxx` ( `Id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增主键', `ServerId` int(11) NOT NULL COMMENT '工会所属区服ID', `TeamId` int(11) NOT NULL COMMENT '工会ID', `TeamMemId` int(11) NOT NULL COMMENT '成员ID', `Time` int(11) NOT NULL COMMENT '时间', `CardNum` int(11) NOT NULL COMMENT '房卡变动数量', `Type` smallint(6) NOT NULL COMMENT '房卡变动类型', `Balance` int(11) NOT NULL COMMENT '工会房卡余额', `Operator` varchar(50) NOT NULL DEFAULT '' COMMENT '操作者', `Remark` varchar(50) NOT NULL DEFAULT '' COMMENT '备注', PRIMARY KEY (`Id`), KEY `idx_tid_mid_time` (`TeamId`,`TeamMemId`,`Time`), KEY `idx_mid_time` (`TeamMemId`,`Time`) ) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8mb4; ------------------- --team随机ID表 ------------------ CREATE TABLE `team_id_table` ( `Id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键', `TeamId` int(11) NOT NULL DEFAULT '0' COMMENT '工会ID', PRIMARY KEY (`Id`) ) ENGINE=InnoDB AUTO_INCREMENT=931979 DEFAULT CHARSET=utf8; ----------------- ---team_log表 ----------------- CREATE TABLE `team_log` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键ID', `DeskID` int(11) NOT NULL DEFAULT '0' COMMENT '桌子ID', `TeamID` int(11) NOT NULL DEFAULT '0' COMMENT '工会ID', `UserId1` int(11) NOT NULL DEFAULT '0' COMMENT '玩家ID', `UserId2` int(11) NOT NULL DEFAULT '0' COMMENT '玩家ID', `UserId3` int(11) NOT NULL DEFAULT '0' COMMENT '玩家ID', `UserId4` int(11) NOT NULL DEFAULT '0' COMMENT '玩家ID', `Score1` int(11) NOT NULL DEFAULT '0' COMMENT '得分', `Score2` int(11) NOT NULL DEFAULT '0' COMMENT '得分', `Score3` int(11) NOT NULL DEFAULT '0' COMMENT '得分', `Score4` int(11) NOT NULL DEFAULT '0' COMMENT '得分', `Nike1` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, `HeadImageUrl1` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT '', `Nike2` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, `HeadImageUrl2` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT '', `Nike3` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, `HeadImageUrl3` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT '', `Nike4` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, `HeadImageUrl4` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT '', `OptState` int(11) NOT NULL DEFAULT '0' COMMENT '是否已阅', `PlayFlag` int(11) DEFAULT '0' COMMENT '玩法类型', `Time` int(11) NOT NULL DEFAULT '0' COMMENT '时间戳', `serverID` int(11) NOT NULL COMMENT '服务器ID', PRIMARY KEY (`Id`), KEY `TeamID` (`TeamID`), KEY `Indx_time_teamid` (`Time`,`TeamID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='记录使用工会房间的开局日志'; ----------------------- --公会成员操作log ----------------------- CREATE TABLE `team_mem_opt` ( `Id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增主键', `TeamID` int(11) NOT NULL DEFAULT '0' COMMENT '工会ID', `TeamName` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT '工会名称', `UserID` int(11) NOT NULL DEFAULT '0' COMMENT '玩家ID', `Opt` tinyint(4) NOT NULL DEFAULT '0' COMMENT '操作类型', `OptTime` int(11) NOT NULL DEFAULT '0' COMMENT '操作的时间戳', PRIMARY KEY (`Id`), KEY `indx_TeamId` (`TeamID`), KEY `indx_UserID_TeamID` (`UserID`,`TeamID`) ) ENGINE=InnoDB AUTO_INCREMENT=79 DEFAULT CHARSET=utf8 COMMENT='玩家加入离开工会的日志表'; -------------- --公会成员表 -------------- CREATE TABLE `team_member` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `UserID` int(11) NOT NULL DEFAULT '0' COMMENT '玩家ID', `TeamID` int(11) NOT NULL DEFAULT '0' COMMENT '工会ID', `serverID` int(11) NOT NULL COMMENT '服务器ID', `UseCardNum` int(11) NOT NULL DEFAULT '0' COMMENT '当天房卡使用量', `TeamState` int(11) NOT NULL DEFAULT '0' COMMENT '玩家在工会中的状态', `LastUserCardTime` int(11) NOT NULL DEFAULT '0' COMMENT '最后一次使用工会房卡的时间戳', `JoinTime` int(11) NOT NULL DEFAULT '0' COMMENT '加入工会的时间戳', `ReqTime` int(11) NOT NULL DEFAULT '0' COMMENT '申请退出工会的时间戳', `WinerCount` int(11) DEFAULT '0' COMMENT '大赢家次数', `TotalUseCardNum` int(11) DEFAULT '0' COMMENT '使用俱乐部房卡总数', `TotalCreateDeskCount` int(11) DEFAULT '0' COMMENT '通过俱乐部创建房间的次数', `TotalPlayCount` int(11) DEFAULT '0' COMMENT '参与俱乐部房间游戏的次数', `QuitTime` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`Id`), KEY `TeamID` (`TeamID`), KEY `Indx_UserID_TeamID` (`UserID`,`TeamID`) ) ENGINE=InnoDB AUTO_INCREMENT=47 DEFAULT CHARSET=utf8 COMMENT='存储工会成员'; -------------- --封禁用户表 -------------- CREATE TABLE IF NOT EXISTS `block_user` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `UserID` int(11) NOT NULL COMMENT '用户ID', `StartTime` int(11) NOT NULL DEFAULT '0' COMMENT '封禁开始时间戳', `EndTime` int(11) NOT NULL DEFAULT '0' COMMENT '封禁结束时间戳,-1为永久封禁', PRIMARY KEY (`Id`), UNIQUE KEY `UserID` (`UserID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='封禁用户表';
Python
UTF-8
1,393
3.328125
3
[]
no_license
class Node: def __init__(self,val): self.data = val self.next = None def construct(L): root = Node(L[0]) curr = root for i in range(1,len(L)): curr.next = Node(L[i]) curr = curr.next return root def merge(root1,root2): res = None if not root1: return root2 if not root2: return root1 if root1.data < root2.data: res = root1 res.next = merge(root1.next,root2) else: res = root2 res.next = merge(root1,root2.next) return res def middle(root): if not root: return root slow,fast = root,root while fast.next and fast.next.next: slow = slow.next fast = fast.next.next return slow def mergeSort(root): if not root or not root.next: return root mid = middle(root) afterMid = mid.next mid.next = None left = mergeSort(root) right = mergeSort(afterMid) ret = merge(left,right) return ret def printList(root): while root: print(root.data,end=' ') root = root.next def solution(L): # Write your code here... root = construct(L) root = mergeSort(root) printList(root) try: N=int(input()) L=[] n=0 for e in input().split(): if(n<N): L.append(int (e)) n+=1 solution(L) except: print("no element present")
Java
UTF-8
2,461
2.015625
2
[]
no_license
package com.zcbspay.platform.cnaps.beps.message.bean; import java.io.Serializable; /** * 代收付合同协议bean * * @author guojia * @version * @date 2017年2月23日 下午4:00:22 * @since */ public class ContractBean implements Serializable{ /** * serialVersionUID */ private static final long serialVersionUID = 6399563862295246595L; /** * 合同协议类型 */ private String contractType; /** * 协议号 */ private String agreementNumber; /** * 付款人名称 */ private String debtorName; /** * 付款人账号 */ private String debtorAccountNo; /** * 付款人开户行行号 */ private String debtorIssuerCode; /** * 付款清算行行号 */ private String debtorAgentCode; /** * 付款行行号 */ private String debtorBranchCode; /** * 收款人名称 */ private String creditorName; /** * 商户号 */ private String merchNo; public String getContractType() { return contractType; } public void setContractType(String contractType) { this.contractType = contractType; } public String getAgreementNumber() { return agreementNumber; } public void setAgreementNumber(String agreementNumber) { this.agreementNumber = agreementNumber; } public String getDebtorName() { return debtorName; } public void setDebtorName(String debtorName) { this.debtorName = debtorName; } public String getDebtorAccountNo() { return debtorAccountNo; } public void setDebtorAccountNo(String debtorAccountNo) { this.debtorAccountNo = debtorAccountNo; } public String getDebtorIssuerCode() { return debtorIssuerCode; } public void setDebtorIssuerCode(String debtorIssuerCode) { this.debtorIssuerCode = debtorIssuerCode; } public String getDebtorAgentCode() { return debtorAgentCode; } public void setDebtorAgentCode(String debtorAgentCode) { this.debtorAgentCode = debtorAgentCode; } public String getDebtorBranchCode() { return debtorBranchCode; } public void setDebtorBranchCode(String debtorBranchCode) { this.debtorBranchCode = debtorBranchCode; } public String getCreditorName() { return creditorName; } public void setCreditorName(String creditorName) { this.creditorName = creditorName; } public String getMerchNo() { return merchNo; } public void setMerchNo(String merchNo) { this.merchNo = merchNo; } }
Java
UTF-8
15,173
2.15625
2
[]
no_license
package App.HKM; import java.awt.EventQueue; import javax.swing.JFrame; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Arrays; import javax.swing.JLabel; import java.awt.Font; import java.awt.Color; import java.awt.Cursor; import javax.swing.SwingConstants; import javax.swing.JPasswordField; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.LayoutStyle.ComponentPlacement; import App.HKM.Extend.Extend; import App.HKM.Extend.Message; import App.HKM.Extend.TextBubbleBorder; import ServerManagerData.ClientToServer; import java.awt.SystemColor; import javax.swing.ImageIcon; public class ChangeUser { JFrame frame; private JPasswordField txtpassword_ht; private JPasswordField txtpassword_renew; private JPasswordField txtpassword_new; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { if (Login.cache_Login == null) { ChangeUser window = new ChangeUser(); window.frame.setVisible(true); } else { // new Message("Bạn cần đăng nhập để có thể truy cập // vào."); } } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public ChangeUser() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { Extend extend = new Extend(); frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setAlwaysOnTop(true); frame.setBounds(100, 100, 554, 366); JLabel lbliMtKhu = new JLabel("Đổi mật khẩu"); lbliMtKhu.setHorizontalAlignment(SwingConstants.CENTER); lbliMtKhu.setForeground(new Color(75, 0, 130)); lbliMtKhu.setFont(new Font("Tahoma", Font.PLAIN, 21)); JLabel lblXinChoTi = new JLabel("Xin chào tài khoản:"); lblXinChoTi.setIcon(new ImageIcon(ChangeUser.class.getResource("/App/HKM/image/Checkmark_30px.png"))); lblXinChoTi.setFont(new Font("Tahoma", Font.BOLD, 14)); lblXinChoTi.setForeground(Color.GREEN); JLabel User = new JLabel("User"); User.setFont(new Font("Tahoma", Font.BOLD, 14)); User.setForeground(new Color(0, 128, 0)); JLabel lblNhpMtKhu = new JLabel("Nhập mật khẩu hiện tại:"); lblNhpMtKhu.setIcon(new ImageIcon(ChangeUser.class.getResource("/App/HKM/image/Password_30px_1.png"))); lblNhpMtKhu.setFont(new Font("Tahoma", Font.BOLD, 14)); lblNhpMtKhu.setForeground(SystemColor.textHighlight); JLabel lblNhpMtKhu_1 = new JLabel("Nhập mật khẩu mới:"); lblNhpMtKhu_1.setIcon(new ImageIcon(ChangeUser.class.getResource("/App/HKM/image/Plus_30px.png"))); lblNhpMtKhu_1.setForeground(SystemColor.textHighlight); lblNhpMtKhu_1.setFont(new Font("Tahoma", Font.BOLD, 14)); JLabel lblNhpLiMt = new JLabel("Nhập lại mật khẩu mới:"); lblNhpLiMt.setIcon(new ImageIcon(ChangeUser.class.getResource("/App/HKM/image/Registered Trademark_30px.png"))); lblNhpLiMt.setForeground(SystemColor.textHighlight); lblNhpLiMt.setFont(new Font("Tahoma", Font.BOLD, 14)); txtpassword_ht = new JPasswordField(); txtpassword_ht.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { txtpassword_ht.setBorder(new TextBubbleBorder(new Color(135, 206, 235), 2, 4, 0)); } }); txtpassword_ht.setBorder(new TextBubbleBorder(new Color(135, 206, 235), 2, 4, 0)); txtpassword_renew = new JPasswordField(); txtpassword_renew.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { txtpassword_renew.setBorder(new TextBubbleBorder(new Color(135, 206, 235), 2, 4, 0)); } }); txtpassword_renew.setBorder(new TextBubbleBorder(new Color(135, 206, 235), 2, 4, 0)); txtpassword_new = new JPasswordField(); txtpassword_new.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { txtpassword_new.setBorder(new TextBubbleBorder(new Color(135, 206, 235), 2, 4, 0)); } }); txtpassword_new.setBorder(new TextBubbleBorder(new Color(135, 206, 235), 2, 4, 0)); if (Login.cache_Login != null) { User.setText(Login.cache_Login); } JLabel error = new JLabel(""); error.setForeground(new Color(220, 20, 60)); error.setIcon(new ImageIcon(ChangeUser.class.getResource("/App/HKM/image/Info Squared_20px.png"))); JLabel Submit = new JLabel("LƯU"); Submit.setCursor(new Cursor(Cursor.HAND_CURSOR)); Submit.setOpaque(true); Submit.setBorder(new TextBubbleBorder(new Color(135, 206, 235), 2, 4, 0)); txtpassword_renew.addKeyListener(new KeyAdapter() { String password_ht; char[] password_new; char[] password_renew; String errors = ""; @SuppressWarnings("deprecation") @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { this.password_ht = txtpassword_ht.getText(); this.password_new = txtpassword_new.getPassword(); this.password_renew = txtpassword_renew.getPassword(); if (this.password_ht.isEmpty() || String.valueOf(this.password_new).isEmpty() || String.valueOf(this.password_renew).isEmpty()) { errors = "Bạn không được bỏ trống."; txtpassword_ht.setBorder(new TextBubbleBorder(Color.RED, 2, 4, 0)); txtpassword_new.setBorder(new TextBubbleBorder(Color.RED, 2, 4, 0)); txtpassword_renew.setBorder(new TextBubbleBorder(Color.RED, 2, 4, 0)); } else { try { ClientToServer CtS = new ClientToServer("check_exist_record", "admin", "User", "__User__", Login.cache_Login, "", 0); String request = CtS.getValueRequests(); if (request.equals("true")) { CtS = new ClientToServer("check_exist_record", "admin", "User", "__Password__", extend.Token(String.valueOf(this.password_ht)), "", 0); request = CtS.getValueRequests(); if (request.equals("true")) { if (this.password_new.length < 8 || this.password_renew.length < 8) { errors = "Độ dài mật khẩu phải lớn hơn hoặc bằng 8 kí tự."; txtpassword_new.setBorder(new TextBubbleBorder(Color.RED, 2, 4, 0)); txtpassword_renew.setBorder(new TextBubbleBorder(Color.RED, 2, 4, 0)); } else { if (!Arrays.equals(this.password_new, this.password_renew)) { System.out.println(this.password_new); System.out.println(this.password_renew); errors = "mật khẩu nhập lại không khớp."; txtpassword_renew.setBorder(new TextBubbleBorder(Color.RED, 2, 4, 0)); } else { CtS = new ClientToServer("update", "admin", "User", "__User__", Login.cache_Login, "__Password__", extend.Token(String.valueOf(this.password_new)), 0); request = CtS.getValueRequests(); errors = "Đổi mật khẩu thành công."; frame.setAlwaysOnTop(false); new Message("Đổi mật khẩu thành công"); frame.dispose(); } } } } else { errors = "Tài khoản hoặc mật khẩu không khớp."; txtpassword_new.setBorder(new TextBubbleBorder(Color.RED, 2, 4, 0)); txtpassword_renew.setBorder(new TextBubbleBorder(Color.RED, 2, 4, 0)); } } catch (Exception e2) { // TODO: handle exception } } error.setText(errors); txtpassword_ht.setBorder(new TextBubbleBorder(Color.RED, 2, 4, 0)); txtpassword_ht.setBorder(new TextBubbleBorder(Color.RED, 2, 4, 0)); } } }); Submit.addMouseListener(new MouseAdapter() { public String password_ht; public char[] password_new; private char[] password_renew; private String errors = ""; @SuppressWarnings("deprecation") @Override public void mouseClicked(MouseEvent e) { this.password_ht = txtpassword_ht.getText(); this.password_new = txtpassword_new.getPassword(); this.password_renew = txtpassword_renew.getPassword(); if (this.password_ht.isEmpty() || String.valueOf(this.password_new).isEmpty() || String.valueOf(this.password_renew).isEmpty()) { errors = "Bạn không được bỏ trống."; txtpassword_ht.setBorder(new TextBubbleBorder(Color.RED, 2, 4, 0)); txtpassword_new.setBorder(new TextBubbleBorder(Color.RED, 2, 4, 0)); txtpassword_renew.setBorder(new TextBubbleBorder(Color.RED, 2, 4, 0)); } else { try { ClientToServer CtS = new ClientToServer("check_exist_record", "admin", "User", "__User__", Login.cache_Login, "", 0); String request = CtS.getValueRequests(); if (request.equals("true")) { CtS = new ClientToServer("check_exist_record", "admin", "User", "__Password__", extend.Token(String.valueOf(this.password_ht)), "", 0); request = CtS.getValueRequests(); if (request.equals("true")) { if (this.password_new.length < 8 || this.password_renew.length < 8) { errors = "Độ dài mật khẩu phải lớn hơn hoặc bằng 8 kí tự."; txtpassword_new.setBorder(new TextBubbleBorder(Color.RED, 2, 4, 0)); txtpassword_renew.setBorder(new TextBubbleBorder(Color.RED, 2, 4, 0)); } else { if (!Arrays.equals(this.password_new, this.password_renew)) { System.out.println(this.password_new); System.out.println(this.password_renew); errors = "mật khẩu nhập lại không khớp."; txtpassword_renew.setBorder(new TextBubbleBorder(Color.RED, 2, 4, 0)); } else { CtS = new ClientToServer("update", "admin", "User", "__User__", Login.cache_Login, "__Password__", extend.Token(String.valueOf(this.password_new)), 0); request = CtS.getValueRequests(); errors = "Đổi mật khẩu thành công."; frame.setAlwaysOnTop(false); new Message("Đổi mật khẩu thành công"); frame.dispose(); } } } } else { errors = "Tài khoản hoặc mật khẩu không khớp."; txtpassword_new.setBorder(new TextBubbleBorder(Color.RED, 2, 4, 0)); txtpassword_renew.setBorder(new TextBubbleBorder(Color.RED, 2, 4, 0)); } } catch (Exception e2) { // TODO: handle exception } } error.setText(errors); txtpassword_ht.setBorder(new TextBubbleBorder(Color.RED, 2, 4, 0)); txtpassword_ht.setBorder(new TextBubbleBorder(Color.RED, 2, 4, 0)); } }); Submit.setFont(new Font("Tahoma", Font.PLAIN, 21)); Submit.setHorizontalAlignment(SwingConstants.CENTER); Submit.setBackground(new Color(210, 180, 140)); Submit.setForeground(new Color(220, 20, 60)); GroupLayout groupLayout = new GroupLayout(frame.getContentPane()); groupLayout .setHorizontalGroup( groupLayout.createParallelGroup(Alignment.LEADING) .addGroup( groupLayout.createSequentialGroup().addGap(7) .addGroup(groupLayout .createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup() .addComponent(lbliMtKhu, GroupLayout.DEFAULT_SIZE, 533, Short.MAX_VALUE) .addContainerGap()) .addGroup(groupLayout.createSequentialGroup() .addComponent(lblXinChoTi).addGap(18).addComponent(User) .addContainerGap()) .addGroup(groupLayout.createSequentialGroup() .addGroup(groupLayout .createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup() .addGroup(groupLayout .createParallelGroup( Alignment.LEADING) .addComponent(lblNhpLiMt) .addComponent(lblNhpMtKhu) .addComponent(lblNhpMtKhu_1)) .addGap(27) .addGroup(groupLayout .createParallelGroup( Alignment.LEADING) .addComponent(txtpassword_renew, GroupLayout.DEFAULT_SIZE, 182, Short.MAX_VALUE) .addGroup(Alignment.TRAILING, groupLayout .createSequentialGroup() .addPreferredGap( ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent( txtpassword_ht, GroupLayout.PREFERRED_SIZE, 182, GroupLayout.PREFERRED_SIZE)) .addComponent(txtpassword_new, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 182, Short.MAX_VALUE)) .addGap(19)) .addGroup(groupLayout.createSequentialGroup() .addGap(28).addComponent(error) .addPreferredGap( ComponentPlacement.RELATED))) .addComponent(Submit, GroupLayout.PREFERRED_SIZE, 79, GroupLayout.PREFERRED_SIZE) .addGap(37))))); groupLayout.setVerticalGroup(groupLayout.createParallelGroup(Alignment.TRAILING).addGroup(groupLayout .createSequentialGroup().addGap(7).addComponent(lbliMtKhu) .addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(lblXinChoTi) .addComponent(User)) .addGap(35) .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(lblNhpMtKhu).addComponent( txtpassword_ht, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGap(33) .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(lblNhpMtKhu_1).addComponent( txtpassword_new, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGap(33) .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(lblNhpLiMt).addComponent( txtpassword_renew, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGap(18) .addGroup(groupLayout.createParallelGroup(Alignment.TRAILING) .addComponent(Submit, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE) .addComponent(error)) .addGap(25))); frame.getContentPane().setLayout(groupLayout); } }
C++
UTF-8
407
3.0625
3
[]
no_license
#include<iostream> using namespace std; int main(){ int a, b, i, j, counter=0; cin >> a >> b; for(i=a;i <= b;i++){ string current = to_string(i); for(j=0;j < current.length() / 2 ;j++){ if(current[j] != current[current.length() - j - 1]) break; } if(j != 0 && j == current.length() / 2) counter++; } cout << counter << endl; return 0; }
Python
UTF-8
157
3.375
3
[]
no_license
import classcars car = classcars.Cars('red', 'big') print('your car\'s color is:{},shape is:{},now you can drive it。'.format(car.color, car.shape))
C++
UTF-8
1,318
2.703125
3
[ "MIT" ]
permissive
#include<stdio.h> #include<iostream> #include<cmath> #include<algorithm> #include<cstring> #include<map> #include<set> #include<vector> #include<utility> #include<math.h> #define sd(x) scanf("%d",&x); #define sd2(x,y) scanf("%d %d",&x,&y); #define sd3(x,y,z) scanf("%d %d %d",&x,&y,&z); #define sull(x) scanf("%ull",&x); #define print(x) printf("%d\n",x); #define print2(x,y) printf("%d %d\n",x,y); #define print3(x,y,z) printf("%d %d %d\n",x,y,z); #define printull(x) printf("%ull\n",x); using namespace std; int main(){ int n, m, A[500][500], B[500][500], dp[500][500], temp; //A and B are the cummulative sums of Y and B sd2(n,m); while(n > 0 and m > 0){ for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ sd(temp); A[i][j] = (j)? temp + A[i][j-1]: temp; } } for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ sd(temp); B[i][j] = (i)? temp + B[i-1][j]: temp; } } dp[0][0] = max(A[0][0], B[0][0]); for(int i = 1; i < m; i++) dp[0][i] = max(A[0][i], B[0][i] + dp[0][i-1]); for(int i = 1; i < n; i++) dp[i][0] = max(A[i][0] + dp[i-1][0], B[i][0]); for(int i = 1; i < n; i++) for(int j = 1; j < m; j++) dp[i][j] = max(A[i][j] + dp[i-1][j], B[i][j] + dp[i][j-1]); printf("%d\n", dp[n-1][m-1]); sd2(n,m); } return 0; }
Java
UTF-8
748
3.203125
3
[]
no_license
// @Title: 最长和谐子序列 (Longest Harmonious Subsequence) // @Author: 15218859676 // @Date: 2020-11-29 22:55:32 // @Runtime: 15 ms // @Memory: 38.7 MB class Solution { public int findLHS(int[] nums) { //返回最长和谐子序列的长度 //和谐子序列:数组中元素最大和最小值差是1 int len = nums.length; if(len < 2){ return 0; } Arrays.sort(nums); int begin = 0; int res = 0; for(int i = 0 ; i < len ; i++){ while(nums[i] - nums[begin] > 1){ begin++; }if(nums[i] - nums[begin] == 1){ res = Math.max(res, i - begin + 1); } } return res; } }
Shell
UTF-8
788
2.78125
3
[]
no_license
cd /home/project/core ./build.sh echo " ====> 更新module-manage项目开始 ..." path="/home/project/module/manage" cd $path back=$path"/backup/`date +%G_%m_%d_%H_%M_%S`" echo " ====> 项目更新中 ..." svn co --username xxx --password xxx https://192.168.1.254/svn/developer/trunk/module-parent/module-manage module-manage cd module-manage echo " ====> 项目编译打包中 ..." mvn clean package install -DskipTests mv $path"/deploy" $back echo " ====> 开始解压 module-manage.war ..." unzip -oq /manage-1.0.0-SNAPSHOT.war -d /home/project/module/manage/deploy echo " ====> 开始重启manage-module-tomcat中 ..." cd /home/server/module/manage-module-tomcat/bin ./shutdown.sh ./startup.sh & tail -f ../logs/catalina.out echo " ====> 主人,项目部署完毕了 ..."
PHP
UTF-8
1,509
2.703125
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class AddToCardController extends Controller { public function addToCart($id) { $cart = session()->get('cart'); if (!$cart){ $cart = [$id => $this->sessionData($this->getSeat($id), $id)]; return $this->setSessionAndReturnResponse($cart); } $cart[$id] = $this->sessionData($this->getSeat($id), $id); return $this->setSessionAndReturnResponse($cart); } public function removeFromCart($id) { $cart = session()->get('cart'); if (isset($cart[$id])){ unset($cart[$id]); session()->put('cart', $cart); } return redirect()->back()->with('success', "Successfully Removed from Cart"); } protected function sessionData($data, $id){ return [ 'seat_id' => $id, 'seat_no' => $data, 'quantity' => 1, ]; } protected function setSessionAndReturnResponse($cart){ session()->put('cart', $cart); return redirect()->back()->with('success', "Successfully Added to Cart"); } public function getSeat($id) { $y=0; foreach(range('A', 'J') as $key=>$column) { for ($k=1; $k<=4; $k++) { $y=$y+1; if ($y == $id) { $data = $column.$k; } } } return $data; } }
C
UTF-8
25,767
2.515625
3
[]
no_license
// CDCL.c // Joshua Blinkhorn 29.04.2019 // This file is part of CDCL #include "CDCL.h" #include <stdlib.h> #include <stdio.h> #include <math.h> #include <limits.h> #include <time.h> #include "getRSS.c" #ifdef DEBUG #define DEBUG_MSG(x) (x) #else #define DEBUG_MSG(x) #endif // MACROS // results #define UNSAT 0 #define SAT 1 // truth values #define UNASSIGNED 0 #define POSITIVE 1 #define NEGATIVE -1 // assignment types #define DEC_ASS 0 #define PROP_ASS 1 #define CON_ASS 2 // special values #define NULL_DEC_LEVEL ULONG_MAX - 1 #define MAX_VARS ULONG_MAX / 2 // low level types typedef unsigned char result_t; typedef signed char truth_value_t; typedef unsigned char ass_type_t; typedef signed long int DIMACS_lit_t; typedef unsigned long int cnf_size_t; typedef unsigned long int var_set_size_t; // deprecate typedef unsigned long int model_size_t; // deprecate typedef unsigned long int mutable_size_t; typedef unsigned long int lit_t; typedef signed long int DIMACS_lit_t; // stats clock_t start_time; // higher level types // cls // a clause is a pointer to a literal. It names an array of literals. // note that the cls_t typedef is superflous, we could use lit_t* instead, but it // might be useful if later on we need a more sophisticated clause object typedef lit_t* cls_t; // cnf // a CNF is a struct storing (1) an array of clauses and (2) the size of the array typedef struct cnf { cls_t* clauses; cnf_size_t size; } cnf_t; // mutable (array) // this is an automatically resized array of pointers to lit_t. // it can be used to store a cnf, or a list of pointers to literals (e.g. the // watched literals for a singleton assignment), which can also be thought of // as a set of unit clauses // the array becomes twice as large whenever necessary to add an item typedef struct mutable { lit_t** data; mutable_size_t size; mutable_size_t used; } mutable_t; // assignment // stores various information about a singleton assignment, including // a list of watched literals typedef struct ass { truth_value_t truth_value; dec_level_t dec_level; ass_type_t ass_type; mutable_t watched_lits; } ass_t; // trail // a trail is an ordered sequence of pointers literals // it is allocated as a fixed size array, since it size never exceeds // the number of variables // head and tail are pointers into the array used in propagation typedef struct trail { ass_t** sequence; ass_t** head; ass_t** tail; } trail_t; // global solver var_set_size_t num_vars; var_set_size_t num_asses; unsigned long num_conflicts = 0; unsigned long num_decisions = 0; unsigned long num_unit_props = 0; unsigned long num_redefinitions = 0; cnf_t cnf; mutable_t learned_cnf; ass_t* model; trail_t trail; state_t stat; // IMPLEMENTATION void error(char* message); // LITERAL RELATED FUNCTIONS lit_t DIMACS_to_lit(DIMACS_lit_t value) { // converts a DIMACS literal into an internal literal // internal literals are represented as values from 0 to (2 * num_vars) - 1 // values from 0 to num_vars - 1 represent positive literals, // values from num_vars to (2 * num_vars) - 1 represent negative literals. return (lit_t) ((value < 0 ? -1 : 1) * value) - 1 + ((value < 0) * num_vars); } DIMACS_lit_t lit_to_DIMACS(lit_t lit) { // converts an internal literal back into a DIMACS literal // this should only ever be used for printing literal values return (DIMACS_lit_t)((lit % num_vars) + 1) * ((lit < num_vars) ? 1 : -1); } truth_value_t lit_truth_value(lit_t* lit) { // determines the truth value of the literal under the current assignment return (model + *lit)->truth_value; } lit_t ass_to_lit(ass_t* ass) { // determines the literal satisfied by the assignment pointed to by ass return (lit_t)(ass - model); } lit_t get_comp_lit(lit_t lit) { // returns the complementary literal return lit + ((lit < num_vars? 1 : -1) * num_vars); } void lit_print(lit_t* lit) { //fprintf(stderr, "%lu", *lit); // prints an internal literal in the form of a DIMACS literal fprintf(stderr, "%ld", lit_to_DIMACS(*lit)); } void lit_print_binary(lit_t* lit) { // prints the bitwise encoding of the literal size_t which_bit, num_bits; num_bits = sizeof(*lit) * 8; for (which_bit = 0; which_bit < num_bits; which_bit++) { fprintf(stderr,"%lu", (*lit >> (num_bits - which_bit - 1)) & (lit_t)1); } } // CLAUSE RELATED FUNCTIONS cls_t cls_init(lit_t width) { // initialises a clause of size `width' // the fist `literal' is the size of the clause cls_t cls; if ((cls = (lit_t*)malloc(sizeof(lit_t) * (width + 1))) == NULL) error("cannot allocate clause"); cls[0] = width; return cls; } char cls_is_unit(cls_t cls) { // returns 1 if the given clause is a unit clause, 0 otherwise return (cls[0] == 1) ? 1 : 0; } void cls_free(cls_t cls) { free(cls); } void cls_print(cls_t cls) { var_set_size_t width = cls[0]; var_set_size_t which_lit; for(which_lit = 1; which_lit <= width; which_lit++) { lit_print(cls + which_lit); fprintf(stderr, " "); } } // CNF RELATED FUNCTIONS void cnf_print() { cnf_size_t which_clause; fprintf(stderr, "FORMULA:\n"); for(which_clause = 0; which_clause < cnf.size; which_clause++) { cls_print(cnf.clauses[which_clause]); fprintf(stderr, "\n"); } } // MUTABLE RELATED FUNCTIONS void mutable_init(mutable_t* mutable) { // allocate memory for data - default size is 1 if ((mutable->data = (lit_t**)malloc(sizeof(lit_t*))) == NULL) error("cannot allocate mutable data"); // set default member values mutable->size = 1L; mutable->used = 0L; } // use this to free a watched literal list void mutable_free(mutable_t* mutable) { // frees only the data of the pointed to mutable free(mutable->data); } // use this to free learned cnf void mutable_free_clauses(mutable_t* mutable) { // frees both the data of the pointed to mutable, and the clauses // that the data points to cnf_size_t which_clause, num_clauses; num_clauses = mutable->used; for(which_clause = 0; which_clause < num_clauses; which_clause++) cls_free(mutable->data[which_clause]); free(mutable->data); } void mutable_push(mutable_t* mutable, lit_t* datum) { // pushes the datum onto the mutable's data array mutable_size_t size; if (mutable->used == (size = mutable->size)) { if ((mutable->data = (lit_t**)realloc(mutable->data, 2 * size * sizeof(lit_t*))) == NULL) error("cannot reallocate mutable data"); mutable->size = 2 * size; mutable->data[mutable->used++] = datum; } else { mutable->data[mutable->used++] = datum; } } // use to print a learned cnf void mutable_print_clauses(mutable_t* mutable) { mutable_size_t which_clause, num_clauses; lit_t** data; fprintf(stderr, "LEARNED CLAUSES:\n"); fprintf(stderr, "size: %lu, used: %lu\n", mutable->size, mutable->used); num_clauses = mutable->used; data = mutable->data; for(which_clause = 0; which_clause < num_clauses; which_clause++) { cls_print(data[which_clause]); fprintf(stderr, "\n"); } } // use to print a watched literal list void mutable_print_lits(mutable_t* mutable) { mutable_size_t which_lit, num_lits; lit_t** data; fprintf(stderr, "size: %lu, used: %lu, literals:", mutable->size, mutable->used); num_lits = mutable->used; data = mutable->data; for(which_lit = 0; which_lit < num_lits; which_lit++) { lit_print(data[which_lit]); } fprintf(stderr, "\n"); } void print_watched_lits() { model_size_t which_ass; fprintf(stderr, "WATCHED LITERALS\n"); for (which_ass = 0; which_ass < num_asses; which_ass++) { mutable_print_lits(&(model[which_ass].watched_lits)); } fprintf(stderr, "\n"); } // ASSIGNMENT RELATED FUNCTIONS void assign_by_lit(lit_t lit) { // overwrites the assignment satisfying the literal into the model // the assignment type should already have been set when the literal // was added to the trail lit_t comp_lit = get_comp_lit(lit); model[lit].truth_value = POSITIVE; model[lit].dec_level = dec_level; model[comp_lit].truth_value = NEGATIVE; model[comp_lit].dec_level = dec_level; } void unassign_by_lit(lit_t lit) { // unassigns the variable for this literal (i.e. for the literal and its complement) // lit_t comp_lit = get_comp_lit(lit); model[lit].truth_value = UNASSIGNED; model[comp_lit].truth_value = UNASSIGNED; } // prints the value of an assignment and its decision level void ass_print(ass_t* ass) { dec_level_t dec_level = ass->dec_level; if(ass->truth_value == UNASSIGNED) fprintf(stderr, "0 "); else { fprintf(stderr, "%2d / %ld ", ass->truth_value, dec_level == NULL_DEC_LEVEL ? -1L : (long)dec_level); switch(ass->ass_type) { case DEC_ASS: fprintf(stderr, "D "); break; case PROP_ASS: fprintf(stderr, "P "); break; case CON_ASS: fprintf(stderr, "C "); break; default: break; } } } // this function assumes trail.head > trail.sequence void backtrack(dec_level_t new_dec_level) { DEBUG_MSG(fprintf(stderr, "In backtrack(). Backtracking to decision level %lu.\n", new_dec_level)); // go backwards through the trail and delete the assignments while((trail.head >= trail.sequence) && ((*(trail.head))->dec_level > new_dec_level)) { unassign_by_lit(*trail.head - model); trail.head--; } trail.head++; trail.tail = trail.head; //revert to given decision level dec_level = new_dec_level; } // MODEL RELATED FUNCTIONS // prints the contents of the given model void print_model() { var_set_size_t which_var; fprintf(stderr, "MODEL:\n"); // print the assignment for(which_var = 0; which_var < num_vars; which_var++) { fprintf(stderr, "%lu: ", which_var + 1); ass_print(model + which_var); fprintf(stderr, "\n"); } fprintf(stderr, "\n"); } // TRAIL RELATED FUNCTIONS void trail_add_ass(ass_t* ass) { *(trail.tail) = ass; trail.tail++; } void trail_add_lit(lit_t lit, ass_type_t ass_type) { model[lit].ass_type = ass_type; model[get_comp_lit(lit)].ass_type = ass_type; *(trail.tail) = model + lit; trail.tail++; } void print_trail() { ass_t** temp_pointer; fprintf(stderr, "TRAIL: "); if (trail.sequence == trail.tail) { fprintf(stderr, " (empty)\n\n"); return; } fprintf(stderr, "\n"); for(temp_pointer = trail.sequence; temp_pointer < trail.tail; temp_pointer++) { fprintf(stderr, "%lu: %ld ", temp_pointer - trail.sequence + 1, lit_to_DIMACS(*temp_pointer - model)); if ((*temp_pointer)->truth_value == UNASSIGNED) fprintf(stderr, "U "); else switch((*temp_pointer)->ass_type) { case DEC_ASS: fprintf(stderr, "D "); break; case PROP_ASS: fprintf(stderr, "P "); break; case CON_ASS: fprintf(stderr, "C "); break; default: break; } if (temp_pointer == trail.head) fprintf(stderr, "HEAD"); if (temp_pointer == trail.tail) fprintf(stderr, "TAIL"); fprintf(stderr, "\n"); } fprintf(stderr, "\n"); } // CDCL INTERFACE IMPLEMENTATION void CDCL_print_stats() { fprintf(stderr, "Conflicts: %lu\n", num_conflicts); fprintf(stderr, "Decisions: %lu\n", num_decisions); fprintf(stderr, "Unit Propagations: %lu\n", num_unit_props); //fprintf(stderr, "Redefinitions: %lu\n", num_redefinitions); fprintf(stderr, "%1.1lfs ", ((double)(clock() - start_time)) / CLOCKS_PER_SEC); fprintf(stderr, "%1.1zdMb ", getPeakRSS() / 1048576); fprintf(stderr, "\n"); } void CDCL_report_SAT() { print_model(); fprintf(stderr, "v SAT\n"); CDCL_print_stats(); exit(0); } void CDCL_report_UNSAT() { fprintf(stderr, "v UNSAT\n"); CDCL_print_stats(); exit(0); } // initialises global solver according to the DIMACS file 'input'. void CDCL_init(char* DIMACS_filename) { FILE* input, *cursor; char buffer[5]; // used only to read the `cnf' string from the input file char ch; // used to read single characters from the input file DIMACS_lit_t DIMACS_lit; // temporary literal for reading var_set_size_t width; var_set_size_t which_lit; var_set_size_t which_ass; cnf_size_t which_clause; cls_t cls; start_time = clock(); state = DECIDE; // open file connections // TODO: currently using two file connections to find size of clauses before writing // them; it is probably possible to use just one, and to traverse the stream // backwards when needed if ((input = (FILE *)fopen(DIMACS_filename, "r")) == NULL) error("cannot open file"); if ((cursor = (FILE *)fopen(DIMACS_filename, "r")) == NULL) error("cannot open file"); // parse header // disregard comment lines while ((ch = fgetc(input)) == 'c') while ((ch = fgetc(input)) != '\n') continue; while ((ch = fgetc(cursor)) == 'c') while ((ch = fgetc(cursor)) != '\n') continue; // read header line if (ch != 'p') error("bad input - 'p' not found"); if ((fscanf(input, "%s", buffer)) != 1) error("bad input - 'cnf' not found"); fscanf(cursor, "%s", buffer); // read number of variables if ((fscanf(input, "%lu", &(num_vars))) != 1) error("bad input - number of vars missing"); fscanf(cursor, "%lu", &(num_vars)); if (num_vars > pow(2,(sizeof(lit_t) * 8) - 3) - 1) // i.e. more variables than our data type can handle error("too many vars"); num_asses = num_vars * 2; // initialise model if ((model = (ass_t*)malloc(sizeof(ass_t) * num_asses)) == NULL) error("cannot allocate model"); for (which_ass = 0; which_ass < num_asses; which_ass++) { // set default values and initialise watched literals mutable for each assignment model[which_ass].truth_value = UNASSIGNED; mutable_init(&(model[which_ass].watched_lits)); } // initialise trail if ((trail.sequence = (ass_t**)malloc(sizeof(ass_t*) * num_asses)) == NULL) error("cannot allocate trail sequence"); trail.head = trail.sequence; trail.tail = trail.sequence; // read number of clauses if(fscanf(input, "%lu", &cnf.size) != 1) error("bad input - number of clauses not found"); fscanf(cursor, "%lu", &cnf.size); // initialise cnf if ((cnf.clauses = (cls_t*)malloc(sizeof(cls_t) * cnf.size)) == NULL) error("cannot allocate cnf clauses"); // allocate clauses and add to formula for(which_clause = 0; which_clause < cnf.size; which_clause++) { // find width of clause with cursor fscanf(cursor, "%ld", &DIMACS_lit); for(width = 0; DIMACS_lit != 0; width++) fscanf(cursor, "%ld", &DIMACS_lit); // if the width is 0, note that the formula is UNSAT and return if (width == 0) { CDCL_report_UNSAT(); exit(0); } // if the width is 1, add the assignment as a level 0 unit propagation if (width == 1) { fscanf(input, "%ld", &DIMACS_lit); trail_add_lit(DIMACS_to_lit(DIMACS_lit), PROP_ASS); fscanf(input, "%ld", &DIMACS_lit); state = PROPAGATE; // we do not store unit clauses, so decrement counters cnf.size--; which_clause--; } else { // initialise clause cls = cls_init(width); // set liqterals with input which_lit = 1; fscanf(input, "%ld", &DIMACS_lit); while(DIMACS_lit != 0) { cls[which_lit] = DIMACS_to_lit(DIMACS_lit); fscanf(input, "%ld", &DIMACS_lit); which_lit++; } // put the clause into the cnf cnf.clauses[which_clause] = cls; // watch the first two literals mutable_push(&(model[get_comp_lit(cls[1])].watched_lits), cls); mutable_push(&(model[get_comp_lit(cls[2])].watched_lits), cls); } } // set default decision level dec_level = 0; // initialise empty learned clause list mutable_init(&(learned_cnf)); } void CDCL_free() { cnf_size_t which_clause; var_set_size_t which_ass; // free memory for the cnf for (which_clause = 0; which_clause < cnf.size; which_clause++) cls_free(cnf.clauses[which_clause]); free(cnf.clauses); // free memory for the learned cnf mutable_free_clauses(&learned_cnf); // free memory for the model for (which_ass = 0; which_ass < num_asses; which_ass++) mutable_free(&(model[which_ass].watched_lits)); free(model); // free memory for the trail free(trail.sequence); } // TODO: the watched literals should be the first two in the clause // then we can deal with them by swapping them explicitly with some other literal, // if possible // handles the entire propagation cycle in a single function // head should immediately precede tail of the trail when this function // is called, // in case of conflict, tail will exceed head when it returns // otherwise tail and head will be identical // this function is responsible for all watched literals handling, except for the // assignment of inital watched literals of learned clause, which is handled // by conflict analysis // the assignment at head when the function is called is handled first // the watched literals are visited in order // the function first attemps to push the watch to another literal // if the clause is found to be unit, the assignment is checked for conflict // if conflict is found, the watched literals for the current assignment are // cleaned up and the function returns CONFLICT // if no conflict is found, the unit assignment is added to the tail of the trail // when all clauses have been visited, the trail head is incremented // the function returns NO_CONFLICT when head and tail are again identical state_t CDCL_prop() { lit_t* watched_lit, *other_watched_lit, *candidate_lit; lit_t temp_lit; var_set_size_t which_lit; cls_t clause; cnf_size_t num_clauses, which_clause; mutable_t new_watchers; model_size_t propagator, width; ass_t** temp_head; lit_t** data; //ass_t* ass; DEBUG_MSG(fprintf(stderr, "In CDCL_prop()..\n")); while (trail.head != trail.tail) { // store the literal that we are propagating propagator = *(trail.head) - model; // add the propagating assignment to the model, set all successive additions // as propagations assign_by_lit(propagator); // fetch a pointer to the list of watched literals, and its size data = model[propagator].watched_lits.data; num_clauses = model[propagator].watched_lits.used; // initialise a new mutable for the replacement list mutable_init(&new_watchers); DEBUG_MSG(fprintf(stderr, "Propagating literal %ld on %lu clauses\n", lit_to_DIMACS(propagator), num_clauses)); DEBUG_MSG(print_model()); DEBUG_MSG(print_trail()); DEBUG_MSG(print_watched_lits()); // cycle through the watched literals' clauses for (which_clause = 0; which_clause < num_clauses; which_clause++) { // get the current clause and its width clause = data[which_clause]; width = *clause; DEBUG_MSG(fprintf(stderr, "Dealing with clause: ")); DEBUG_MSG(cls_print(clause)); // get pointers to the watched literal being processed, // the other watched literal, and the first candidate literal if (clause[1] == get_comp_lit(propagator)) { watched_lit = clause + 1; other_watched_lit = clause + 2; } else { watched_lit = clause + 2; other_watched_lit = clause + 1; } // if the other watched literal is satisfied, we leave the clause as it is if (lit_truth_value(other_watched_lit) == POSITIVE) { // so the watched literal goes onto the replacement list mutable_push(&new_watchers, clause); DEBUG_MSG(fprintf(stderr, " -> ")); DEBUG_MSG(cls_print(clause)); DEBUG_MSG(fprintf(stderr, " (no change - other watched literal is satisfied)\n")); } else { // cycle through the remaining candidate literals for(which_lit = 3; which_lit <= width; which_lit++) { candidate_lit = clause + which_lit; if (lit_truth_value(candidate_lit) != NEGATIVE) { // we found an eligible literal // swap it for the original watched literal temp_lit = *candidate_lit; *candidate_lit = *watched_lit; *watched_lit = temp_lit; // add it to the appropriate list mutable_push(&(model[get_comp_lit(*watched_lit)].watched_lits), clause); DEBUG_MSG(fprintf(stderr, " -> ")); DEBUG_MSG(cls_print(clause)); DEBUG_MSG(fprintf(stderr, "\n")); // force inner loop to terminate break; } } if (which_lit > width) { // we have a unit clause based on the other watched literal DEBUG_MSG(fprintf(stderr, "found unit clause %ld", lit_to_DIMACS(*other_watched_lit))); num_unit_props++; // the watched literal should be placed on the replacement list mutable_push(&new_watchers, clause); // the implied assignment is not in the model, nor is its negation // but either may be on the trail // cycle through the trail for (temp_head = trail.sequence; temp_head < trail.tail; temp_head++) { if (*other_watched_lit == *temp_head - model) { // the implied assignment is already on the trail DEBUG_MSG(fprintf(stderr, " -- ignoring repeated unit clause.\n")); break; } if (*other_watched_lit == get_comp_lit(*temp_head - model)) // the implied assignment yields a conflict { DEBUG_MSG(fprintf(stderr, " -- detected conflict - aborting propagation.\n")); // add clauses for unprocessed watched literals to replacement // list for (which_clause++; which_clause < num_clauses; which_clause++) mutable_push(&new_watchers, data[which_clause]); // free the old data and instate the new list mutable_free(&(model[propagator].watched_lits)); model[propagator].watched_lits = new_watchers; return CONFLICT; } } if (temp_head == trail.tail) { // add unit assignment to trail trail_add_lit(*other_watched_lit, PROP_ASS); DEBUG_MSG(fprintf(stderr, " -- added to trail.\n")); } } } } // propagation for this assignment has completed without conflict // instate new watched lits mutable_free(&(model[propagator].watched_lits)); model[propagator].watched_lits = new_watchers; // increment head trail.head++; DEBUG_MSG(fprintf(stderr, "Completed propagation on literal %ld without conflict\n", lit_to_DIMACS(propagator))); } // propagation terminates without a conflict DEBUG_MSG(fprintf(stderr,"Propagation cycle complete.\n")); return DECIDE; } // easy decision heuristic: assigns the first unassigned variable positively // trail.head and trail.tail are always equal when CDCL_decide() is called // and point to the location after the final assignment // if the function returns PROPAGATE, trail.head points to the location of // the final assignment, trail.tail to the next location. int CDCL_decide() { model_size_t which_ass; DEBUG_MSG(fprintf(stderr, "In CDCL_decide(). ")); num_decisions++; // find an unassigned var for (which_ass = 0; which_ass < num_vars; which_ass++) { if(model[which_ass].truth_value == UNASSIGNED) { // set assignment type model[which_ass].ass_type = DEC_ASS; model[which_ass + num_vars].ass_type = DEC_ASS; // put the assignment on the trail trail_add_lit(which_ass, DEC_ASS); // update decision level dec_level++; DEBUG_MSG(fprintf(stderr, "Made decision %lu.\n", lit_to_DIMACS(which_ass))); DEBUG_MSG(print_model()); DEBUG_MSG(print_trail()); return PROPAGATE; } } DEBUG_MSG(fprintf(stderr, "No decision possible.\n")); return SUCCESS; } // the simplest clause learning: DPLL-style // learn clauses that encode DPLL brandhing void CDCL_repair_conflict() { cls_t learned_cls; model_size_t which_var; DEBUG_MSG(fprintf(stderr, "In CDCL_repair_conflict.")); num_conflicts++; if (dec_level == 0) CDCL_report_UNSAT(); // decision level 1 is a special case - no clause actually need be learned if (dec_level != 1) { // construct the learned clause learned_cls = cls_init(dec_level); for (which_var = 0; which_var < num_vars; which_var++) { if((model[which_var].truth_value != UNASSIGNED) && (model[which_var].ass_type == DEC_ASS)) { // put the highest decision level literals first learned_cls[dec_level - model[which_var].dec_level + 1] = (model[which_var].truth_value == POSITIVE) ? get_comp_lit(which_var) : which_var; } } DEBUG_MSG(fprintf(stderr, "Learned clause: ")); DEBUG_MSG(cls_print(learned_cls)); DEBUG_MSG(fprintf(stderr, "\n")); // watch the highest level literals in the clause mutable_push(&(model[get_comp_lit(learned_cls[1])].watched_lits), learned_cls); mutable_push(&(model[get_comp_lit(learned_cls[2])].watched_lits), learned_cls); // add clause to the formula mutable_push(&learned_cnf, learned_cls); } // note that backtracking leaves the head pointing to the last decision assignment. // backtrack, and add the negation of the last decision (as PROP_ASS) to the trail backtrack(dec_level - 1); trail_add_lit(get_comp_lit(*(trail.head) - model), CON_ASS); } void CDCL_print() { cnf_print(); fprintf(stderr, "\n"); mutable_print_clauses(&learned_cnf); print_model(); print_trail(); // print_watched_lits(); } // error function implementation void error(char* message) { fprintf(stderr, "FATAL ERROR: %s.\n", message); exit(1); }
Java
UTF-8
234
2.9375
3
[ "MIT" ]
permissive
class Solution { public int titleToNumber(String s) { int result = 0; for(int i=s.length()-1;i>=0;i--){ result+=(s.charAt(i)-'A'+1)*Math.pow(26,s.length()-1-i); } return result; } }
Markdown
UTF-8
8,268
3.359375
3
[]
no_license
Реализовать алгоритмы матричных операций: Замечание: можно реализовать алгоритмы самостоятельно или воспользоваться готовыми библиотеками. Для большинства операций используется библиотека Apache Commons Math Создание матрицы происходит следующим образом: ```java // Импортируем используемые библиотеки import org.apache.commons.math3.linear.MatrixUtils; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.RealMatrixFormat; // Создаем двумерный массив с данными для матрицы double[][] firstData = { {3, -5, 4}, {1, 5, -6}}; // Вызываем библиотечную функцию для создания матрицы из двумерного массива RealMatrix firstMatrix = MatrixUtils.createRealMatrix(firstData); // Аналагично для следующих матриц // Матрица для сложиния и вычитания // Создаем двумерный массив с данными для матрицы double[][] secondData = { {7, 4, 9}, {4, -3, -8}}; // Вызываем библиотечную функцию для создания матрицы из двумерного массива RealMatrix secondMatrix = MatrixUtils.createRealMatrix(secondData); // Матрица для умножения // Создаем двумерный массив с данными для матрицы double[][] thirdData = { {1, 2}, {6, 3}, {7, 1}}; // Вызываем библиотечную функцию для создания матрицы из двумерного массива RealMatrix thirdMatrix = MatrixUtils.createRealMatrix(thirdData); // Создаем объект для форматированного вывода RealMatrixFormat output = new RealMatrixFormat("", "", "", "", "\n", " "); ``` * Задания: 1) подпрограмму транспонирования матрицы Входные данные: два целых числа n и m (n – количество строк, m – количество столбцов), матрица размерности n x m Выходные данные: транспонированная матрица размерности m x n * Решение: ```java // Создание форматированной транспонированной матрицы output.format(firstMatrix.transpose()); // Вывод в консоль System.out.printf("Транспонированая матрица:\n%s\n", output.format(firstMatrix.transpose())); ``` * Результат вывода в консоль: ```text Транспонированая матрица: 3 1 -5 5 4 -6 ``` 2) подпрограмму умножения матрицы на число Входные данные: число-множитель, два целых числа n и m (n – количество строк, m – количество столбцов), матрица размерности n x m Выходные данные: матрица – результат умножения числа-множителя на исходную матрицу * Решение: ```java // Число-множитель int number = 8; // Создание форматированной матрицы умноженной на число output.format(firstMatrix.scalarMultiply(number)); // Вывод в консоль System.out.printf("Матрица умноженная на число %d:\n%s\n", number, output.format(firstMatrix.scalarMultiply(number))); ``` * Результат вывода в консоль: ```text Матрица умноженная на число 8: 24 -40 32 8 40 -48 ``` 3) подпрограмму сложения матриц Входные данные: два целых числа n и m (n – количество строк, m – количество столбцов), матрица_1 размерности n ´ m, матрица_2 размерности n ´ m Выходные данные: матрица – результат сложения матриц * Решение: ```java // Сложение матриц и форматирование результата output.format(firstMatrix.add(secondMatrix)); // Вывод в консоль System.out.printf("Результат сложения матриц:\n%s\n", output.format(firstMatrix.add(secondMatrix))); ``` * Результат вывода в консоль: ```text Результат сложения матриц: 10 -1 13 5 2 -14 ``` 4) подпрограмму вычитания матриц Входные данные: два целых числа n и m (n – количество строк, m – количество столбцов), матрица_1 размерности n x m, матрица_2 размерности n x m Выходные данные: матрица – результат вычитания матриц * Решение: ```java // Вычитание матрицы и форматирование результата output.format(firstMatrix.subtract(secondMatrix)); // Вывод в консоль System.out.printf("Результат вычитания матриц:\n%s\n", output.format(firstMatrix.subtract(secondMatrix))); ``` * Результат вывода в консоль: ```text Результат вычитания матриц: -4 -9 -5 -3 8 2 ``` 5) подпрограмму умножения матриц Входные данные: три целых числа n, m и (n – количество строк матрицы_1, m – количество столбцов матрицы_1 и количество строк матрицы_2, k – количество столбцов матрицы_2), матрица_1 размерности n x m, матрица_2 размерности m x k Выходные данные: матрица размерности n ´ k – результат умножения матриц * Решение: ```java // Вычитание матрицы и форматирование результата output.format(firstMatrix.multiply(thirdMatrix)); // Вывод в консоль System.out.printf("Результат перемножения матриц:\n%s\n", output.format(firstMatrix.multiply(thirdMatrix))); ``` * Результат вывода в консоль: ```text Результат перемножения матриц: 1 -5 -11 11 ``` 6) подпрограммы вычисления норм (||·||1, ||·||e, ||·||∞) матрицы Входные данные: два целых числа n и m (n – количество строк, m – количество столбцов), матрица размерности n x m Выходные данные: соответствующая норма матрицы * Решения: --- * Норма - сумма: ```java System.out.println("||.||1 = " + firstMatrix.getNorm()); ``` * Результат вывода в консоль: ```text ||.||1 = 10.0 ``` --- * Евклидова норма: ```java System.out.println("||.||e = " + firstMatrix.getFrobeniusNorm()); ``` * Результат вывода в консоль: ```text ||.||e = 10.583005244258363 ``` --- * Норма - максимум: ```java public static Double getMaxNorm(RealMatrix matrix) { // Список для хранения суммы строки ArrayList<Double> list = new ArrayList<>(); // Подсчет суммы в строке for (int i = 0; i < matrix.getData().length; i++) { list.add(Arrays.stream(matrix.getRow(i)) .map(Math::abs) .sum()); } return list.stream().max(Double::compareTo).get(); } ``` * Результат вывода в консоль: ```text ||·||∞ = 12.0 ```
C#
UTF-8
444
2.640625
3
[]
no_license
 using UnityEngine; public class PlayerData { private Vector3 _position; private Quaternion _rotation; // コンストラクタ public PlayerData(){} // デストラクタ ~PlayerData(){} public Vector3 Position { get { return _position; } set { _position = value; } } public Quaternion Rotation { get { return _rotation; } set { _rotation = value; } } }
Java
UTF-8
17,160
2.125
2
[]
no_license
package kasirapp; import javax.swing.JFrame; import javax.swing.JOptionPane; public class mainForm extends javax.swing.JFrame { JFrame jf = new JFrame(); public mainForm() { initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); nama_makanan = new javax.swing.JComboBox<>(); harga_makanan = new javax.swing.JTextField(); jumlah_porsi = new javax.swing.JTextField(); total_harga = new javax.swing.JTextField(); nominal_uang = new javax.swing.JTextField(); kembalian = new javax.swing.JTextField(); batal = new javax.swing.JButton(); keluar = new javax.swing.JButton(); bayar = new javax.swing.JButton(); hitung_total = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Comic Sans MS", 1, 14)); // NOI18N jLabel1.setText("= APLIKASI KASIR WARUNG LUMAYAN ="); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabel2.setText("Nama Makanan :"); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabel3.setText("Harga Makanan : Rp"); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabel4.setText("Jumlah Porsi :"); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabel5.setText("Total Harga : Rp "); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabel6.setText("Nominal Uang : Rp "); jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabel7.setText("Kembali : Rp"); nama_makanan.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Pilih Menu", "Soto Betawi", "Sate Ayam", "Mie Ayam", "Ayam Goreng", "Bebek Goreng", "Nasi Goreng" })); nama_makanan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { nama_makananActionPerformed(evt); } }); harga_makanan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { harga_makananActionPerformed(evt); } }); jumlah_porsi.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jumlah_porsiActionPerformed(evt); } }); total_harga.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { total_hargaActionPerformed(evt); } }); nominal_uang.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { nominal_uangActionPerformed(evt); } }); kembalian.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { kembalianActionPerformed(evt); } }); batal.setText("CLEAR"); batal.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { batalActionPerformed(evt); } }); keluar.setText("KELUAR"); keluar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { keluarActionPerformed(evt); } }); bayar.setText("BAYAR"); bayar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bayarActionPerformed(evt); } }); hitung_total.setText("HITUNG TOTAL"); hitung_total.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { hitung_totalActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(keluar) .addGap(18, 18, 18)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(45, 45, 45) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addGap(272, 272, 272) .addComponent(batal)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jLabel7)) .addGap(4, 4, 4) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(kembalian, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(total_harga, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(nominal_uang, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(bayar) .addGap(24, 24, 24)))) .addComponent(jLabel3) .addGroup(layout.createSequentialGroup() .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jumlah_porsi, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(37, 37, 37) .addComponent(hitung_total)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(harga_makanan, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(nama_makanan, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGroup(layout.createSequentialGroup() .addGap(72, 72, 72) .addComponent(jLabel1))) .addContainerGap(32, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(jLabel1) .addGap(28, 28, 28) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(nama_makanan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(batal)) .addGap(19, 19, 19) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(harga_makanan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(23, 23, 23) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jumlah_porsi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(hitung_total)) .addGap(21, 21, 21) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(total_harga, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(nominal_uang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6) .addComponent(bayar)) .addGap(21, 21, 21) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(kembalian, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(keluar) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void nama_makananActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nama_makananActionPerformed String NamaMakanan=(String)nama_makanan.getSelectedItem(); switch (NamaMakanan){ case "Soto Betawi": harga_makanan.setText("15000"); break; case "Sate Ayam": harga_makanan.setText("18000"); break; case "Mie Ayam": harga_makanan.setText("10000"); break; case "Ayam Goreng": harga_makanan.setText("15000"); break; case "Bebek Goreng": harga_makanan.setText("20000"); break; case "Nasi Goreng": harga_makanan.setText("16000"); break; } }//GEN-LAST:event_nama_makananActionPerformed private void harga_makananActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_harga_makananActionPerformed // TODO add your handling code here: }//GEN-LAST:event_harga_makananActionPerformed private void jumlah_porsiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jumlah_porsiActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jumlah_porsiActionPerformed private void total_hargaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_total_hargaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_total_hargaActionPerformed private void nominal_uangActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nominal_uangActionPerformed // TODO add your handling code here: }//GEN-LAST:event_nominal_uangActionPerformed private void kembalianActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_kembalianActionPerformed // TODO add your handling code here: }//GEN-LAST:event_kembalianActionPerformed private void batalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_batalActionPerformed nama_makanan.setSelectedIndex(0); harga_makanan.setText(""); jumlah_porsi.setText(""); total_harga.setText(""); nominal_uang.setText(""); kembalian.setText(""); }//GEN-LAST:event_batalActionPerformed private void keluarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_keluarActionPerformed System.exit(0); }//GEN-LAST:event_keluarActionPerformed private void hitung_totalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hitung_totalActionPerformed int JumlahPorsi = Integer.parseInt(jumlah_porsi.getText()); int HargaMakanan = Integer.parseInt(harga_makanan.getText()); total_harga.setText(Integer.toString(HargaMakanan * JumlahPorsi)); }//GEN-LAST:event_hitung_totalActionPerformed private void bayarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bayarActionPerformed int NominalUang = Integer.parseInt(nominal_uang.getText()); int TotalHarga = Integer.parseInt(total_harga.getText()); if (NominalUang >= TotalHarga){ kembalian.setText(Integer.toString(NominalUang - TotalHarga)); }else { JOptionPane.showMessageDialog(jf, "Maaf uang tidak cukup"); } }//GEN-LAST:event_bayarActionPerformed public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(mainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(mainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(mainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(mainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new mainForm().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton batal; private javax.swing.JButton bayar; private javax.swing.JTextField harga_makanan; private javax.swing.JButton hitung_total; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JTextField jumlah_porsi; private javax.swing.JButton keluar; private javax.swing.JTextField kembalian; private javax.swing.JComboBox<String> nama_makanan; private javax.swing.JTextField nominal_uang; private javax.swing.JTextField total_harga; // End of variables declaration//GEN-END:variables }
Java
UTF-8
1,091
2.03125
2
[]
no_license
package com.dsa.subscription.converter; import com.dsa.subscription.entity.Subscription; import com.dsa.subscription.stream.dto.SubscriptionDTO; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.junit.jupiter.MockitoExtension; import static com.dsa.subscription.util.MockUtils.*; @ExtendWith(MockitoExtension.class) public class SubscriptionConverterTest { @InjectMocks SubscriptionConverter converter; @Test public void whenValidRequestSubscriptionDTO_thenReturnSubscriptionDTO() { SubscriptionDTO subscriptionDTOConverted = converter.toDTO(buildRequestSubscriptionDTO()); Assertions.assertEquals(buildSubscriptionDTO(), subscriptionDTOConverted); } @Test public void whenValidSubscriptionDTO_thenReturnSubscriptionEntity() { Subscription subscriptionConverted = converter.toEntity(SUBSCRIPTION_ID, buildStatus()); Assertions.assertEquals(buildSubscription(), subscriptionConverted); } }
C++
UTF-8
978
2.78125
3
[]
no_license
#ifndef __MORSUTIL_H #define __MORSUTIL_H typedef void (*MorseON)(int freq,char ditdah); typedef void (*MorseOFF)(void); class Morse { private: int ditlen; int dahlen; int ditdahdel; int letterdel; int delscale; int freq; MorseON morseon; MorseOFF morseoff; public: Morse (MorseON mon,MorseOFF moff); Morse (void); ~Morse (void) { return; } char* morsestring(char c); char* playmorsestring(char* s); char* playchar(char c); char* playstring(char* s); char charof(char *mstring); int scale(void) { return delscale; } int scale(int s); int frequency(void) { return freq; } int frequency(int f) { if (f>0) freq=f; return freq; } MorseON ON (MorseON mon) { if (mon) morseon=mon; return morseon; } MorseOFF OFF(MorseOFF moff) { if (moff) morseoff=moff; return morseoff; } Morse& operator<<(char c); Morse& operator<<(char* s); }; //class Morse #endif
SQL
UTF-8
504
2.75
3
[ "MIT" ]
permissive
create table if not exists `x_xadmin`( `id` int auto_increment, `username` varchar(20) not null, `password` varchar(32) not null, `aid` smallint unsigned not null default 0 comment '权限id', `addtime` int unsigned not null, `status` tinyint unsigned not null default 1 comment '状态', `login_error_times` tinyint unsigned not null default 0 comment '登录错误次数', primary key(`id`), key uname(`username`) )engine=MyISAM auto_increment=1 default charset=utf8 comment '管理员表';
Markdown
UTF-8
1,259
3.28125
3
[]
no_license
#Author: ======== * Delacroix Louis #Explication: ============= * Ce projet s'inscrit dans le cadre de mes études. Il a pour but de nous faire découvrir la programmation en assembleur sur Intel 64. * La calculatrice est suffixée donc l'opérateur est à la fin de l'opération. Et elle ne fait que des calculs sur des nombres entiers. * Les opérations possibles sont la division, la multiplication, l'addition et la soustraction. #Versions: ========== ##Version 1: ============ Cette version est simple, le programme ne comporte pas de fonction seulement des parties interconnectées ##Version 2: ============ Cette version est plus complexe, c'est quasiment le même programme sauf qu'à la place de parties inteconnectées on fait appelle à des fonctions assembleurs ##Version 3: ============ Dans cette version, on mélange un programme asssembleur et C, les fonctions sont écrites en C et les programme principale (main) est écrit en assemblrur #Utilisation : ============== * Chaque version a son propre Makefile il suffit de taper la commande make dans la version voulu puis de taper ./calc * Il ne reste plus qu'à ecrire le calcule. Exemple: * On veut réaliser l'opération suivante (((1+2)*3)/9)-1 * ~./calc * 1 2 + 3 * 9 / 1 - * 0
Shell
UTF-8
785
3.84375
4
[]
no_license
#!/bin/bash function usage { echo "description" } if [ "$1" == "-h" ] || [ "$1" == "-help" ]; then usage #write usage function# fi #OPERATORS=() if [ "$1" == "arith" ]; then #SELECTEDOPERATOR=${OPERATORS[$RANDOM % ${#operators[@]} ]} if [[ "$2" =~ [0-9] ]] && [[ "$3" =~ [0-9] ]]; then FIRSTNUMBER=$(( ( RANDOM % $((10**${2})) ) )) SECONDNUMBER=$(( ( RANDOM % $((10**${3})) ) )) echo "${FIRSTNUMBER} * ${SECONDNUMBER}" else echo "please enter the number of digits for each operand" fi read ANSWER while [ $ANSWER -ne $((${FIRSTNUMBER} * ${SECONDNUMBER})) ]; do echo "incorrect, try again" read ANSWER done echo "Good job!" #echo "$(( ( RANDOM % ${FIRSTNUMBER} ) )) * $(( ( RANDOM % ${SECONDNUMBER} ) ))" fi
Rust
UTF-8
529
2.671875
3
[ "Apache-2.0", "MIT" ]
permissive
use edgedb_derive::Queryable; use edgedb_protocol::queryable::{Queryable, Decoder}; #[derive(Queryable, Debug, PartialEq)] enum Status { Open, Closed, Invalid, } #[test] fn enumeration() { let dec = Decoder::default(); assert_eq!(Status::decode(&dec, &b"Open"[..]).unwrap(), Status::Open); assert_eq!(Status::decode(&dec, &b"Closed"[..]).unwrap(), Status::Closed); assert_eq!(Status::decode(&dec, &b"Invalid"[..]).unwrap(), Status::Invalid); Status::decode(&dec, &b"closed"[..]).unwrap_err(); }
JavaScript
UTF-8
1,153
3.21875
3
[]
no_license
export function getRandomWages() { let wages = []; for (let i = 0; i <= 2500; i++) { wages[i] = (2 * Math.random()) - 1; } return wages; } export function generateGrid(rows, cols) { const containter = document.getElementById('container'); const resultGrid = document.getElementById('resultGrid'); container.style.setProperty('--grid-rows', rows); container.style.setProperty('--grid-cols', cols); resultGrid.style.setProperty('--grid-rows', rows); resultGrid.style.setProperty('--grid-cols', cols); for (let c = 1; c <= (rows * cols); c++) { const cell = document.createElement("div"); container.appendChild(cell).className = `grid-item number-${c}`; containter.appendChild(cell).style = 'background-color: black;'; const cell_resultGrid = document.createElement("div"); resultGrid.appendChild(cell_resultGrid).className = `grid-item-result number-${c}`; resultGrid.appendChild(cell_resultGrid).style = 'background-color: black;'; }; } export function getRandomInt(max) { return (Math.floor(Math.random() * Math.floor(max))); }
C#
UTF-8
8,841
2.6875
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace MT4OrderAnalyze { public static class StringUtil { public static MatchResult MatchRuleResult(MatchRule rule, string source, int startIndex = 0) { MatchResult result = new MatchResult { IsMatched = false, GroupId = rule.RuleId }; int idxBegin = source.IndexOf(rule.Begin, startIndex); if (idxBegin != -1) { int idxEnd = source.IndexOf(rule.End, idxBegin + rule.Begin.Length); if (idxEnd != -1) { result.SourceIndex = idxBegin; result.MatchLength = idxEnd + rule.End.Length - idxBegin; result.IsMatched = true; #region 子匹配 if (rule.SubRules != null && rule.SubRules.Any()) { result.SubResults = new List<MatchResult>(); string rangeSource = result.SourceViewOf(source); int subIdx = 0; string sItemView = string.Empty; foreach (var sRule in rule.SubRules) { MatchResult subResult = MatchRuleResult(sRule, rangeSource, subIdx); while (subResult.IsMatched == true) { subResult.GroupId = sRule.RuleId; sItemView = subResult.SourceViewOf(rangeSource); result.SubResults.Add(subResult); subIdx = subResult.SourceIndex + subResult.MatchLength; subResult = MatchRuleResult(sRule, rangeSource, subIdx); } } } #endregion } } return result; } public static string StripHtml(this string source) { return Regex.Replace(source, "(<[^>]+)>", ""); } public static double ToDouble(this string strPrice) { return Double.Parse(strPrice.Replace(" ", "")); } public static string CurrentPercent(this double nowMoney, double investorTotal) { if (nowMoney > investorTotal) return ((nowMoney - investorTotal) / investorTotal).ToString("P2"); else if (nowMoney < investorTotal) return "-" + ((investorTotal - nowMoney) / investorTotal).ToString("P2"); else return "0.00%"; } public static string DiffPercent(this double nowMoney, double lastMoney) { return CurrentPercent(nowMoney, lastMoney); } } public class MatchRule { public string RuleId { get; set; } public string Begin { get; set; } public string End { get; set; } public List<MatchRule> SubRules { get; set; } } public class MatchResult : ICloneable { /// <summary> /// 对应MatchRule的RuleId /// </summary> public string GroupId { get; set; } public int SourceIndex { get; set; } public int MatchLength { get; set; } public List<MatchResult> SubResults { get; set; } public bool IsMatched { get; set; } public object Clone() { return new MatchResult { GroupId = GroupId, SourceIndex = SourceIndex, IsMatched = IsMatched, SubResults = SubResults, MatchLength = MatchLength }; } public string SourceViewOf(string source) { int totalLen = source.Length; if (SourceIndex > totalLen) return string.Empty; if (SourceIndex + MatchLength > totalLen) return source.Substring(SourceIndex); return source.Substring(SourceIndex, MatchLength); } } public class TradeItemResult : MatchResult { internal const int CLOSE_ITEM_LENGTH = 14; internal const int CANCELL_ITEM_LENGTH = 11; internal const int BALANCE_ITEM_LENGTH = 5; internal const string WIN_CHAR = "↑"; internal const string LOSE_CHAR = "↓"; public TradeItemResult(string itemString) { ItemString = itemString; } public string ItemString { get; set; } public string ContainerFormat { get { return ItemString.Substring(0, ItemString.IndexOf(">") + 1) + "{0}</tr>"; } } public string GetOrderTicket() { return SubResults[0].SourceViewOf(ItemString).StripHtml(); } double getSubResultDouble(int idxSub) { return SubResults[idxSub].SourceViewOf(ItemString) .StripHtml().ToDouble(); } public double GetProfit() { if (SubResults.Count == BALANCE_ITEM_LENGTH) return getSubResultDouble(BALANCE_ITEM_LENGTH - 1); else if (SubResults.Count == CLOSE_ITEM_LENGTH) return getSubResultDouble(CLOSE_ITEM_LENGTH - 1); return 0.00; } public int GetProfitPoint() { if (SubResults.Count == CLOSE_ITEM_LENGTH) { double diff = GetOrderPriceClose() - GetOrderPriceOpen(); string fmt = "0.".PadRight(GetDigits() + 2, '0'); if (diff == 0) { return 0; } else { return int.Parse(Math.Abs(diff).ToString(fmt).Replace(".", "").TrimStart('0')); } } return 0; } public double GetSwap() { if (SubResults.Count == CLOSE_ITEM_LENGTH) return getSubResultDouble(CLOSE_ITEM_LENGTH - 2); return 0.00; } public DateTime GetOpenTime() { return DateTime.Parse(SubResults[1].SourceViewOf(ItemString).StripHtml()); } public DateTime? GetCloseTime() { if (SubResults.Count == CLOSE_ITEM_LENGTH || SubResults.Count == CANCELL_ITEM_LENGTH) return DateTime.Parse(SubResults[8].SourceViewOf(ItemString).StripHtml()); return null; } public string GetOrderType() { return SubResults[2].SourceViewOf(ItemString).StripHtml(); } public double GetOrderSize() { if (SubResults.Count == CLOSE_ITEM_LENGTH) return getSubResultDouble(3); return 0.00; } public string GetOrderSymbol() { if (SubResults.Count == CLOSE_ITEM_LENGTH) return SubResults[4].SourceViewOf(ItemString).StripHtml(); return string.Empty; } public int GetDigits() { if (SubResults.Count == CLOSE_ITEM_LENGTH) { string strOpen = SubResults[5].SourceViewOf(ItemString).StripHtml().Replace(" ", "").Trim(); int idx = strOpen.IndexOf('.'); return strOpen.Substring(idx + 1).Length; } return 0; } public double GetOrderPriceOpen() { if (SubResults.Count == CLOSE_ITEM_LENGTH) return getSubResultDouble(5); return 0.00; } public double GetOrderPriceClose() { if (SubResults.Count == CLOSE_ITEM_LENGTH) return getSubResultDouble(9); return 0.00; } public double GetCommission() { if (SubResults.Count == CLOSE_ITEM_LENGTH) return getSubResultDouble(CLOSE_ITEM_LENGTH - 4); return 0.00; } public bool IsCancelledOrder() { return SubResults.Count == CANCELL_ITEM_LENGTH; } public bool IsBalanceItem() { return GroupId == "BalanceItem"; } public static TradeItemResult FromSource(MatchResult rawResult, string source) { TradeItemResult ret = new TradeItemResult(source); ret.GroupId = rawResult.GroupId; ret.SourceIndex = rawResult.SourceIndex; ret.IsMatched = rawResult.IsMatched; ret.SubResults = rawResult.SubResults; ret.MatchLength = rawResult.MatchLength; return ret; } } }
C++
UTF-8
10,684
3.140625
3
[]
no_license
#include "Classes.h" using namespace std; Card::Card() { _suit = "Hearts"; _rank = "Queen"; _value = 12; } Card::Card(string suit, string rank, int value) { _suit = suit; _rank = rank; _value = value; } void Card::ConvertValuetoRank() { if (_value == 1) { SetRank("2"); } else if (_value == 2) { SetRank("3"); } else if (_value == 3) { SetRank("4"); } else if (_value == 4) { SetRank("5"); } else if (_value == 5) { SetRank("6"); } else if (_value == 6) { SetRank("7"); } else if (_value == 7) { SetRank("8"); } else if (_value == 8) { SetRank("9"); } else if (_value == 9) { SetRank("10"); } else if (_value == 10) { SetRank("Jack"); } else if (_value == 11) { SetRank("Queen"); } else if (_value == 12) { SetRank("King"); } else if (_value == 13) { SetRank("Ace"); } } void Card::SetRank(string rank) { _rank = rank; } void Card::SetSuit(string suit) { _suit = suit; } void Card::SetValue(int value) { _value = value; } string Card::GetRank() const { return _rank; } string Card::GetSuit() const { return _suit; } int Card::GetValue() const { return _value; } ////////////////////////////////// Game::Game() { _round = 0; _score = 0; Player player; Player computer; string entry = "0"; //player._hand.clear(); //computer._hand.clear(); CreateDeck(); Introduction(); ShuffleDeck(); //TestDeck(); SplitDeck(player, computer); //TestSplit(player, computer); //UpdateScores(player, computer); do { _round++; if (player._hand.size() != 0 || computer._hand.size() != 0) { Compare(player, computer, player.DrawCard(), computer.DrawCard()); //TestSplit(player, computer); UpdateScores(player, computer); } do { cout << "Enter D to draw or Q to quit: "; cin >> entry; } while (entry != "D" && entry != "Q" && entry != "d" && entry != "q"); } while (player._hand.size() != 0 && computer._hand.size() != 0 && ((entry != "Q" ||entry != "q") && (entry == "D" || entry == "d"))); if (player.GetScore() == 52) { cout << "Congrats! You win!! You won in " << _round << "rounds." << endl; } else if (player.GetScore() > computer.GetScore()) { cout << "Congrats you had a higher score than the computer! You win!" << endl; } else { cout << "Sorry, the computer beat you :(" << endl; } } void Game::Introduction() { cout << "Welcome to WAR!." << endl; cout << "You will be playing against the computer." << endl; cout << "Each of you have will start with half of the deck (26 cards)." << endl; cout << "The goal is to get the whole deck (52 cards)\nor have a higher amount of cards than the computer." << endl; cout << "(Because, yes, to get 52 cards will take a long time,\nbut hey, good thing to procrastinate with)" << endl; cout << "To do this, you will draw one card at a time, then compare the scores." << endl; cout << "Whichever drew the higher valued card gets to put those two cards back into their hand." << endl; cout << "Aces beat all. If the two cards drawn have the same value, then a WAR starts."<< endl; cout << "During WAR, each player draws three more cards, but does not look at the first two,\nthe third cards drawn then are compared just like normal." << endl; cout << "The winner of the WAR get to keep all the cards played in that round." << endl; system("pause"); } void Game::CreateDeck() { for (int i = 0; i < 13; i++) { Card card; card.SetValue(i + 1); card.SetSuit("Hearts"); _deck.push_back(card); } for (int i = 0; i < 13; i++) { Card card; card.SetValue(i + 1); card.SetSuit("Spades"); _deck.push_back(card); } for (int i = 0; i < 13; i++) { Card card; card.SetValue(i + 1); card.SetSuit("Diamonds"); _deck.push_back(card); } for (int i = 0; i < 13; i++) { Card card; card.SetValue(i + 1); card.SetSuit("Clubs"); _deck.push_back(card); } for (int i = 0; i < 52; i++) { _deck.at(i).ConvertValuetoRank(); } ShuffleDeck(); } void Game::ShuffleDeck() { for (int i = 0; i < 52; i++) { Card holder; int pos1 = (rand() % 52); int pos2 = (rand() % 52); holder = _deck.at(pos1); _deck.at(pos1) = _deck.at(pos2); _deck.at(pos2) = holder; } } void Game::SplitDeck(Player &player, Player &computer) { for (int i = 0; i < 26; i++) { player.SetHand(_deck.at(i), i); computer.SetHand(_deck.at(i + 26), i); } } Card Game::MoveCard() { Card a = _deck.at(_deck.size()); _deck.pop_back(); return a; } void Game::TestDeck() { for (int i = 0; i < 52; i++) { cout << _deck.at(i).GetRank() << " " << _deck.at(i).GetSuit() << " " << _deck.at(i).GetValue() << endl; }; ShuffleDeck(); for (int i = 0; i < 52; i++) { cout << _deck.at(i).GetRank() << " " << _deck.at(i).GetSuit() << " " << _deck.at(i).GetValue() << endl; }; } void Game::TestSplit(Player &player, Player &computer) { cout << "Player:" << endl; int pLength = player._hand.size(); for (int i = 0; i < pLength; i++) { cout << i << "#" <<player._hand.at(i).GetRank() << " " << player._hand.at(i).GetSuit() << endl; } cout << "--------------------" << endl; int cLength = computer._hand.size(); cout << "Computer:" << endl; for (int i = 0; i < cLength; i++) { cout << i << "#" << computer._hand.at(i).GetRank() << " " << computer._hand.at(i).GetSuit() << endl; } } void Game::Compare(Player &player, Player &computer, Card plCard, Card coCard) { _war = 0; //computer.RemoveCard(); //player.RemoveCard(); int p = plCard.GetValue(); int c = coCard.GetValue(); cout << "Computer Drew: " << coCard.GetRank() << " of " << coCard.GetSuit() << endl; cout << "Player Drew: " << plCard.GetRank() << " of " << plCard.GetSuit() << endl; if (p == c) { int w = War(player, computer); if (w == 1) { player.AddCard(coCard); player.AddCard(plCard); } else if (w == 2) { computer.AddCard(plCard); computer.AddCard(coCard); } } if (p > c) { cout << "Player's is higher." << endl; player.AddCard(coCard); player.AddCard(plCard); } else if (c > p) { cout << "Computer's is higher." << endl; computer.AddCard(plCard); computer.AddCard(coCard); } } void Game::UpdateScores(Player &player, Player &computer) { computer.UpdateScore(); player.UpdateScore(); _score = player.GetScore(); cout << "-----------------------" << endl; cout << "Current Score: " << player.GetScore() << "/52" << endl; cout << "-----------------------" << endl; } int Game::GetScore() { return _score; } int Game::GetRounds() { return _round; } int War(Player &player, Player &computer) { int _war = 0; cout << "-----WAR!-----" << endl; Card pl4; Card co4 = computer.DrawCard(); Card pl2; Card pl1; Card co1; Card co2; if (player._hand.size() != 0 && computer._hand.size() != 0) { pl4 = player.DrawCard(); co4 = computer.DrawCard(); int p4 = pl4.GetValue(); int c4 = co4.GetValue(); if (player._hand.size() != 0) { pl2 = player.DrawCard(); } if (player._hand.size() != 0) { pl1 = player.DrawCard(); } if (computer._hand.size() != 0) { co2 = computer.DrawCard(); } if (computer._hand.size() != 0) { co1 = computer.DrawCard(); } cout << "Computer Drew: " << co4.GetRank() << " of " << co4.GetSuit() << endl; cout << "Player Drew: " << pl4.GetRank() << " of " << pl4.GetSuit() << endl; if (p4 == c4) { int w = War(player, computer); if (w == 1) { player.AddCard(co4); player.AddCard(pl4); player.AddCard(co2); player.AddCard(pl2); player.AddCard(co1); player.AddCard(pl1); return 1; } else if (w == 2) { computer.AddCard(pl4); computer.AddCard(co4); computer.AddCard(pl2); computer.AddCard(co2); computer.AddCard(pl1); computer.AddCard(co1); return 2; } } if (p4 > c4) { cout << "Player's is higher." << endl; player.AddCard(co4); player.AddCard(pl4); player.AddCard(co2); player.AddCard(pl2); player.AddCard(co1); player.AddCard(pl1); return 1; } else if (c4 > p4) { cout << "Computer's is higher." << endl; computer.AddCard(pl4); computer.AddCard(co4); computer.AddCard(pl2); computer.AddCard(co2); computer.AddCard(pl1); computer.AddCard(co1); return 2; } } } ////////////////////////////////// Player::Player() { _score = 0; _hand.resize(26); } Player::Player(vector <Card> a, int score) { _hand = a; _score = 0; } void Player::SetHand(Card c, int i) { _hand.at(i).SetRank(c.GetRank()); _hand.at(i).SetSuit(c.GetSuit()); _hand.at(i).SetValue(c.GetValue()); } //Card Player::GetHand(int r) { // return _hand.at(r); //} Card Player::DrawCard() { int length = _hand.size(); Card c = _hand.at(0); for (int i = 1; i < length; i++) { _hand.at(i-1) = _hand.at(i); } _hand.pop_back(); return c; } void Player::AddCard(Card c) { _hand.push_back(c); } //void Player::RemoveCard() { // _hand.pop_back(); //} void Player::UpdateScore() { _score = _hand.size(); } int Player::GetScore() { return _score; }
Java
UTF-8
2,478
2.203125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2018 Johannes Donath <johannesd@torchmind.com> * and other copyright owners as documented in the project's IP log. * * Licensed 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.basinmc.ejector.command; import edu.umd.cs.findbugs.annotations.NonNull; import java.util.List; import java.util.Set; import org.basinmc.ejector.command.error.CommandException; import org.basinmc.ejector.command.error.CommandParameterException; import org.basinmc.ejector.communication.Message; /** * Provides a command implementation to which the bot will reply in a certain manner.. * * @author <a href="mailto:johannesd@torchmind.com">Johannes Donath</a> */ public interface Command { /** * Executes the command's internal logic. * * @param context a command context. * @param commandName a command name. * @param arguments a list of arguments. * @throws CommandParameterException when the supplied parameters are outside of their expected * bounds. * @throws CommandException when the command execution itself fails. */ void execute(@NonNull Context context, @NonNull String commandName, @NonNull List<String> arguments) throws CommandException; /** * Retrieves a list of command names which this command is accessible. * * @return one or more names. */ @NonNull Set<String> getNames(); /** * Provides contextual information to commands during their invocation. */ interface Context { /** * Retrieves the name of the user which invoked the command. * * @return a name. */ @NonNull String getUserName(); /** * Retrieves a formatted user reference which may be prepended to a response in order to ping * the user which invoked the command. * * @return a reference. */ @NonNull String getUserReference(); /** * Sends a message to the source communication adapter. * * @param message a message. */ void sendMessage(@NonNull Message message); } }
Java
UTF-8
7,076
2.03125
2
[ "MIT" ]
permissive
package com.simperium.client; import com.simperium.util.JSONDiff; import com.simperium.util.Logger; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; import java.util.TimerTask; import static com.simperium.util.Uuid.uuid; public class Change { public static final String TAG="Simperium.Change"; public interface OnRetryListener { public void onRetry(Change change); } public interface OnAcknowledgedListener { public void onAcknowledged(Change change); } public interface OnCompleteListener { public void onComplete(Change change); } public static final String OPERATION_MODIFY = "M"; public static final String OPERATION_REMOVE = JSONDiff.OPERATION_REMOVE; public static final String ID_KEY = "id"; public static final String CHANGE_ID_KEY = "ccid"; public static final String SOURCE_VERSION_KEY = "sv"; public static final String OPERATION_KEY = "o"; public static final String OBJECT_DATA_KEY = "d"; private String operation; private String key, bucketName; private String ccid; private boolean pending = true, acknowledged = false, sent = false; private OnRetryListener retryListener; private OnCompleteListener completeListener; private OnAcknowledgedListener acknowledgedListener; private Change compressed; private JSONDiff jsondiff = new JSONDiff(); private boolean sendFullObject = false; private TimerTask retryTimer; private Integer retryCount = 0; /** * Constructs a change object from a map of values */ public static Change buildChange(Syncable object, JSONObject properties) throws JSONException { return new Change( properties.getString(OPERATION_KEY), object.getBucketName(), object.getSimperiumKey() ); } public static Change buildChange(String operation, String ccid, String bucketName, String key){ return new Change(operation, ccid, bucketName, key); } public Change(String operation, String bucketName, String key){ this(operation, uuid(), bucketName, key); } protected Change(String operation, String ccid, String bucketName, String key){ this.operation = operation; this.ccid = ccid; this.bucketName = bucketName; this.key = key; this.resetTimer(); } public boolean isModifyOperation(){ return operation.equals(OPERATION_MODIFY); } public boolean isRemoveOperation() { return operation.equals(OPERATION_REMOVE); } public boolean isPending(){ return pending; } public boolean isSent(){ return sent; } public boolean isComplete(){ return !pending; } public boolean isAcknowledged(){ return acknowledged; } protected void setAcknowledged(){ acknowledged = true; resetTimer(); if (acknowledgedListener != null) { acknowledgedListener.onAcknowledged(this); } if (compressed != null) { compressed.setAcknowledged(); } } protected void setComplete(){ pending = false; if (completeListener != null) { completeListener.onComplete(this); } if (compressed != null) { compressed.setComplete(); } } protected void setSent(){ sent = true; if (compressed != null) { compressed.setSent(); } } protected boolean keyMatches(Change otherChange){ return otherChange.getKey().equals(getKey()); } public String getKey(){ return key; } public String getBucketName(){ return bucketName; } public String getChangeId(){ return this.ccid; } public String getOperation(){ return operation; } public void setSendFullObject(boolean sendFullObject) { this.sendFullObject = sendFullObject; } public JSONObject toJSONObject(JSONObject target, Ghost ghost) throws ChangeEmptyException, ChangeInvalidException { try { JSONObject json = new JSONObject(); json.put(ID_KEY, getKey()); json.put(CHANGE_ID_KEY, getChangeId()); json.put(JSONDiff.DIFF_OPERATION_KEY, getOperation()); if (!getOperation().equals(OPERATION_REMOVE) && ghost.getVersion() != null && ghost.getVersion() > 0) { json.put(SOURCE_VERSION_KEY, ghost.getVersion()); } JSONObject diff = getDiff(target, ghost); boolean requiresDiff = requiresDiff(); if (requiresDiff && diff.length() == 0) { throw new ChangeEmptyException(this); } if (requiresDiff) { json.put(JSONDiff.DIFF_VALUE_KEY, diff.getJSONObject(JSONDiff.DIFF_VALUE_KEY)); } if (sendFullObject) { json.put(OBJECT_DATA_KEY, target); } return json; } catch (JSONException e) { throw new ChangeInvalidException(this, "Could not build change JSON", e); } } protected Map<String,Object> toJSONSerializable(){ Map<String,Object> props = new HashMap<String,Object>(3); // key, version, origin, target, ccid props.put(OPERATION_KEY, operation); props.put(ID_KEY, key); props.put(CHANGE_ID_KEY, ccid); return props; } public void setOnAcknowledgedListener(OnAcknowledgedListener listener){ acknowledgedListener = listener; } public void setOnCompleteListener(OnCompleteListener listener){ } public Integer getRetryCount() { return retryCount; } public void incrementRetryCount() { retryCount++; } protected void setOnRetryListener(OnRetryListener listener){ retryListener = listener; } protected void resetTimer(){ if (retryTimer != null) { retryTimer.cancel(); } retryTimer = new TimerTask(){ @Override public void run(){ Logger.log("Simperium.Channel", String.format("Retry change: %s", Change.this)); if (retryListener != null) { retryListener.onRetry(Change.this); } } }; } protected TimerTask getRetryTimer(){ return retryTimer; } public String toString(){ return String.format("Change %s %s %s", getChangeId(), getKey(), operation); } /** * The change message requires a diff value in the JSON payload */ public boolean requiresDiff(){ return operation.equals(OPERATION_MODIFY); } public JSONObject getDiff(JSONObject target, Ghost ghost){ try { return jsondiff.diff(ghost.getDiffableValue(), target); } catch (Exception e) { throw new RuntimeException(e); } } }
Markdown
UTF-8
6,856
3.359375
3
[]
no_license
CMSC 508 Database Problem Proposal ## Problem Statement: This database will be used to determine which tech websites are offering the best deals for tech and tech peripherals. When considering what components a user is going to build their computer with or what phone is worth buying, it is ideal to take into account many more factors than just the piece itself. For instance, a user might want to buy a set of two 8GB DDR4 RAM sticks at the lowest price possible without skipping out on quality. While there may be many 8GB sticks in roughly the same price range, to assure the user that they will still get the most cost efficient choice, they will have to consider if the brand they are buying is trustworthy and decently well known, alongside which websites are selling at the lowest price. It is risky to buy blindly, but utilizing the database would allow the user to compare two different 8GB sets and determine which is more likely to be worth their money by comparing which brand has better overall statistics, like RAM speed or voltage. On the other end, this database could also be used to help vendors, as they would be able to view the historical prices of individual components throughout the years. Tracking the price history of pieces would allow the vendor to know what would be a decent price to set a product to, as to not scare away customers with prices that are much higher than competitors’ while also not selling at prices that are too low to profit off of. Additionally, businesses that buy in bulk to stock their own shelves would be able to analyze trends in the fluctuations of prices. For example, a business recognizing that GPUs tend to spike in price right before the holidays would allow them to stock up on GPUs and sell them to turn over a profit. Being able to monitor the tech market and find most opportune time to make purchases or sell supplies is invaluable in today’s highly competitive industry. A database that tracks the price history of items across websites, filters products by specific attributes, compares products using set qualities, and lists important data (such as release dates, stock, and availability via location) would give users an extra edge on where to buy and sell from. Therefore, the primary user groups for this database would consist of the following: • Vendors: Sell products to both normal customers and businesses, while providing the bulk of components. Vendors will update the database with their listings, stock, release dates, compatibility data, and information such what their prices are for selling in bulk. They will also use the current price trends to determine what a good price is to sell their parts at. This benefits both the customer and vendor, as customers get fair prices, while the vendor also gets more sales from having an a fair price range. • Businesses: Will mostly buy from vendors in bulk to replenish their own storefronts. Businesses will also benefit from the historical prices by getting insight on when it is an opportune time to buy pieces in bulk. Knowing the historical highs and lows of a piece means they can accurately predict the best prices to turn profit with. Businesses may also use the database to list assembled products and the various websites that they sell their products on. For example, Alienware may be sold on their official website, but listing that Alienware can also be bought from Amazon stores as well would give Alienware a farther reach and different shipping locations. • Users: Benefit from being able to use the database to efficiently search for specific products and compare products to see what will yield the best value. The user will be able to narrow down the search filter to multiple levels to compare the exact specifications they want to. For example, they can search for RAM to list all RAM sets, but then narrow it down to show RAM from a certain vendor’s website only. It can be narrowed down even further by filtering the search to show RAM under a certain price, and narrowed down once again by only showing website results for vendors that have locations near the user to reduce shipping costs. Users in turn regulate the prices of pieces indirectly by buying pieces only when they are in a range they see fit. This forms an automated and self-maintained quality control system over the database and lets businesses or vendors know what are the most reasonable prices. ## In order for this to all function together, the database requires the following entity sets: • Websites/Vendors • Monitors • Keyboards • Phones • Motherboards • Storage (Hard drives) • Memory • CPUs • Warehouses • Item • Stock And to maintain database the database should be able to undergo changes such as: • Grab new websites and their listings. • Delete any links to websites that are no longer functional or too dated. • Update data to already existing listings. • Add new tags for filtering out certain websites or components. • Update the dates when pieces go on sale and when they return to normal prices. • Update information about what warehouses have what items, along with the stock for each website and their respective websites/vendors. ## The database could be used to find solutions for plenty of queries, such as: 1. What is the current price for this item? 2. What is the lowest price for this product across all vendor websites? 3. List the names of keyboards and monitors that share the same color. 4. What is the highest price historically for this item, on a certain vendor website? 5. List all item IDs of a certain component that are currently priced above a price threshold and have a certain number of stock left in a specific warehouse. 6. Does this vendor have this item in stock? 7. List all items available in a product line on a vendor site. 8. What items are currently sold by this manufacturer? 9. List all items under a certain price under a component category, across all vendor sites. 10. What motherboards are compatible with this CPU? (matching chipset) 11. List all the memory + corresponding prices on a site that are at least 8GB. 12. What is the location of the warehouse where this item is located? 13. What sites have free shipping available for this product? 14. Which SSDs on this site are currently on sale? 15. What devices are compatible with my carrier? 16. What devices run on Android 11? 17. List all products currently on sale by a specific company that have never had a historical high that surpassed a price threshold and has never fallen below a certain price threshold. 18. What phones were released so far this year? 19. What is the most-outdated hard-drive that is still in stock in this warehouse? 20. What are the 5 most expensive monitors from this brand?
Rust
UTF-8
8,264
3.453125
3
[ "MIT" ]
permissive
//! An MPSC channel whose receiving end is an event source //! //! Create a channel using `Channel::<T>::new()`, which returns a //! `Sender<T>` that can be cloned and sent accross threads if `T: Send`, //! and a `Channel<T>` that can be inserted into an `EventLoop`. It will generate //! one event per message. use std::cell::RefCell; use std::rc::Rc; use std::sync::{mpsc, Arc, Mutex}; use mio::{event::Event as MioEvent, Waker}; use crate::{EventDispatcher, EventSource}; /// The events generated by the channel event source pub enum Event<T> { /// A message was received and is bundled here Msg(T), /// The channel was closed /// /// This means all the `Sender`s associated with this channel /// have been dropped, no more messages will ever be received. Closed, } /// The sender end of a channel /// /// It can be cloned and sent accross threads (if `T` is). pub struct Sender<T> { sender: mpsc::Sender<T>, waker: Arc<Mutex<Option<Arc<Waker>>>>, } #[cfg_attr(tarpaulin, skip)] impl<T> Clone for Sender<T> { fn clone(&self) -> Sender<T> { Sender { sender: self.sender.clone(), waker: self.waker.clone(), } } } impl<T> Sender<T> { /// Send a message to the channel /// /// This will wake the event loop and deliver an `Event::Msg` to /// it containing the provided value. pub fn send(&self, t: T) -> Result<(), mpsc::SendError<T>> { let g = self.waker.lock().unwrap(); if let Some(ref w) = *g { let _ = w.wake(); } self.sender.send(t) } } /// The sender end of a synchronous channel /// /// It can be cloned and sent accross threads (if `T` is). pub struct SyncSender<T> { sender: mpsc::SyncSender<T>, waker: Arc<Mutex<Option<Arc<Waker>>>>, } #[cfg_attr(tarpaulin, skip)] impl<T> Clone for SyncSender<T> { fn clone(&self) -> SyncSender<T> { SyncSender { sender: self.sender.clone(), waker: self.waker.clone(), } } } impl<T> SyncSender<T> { /// Send a message to the synchronous channel /// /// This will wake the event loop and deliver an `Event::Msg` to /// it containing the provided value. If the channel is full, this /// function will block until the event loop empties it and it can /// deliver the message. Readiness is signalled to the event loop /// *before* blocking. pub fn send(&self, t: T) -> Result<(), mpsc::SendError<T>> { let g = self.waker.lock().unwrap(); if let Some(ref w) = *g { let _ = w.wake(); } self.sender.send(t) } /// Send a message to the synchronous channel /// /// This will wake the event loop and deliver an `Event::Msg` to /// it containing the provided value. If the channel is full, this /// function will return an error. The event loop will be signalled /// for readinnes in all cases. pub fn try_send(&self, t: T) -> Result<(), mpsc::TrySendError<T>> { let g = self.waker.lock().unwrap(); if let Some(ref w) = *g { let _ = w.wake(); } self.sender.try_send(t) } } /// The receiving end of the channel /// /// This is the event source to be inserted into your `EventLoop`. pub struct Channel<T> { receiver: Rc<mpsc::Receiver<T>>, waker: Arc<Mutex<Option<Arc<Waker>>>>, } /// Create a new asynchronous channel pub fn channel<T>() -> (Sender<T>, Channel<T>) { let (sender, receiver) = mpsc::channel(); let waker = Arc::new(Mutex::new(None)); ( Sender { sender, waker: waker.clone(), }, Channel { receiver: Rc::new(receiver), waker, }, ) } /// Create a new synchronous, bounded channel pub fn sync_channel<T>(bound: usize) -> (SyncSender<T>, Channel<T>) { let (sender, receiver) = mpsc::sync_channel(bound); let waker = Arc::new(Mutex::new(None)); ( SyncSender { sender, waker: waker.clone(), }, Channel { receiver: Rc::new(receiver), waker, }, ) } impl<T: 'static> EventSource for Channel<T> { type Event = Event<T>; fn make_dispatcher<Data: 'static, F: FnMut(Event<T>, &mut Data) + 'static>( &mut self, callback: F, waker: &Arc<Waker>, ) -> Rc<RefCell<dyn EventDispatcher<Data>>> { *(self.waker.lock().unwrap()) = Some(waker.clone()); Rc::new(RefCell::new(Dispatcher { _data: ::std::marker::PhantomData, receiver: self.receiver.clone(), callback, })) } } struct Dispatcher<Data, T, F: FnMut(Event<T>, &mut Data)> { _data: std::marker::PhantomData<fn(&mut Data)>, receiver: Rc<mpsc::Receiver<T>>, callback: F, } impl<Data, T, F: FnMut(Event<T>, &mut Data)> EventDispatcher<Data> for Dispatcher<Data, T, F> { fn ready(&mut self, _: Option<&MioEvent>, data: &mut Data) { loop { match self.receiver.try_recv() { Ok(val) => (self.callback)(Event::Msg(val), data), Err(mpsc::TryRecvError::Empty) => break, Err(mpsc::TryRecvError::Disconnected) => { (self.callback)(Event::Closed, data); break; } } } } } #[cfg(test)] mod tests { use super::*; #[test] fn basic_channel() { let mut event_loop = crate::EventLoop::new().unwrap(); let handle = event_loop.handle(); let (tx, rx) = channel::<()>(); // (got_msg, got_closed) let mut got = (false, false); let _source = handle .insert_source(rx, move |evt, got: &mut (bool, bool)| match evt { Event::Msg(()) => { got.0 = true; } Event::Closed => { got.1 = true; } }) .map_err(Into::<std::io::Error>::into) .unwrap(); // nothing is sent, nothing is received event_loop .dispatch(Some(::std::time::Duration::from_millis(0)), &mut got) .unwrap(); assert_eq!(got, (false, false)); // a message is send tx.send(()).unwrap(); event_loop .dispatch(Some(::std::time::Duration::from_millis(0)), &mut got) .unwrap(); assert_eq!(got, (true, false)); // the sender is dropped ::std::mem::drop(tx); event_loop .dispatch(Some(::std::time::Duration::from_millis(0)), &mut got) .unwrap(); assert_eq!(got, (true, true)); } #[test] fn basic_sync_channel() { let mut event_loop = crate::EventLoop::new().unwrap(); let handle = event_loop.handle(); let (tx, rx) = sync_channel::<()>(2); let mut received = (0, false); let _source = handle .insert_source(rx, move |evt, received: &mut (u32, bool)| match evt { Event::Msg(()) => { received.0 += 1; } Event::Closed => { received.1 = true; } }) .map_err(Into::<std::io::Error>::into) .unwrap(); // nothing is sent, nothing is received event_loop .dispatch(Some(::std::time::Duration::from_millis(0)), &mut received) .unwrap(); assert_eq!(received.0, 0); assert!(!received.1); // fill the channel tx.send(()).unwrap(); tx.send(()).unwrap(); assert!(tx.try_send(()).is_err()); // empty it event_loop .dispatch(Some(::std::time::Duration::from_millis(0)), &mut received) .unwrap(); assert_eq!(received.0, 2); assert!(!received.1); // send a final message and drop the sender tx.send(()).unwrap(); std::mem::drop(tx); // final read of the channel event_loop .dispatch(Some(::std::time::Duration::from_millis(0)), &mut received) .unwrap(); assert_eq!(received.0, 3); assert!(received.1); } }
Python
UTF-8
18,217
2.703125
3
[]
no_license
# -*- coding: utf-8 -*- """all procedures for recipes""" import pandas as pd import numpy as np from . ingredient import Ingredient from .. import config from .. import transformer import time from typing import List, Union, Dict, Optional import re import logging logger = logging.getLogger(__name__) def translate_header(ingredient: Ingredient, *, result=None, **options) -> Ingredient: """Translate column headers available options are: `dictionary`: a dictionary of oldname -> newname mappings """ logger.info("translate_header: " + ingredient.ingred_id) rm = options['dictionary'] data = ingredient.copy_data() for k in list(data.keys()): if k in rm.keys(): # if we need to rename the concept name data[rm[k]] = data[k].rename(columns=rm).copy() del(data[k]) else: # we only rename index/properties columns data[k] = data[k].rename(columns=rm) # also rename the key newkey = ingredient.key if ingredient.dtype in ['datapoints', 'concepts']: for key in rm.keys(): if key in ingredient.key: newkey = newkey.replace(key, rm[key]) else: for key in rm.keys(): if key in ingredient.key: newkey[ingredient.key.index(key)] = rm[key] if not result: result = ingredient.ingred_id + '-translated' return Ingredient(result, None, newkey, None, data=data) def translate_column(ingredient: Ingredient, *, result=None, **options) -> Ingredient: """Translate column values. available options are: `dictionary`: a dictionary of oldname -> newname mappings `column`: the column to rename `base`: if base is provided, transform the columns base on information of base ingredient. So that oldname column will be change to values from newname column. Note: if base and column are provided at same time, it will raise an error. """ logger.info("translate_column: " + ingredient.ingred_id) if 'column' in options.keys() and 'base' in options.keys(): raise ValueError("only accept column or base option, not both") try: column = options['column'] rm = options['dictionary'] except KeyError: base_dict = options['base'].get_data() assert len(options['dictionary']) == 1 assert len(base_dict) == 1 _, base_df = base_dict.popitem() k, v = options['dictionary'].popitem() column = k rm = base_df.set_index(k)[v].to_dict() di = ingredient.copy_data() for k, df in di.items(): df = df.set_index(column) di[k] = df.rename(index=rm).reset_index() if not result: result = ingredient.ingred_id + '-translated' return Ingredient(result, None, ingredient.key, None, data=di) def copy(ingredient: Ingredient, *, result=None, **options) -> Ingredient: """make copy of ingredient data, with new names. available options: `dictionary`: a dictionary of oldname -> newname mappings """ logger.info("copy: " + ingredient.ingred_id) dictionary = options['dictionary'] data = ingredient.copy_data() for k, v in dictionary.items(): if isinstance(v, str): # value is str, means only make one copy data[v] = data[k].rename(columns={k: v}).copy() else: # then it's a list, should make multiple copy for n in v: data[n] = data[k].rename(columns={k: n}).copy() # usually the old ingredient won't be used after creating copy. # just reset the data to save memory ingredient.reset_data() if not result: result = ingredient.ingred_id + '_' return Ingredient(result, None, ingredient.key, None, data=data) def merge(*ingredients: List[Ingredient], result=None, **options): """the main merge function avaliable options: deep: if True, then do deep merging. Default is False About deep merging: deep merge is when we check every datapoint for existence if false, overwrite is on the file level. If key-value (e.g. geo,year-population_total) exists, whole file gets overwritten if true, overwrite is on the row level. If values (e.g. afr,2015-population_total) exists, it gets overwritten, if it doesn't it stays """ logger.info("merge: " + str([i.ingred_id for i in ingredients])) # assert that dtype and key are same in all dataframe try: assert len(set([x.key for x in ingredients])) == 1 assert len(set([x.dtype for x in ingredients])) == 1 except (AssertionError, TypeError): log1 = "multiple dtype/key detected: \n" log2 = "\n".join(["{}: {}, {}".format(x.ingred_id, x.dtype, x.key) for x in ingredients]) logger.warning(log1+log2) raise ValueError("can't merge data with multiple dtype/key!") # get the dtype and index # we have assert dtype and key is unique, so we take it from # the first ingredient dtype = ingredients[0].dtype if dtype == 'datapoints': index_col = ingredients[0].key_to_list() newkey = ','.join(index_col) else: index_col = ingredients[0].key newkey = index_col if 'deep' in options.keys(): deep = options.pop('deep') else: deep = False if deep: logger.info("merge: doing deep merge") # merge data from ingredients one by one. res_all = {} for i in ingredients: res_all = _merge_two(res_all, i.get_data(), index_col, dtype, deep) if not result: result = 'all_data_merged_'+str(int(time.time() * 1000)) return Ingredient(result, None, newkey, '*', data=res_all) def __get_last_item(ser): if ser.last_valid_index() is None: return np.nan else: return ser[ser.last_valid_index()] def _merge_two(left: Dict[str, pd.DataFrame], right: Dict[str, pd.DataFrame], index_col: Union[List, str], dtype: str, deep=False) -> Dict[str, pd.DataFrame]: """merge 2 ingredient data.""" if len(left) == 0: return right if dtype == 'datapoints': if deep: for k, df in right.items(): if k in left.keys(): left[k] = left[k].append(df, ignore_index=True) left[k] = left[k].drop_duplicates(subset=index_col, keep='last') left[k] = left[k].sort_values(by=index_col) else: left[k] = df else: for k, df in right.items(): left[k] = df res_data = left elif dtype == 'concepts': left_df = pd.concat(left.values()) right_df = pd.concat(right.values()) if deep: merged = left_df.append(right_df, ignore_index=True) res = merged.groupby(index_col).agg(__get_last_item) res_data = {'concept': res.reset_index()} else: res_data = {'concept': right_df.drop_duplicates(subset='concept', keep='last')} else: # TODO raise NotImplementedError('entity data do not support merging yet.') return res_data def identity(ingredient: Ingredient, *, result=None, **options) -> Ingredient: """return the ingredient as is. available options: copy: if copy is True, then treat all data as string. Default: False """ if 'copy' in options and options['copy'] is True: ingredient.data = ingredient.get_data(copy=True) else: ingredient.data = ingredient.get_data() if result: ingredient.ingred_id = result return ingredient def filter_row(ingredient: Ingredient, *, result=None, **options) -> Ingredient: """filter an ingredient based on a set of options and return the result as new ingredient. Args: ingredient: Ingredient object result: ingred_id of return ingredient options: dict of options available options: dictionary: test """ logger.info("filter_row: " + ingredient.ingred_id) data = ingredient.get_data() dictionary = options.pop('dictionary') res = {} for k, v in dictionary.items(): from_name = v.pop('from') df = data[from_name] if len(v) == 0: res[k] = df.rename(columns={from_name: k}) continue queries = [] for col, val in v.items(): if isinstance(val, list): queries.append("{} in {}".format(col, val)) elif isinstance(val, str): queries.append("{} == '{}'".format(col, val)) elif np.issubdtype(type(val), np.number): queries.append("{} == {}".format(col, val)) # TODO: support more query methods. else: raise ValueError("not supported in query: " + str(type(val))) query_string = ' and '.join(queries) df = df.query(query_string).copy() df = df.rename(columns={from_name: k}) # drops all columns with unique contents. and update the key. newkey = ingredient.key keys = ingredient.key_to_list() for c in df.columns: if ingredient.dtype == 'datapoints': if c in v.keys() and len(df[c].unique()) > 1: logger.debug("column {} have multiple values: {}".format(c, df[c].unique())) elif len(df[c].unique()) <= 1: df = df.drop(c, axis=1) if c in keys: keys.remove(c) newkey = ','.join(keys) else: raise NotImplementedError("filtering concept/entity") res[k] = df if not result: result = ingredient.ingred_id + '-filtered' return Ingredient(result, None, newkey, '*', data=res) def filter_item(ingredient: Ingredient, *, result: Optional[str]=None, **options) -> Ingredient: """filter item from the ingredient data dict. available options: items: a list of items to filter from base ingredient """ logger.info("filter_item: " + ingredient.ingred_id) data = ingredient.get_data() items = options.pop('items') try: data = dict([(k, data[k]) for k in items]) except KeyError: logger.debug("keys in {}: {}".format(ingredient.ingred_id, str(list(data.keys())))) raise if not result: result = ingredient.ingred_id return Ingredient(result, None, ingredient.key, None, data=data) def align(to_align: Ingredient, base: Ingredient, *, result=None, **options) -> Ingredient: """align 2 ingredient by a column. This function is like an automatic version of translate_column. It firstly creating the mapping dictionary by searching in the base ingredient for data in to_align ingredient, and then translate according to the mapping file. available options: `search_cols`: a list of columns of base ingredient, to search for values `to_find`: the column of ingredient to_align. The function will search the data of this column in search_cols `to_replace`: the column of to_align ingredient to replace with new value. can be same as to_find or a new column `drop_not_found`: if we should drop those entities not found in the base """ try: search_cols = options.pop('search_cols') to_find = options.pop('to_find') to_replace = options.pop('to_replace') except KeyError: raise KeyError("not enough parameters! please check your recipe") if 'drop_not_found' not in options: drop_not_found = True else: drop_not_found = options['drop_not_found'] if len(base.get_data()) > 1: logger.critical(base.get_data().keys()) raise NotImplementedError('align to base data with multiple dataframes is not supported yet.') logger.info("aligning: {} with {}".format(to_align.ingred_id, base.ingred_id)) base_data = list(base.get_data().values())[0] ing_data = to_align.get_data() base_data = base_data.set_index(base.key) mapping = {} no_match = [] for k, df in ing_data.items(): for f in df[to_find].unique(): if f in mapping: continue # filtering name in all search_cols bools = [] for sc in search_cols: bools.append(base_data[sc] == f) mask = bools[0] for m in bools[1:]: mask = mask | m filtered = base_data[mask] if len(filtered) == 1: mapping[f] = filtered.index[0] elif len(filtered) > 1: logger.warning("multiple match found: "+f) mapping[f] = filtered.index[0] else: no_match.append(f) if drop_not_found: # drop those entities not found in the mappings df_ = df[df[to_find].isin(mapping.keys())].copy() else: df_ = df.copy() for old, new in mapping.items(): if not pd.isnull(new): df_.at[df_[to_find] == old, to_replace] = new ing_data[k] = df_ if len(no_match) > 0: logger.warning("no match found for: " + str(set(no_match))) if not result: result = to_align.ingred_id + '-aligned' if to_align.dtype == 'datapoints': newkey = to_align.key.replace(to_find, to_replace) return Ingredient(result, None, newkey, None, data=ing_data) else: return Ingredient(result, None, to_replace, None, data=ing_data) def groupby(ingredient: Ingredient, *, result=None, **options) -> Ingredient: """group ingredient data by column(s) and run aggregate function available options: by: the column(s) to group, can be a list or a string aggregate: the function to aggregate. Default: sum """ data = ingredient.get_data() by = options.pop('by') logger.info("groupby: " + ingredient.ingred_id) try: agg = options.pop('aggregate') except KeyError: logger.warning("no aggregate function found, assuming sum()") agg = 'sum' for k, df in data.items(): df = df.groupby(by=by).agg({k: agg}) newkey = ','.join(df.index.names) data[k] = df.reset_index() if not result: result = ingredient.ingred_id + '-agg' return Ingredient(result, None, newkey, None, data=data) def accumulate(ingredient: Ingredient, *, result=None, **options) -> Ingredient: """run accumulate function on ingredient data. available options: op: a dictionary of concept_name: function mapping """ logger.info("accumulate: " + ingredient.ingred_id) if ingredient.dtype != 'datapoints': raise ValueError("only datapoint support this function!") ops = options.pop('op') data = ingredient.get_data() index = ingredient.key_to_list() funcs = { 'aagr': _aagr } for k, func in ops.items(): df = data[k] df = df.groupby(by=index).agg('sum') assert re.match('[a-z_]+', func) # only lower case chars allowed, for security # assuming level0 index is geo # because we should run accumulate for each country # TODO: https://github.com/semio/ddf_utils/issues/25 if func in funcs: df = df.groupby(level=0, as_index=False).apply(funcs[func]) df = df.reset_index() df = df[index + [k]] else: df = eval("df.groupby(level=0).{}()".format(func)) df = df.reset_index() data[k] = df if not result: result = ingredient.ingred_id + '-accued' return Ingredient(result, None, ingredient.key, None, data=data) def _aagr(df: pd.DataFrame, window: int=10): """average annual growth rate""" pct = df.pct_change() return pct.rolling(window).apply(np.mean).dropna() def run_op(ingredient: Ingredient, *, result=None, **options) -> Ingredient: """run math operation on each row of ingredient data. available options: op: a dictionary of concept_name: function mapping """ assert ingredient.dtype == 'datapoints' logger.info("run_op: " + ingredient.ingred_id) data = ingredient.get_data() keys = ingredient.key_to_list() ops = options['op'] # concat all the datapoint dataframe first, and eval the ops to_concat = [v.set_index(keys) for v in data.values()] df = pd.concat(to_concat, axis=1) for k, v in ops.items(): res = df.eval(v).dropna() # type(res) is Series res.name = k if k not in df.columns: df[k] = res data[k] = res.reset_index() if not result: result = ingredient.ingred_id + '-op' return Ingredient(result, None, ingredient.key, None, data=data) def extract_concepts(*ingredients: List[Ingredient], result=None, **options) -> Ingredient: """extract concepts from other ingredients. """ if options: base = options['join']['base'] try: join = options['join']['type'] except KeyError: join = 'full_outer' concepts = base.get_data()['concepts'].set_index('concept') else: concepts = pd.DataFrame([], columns=['concept', 'concept_type']).set_index('concept') new_concepts = set() for i in ingredients: data = i.get_data() for k, df in data.items(): # TODO: add logic for concepts/entities ingredients new_concepts.add(k) if k in concepts.index: continue if np.issubdtype(df[k].dtype, np.number): concepts.ix[k, 'concept_type'] = 'measure' else: concepts.ix[k, 'concept_type'] = 'string' if join == 'ingredients_outer': # ingredients_outer join: only keep concepts appears in ingredients concepts = concepts.ix[new_concepts] if not result: result = 'concepts_extracted' return Ingredient(result, None, 'concept', None, data=concepts.reset_index())