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
Rust
UTF-8
4,662
3.34375
3
[]
no_license
//! Exercise for using logging statements appropriately. //! //! This exercise contains many println! statements which //! should not be released as part of making the code public. //! It would be better to add useful logging statements with //! appropriate severity levels to the MemoryBuffer API instead. //! //! 1) Integrate the `log` and `env_logger` crates //! 2) Choose where new logging calls make sense //! 3) Verify that RUST_LOG works as expected #[macro_use] extern crate log; extern crate env_logger; use std::fmt::{self, Debug}; use std::ops::{Deref, DerefMut}; #[derive(Copy, Clone, Debug, PartialEq)] enum Permission { ReadOnly, ReadWrite, } use buffer::MemoryBuffer; mod buffer { use std::collections::HashMap; use super::{TruncatedDebug, Permission}; const BLOCK_SIZE: usize = 32; #[derive(Debug)] pub struct MemoryBuffer { buffer: TruncatedDebug<[u16; BLOCK_SIZE]>, permissions: TruncatedDebug<HashMap<usize, Permission>>, } impl MemoryBuffer { /// Create a new memory buffer. pub fn new() -> MemoryBuffer { MemoryBuffer { buffer: TruncatedDebug([0; BLOCK_SIZE]), permissions: TruncatedDebug(HashMap::new()), } } /// Mark every memory slot as being read-only. pub fn make_read_only(&mut self) { self.change_permissions(0, BLOCK_SIZE, Permission::ReadOnly); info!("buffer is read only"); } /// Mark all of the memory slots between `start` and `end` as having the given permission. fn change_permissions(&mut self, start: usize, end: usize, perm: Permission) { trace!("changing permissions from {} to {} to {:?}", start, end, perm); for idx in start..end { self.permissions.insert(idx, perm); } } /// Return the permission for the given slot, defaulting to ReadWrite if not explicit /// permission has been set. fn permission_at(&self, idx: usize) -> Permission { *self.permissions.get(&idx).unwrap_or(&Permission::ReadWrite) } /// Write a value to the given slot. Returns Err if the slot does not have ReadWrite /// permissions attached to it. pub fn write_memory_at(&mut self, idx: usize, val: u16) -> Result<(), ()> { if idx > self.buffer.len() { error!("invalid index: {}", idx); return Err(()); } if self.permission_at(idx) != Permission::ReadOnly { self.buffer[idx] = val; Ok(()) } else { Err(()) } } /// Write a value to the given slot. Returns Err if the slot does not have ReadWrite /// permissions attached to it. pub fn read_memory_at(&mut self, idx: usize) -> Result<u16, ()> { if idx > self.buffer.len() { error!("invalid index: {}", idx); Err(()) } else { Ok(self.buffer[idx]) } } /// The size of this memory buffer. pub fn size(&self) -> usize { BLOCK_SIZE } } } struct TruncatedDebug<T: Debug>(T); impl<T: Debug> Deref for TruncatedDebug<T> { type Target = T; fn deref(&self) -> &T { &self.0 } } impl<T: Debug> DerefMut for TruncatedDebug<T> { fn deref_mut(&mut self) -> &mut T { &mut self.0 } } impl<T: Debug> Debug for TruncatedDebug<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut truncated = format!("{:?}", self.0); let last = truncated.chars().last(); truncated.truncate(20); truncated.push_str("..."); if let Some(last) = last { truncated.push(last); } write!(f, "{}", truncated) } } fn main() { env_logger::init(); // Create a memory buffer representation. let mut buffer = MemoryBuffer::new(); // Initialize each memory slot with a unique value. for i in 0..buffer.size() { let _ = buffer.write_memory_at(i, (i + 1) as u16); } // Mark every memory slot as read-only. buffer.make_read_only(); // Try to overwrite each memory slot with 0. // This is supposed to silently fail, since the buffer // should be read-only. for i in 0..buffer.size() { let _ = buffer.write_memory_at(i, 0); } // Look for any evidence that any writes succeeded. for i in 0..buffer.size() { if buffer.read_memory_at(i) == Ok(0) { // ???? } } }
Java
UTF-8
293
2.8125
3
[]
no_license
package com.leach.advance.annotation.meta.inherited; /** * @author Administrator * @name 概述: * @date 2019/3/6 15:54 */ public class Cat extends Animal { @Override public void sayMyself() { System.out.println("大家好,我是猫咪^_^!"); } }
C++
UTF-8
492
2.75
3
[]
no_license
#pragma once struct node { node* parent; node* left; node* right; int key; int height; int heaviness;//right->height - left->height }; class AVL { private: node* AVLRootNode; int kValue; public: AVL(void); void addNode(void); void printAVL(node*); node* getRootNode(void); int setHeight(node*); void setHeaviness(node*); void rightRotate(node*); void leftRotate(node*); void makeAVL(node*); //~AVL(void); };
Markdown
UTF-8
2,904
3.625
4
[ "MIT", "Apache-2.0" ]
permissive
--- layout: post title: "Problem: Serialize and Deserialize BST" date: 2015-02-18 00:00:00 author: "Marcy" header-img: "img/post-bg-2015.jpg" catalog: true category: algnote algnote-tags: - Coding Interview - Coding Practice - Algorithms and Data Structures - Tree - Binary Tree - Binary Search Tree - Medium --- ## Question Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary search tree can be serialized to a string and this string can be deserialized to the original tree structure. **The encoded string should be as compact as possible.** Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless. ## Solution TODO #### Code Here is a sample solution. ```java /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Codec { // Encodes a tree to a single string. public String serialize(TreeNode root) { List<String> list = new ArrayList<>(); serialize(root, list); return String.join(" ", list); } private void serialize(TreeNode root, List<String> list) { if(root == null) return; list.add(String.valueOf(root.val)); serialize(root.left, list); serialize(root.right, list); } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { if(data.length() == 0) return null; Queue<Integer> q = new LinkedList<>(); String[] list = data.split(" "); for(String s: list) { q.offer(Integer.valueOf(s)); } return deserialize(q, Long.MIN_VALUE, Long.MAX_VALUE); } public TreeNode deserialize(Queue<Integer> q, long min, long max) { if(q.isEmpty()) return null; if(q.peek() < min || q.peek() > max) return null; int val = q.poll(); TreeNode n = new TreeNode(val); n.left = deserialize(q, min, val); n.right = deserialize(q, val, max); return n; } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.deserialize(codec.serialize(root)); ``` ## Performance Both serialize and deserialize methods traverse over each node in the tree once. So the time complexity is `O(n)`, and the space complexity is `O(n)` for using recursion and the queue.
Java
UTF-8
4,729
3.65625
4
[]
no_license
package uk.ac.qub.UpdatedCalculator; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class Testing { CalculatorMethods cm = new CalculatorMethods(); @Before public void setUp() throws Exception { } @Test public void testAddMe() { //Testing AddMe method int num1, num2; //Setting up ints to test num1 = 1; //num1 is 1 num2 = 2; //num2 is 2 int expected = 3; //Expected value of addition method int actual = cm.addMe(num1, num2); //Actual value of addition method - invoke method assertEquals(expected, actual); //assertEquals method on the two values. } @Test /** * Testing AddMeThree method. Should add up three numbers and return the results. */ public void testAddMeThree() { int num1, num2, num3; //Setting up ints to test num1 = 1; //num1 is 1 num2 = 2; //num2 is 2 num3 = 3; //num3 is 3 int expected = 6; //Expected value of addition method int actual = cm.addMeThree(num1, num2, num3); //Actual value of addition method - invoke method assertEquals(expected, actual); //assertEquals method on the two values } /** * Testing subtractMe method. Should substract two numbers and return the results. */ @Test public void testSubtractMe() { int num1, num2; //Setting up ints to test num1 = 10; //num1 is 10 num2 = 5; //num2 is 5 int expected = 5; //Expected value of subtraction method int actual = cm.subtractMe(num1, num2); //Actual value of subtraction method - invoke method assertEquals(expected, actual); //assertEquals method on the two values to see if the two values are the same. If not, should fail. } /** * Testing subtractMeThree method. Should subtract three numbers and return the results. */ @Test public void testSubtractMeThree() { int num1, num2, num3, actual, expected; //Setting up ints to test num1 = 20; num2 = 5; num3 = 5; expected = 10; //Expected value for the subtraction method actual = cm.subtractMeThree(num1, num2, num3); //Actual value of subtraction method - invoke method assertEquals(expected, actual); //assertEquals method on the two values to see if the two values are the same. If not, should fail. } /** * Testing multiplyMe method. Should multiply two numbers and return the results */ @Test public void testMultiplyMe() { int num1, num2, actual, expected; //Setting up ints to test num1 = 2; num2 = 5; expected = 10; //Expected value for the multiply method actual = cm.multiplyMe(num1, num2); //Actual value of multiply method - invoke method assertEquals(expected, actual); //assertEquals method on the two values to see if the two values are the same. If not, should fail. } /** * This method is testing the divideMe method. Happy case. Should divide two numbers and return the results */ @Test public void testDivideMe() { int num1, num2, actual, expected; //Setting up ints to test num1 = 10; num2 = 2; expected = 5; //Expected value for the dividing method actual = cm.divideMe(num1, num2); //Actual value of divide method - invoke method assertEquals(expected, actual); //assertEquals method on the two values to see if the two values are the same. If not, should fail. } /** * Testing handling of division by zero. Should fail with an ArithmeticException */ @Test(expected=java.lang.ArithmeticException.class) public void testDivideMeFail(){ int num1, num2; num1 = 0; num2 = 10; int actual = cm.divideMe(num1, num2); } /** * Testing setting of memory var */ @Test public void testMemory() { int expected, actual; expected = 1; actual = cm.setMemory(expected); assertEquals(expected, actual); } /** * Testing adding to memory value. */ @Test public void testAddToMemory() { int num1, memory, expected, actual; num1 = 2; memory = 1; expected = 3; actual = cm.addToMemory(num1, memory); assertEquals(expected, actual); } /** * Testing recall of memory var. Should print out whatever user has placed into memory */ @Test public void testRecallMemory() { cm.setMemory(2); cm.recallMemory(); } /** * Testing clearing memory var, should return 0 */ @Test public void testClearMemory() { int actual, expected, memory; expected = 0; memory = 1; actual = cm.clearMemory(memory); assertEquals(expected, actual); } /** * Testing square root function */ @Test public void testFindSquareRoot() { int actual, expected, num1; num1 = 100; expected = 10; actual = cm.findSquareRoot(num1); assertEquals(expected, actual); } }
Shell
UTF-8
150
2.765625
3
[]
no_license
#!/bin/bash BASEDIR="$(dirname "$0")" ROOT="$(realpath $BASEDIR/..)" PYTH="$(which python)" PWD="$(pwd)" cd $ROOT $PYTH $ROOT/test/test.py cd $PWD
Java
UTF-8
1,627
3.5
4
[ "CC0-1.0" ]
permissive
package mx.com.ventas; public class Orden { private final int idOrden; private final Producto[] productos; private static int contadorOrdenes; private int contadorProductos; private static final int MAX_PRODUCTOS = 10; public Orden() { this.idOrden = ++Orden.contadorOrdenes; this.productos = new Producto[Orden.MAX_PRODUCTOS];//Se inicializa el arreglo con el objeto Producto } public void agregarProducto(Producto producto) { if (this.contadorProductos < Orden.MAX_PRODUCTOS) {//Comparacion con el contador y el arreglo this.productos[this.contadorProductos++] = producto;//añadimos el producto a nuestro arreglo } else { System.out.println("Se ha superado el máximo de productos" + Orden.MAX_PRODUCTOS); } } public double calcularTotal() { double total = 0; for (int a = 0; a < this.contadorProductos; a++) { total += this.productos[a].getPrecio();//Simplficado en una linea de código // Forma extensa // Producto producto = this.productos[a]; // total += productos[a].getPrecio(); } return total; } public void mostrarOrden() { System.out.println("Id Orden: " + this.idOrden); double totalOrden = this.calcularTotal(); System.out.println("Total de la Orden: $" + totalOrden); System.out.println("Productos de la orden: "); for (int i = 0; i < this.contadorProductos; i++) { System.out.println(this.productos[i]); } } }
Markdown
UTF-8
5,236
3.0625
3
[]
no_license
# Data Visualization Final 2019 ## Team Member : Vaidehi Thete (vvt221) ## Tasks Chosen: 1. What is the serving rate for each scenario throughout the day, comparing to the overall serving rate? Serving rate is the number of successfully matched trip in a period of time. For example, is the serving rate higher in the rush hour or at night? 2. For those trips that could not be served, do they follow a spatial or temporal pattern? For example, are most of those trips originated in particular regions, and of certain times? 4. We also limit vehicle capacity to at most 4 passengers. Were there vehicles violating this condition? If so, can you show any pattern about these vehicles? For example, how many of them were violating, and where were they distributed in both time and space? ##### Note : Steps for the creation of the dataset for visualization purposes are available in the supporting .ipynb notebooks which can be found in the repo. ## Links to Visualization and Short Explanation: ### Task 1: What is the serving rate for each scenario throughout the day, comparing to the overall serving rate? Serving rate is the number of successfully matched trip in a period of time. For example, is the serving rate higher in the rush hour or at night? #### Plot 1: https://bl.ocks.org/vvt221/0820e350bd4019b50fc4f7b903c1435e #### Explanation 1: The above plot shows the hourly serving rate against the mean serving rate based on the number of requests made. Serving rate is very high in the morning hours accounting for everyone probably commuting to the workplaces. There is a dip around 11 am and stays below the mean till 8.00 pm from where it rises above the average serving rate till 10.00pm after which it again falls below the averge serving rate. Clearly, the serving rate is very high during the morning hours. ### Task 2: For those trips that could not be served, do they follow a spatial or temporal pattern? For example, are most of those trips originated in particular regions, and of certain times? #### Plot 1: https://bl.ocks.org/vvt221/7308a3becd0c42c40a22ff735f3fb555 #### Explanation: From the plot it can be seen that a majority of the trips are not served in the early hours of the morning from 12.00 AM to 4.00 AM. However, this trend suddenly drops between 5.00 AM and 11.00 AM . This could be because this is the time duration around which people commute to their workplaces and they cannot afford to be late which is why the number of trips where the rides are dropped is low. There is once again an increase in the number of trips dropped. However there is a sharp decline in the number of trips dropped at 9.00 pm ,which could be due to people wanting to reach home as early as possible. The high percentage of ride dropping during the hours discussed above could be due to the high price being charged during these hours but data is not available to verify that. #### Plot 2: https://bl.ocks.org/vvt221/361d67866f021d266f52fd930f7792bb #### Explanation: This plot shows the bar charts based on the counts of the Actual_Pickup station where most rides could not be served. The counts are then sorted in decreasing order of their frequency. Station ID 229 and Station ID 1196 hold the record for having the highest number of dropped records. Further exploration is done in the spatial plot below: #### Plot 3: https://bl.ocks.org/vvt221/89551b051b549965b8ac67b375280bbd #### Explanation: This plot shows the number of dropped rides at census tract level in Manhattan. From the plot we can see that a large number of rides are dropped in the Central Park region. There are few census tracts near the financial district which hace a high drop rate. Another region with a high ride drop rate is the area in the upper regions of Manhattan. ### Task 4: We also limit vehicle capacity to at most 4 passengers. Were there vehicles violating this condition? Ifso, can you show any pattern about these vehicles? For example, how many of them were violating,and where were they distributed in both time and space? #### Plot 1: https://bl.ocks.org/vvt221/8bf02bece90b84e4d349cc51645e23d0 #### Explanation: This plot shows the hourly distribution of counts of rides where the number of passengers exceeded 4. There are a lot of such rides during the late night hours and early morning hours. But the number is less during the morning and afternoon hours. It could be possible due to garbage values because the passenger count exceeds 10 and goes on till 68 which are probably garbage values. #### Plot 2: https://bl.ocks.org/vvt221/dc8610c07a8ba2818e291a37eacc89f6 #### Explanation: This plot shows the number of passengers exceeding 4 varies throughout the hour of the day and pretty much is consistent with the above plot but can be used to see how the distribution varies hourly at a granular level. #### Plot 3: https://bl.ocks.org/vvt221/ca1a385328565e7df266ea28e258db10 #### Explanation: This plot over here shows the spatial distribution of rides where the passenger count exceeds 4 at the census tract level. The preponderance of such rides all over Manhattan leads us to believe that it could possible be due to garbage values being entered in the passenger info field.
Java
UTF-8
3,366
2.3125
2
[]
no_license
package cursedflames.modifiers.common.config; import java.nio.file.Path; import java.util.Arrays; import java.util.List; import com.electronwill.nightconfig.core.file.CommentedFileConfig; import com.electronwill.nightconfig.core.io.WritingMode; import net.minecraftforge.common.ForgeConfigSpec; import net.minecraftforge.common.ForgeConfigSpec.ConfigValue; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.config.ModConfig; @Mod.EventBusSubscriber public class Config { public static final String CATEGORY_GENERAL = "general"; public static final String CATEGORY_REFORGE = "reforge"; public static final String SUBCAT_CURIO = "curio"; private static final ForgeConfigSpec.Builder COMMON_BUILDER = new ForgeConfigSpec.Builder(); private static final ForgeConfigSpec.Builder CLIENT_BUILDER = new ForgeConfigSpec.Builder(); public static ForgeConfigSpec COMMON_CONFIG; public static ForgeConfigSpec CLIENT_CONFIG; public static ForgeConfigSpec.BooleanValue CURIO_IS_WHITELIST; public static ConfigValue<List<? extends String>> CURIO_SLOTS_ALLOWED; public static ForgeConfigSpec.BooleanValue REFORGE_ENABLED; public static ForgeConfigSpec.IntValue REFORGE_COST_MIN; public static ForgeConfigSpec.IntValue REFORGE_COST_MAX; static { COMMON_BUILDER.comment("General configuration").push(CATEGORY_GENERAL); setupGeneralConfig(); COMMON_BUILDER.pop(); COMMON_BUILDER.comment("Reforger configuration").push(CATEGORY_REFORGE); setupReforgeConfig(); COMMON_BUILDER.pop(); COMMON_CONFIG = COMMON_BUILDER.build(); CLIENT_CONFIG = CLIENT_BUILDER.build(); } private static void setupGeneralConfig() { COMMON_BUILDER.comment("Curios").push(SUBCAT_CURIO); CURIO_IS_WHITELIST = COMMON_BUILDER .comment("If true, the list of curio modifier slots is a whitelist, otherwise it's a blacklist") .define("curio_is_whitelist", false); CURIO_SLOTS_ALLOWED = COMMON_BUILDER .comment("Blacklist/Whitelist of curio slots that allow modifiers", "Set curio_is_whitelist to control whether this is a whitelist or blacklist.") .defineList("curio_slots_list", Arrays.asList("example1", "example2"), String.class::isInstance); COMMON_BUILDER.pop(); } private static void setupReforgeConfig() { REFORGE_ENABLED = COMMON_BUILDER .comment("Whether the reforger gui, accessed by right clicking the smithing station, is enabled", "If disabled, items will not be reforgeable") .define("reforge_enabled", true); REFORGE_COST_MIN = COMMON_BUILDER .comment("Minimum cost, in XP points, to reforge an item") .defineInRange("reforge_cost_min", 80, 1, Integer.MAX_VALUE/100); REFORGE_COST_MAX = COMMON_BUILDER .comment("Maximum cost, in XP points, to reforge an item") .defineInRange("reforge_cost_max", 160, 1, Integer.MAX_VALUE/100); } public static void loadConfig(ForgeConfigSpec spec, Path path) { final CommentedFileConfig configData = CommentedFileConfig.builder(path) .sync() .autosave() .writingMode(WritingMode.REPLACE) .build(); configData.load(); spec.setConfig(configData); } @SubscribeEvent public static void onLoad(final ModConfig.Loading configEvent) { } @SubscribeEvent public static void onReload(final ModConfig.ConfigReloading configEvent) { } }
Python
UTF-8
398
3.171875
3
[]
no_license
from typing import * class Solution: """ https://www.cnblogs.com/grandyang/p/5226206.html 博弈的问题,竟然能用这种方式。那么292题也能用这种方式了 """ def canWin(self, s): for i in range(1, len(s)): if s[i] == "+" and s[i-1] == "+" and not self.canWin(s[0:i-1] + '--' + s[i+1:]): return True return False
PHP
UTF-8
800
2.96875
3
[ "MIT" ]
permissive
<?php /** * Part of the tueena lib * * @license http://www.opensource.org/licenses/mit-license.php MIT License * @link http://tueena.org/ * @author Bastian Fenske <bastian.fenske@tueena.org> * @file */ declare(strict_types=1); namespace tueenaLib\sql\results; class SelectResult implements ISelectResult { /** * @var \PDOStatement */ private $pdoStatement; public function __construct(\PDOStatement $pdoStatement) { $this->pdoStatement = $pdoStatement; } public function fetchNumeric() { $result = $this->pdoStatement->fetch(\PDO::FETCH_NUM); return $result ? $result : null; } public function fetchAssoc() { $result = $this->pdoStatement->fetch(\PDO::FETCH_ASSOC); return $result ? $result : null; } public function getNumRows(): int { return $this->pdoStatement->rowCount(); } }
JavaScript
UTF-8
1,999
2.765625
3
[]
no_license
var mongo = require("./Mongo.js"); var codesReponse = require("./responseCodes.js"); exports.inscriptionHandler = function(login, mdp){ return new Promise(function(resolve,reject){ mongo.findPlayer(login).then(function(playerFound){ if(playerFound){ reject(new responseObject(false, "loginExists", null)); }else{ mongo.insertPlayer(login, mdp).then(function(playerData){ resolve(new responseObject(true, "inscriptionOk", playerData)); }).catch(function(inscriptionKO){ reject(new responseObject(false, inscriptionKO, null)); }); } }).catch(function(errFind){ reject(new responseObject(false, errFind, null)); }); }); }; exports.validerMdp = function(mdp){ return new Promise(function(resolve, reject) { /* Mdp entre 4 et 8 charactères */ if(mdp.match("^.{4,}$")){ resolve(new responseObject(true, "mdpOk", null)); }else{ reject(new responseObject(false, "mdpRegexKo", null)); } }); }; function responseObject(isSuccess, code, data) { this.success = isSuccess; this.player = data; if(this.success){ for (var i=0; i<codesReponse.okCodes.length; i++) { if(codesReponse.okCodes[i].id== code) { this.status = codesReponse.okCodes[i].status; this.message = codesReponse.okCodes[i].message; break; } } } else { for (var i=0; i<codesReponse.errorCodes.length; i++) { if(codesReponse.errorCodes[i].id == code) { this.status = codesReponse.errorCodes[i].status; this.message = codesReponse.errorCodes[i].message; break; } } } if(this.status==undefined){ this.status = 400; this.message = "Erreur non répertoriée : " + code.message; } }
Python
UTF-8
599
2.75
3
[]
no_license
from PIL import Image import struct def read_image(filename): f = open(filename,'rb') index = 0 buf = f.read() f.close() magic,images,rows,colums = struct.unpack_from('>IIII',buf,index) index += struct.calcsize('>IIII') for i in xrange(images): image = Image.new('L',(colums,rows)) for x in xrange(rows): for y in xrange(colums): image.putpixel((y,x),int(struct.unpack_from('>B',buf,index)[0])) index+=struct.calcsize('>B') print 'save ' + str(i) + 'image' image.save('test' + str(i) + '.png')
PHP
UTF-8
2,003
2.734375
3
[]
no_license
<?php include('connection.php'); if(isset($_POST['upload'])){ $name = $_FILES['file']['name']; $target_dir = "audioupload/"; $target_file = $target_dir . basename($_FILES["file"]["name"]); $audiodescription = ($_REQUEST['audiodescrition']); $audioFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); $uploadOk = 1; // Select file type $sql = "SELECT audiopath, audiodescription FROM audioupload WHERE audiopath='$target_file' and audiodescription='$audiodescription' "; $results = mysqli_query($conn, $sql); // Check if file already exists if (mysqli_num_rows($results) > 0) { $uploadOk = 0; echo "Sorry, file already exists ! "; } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists !! "; $uploadOk = 0; } // Check file size if ($_FILES["file"]["size"] > 45000000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if($audioFileType != "mp3") { echo "Sorry, only mp3 files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded!!!"; // if everything is ok, try to upload file } else { // Insert record $query = "insert into audioupload(audiopath, audiodescription) values( '$target_file','$audiodescription')"; mysqli_query($conn,$query) or die(mysqli_error($con)); if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } } } ?>
Java
UTF-8
11,139
1.914063
2
[ "ISC", "Apache-2.0", "MIT" ]
permissive
package act.mail; /*- * #%L * ACT Framework * %% * Copyright (C) 2014 - 2017 ActFramework * %% * 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. * #L% */ import act.app.App; import act.app.AppHolderBase; import org.osgl.exception.ConfigurationException; import org.osgl.http.H; import org.osgl.util.C; import org.osgl.util.E; import org.osgl.util.S; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import java.util.*; import static org.osgl.http.H.Format.HTML; import static org.osgl.http.H.Format.TXT; public class MailerConfig extends AppHolderBase { public static final String FROM = "from"; public static final String CONTENT_TYPE = "content_type"; public static final String LOCALE = "locale"; public static final String SUBJECT = "subject"; public static final String TO = "to"; public static final String CC = "cc"; public static final String BCC = "bcc"; public static final String SMTP_HOST = "smtp.host"; public static final String SMTP_PORT = "smtp.port"; public static final String SMTP_TLS = "smtp.tls"; public static final String SMTP_SSL = "smtp.ssl"; public static final String SMTP_USERNAME = "smtp.username"; public static final String SMTP_PASSWORD = "smtp.password"; private String id; private boolean isDefault; private boolean mock; private InternetAddress from; private H.Format contentType; private Locale locale; private String subject; private String host; private String port; private boolean useTls; private boolean useSsl; private String username; private String password; private List<InternetAddress> toList; private List<InternetAddress> ccList; private List<InternetAddress> bccList; private volatile Session session; public MailerConfig(String id, Map<String, String> properties, App app) { super(app); E.illegalArgumentIf(S.blank(id), "mailer config id expected"); this.id = id; this.isDefault = "default".equals(id); this.from = getFromConfig(properties); this.contentType = getContentTypeConfig(properties); this.locale = getLocaleConfig(properties); this.subject = getProperty(SUBJECT, properties); this.host = getProperty(SMTP_HOST, properties); if ("gmail".equals(this.host)) { this.host = "smtp.gmail.com"; } this.username = getProperty(SMTP_USERNAME, properties); if (null == host) { if (S.notBlank(this.username) && this.username.endsWith("gmail.com")) { this.host = "smtp.gmail.com"; } else { info("smtp host configuration not found, will use mock smtp to send email"); mock = true; } } if (!mock) { this.useTls = getBooleanConfig(SMTP_TLS, properties) || S.eq("smtp.gmail.com", this.host) || S.eq("smtp-mail.outlook.com", this.host); this.useSsl = !this.useTls && getBooleanConfig(SMTP_SSL, properties); this.port = getPortConfig(properties); this.password = getProperty(SMTP_PASSWORD, properties); if (null == username || null == password) { warn("Either smtp.username or smtp.password is not configured for mailer[%s]", id); } } this.toList = getEmailListConfig(TO, properties); this.ccList = getEmailListConfig(CC, properties); this.bccList = getEmailListConfig(BCC, properties); } private String getProperty(String key, Map<String, String> properties) { String key0 = key; key = S.concat("mailer.", id, ".", key); String val = properties.get(key); if (null != val) { return val; } String key2 = "act." + key; val = properties.get(key2); if (null != val) { return val; } if (isDefault) { key = S.concat("mailer.", key0); val = properties.get(key); if (null != val) { return val; } return properties.get(S.concat("act.", key)); } else { return null; } } private List<InternetAddress> getEmailListConfig(String key, Map<String, String> properties) { String s = getProperty(key, properties); if (S.blank(s)) { return C.list(); } List<InternetAddress> l = new ArrayList<>(); return MailerContext.canonicalRecipients(l, s); } private String getPortConfig(Map<String, String> properties) { String port = getProperty(SMTP_PORT, properties); if (null == port) { if (!useSsl && !useTls) { port = "25"; } else if (useSsl) { port = "465"; } else { port = "587"; } warn("No smtp.port found for mailer[%s] configuration will use the default number: ", id, port); } else { try { Integer.parseInt(port); } catch (Exception e) { throw E.invalidConfiguration("Invalid port configuration for mailer[%]: %s", id, port); } } return port; } private boolean getBooleanConfig(String key, Map<String, String> properties) { String s = getProperty(key, properties); return null != s && Boolean.parseBoolean(s); } private Locale getLocaleConfig(Map<String, String> properties) { String s = getProperty(LOCALE, properties); if (null == s) { return app().config().locale(); } else { // the following code credit to // http://www.java2s.com/Code/Java/Network-Protocol/GetLocaleFromString.htm String localeString = s.trim(); if (localeString.toLowerCase().equals("default")) { return app().config().locale(); } // Extract language int languageIndex = localeString.indexOf('_'); String language = null; if (languageIndex == -1) { // No further "_" so is "{language}" only return new Locale(localeString, ""); } else { language = localeString.substring(0, languageIndex); } // Extract country int countryIndex = localeString.indexOf('_', languageIndex + 1); String country; if (countryIndex == -1) { // No further "_" so is "{language}_{country}" country = localeString.substring(languageIndex + 1); return new Locale(language, country); } else { // Assume all remaining is the variant so is "{language}_{country}_{variant}" country = localeString.substring(languageIndex + 1, countryIndex); String variant = localeString.substring(countryIndex + 1); return new Locale(language, country, variant); } } } private H.Format getContentTypeConfig(Map<String, String> properties) { String s = getProperty(CONTENT_TYPE, properties); if (null == s) { return null; } try { H.Format fmt = H.Format.valueOf(s); if (fmt.isSameTypeWithAny(HTML, TXT)) { return fmt; } throw E.invalidConfiguration("Content type not supported by mailer: %s", fmt); } catch (ConfigurationException e) { throw e; } catch (Exception e) { throw E.invalidConfiguration("Invalid mailer config content type: %s", s); } } private InternetAddress getFromConfig(Map<String, String> properties) { String s = getProperty(FROM, properties); if (null == s) { return null; } try { InternetAddress[] ia = InternetAddress.parse(s); if (null == ia || ia.length == 0) return null; return ia[0]; } catch (AddressException e) { throw E.invalidConfiguration(e, "invalid mailer from address: %s", s); } } @Override protected void releaseResources() { if (null != session) { session = null; } } public String id() { return id; } public String subject() { return subject; } public H.Format contentType() { return contentType; } public InternetAddress from() { return from; } public String username() { return username; } public String password() { return password; } public Locale locale() { return (null != locale) ? locale : app().config().locale(); } public List<InternetAddress> to() { return toList; } public List<InternetAddress> ccList() { return ccList; } public List<InternetAddress> bccList() { return bccList; } public boolean mock() { return mock; } public Session session() { if (null == session) { synchronized (this) { if (null == session) { session = createSession(); } } } return session; } private Session createSession() { Properties p = new Properties(); if (mock()) { p.setProperty("mail.smtp.host", "unknown"); p.setProperty("mail.smtp.port", "465"); } else { p.setProperty("mail.smtp.host", host); p.setProperty("mail.smtp.port", port); } if (null != username && null != password) { if (useTls) { p.put("mail.smtp.starttls.enable", "true"); } else if (useSsl) { p.put("mail.smtp.socketFactory.port", port); p.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); } p.setProperty("mail.smtp.auth", "true"); Authenticator auth = new Authenticator() { //override the getPasswordAuthentication method protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }; return Session.getInstance(p, auth); } else { return Session.getInstance(p); } } }
Java
UTF-8
4,445
3.125
3
[]
no_license
package com.xyw.util.helper; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.HashMap; import java.util.Map; import javax.crypto.Cipher; public class RSAEncrypt { private static Map<Integer, String> keyMap = new HashMap<Integer, String>(); //用于封装随机产生的公钥与私钥 public static final String PublicKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC2voVB1sc3L6Lr7sUIRQ+v/vf8Pl1GtytDONb8mPNRN64Z1Axx39c0gv6Nin1Yz7D28D1NzRdSrdVHcgCBW5zENicv8jZ1LFP+B0+g8iwGRUwu0gNEzP1/KPQPtf2Fx5i/Bf06mg3v1FWd3Q7qQJzo9af/FXg7TEBu1Bp53+yfyQIDAQAB"; public static final String PrivateKey="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALa+hUHWxzcvouvuxQhFD6/+9/w+XUa3K0M41vyY81E3rhnUDHHf1zSC/o2KfVjPsPbwPU3NF1Kt1UdyAIFbnMQ2Jy/yNnUsU/4HT6DyLAZFTC7SA0TM/X8o9A+1/YXHmL8F/TqaDe/UVZ3dDupAnOj1p/8VeDtMQG7UGnnf7J/JAgMBAAECgYBF5PS+y9ECMHwV1QsTMKbhX5mlpoyygVhQq6q+jhlyFOPICSyBWWXMNdX6eN+cWkOLDzPDUA/9lXMfkmDTGSEJ3Q1HnRYAzV7HWVrSBotVuFJ3C8QvT/mmWt6uu/UfKttieoW4+gBtSsafwNPNM1wj8m7yKCq6JvB9uAhxR01gSQJBAOZD3TmAgPCkB9tF9A3uUIJprmgihGYcS75/+/y6Olzug6GOH9LiEec/KzDsjG02Id6H7jQMD4KhwwcIHm379icCQQDLKwhDxoATkydLnWH0bM9RWtFRo9m1SRrbvwt3CwJfjCvuRGDc2Xmu3udu9nM9qiZkfXfl9/GD8J0hObmsVOCPAkEAr+aHyLVxymKD3e3CUiILPpScttAndBmJgy0hwh5BF1zdET0Q8nfgVVbcF7OcUpFXrjcIsJnF/3SzF1wMYthnYQJAawt3RU52+NlVoO+BRul1qiWxl9Q+xteHwTQ9dDFmxLT0CIwahQJIrKxhQAO14E2gAN5ip9YleCD0iScC/xuRXQJAKcCu/1byxNiBb0r/16JDom6cKqpNH1NlIQrQm1DRyQXqu9V+OGWGgC3JSG7yervZu2wQF42FBVHLYqB3MgXZkw=="; public final static String RSA_TYPE = "RSA/ECB/PKCS1Padding"; public static void main(String[] args) throws Exception { //生成公钥和私钥 genKeyPair(); //加密字符串 String message = "df723820"; System.out.println("随机生成的公钥为:" + keyMap.get(0)); System.out.println("随机生成的私钥为:" + keyMap.get(1)); String messageEn = encrypt(message,keyMap.get(0)); System.out.println(message + "\t加密后的字符串为:" + messageEn); String messageDe = decrypt(messageEn,keyMap.get(1)); System.out.println("还原后的字符串为:" + messageDe); String enc=encrypt("xyw",PublicKey); // String enc=encrypt("xyw",keyMap.get(0)); System.out.println("加密后的字符串为:" + enc); // System.out.println("还原后的字符串为:" + decrypt(enc,keyMap.get(1))); System.out.println("还原后的字符串为:" + decrypt(enc,PrivateKey)); } /** * 随机生成密钥对 * @throws NoSuchAlgorithmException */ public static void genKeyPair() throws NoSuchAlgorithmException { // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象 KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); // 初始化密钥对生成器,密钥大小为96-1024位 keyPairGen.initialize(1024,new SecureRandom()); // 生成一个密钥对,保存在keyPair中 KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 得到私钥 RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 得到公钥 String publicKeyString = new String(Base64.encode(publicKey.getEncoded())); // 得到私钥字符串 String privateKeyString = new String(Base64.encode((privateKey.getEncoded()))); // 将公钥和私钥保存到Map keyMap.put(0,publicKeyString); //0表示公钥 keyMap.put(1,privateKeyString); //1表示私钥 } /** * RSA公钥加密 * * @param str * 加密字符串 * @param publicKey * 公钥 * @return 密文 * @throws Exception * 加密过程中的异常信息 */ public static String encrypt(String str, String publicKey ) throws Exception { //base64编码的公钥 byte[] decoded = Base64.decode(publicKey); RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded)); //RSA加密 Cipher cipher = Cipher.getInstance(RSA_TYPE); cipher.init(Cipher.ENCRYPT_MODE, pubKey); String outStr = Base64.encode(cipher.doFinal(str.getBytes("UTF-8"))); return outStr; } /** * RSA私钥解密 * * @param str * 加密字符串 * @param privateKey * 私钥 * @return 铭文 * @throws Exception * 解密过程中的异常信息 */ public static String decrypt(String str, String privateKey) throws Exception { //64位解码加密后的字符串 byte[] inputByte = Base64.decode(str); //base64编码的私钥 byte[] decoded = Base64.decode(privateKey); RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded)); //RSA解密 Cipher cipher = Cipher.getInstance(RSA_TYPE); cipher.init(Cipher.DECRYPT_MODE, priKey); String outStr = new String(cipher.doFinal(inputByte)); return outStr; } }
C++
UTF-8
1,069
2.96875
3
[]
no_license
/************************************************************************* > File Name: B1004.cpp > Author: ji_zhang > Mail: > Created Time: 2017/11/10 1:52:52 ************************************************************************/ #include <algorithm> #include<iostream> #include <string> #include <vector> using namespace std; class student{ private: string name; string stuid; int score; int rank; public: student():score(0),rank(0){}; student(const student&s){ name=s.name; stuid=s.stuid ; score=s.score; rank=s.rank; } ~student(){}; void print(){ cout<<name<<" "<<stuid ; } const int gets() const{ return score; } void reads(){ cin>>name>>stuid>>score; } } ; bool cmp(const student &a,const student &b){ return a.gets()>b.gets(); } int main(){ vector<student> stu; int i; cin>>i; int num=i; student temp; while(i>0){ --i; temp.reads(); stu.push_back(temp); } sort(stu.begin(),stu.end(),cmp); stu[0].print(); cout<<endl; stu[num-1].print(); return 0; }
Python
UTF-8
418
2.90625
3
[]
no_license
# # @lc app=leetcode id=1637 lang=python3 # # [1637] Widest Vertical Area Between Two Points Containing No Points # # @lc code=start class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: temp = [i[0] for i in points] temp.sort() ans = 0 for i in range(1, len(temp)): ans = max(ans, temp[i]-temp[i-1]) return ans # @lc code=end
Shell
UTF-8
1,025
3.953125
4
[ "Apache-2.0" ]
permissive
#!/bin/bash # # Add a newly launched service to the load balancer. set -eou pipefail [ ! $# = 3 ] && { cat <<USAGE >&2 Usage: peekaboo-up <container> <port> <lb id> Adds or updates a node on a load balancer that corresponds to a published port of a named Docker container. USAGE exit 1 } CONTAINER_NAME=${1:-} CONTAINER_PORT=${2:-} LOAD_BALANCER_ID=${3:-} # Locate the published port to add to the load balancer. PORT_PATH=/var/deconst/ports/${CONTAINER_NAME}.${CONTAINER_PORT}.port [ -e ${PORT_PATH} ] || { echo "Port file ${PORT_PATH} does not exist." exit 1 } APP_PORT=$(cat ${PORT_PATH}) [ -z ${APP_PORT} ] && { echo "Unable to find the application port for container ${CONTAINER_NAME}" >&2 exit 1 } echo "Adding ${CONTAINER_NAME}:${APP_PORT} to the load balancer ${LOAD_BALANCER_ID}." export LOAD_BALANCER_ID=${LOAD_BALANCER_ID} export OS_USERNAME=${RACKSPACE_USERNAME} export OS_PASSWORD=${RACKSPACE_APIKEY} export OS_REGION_NAME=${RACKSPACE_REGION} export APP_PORT=${APP_PORT} /opt/bin/peekaboo
C#
UTF-8
16,332
2.546875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MySql.Data.MySqlClient; namespace UNOService { public class DatabaseHandler { private MySqlConnection connection; private string serverIP = "localhost"; private string databaseName = "unogame"; private string userName = "root"; private string password = ""; private int timeOutSeconds = 30; public DatabaseHandler() { string connectionInfo = $"server = {serverIP}; database = {databaseName}; user id = {userName}; password = {password}; connect timeout = {timeOutSeconds};"; connection = new MySqlConnection(connectionInfo); } public String GetPlayerInfo(String column, String username) { try { String info; connection.Open(); MySqlCommand cmd; String sql = "SELECT " + column + " FROM `players` WHERE Username = '" + username + "'"; cmd = new MySqlCommand(sql, connection); MySqlDataReader reader = cmd.ExecuteReader(); info = Convert.ToString(reader[0].ToString()); if (info != null || info != "") return info; } catch (Exception ex) { throw new Exception(ex.Message); } finally { connection.Close(); } return "Invalid"; } public void AddPlayerWon(string username) { try { connection.Open(); string sql = "UPDATE `players` SET GamesWon =`GamesWon`+" + 1 + " WHERE `Username`='" + userName + "';"; MySqlCommand cmd = new MySqlCommand(sql, connection); cmd.ExecuteNonQuery(); } catch (Exception ex) { throw new Exception(ex.Message); } finally { connection.Close(); } } public void AddGamesPlayed(string username) { try { connection.Open(); string sql = "UPDATE `players` SET Gamesplayed =`Gamesplayed`+" + 1 + " WHERE `Username`='" + userName + "';"; MySqlCommand cmd = new MySqlCommand(sql, connection); cmd.ExecuteNonQuery(); } catch (Exception ex) { throw new Exception(ex.Message); } finally { connection.Close(); } } public void InsertGamePlayed(Player p/*, int gameID,string username*/) { try { connection.Open(); string sql = "INSERT INTO `savegame` (`GameID`, `Username`) VALUES (" + p.Game.GameID + ", '" + p.UserName + "');"; MySqlCommand cmd = new MySqlCommand(sql, connection); cmd.ExecuteNonQuery(); } catch (Exception ex) { throw new Exception(ex.Message); } finally { connection.Close(); } } public void InsertPlayer(String username, String password) { try { connection.Open(); MySqlCommand cmd; String sql = "INSERT INTO `players` (`Username`, `Password`, `GamesWon`, `GamesPlayed`) VALUES ('" + username + "', '" + password + "', NULL, NULL);"; cmd = new MySqlCommand(sql, connection); cmd.ExecuteNonQuery(); connection.Close(); } catch (Exception ex) { throw new Exception(ex.Message); } finally { connection.Close(); } } public int FindCard(Card c) { try { connection.Open(); MySqlCommand cmd1; String sql1 = "SELECT CardID FROM `card` WHERE Type = '" + c.Type + "' AND Color = '" + c.Color + "' AND Number =" + c.Number + ";"; cmd1 = new MySqlCommand(sql1, connection); MySqlDataReader reader = cmd1.ExecuteReader(); string cardID = reader.Read().ToString(); return Convert.ToInt32(cardID); } catch (Exception ex) { throw new Exception(ex.Message); } finally { connection.Close(); } } //public Card FindCard(int cardID) //{ // try // { // connection.Open(); // MySqlCommand cmd1; // String sql1 = "SELECT CardID FROM `card` WHERE Type = '" + c.Type + "' AND Color = '" + c.Color + "' AND Number =" + c.Number + ")"; // cmd1 = new MySqlCommand(sql1, connection); // MySqlDataReader reader = cmd1.ExecuteReader(); // string cardID = reader.Read().ToString(); // return null; // } // catch (Exception ex) // { // throw new Exception(ex.Message); // } // finally // { // connection.Close(); // } //} public void InsertMove(int gameID, string username, Game.Move.Types moveType) { try { connection.Open(); MySqlCommand cmd; String sql = "INSERT INTO `move` (`ID`, `Username`, `GameID` , `Type`) VALUES ('', '" + userName + "' ," + gameID + " , '" + moveType + "')"; cmd = new MySqlCommand(sql, connection); cmd.ExecuteNonQuery(); } catch (Exception ex) { throw new Exception(ex.Message); } finally { connection.Close(); } } public void InsertMove(int gameID, string username, int card, Game.Move.Types moveType) { try { connection.Open(); MySqlCommand cmd; String sql = "INSERT INTO `move` (`ID`, `Username`, `GameID` , `Type`, `Card`) VALUES ('', '" + userName + "' ," + gameID + " , '" + moveType + "' , '" + card + "')"; cmd = new MySqlCommand(sql, connection); cmd.ExecuteNonQuery(); } catch (Exception ex) { throw new Exception(ex.Message); } finally { connection.Close(); } } //public void InsertMove(int gameID,string username,int cardID) //{ // try // { // connection.Open(); // MySqlCommand cmd; // String sql = "INSERT INTO `moves` (`ID`, `Username`, `Game ID` , `Card`) VALUES ('', '" + userName + "' ," + gameID + " , " + cardID +")"; // cmd = new MySqlCommand(sql, connection); // cmd.ExecuteNonQuery(); // } // catch (Exception ex) // { // throw new Exception(ex.Message); // } // finally // { // connection.Close(); // } //} public List<Game.Move> GetMoves(int gameID) { try { connection.Open(); MySqlCommand cmd; String sql = "SELECT Username,GameID,Type,Card FROM `move` WHERE GameID = " + gameID + "ORDER BY ID )"; cmd = new MySqlCommand(sql, connection); MySqlDataReader reader = cmd.ExecuteReader(); string row = reader.Read().ToString(); List<Game.Move> moves = new List<Game.Move>(); string username; Card card; Game.Move.Types type; while (reader.Read()) { username = reader[0].ToString(); card = GetCard(Convert.ToInt32(reader[1])); type = (Game.Move.Types)reader[2]; moves.Add(new Game.Move(username, gameID, card, type)); } return moves; } catch (Exception ex) { throw new Exception(ex.Message); } finally { connection.Close(); } } public Card GetCard(int cardID) { try { connection.Open(); MySqlCommand cmd; String sql = "SELECT Type,Color,Number FROM `card` WHERE CardID = " + cardID + ")"; cmd = new MySqlCommand(sql, connection); MySqlDataReader reader = cmd.ExecuteReader(); string row = reader.Read().ToString(); Game.CardType Type; Game.CardColor Color; int Number; Card c = null; while (reader.Read()) { Type = (Game.CardType)reader[0]; Color = (Game.CardColor)reader[1]; Number = Convert.ToInt32(reader[2]); c = new Card(Type, Color, Number); } return c; } catch (Exception ex) { throw new Exception(ex.Message); } finally { connection.Close(); } } public bool CheckLogin(string username, string password) { try { String passwordDB; connection.Open(); MySqlCommand cmd; String sql = "SELECT Password FROM `players` WHERE Username = '" + username + "'"; cmd = new MySqlCommand(sql, connection); MySqlDataReader reader = cmd.ExecuteReader(); reader.Read(); passwordDB = Convert.ToString(reader[0]); if (passwordDB != null || passwordDB != "") { if (passwordDB == password) return true; } return false; } catch (Exception ex) { throw new Exception(ex.Message); } finally { connection.Close(); } } public bool CheckUserName(string username) { try { connection.Open(); MySqlCommand cmd; String sql = "SELECT count(*) FROM `players` where Username = '" + username + "'"; cmd = new MySqlCommand(sql, connection); int numberRows = Convert.ToInt32(cmd.ExecuteScalar()); connection.Close(); if (numberRows == 1) return true; else return false; } catch (Exception ex) { throw new Exception(ex.Message); } finally { connection.Close(); } } public void InsertCard(Card card, int gameID) { try { connection.Open(); MySqlCommand cmd; String sql = "INSERT INTO `deck` (`ID`, `Type`, `Color`, `Number`) VALUES (" + gameID + ", '" + card.Type + "' ,'" + card.Color + "', " + card.Number + ");"; cmd = new MySqlCommand(sql, connection); cmd.ExecuteNonQuery(); } catch (Exception ex) { throw new Exception(ex.Message); } finally { connection.Close(); } } public void InsertPlayers(List<Player> players) { try { connection.Open(); MySqlCommand cmd; foreach (var item in players) { String sql = "INSERT INTO `gameinfo` (`GameID`, `PlayerUserName`) VALUES (" + item.Game.GameID + ", '" + item.UserName + "');"; cmd = new MySqlCommand(sql, connection); cmd.ExecuteNonQuery(); } } catch (Exception ex) { throw new Exception(ex.Message); } finally { connection.Close(); } } public List<Player> GetPlayersOfTheGame(int GameID) { try { connection.Open(); MySqlCommand cmd1; String sql1 = "SELECT PlayerUserName FROM `gameinfo` WHERE GameID = " + GameID + ";"; cmd1 = new MySqlCommand(sql1, connection); MySqlDataReader reader = cmd1.ExecuteReader(); string username = reader.Read().ToString(); List<Player> players = new List<Player>(); if (username != null) { Player p = new Player(username); players.Add(p); } while (reader.Read()) { username = reader.Read().ToString(); if (username != null) { Player p = new Player(username); players.Add(p); } } return players; } catch (Exception ex) { throw new Exception(ex.Message); } finally { connection.Close(); } } public Stack<Card> GetDeck(int gameID) { try { connection.Open(); MySqlCommand cmd1; String sql1 = "SELECT Type,Color,Number FROM `deck` WHERE GameID = " + gameID + "ORDER BY GameID;"; cmd1 = new MySqlCommand(sql1, connection); MySqlDataReader reader = cmd1.ExecuteReader(); string row = reader.Read().ToString(); Stack<Card> cards = new Stack<Card>(); Game.CardType Type; Game.CardColor Color; int Number; while (reader.Read()) { Type = (Game.CardType)reader[0]; Color = (Game.CardColor)reader[1]; Number = Convert.ToInt32(reader[2]); cards.Push(new Card(Type, Color, Number)); } return cards; } catch (Exception ex) { throw new Exception(ex.Message); } finally { connection.Close(); } } public List<int> GetSavedGame(string username) { try { connection.Open(); MySqlCommand cmd; String sql = "SELECT GameID FROM `savegame` WHERE Username = '" + username + "';"; cmd = new MySqlCommand(sql, connection); MySqlDataReader reader = cmd.ExecuteReader(); string row = reader.Read().ToString(); Stack<Card> cards = new Stack<Card>(); List<int> id = new List<int>(); while (reader.Read()) { id.Add(Convert.ToInt32(reader[0])); } return id; } catch (Exception ex) { throw new Exception(ex.Message); } finally { connection.Close(); } } } }
PHP
UTF-8
967
3.453125
3
[]
no_license
<?php require('noPhpredis.php'); /* Basic 'static' usage. Stores all three supported types, retrieves them. */ /* Basic use, store a string to a key value */ print_r(noPhpredis::put('test_string','test')); /* Stores an 1 dimensional assoc. array (or object) as a hash; embedded arrays/objects are serialized */ $example_assoc_array = array('item1'=>'here is my data','item2'=>'here is items 2 data'); print_r(noPhpredis::put($example_assoc_array,'test')); /* Stores 1 dimensional enumerated array as list; embedded array/objects are serialized */ $example_list_data = array(0=>'item 0',1=>'item 1',2=>'item 2'); print_r(noPhpredis::put($example_list_data,'test3')); /* Getting back all data stored using the same method (get) */ echo "\n A redis string \n"; print_r(noPhpredis::get('test')); echo "\n A redis hash \n"; print_r(noPhpredis::get('test2')); echo "\n A redis list \n"; print_r(noPhpredis::get('test3'));
Java
UTF-8
446
2.03125
2
[]
no_license
package com.yfr.model; public class OrdersKey { private Integer orderid; private String username; public Integer getOrderid() { return orderid; } public void setOrderid(Integer orderid) { this.orderid = orderid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username == null ? null : username.trim(); } }
Java
UTF-8
355
3.5625
4
[]
no_license
import java.util.Scanner; public class MajorMinor { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("Enter age:"); int a = s.nextInt(); if(a>= 18) { System.out.println("Major"); } else if(a < 0 ) { System.out.println("Invalid Age"); } else System.out.println("Minor"); } }
Markdown
UTF-8
1,921
3.546875
4
[]
no_license
## Week 1 Questions (optional) *Social network connectivity.* Given a social network containing n members and a log file containing m timestamps at which times pairs of members formed friendships, design an algorithm to determine the earliest time at which all members are connected (i.e., every member is a friend of a friend of a friend ... of a friend). Assume that the log file is sorted by timestamp and that friendship is an equivalence relation. The running time of your algorithm should be mlogn or better and use extra space proportional to n. > set up a counter to record maximum disjoint size so far, > if it exceeds the total member, then we will return the timestamps associated with last pair unioned *Union-find with specific canonical element.* Add a method 𝚏𝚒𝚗𝚍() to the union-find data type so that 𝚏𝚒𝚗𝚍(𝚒) returns the largest element in the connected component containing i. The operations, 𝚞𝚗𝚒𝚘𝚗(), 𝚌𝚘𝚗𝚗𝚎𝚌𝚝𝚎𝚍(), and 𝚏𝚒𝚗𝚍() should all take logarithmic time or better. For example, if one of the connected components is {1,2,6,9}, then the 𝚏𝚒𝚗𝚍() method should return 9 for each of the four elements in the connected components. > always choose the larger element as root in the union method. > find can just return root of the element. >Hint: maintain an extra array to the weighted quick-union data structure that stores for each root >𝚒 the large element in the connected component containing 𝚒. *Successor with delete.* Given a set of N integers S={0,1,...,N−1} and a sequence of requests of the following form: - Remove x from S - Find the successor of x: the smallest y in S such that y≥x. design a data type so that all operations (except construction) should take logarithmic time or better. >Hint: use the modification of the union−find data discussed in the previous question.
Java
UTF-8
10,232
3.15625
3
[]
no_license
import java.util.Scanner; import java.io.*; import java.sql.*; /** *The databaseDriver class contains the main method, which does most of the printing to the terminal and user interface */ public class databaseDriver { /** * The main method prints to the console and gathers information to send to the 3 "action" classes */ public static void main(String args[]) { Delete DeleteStatement = new Delete(); //instantiating Delete class Insert InsertStatement = new Insert(); //instantiating Insert class Update UpdateStatement = new Update(); //instantiating Update class HRIDMax hridMax = new HRIDMax(); //variable used to find the largest current HRID in HumResource Scanner userInput = new Scanner(System.in); //creates a Scanner instance to read information from the console String action; //one of the 3 actions available to the user (INSERT, UPDATE, or DELETE) String tableLoc; //the name of the table in which actions are being taken (FOOD, WATER, or MEDICALCENTER) int HRID = 1009; //starts HRID at the highest starting value + 1 while (true) { //continue looping the prompts until the user types "exit" at an appropriate time System.out.println("What action do you want to take? (INSERT, UPDATE, or DELETE)" + "\nor type \"EXIT\" to exit the program"); //assumes the user inputs one of these values action = userInput.nextLine().toUpperCase(); //grabs the input from the user and stores it if (action.equalsIgnoreCase("EXIT")) { return; //causes the while loop to end, ending the program } System.out.println("In which table do you want to " + action + "? (Food, Water, MedicalCenter)"); tableLoc = userInput.nextLine().toUpperCase(); /** * This is where we generate different SQL insert, update, and delete values based on userInput. * In each case, we need to account for 3 separate individual cases (Food, Water, MedicalCenter). * This accounts for a total of 9 innermost if loops, or 3 sets of 3. */ if (action.equals("INSERT")) { //---------------------------------------------------------------------------------INSERT--------------------------------- String insertValues = ""; insertValues += HRID; //the first value in insertValues is HRID if (tableLoc.equals("MEDICALCENTER")) { int NumBeds; //stores user input int EmergencyRoomCapacity; //stores user input int NumDoctors; //stores user input int NumNurses; //stores user input System.out.println("Insert NumBeds (int):"); NumBeds = userInput.nextInt(); userInput.nextLine(); System.out.println("Insert EmergencyRoomCapacity (int):"); EmergencyRoomCapacity = userInput.nextInt(); userInput.nextLine(); System.out.println("Insert NumDoctors (int):"); NumDoctors = userInput.nextInt(); userInput.nextLine(); System.out.println("Insert NumNurses (int):"); NumNurses = userInput.nextInt(); userInput.nextLine(); //make insertValues a list separated by commas insertValues += ", " + NumBeds + ", " + EmergencyRoomCapacity + ", " + NumDoctors + ", " + NumNurses; } else if (tableLoc.equals("FOOD")) { String FType; //stores user input int FMealsAvailable; //stores user input String FSpecificDesc; //stores user input System.out.println("Insert FType (String):"); FType = userInput.nextLine(); System.out.println("Insert FMealsAvailable (int):"); FMealsAvailable = userInput.nextInt(); userInput.nextLine(); System.out.println("Insert FSpecificDesc (String):"); FSpecificDesc = userInput.nextLine(); //make insertValues a list separated by commas insertValues += ", '" + FType + "', " + FMealsAvailable + ", '" + FSpecificDesc + "'"; } else if (tableLoc.equals("WATER")) { int Num10OzBottlesAvailable; //stores user input int NumHalfLiterBottlesAvailable; //stores user input int Num5GallonJugsAvailable; //stores user input System.out.println("Insert Num10OzBottlesAvailable (int):"); Num10OzBottlesAvailable = userInput.nextInt(); userInput.nextLine(); System.out.println("Insert NumHalfLiterBottlesAvailable (int):"); NumHalfLiterBottlesAvailable = userInput.nextInt(); userInput.nextLine(); System.out.println("Insert Num5GallonJugsAvailable (int):"); Num5GallonJugsAvailable = userInput.nextInt(); //make insertValues a list separated by commas insertValues += ", " + Num10OzBottlesAvailable + ", " + NumHalfLiterBottlesAvailable + ", " + Num5GallonJugsAvailable; } //Call a method in Insert class with the proper parameters InsertStatement.callSQLInsert(tableLoc, insertValues, HRID); } else if (action.equals("UPDATE")) { //---------------------------------------------------------------------------------UPDATE------------------------------- String updateValues = ""; //stores values, used to concatenate all the data into one string System.out.println("Which HRID row in " + tableLoc + " do you want to update?"); HRID = userInput.nextInt(); userInput.nextLine(); //TODO: give the user a table to view of the possible rows to update (??) if (tableLoc.equals("MEDICALCENTER")) { int NumBeds; //number of beds, stores user input int EmergencyRoomCapacity; //capacity, stores user input int NumDoctors; //number of doctors, stores user input int NumNurses; //number of nurses, stores user input //Prompt the user for the necessary values and store their responses System.out.println("Update value for NumBeds (int):"); NumBeds = userInput.nextInt(); userInput.nextLine(); System.out.println("Update value for EmergencyRoomCapacity (int):"); EmergencyRoomCapacity = userInput.nextInt(); userInput.nextLine(); System.out.println("Update value for NumDoctors (int):"); NumDoctors = userInput.nextInt(); userInput.nextLine(); System.out.println("Update value for NumNurses (int):"); NumNurses = userInput.nextInt(); userInput.nextLine(); updateValues = NumBeds + " " + EmergencyRoomCapacity + " " + NumDoctors + " " + NumNurses; } else if (tableLoc.equals("FOOD")) { String FType; //stores user input int FMealsAvailable; //stores user input String FSpecificDesc; //stores user input System.out.println("Update value for FType (String):"); FType = userInput.nextLine(); System.out.println("Update value for FMealsAvailable (int):"); FMealsAvailable = userInput.nextInt(); userInput.nextLine(); System.out.println("Update value for FSpecificDesc (String):"); FSpecificDesc = userInput.nextLine(); updateValues = FType + " " + FMealsAvailable + " " + FSpecificDesc; } else if (tableLoc.equals("WATER")) { int Num10OzBottlesAvailable; int NumHalfLiterBottlesAvailable; int Num5GallonJugsAvailable; System.out.println("Update value for Num10OzBottlesAvailable (int):"); Num10OzBottlesAvailable = userInput.nextInt(); userInput.nextLine(); System.out.println("Update value for NumHalfLiterBottlesAvailable (int):"); NumHalfLiterBottlesAvailable = userInput.nextInt(); userInput.nextLine(); System.out.println("Update value for Num5GallonJugsAvailable (int):"); Num5GallonJugsAvailable = userInput.nextInt(); userInput.nextLine(); updateValues = Num10OzBottlesAvailable + " " + NumHalfLiterBottlesAvailable + " " + Num5GallonJugsAvailable; } //Call a method in Update class with the proper parameters UpdateStatement.callSQLUpdate(tableLoc, updateValues, HRID); } else if (action.equals("DELETE")) { //------------------------------------------------------------------------------DELETE-------------------------------- //show all the HRID available? int deleteHRID; //stores user input for which HRID to delete from the table System.out.println("What HRID do you want to delete?"); deleteHRID = userInput.nextInt(); userInput.nextLine(); //Call a method in Delete class with the proper parameters DeleteStatement.callSQLDelete(tableLoc, deleteHRID); } HRID++; } } }
Java
UTF-8
304
2.171875
2
[]
no_license
package com.github.justinespinosa.textmode.curses.ui.event; public class UiInputEvent extends UiEvent { private TerminalInputEvent original; public UiInputEvent(TerminalInputEvent e) { super(e.getSource()); original = e; } public TerminalInputEvent getOriginalEvent(){ return original; } }
Java
UTF-8
713
2.59375
3
[]
no_license
package org.tz.pos.Lagerverwaltung; public class Lieferant { private int lieferantenNr; private String lieferantenName; public Lieferant(int lieferantenNr, String lieferantenName) { this.lieferantenNr = lieferantenNr; this.lieferantenName = lieferantenName; } public Lieferant() { } public int getLieferantenNr() { return lieferantenNr; } public void setLieferantenNr(int lieferantenNr) { this.lieferantenNr = lieferantenNr; } public String getLieferantenName() { return lieferantenName; } public void setLieferantenName(String lieferantenName) { this.lieferantenName = lieferantenName; } public String toString() { return Integer.toString(getLieferantenNr()); } }
Java
UTF-8
1,613
2.25
2
[]
no_license
package com.Group2.InterestCalc.Controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.Group2.InterestCalc.Repositary.InterestRateRepo; import com.Group2.InterestCalc.Resources.InterestRates; @RestController @RequestMapping("/admin") @CrossOrigin(origins = "http://localhost:4200") public class InterestUpdateController { @Autowired InterestRateRepo interestRateRepo; @PostMapping("/interestRates") public ResponseEntity<InterestRates> postIntersetRates(@RequestBody InterestRates intersetRates ) { try { return ResponseEntity.created(null).body(interestRateRepo.saveAndFlush(intersetRates)); }catch (Exception e) { System.out.println(e); return ResponseEntity.badRequest().eTag("Failed to create Interest Rates!!").body(null); } } @PutMapping("/updateInterestRates") public ResponseEntity<InterestRates> updateInterstRates(@RequestBody InterestRates interestRates){ try { return ResponseEntity.ok(interestRateRepo.save(interestRates)); } catch (IllegalArgumentException e) { // TODO: handle exception return ResponseEntity.badRequest().eTag("Failed to update Interest Rates!!").body(null); } } }
C
UTF-8
227
2.5625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include "bulacio.h" int main() { int n1, n2; printf("%d", getIntRange("Ingrese una nota: ", "ERROR. Ingrese una nota valida: ", 0, 10, 3, -1)); return 0; }
Python
UTF-8
1,915
4.125
4
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- # author:ShidongDu time:2020/4/4 ''' 给你一个字符串 s 和一个整数 k 。请你用 s 字符串中 所有字符 构造 k 个非空 回文串 。 如果你可以用 s 中所有字符构造 k 个回文字符串,那么请你返回 True ,否则返回 False 。 示例 1: 输入:s = "annabelle", k = 2 输出:true 解释:可以用 s 中所有字符构造 2 个回文字符串。 一些可行的构造方案包括:"anna" + "elble","anbna" + "elle","anellena" + "b" 示例 2: 输入:s = "leetcode", k = 3 输出:false 解释:无法用 s 中所有字符构造 3 个回文串。 示例 3: 输入:s = "true", k = 4 输出:true 解释:唯一可行的方案是让 s 中每个字符单独构成一个字符串。 示例 4: 输入:s = "yzyzyzyzyzyzyzy", k = 2 输出:true 解释:你只需要将所有的 z 放在一个字符串中,所有的 y 放在另一个字符串中。那么两个字符串都是回文串。 示例 5: 输入:s = "cr", k = 7 输出:false 解释:我们没有足够的字符去构造 7 个回文串。 提示: 1 <= s.length <= 10^5 s 中所有字符都是小写英文字母。 1 <= k <= 10^5 ''' class Solution: def canConstruct(self, s: str, k: int) -> bool: # 统计每个字符出现的次数 # 单数个字符数量不得超过k个 if len(s) < k: return False char_dict = {} for char in s: if char in char_dict: char_dict[char] += 1 else: char_dict[char] = 1 tmp = 0 for key in char_dict.keys(): if char_dict[key] % 2 != 0: #奇数 tmp += 1 return True if tmp<=k else False if __name__ == '__main__': solution = Solution() s = "yzyzyzyzyzyzyzy" k = 2 res = solution.canConstruct(s, k) print(res)
PHP
UTF-8
6,168
2.59375
3
[]
no_license
<?php class PostsController extends AppController { public function execute() { /* * inherits from base controller: read-only * $this->request; * $this->request_parts; * $this->page; * $this->current_theme_pages_dir; * $this->current_theme_templates_dir; */ /* * inherits from base controller: read-write */ $this->templates_dir; $this->pages_dir = 'posts'; if($this->page == 'new') { $page_data = array( 'page_title' => 'Create new post', 'page_keywords' => '', 'page_description' => '', 'robots_value' => 'all', 'open_graph_data' => array( 'url' => SITE_URL. '/'. $this->request, 'title' => 'Create new post', 'description' => '', 'image-url' => '', 'content-type' => 'website', )); $this->_display('create.php', $page_data, $container_template=''); } //e.g http://localhost/sites/naija-so/posts/11/ else if(is_numeric($this->page)) { $post_id = $this->page; $post = PostModel::get_post_instance($post_id); $post_title = $post->get('title'); $post_content = $post->get('content'); $tags = $post->get_tags(); $keywords = ''; for($i=0, $len=count($tags); $i < $len; $i++): $tag = TagModel::get_tag_instance($tags[$i]); $keywords .= $tag->get('name'). ','; endfor; $endpoint = get_uri_end_point( array('ignore_query_string'=>true) ); if( $endpoint == 'edit' ) { $slug_from_url = 'edit'; $page_file = 'edit-post.php'; } else { update_post_view($post_id); $slug_from_url = $endpoint; $page_file = 'view.php'; } $page_data = array( 'page_title' => sanitize_html_attribute( $post_title ), 'page_keywords' => $keywords, 'page_description' => sanitize_html_attribute( $post_content ), 'robots_value' => 'all', 'post_id' => $post_id, 'post' => $post, 'slug_from_url' => $slug_from_url, 'open_graph_data' => array( 'url' => get_post_url($post_id), 'title' => sanitize_html_attribute( $post_title ), 'description' => sanitize_html_attribute( $post_content ), 'image-url' => get_post_image_url($post_id), 'content-type' => 'article', )); $this->_display($page_file, $page_data, $container_template=''); } //else if ( $this->page == 'forum' || $this->page == 'category' ) else { $part = ( $this->page == 'forum' || $this->page == 'category' || $this->page == 'tagged' || $this->page == 'author') ? urldecode( $this->request_parts[2] ) : ''; $limit = 20; $order_data = array('date_created'=>'DESC'); $image_url = SITE_URL. '/logo-large.png'; switch($this->page) { case 'forum' : $forum_id = (is_integer($part) || is_numeric($part)) ? $part : get_forum_id($part); $forum = ForumModel::get_forum_instance( $forum_id ); //$post_ids = $forum->get_posts(array('parent_id'=>0), $order_data, $limit); $categories = $forum->get_categories(); $page_title = $forum->get('name'). ' forum posts'; $page_description = 'View '. $forum->get('name'). ' forum posts'; $page_keywords = ''; for($i=0, $len=count($categories); $i < $len; $i++): $category = CategoryModel::get_category_instance($categories[$i]); $page_keywords .= $category->get('name'). ','; endfor; break; case 'category' : $category_id = (is_integer($part) || is_numeric($part)) ? $part : get_category_id($part); $category = CategoryModel::get_category_instance( $category_id ); //$post_ids = $category->get_posts(array('parent_id'=>0), $order_data, $limit); $page_title = $category->get('name'). ' category posts'; $page_description = 'View '. $category->get('name'). ' category posts'; $page_keywords = ''; break; case 'tagged': $tag_id = (is_integer($part) || is_numeric($part)) ? $part : get_tag_id($part); $tag = TagModel::get_tag_instance( $tag_id ); //$post_ids = $tag->get_posts(array('parent_id'=>0), $order_data, $limit); $page_title = $tag->get('name'). ' tag posts'; $page_description = 'View posts tagged '. $tag->get('name'); $page_keywords = ''; break; case 'author' : $author_id = get_user_id($part); $author = UserModel::get_user_instance( $author_id ); //$post_ids = get_user_posts($author_id, array('parent_id'=>0), $order_data, $limit); $page_title = 'Posts by '. $author->get('username'); $page_description = 'View posts created by '. $author->get('username'); $page_keywords = $author->get('username'). ''; break; default : //index page //$post_ids = PostModel::get_posts( true, array('parent_id'=>0), $order_data, $limit ); //get only top-level posts $page_title = 'Recent posts'; $page_description = ''; $page_keywords = ''; } $page_data = array( 'page_title' => $page_title, 'page_keywords' => $page_keywords, 'page_description' => $page_description, 'robots_value' => 'all', //'posts' => $post_ids, 'open_graph_data' => array( 'url' => SITE_URL. '/'. $this->request, 'title' => $page_title, 'description' => $page_description, 'image-url' => $image_url, 'content-type' => 'website', )); $this->_display('index.php', $page_data, $container_template=''); } /* else { $page_data = array( 'page_title' => '', 'page_keywords' => '', 'page_description' => '', 'robots_value' => 'all', 'posts' => PostModel::get_posts( true, array('parent_id'=>0), array('date_created'=>'DESC'), 20 ), //get only top-level posts 'open_graph_data' => array( 'url' => generate_url(array('controller'=>'')), 'title' => '', 'description' => '', 'image-url' => '', 'content-type' => 'website', )); $this->_display('index.php', $page_data, $container_template=''); } */ } }
C
UTF-8
7,386
2.546875
3
[ "BSD-2-Clause" ]
permissive
/* * Copyright (c) 2016-2018 Mindaugas Rasiukevicius <rmind at noxt eu> * All rights reserved. * * Use is subject to license terms, as specified in the LICENSE file. */ /* * Epoch-based reclamation (EBR). Reference: * * K. Fraser, Practical lock-freedom, * Technical Report UCAM-CL-TR-579, February 2004 * https://www.cl.cam.ac.uk/techreports/UCAM-CL-TR-579.pdf * * Summary: * * Any workers (threads or processes) actively referencing (accessing) * the globally visible objects must do that in the critical path covered * using the dedicated enter/exit functions. The grace period is * determined using "epochs" -- implemented as a global counter (and, * for example, a dedicated G/C list for each epoch). Objects in the * current global epoch can be staged for reclamation (garbage collection). * Then, the objects in the target epoch can be reclaimed after two * successful increments of the global epoch. Only three epochs are * needed (e, e-1 and e-2), therefore we use clock arithmetics. * * See the comments in the ebr_sync() function for detailed explanation. */ #include <sys/queue.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <time.h> #include <errno.h> #include <pthread.h> #include <sched.h> #include "ebr.h" #include "utils.h" #define ACTIVE_FLAG (0x80000000U) typedef struct ebr_tls { /* * - A local epoch counter for each thread. * - The epoch counter may have the "active" flag set. * - Thread list entry (pointer). */ unsigned local_epoch; LIST_ENTRY(ebr_tls) entry; } ebr_tls_t; struct ebr { /* * - There is a global epoch counter which can be 0, 1 or 2. * - TLS with a list of the registered threads. */ unsigned global_epoch; pthread_key_t tls_key; pthread_mutex_t lock; LIST_HEAD(, ebr_tls) list; }; ebr_t * ebr_create(void) { ebr_t *ebr; int ret; ret = posix_memalign((void **)&ebr, CACHE_LINE_SIZE, sizeof(ebr_t)); if (ret != 0) { errno = ret; return NULL; } memset(ebr, 0, sizeof(ebr_t)); if (pthread_key_create(&ebr->tls_key, free) != 0) { free(ebr); return NULL; } pthread_mutex_init(&ebr->lock, NULL); return ebr; } void ebr_destroy(ebr_t *ebr) { pthread_key_delete(ebr->tls_key); pthread_mutex_destroy(&ebr->lock); free(ebr); } /* * ebr_register: register the current worker (thread/process) for EBR. * * => Returns 0 on success and errno on failure. */ int ebr_register(ebr_t *ebr) { ebr_tls_t *t; t = pthread_getspecific(ebr->tls_key); if (__predict_false(t == NULL)) { int ret; ret = posix_memalign((void **)&t, CACHE_LINE_SIZE, sizeof(ebr_tls_t)); if (ret != 0) { errno = ret; return -1; } pthread_setspecific(ebr->tls_key, t); } memset(t, 0, sizeof(ebr_tls_t)); pthread_mutex_lock(&ebr->lock); LIST_INSERT_HEAD(&ebr->list, t, entry); pthread_mutex_unlock(&ebr->lock); return 0; } void ebr_unregister(ebr_t *ebr) { ebr_tls_t *t; t = pthread_getspecific(ebr->tls_key); if (t == NULL) { return; } pthread_setspecific(ebr->tls_key, NULL); pthread_mutex_lock(&ebr->lock); LIST_REMOVE(t, entry); pthread_mutex_unlock(&ebr->lock); free(t); } /* * ebr_enter: mark the entrance to the critical path. */ void ebr_enter(ebr_t *ebr) { ebr_tls_t *t; unsigned epoch; t = pthread_getspecific(ebr->tls_key); ASSERT(t != NULL); /* * Set the "active" flag and set the local epoch to global * epoch (i.e. observe the global epoch). Ensure that the * epoch is observed before any loads in the critical path. */ epoch = ebr->global_epoch | ACTIVE_FLAG; atomic_store_explicit(&t->local_epoch, epoch, memory_order_relaxed); atomic_thread_fence(memory_order_seq_cst); } /* * ebr_exit: mark the exit of the critical path. */ void ebr_exit(ebr_t *ebr) { ebr_tls_t *t; t = pthread_getspecific(ebr->tls_key); ASSERT(t != NULL); /* * Clear the "active" flag. Must ensure that any stores in * the critical path reach global visibility before that. */ ASSERT(t->local_epoch & ACTIVE_FLAG); atomic_thread_fence(memory_order_seq_cst); atomic_store_explicit(&t->local_epoch, 0, memory_order_relaxed); } /* * ebr_sync: attempt to synchronise and announce a new epoch. * * => Synchronisation points must be serialised. * => Return true if a new epoch was announced. * => Return the epoch ready for reclamation. */ bool ebr_sync(ebr_t *ebr, unsigned *gc_epoch) { unsigned epoch; ebr_tls_t *t; /* * Ensure that any loads or stores on the writer side reach * the global visibility. We want to allow the callers to * assume that the ebr_sync() call serves as a full barrier. */ epoch = atomic_load_explicit(&ebr->global_epoch, memory_order_relaxed); atomic_thread_fence(memory_order_seq_cst); /* * Check whether all active workers observed the global epoch. */ LIST_FOREACH(t, &ebr->list, entry) { unsigned local_epoch; bool active; local_epoch = atomic_load_explicit(&t->local_epoch, memory_order_relaxed); active = (local_epoch & ACTIVE_FLAG) != 0; if (active && (local_epoch != (epoch | ACTIVE_FLAG))) { /* No, not ready. */ *gc_epoch = ebr_gc_epoch(ebr); return false; } } /* Yes: increment and announce a new global epoch. */ atomic_store_explicit(&ebr->global_epoch, (epoch + 1) % 3, memory_order_relaxed); /* * Let the new global epoch be 'e'. At this point: * * => Active workers: might still be running in the critical path * in the e-1 epoch or might be already entering a new critical * path and observing the new epoch e. * * => Inactive workers: might become active by entering a critical * path before or after the global epoch counter was incremented, * observing either e-1 or e. * * => Note that the active workers cannot have a stale observation * of the e-2 epoch at this point (there is no ABA problem using * the clock arithmetics). * * => Therefore, there can be no workers still running the critical * path in the e-2 epoch. This is the epoch ready for G/C. */ *gc_epoch = ebr_gc_epoch(ebr); return true; } /* * ebr_staging_epoch: return the epoch where objects can be staged * for reclamation. */ unsigned ebr_staging_epoch(ebr_t *ebr) { /* The current epoch. */ return ebr->global_epoch; } /* * ebr_gc_epoch: return the epoch where objects are ready to be * reclaimed i.e. it is guaranteed to be safe to destroy them. */ unsigned ebr_gc_epoch(ebr_t *ebr) { /* * Since we use only 3 epochs, e-2 is just the next global * epoch with clock arithmetics. */ return (ebr->global_epoch + 1) % 3; } void ebr_full_sync(ebr_t *ebr, unsigned msec_retry) { const struct timespec dtime = { 0, msec_retry * 1000 * 1000 }; const unsigned target_epoch = ebr_staging_epoch(ebr); unsigned epoch, count = SPINLOCK_BACKOFF_MIN; wait: while (!ebr_sync(ebr, &epoch)) { if (count < SPINLOCK_BACKOFF_MAX) { SPINLOCK_BACKOFF(count); } else if (msec_retry) { (void)nanosleep(&dtime, NULL); } else { sched_yield(); } } if (target_epoch != epoch) { goto wait; } } /* * ebr_incrit_p: return true if the current worker is in the critical path, * i.e. called ebr_enter(); otherwise, return false. * * Note: this routine should generally only be used for diagnostic asserts. */ bool ebr_incrit_p(ebr_t *ebr) { ebr_tls_t *t; t = pthread_getspecific(ebr->tls_key); ASSERT(t != NULL); return (t->local_epoch & ACTIVE_FLAG) != 0; }
Java
GB18030
375
1.570313
2
[]
no_license
package com.lzairport.ais.service.telex; import javax.ejb.Remote; import com.lzairport.ais.models.telex.AllowType; import com.lzairport.ais.service.IService; /** * 籨Serviceӿ * @author ZhangYu * @version 0.9a 29/04/15 * @since JDK 1.6 * */ @Remote public interface IAllowTypeService extends IService<Integer, AllowType> { }
Java
UTF-8
4,176
2.53125
3
[]
no_license
package ca.concordia.lanterns.tileplacement.impl; import java.util.Arrays; import java.util.List; import ca.concordia.lanterns.controllers.GameController; import ca.concordia.lanterns.exchange.impl.helper.DedicationThreat; import ca.concordia.lanternsentities.DedicationTokenWrapper; import ca.concordia.lanternsentities.Game; import ca.concordia.lanternsentities.LakeTile; import ca.concordia.lanternsentities.Player; import ca.concordia.lanternsentities.TileSide; import ca.concordia.lanternsentities.ai.TilePlayBehavior; import ca.concordia.lanternsentities.enums.Colour; import ca.concordia.lanternsentities.enums.DedicationType; import ca.concordia.lanternsentities.helper.MatrixOrganizer; import ca.concordia.lanternsentities.helper.MatrixOrganizer.Direction; public class WorstTile implements TilePlayBehavior { private GameController controller = new GameController(); @Override public void placeTile(Game game, Player currentPlayer) { List<LakeTile> playerTiles = currentPlayer.getTiles(); if(playerTiles.isEmpty()) { return; } // sort the game dedications DedicationType[] sortedGameDedications = DedicationTokenWrapper.sortDedications (game.getDedications()); int nextPlayerIndex = game.getCurrentTurnPlayer() + 1; Player[] players = game.getPlayers(); int i = 0 ; while(i != players.length - 1){ // Ensures clockwise movement and appropriate indexing nextPlayerIndex = nextPlayerIndex % players.length ; for (DedicationType dedicationType: sortedGameDedications){ DedicationThreat threat = DedicationThreat.getThreat(dedicationType, players[nextPlayerIndex], game); if (threat != null){ boolean isStopped = stopThreat(game, threat, players[nextPlayerIndex].getId()); // We can only stop one dedication by making one exchange. if (isStopped) { return; } } } ++nextPlayerIndex; ++i; } // Assign the first available lake tile to the first available place in lake LakeTile[][] lake = game.getLake(); for (int k = 0; k != lake.length; ++k) { for (int j = 0; j != lake[k].length; ++j) { if (lake[k][j] != null){ TileSide[] side = lake[k][j].getSides(); for (int p = 0; p != side.length; ++p) { if (side[p].getAdjacent() == null) { controller.placeLakeTile(game, currentPlayer.getId(), 0, lake[k][j].getId(), p, 0); return; } } } } } } private boolean stopThreat(Game game, DedicationThreat threat, int playerID){ Player player = game.getPlayer(playerID); Colour absentColour = threat.getAbsentColour(); if (player == null){ throw new IllegalArgumentException("The game do not have a player with ID: " + playerID); } List<LakeTile> playerTiles = player.getTiles(); int maxFoundColourCount = 0; int selectedPlayerTileIndex = -1; int selectedPlayerTileSideIndex = -1; for (int i = 0; i != playerTiles.size(); ++i) { int foundColourCount = 0; int playerTileSideIndex = 0; TileSide[] side = playerTiles.get(i).getSides(); for (int j = 0; j != side.length; ++j) { if (side[j].getColour() == absentColour) { ++foundColourCount; playerTileSideIndex = j; } } if (foundColourCount > maxFoundColourCount){ maxFoundColourCount = foundColourCount; selectedPlayerTileIndex = i; selectedPlayerTileSideIndex = playerTileSideIndex; } } if (selectedPlayerTileIndex == -1){ return false; } List<MatrixOrganizer.Direction> directions = Arrays.asList(MatrixOrganizer.Direction.values()); LakeTile[][] lake = game.getLake(); Direction oppDirection = MatrixOrganizer.getOppositeTileSideIndex(directions.get(playerID)); int lakeTileSideIndex = directions.indexOf(oppDirection); for (int i = 0; i != lake.length; ++i) { for (int j = 0; j != lake[i].length; ++j) { if (lake[i][j] != null) { if (lake[i][j].getSides()[lakeTileSideIndex].getAdjacent() == null) { controller.placeLakeTile(game, playerID, selectedPlayerTileIndex, lake[i][j].getId(), lakeTileSideIndex, selectedPlayerTileSideIndex); return true; } } } } return false; } }
Java
UTF-8
12,323
2.984375
3
[]
no_license
package com.hackthon.samurai.util; import java.sql.Date; import java.sql.Timestamp; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; public class DateUtil { public static final String YYYYMMDD_SLASH = "yyyy/MM/dd"; public static final String YYYYMMDD_HYPEN = "yyyy-MM-dd"; public static final String YYYYMMDD_BLANK = "yyyyMMdd"; public static final String YYYYMMDD_UNDERSCORE = "yyyy_MM_dd"; public static final String YYYYMMMDD_SLASH = "yyyy/MMM/dd"; public static final String YYYYMMMDD_HYPEN = "yyyy-MMM-dd"; public static final String YYYYMMMDD_BLANK = "yyyyMMMdd"; public static final String YYYYMMMDD_UNDERSCORE = "yyyy_MM_dd"; public static final String DDMMYYYY_SLASH = "dd/MM/yyyy"; public static final String DDMMYYYY_HYPEN = "dd-MM-yyyy"; public static final String DDMMYYYY_BLANK = "ddMMyyyy"; public static final String DDMMYYYY_UNDERSCORE = "dd_MM_yyyy"; public static final String DDMMMYYYY_SLASH = "dd/MMM/yyyy"; public static final String DDMMMMYYYY_HYPEN = "dd-MMM-yyyy"; public static final String DDMMMYYYY_BLANK = "ddMMMyyyy"; public static final String DDMMMYYYY_UNDERSCORE = "dd_MMM_yyyy"; public static final String MMDDYYYY_SLASH = "MM/dd/yyyy"; public static final String MMDDYYYY_HYPEN = "MM-dd-yyyy"; public static final String MMDDYYYY_BLANK = "MMddyyyy"; public static final String MMDDYYYY_UNDERSCORE = "MM_dd_yyyy"; public static final String MMMDDYYYY_SLASH = "MMM/dd/yyyy"; public static final String MMMDDYYYY_HYPEN = "MMM-dd-yyyy"; public static final String MMMDDYYYY_BLANK = "MMMddyyyy"; public static final String MMMDDYYYY_UNDERSCORE = "MMM_dd_yyyy"; public static final String HHMMSS = "HHmmss"; public static final String HHMMSS_COLON = "HH:mm:ss"; /** * All minutes have this many milliseconds except the last minute of the day * on a day defined with a leap second. */ public static final long MILLISECS_PER_MINUTE = 60 * 1000; /** * Number of milliseconds per hour, except when a leap second is inserted. */ public static final long MILLISECS_PER_HOUR = 60 * MILLISECS_PER_MINUTE; /** * Number of leap seconds per day expect on <BR/> * 1. days when a leap second has been inserted, e.g. 1999 JAN 1. <BR/> * 2. Daylight-savings "spring forward" or "fall back" days. */ protected static final long MILLISECS_PER_DAY = 24 * MILLISECS_PER_HOUR; /** * Method to get the time stamp * * @param date * @return */ public static Timestamp getTimeStamp(Date date) { SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String strDate = dt.format(date); Timestamp t = null; t = Timestamp.valueOf(strDate.replace("/", "-")); return t; } /** * * This Method is to get the current date and time in specified format ( eg * :"yyyy-MM-dd_HHmmss") * * @param format * @return */ public static String getCurrentDateTime(String format) { DateFormat df = new SimpleDateFormat(format); String curDateTime = df.format(new java.util.Date()); return curDateTime; } /** * * This Method is to check the string date and date are equal * * @param strDate * @param date * @return */ public static boolean checkStrDateAndDate(String strDate, java.util.Date date) { boolean result = false; if (strDate.equals(getStringDateFromDate(date, YYYYMMDD_SLASH))) { result = true; } return result; } /** * * This Method is to get the Date as YMD String * * @param date * @return */ public static String getStringDateFromDate(java.util.Date date, String dateFormat) { SimpleDateFormat dt = new SimpleDateFormat(dateFormat); String strDate = dt.format(date); return strDate; } /** * * This Method is to getTodayWithoutSlash * * @return */ public static String getTodayWithoutSlash() { java.util.Date today = Calendar.getInstance().getTime(); String dat = "" + today.getDate(); dat = dat.length() == 1 ? "0" + dat : dat; String mon = "" + (today.getMonth() + 1); mon = mon.length() == 1 ? "0" + mon : mon; String year = "" + (1900 + today.getYear()); year = year.length() == 1 ? "0" + year : year; String to = dat + mon + year; String to1 = year + "" + mon + "" + dat; return to1; } /** * Method to get the time stamp * * @param date * @return */ public static Timestamp getTimeStamp() { SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String strDate = dt.format(new java.util.Date()); Timestamp t = null; t = Timestamp.valueOf(strDate.replace("/", "-")); return t; } /** * * This Method is to getPreviousFridayDateFromDate * * @param date * @return */ public static java.util.Date getPreviousFridayDateFromDate(java.util.Date date) { Calendar c = Calendar.getInstance(); c.setTime(date); c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH) - (c.get(Calendar.DAY_OF_WEEK) + 1)); return c.getTime(); } /** * * This Method is to check for Friday and Future * * @param str_date * @return */ public static boolean isFridayAndNotFuture(String str_date) throws Exception { boolean result = false; java.util.Date date = null; if (str_date != null && !str_date.trim().equals("")) { date = getDateFromString(str_date, YYYYMMDD_SLASH); if (isFuture(date)) { new Exception("Date Should not be today or future day"); result = false; } else { Calendar c = Calendar.getInstance(); c.setTime(date); if (c.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) { result = true; } else { new Exception("Entered Date is not Friday"); } } } else { new Exception("Date Should not be blank"); } return result; } /** * * This Method is to * * @param str_date * @return */ public static java.util.Date getPreviousFridayDateFromString(String str_date, String dateFormat) throws Exception { java.util.Date date; if (str_date != null && !str_date.trim().equals("")) { date = getDateFromString(str_date, dateFormat); } else { date = getDateFromString(getStringDateFromDate(new java.util.Date(), dateFormat), dateFormat); } Calendar c = Calendar.getInstance(); c.setTime(date); c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH) - (c.get(Calendar.DAY_OF_WEEK) + 1)); return c.getTime(); } /** * * This Method is to * * @param str_date * @return */ public static java.util.Date[] getPreviousFiveFridayDate(String dateFormat) throws Exception { java.util.Date[] dates = new java.util.Date[5]; dates[0] = getPreviousFridayDateFromString(null, dateFormat); for (int i = 1; i < 5; i++) { dates[i] = getDateFromString(getStringDateFromDate(getPreviousFridayDateFromDate(dates[i - 1]), dateFormat), dateFormat); ; } return dates; } /** * * This Method is to get the Previous Fifth Friday Date * * @param str_date * @return */ public static java.util.Date getPreviousFifthFridayDate(String dateFormat) throws Exception { java.util.Date[] dates; dates = getPreviousFiveFridayDate(dateFormat); return dates[4]; } /** * * This Method is to get next Friday Date * * @param str_date * @return */ public static java.util.Date getNextFridayDate(String str_date, String dateFormat) throws Exception { java.util.Date date; if (str_date != null && !str_date.trim().equals("")) { date = getDateFromString(str_date, dateFormat); } else { date = getDateFromString(getStringDateFromDate(new java.util.Date(), dateFormat), dateFormat); } Calendar c = Calendar.getInstance(); c.setTime(date); int toAdd = Calendar.FRIDAY - c.get(Calendar.DAY_OF_WEEK); if (toAdd < 0) { toAdd = Calendar.FRIDAY; } else if (toAdd == 0) { toAdd = Calendar.FRIDAY + 1; } c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH) + toAdd); if (isFuture(c.getTime())) { new Exception("Next Friday should not be today or a future date"); return getPreviousFridayDateFromDate(c.getTime()); } return c.getTime(); } /** * * This Method is to check the given date is future or not * * @param date * @return */ public static boolean isFuture(java.util.Date date) { boolean result = false; Calendar c = Calendar.getInstance(); c.setTime(date); Calendar d = Calendar.getInstance(); if ((c.get(Calendar.MONTH) == d.get(Calendar.MONTH)) && (c.get(Calendar.DAY_OF_MONTH) == d.get(Calendar.DAY_OF_MONTH))) { result = true; } else if (c.getTimeInMillis() > d.getTimeInMillis()) { result = true; } return result; } /** * * This Method is to get date object from date String * * @param str_date, * format (eg: "yyyy/MM/dd") * @return */ public static java.util.Date getDateFromString(String str_date, String dateFormat) throws Exception { DateFormat formatter; java.util.Date date = null; formatter = new SimpleDateFormat(dateFormat); try { date = (java.util.Date) formatter.parse(str_date); } catch (Exception e) { new Exception(e.getMessage()); } return date; } public static long diffDayPeriods(java.util.Date oldDate) { Calendar c = Calendar.getInstance(); c.setTime(oldDate); Calendar d = Calendar.getInstance(); long diff = d.getTimeInMillis() - c.getTimeInMillis(); // System.out.println("diff : "+ diff); // System.out.println("diff/MILLISECS_PER_DAY : "+ // diff/MILLISECS_PER_DAY); // return diff/MILLISECS_PER_DAY; return diff / MILLISECS_PER_MINUTE; } public static long diffInDays(java.util.Date oldDate) { Calendar c = Calendar.getInstance(); c.setTime(oldDate); Calendar d = Calendar.getInstance(); long diff = d.getTimeInMillis() - c.getTimeInMillis(); // System.out.println("diff : "+ diff); // System.out.println("diff/MILLISECS_PER_DAY : "+ // diff/MILLISECS_PER_DAY); return diff / MILLISECS_PER_DAY; // return diff/MILLISECS_PER_MINUTE; } public static long diffInHrs(java.util.Date oldDate) { Calendar c = Calendar.getInstance(); c.setTime(oldDate); Calendar d = Calendar.getInstance(); long diff = d.getTimeInMillis() - c.getTimeInMillis(); // System.out.println("diff : "+ diff); // System.out.println("diff/MILLISECS_PER_DAY : "+ // diff/MILLISECS_PER_DAY); return diff / MILLISECS_PER_HOUR; // return diff/MILLISECS_PER_MINUTE; } public static boolean validateWakeupTime(String wakeupTime) { boolean result = false; Calendar c = Calendar.getInstance(); String[] wakeupTime1 = wakeupTime.split(":"); int hr = Integer.parseInt(wakeupTime1[0]); int min = Integer.parseInt(wakeupTime1[1]); wakeupTime = hr + ":" + min; String currentWakeupTime = c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE); // System.out.println("Checking wakeuptime : " + wakeupTime +" current // time : "+currentWakeupTime); // System.out.println(currentWakeupTime); if (wakeupTime.equalsIgnoreCase(currentWakeupTime)) { result = true; } return result; } /** * * This Method is to getStringDate * * @param date * @param format * @return */ public static String getPtdmStringDate(String date) { String rStringDate = null; SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); if (date != null && date.length() > 0) { try { java.util.Date rdate = (java.util.Date) formatter.parse(date); rStringDate = getStringDateFromDate(rdate, "MM/dd/yyyy" + " " + "HH:mm:ss"); // System.out.println("String date is: " + // dynamicFormat(rdate)); } catch (ParseException e) { e.printStackTrace(); } } return rStringDate; } /** * @param args */ public static void main(String[] args) { System.out.println(Calendar.getInstance().getTime().getTime()); System.out.println(Calendar.getInstance().getTime().getTime()); System.out.println(validateWakeupTime("20:25")); System.out.println(" getStringDateFromDate ::::: " + getPtdmStringDate("20121213130506")); Calendar c = Calendar.getInstance(); c.add(Calendar.HOUR, -3); System.out.println(diffDayPeriods(c.getTime())); try { System.out.println(" getNextFridayDate ::::: " + getNextFridayDate(null, YYYYMMMDD_SLASH)); } catch (Exception e) { e.printStackTrace(); } } }
SQL
UTF-8
1,574
3.71875
4
[]
no_license
drop database HCA; create database HCA; use HCA; create table users ( ID int(10) NOT NULL AUTO_INCREMENT, USERNAME varchar(50) NOT NULL, EMAIL varchar(50) NOT NULL, PASSWORD varchar(50) NOT NULL, ISADMIN varchar(1) NOT NULL DEFAULT 0, createdAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, updatedAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, UNIQUE UQ_USER_1 (USERNAME), PRIMARY KEY(ID) ); INSERT INTO users (ID, USERNAME, EMAIL, PASSWORD, ISADMIN) VALUES (1, 'Michelle', 'michelle@mail.com', 'password', '1'); INSERT INTO users (ID, USERNAME, EMAIL, PASSWORD, ISADMIN) VALUES (2, 'Megan', 'megan@mail.com', 'password', '0'); INSERT INTO users (ID, USERNAME, EMAIL, PASSWORD, ISADMIN) VALUES (3, 'Peggy', 'peggy@mail.com', 'password', '0'); INSERT INTO users (ID, USERNAME, EMAIL, PASSWORD, ISADMIN) VALUES (4, 'Bob', 'bob@mail.com', 'password', '1'); INSERT INTO users (ID, USERNAME, EMAIL, PASSWORD, ISADMIN) VALUES (5, 'Jenny', 'jenny@mail.com', 'password', '0'); INSERT INTO users (ID, USERNAME, EMAIL, PASSWORD, ISADMIN) VALUES (6, 'Kenzi', 'kenzi@mail.com', 'password', '0'); #SELECT * FROM users; #SELECT * FROM users WHERE ISADMIN = '0'; #SELECT * FROM users WHERE USERNAME = 'Megan' AND PASSWORD = "password"; #SELECT ID FROM users WHERE USERNAME = "Jenny"; #SELECT USERNAME, EMAIL FROM users WHERE ID = 1; #INSERT INTO users (ID, USERNAME, EMAIL, PASSWORD, ISADMIN ) VALUES (7, 'David', 'david@mail.com', 'password', '0'); #SELECT * FROM users; #UPDATE users SET EMAIL = 'michelle2@mail.com' WHERE ID = 1; #SELECT * FROM users; #DELETE FROM users WHERE ID = 7; #SELECT * FROM users;
JavaScript
UTF-8
2,799
2.65625
3
[]
no_license
var path = require('path'); var fs = require('fs'); var AD = require('ad-utils'); var async = require('async'); var currentOptions = { loginCorrect:true, key:'mockGMA' } var GMA = function(options) { this.data={ assignments:[], measurements:[] }; this.lookup = { assignmentID_measurementID:{} // hash of assignment_id : measurement_ids } this.options = AD.sal.extend({}, { loginCorrect:true, }, options); this.key = currentOptions.key+''; } module.exports = GMA; var _assignments = []; GMA.setAssignments = function( assignments ) { var list = []; assignments.forEach(function(entry){ list.push( new Assignment(entry) ); }) _assignments = list; } var _measurements = []; GMA.setMeasurements = function( measurements ) { _measurements = measurements; } // able to allow setting of options : // .options() : returns the current option settings // .options({ key:value }) : sets the current options settings GMA.options = function(options) { if (typeof options == 'undefined'){ return currentOptions; } else { var newOptions = {}; for (var c in currentOptions) { if (typeof options[c] != 'undefined') newOptions[c] = options[c]; else newOptions[c] = currentOptions[c]; } currentOptions = newOptions; } } //----------------------------------------------------------------------------- // gma-api methods //----------------------------------------------------------------------------- GMA.prototype.loginWithTicket = function( ticket ) { var dfd = AD.sal.Deferred(); if (currentOptions.loginCorrect) { dfd.resolve(); } else { dfd.reject(new Error('MockObject: invalid loginWithTicket')); } return dfd; } // getAssignments returns 3 values: byID, byName, array GMA.prototype.getAssignments = function () { var dfd = AD.sal.Deferred(); var byID = { /* nodeId : shortName */ }; var byName = { /* shortName : nodeId */ }; _assignments.forEach(function(entry){ byID[entry.nodeId] = entry.shortName; byName[entry.shortName] = entry.nodeId; }) dfd.resolve(byID, byName, _assignments); return dfd; } //----------------------------------------------------------------------------- // mock Assignment //----------------------------------------------------------------------------- var Assignment = function(data) { this.gma = data.gma; this.nodeId = data.nodeId; this.shortName = data.shortName; this.role = data.role; // staff vs director }; Assignment.prototype.getMeasurements = function(role) { var dfd = AD.sal.Deferred(); dfd.resolve(_measurements); return dfd; }
PHP
UTF-8
927
3.234375
3
[ "BSD-3-Clause" ]
permissive
<?php namespace Bencode\Core\Traits; /** * Primarily used in the Bencode factory object, this Trait defines a method * that can be used to either `read` or `decode` a value into an object given. * * This method is *fail-safe* up to the point of throwing internal Exceptions * from each individual Element. */ trait FactoryBuild { /** * Determines if the Element should `read` or `decode` the value. * * @param Element $element The Element object * @param mixed $value The value to put in the Object * @param boolean $decode True to `decode`, false to `read` * * @return Element An Element object representing the value */ public function decodeOrRead($element, $value, $decode) { if ($decode) { $element->decode($value); } else { $element->read($value); } return $element; } }
JavaScript
UTF-8
521
2.78125
3
[]
no_license
import React from 'react'; /* Добавить сортировку для задач по названию задачи */ const TasksSorter = (props) => { const {tasks, sortCallback} = props; const sortByName = () => { tasks.sort((t1, t2) => { if (t1.name < t2.name) return -1; if (t1.name > t2.name) return 1; return 0; }); sortCallback(tasks); } return ( <div> <button onClick={sortByName}>Сортировать по имени</button> </div> ) } export default TasksSorter;
Markdown
UTF-8
2,117
3.046875
3
[]
no_license
--- date: 2013-01-05 layout: text alias: /post/39755076457/scripting-gmail title: Scripting Gmail categories: [thought] --- <p>In an attempt to get on top of my email this year, I thought about writing an app to auto cleanup my inbox based on various rules. I love the idea of inbox zero, but would rather a lot of the heavy lifting was done for me - hitting archive is just too much work.</p> <p>It turns out that Google provide a really easy way to script various google services, including gmail, through "scripts" within Google Drive. It's really straightforward: you can just write scripts in JavaScript with various google libraries to talk to each service, and since it's all within your google account you don't have to deal with authentication etc. You can easily set scripts up to auto-run every hour, day, etc too.</p> <p>Since <a href="http://twitter.com/benwerd">Ben Werdmuller</a> <a href="https://twitter.com/benwerd/status/286910176471175169">asked for someone to write an app with almost the same functionality</a> I figured I should write it up.</p> <ol> <li><p>Go to Google Drive, and do <strong>Create > More > Script</strong></p></li> <li><p>You can then script away to your hearts content. Here's the <a href="https://developers.google.com/apps-script/class_gmailapp">documentation</a> for the GmailApp library. <a href="https://gist.github.com/4462403">Here's my example</a> where I automatically archive anything that's over seven days old that I haven't starred.</p> <pre><code> function archiveOld() { var q = 'in:inbox -is:starred older_than:7d'; var threads = GmailApp.search(q); for (var thread in threads) { GmailApp.moveThreadToArchive(threads[thread]); } } archiveOld(); </code></pre></li> <li><p>You can set up triggers to run your script daily/hourly etc with <strong>Resources > Current script triggers</strong>.</p></li> <li><p>For more documentation on possible search queries like in my example above, <a href="http://support.google.com/mail/bin/answer.py?hl=en&amp;answer=7190">the very extensive search parameters docs are available here</a>.</p></li> </ol>
Java
UTF-8
210
2.390625
2
[]
no_license
package domain; public class Message { public String message; public Person sender; public Message(String message, Person sender){ this.message=message; this.sender=sender; } }
TypeScript
UTF-8
3,498
2.640625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
import { CellClassParams, ColDef } from "../entities/colDef"; import { Autowired, Bean } from "../context/context"; import { ExpressionService } from "../valueService/expressionService"; import { BeanStub } from "../context/beanStub"; import { RowClassParams } from "../entities/gridOptions"; @Bean('stylingService') export class StylingService extends BeanStub { @Autowired('expressionService') private expressionService: ExpressionService; public processAllCellClasses( colDef: ColDef, params: CellClassParams, onApplicableClass: (className: string) => void, onNotApplicableClass?: (className: string) => void ) { this.processClassRules(colDef.cellClassRules, params, onApplicableClass, onNotApplicableClass); this.processStaticCellClasses(colDef, params, onApplicableClass); } public processClassRules( classRules: { [cssClassName: string]: (Function | string) } | undefined, params: RowClassParams | CellClassParams, onApplicableClass: (className: string) => void, onNotApplicableClass?: (className: string) => void ) { if (classRules == null) { return; } const classNames = Object.keys(classRules!); const classesToApply: {[name: string]: boolean} = {}; const classesToRemove: {[name: string]: boolean} = {}; for (let i = 0; i < classNames.length; i++) { const className = classNames[i]; const rule = classRules![className]; let resultOfRule: any; if (typeof rule === 'string') { resultOfRule = this.expressionService.evaluate(rule, params); } else if (typeof rule === 'function') { resultOfRule = rule(params); } // in case className = 'my-class1 my-class2', we need to split into individual class names className.split(' ').forEach(singleClass => { if (singleClass == null || singleClass.trim() == '') { return; } resultOfRule ? classesToApply[singleClass] = true : classesToRemove[singleClass] = true; }); } // we remove all classes first, then add all classes second, // in case a class appears in more than one rule, this means it will be added // if appears in at least one truthy rule if (onNotApplicableClass) { Object.keys(classesToRemove).forEach(onNotApplicableClass); } Object.keys(classesToApply).forEach(onApplicableClass); } public getStaticCellClasses(colDef: ColDef, params: CellClassParams): string[] { const { cellClass } = colDef; if (!cellClass) { return []; } let classOrClasses: string | string[] | null | undefined; if (typeof cellClass === 'function') { const cellClassFunc = cellClass; classOrClasses = cellClassFunc(params); } else { classOrClasses = cellClass; } if (typeof classOrClasses === 'string') { classOrClasses = [classOrClasses]; } return classOrClasses || []; } private processStaticCellClasses( colDef: ColDef, params: CellClassParams, onApplicableClass: (className: string) => void ) { const classOrClasses = this.getStaticCellClasses(colDef, params); classOrClasses.forEach((cssClassItem: string) => { onApplicableClass(cssClassItem); }); } }
C++
UTF-8
2,843
3.296875
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbliss <dbliss@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/14 20:10:43 by dbliss #+# #+# */ /* Updated: 2021/03/16 15:08:35 by dbliss ### ########.fr */ /* */ /* ************************************************************************** */ #include <iostream> #include <stdlib.h> struct Data { std::string s1; int i; std::string s2; }; std::string RandomString(unsigned long len) { std::string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; std::string newstr; int pos; while(newstr.size() != len) { pos = ((rand() % (str.size() - 1))); newstr += str.substr(pos,1); } return newstr; } int randomInt() { srand (time(NULL)); int ret = rand() % 100; return (ret); } void* serialize(void) // тут сделать вывод значений!!!! { std::string s1 = RandomString(10); std::string s2 = RandomString(20); int num = randomInt(); std::string all = s1 + std::to_string(num) + s2; char *s_all = const_cast <char*> (all.c_str()); void *all_new = reinterpret_cast <void *> (s_all); std::cout << "data we want to serialize :" << std::endl; std::cout << "random string 1: " << s1 << std::endl; std::cout << "interger: " << num << std::endl; std::cout << "random string 2: " << s2 << std::endl; return (all_new); } Data * deserialize(void * raw) { Data* d = new Data; char* new_raw = reinterpret_cast<char*>(raw); d->s1 = std::string(new_raw, 10); d->i = static_cast<int>(*(new_raw + 10) - 48) * 10; d->i += static_cast<int>(*(new_raw + 11) - 48); d->s2 = std::string(new_raw + 12, 20); // add 12 to the adress; std::cout << "arr size is: " << sizeof(d->s1) << std::endl; std::cout << "arr size is: " << sizeof(d->i) << std::endl; std::cout << "arr size is: " << sizeof(d->s2) << std::endl; std::cout << "d->s1: " << d->s1 << std::endl; std::cout << "d->i: " << d->i << std::endl; std::cout << "d->s2: "<< d->s2 << std::endl; return (d); } int main() { void *Sdata = serialize(); std::cout << "data after serializing and deserializing: " << std::endl; deserialize(Sdata); return 0; }
Java
UTF-8
7,429
1.796875
2
[]
no_license
package com.leasing.rentearly.rentearlyservice.projectInfo.enity.dto; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.leasing.common.base.entity.BaseDTO; import com.leasing.common.entity.foundation.vo.OrgVO; import javax.persistence.*; import java.math.BigDecimal; /** * @project:leasing-cloud * @date:2019/10/28 * @author:jiaoshy@yonyou.com * @description: 立项参照 **/ @Entity @Table(name = "yls_project_approval") @JsonIgnoreProperties(value = { "hibernateLazyInitializer","handler"}) public class ProjectApprovalDTO extends BaseDTO { @Id public String pkProjectApproval; public String projectFilingCode; public String projectFilingName; /** * 项目报备批次 */ public Integer projectFilingBatch; /** * 客户主键 */ public String pkConsumer; /** * 文档规则 */ public String projectApprovalRule; /** * 项目类型 */ public Short projectType; /** * 项目金额 */ public BigDecimal releaseAmount; /** * 地区审批总额 */ public BigDecimal areaApproveTotal; /** * 地区实际投放总额 */ public BigDecimal areaLoanTotal; /** * 地区剩余投放总额 */ public BigDecimal areaSurplusTotal; /** * 地区可用授信额度 */ public BigDecimal areaUsableTotal; /** * 行业审批总额 */ public BigDecimal industryApproveTotal; /** * 行业实际投放总额 */ public BigDecimal industryLoanTotal; /** * 行业剩余投放总额 */ public BigDecimal industrySurplusTotal; /** * 行业可用授信额度 */ public BigDecimal industryUsableTotal; /** * 所属公司 */ @ManyToOne(fetch = FetchType.LAZY) //JPA注释: 一对一 关系 @JoinColumn(name = "pkProOrg") public OrgVO pkProOrg; // public ProjectApprovalDTO(String pkProjectApproval,String projectFilingCode,String projectFilingName, Integer projectFilingBatch, String pkConsumer, String projectApprovalRule, Short projectType, BigDecimal releaseAmount, BigDecimal areaApproveTotal, BigDecimal areaLoanTotal, BigDecimal areaSurplusTotal, BigDecimal areaUsableTotal, BigDecimal industryApproveTotal, BigDecimal industryLoanTotal, BigDecimal industrySurplusTotal, BigDecimal industryUsableTotal, OrgVO pkProOrg) { // this.pkProjectApproval = pkProjectApproval; // this.projectFilingCode = projectFilingCode; // this.projectFilingName = projectFilingName; // this.projectFilingBatch = projectFilingBatch; // this.pkConsumer = pkConsumer; // this.projectApprovalRule = projectApprovalRule; // this.projectType = projectType; // this.releaseAmount = releaseAmount; // this.areaApproveTotal = areaApproveTotal; // this.areaLoanTotal = areaLoanTotal; // this.areaSurplusTotal = areaSurplusTotal; // this.areaUsableTotal = areaUsableTotal; // this.industryApproveTotal = industryApproveTotal; // this.industryLoanTotal = industryLoanTotal; // this.industrySurplusTotal = industrySurplusTotal; // this.industryUsableTotal = industryUsableTotal; // this.pkProOrg = pkProOrg; // this.setCode(projectFilingCode); // this.setName(projectFilingName); // this.setPk(pkProjectApproval); // } public String getPkProjectApproval() { return pkProjectApproval; } public void setPkProjectApproval(String pkProjectApproval) { this.pkProjectApproval = pkProjectApproval; } public String getProjectFilingCode() { return projectFilingCode; } public void setProjectFilingCode(String projectFilingCode) { this.projectFilingCode = projectFilingCode; } public String getProjectFilingName() { return projectFilingName; } public void setProjectFilingName(String projectFilingName) { this.projectFilingName = projectFilingName; } public Integer getProjectFilingBatch() { return projectFilingBatch; } public void setProjectFilingBatch(Integer projectFilingBatch) { this.projectFilingBatch = projectFilingBatch; } public String getPkConsumer() { return pkConsumer; } public void setPkConsumer(String pkConsumer) { this.pkConsumer = pkConsumer; } public String getProjectApprovalRule() { return projectApprovalRule; } public void setProjectApprovalRule(String projectApprovalRule) { this.projectApprovalRule = projectApprovalRule; } public Short getProjectType() { return projectType; } public void setProjectType(Short projectType) { this.projectType = projectType; } public BigDecimal getReleaseAmount() { return releaseAmount; } public void setReleaseAmount(BigDecimal releaseAmount) { this.releaseAmount = releaseAmount; } public BigDecimal getAreaApproveTotal() { return areaApproveTotal; } public void setAreaApproveTotal(BigDecimal areaApproveTotal) { this.areaApproveTotal = areaApproveTotal; } public BigDecimal getAreaLoanTotal() { return areaLoanTotal; } public void setAreaLoanTotal(BigDecimal areaLoanTotal) { this.areaLoanTotal = areaLoanTotal; } public BigDecimal getAreaSurplusTotal() { return areaSurplusTotal; } public void setAreaSurplusTotal(BigDecimal areaSurplusTotal) { this.areaSurplusTotal = areaSurplusTotal; } public BigDecimal getAreaUsableTotal() { return areaUsableTotal; } public void setAreaUsableTotal(BigDecimal areaUsableTotal) { this.areaUsableTotal = areaUsableTotal; } public BigDecimal getIndustryApproveTotal() { return industryApproveTotal; } public void setIndustryApproveTotal(BigDecimal industryApproveTotal) { this.industryApproveTotal = industryApproveTotal; } public BigDecimal getIndustryLoanTotal() { return industryLoanTotal; } public void setIndustryLoanTotal(BigDecimal industryLoanTotal) { this.industryLoanTotal = industryLoanTotal; } public BigDecimal getIndustrySurplusTotal() { return industrySurplusTotal; } public void setIndustrySurplusTotal(BigDecimal industrySurplusTotal) { this.industrySurplusTotal = industrySurplusTotal; } public BigDecimal getIndustryUsableTotal() { return industryUsableTotal; } public void setIndustryUsableTotal(BigDecimal industryUsableTotal) { this.industryUsableTotal = industryUsableTotal; } public OrgVO getPkProOrg() { return pkProOrg; } public void setPkProOrg(OrgVO pkProOrg) { this.pkProOrg = pkProOrg; } public String getPk() { return pkProjectApproval; } public void setPk(String pk) { this.pkProjectApproval = pk; } @Transient public String name; @Transient public String code; public String getName(){ return projectFilingName; } public String getCode(){ return projectFilingCode; } public void setName(String name) { this.name = this.projectFilingName; } public void setCode(String code) { this.code = this.projectFilingCode; } }
PHP
UTF-8
1,644
2.609375
3
[ "MIT" ]
permissive
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="description" content="Evenementen Website" /> <meta name="keywords" content="HTML,CSS,JavaScript" /> <meta name="author" content="Brent Berghmans" /> <link rel="stylesheet" href="/~brentberghmans/styles/generalStyle.css" type="text/css" /> <script src="/~brentberghmans/src/scripts/topScroll.js" type="text/JavaScript"></script> <meta name="viewport" content="width=device-width" /> <title>Edit comment</title> </head> <body> <?php include "/home/brentberghmans/public_html/src/scripts/header.php"; ?> <div id="content"> <?php if(isset($_SESSION['rights']) && ($_SESSION['rights'] == "mod" || $_SESSION['rights'] == "admin") && isset($_POST['commentid']) && $_POST['commentid'] != null) { ?> <form class='basic_form' action='/~brentberghmans/src/scripts/editComment.php' method='POST'> <?php echo "<input type='hidden' name='commentid' value='". $_POST['commentid'] . "' />"; include '/home/brentberghmans/secure/DB_INFO.php'; //Connectie maken met DB try { $conn = new PDO("pgsql:host=" . $DB_HOST . ";dbname=" . $DB_DB, $DB_USR , $DB_PW); } catch (PDOException $e) { return "dberror"; } $conn = $conn->prepare("SELECT content, eventid FROM comments WHERE commentid = :commentid ;"); $conn->bindValue(':commentid', $_POST['commentid']); if($conn->execute()) { $row = $conn->fetch(PDO::FETCH_BOTH); } echo "<textarea name='content'>" . $row['content'] . "</textarea>"; echo "<input type='hidden' name='eventid' value='" . $row['eventid'] . "' />"; echo "<input type='submit' />"; ?> </form> <?php } ?> </div> </body> </html>
Java
UTF-8
1,102
3.53125
4
[]
no_license
package com.xiechao.swordToOffers.algorithms.tree; import com.xiechao.swordToOffers.algorithms.TreeNode; /** * @ClassName LeetCode654 * @Author xiechao * @Date 2019/3/25 * @Time 10:20 * @Description LeetCode654 Maximum Binary Tree * * 给出一个数组,构造二叉树,要求 * - 根节点是最大值 * - 左孩子是位于最大值左侧的最大值 * - 右孩子是位于最大值右侧的最大值 */ public class LeetCode654 { public TreeNode constructMaximumBinaryTree(int[] nums) { return helper(nums, 0 , nums.length); } //[start,end) private TreeNode helper(int[] nums, int start ,int end){ if(start >= end) return null; int max = nums[start]; int indexOfMax = start; for (int i = start; i < end; i++) { if(max <= nums[i]){ max = nums[i]; indexOfMax = i; } } TreeNode root = new TreeNode( max ); root.left = helper(nums, start, indexOfMax); root.right = helper(nums, indexOfMax + 1 ,end); return root; } }
Markdown
UTF-8
3,592
2.875
3
[]
no_license
# Solar System Navigator - team SET-CI As a team, we want to share our love and enthusiasm for the solar system with anyone searching for information about the cosmos. We chose a responsive design for functional viewing and user interaction from any screen size. Users can easily navigate through beautiful and informative pages to discover accessible information for any level of study. The application also provides opportunities for users to customize their experience as they navigate through our solar system. ## Table of Contents - [General Info](#general-info) - [Homepage](#homepage) - [Mobile View Homepage](#mobile-view-homepage) - [Planet Page Example 1](#planet-page-example-1) - [Planet Page Example 2](#planet-page-example-2) - [Mobile Planet Page Example 1](#mobile-planet-page-example-1) - [Mobile Planet Page Example 2](#mobile-planet-page-example-1) - [Modal Example](#modal-example) - [Technologies](#technologies) - [API References](#api-references) - [Demo Video](#demo-video) - [Authors](#authors) ## General Info This application meets but is not limited to the following criteria: * Use a CSS framework other than Bootstrap. * Be deployed to GitHub Pages. * Be interactive (i.e., accept and respond to user input). * Use at least two server-side APIs. * Does not use alerts, confirms, or prompts (use modals). * Use client-side storage to store persistent data. * Be responsive. * Have a polished UI. * Have a clean repository that meets quality coding standards (file structure, naming conventions, follows best practices for class/id naming conventions, indentation, quality comments, etc.). * Have a quality README (with unique name, description, technologies used, screenshot, and link to deployed application). ## Homepage ![Homepage](https://github.com/sloanlacey/Project-1/blob/main/assets/images/homepage.png) ## Mobile View Homepage ![Mobile View Homepage](https://github.com/sloanlacey/Project-1/blob/main/assets/images/mobilehomepage.png) ## Planet Page Example 1 ![Planet Page Example 1](https://github.com/sloanlacey/Project-1/blob/main/assets/images/planetexample1.png) ## Planet Page Example 2 ![Planet Page Example 2](https://github.com/sloanlacey/Project-1/blob/main/assets/images/planetexample2.png) ## Mobile Planet Page Example 1 ![Mobile Planet Page Example 1](https://github.com/sloanlacey/Project-1/blob/main/assets/images/mobileplanet1.png) ## Mobile Planet Page Example 2 ![Mobile Planet Page Example 2](https://github.com/sloanlacey/Project-1/blob/main/assets/images/mobileplanet2.png) ## Modal Example ![Modal Example](https://github.com/sloanlacey/Project-1/blob/main/assets/images/modalexample.png) ## Technologies * This application was built with: - [JavaScript](https://www.javascript.com/) - [HTML](https://html.com/) - [CSS](https://www.w3.org/Style/CSS/Overview.en.html) - [Materialize CSS](https://materializecss.com/) ## API References * The API's used in this application are as follows: - [Wikipedia API](https://en.wikipedia.org/w/api.php?action=query&titles=earth&prop=extracts&format=json) - [Open Weather API](https://openweathermap.org/api) - [NASA Insight Mars Weather API](https://api.nasa.gov/) - [NASA Earth Imaging API](https://api.nasa.gov/) - [Moon Phase and Luminosity API](https://rapidapi.com/burningsoul/api/moonapi/endpoints) ## Demo Video Coming soon! ## Authors - [Aaron Alexander](https://github.com/Kitesur7) - [Michael Alexander](https://github.com/ALEX00100alex) - [Steve Eliuth](https://github.com/Eliuth4k9) - [Alexander Fok](https://github.com/alex-fok) - [Sloan Lacey](https://github.com/sloanlacey)
C++
UTF-8
1,373
2.84375
3
[]
no_license
#include <cstdio> #include <iostream> #include <string> #include <stack> #include <algorithm> using namespace std; typedef long long int ll; ll arr[21]; ll fact (int n) { if(n == 0 || n == 1) return 1; arr[n] = n * fact(n - 1); return arr[n]; } int main() { int tes, o = 0; scanf("%d", &tes); while(tes--){ o++; stack <string> f, b; string s = "http://www.lightoj.com/" , c; printf("Case %d:\n",o); while(cin >> c && c != "QUIT") { if(c == "BACK") { if(b.empty()) printf("Ignored\n"); else { f.push(s); s = b.top(); b.pop(); cout<<s<< endl; } } else if(c == "FORWARD") { if(f.empty()) { cout<<"Ignored"<< endl; } else{ b.push(s); s = f.top(); f.pop(); cout<<s<< endl; } } else { b.push(s); cin >> s; cout<<s<< endl; while(f.size()) f.pop(); } } } }
Python
UTF-8
1,136
2.734375
3
[]
no_license
from _collections import deque n, m = map(int, input().split()) data = [list(map(int, input().split())) for _ in range(n)] dx, dy = [-1, 1, 0, 0], [0, 0, -1, 1] chick_map = [] house_map = [] for i in range(n): for j in range(n): if data[i][j] == 2: chick_map.append((i, j)) elif data[i][j] == 1: house_map.append((i, j)) result_data = [] visited = [False for _ in range(len(chick_map))] def dfs(cnt, idx, param_data): if cnt == m: cal_solved(param_data) return for i in range(idx, len(chick_map)): if visited[i] == False: visited[i] = True param_data.append(chick_map[i]) dfs(cnt + 1, i, param_data) param_data.pop() visited[i] = False glo_result = [] def cal_solved(result): sum_result = 0 for i in house_map: sum_data = int(1e9) for j in result: x1, y1 = i x2, y2 = j sum_data = min(sum_data, (abs(x1 - x2) + abs(y1 - y2))) sum_result += sum_data glo_result.append(sum_result) dfs(0, 0, []) print(min(glo_result))
C++
UTF-8
330
2.609375
3
[]
no_license
#include "types.h" m_Point::m_Point() { x = y = t = 0; for each (GLdouble xt in coeff_xt) xt = 0.0; for each (GLdouble yt in coeff_yt) yt = 0.0; } m_Point::m_Point(GLdouble x, GLdouble y) { this->x = x; this->y = y; this->t = 0; for each (GLdouble xt in coeff_xt) xt = 0.0; for each (GLdouble yt in coeff_yt) yt = 0.0; }
Java
UTF-8
893
3.453125
3
[]
no_license
/** * */ package RandomGuessMatch; /** * @author MH137428 * */ import javax.swing.JOptionPane; public class randomGuessMatchBoolean { /** * @param args */ public static void main(String[] args) { boolean response; String answer; int random, input, difference; final int min = 1; final int max = 5; random = min + (int)(Math.random() * max); answer = JOptionPane.showInputDialog(null, "Guess a number between " + min + " and " + max + ".", "Choose A Number", JOptionPane.INFORMATION_MESSAGE); input = Integer.parseInt(answer); difference = java.lang.Math.abs(random - input); response = (input == random); JOptionPane.showMessageDialog(null, "You were " + difference + " off of the correct number."); JOptionPane.showMessageDialog(null, "You put " + input + " when the random number was " + random + " . That's " + response + "."); } }
Java
UTF-8
213
1.8125
2
[ "MIT" ]
permissive
package uk.gov.hmcts.reform.fpl.enums; public enum HearingStatus { ADJOURNED, ADJOURNED_AND_RE_LISTED, ADJOURNED_TO_BE_RE_LISTED, VACATED, VACATED_AND_RE_LISTED, VACATED_TO_BE_RE_LISTED }
C#
UTF-8
524
2.53125
3
[]
no_license
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace Assets { public class BaseGameObject : MonoBehaviour { public void WaitForSeconds(Action action, float time) { StartCoroutine(CoWaitForSeconds(action, time)); } private IEnumerator CoWaitForSeconds(Action action, float time) { yield return new WaitForSeconds(time); action(); } } }
PHP
UTF-8
398
2.703125
3
[ "MIT" ]
permissive
<?php namespace App\Models; use DB; use Illuminate\Database\Eloquent\Model; class User extends Model { /** * The database table used by the model. * * @var string */ protected $table = 'users'; /** * select sms * * @return Illuminate\Database\Eloquent\Relations\BelongsTo */ public function select(array $data) { return DB::table($this->table)->where($data)->get(); } }
Java
UTF-8
1,170
2.5
2
[]
no_license
package com.zgh.spring.ioc.container; import com.zgh.spring.ioc.container.bean.BeanDefinition; import com.zgh.spring.ioc.container.bean.BeanProperty; import com.zgh.spring.ioc.container.bean.BeanPropertys; import com.zgh.spring.ioc.container.factory.BeanFactory; import com.zgh.spring.ioc.container.factory.DefaultBeanFactory; import com.zgh.spring.ioc.container.service.HelloWorldSpringService; public class Test { public static void main(String[] args) { BeanFactory beanFactory = new DefaultBeanFactory(); BeanDefinition beanDefinition = new BeanDefinition("com.zgh.spring.ioc.container.service.HelloWorldSpringService"); BeanPropertys beanPropertys = beanDefinition.getBeanPropertys(); beanPropertys.addBeanProperty(new BeanProperty("stringText","Hello! This is Field Stringtext Value!")); beanPropertys.addBeanProperty(new BeanProperty("stringValue","Hello! This is Field stringValue Text!")); beanFactory.registerBeanDefinition("helloSpringService", beanDefinition); HelloWorldSpringService helloWorldSpringService = (HelloWorldSpringService) beanFactory .getBean("helloSpringService"); helloWorldSpringService.doService(); } }
C#
UTF-8
683
3.078125
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; namespace InheritanceRefactorings.ReplaceDelegationWithInheritance.Bad { public class EmployeeCollection { private List<Employee> _employees = new List<Employee>(); public int Count { get { return _employees.Count; } } public IEnumerable<Employee> ListCurrentEmployees() { return _employees.Where(e => e.IsEmployed).AsEnumerable(); } public void Add(Employee employee) { _employees.Add(employee); } public void Remove(Employee employee) { _employees.Remove(employee); } } }
Markdown
UTF-8
2,508
2.609375
3
[]
no_license
# Lazarus-VPN # "vpn" directory EasyRSA This Repository contains EasyRsa directory, which is used to initialize pki to crate CA and issue/revoke/renew certificates. Configs configs/base Config directory contains base config parameters for client configuration based on OS type i.e. Windows, Linux or Mac. config/clients This directory also contains any client config generated (.ovpn files) OpenVPN-Server This directory contain configuration file for OpenVPN server. How to setup CA and Generate Server Certificate & Keys ------------------------------------------------------ 1. Clone the repository 2. Make sure vars file has relevant settings, if not you can change it and save. 3. Goto EasyRSA directory and initialize the pki ./easyrsa init-pki This will create a new directory under EasyRSA directory named "pki" This newly created directory will hold all certificates and keys. 4. 6. Generate CA certificate adn key using below command ./easyrsa build-ca nopass 5. Generate server certificate using below command ./easyrsa build-server-full server nopass 6. Generate Diffie–Hellman key exchange using below command ./easyrsa gen-dh Install OpenVPN Server ---------------------- * Ubuntu 16.04/18.04 -------------------- sudo apt-get update sudo apt-get install openvpn cd OpenVPN-Server cp server.conf /etc/openvpn/ cd ../EasyRSA-v3.0.6 cp pki/issued/server.crt /etc/openvpn/ cp pki/private/server.key /etc/openvpn/ cp pki/dh.pem /etc/openvpn/ cd /etc/openvpn openvpn --genkey --secret ta.key * Start OpenVPN Server sudo systemctl start openvpn@server Above commandwill start openvpn server on port 1194/UDP Generate Client Certificate & Configuration file ------------------------------------------------ 1. Goto Scripts directory generate-client-config.sh script is responsible for generating client certifiate and keys along with inline readymade ovpn configuration file. It take 3 arguments as listed below ./generate-client-config.sh <client_first_name> <operating_system> <passphrase> 2. Generate certificate and configuartion file as below ./generate-client-config.sh fake_user windows fakepassword 3. Newly created configuration file will be available under <ROOT_REPO_DIR>/configs/clients directory
Java
UTF-8
1,187
2.34375
2
[]
no_license
package com.accipio.tutorme; import android.app.Application; import android.graphics.Bitmap; /** * Created by rachel on 2016-11-02. */ public class TutorMeApplication extends Application { private String userID; private String firstName; private String lastName; private String email; private boolean tutor = false; private Bitmap image; public String getID() { return userID; } public void setID(String ID) { userID = ID; } public String getFirstName() { return firstName; } public void setFirstName(String fname) { firstName = fname; } public String getLastName() { return lastName; } public void setLastName(String lname) { lastName = lname; } public String getEmail() { return email; } public void setEmail(String address) { email = address; } public boolean isTutor() { return tutor; } public void setTutor(boolean isTutor) { tutor = isTutor; } public void setImage(Bitmap picture) { image = picture; } public Bitmap getImage() { return image; } }
C#
UTF-8
8,419
2.796875
3
[]
no_license
using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Reflection; using System.Drawing.Drawing2D; using System.Drawing.Imaging; namespace RangeSelect { public partial class SelectionRangeSlider : UserControl { /// <summary> /// Enumeration for the slider edge /// </summary> enum MovingMode { MovingMin, MovingMax } MovingMode movingMode; #region Properties /// <summary> /// Background Image. /// </summary> [Description("Background image of the range selector.")] public Image Image { get { return image; } set { image = value; Invalidate();} } Image image = null; /// <summary> /// Minimum value of the slider. /// </summary> [Description("Minimum value of the range selector.")] public int Min { get { return min; } set { min = value; Invalidate(); } } int min = 0; /// <summary> /// Maximum value of the slider. /// </summary> [Description("Maximum value of the range selector.")] public int Max { get { return max; } set { max = value; Invalidate(); } } int max = 100; /// <summary> /// Minimum value of the selection range. /// </summary> [Description("Minimum value of the selection range.")] public int SelectedMin { get { return selectedMin; } set { selectedMin = value; if (SelectionChanged != null) SelectionChanged(this, null); labelMin.Text = value.ToString(); Invalidate(); } } int selectedMin = 0; /// <summary> /// Maximum value of the selection range. /// </summary> [Description("Maximum value of the selection range.")] public int SelectedMax { get { return selectedMax; } set { selectedMax = value; if (SelectionChanged != null) SelectionChanged(this, null); labelMax.Text = value.ToString(); Invalidate(); } } int selectedMax = 100; /// <summary> /// Step. /// </summary> [Description("Step.")] public int Step { get { return step; } set { step = value; Invalidate(); } } int step = 5; /// <summary> /// Label / Description of the range selector. /// </summary> [Description("Label / Description of the range selector.")] public string Label { get { return label; } set { label = value; labelDescription.Text = value; Invalidate(); } } string label = ""; /// <summary> /// Color of the background. /// </summary> [Description("Background color.")] public Color BackgroundColor { get { return bgBrush.Color; } set { bgBrush.Color = value; Invalidate(); } } SolidBrush bgBrush = new SolidBrush(Color.White); /// <summary> /// Color of the selected range. /// </summary> [Description("Selected range color.")] public Color SelectionColor { get { return brush.Color; } set { brush.Color = value; Invalidate(); } } SolidBrush brush = new SolidBrush(Color.FromArgb(255, Color.Red)); /// <summary> /// Fired when the selected range changes. /// </summary> [Description("Fired when the selected range changes.")] public event EventHandler SelectionChanged; #endregion public SelectionRangeSlider() { InitializeComponent(); //avoid flickering typeof(Panel).InvokeMember("DoubleBuffered", BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic, null, panelBG, new object[] { true }); panelBG.Paint += new PaintEventHandler(SelectionRangeSlider_Paint); panelBG.MouseDown += new MouseEventHandler(SelectionRangeSlider_MouseDown); panelBG.MouseMove += new MouseEventHandler(SelectionRangeSlider_MouseMove); //change the text on labels labelMin.Text = min.ToString(); labelMax.Text = max.ToString(); labelDescription.Text = label; } #region Events // Paint event void SelectionRangeSlider_Paint(object sender, PaintEventArgs e) { var panel = sender as Panel; if (image != null) { //draw the image Bitmap bm = new Bitmap(panel.Width, panel.Height); using (Graphics gr = Graphics.FromImage(bm)) { gr.InterpolationMode = InterpolationMode.HighQualityBicubic; Rectangle dest_rect = new Rectangle(0, 0, panel.Width, panel.Height); Rectangle source_rect = new Rectangle(0, 0, image.Width, image.Height); e.Graphics.DrawImage(image, dest_rect, source_rect, GraphicsUnit.Pixel); } bm.Dispose(); } else { //paint background in white e.Graphics.FillRectangle(bgBrush, ClientRectangle); } //paint selection range in blue Rectangle selectionRect = new Rectangle( (selectedMin - Min) * panel.Width / (Max - Min), 0, (selectedMax - selectedMin) * panel.Width / (Max - Min), panel.Height); e.Graphics.FillRectangle(brush, selectionRect); } // Mouse down event void SelectionRangeSlider_MouseDown(object sender, MouseEventArgs e) { //check where the user clicked so we can decide which side to move int pointedValue = Min + e.X * (Max - Min) / Width; int distMin = Math.Abs(pointedValue - SelectedMin); int distMax = Math.Abs(pointedValue - SelectedMax); int minDist = Math.Min(distMin, distMax); if (minDist == distMin) movingMode = MovingMode.MovingMin; else movingMode = MovingMode.MovingMax; //call this to refresh the position of the selected slider SelectionRangeSlider_MouseMove(sender, e); } // Mouse drag event void SelectionRangeSlider_MouseMove(object sender, MouseEventArgs e) { //if the left mouse button was pushed, move the selected slider if (e.Button != MouseButtons.Left) return; int pointedValue = Min + e.X * (Max - Min) / Width; int dStep = pointedValue % step; pointedValue = step * (pointedValue / step); if (dStep > step / 2) pointedValue += step; if (movingMode == MovingMode.MovingMin) { if (pointedValue >= SelectedMax) { // we don't want a region of 0 pointedValue = SelectedMax - 1; movingMode = MovingMode.MovingMax; } if (pointedValue < min) pointedValue = min; SelectedMin = pointedValue; labelMin.Text = SelectedMin.ToString(); } else if(movingMode == MovingMode.MovingMax) { if (pointedValue <= SelectedMin) { // we don't want a region of 0 pointedValue = SelectedMin + 1; movingMode = MovingMode.MovingMin; } if (pointedValue > max) pointedValue = max; SelectedMax = pointedValue; labelMax.Text = SelectedMax.ToString(); } } #endregion } }
Java
UTF-8
3,347
2.359375
2
[]
no_license
package com.sxh.demo.adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.sxh.demo.R; import com.sxh.demo.beans.MenuBean; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Administrator on 2018/9/4. */ public class LinearPicsAdapter extends RecyclerView.Adapter<LinearPicsAdapter.ViewHolder> { private List<MenuBean.DataEntity> data=new ArrayList<>(); private Context mContext; private int width; private Map<Integer, ImageView> mCaches = new HashMap<>(); public LinearPicsAdapter(Context context) { mContext=context; } public List<MenuBean.DataEntity> getData() { return data; } public void setData(List<MenuBean.DataEntity> data) { this.data = data; notifyDataSetChanged(); } @Override public LinearPicsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View contentView = LayoutInflater.from(parent.getContext()).inflate(R.layout.linear_menu_item, parent, false); LinearPicsAdapter.ViewHolder viewHolder = new LinearPicsAdapter.ViewHolder(contentView); return viewHolder; } @Override public void onBindViewHolder(ViewHolder holder, final int position) { RequestOptions options=new RequestOptions(); options.placeholder(R.mipmap.not_pic); options.error(R.mipmap.not_pic); Glide.with(mContext).load(data.get(position).getImg()).apply(options).into(holder.icon); holder.name.setText(data.get(position).getName()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mItemClickListeners!=null){ mItemClickListeners.onClickListener(position); } } }); mCaches.put(position, holder.icon); } public ImageView getItemView(int position) { return mCaches.get(position); } public List<ImageView> getAllView(){ List<ImageView> list=new ArrayList<>(); list.clear(); for (int i=0;i<mCaches.size();i++){ list.add(mCaches.get(i)); } return list; } @Override public int getItemCount() { if (data!=null) { return data.size(); }else{ return 0; } } public class ViewHolder extends RecyclerView.ViewHolder { private ImageView icon; private TextView name; public ViewHolder(View itemView) { super(itemView); icon = (ImageView) itemView.findViewById(R.id.index_menu_icon); name = (TextView) itemView.findViewById(R.id.index_menu_name); } } private OnItemClickListeners mItemClickListeners; public void setItemClickListeners(OnItemClickListeners itemClickListeners) { mItemClickListeners = itemClickListeners; } public interface OnItemClickListeners{ void onClickListener(int position); } }
Python
UTF-8
7,156
2.84375
3
[]
no_license
import os import pandas as pd import numpy as np from flask_cors import CORS __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) from flask import Flask, jsonify, request app = Flask(__name__) CORS(app) @app.route('/home') def home(): headers = ['year', 'level_1', 'level_2', 'value'] dtypes = {'year': 'float', 'level_1': 'str', 'level_2': 'str', 'value': 'float'} df = pd.read_csv( os.path.join(__location__, 'data.csv') , sep=',', header=0, names=headers, dtype=dtypes, na_values=["na"]) gender = request.args.get('gender') year = request.args.get('year') if not gender: gender = 'all' if not year: year = 2019 else: year = int(year) graph_data = df[(df.level_1 != "Total Residents") & (df.level_1 != "Total Male Residents") & (df.level_1 != "Total Female Residents")] if year == 1970: graph_data = graph_data[graph_data["year"] < 1970] elif year == 1980: graph_data = graph_data[(graph_data["year"] >= 1970) & (graph_data["year"] < 1980)] elif year == 1990: graph_data = graph_data[(graph_data["year"] >= 1980) & (graph_data["year"] < 1990)] elif year == 2000: graph_data = graph_data[(graph_data["year"] >= 1990) & (graph_data["year"] < 2000)] elif year == 2010: graph_data = graph_data[(graph_data["year"] >= 2000) & (graph_data["year"] < 2010)] else: graph_data = graph_data[(graph_data["year"] >= 2010)] if gender == "all": graph_data = graph_data[(~graph_data["level_1"].str.contains("Male")) & ((~graph_data["level_1"].str.contains("Female")))] elif gender == "male": graph_data = graph_data[(graph_data["level_1"].str.contains("Male")) | ((graph_data["level_1"].str.contains("Males")))] else: graph_data = graph_data[(graph_data["level_1"].str.contains("Female")) | ((graph_data["level_1"].str.contains("Females")))] graph_data = graph_data.groupby(['year', 'level_1']) # c = graph_data['value'].agg(np.sum) data = {} for i, v in graph_data['value'].agg(np.sum).iteritems(): t = i[1].replace('Males','').replace("Total Male ","") t = t.replace('Females','').replace("Total Female ","") t = t.replace('Total','').replace(" Ethnic Groups ()","") t = t.strip() if i[0] in data: data[i[0]][t] = v # data[i[0]][t + "Color"] = "hsl(273, 70%, 50%)" else: data[i[0]] = { "year": i[0], t: v, # t + "Color": "hsl(273, 70%, 50%)", } return jsonify( data=list(data.values()) ) @app.route('/population') def population(): headers = ['year', 'level_1', 'level_2', 'value'] dtypes = {'year': 'float', 'level_1': 'str', 'level_2': 'str', 'value': 'float'} df = pd.read_csv( os.path.join(__location__, 'data.csv') , sep=',', header=0, names=headers, dtype=dtypes, na_values=["na"]) graph_data = df[(~df["level_2"].str.contains("Over"))] gender = request.args.get('gender') if not gender: gender = 'all' if gender == "all": graph_data = graph_data[graph_data.level_1 == "Total Residents"] elif gender == "male": graph_data = graph_data[graph_data.level_1 == "Total Male Residents"] else: graph_data = graph_data[graph_data.level_1 == "Total Female Residents"] graph_data = graph_data.groupby(['year', 'level_1']) total_population = [] for i, v in graph_data['value'].agg(np.sum).iteritems(): total_population.append({ "x": i[0], "y":v }) return jsonify( data=list(total_population) ) @app.route('/ethnic_groups') def ethnicGroupPopulation(): headers = ['year', 'level_1', 'level_2', 'value'] dtypes = {'year': 'float', 'level_1': 'str', 'level_2': 'str', 'value': 'float'} df = pd.read_csv( os.path.join(__location__, 'data.csv') , sep=',', header=0, names=headers, dtype=dtypes, na_values=["na"]) graph_data = df[(df.level_1 != "Total Residents") & (~df["level_2"].str.contains("Over"))] year = request.args.get('year') gender = request.args.get('gender') if not gender: gender = 'all' if not year: year = 2019 else: year = int(year) graph_data = graph_data[graph_data.year == year] if gender == "all": graph_data = graph_data[(~graph_data["level_1"].str.contains("Male")) & (~graph_data["level_1"].str.contains("Female"))] elif gender == "male": graph_data = graph_data[ (graph_data["level_1"] != "Total Male Residents") & (graph_data["level_1"].str.contains("Male"))] else: graph_data = graph_data[ (graph_data["level_1"] != "Total Female Residents") & (graph_data["level_1"].str.contains("Female"))] graph_data = graph_data.groupby(['year', 'level_1']) ethnic_population = [] for i, v in graph_data['value'].agg(np.sum).iteritems(): t = i[1].replace('Total','').replace(" Ethnic Groups ()","") t = t.replace("Males",'').replace("Male",'').replace("Females",'').replace("Female",'') t = t.strip() ethnic_population.append({ "id": t, "label": t, "value": v }) return jsonify( data=list(ethnic_population) ) @app.route('/age_groups') def ageGroupPopulation(): headers = ['year', 'level_1', 'level_2', 'value'] dtypes = {'year': 'float', 'level_1': 'str', 'level_2': 'str', 'value': 'float'} df = pd.read_csv( os.path.join(__location__, 'data.csv') , sep=',', header=0, names=headers, dtype=dtypes, na_values=["na"]) graph_data = df[(df.level_1 != "Total Residents") & (~df["level_2"].str.contains("Over"))] year = request.args.get('year') gender = request.args.get('gender') if not gender: gender = 'all' if not year: year = 2019 else: year = int(year) graph_data = graph_data[graph_data.year == year] if gender == "all": graph_data = graph_data[(~graph_data["level_1"].str.contains("Male")) & (~graph_data["level_1"].str.contains("Female"))] elif gender == "male": graph_data = graph_data[ (graph_data["level_1"] != "Total Male Residents") & (graph_data["level_1"].str.contains("Male"))] else: graph_data = graph_data[ (graph_data["level_1"] != "Total Female Residents") & (graph_data["level_1"].str.contains("Female"))] graph_data = graph_data.groupby(['year', 'level_2']) age_population = [] for i, v in graph_data['value'].agg(np.sum).iteritems(): t = i[1].replace('Total','').replace(" Ethnic Groups ()","") t = t.replace("Years", '').strip() age_population.append({ "age group": t, "population": v }) if len(age_population) > 9: age_population.insert(1, age_population.pop(9)) return jsonify( data=list(age_population) ) if __name__ == "__main__": app.run()
C#
UTF-8
799
2.671875
3
[]
no_license
/* **************************************************************** * SharpSword zhangliang4629@163.com 10/3/2016 4:28:58 PM * ****************************************************************/ using System; namespace SharpSword.Events { /// <summary> /// 此接口返回对象构造函数入参数据,方便在运行时创建此对象的时候作为入参创建对象 /// 注意:运行时创建对象的时候,会根据参数GetConstructorArgs()方法返回的参数个数来选择正确的构造函数进行创建 /// </summary> public interface IEventDataWithInheritableGenericArgument { /// <summary> /// 获取构造函数参数值 /// </summary> /// <returns></returns> object[] GetConstructorArgs(); } }
Shell
UTF-8
236
3
3
[ "Apache-2.0" ]
permissive
#!/bin/bash set -ex trap killcontainer ERR function killcontainer(){ killall -9 sleep } while true ; do sleep 10 curl -s http://172.22.0.1:5050 > /dev/null || ( echo "Can't contact ironic-inspector-api" && exit 1 ) done
JavaScript
UTF-8
535
3.640625
4
[]
no_license
var add = function(a,b){ return a+b; } var myObject = { value:0, increment:function (inc){ this.value += typeof inc === 'number' ? inc :1; } }; myObject.increment(); document.writeln(myObject.value); myObject.increment(2); document.writeln(myObject.value); var sum = add(3,4); myObject.double = function(){ var helper = function(){ document.writeln(this);//undefined this.value = add(this.value,this.value); } helper(); }; myObject.double(); document.writeln(myObject.value);//3
Rust
UTF-8
516
2.875
3
[ "MIT", "LicenseRef-scancode-other-permissive", "Apache-2.0", "BSD-3-Clause", "BSD-2-Clause", "NCSA" ]
permissive
//! Check that fold closures aren't duplicated for each iterator type. // compile-flags: -C opt-level=0 fn main() { (0i32..10).by_ref().count(); (0i32..=10).by_ref().count(); } // `count` calls `fold`, which calls `try_fold` -- find the `fold` closure: // CHECK: {{^define.*Iterator::fold::.*closure}} // // Only one closure is needed for both `count` calls, even from different // monomorphized iterator types, as it's only generic over the item type. // CHECK-NOT: {{^define.*Iterator::fold::.*closure}}
PHP
UTF-8
1,018
2.578125
3
[ "MIT" ]
permissive
<?php use Windwalker\Renderer\BladeRenderer; class HotPostsWidget extends WP_Widget { private $blade; function __construct() { parent::__construct( 'hot_posts_widget', '熱門文章1', ['description'=>'這是一個會顯示熱門文章的小工具,資料來源是 Google Analytics'] ); $this->blade = new BladeRenderer(__DIR__ . '/template/', ['cache_path'=>__DIR__ . '/cache']); } public function widget($args, $instance) { global $wpdb; $table_name = $wpdb->prefix . "statistics"; $data = $wpdb->get_results("SELECT `post_id` ,sum(`count`) FROM `$table_name` where `date` > NOW() - INTERVAL 2 week group by `post_id` order by sum(`count`) desc limit 0,30", ARRAY_N); echo $this->blade->render('widget', ['posts'=>$data]); } public function form($instance) { } public function update($new, $old) { } } add_action('widgets_init', function() { register_widget('HotPostsWidget'); });
Python
UTF-8
2,548
2.734375
3
[ "MIT" ]
permissive
import json from flask import Flask, jsonify, abort, request from modules.quiz.controllers import Controller from modules.quiz.utils.data import get_str from modules.quiz.utils.quiz import quiz_helper app = Flask(__name__) controller = Controller() def run(): app.run() # @app.route('/quiz', methods=['GET', 'POST']) # I was thinking about creating a quiz with name, description, max_score # and number_of questions parametrized but didn't have the time @app.route('/quiz', methods=['GET']) def create_quiz(): """ A new instance of a quiz :return: json representing the quiz or with a custom error """ # if request.method == 'POST': # quiz_data = json.loads(request.get_json())["quiz"] # name = quiz_data["name"] # description = quiz_data["description"] # new_quiz = controller.get_new_quiz(name=name, description=description, question_count=20, max_score=10.0) # return quiz_helper.to_json(new_quiz) # else:''' new_quiz = controller.get_new_quiz(question_count=20, max_score=10.0) return quiz_helper.to_json(new_quiz) @app.route('/quiz/<quiz_code>', methods=['GET']) def get_quiz(quiz_code): """ Get the selected quiz instance :param quiz_code: :return: json representing the quiz or with a custom error """ message = controller.get_quiz(quiz_code) return message @app.route('/quiz/<quiz_code>/update', methods=['PUT']) def update_quiz(quiz_code): json_data = get_str(request.get_json()) message = controller.update_quiz(json_data, quiz_code) return message @app.route('/quiz/<quiz_code>/answer', methods=['PUT']) def answer(quiz_code): """ Updates the quiz instance with the information received as json :param quiz_code: :return: json representing the quiz or with a custom error """ json_data = get_str(request.get_json()) text_response = controller.answer_quiz(json_data, quiz_code) return text_response @app.route('/quiz/<quiz_code>/grade', methods=['get']) def grade(quiz_code): """ Grades the instance according to the options selected using the answer method :param quiz_code: :return: json representing the quiz or with a custom error """ text_response = controller.grade_quiz(quiz_code) return text_response if __name__ == '__main__': app.run() @app.errorhandler(404) def not_found(error): return jsonify({'error': 'Not found'}) @app.errorhandler(405) def too_many(error): return jsonify({'error': 'Too many results'})
PHP
UTF-8
721
2.53125
3
[]
no_license
<?php session_start(); function blockPage() { $blockRoutes = ['login']; $currentUri = $_SERVER['REQUEST_URI']; //todos/edit/.... foreach($blockRoutes as $route) { if(strpos($currentUri, $route)){ return true; } } return false; } if(!blockPage() && empty($_SESSION['user'])) { redirect('login'); } elseif(!blockPage()) { $user = $_SESSION['user']; } ?> <nav> <ul> <?php if(!blockPage()): ?> <li><a href="/" >Home</a></li> <li><a href="/about" >About</a></li> <li><a href="/todos" >Todos</a></li> <li><a href="/contact" >Contact</a></li> <li><a href="/logout">Logout</a> </li> <?php endif ?> </ul> </nav>
C++
UTF-8
4,217
3.0625
3
[]
no_license
#include "GDFReader.h" GDFReader::GDFReader(){} GDFReader::GDFReader(string inputfilepath,string outputfilepath){ this->setinputFilePath(inputfilepath); this->setoutputFilePath(outputfilepath); } GDFReader::~GDFReader(){} inline string GDFReader::trim(string s){ string str=s; str.erase(0, str.find_first_not_of(' ')); str.erase(str.find_last_not_of(' ')+1); return str; } //The input file can contain gaps and empty lines and also most of the other corner cases are handled by this code. void GDFReader::ModifyFile(){ try{ int pos = this->getinputFilePath().find("."); string t ; t = this->getinputFilePath().substr(pos + 1, this->getinputFilePath().size()); if(t!="gdf"){ throw t; } fstream file; file.open(this->getinputFilePath()); if(!file.is_open()){ throw 404; } Graph G; stringstream ss; string token; int namecolumn=0,node1column=0,node2column=0,weighcolumn=0,directedcolumn=0,currColumn=0; string line;getline(file,line); while(line==""){ getline(file,line); } //Reading Nodedef if((trim(line).substr(0,8))==NODEDEF){ ss<<trim(line).substr(8,line.length()-8); currColumn=0; while(getline(ss,token,',')){ if(token.find("name")!=string::npos)namecolumn=currColumn; currColumn++; } ss.clear(); while(getline(file,line) and trim(line).substr(0,8)!=EDGEDEF){ ss<<line; currColumn=0; while(getline(ss,token,',')){ if(currColumn==namecolumn){ G.AddNode(trim(token)); } currColumn++; } ss.clear(); } G.Build(); } //Reading Edgedef if(trim(line).substr(0,8)==EDGEDEF){ ss<<trim(line).substr(8,line.length()-8); currColumn=0; while(getline(ss,token,',')){ if(token.find("node1")!=string::npos)node1column=currColumn; if(token.find("node2")!=string::npos)node2column=currColumn; if(token.find("weight")!=string::npos)weighcolumn=currColumn; if(token.find("directed")!=string::npos)directedcolumn=currColumn; currColumn++; } ss.clear(); while(getline(file,line)){ ss<<line; currColumn=0; string node1,node2;double weight;bool directed; while(getline(ss,token,',')){ if(currColumn==node1column){ node1=trim(token); } else if(currColumn==node2column){ node2=trim(token); } else if(currColumn==weighcolumn){ weight=stod(trim(token)); } else if(currColumn==directedcolumn){ directed=(trim(token)=="true"); } currColumn++; } if(currColumn!=4)throw 504; G.AddEdge(node1,node2,weight); if(!directed){ G.AddEdge(node2,node1,weight); } ss.clear(); } } G.GetCSVRepresentation(this->getoutputFilePath(),";"); file.close(); cout<<"\u001B[32m"<<"Generated the .csv successfully!"<<"\u001B[0m"<<endl; } catch(string t){ cerr<<"\u001B[31m"<<"Error : "<<"\u001B[0m"<<"Input file extension should be .gdf : ."<<t<<" Provided"<<endl; exit(0); } catch(int i){ if(i==404) cerr<<"\u001B[31m"<<"Error : "<<"\u001B[0m"<<"Couldn't find the file at the specified input path"<<endl; if(i==504) cerr<<"\u001B[31m"<<"Error : "<<"\u001B[0m"<<"Found some ambiguity in the input file"<<endl; exit(0); } }
Shell
UTF-8
4,260
3.28125
3
[]
no_license
#!/bin/bash # # This file is released under the terms of the Artistic License. # Please see the file LICENSE, included in this package, for details. # # Copyright (C) 2005 Jenny Zhang & Open Source Development Labs, Inc. # # # This file is modified for adding MySQL support. # # (c)Copyright 2006 Hewlett-Packard Development Company, L.P. # Copyright(c) Information-technology Promotion Agency, Japan. All rights reserved 2006. # Result of Open Source Software Development Activities # of Information-technology Promotion Agency, Japan. # DIR=`dirname $0` . ${DIR}/pgsql_profile || exit 1 USE_TABLESPACES=0 VARCHAR="VARCHAR" while getopts "ti" OPT; do case ${OPT} in t) USE_TABLESPACES=1 ;; i) VARCHAR="CHAR" ;; esac done PSQL="@PSQL@ -e -d ${SID} -c" if [ ${USE_TABLESPACES} -eq 1 ]; then TS_SUPPLIER_DIR="${TSDIR}/supplier/ts" TS_PART_DIR="${TSDIR}/part/ts" TS_PARTSUPP_DIR="${TSDIR}/partsupp/ts" TS_CUSTOMER_DIR="${TSDIR}/customer/ts" TS_ORDERS_DIR="${TSDIR}/orders/ts" TS_LINEITEM_DIR="${TSDIR}/lineitem/ts" TS_NATION_DIR="${TSDIR}/nation/ts" TS_REGION_DIR="${TSDIR}/region/ts" mkdir -p ${TS_SUPPLIER_DIR} mkdir -p ${TS_PART_DIR} mkdir -p ${TS_PARTSUPP_DIR} mkdir -p ${TS_CUSTOMER_DIR} mkdir -p ${TS_ORDERS_DIR} mkdir -p ${TS_LINEITEM_DIR} mkdir -p ${TS_NATION_DIR} mkdir -p ${TS_REGION_DIR} SUPPLIER_TABLESPACE="TABLESPACE dbt3_supplier" PART_TABLESPACE="TABLESPACE dbt3_part" PARTSUPP_TABLESPACE="TABLESPACE dbt3_partsupp" CUSTOMER_TABLESPACE="TABLESPACE dbt3_customer" ORDERS_TABLESPACE="TABLESPACE dbt3_orders" LINEITEM_TABLESPACE="TABLESPACE dbt3_lineitem" NATION_TABLESPACE="TABLESPACE dbt3_nation" REGION_TABLESPACE="TABLESPACE dbt3_region" ${PSQL} "CREATE ${SUPPLIER_TABLESPACE} LOCATION '${TS_SUPPLIER_DIR}';" ${PSQL} "CREATE ${PART_TABLESPACE} LOCATION '${TS_PART_DIR}';" ${PSQL} "CREATE ${PARTSUPP_TABLESPACE} LOCATION '${TS_PARTSUPP_DIR}';" ${PSQL} "CREATE ${CUSTOMER_TABLESPACE} LOCATION '${TS_CUSTOMER_DIR}';" ${PSQL} "CREATE ${ORDERS_TABLESPACE} LOCATION '${TS_ORDERS_DIR}';" ${PSQL} "CREATE ${LINEITEM_TABLESPACE} LOCATION '${TS_LINEITEM_DIR}';" ${PSQL} "CREATE ${NATION_TABLESPACE} LOCATION '${TS_NATION_DIR}';" ${PSQL} "CREATE ${REGION_TABLESPACE} LOCATION '${TS_REGION_DIR}';" fi ${PSQL} " CREATE TABLE supplier ( s_suppkey INTEGER, s_name CHAR(25), s_address $VARCHAR(40), s_nationkey INTEGER, s_phone CHAR(15), s_acctbal REAL, s_comment $VARCHAR(101)) ${SUPPLIER_TABLESPACE}; " || exit 1 ${PSQL} " CREATE TABLE part ( p_partkey INTEGER, p_name $VARCHAR(55), p_mfgr CHAR(25), p_brand CHAR(10), p_type $VARCHAR(25), p_size INTEGER, p_container CHAR(10), p_retailprice REAL, p_comment $VARCHAR(23)) ${PART_TABLESPACE}; " || exit 1 ${PSQL} " CREATE TABLE partsupp ( ps_partkey INTEGER, ps_suppkey INTEGER, ps_availqty INTEGER, ps_supplycost REAL, ps_comment $VARCHAR(199)) ${PARTSUPP_TABLESPACE}; " || exit 1 ${PSQL} " CREATE TABLE customer ( c_custkey INTEGER, c_name $VARCHAR(25), c_address $VARCHAR(40), c_nationkey INTEGER, c_phone CHAR(15), c_acctbal REAL, c_mktsegment CHAR(10), c_comment $VARCHAR(117)) ${CUSTOMER_TABLESPACE}; " || exit 1 ${PSQL} " CREATE TABLE orders ( o_orderkey INTEGER, o_custkey INTEGER, o_orderstatus CHAR(1), o_totalprice REAL, o_orderDATE DATE, o_orderpriority CHAR(15), o_clerk CHAR(15), o_shippriority INTEGER, o_comment $VARCHAR(79)) ${ORDERS_TABLESPACE}; " || exit 1 ${PSQL} " CREATE TABLE lineitem ( l_orderkey INTEGER, l_partkey INTEGER, l_suppkey INTEGER, l_linenumber INTEGER, l_quantity REAL, l_extendedprice REAL, l_discount REAL, l_tax REAL, l_returnflag CHAR(1), l_linestatus CHAR(1), l_shipDATE DATE, l_commitDATE DATE, l_receiptDATE DATE, l_shipinstruct CHAR(25), l_shipmode CHAR(10), l_comment $VARCHAR(44)) ${LINEITEM_TABLESPACE}; " || exit 1 ${PSQL} " CREATE TABLE nation ( n_nationkey INTEGER, n_name CHAR(25), n_regionkey INTEGER, n_comment $VARCHAR(152)) ${NATION_TABLESPACE}; " || exit 1 ${PSQL} " CREATE TABLE region ( r_regionkey INTEGER, r_name CHAR(25), r_comment $VARCHAR(152)) ${REGION_TABLESPACE}; " || exit 1 ${PSQL} " CREATE TABLE time_statistics ( task_name VARCHAR(40), s_time TIMESTAMP, e_time TIMESTAMP, int_time INTEGER); " || exit 1 exit 0
C++
UTF-8
446
2.6875
3
[]
no_license
#include "../externals/csvstream/csvstream.h" #include "containers.h" using namespace std; // Main Function int main() { std::vector<Data> pet_owners; std::string in_file = "../data/input.csv"; LoadData(pet_owners, in_file); //loop for (auto it = std::begin(pet_owners); it != std::end(pet_owners); ++it) { std::cout << it->id << "\t" << it->name << "\t" << it->animal << std::endl; } return 0; }
Java
UTF-8
2,816
2.1875
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package sna.controller.entities; import java.io.Serializable; import java.util.Date; import java.util.Set; import javax.enterprise.context.RequestScoped; import javax.inject.Named; import sna.repository.entities.Region; import sna.repository.entities.Sponsors; import sna.repository.entities.Animal; /** * * @author Jaimon TT */ @RequestScoped @Named(value = "event") public class Events implements Serializable { private int eventID; private String eventName; private String eventDescription; private Region regionID; private Animal animalID; private Date startingDate; private Date endingDate; private Sponsors sponsorID; public Events() { } public Events(int eventID, String eventName, String eventDescription, Region regionID, Animal animalID, Date startingDate, Date endingDate, Sponsors sponsorID) { this.eventID = eventID; this.eventName = eventName; this.eventDescription = eventDescription; this.regionID = regionID; this.animalID = animalID; this.startingDate = startingDate; this.endingDate = endingDate; this.sponsorID = sponsorID; } public String getEventDescription() { return eventDescription; } public void setEventDescription(String eventDescription) { this.eventDescription = eventDescription; } public int getEventID() { return eventID; } public void setEventID(int eventID) { this.eventID = eventID; } public String getEventName() { return eventName; } public void setEventName(String eventName) { this.eventName = eventName; } public Date getStartingDate() { return startingDate; } public void setStartingDate(Date startingDate) { this.startingDate =startingDate; } public Date getEndingDate() { return endingDate; } public void setEndingDate(Date endingDate) { this.endingDate = endingDate; } public Sponsors getSponsorID() { return sponsorID; } public void setSponsorID(Sponsors sponsorID) { this.sponsorID = sponsorID; } public Region getRegionID() { return regionID; } public void setRegionID(Region regionID) { this.regionID = regionID; } public Animal getAnimalID() { return animalID; } public void setAnimalID(Animal animalID) { this.animalID = animalID; } }
Java
UTF-8
321
3.234375
3
[]
no_license
package arrays; public class ArrayExample3 { public static void main(String[] args) { // TODO Auto-generated method stub int a[]= {50, 100, 150,200, 250}; int sum=0; for(int i:a) { sum= sum+i; //50 150 300 500 750 System.out.println(sum); } } }
Ruby
UTF-8
952
3.96875
4
[]
no_license
# Require allows us to pull in code from a gem into this file require "rest-client" require "pry" require "json" # Get a search term from the user def get_search_term puts "Please enter a search term: " gets.chomp end # Make a request to the API with the search term and parse the response into a hash def get_response(search_term) JSON.parse(RestClient.get("https://www.googleapis.com/books/v1/volumes?q=#{search_term}")) end # Get all of the books def get_books(response) response["items"] end # Get the title of a book def get_title(book) book["volumeInfo"]["title"] end # Iterate through all of the books and output the title for each one def print_all_titles(books) books.each do |book| puts get_title(book) end end # Run method - uses the other methods we've created to run our app def run search_term = get_search_term response = get_response(search_term) books = get_books(response) print_all_titles(books) end
Go
UTF-8
942
2.65625
3
[]
no_license
package main import ( "crypto/tls" "fmt" "github.com/Unknwon/goconfig" "gopkg.in/gomail.v2" ) func SendMail(subject string, body string) { var session string = "mail" c, err := goconfig.LoadConfigFile("set.ini") if err != nil { panic(err) } from, _ := c.GetValue(session, "from") tolist := c.MustValueArray(session, "to", ",") host, _ := c.GetValue(session, "host") port, _ := c.Int(session, "port") username, _ := c.GetValue(session, "username") password, _ := c.GetValue(session, "password") m := gomail.NewMessage() m.SetHeader("From", from) m.SetHeader("To", tolist...) m.SetHeader("Subject", subject) m.SetBody("text/html", body) d := gomail.NewDialer(host, port, username, password) d.TLSConfig = &tls.Config{InsecureSkipVerify: true} // Send the email if err := d.DialAndSend(m); err != nil { panic(err) } } func main() { SendMail("12345", "djjdei djei djeijdie jidjie ") fmt.Printf("fin\n") }
C++
UTF-8
7,021
3.046875
3
[]
no_license
#include "LevelFactory.h" #include <Core/Engine.h> float LevelFactory::generateNextLevel(int level, glm::vec2 resolution, std::vector<Object2D*>& objects) { while (!objects.empty()) { Object2D* tmpObj = objects.at(objects.size() - 1); objects.pop_back(); delete tmpObj; } float levelDurationSeconds = -100; // endless mode. switch (level) { case 1: levelDurationSeconds = generateLevel1(resolution, objects); printf("Press N to start level 1.\n"); break; case 2: levelDurationSeconds = generateLevel2(resolution, objects); printf("Press N to start level 2.\n"); break; default: generateEndless(resolution, objects); printf("Press N to start endless level.\n"); break; } printf("Press P to pause/unpause the game.\n"); return levelDurationSeconds; } float LevelFactory::generateLevel1(glm::vec2 resolution, std::vector<Object2D*>& objects) { // Obstacles objects.push_back(new Obstacle2D( glm::vec2(Constants::leftGroundEnd * 0.75f, resolution.y * 0.3f), Constants::obstacleLengthOx, Constants::obstacleWidthOy)); objects.push_back(new Obstacle2D( glm::vec2(Constants::leftGroundEnd * 0.85f, resolution.y * 0.75f), Constants::obstacleLengthOx, Constants::obstacleWidthOy * 1.3)); // Ox ground objects.push_back(new Obstacle2D( glm::vec2(0, 0), Constants::leftGroundEnd, Constants::groundWidth)); // Ox ground objects.push_back(new Obstacle2D( glm::vec2(Constants::exitHoleEnd, 0), resolution.x - Constants::exitHoleEnd, Constants::groundWidth)); // Oy wall objects.push_back(new Obstacle2D( glm::vec2(resolution.x - Constants::wallLength, 0), Constants::wallLength, resolution.y)); float x = Constants::leftGroundEnd + Constants::balloonRadius * 2; float y = -Constants::balloonRadius * 2; int delay = 2; glm::vec3 color; while (true) { int chance = (int)x % 96 + delay % 5; if (chance <= 50) { color = Constants::redBalloonColor; } else { color = Constants::yellowBalloonColor; } if (x >= Constants::exitHoleEnd - Constants::balloonRadius) break; float floatingSpeed = 100 + (int)x % 50 + (delay * 9) % 6; float spawnTime = (int)x % 9 + delay % 5; // seconds objects.push_back(new Balloon2D(glm::vec2(x, y), color, floatingSpeed, spawnTime, Constants::balloonRadius)); x += Constants::balloonRadius; ++delay; } return Constants::level1Duration; } float LevelFactory::generateLevel2(glm::vec2 resolution, std::vector<Object2D*>& objects) { objects.push_back(new Obstacle2D( glm::vec2(resolution.x - Constants::wallLength, 0), Constants::wallLength, Constants::wallWidth)); objects.push_back(new Obstacle2D( glm::vec2(resolution.x - Constants::wallLength, resolution.y - Constants::wallWidth), Constants::wallLength, Constants::wallWidth)); float x = resolution.x + Constants::shurikenRadius * 2; float y = Constants::wallWidth + Constants::shurikenRadius * 2; int stars = 2; glm::vec3 color; int maxStars = 7; int delay = 2; while (true) { int chance = (int)y % 96 + delay % 5; if (chance <= 50) { color = glm::vec3(0.95f, 0.975f, 0.975f); } else { color = glm::vec3(0.25f, 0.25f, 0.25f); } if (y >= resolution.y - Constants::wallWidth) break; float speed = 100 + (int)y % 50 + (9 * delay) % 21; float angularSpeed = speed + 200 + (maxStars - 1 - (stars % maxStars)) * 50; float spawnTime = (int)y % 9 + delay % 5; // seconds objects.push_back(new Shuriken2D(glm::vec2(x, y), speed, angularSpeed, stars % maxStars, spawnTime, Constants::shurikenRadius, color)); stars += (int)y % 32 + delay % 2; y += Constants::shurikenRadius; ++delay; } return Constants::level2Duration; } void LevelFactory::generateEndless(glm::vec2 resolution, std::vector<Object2D*>& objects) { objects.push_back(new Obstacle2D( glm::vec2(resolution.x - Constants::wallLength, 0), Constants::wallLength, Constants::wallWidth)); objects.push_back(new Obstacle2D( glm::vec2(resolution.x - Constants::wallLength, resolution.y - Constants::wallWidth), Constants::wallLength, Constants::wallWidth)); // Generate balloons { float x = Constants::leftGroundEnd + Constants::balloonRadius * 2; float y = -Constants::balloonRadius * 2; float levelDurationSeconds = 40; int delay = 2; glm::vec3 color; while (true) { int chance = (int)x % 96 + delay % 5; if (chance <= 50) { color = Constants::redBalloonColor; } else { color = Constants::yellowBalloonColor; } if (x >= Constants::exitHoleEnd - Constants::balloonRadius) break; float floatingSpeed = 100 + (int)x % 50 + (delay * 9) % 6; float spawnTime = (int)x % 9 + delay % 5; // seconds objects.push_back(new Balloon2D(glm::vec2(x, y), color, floatingSpeed, spawnTime, Constants::balloonRadius)); x += Constants::balloonRadius; ++delay; } } // Generate shurikens { float x = resolution.x + Constants::shurikenRadius * 2; float y = Constants::wallWidth + Constants::shurikenRadius * 2; float levelDurationSeconds = 30; int stars = 2; glm::vec3 color; int maxStars = 7; int delay = 2; while (true) { int chance = (int)y % 96 + delay % 5; if (chance <= 50) { color = glm::vec3(0.95f, 0.975f, 0.975f); } else { color = glm::vec3(0.25f, 0.25f, 0.25f); } if (y >= resolution.y - Constants::wallWidth) break; float speed = 300 + (int)y % 50 + (9 * delay) % 21; float angularSpeed = speed + 200 + (maxStars - 1 - (stars % maxStars)) * 50; float spawnTime = (int)y % 9 + (delay * 3) % 11; // seconds objects.push_back(new Shuriken2D(glm::vec2(x, y), speed, angularSpeed, stars % maxStars, spawnTime, Constants::shurikenRadius, color)); stars += (int)y % 32 + delay % 2; y += Constants::shurikenRadius * 4; ++delay; } } }
Markdown
UTF-8
1,419
3.953125
4
[]
no_license
### 206. Reverse Linked List - *Easy* #### 反转一个单链表 --- #### Code ``` # Java 双指针迭代 class Solution { public ListNode reverseList(ListNode head) { ListNode cur = head; ListNode pre = null; ListNode tmp = null; while(cur != null){ tmp = cur.next; cur.next = pre; pre = cur; cur = tmp; } return pre; } } # C++实现 class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* cur = head; ListNode* pre = nullptr; ListNode* tmp = nullptr; if(cur == nullptr) return nullptr; while(cur != nullptr){ tmp = cur->next; cur->next = pre; pre = cur; cur = tmp; } return pre; } }; ``` #### Note ##### 迭代 按正常顺序:1 - 2 - 3 - 4 - 5 设置头节点为`cur`,`pre`在`cur`前,`cur`为节点1时,`pre`指针指向`null`,随后移动两指针遍历链表,指针`cur`指向节点2时,`pre`指针指向节点1。此时1在2前。 但若想实现逆序,需要将原来的由节点1指向节点2改为节点2指向节点1。因此在遍历过程中将`pre`节点赋值给`cur.next`,然后`cur`节点将自己的值赋给`pre`节点,自己本身通过`tmp`节点的赋值向后移动。 遍历链表,实现逆序。 ![](image\迭代.gif)
C
UTF-8
972
3.015625
3
[]
no_license
#include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include "../general.h" int very_complex_function(char* password) { int result; char buffer[16]; result = 0; strcpy(buffer, password); if(strcmp(buffer, getflag()) == 0) result = 1; return result; } int main() { init(); char pass[64] = {0}; read(0, pass, 63); if(very_complex_function(pass)){ printf("Welcome back! Here is your token: %s\n", getflag()); } else { printf("Unauthorized user/passwd\n"); } } /* Similar to the exercise 3-Return Address. After drawing the stack we realise that the buffer is stored after the variable result so we can overwrite result. The result variable is at 0xbfffeedc and the buffer is at 0xbfffeecc So we need to write (0xbfffeedc - 0xbfffeecc) = 16 bytes plus the value 1 which will be \x01\x00\x00\x00 python -c "print 'A'*16 + '\x01\x00\x00\x00'" | nc mustard.stt.rnl.tecnico.ulisboa.pt 9994 */
Shell
UTF-8
492
3.359375
3
[]
no_license
#!/bin/bash #Pega a instancia pela tag nome id_instancia=$(aws ec2 describe-instances --filters "Name=tag:Name,Values=$1" --query 'Reservations[].Instances[].InstanceId' | tr -d '"' | tr -d '[' | tr -d ']') # Cria a imagem aws ec2 create-image --instance-id $id_instancia --name "$1_$(date +%F)" --description "$1" --no-reboot if [ $? -eq 0 ] then # Desliga a instancia aws ec2 stop-instances --instance-ids $id_instancia else echo "Favor colocar o nome correto da instância" fi
C#
UTF-8
1,287
3.859375
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //We are given a school. In the school there are classes class School : Comment { private readonly string Name; private List<Class> classes; public School(string name) { this.Name = name; classes = new List<Class>(); } //Classes have unique text identifier - verify it when adding a new class to the school's list public void AddAClassInTheSchool(Class cl) { Console.WriteLine("Adding a new class (\"{0}\") to the school's list:", cl.Name); bool isUnique = true; do { isUnique = true; foreach (var item in this.classes) { if (cl.Name == item.Name) { isUnique = false; break; } } if (!isUnique) { Console.Write("The class name \"{0}\" is not free. Please chose an unique name to this class: ", cl.Name); cl.Name = Console.ReadLine(); } } while (!isUnique); this.classes.Add(cl); Console.WriteLine("Adding completed."); Console.WriteLine(); } }
Java
UTF-8
11,661
2.03125
2
[]
no_license
package com.shidonghui.mymagic.model; /** * @author ZhangKun * @create 2019/6/11 * @Describe 用户信息 */ public class UserModel { /** * msg : null * rstCde : 0 * data : {"userId":"7011727918U","balance":5339.44,"cashCouponBalance":2337,"point1":0,"point":0,"cardBagCount":28,"realname":"张堃","idcardno":"1311****1610","titles":null,"avatar":"","avatarThumb":"","vipLevel":"SILVER","type":"PUPIL","nickname":"师董会测试导师11师资管理","msisdn":"18810431910","signature":"111","isFendaExpert":true,"company":"师董会北京","post":"还回家","isSigned":0,"isIdVerify":1,"isAlipayAttestation":0,"exepirence":5,"wxBind":"0","qqBind":"0","areaCode":"ss","shareWxTimelineCount":0,"signedNumber":"0","todaySignedNumber":5,"vipDueTime":"1605336262810","city":"保定","sex":"0","individualResume":"VB那你","rongToken":"nI3aQlYNMKAiuCiKXCSTkceKlmIDjPqt/tjAMngLO6QRuWNhcl1bKcPmG9eJMHYoh0JJhCtobm2jG9+wdaGOH6eSXGRbKRRB","inviteCode":"108532","creatGroupCount":0,"joinGroupCount":2,"friendCount":3,"isExpertCheck":0,"isAudit":1,"isPartner":0} */ private Object msg; private int rstCde; private DataBean data; public Object getMsg() { return msg; } public void setMsg(Object msg) { this.msg = msg; } public int getRstCde() { return rstCde; } public void setRstCde(int rstCde) { this.rstCde = rstCde; } public DataBean getData() { return data; } public void setData(DataBean data) { this.data = data; } public static class DataBean { /** * userId : 7011727918U * balance : 5339.44 * cashCouponBalance : 2337 * point1 : 0 * point : 0 * cardBagCount : 28 * realname : 张堃 * idcardno : 1311****1610 * titles : null * avatar : * avatarThumb : * vipLevel : SILVER * type : PUPIL * nickname : 师董会测试导师11师资管理 * msisdn : 18810431910 * signature : 111 * isFendaExpert : true * company : 师董会北京 * post : 还回家 * isSigned : 0 * isIdVerify : 1 * isAlipayAttestation : 0 * exepirence : 5 * wxBind : 0 * qqBind : 0 * areaCode : ss * shareWxTimelineCount : 0 * signedNumber : 0 * todaySignedNumber : 5 * vipDueTime : 1605336262810 * city : 保定 * sex : 0 * individualResume : VB那你 * rongToken : nI3aQlYNMKAiuCiKXCSTkceKlmIDjPqt/tjAMngLO6QRuWNhcl1bKcPmG9eJMHYoh0JJhCtobm2jG9+wdaGOH6eSXGRbKRRB * inviteCode : 108532 * creatGroupCount : 0 * joinGroupCount : 2 * friendCount : 3 * isExpertCheck : 0 * isAudit : 1 * isPartner : 0 */ private String userId; private double balance; private int cashCouponBalance; private int point1; private int point; private int cardBagCount; private String realname; private String idcardno; private Object titles; private String avatar; private String avatarThumb; private String vipLevel; private String type; private String nickname; private String msisdn; private String signature; private boolean isFendaExpert; private String company; private String post; private int isSigned; private int isIdVerify; private int isAlipayAttestation; private int exepirence; private String wxBind; private String qqBind; private String areaCode; private int shareWxTimelineCount; private String signedNumber; private int todaySignedNumber; private String vipDueTime; private String city; private String sex; private String individualResume; private String rongToken; private String inviteCode; private int creatGroupCount; private int joinGroupCount; private int friendCount; private int isExpertCheck; private int isAudit; private int isPartner; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } public int getCashCouponBalance() { return cashCouponBalance; } public void setCashCouponBalance(int cashCouponBalance) { this.cashCouponBalance = cashCouponBalance; } public int getPoint1() { return point1; } public void setPoint1(int point1) { this.point1 = point1; } public int getPoint() { return point; } public void setPoint(int point) { this.point = point; } public int getCardBagCount() { return cardBagCount; } public void setCardBagCount(int cardBagCount) { this.cardBagCount = cardBagCount; } public String getRealname() { return realname; } public void setRealname(String realname) { this.realname = realname; } public String getIdcardno() { return idcardno; } public void setIdcardno(String idcardno) { this.idcardno = idcardno; } public Object getTitles() { return titles; } public void setTitles(Object titles) { this.titles = titles; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getAvatarThumb() { return avatarThumb; } public void setAvatarThumb(String avatarThumb) { this.avatarThumb = avatarThumb; } public String getVipLevel() { return vipLevel; } public void setVipLevel(String vipLevel) { this.vipLevel = vipLevel; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getMsisdn() { return msisdn; } public void setMsisdn(String msisdn) { this.msisdn = msisdn; } public String getSignature() { return signature; } public void setSignature(String signature) { this.signature = signature; } public boolean isIsFendaExpert() { return isFendaExpert; } public void setIsFendaExpert(boolean isFendaExpert) { this.isFendaExpert = isFendaExpert; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getPost() { return post; } public void setPost(String post) { this.post = post; } public int getIsSigned() { return isSigned; } public void setIsSigned(int isSigned) { this.isSigned = isSigned; } public int getIsIdVerify() { return isIdVerify; } public void setIsIdVerify(int isIdVerify) { this.isIdVerify = isIdVerify; } public int getIsAlipayAttestation() { return isAlipayAttestation; } public void setIsAlipayAttestation(int isAlipayAttestation) { this.isAlipayAttestation = isAlipayAttestation; } public int getExepirence() { return exepirence; } public void setExepirence(int exepirence) { this.exepirence = exepirence; } public String getWxBind() { return wxBind; } public void setWxBind(String wxBind) { this.wxBind = wxBind; } public String getQqBind() { return qqBind; } public void setQqBind(String qqBind) { this.qqBind = qqBind; } public String getAreaCode() { return areaCode; } public void setAreaCode(String areaCode) { this.areaCode = areaCode; } public int getShareWxTimelineCount() { return shareWxTimelineCount; } public void setShareWxTimelineCount(int shareWxTimelineCount) { this.shareWxTimelineCount = shareWxTimelineCount; } public String getSignedNumber() { return signedNumber; } public void setSignedNumber(String signedNumber) { this.signedNumber = signedNumber; } public int getTodaySignedNumber() { return todaySignedNumber; } public void setTodaySignedNumber(int todaySignedNumber) { this.todaySignedNumber = todaySignedNumber; } public String getVipDueTime() { return vipDueTime; } public void setVipDueTime(String vipDueTime) { this.vipDueTime = vipDueTime; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getIndividualResume() { return individualResume; } public void setIndividualResume(String individualResume) { this.individualResume = individualResume; } public String getRongToken() { return rongToken; } public void setRongToken(String rongToken) { this.rongToken = rongToken; } public String getInviteCode() { return inviteCode; } public void setInviteCode(String inviteCode) { this.inviteCode = inviteCode; } public int getCreatGroupCount() { return creatGroupCount; } public void setCreatGroupCount(int creatGroupCount) { this.creatGroupCount = creatGroupCount; } public int getJoinGroupCount() { return joinGroupCount; } public void setJoinGroupCount(int joinGroupCount) { this.joinGroupCount = joinGroupCount; } public int getFriendCount() { return friendCount; } public void setFriendCount(int friendCount) { this.friendCount = friendCount; } public int getIsExpertCheck() { return isExpertCheck; } public void setIsExpertCheck(int isExpertCheck) { this.isExpertCheck = isExpertCheck; } public int getIsAudit() { return isAudit; } public void setIsAudit(int isAudit) { this.isAudit = isAudit; } public int getIsPartner() { return isPartner; } public void setIsPartner(int isPartner) { this.isPartner = isPartner; } } }
Markdown
UTF-8
716
2.65625
3
[]
no_license
# Article 48 Le pouvoir disciplinaire est exercé, à l'égard des magistrats du siège par le Conseil supérieur de la magistrature et à l'égard des magistrats du parquet ou du cadre de l'administration centrale du ministère de la justice par le garde des sceaux, ministre de la justice. Il est exercé à l'égard des magistrats en position de détachement ou de disponibilité ou ayant définitivement cessé leurs fonctions par la formation du Conseil supérieur compétente pour les magistrats du siège ou par le garde des sceaux, selon que ces magistrats ont exercé leurs dernières fonctions dans le corps judiciaire au siège ou au parquet et à l'administration centrale du ministère de la justice.
C++
UTF-8
5,388
2.53125
3
[]
no_license
/*************************************************************************** * Copyright (C) 2004 by Dynamol Inc. * * john.furr@dynamol.com * ***************************************************************************/ #include "cluster.h" #include "linAlg.h" #include <iomanip> clusterPoint::clusterPoint(int num, group *parent, vector<float> &coords, float radius, float energy) : point(num, coords, radius) { this->num = num; this->coords = coords; this->radius = radius; this->energy = energy; this->parent = parent; } clusterPoint::~clusterPoint() {} cluster::cluster() { } cluster::~cluster() { } void cluster::hierarchal(vector< vector<float> > &datMat, vector<float> &props, vector< vector< vector<float> > > &newClusters, int num) { /** This section organizes the data into groups of points */ vector<group *> Groups; datMat2Groups(datMat, props, Groups); /** This section forms a vector of points for use with the bsp */ vector<point *> Points; //vector<clusterPoint *> Points; for (int i=0; i<Groups.size(); i++) { Points.push_back(Groups[i]->Points[0]); } BSP *bsp = new BSP(3, Points); //////////////cout <<"Groups.size(): " << Groups.size() << endl; //////////////cout <<"Points.size(): " << Points.size() << endl; //////////////cout <<"bsp->count: " << bsp->count << endl; //////////////cout <<"bsp->avg: " << bsp->avg << endl; //closestPoints(bsp, point *p1, point *p2); int index1, index2; int sphereSize = 1; while (Groups.size() > num) { while (!closestGroups(Groups, bsp, index1, index2, sphereSize)) sphereSize++; mergeGroups(Groups, index1, index2); //////////////cout <<"Groups " << Groups.size() << setw(12) << sphereSize << endl; } groups2Clusters(Groups, newClusters); } void cluster::groups2Clusters(vector<group *> &Groups, vector< vector< vector<float> > > &newClusters) { newClusters.resize(Groups.size()); for (int i=0; i<Groups.size(); i++) { //////////////cout <<"Points: " << Groups[i]->Points.size() << endl; group *g = Groups[i]; newClusters[i].resize(g->Points.size()); for (int j=0; j<g->Points.size(); j++) { newClusters[i][j] = g->Points[j]->coords; } } } void cluster::mergeGroups(vector<group *> &Groups, int index1, int index2) { //////////////cout <<"Welcome to mergeGroups "<<index1 << setw(12) << index2 << setw(12) <<Groups.size() << endl; group *g1 = Groups[index1]; group *g2 = Groups[index2]; if (g1->Points[0]->energy < g2->Points[0]->energy) { for (int i=0; i<g2->Points.size(); i++) { g1->Points.push_back(g2->Points[i]); g2->Points[i]->parent = g1; } Groups.erase(Groups.begin()+index2); } else { for (int i=0; i<g1->Points.size(); i++) { g2->Points.push_back(g1->Points[i]); g1->Points[i]->parent = g2; } Groups.erase(Groups.begin()+index1); } } bool cluster::closestGroups(vector<group *> &Groups, BSP *bsp, int &index1, int &index2, int sphereSize) { float DIST = 1000000.0; float EDIFF = 10000000.0; int groupIndex = -1; int hitIndex = -1; //group *hitGroup; vector<point *> hits; for (int i=0; i < Groups.size(); i++) { hits.clear(); group *g = Groups[i]; //The first point is the one we compare to; point *centerPoint = g->centerPoint; clusterPoint *groupPoint = g->centerPoint; bsp->getPoints(centerPoint, hits, sphereSize); for (int j=0; j<hits.size(); j++) { float dist = bsp->distance(centerPoint->coords, hits[j]->coords); //float dist = dist2(centerPoint->coords, hits[j]->coords); if (dist <= DIST) { clusterPoint *tmp = reinterpret_cast<clusterPoint *>(hits[j]); float eDiff = fabs(groupPoint->energy - tmp->energy); if (eDiff < EDIFF && tmp->parent != g) { groupIndex = i; hitIndex = j; DIST = dist; int count = 1; EDIFF = eDiff; } } } } if (groupIndex == -1) { ////////////cout <<"Retuning false: " << sphereSize << endl; return false; } index1 = groupIndex; point *p = Groups[groupIndex]->centerPoint; hits.clear(); bsp->getPoints(p, hits, sphereSize); point *p2 = hits[hitIndex]; clusterPoint *cp2 = reinterpret_cast<clusterPoint *>(p2); group *closestGroup = cp2->parent; for (int i=0; i<Groups.size(); i++) { if (closestGroup == Groups[i]) { index2 = i; break; } } if (Groups[index1] == Groups[index2]) { ////////////cout <<"Major Problemo!"<<endl; //int test = 0; //cin >> test; } return true; } void cluster::datMat2Groups(vector< vector<float> > &datMat, vector<float> &props, vector<group *> &Groups) { for (int i=0; i<datMat.size(); i++) { //determine the effect of changing the size value...currently 1 group *g = new group; clusterPoint *p = new clusterPoint(i, g, datMat[i], 1, props[i]); g->Points.push_back(p); g->centerPoint = p; Groups.push_back(g); } }
TypeScript
UTF-8
1,630
2.875
3
[]
no_license
import fs from 'fs'; import path from 'path'; /* Обязательный аргумент передается просто ссылкой, например /home/roman/Документы/Git/Homework/ */ /* Глубина передается, через опциональный флаг --depth или -d */ const argv = process.argv.slice(2); const pathToDir = argv.find((elem) => !elem.includes('--depth=') || !elem.includes('-d=')); if (!pathToDir) { throw console.error('🤯🤯🤯', '\x1b[31m', 'Не указан обязательный аргумент "путь до директории"'); } const findDepth = argv.find((elem) => elem.includes('--depth=') || elem.includes('-d='))?.split('=')[1]; const d = Number.parseInt(findDepth || '0'); const depth = d < 0 || isNaN(d) ? 0 : d; const currentPath = path.resolve(pathToDir); function IterateTree(pathTree: string, number: number) { let iterate = number; fs.readdirSync(pathTree).forEach((elem, index) => { if (index === 0) { iterate = iterate + 1; } const stats = fs.statSync(path.resolve(pathTree, elem)); const isDirectory = stats.isDirectory(); const isFile = stats.isFile(); const symbolIterate = iterate - 1; if (isFile) { console.log('-'.repeat(symbolIterate), elem); } if (isDirectory && iterate <= depth) { console.log('-'.repeat(symbolIterate), '/', elem); const localPath = path.resolve(pathTree, elem); IterateTree(localPath, iterate); } else if (isDirectory) { console.log('-'.repeat(symbolIterate), '/', elem); } }); } IterateTree(currentPath, 0);
C#
UTF-8
1,494
2.734375
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; namespace Andersc.CodeLib.Common.Network { public static class HttpRequestHelper { public static string GetResponseText(string url, Browser browser = null, string httpMethod = "GET") { var request = WebRequest.Create(url) as HttpWebRequest; request.Method = httpMethod; if (browser.IsNull()) { browser = Browser.Firefox28; } request.UserAgent = browser.UserAgent; //request.Accept = browser.Accept; //request.Headers.Add(HttpRequestHeader.AcceptEncoding, browser.AcceptEncoding); //request.Headers.Add(HttpRequestHeader.AcceptLanguage, browser.AcceptLanguage); // request Charset. // TODO: Find suitable autoRedirections & timeout. request.MaximumAutomaticRedirections = 5; request.Timeout = 1000 * 6; using (var resp = request.GetResponse() as HttpWebResponse) { var reader = resp.CharacterSet.IsNull() ? new StreamReader(resp.GetResponseStream()) : new StreamReader(resp.GetResponseStream(), Encoding.GetEncoding(resp.CharacterSet)); var result = reader.ReadToEnd(); reader.Close(); return result; } } } }
PHP
UTF-8
8,887
2.515625
3
[ "Apache-2.0" ]
permissive
<?php namespace UUP\Web\Component\Collection; require_once('CollectionWrapper.php'); /** * Generated by PHPUnit_SkeletonGenerator on 2017-09-28 at 12:44:31. */ class CollectionTest extends \PHPUnit_Framework_TestCase { /** * @var Collection */ protected $object; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ protected function setUp() { $this->object = new CollectionWrapper(); } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. */ protected function tearDown() { } /** * @covers UUP\Web\Component\Collection\Collection::__set */ public function test__set() { $expect = 'value1'; $this->object->name1 = $expect; $actual = $this->object->data('name1'); self::assertNotNull($actual); self::assertEquals($actual, $expect); } /** * @covers UUP\Web\Component\Collection\Collection::__get */ public function test__get() { $expect = 'value1'; $this->object->set('name1', $expect); $actual = $this->object->name1; self::assertNotNull($actual); self::assertEquals($actual, $expect); } /** * @covers UUP\Web\Component\Collection\Collection::__toString */ public function test__toString() { $expect = 'name1=value1 name2=value2'; $this->object->set('name1', 'value1'); $this->object->set('name2', 'value2'); $actual = (string) $this->object; self::assertNotNull($actual); self::assertEquals($actual, $expect); } /** * @covers UUP\Web\Component\Collection\Collection::add */ public function testAdd() { // // Create new key: // $expect = 'value1'; $this->object->add('name1', 'value1'); $actual = $this->object->data('name1'); self::assertNotNull($actual); self::assertEquals($actual, $expect); // // Append to existing key: // $expect = 'value1 value2'; $this->object->add('name1', 'value2'); $actual = $this->object->data('name1'); self::assertNotNull($actual); self::assertEquals($actual, $expect); } /** * @covers UUP\Web\Component\Collection\Collection::set */ public function testSet() { // // Create new key: // $expect = 'value1'; $this->object->set('name1', 'value1'); $actual = $this->object->data('name1'); self::assertNotNull($actual); self::assertEquals($actual, $expect); // // Replace existing key value: // $expect = 'value2'; $this->object->set('name1', 'value2'); $actual = $this->object->data('name1'); self::assertNotNull($actual); self::assertEquals($actual, $expect); } /** * @covers UUP\Web\Component\Collection\Collection::get */ public function testGet() { $expect = 'value1'; $this->object->set('name1', 'value1'); $actual = $this->object->get('name1'); self::assertNotNull($actual); self::assertEquals($actual, $expect); } /** * @covers UUP\Web\Component\Collection\Collection::remove */ public function testRemove() { $expect = 'value1'; $this->object->set('name1', 'value1'); $actual = $this->object->get('name1'); self::assertNotNull($actual); self::assertEquals($actual, $expect); $expect = false; $this->object->remove('name1'); $actual = $this->object->get('name1'); self::assertNotNull($actual); self::assertEquals($actual, $expect); } /** * @covers UUP\Web\Component\Collection\Collection::exist */ public function testExist() { $expect = true; $this->object->set('name1', 'value1'); $actual = $this->object->exist('name1'); self::assertNotNull($actual); self::assertEquals($actual, $expect); $expect = false; $this->object->remove('name1'); $actual = $this->object->exist('name1'); self::assertNotNull($actual); self::assertEquals($actual, $expect); } /** * @covers UUP\Web\Component\Collection\Collection::find */ public function testFind() { $expect = false; $actual = $this->object->find('name1'); self::assertNotNull($actual); self::assertEquals($actual, $expect); $expect = 'value1'; $this->object->set('name1', 'value1'); $actual = $this->object->find('name1'); self::assertNotNull($actual); self::assertEquals($actual, $expect); $expect = false; $this->object->remove('name1'); $actual = $this->object->find('name1'); self::assertNotNull($actual); self::assertEquals($actual, $expect); } /** * @covers UUP\Web\Component\Collection\Collection::join */ public function testJoin() { $expect = 'name1=value1 name2=value2'; $this->object->set('name1', 'value1'); $this->object->set('name2', 'value2'); $actual = $this->object->join(); self::assertNotNull($actual); self::assertEquals($actual, $expect); } /** * @covers UUP\Web\Component\Collection\Collection::count */ public function testCount() { $expect = 0; $actual = $this->object->count(); self::assertNotNull($actual); self::assertEquals($actual, $expect); $expect = 1; $this->object->set('name1', 'value1'); $actual = $this->object->count(); self::assertNotNull($actual); self::assertEquals($actual, $expect); $expect = 1; $this->object->set('name1', 'value2'); $actual = $this->object->count(); self::assertNotNull($actual); self::assertEquals($actual, $expect); $expect = 1; $this->object->add('name1', 'value3'); $actual = $this->object->count(); self::assertNotNull($actual); self::assertEquals($actual, $expect); $expect = 2; $this->object->add('name2', 'value1'); $actual = $this->object->count(); self::assertNotNull($actual); self::assertEquals($actual, $expect); } /** * @covers UUP\Web\Component\Collection\Collection::clear */ public function testClear() { $expect = 1; $this->object->set('name1', 'value1'); $actual = $this->object->count(); self::assertNotNull($actual); self::assertEquals($actual, $expect); $expect = 2; $this->object->add('name2', 'value1'); $actual = $this->object->count(); self::assertNotNull($actual); self::assertEquals($actual, $expect); $this->object->clear(); $expect = 0; $actual = $this->object->count(); self::assertNotNull($actual); self::assertEquals($actual, $expect); } }
Markdown
UTF-8
419
2.828125
3
[ "MIT" ]
permissive
--- id: set-locale title: Set locale --- This filter can be used to change the value of current locale. By default, WordPress sets the locale in the admin to `en_US`. With this filter it can be changed to any locale (e.g. when using a multilingual plugin). ```php add_filter('es_forms_general_set_locale', function(string $locale): string { // Get the custom locale (e.g. from the WPML plugin). return $locale; })
C#
UTF-8
1,396
3.390625
3
[]
no_license
using System; using System.Collections.Generic; using EnsureThat; namespace DDD.Collections { /// <summary> /// Supports the comparison of objects for equality based on a key defined by a lambda expression. /// </summary> /// <typeparam name="TSource">The type of the source.</typeparam> /// <typeparam name="TKey">The type of the key.</typeparam> /// <seealso cref="IEqualityComparer{TSource}" /> public class KeyEqualityComparer<TSource, TKey> : IEqualityComparer<TSource> { #region Fields private readonly Func<TSource, TKey> keySelector; #endregion Fields #region Constructors public KeyEqualityComparer(Func<TSource, TKey> keySelector) { Ensure.That(keySelector, nameof(keySelector)).IsNotNull(); this.keySelector = keySelector; } #endregion Constructors #region Methods public bool Equals(TSource x, TSource y) { if (x == null || y == null) return (x == null && y == null); return object.Equals(keySelector(x), keySelector(y)); } public int GetHashCode(TSource obj) { if (obj == null) return int.MinValue; var k = keySelector(obj); if (k == null) return int.MaxValue; return k.GetHashCode(); } #endregion Methods } }
Markdown
UTF-8
2,099
3.21875
3
[]
no_license
# Frontend Mentor - Order summary card solution This is a solution to the [Order summary card challenge on Frontend Mentor](https://www.frontendmentor.io/challenges/order-summary-component-QlPmajDUj). Frontend Mentor challenges help you improve your coding skills by building realistic projects. ## Table of contents - [Overview](#overview) - [The challenge](#the-challenge) - [Screenshot](#screenshot) - [Links](#links) - [My process](#my-process) - [Built with](#built-with) - [What I learned](#what-i-learned) - [Continued development](#continued-development) - [Useful resources](#useful-resources) - [Author](#author) - [Acknowledgments](#acknowledgments) ## Overview ### The challenge Users should be able to: - See hover states for interactive elements ### Screenshot ![](./screenshot.png) ### Links - Solution URL: [https://v2ctor.github.io/fm-order-summary-component-task/](https://v2ctor.github.io/fm-order-summary-component-task/) ## My process ### Built with - BEM methodology - CSS Flex - CSS Grid ### What I learned I found out the CSS grid very straightforward and simple to use. (especially when you don't know much about CSS and layout!) ```css display: grid; grid-template-areas: ". header ." ". content ." ". attr ."; ``` ### Continued development I want to keep focused on using CSS Grid and Flexbox. I'm not (yet) completely comfortable with them, but I definitely like their simplicity :) ### Useful resources - [BEM methodology resource](https://ru.bem.info/methodology/html/) - This helped me understand what BEM is and why it's cool. - [A Complete Guide to Grid](https://css-tricks.com/snippets/css/complete-guide-grid/) - This made me interested in CSS Grid and I personally liked it better than Flexbox. ## Author - GitHub - [v2ctor](https://github.com/v2ctor) - Frontend Mentor - [@v2ctor](https://www.frontendmentor.io/profile/v2ctor) ## Acknowledgments A huge shoutout to [Netlighter](https://github.com/Netlighter) for motivating me and helping me through the completion of this task, even though it's pretty simple!
Java
UTF-8
7,670
2.40625
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ims.servlet.image; import ims.entity.Image; import ims.management.ImageManagement; import ims.management.LoginManagement; import ims.management.ResizeImage; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.rmi.ServerException; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** *This servlet allow contributor to upload a new image * @author andrazhribernik */ @WebServlet(name = "UploadImage", urlPatterns = {"/UploadImage"}) public class UploadImage extends HttpServlet { // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.print("Upload image GET"); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LoginManagement lm = new LoginManagement(request.getSession()); lm.userPermissionForThisPage(response, new String[]{"contributor"}); // Verify the content type String contentType = request.getContentType(); ServletContext cntx= getServletContext(); File file ; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; if ((contentType.indexOf("multipart/form-data") >= 0)) { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File(cntx.getRealPath("temp"))); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax( maxFileSize ); try{ ImageManagement im = new ImageManagement(); // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); Integer price = new Integer(0); String name = ""; while ( i.hasNext () ) { FileItem item = (FileItem)i.next(); if(!item.isFormField()){ name = new File(item.getName()).getName(); //check if image with the same name exists if(!im.isImageNameEmpty(name, lm.getUser())){ response.sendRedirect("./uploadImage.jsp?fileMessage=This image name already exists."); return; } String extension = ""; if(name.matches("(.*)\\.jpg$")){ extension = "jpg"; } else if(name.matches("(.*)\\.png$")){ extension = "png"; } else{ //if extension is not .png or .jpg inform user about an error. response.sendRedirect("./uploadImage.jsp?fileMessage=Wrong file format."); return; } for(String size : new String[]{"300","600","1200"}){ String imagePath = "Images"+File.separator+size+File.separator+lm.getUser().getUsername()+File.separator+name; String filename = cntx.getRealPath(imagePath); System.out.println(filename); File newImage = new File(filename); if (!newImage.getParentFile().exists()) newImage.getParentFile().mkdirs(); if(!newImage.canWrite()){ newImage.setWritable(true); } BufferedImage originalImage = ImageIO.read(item.getInputStream()); int type = originalImage.getType() == 0? BufferedImage.TYPE_INT_ARGB : originalImage.getType(); BufferedImage resizeImagePng = ResizeImage.resizeImage(originalImage, type, Integer.valueOf(size)); //save image to file system ImageIO.write(resizeImagePng, extension, newImage); } } else{ if(item.getFieldName().equals("price")){ try{ Double inputPrice = Double.valueOf(item.getString()); price = ((Double)(inputPrice.doubleValue() * 100)).intValue(); } catch (Exception e){ response.sendRedirect("./uploadImage.jsp?priceMessage=Incorect price format."); return; } } } } //store new image into database with specified price Image img = new Image(); img.setDate(new Date()); img.setName(name); img.setUseridUser(lm.getUser()); img.setPrice(price); im.addImage(img); }catch(Exception ex) { ex.printStackTrace(); response.sendRedirect("./uploadImage.jsp?fileMessage=Error during uploading file."); return; } }else{ throw new ServerException("This Servlet only handles file upload request"); } response.sendRedirect("./uploadImage.jsp?successMessage=You uploaded new image successfully."); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
Python
UTF-8
5,496
3.46875
3
[]
no_license
import numpy as np import nengo import grid map = ''' ######### # # # # # # # # # # # # # # ######### ''' # this defines the world the agent is in, based on the map above class Cell(grid.Cell): def load(self, c): if c == '#': self.wall = True def color(self): if self.wall: return 'black' # this is for creating a new type of object in the environment class Food(grid.ContinuousAgent): color = 'green' shape = 'circle' # now we actuall make the world world = grid.World(Cell, map=map, directions=4) body = grid.ContinuousAgent() world.add(body, x=2, y=2, dir=1) # create the body for the agent world.add(Food(), x=2, y=4) # create the other objects in the world world.add(Food(), x=4, y=4) # this is the sensory system. It takes objects from the environment and # figures out where they are, returning the result as a vector that nengo # can then use. # # The sensory information is divided into "what" (information about what the # object is -- which in this case is just its color) and "where" (information # about the location of the object -- which in this case is cos(theta)/dist and # sin(theta)/dist). Note that we're dividing by distance, so a large value means # that the object is very close, and a small value means it is far away) class State(nengo.Node): def __init__(self, body): self.body = body super(State, self).__init__(self.update) def compute_angle_and_distance(self, obj): angle = (body.dir-1) * 2 * np.pi / 4 dy = obj.y - self.body.y dx = obj.x - self.body.x obj_angle = np.arctan2(dy, dx) theta = angle - obj_angle dist = np.sqrt(dy**2 + dx**2) return theta, dist def update(self, t): where = [] what = [] color_map = dict(green=1, red=-1) self.n_objects = 0 for obj in world.agents: if obj is not self.body: angle, dist = self.compute_angle_and_distance(obj) color = color_map[obj.color] if dist < 1: dist = 1.0 r = 1.0/dist where.extend([np.sin(angle)*r, np.cos(angle)*r]) what.extend([color]) self.n_objects += 1 return what+where # now we actually build the nengo model. model = nengo.Network() with model: # create a display for the world env = grid.GridNode(world) # create motor neurons and motor outputs for turning and going forward body_speed = nengo.Node(lambda t, x: body.go_forward(x[0]*0.01), size_in=1) body_turn = nengo.Node(lambda t, x: body.turn(x[0]*0.003), size_in=1) turn = nengo.Ensemble(n_neurons=50, dimensions=1) speed = nengo.Ensemble(n_neurons=50, dimensions=1) nengo.Connection(speed, body_speed) nengo.Connection(turn, body_turn) # create sensors and neurons to hold the sensors. We are using an # EnsembleArray so that there are separate neurons to store the information # for each object. sensors = State(body) what = nengo.networks.EnsembleArray(n_ensembles=sensors.n_objects, ens_dimensions=1, n_neurons=50) where = nengo.networks.EnsembleArray(n_ensembles=sensors.n_objects, ens_dimensions=2, n_neurons=100, intercepts=nengo.dists.Uniform(0.1, 1.0)) nengo.Connection(sensors[:sensors.n_objects], what.input, synapse=None) nengo.Connection(sensors[sensors.n_objects:], where.input, synapse=None) # Now let's implement the simplest possible behaviour: turn towards objects. def turn_towards(x): if x[0] < -0.1: return 1 elif x[0] > 0.1: return -1 else: return 0 # do the above function for all the objects for i in range(sensors.n_objects): nengo.Connection(where.ensembles[i], turn, function=turn_towards) def printer(t, sinCosArray): printer._nengo_html_ = "<p>Some Data:\n"+str(sinCosArray)+"</p>" ball_size = find_distance(sinCosArray) printer._nengo_html_ += "<p>Distance: "+str(ball_size)+"</p>" def find_distance(sinCosArray): sin = sinCosArray[0] cos = sinCosArray[1] r = np.sqrt(sin*sin+cos*cos) return r def stop_if_r_is_large(sinCosArray): size = find_distance(sinCosArray) if size > 0.95: return 1 else: return 0 def stop_speed(x): if x > 0.5: return -0.3 else: return 0 # TODO Make a display node display = nengo.Node(printer, size_in=2) nengo.Connection(where.ensembles[0], display) #nengo.Connection(where.ensembles[1], display) # Stop node stop = nengo.Ensemble(n_neurons=50, dimensions=1) for i in range(len(where.ensembles)): nengo.Connection(where.ensembles[i], stop, function=stop_if_r_is_large) nengo.Connection(stop, speed, function=stop_speed) # and let's just move forward at a fixed speed. fixed_speed = nengo.Node(0.3) nengo.Connection(fixed_speed, speed)
Python
UTF-8
324
3.515625
4
[]
no_license
from datetime import datetime now = datetime.now() fecha = "%02d/%02d/%04d" % (now.day, now.month, now.year) # En formato DD/MM/YYYY hora = "%02d:%02d:%02d" % (now.hour, now.minute, now.second) # En formato HH:MM:SS #Imprime el mensaje con día y hora: print("La fecha de hoy es " + fecha + ", y son las " + hora + ".")
PHP
UTF-8
3,084
2.671875
3
[]
no_license
<?php session_start(); $servername = "localhost"; $username = "root"; $password = "happypappy"; $dbname = "shoes4days"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } //if not logged in redirect to login page if($_SESSION["loggedIn"] != TRUE) { header("Location:login.php"); } $uname = $_SESSION["username"]; $qry = mysqli_query($conn, "SELECT username FROM Employees WHERE username='$uname'"); $row = mysqli_fetch_array($qry); ?> <p align="right">Welcome, <?php echo $uname?>! <a href="logout.php">Logout</a></p> <html> <title>W3.CSS</title> <?php include_once 'config.php'; ?> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <body> <!-- Sidebar --> <div class="w3-sidebar w3-light-grey w3-bar-block" style="width:20%"> <h3 class="w3-bar-item"><a href="admin.php" class="w3-bar-item w3-button">Menu</a></h3> <a href="#" class="w3-bar-item w3-button">Customers</a> <a href="orders.php" class="w3-bar-item w3-button">Orders</a> <a href="shoes.php" class="w3-bar-item w3-button">Shoes</a> <a href="employees.php" class="w3-bar-item w3-button">Employees</a> <a href="reviews.php" class="w3-bar-item w3-button">Reviews</a> <a href="dbManage.php" class="w3-bar-item w3-button">Database Management</a> </div> <!-- Page Content --> <div style="margin-left:20%"> <div class="w3-container w3-teal"> <h1>Death By Shoes</h1> </div> <div class="w3-container"> <h2>CUSTOMERS</h2> <br> <br> <style> table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; } </style> <body> <table> <tr> <th>Customer ID</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> <th>Phone Number</th> </tr> <?php $sql = "SELECT * FROM Customer;"; $result = mysqli_query($db, $sql); $check = mysqli_num_rows($result); if($check > 0) { while($row = mysqli_fetch_assoc($result)) { echo "<tr>"; echo "<td>" . $row['customerID'] . "</td>"; echo "<td>" . $row['fname'] . "</td>"; echo "<td>" . $row['lname'] . "</td>"; echo "<td>" . $row['email'] . "</td>"; echo "<td>" . $row['phone_number'] . "</td>"; echo "<tr>"; } } ?> </table> <br> <br> <h3>Add a Customer</h3> <form action="/customer_action.php" method="POST"> First name:<br> <input type="text" name="firstname" placeholder="Enter First Name"> <br> Last name:<br> <input type="text" name="lastname" placeholder="Enter Last Name"> <br> Email:<br> <input type="email" name="email" placeholder="Enter Email"> <br> Phone Number:<br> <input type="text" name="phone" placeholder="Enter Phone Number"> <br> <br> <button type="submit" name="submit">Submit</button> </form> </div> </div> </body> </html>
PHP
UTF-8
1,931
2.640625
3
[ "MIT" ]
permissive
<?php namespace Filament\Tables\Columns; use Illuminate\Support\Facades\Storage; use League\Flysystem\AwsS3v3\AwsS3Adapter; class Image extends Column { use Concerns\CanCallAction; use Concerns\CanOpenUrl; public $disk; public $height = 40; public $width; public $rounded = false; protected function setUp() { $this->disk(config('forms.default_filesystem_disk')); } public function disk($disk) { $this->disk = $disk; return $this; } public function height($height) { $this->height = $height; return $this; } public function getHeight() { if ($this->height === null) return null; if (is_integer($this->height)) return "{$this->height}px"; return $this->height; } public function getWidth() { if ($this->width === null) return null; if (is_integer($this->width)) return "{$this->width}px"; return $this->width; } public function getPath($record) { $path = $this->getValue($record); if (! $path) return null; if (filter_var($path, FILTER_VALIDATE_URL) !== false) { return $path; } $storage = Storage::disk($this->disk); if ( $storage->getDriver()->getAdapter() instanceof AwsS3Adapter && $storage->getVisibility($path) === 'private' ) { return $storage->temporaryUrl( $path, now()->addMinutes(5), ); } return $storage->url($path); } public function rounded() { $this->rounded = true; return $this; } public function size($size) { $this->width = $size; $this->height = $size; return $this; } public function width($width) { $this->width = $width; return $this; } }
Python
UTF-8
63
3.34375
3
[]
no_license
lst=[] for i in range(1,11): lst.append(i**3) print(lst)
Java
UTF-8
1,490
2.15625
2
[]
no_license
package com.evgeniibaibakov.jinbot.bot.command; import com.evgeniibaibakov.jinbot.bot.processing.Command; import com.pengrad.telegrambot.request.BaseRequest; import lombok.extern.log4j.Log4j; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.LinkedList; import java.util.List; import java.util.Optional; @Configuration @Log4j public class CommandConfiguration implements ApplicationContextAware { private ApplicationContext applicationContext; @Bean List<Command> commands() { LinkedList<Command> commands = new LinkedList<>(); converter("pomodoReply").ifPresent(commands::add); converter("pomodoStatusReply").ifPresent(commands::add); converter("defaultReply").ifPresent(commands::add); return commands; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } private Optional<Command> converter(String name) { try { return Optional.ofNullable(applicationContext.getBean(name)) .map(Command.class::cast); } catch (Exception e) { log.error(e); } return Optional.empty(); } }
Markdown
UTF-8
1,792
3.53125
4
[]
no_license
# HTML Images Whenever you build a website, most likely you will need to add images to your site to include a logo, photograph, illustration, diagram, or chart in your site. HTML is the responsible part for adding images to websites. To add images to a web page we use the \<img> element without closing tag. In the \<img> tag there is a mandatory attribute called src. Src refers to the path of the image you eant to include either it was alink or it was inside your project folder. Beside src, we have alt attribute to describe the content of an image in case of website can not load the image. # CSS Color Color not only brings your site to life, but also helps convey the mood and evokes reactions. In computer, red, green and blue RGB are the basic colors and any other colors are a mix of these three colors. So identify a new color you need to select three values: R, G and B. Instead of selecting three values we can directly write the color by normal name or by hex code. For example: rgb values (102,205,170), hex code #66cdaa and Color Name MediumAquaMarine will revloute to the samw color. In css we have many attributes that takes color as a value such as font color and background color. In CSS3 new HSL colors was intrduced. HSL is a shortcut for hue, saturation and lightness. The things that makes HSL better than the others that HSL is noe selecting the color only, but it is used to select the color including the contrast value which was specified seperatly before HSL. ## Color Example body { background-color: silver; color: white; } # CSSText One of the important things to style in your web site is the text. Text Chapter 5: “Images” (pp.94-125) Chapter 11: “Color” (pp.246-263) Chapter 12: “Text” (pp.264-299)
Markdown
UTF-8
1,813
3.515625
4
[ "MIT" ]
permissive
--- title: Execute Bash in Docker date: '2019-07-25' category: Docker --- 在 Docker 开发的过程中,有时会有脚本出错,导致执行结果不及预期的情况。这种错误有时是环境导致的,在非 Docker 环境下无法重现。如果需要通过构建 Docker 添加诸如日志之类的信息来了解具体可能出错的原因,不免有些曲折。可以考虑直接在 Docker 环境下运行 Bash 命令,通过执行脚本中的语句,来查找可能出现问题的原因。 要在 Docker 环境下执行 Bash 脚本,可以遵循以下的步骤: 1. 首先,需要知道当前运行 Docker 的容器 ID ```bash docker container ls ``` 上述命令会列出所有的容器,找到需要调试的那一个即可。 2. 在该容器环境内执行 Bash 命令 ```bash docker exec -ti xxx /bin/bash ``` 这里,`xxx` 就是第一步找到的 Container ID。上述命令用到了两个参数,`-t` 和 `-i`。`-t` 是 `--tty` 的缩写,用于让 Docker 将用户的终端和 stdin/stdout 关联起来;`-i` 是 `--interactive` 的缩写,用于让 Docker 在执行命令的时候允许用户进行交互式的输入输出。 如果只是希望执行一个语句并输出结果(比如 `echo` 一个字符串),那么 `-t` 就足够了,不需要 `-i`。但是对于需要在 Docker 环境下输入 Bash 命令并检查执行结果的情况来说,`-i` 就是必须的。 一个输出 Hello World 的简单例子: ```bash docker exec -t echo "hello world" ``` 另外,可以通过如下的命令知道,`docker exec` 运行的默认环境是在 `/` 下: ```bash docker exec -t pwd # output: / ``` 如需修改这一默认行为,可以通过 `-w` 参数(或 `--workdir`)来执行: ```bash docker exec -w /root -t xxx pwd # output: /root ```
C++
UTF-8
2,099
3.953125
4
[]
no_license
// Лабораторная 9, 1 упражнение // Даны значения температуры, наблюдавшиеся в течение N подряд идущих дней. // Найдите номера дней (в нумерации с нуля) со значением температуры выше среднего арифметического за все N дней. #include <iostream> #include <vector> using namespace std; int countAverageTemp(vector<int> temperature_vector){ int sum = 0; // Сумма температур for (int temperature : temperature_vector) { sum+=temperature; } return sum/temperature_vector.size(); } int main() { vector<int> temperature; // температура во все дни vector<int> highTemperature; // температура в дни превышающая среднюю vector<int> dayNumbers; // номера дней в которые температура превышала заданную, да это можно сделать через hashmap int counterDay; int valueTemperature; int average; // Средняя температура cout << "Введите количество дней: " << endl; cin >> counterDay; cout << "Теперь введите значение температуры для каждого дня" << endl; for (int i = 1; i <= counterDay; i++) { cout << "Введите значение температуры для " << i << " дня: "; cin >> valueTemperature; temperature.push_back(valueTemperature); } average = countAverageTemp(temperature); for (int i = 0; i < temperature.size(); i++) { if(temperature[i] > average) { highTemperature.push_back(temperature[i]); dayNumbers.push_back(i+1); } } for (int day = 0; day < dayNumbers.size(); day++) { cout << "номер дня: " << dayNumbers[day] << " "; cout << " температура в этот день - " << highTemperature[day] << endl; counterDay++; } }
C#
UTF-8
1,460
2.5625
3
[]
no_license
using Ecom.Domain.Entities; using Ecom.Repositories; using System; using System.Threading.Tasks; using Xunit; namespace Ecom.Tests.Integration.Repositorories { public class ProductRepositoryTests { private readonly IMongoDbService mongoDbService; private ProductRepository productRepository; public ProductRepositoryTests() { mongoDbService = new MongoDbService(new TestConfig()); } [Fact] public async Task Should_SaveProduct() { productRepository = new ProductRepository(mongoDbService); var product = new Product { Id = Guid.NewGuid().ToString(), Description = "Product-1", Category = new ProductCategory() { Id = Guid.NewGuid().ToString(), CategoryName = "Category-1" }, Price = 100 }; await productRepository.SaveProduct(product); } [Fact] public async Task Should_UpdateProduct() { productRepository = new ProductRepository(mongoDbService); string existingProductId = "b1a4844d-93ae-416d-a6f0-9dfd89b0ba61"; var product = new Product { Id = existingProductId, Description = "Product-200", Price = 200 }; await productRepository.SaveProduct(product); } } }