language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
PHP
UTF-8
4,349
2.703125
3
[]
no_license
<?php //header("Content-Type: application/vnd.ms-excel"); //header("Content-disposition: attachment; filename=spreadsheet.xls"); $api_key = "b5e3b32b4d29d45c16dc09274e099f731237e35f"; //Lora key $job_id = "146522"; $unit_id = "227816726"; function objectToArray($obj) { if (is_object($obj)) { $obj = get_object_vars($obj); } if (is_array($obj)) { return array_map(__FUNCTION__, $obj); } else { return $obj; } } /* transforms the time and date in a more readable format */ function formatDateAndTime($input) { list($date, $time) = explode('T', $input); list($year, $month, $day) = explode('-', $date); list($exact_time, $nothing) = explode('+', $time); $output = $month . "/" . $day . "/" . $year . " " . $exact_time; return $output; } /* parse the response for extracting the relation between terms */ function extractChoice($input) { $pattern = "/\[[A-Za-z\_\:]*\]/"; preg_match($pattern, $input, $matches); $choice = str_replace(":", "", $matches[0]); return $choice; } /* see the channels that are used */ $channels_query = "curl \"https://api.crowdflower.com/v1/jobs/$job_id/channels?key=$api_key\""; $result = exec($channels_query); print_r($result); // enabled_channels":["amt","crowdguru","mob"] /* get all the units from a job */ $units_list_query = "curl \"https://api.crowdflower.com/v1/jobs/$job_id/units.json?key=$api_key\""; $result_exec = exec($units_list_query); $result = objectToArray(json_decode($result_exec)); /* save the units id */ $units_id = array_keys($result); /* print results into files; for linux*/ $user = posix_getuid(); $userinfo = posix_getpwuid($user); $fp_results = fopen($userinfo["dir"]."/results.csv", 'w'); $fp_overview = fopen($userinfo["dir"]."/overview.csv", 'w'); $table_header_results = array('unit_id', 'worker_id', 'worker_trust', 'external_type', 'step_1_select_the_valid_relations', 'step_2b_if_you_selected_none_in_step_1_explain_why', 'step_2a_copy__paste_only_the_words_from_the_sentence_that_express_the_relation_you_selected_in_step1', 'started_at', 'created_at', 'term1', 'term2', 'sentence'); $table_header_overview = array('job_id', 'unit_id', 'created_at', 'updated_at', 'agreement', 'agg', 'confidence', 'difficulty', 'term1', 'term2', 'sentence'); fputcsv($fp_results, $table_header_results); fputcsv($fp_overview, $table_header_overview); /* get all the information about an unit */ for ($i = 0; $i < count($units_id); $i ++) { $unit_query = "curl \"https://api.crowdflower.com/v1/jobs/$job_id/units/$units_id[$i].json?key=$api_key\""; $result_exec = exec($unit_query); $result = objectToArray(json_decode($result_exec)); $results = $result["results"]; $judgments = $results["judgments"]; $row_overview = array($result["job_id"], $result["id"], formatDateAndTime($result["created_at"]), formatDateAndTime($result["updated_at"]), $result["agreement"], extractChoice($result["results"]["step_1_select_the_valid_relations"]["agg"]), $result["results"]["step_1_select_the_valid_relations"]["confidence"], $result["difficulty"], $result["data"]["term1"], $result["data"]["term2"], $result["data"]["sentence"]); fputcsv($fp_overview, $row_overview); for ($j = 0; $j < count($judgments); $j ++) { $row_result = array($judgments[$j]["unit_id"], $judgments[$j]["worker_id"], $judgments[$j]["worker_trust"], $judgments[$j]["external_type"]); $choices = ""; for ($k = 0; $k < count($judgments[$j]["data"]["step_1_select_the_valid_relations"]); $k ++) { $choices .= extractChoice($judgments[$j]["data"]["step_1_select_the_valid_relations"][$k]) . "\n"; } $choices = substr($choices, 0, -1); array_push($row_result, $choices, $judgments[$j]["data"]["step_2b_if_you_selected_none_in_step_1_explain_why"], $judgments[$j]["data"]["step_2a_copy__paste_only_the_words_from_the_sentence_that_express_the_relation_you_selected_in_step1"], formatDateAndTime($judgments[$j]["started_at"]), formatDateAndTime($judgments[$j]["created_at"]), $judgments[$j]["unit_data"]["term1"], $judgments[$j]["unit_data"]["term2"], $judgments[$j]["unit_data"]["sentence"]); fputcsv($fp_results, $row_result); } } fclose($fp_results); fclose($fp_overview); /* download the .csv file with the results */ $result_file = "curl \"https://api.crowdflower.com/v1/jobs/$job_id.csv?key=$api_key&full=true\""; //$result = exec($result_file); //print_r($result); ?>
Shell
UTF-8
1,816
3.109375
3
[]
no_license
#!/bin/bash function rollback-analytics-db { echo "================rollback analytics db start $(date +%T)==========" if [ ! -e /var/log/deploy/${ENVIRONMENT} ] then mkdir -p /var/log/deploy/${ENVIRONMENT} fi psql postgres -c "\q" &>/dev/null if [ $? -ne 0 ];then su - postgres -c "createuser --superuser root" &>/dev/null fi echo "================rollback analytics db start $(date +%T)==========" >> /var/log/deploy/$ENVIRONMENT/err_rollback_analytics_db_${BACKUP_NAME}.log if [ -e /tmp/${ANALYTICS_DATABASE}_${BACKUP_NAME}.dump ] then cd /tmp dropdb ${ANALYTICS_DATABASE} && createdb -O dealtap ${ANALYTICS_DATABASE} pg_restore -l /tmp/${ANALYTICS_DATABASE}_${BACKUP_NAME}.dump >/tmp/analytics.list sed -i -e '/MATERIALIZED VIEW DATA public data_vm_deal_activity dealtap$/{h;d;};/MATERIALIZED VIEW DATA public data_vm_deal_historic dealtap$/G' /tmp/analytics.list pg_restore -d ${ANALYTICS_DATABASE} -L /tmp/analytics.list /tmp/${ANALYTICS_DATABASE}_${BACKUP_NAME}.dump &>> /var/log/deploy/$ENVIRONMENT/err_rollback_analytics_db_${BACKUP_NAME}.log if [ $? -eq 0 ] then echo "rollback analytics db success" rm -f /tmp/analytics.list rm -f /tmp/${ANALYTICS_DATABASE}_${BACKUP_NAME}.dump else echo "rollback analytics db faild" echo "rollback analytics db faild" >> /var/log/deploy/$ENVIRONMENT/err_rollback_analytics_db_${BACKUP_NAME}.log exit 1 fi else echo "rollback analytics db faild,backup-file no find" echo "rollback analytics db faild,backup-file no find" >> /var/log/deploy/$ENVIRONMENT/err_rollback_analytics_db_${BACKUP_NAME}.log exit 1 fi }
Markdown
UTF-8
1,549
2.828125
3
[ "Apache-2.0" ]
permissive
Import Kibana dashboard for centralized logging and configure it. **Table of Contents:** - [Create a Basic & CloudTrail Logging Dashboard](#create-a-basic--cloudtrail-logging-dashboard) - [Expected Outcome](expected-outcome) ## Create a Basic & CloudTrail Logging Dashboard 1. Login to Centralized Logging Kibana URL using the credentials saved earlier. 2. Navigate to Settings -- Indices and create a new index ussing the following configuration. * Click the checkbox named "Use event times to create index names" * Leave 'Index Pattern Interval' as 'Daily' * In the 'Index Name or pattern' field enter `[cwl-]YYYY.MM.DD` * Select `@timestamp` for 'Time-field name' field. 3. After creating the index, navigate to 'Objects' in the top tab. 4. Click Import and select the saved dashboard file [logging-dashboard-with-cloudtrail.json](../LoggingDashboards/logging-dashboard-with-cloudtrail.json) located in `LoggingDashboards` directory. 5. Once it got imported successfully, there should be 2 dashboards, 5 searches and 13 visualizations which can be validated in the Objects tab of Settings. > NOTE: Ignore if it throws any error (we are re-using old dashboard available in quick start). 6. Navigate to dashboard and view the two saved dashboards 'Basic' & 'CloudTrail'. ## Expected Outcome * Successfully imported the saved dashboard in your Kibana instance. * Able to view Basic & CloudTrail dashboard in Kibana. ![configure-logging-dashboard-image](../images/configure-logging-dashboard.png)
JavaScript
UTF-8
1,563
2.625
3
[]
no_license
var express = require('express'); var Item = require('../models/Item'); var Location = require('../models/Location'); const router = express.Router(); router.route('/') .post(function(req, res){ console.log("POST: /items"); var item = new Item(); item.name = req.body.name; item.price = req.body.price; item.location = req.body.location; item.description = req.body.description; item.save(function(err, itemDocument){ if(err){ console.log(err); res.send(err); return; } console.log(itemDocument); res.send(itemDocument); }) }) .get(function(req, res) { console.log("GET: /items"); Location.find({ 'name': req.query.location }, function(err, location) { if (err) { console.log("Error finding location " + location); res.send(err); } Item.find({ 'location': location[0]._id }) .sort('name') .exec(function(err, items) { if (err) { console.log("Error getting items for location " + location); res.send(err); } console.log(items); res.send(items); }) }); }) router.route('/:id') .get(function(req, res) { console.log("GET: get item with id " + req.params.id); Item.findById(req.params.id, function(err, item) { if (err) { console.log("Error getting item " + req.params.id); res.send(err); } console.log(item); res.send(item) }); }) module.exports = router;
C#
UTF-8
1,960
2.609375
3
[]
no_license
using MySql.Data.MySqlClient; using System; namespace GVRP.Module.Teams.AmmoArmory { public class AmmoArmorieItem : Loadable<uint> { public UInt32 Id { get; set; } public UInt32 AmmoArmorieId { get; set; } public UInt32 ItemId { get; set; } public int RequiredPackets { get; set; } public int TeamPrice { get; set; } public AmmoArmorieItem(MySqlDataReader reader) : base(reader) { Id = reader.GetUInt32("id"); AmmoArmorieId = reader.GetUInt32("ammoarmorie_id"); ItemId = reader.GetUInt32("item_id"); RequiredPackets = reader.GetInt32("required_packets"); TeamPrice = reader.GetInt32("team_price"); } public override uint GetIdentifier() { return Id; } public void ChangeTeamPrice(int newprice) { TeamPrice = newprice; MySQLHandler.ExecuteAsync($"UPDATE team_ammoarmories_items SET team_price = '{TeamPrice}' WHERE id = '{Id}'"); } public int GetRequiredPacketsForTeam(DbTeam dbTeam) { if (dbTeam.TeamMetaData.Respect >= 6000) { return RequiredPackets - 6; } else if (dbTeam.TeamMetaData.Respect >= 5000) { return RequiredPackets - 5; } else if (dbTeam.TeamMetaData.Respect >= 4000) { return RequiredPackets - 4; } else if (dbTeam.TeamMetaData.Respect >= 3000) { return RequiredPackets - 3; } else if (dbTeam.TeamMetaData.Respect >= 2000) { return RequiredPackets - 2; } else if (dbTeam.TeamMetaData.Respect >= 1000) { return RequiredPackets - 1; } else return RequiredPackets; } } }
PHP
UTF-8
474
3.046875
3
[]
no_license
<?php echo convertSeconds(3407) . " This was called before the functions was created <br />"; function convertSeconds($seconds) { $minutes = floor($seconds / 60); $seconds = $seconds % 60; $seconds = ($seconds < 10) ? '0' . $seconds : $seconds; return "$minutes:$seconds"; } echo convertSeconds(547) . '<br/>'; echo convertSeconds(550) //if the function is in an external file you need to include the file before you can call the function ?>
C
UTF-8
3,114
2.796875
3
[]
no_license
#pragma once #include <stm32f103xb.h> #include <sys/_stdint.h> /** * \brief Режим работы DMA */ typedef enum { DmaModePeriphToMem = 0 << 4, DmaModeMemToPeriph = 1 << 4, DmaModeMemToMem = 1 << 14 }DmaMode; /** * \brief Приоритет канала DMA */ typedef enum { DmaPriorityLow = 0 << 12, DmaPriorityMedium = 1 << 12, DmaPriorityHigh = 2 << 12, DmaPriorityVeryHigh = 3 << 12 }DmaPriority; /** * \brief Размер данных приёмника и передатчика (см п.13.3.4 RM0008). */ typedef enum { DmaSizeConfMem8bitPeriph8bit = 0 << 10 | 0 << 8, DmaSizeConfMem8bitPeriph16bits = 0 << 10 | 1 << 8, DmaSizeConfMem8bitPeriph32bits = 0 << 10 | 2 << 8, DmaSizeConfMem16bitsPeriph8bit = 1 << 10 | 0 << 8, DmaSizeConfMem16bitsPeriph16bits = 1 << 10 | 1 << 8, DmaSizeConfMem16bitsPeriph32bits = 1 << 10 | 2 << 8, DmaSizeConfMem32bitsPeriph8bit = 2 << 10 | 0 << 8, DmaSizeConfMem32bitsPeriph16bits = 2 << 10 | 1 << 8, DmaSizeConfMem32bitsPeriph32bits = 2 << 10 | 2 << 8 }DmaSizeConf; /** * \brief Режим автоинкремента адресов приёмника и передатчика (см п.13.4.3 RM0008). */ typedef enum { DmaIncrementModeIncOff = 0 << 6, DmaIncrementModeIncPeriph = 1 << 6, DmaIncrementModeIncMem = 2 << 6, DmaIncrementModeIncMemAndPeriph = 3 << 6 }DmaIncrementMode; /** * \brief Канал DMA, для абстаргирования от типов данных CMSIS. */ typedef DMA_Channel_TypeDef DmaChannel; /** * \brief Функция настройки канала DMA. * \param dma Канал DMA, который будем настраивать. * \param mode Режим передачи данных. * \param priority Приоритет канала. * \param size Размер данных приёмника и отправителя. * \param incMode Настройки автоинкремента адресов. */ inline void DmaConfigureChannel(DmaChannel* dma, DmaMode mode, DmaPriority priority, DmaSizeConf size, DmaIncrementMode incMode) { dma->CCR &= ~0x1FFF; dma->CCR |= mode | priority | size | incMode; } /** * \brief Установка адреса регистра перефирии, откуда/куда брать/класть данные. * \param dma Канал DMA, который будем настраивать. * \param addr Адрес регистра. */ inline void DmaSetPeripheralRegister(DmaChannel* dma, volatile uint32_t* addr) { dma->CPAR = (uint32_t)addr; } /** * \brief Установка адреса регистра в памяти, откуда/куда брать/класть данные. * \param dma Канал DMA, который будем настраивать. * \param addr Адрес регистра. */ inline void DmaSetMemoryRegister(DmaChannel* dma, volatile uint32_t* addr) { dma->CMAR = (uint32_t)addr; } /** * \brief Разрешить тактирование блока DMA1 */ inline void Dma1ClockEnable() { RCC->AHBENR |= RCC_AHBENR_DMA1EN; }
Python
UTF-8
2,565
3.125
3
[]
no_license
class Stmt(object): pass class PrintStmt(Stmt): def __init__(self, exp): self.exp = exp class InputStmt(Stmt): def __init__(self, nome): self.id = nome class LetStmt(Stmt): def __init__(self, nome, e): self.id = nome self.exp = e class IfStmt(Stmt): def __init__(self, c, corpo): self.cond = c self.body = corpo class WhileStmt(Stmt): def __init__(self, c, corpo): self.cond = c self.body = corpo class Expr(object): pass class IdExpr(Expr): def __init__(self, nome): self.id = nome class StringExpr(Expr): def __init__(self, s): self.str = s class ArithExpr(Expr): pass class SumExpr(ArithExpr): def __init__(self, ladoEsquerdo, ladoDireito): self.left = ladoEsquerdo self.right = ladoDireito class SubExpr(ArithExpr): def __init__(self, ladoEsquerdo, ladoDireito): self.left = ladoEsquerdo self.right = ladoDireito class MulExpr(ArithExpr): def __init__(self, ladoEsquerdo, ladoDireito): self.left = ladoEsquerdo self.right = ladoDireito class DivExpr(ArithExpr): def __init__(self, ladoEsquerdo, ladoDireito): self.left = ladoEsquerdo self.right = ladoDireito class UnaryPlusExpr(ArithExpr): def __init__(self, e): self.exp = e class UnaryMinusExpr(ArithExpr): def __init__(self, e): self.exp = e class NumExpr(ArithExpr): def __init__(self, valor): self.v = valor class BooleanExpr(Expr): pass class EqualsExpr(BooleanExpr):# left == right def __init__(self, ladoEsquerdo, ladoDireito): self.left = ladoEsquerdo self.right = ladoDireito class NotEqualsExpr(BooleanExpr):# left != right def __init__(self, ladoEsquerdo, ladoDireito): self.left = ladoEsquerdo self.right = ladoDireito class GreaterThanEqualsExpr(BooleanExpr):# left >= right def __init__(self, ladoEsquerdo, ladoDireito): self.left = ladoEsquerdo self.right = ladoDireito class GreaterThanExpr(BooleanExpr):# left > right def __init__(self, ladoEsquerdo, ladoDireito): self.left = ladoEsquerdo self.right = ladoDireito class LessThanEqualsExpr(BooleanExpr):# left <= right def __init__(self, ladoEsquerdo, ladoDireito): self.left = ladoEsquerdo self.right = ladoDireito class LessThanExpr(BooleanExpr):# left < right def __init__(self, ladoEsquerdo, ladoDireito): self.left = ladoEsquerdo self.right = ladoDireito
Java
UTF-8
790
2.921875
3
[]
no_license
package tcp; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.Socket; public class TcpSender { public static void main(String[] args) throws Exception { String sentence; String repl; for (int i = 0; i < 10000; i++) { Socket socket = new Socket("localhost", 6789); DataOutputStream out = new DataOutputStream(socket.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String msg = "AbraKadabra\n"; out.writeBytes(msg); out.flush(); repl = in.readLine(); // System.out.println("reply: " + repl); socket.close(); } } }
Python
UTF-8
418
3.1875
3
[]
no_license
import numpy as np """point, origo line distance Inputs: - oline: ndarray, line through origo, essentially just one 3d point as a vector - points: ndarray, array of 3d points in homogeneous form ref: https://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html """ def p_ol_dist(oline, points): return np.linalg.norm(np.cross(points, points - oline, axis=1), axis=1) / np.linalg.norm(oline)
C
UTF-8
465
3.59375
4
[]
no_license
#include "float_bits.h" typedef unsigned float_bits; /* If f is denorm, return 0. Otherwise, return f */ float_bits float_denorm_zero(float_bits f) { /* Decompose bit representation into parts */ unsigned sign = f>>31; unsigned exp = f>>23 & 0xFF; unsigned frac = f & 0x7FFFFF; if (exp == 0) { /* Denormalized. Set fraction to 0 */ frac = 0; } /* Reassemble bits */ return (sign << 31) | (exp << 23) | frac; }
JavaScript
UTF-8
1,330
3.1875
3
[]
no_license
const canvas = document.querySelector("#draw"); const ctx = canvas.getContext("2d"); canvas.width = window.innerWidth; canvas.height = window.innerHeight; ctx.strokeStyle = "#BADA55"; ctx.lineJoin = "round"; ctx.lineCap = "round"; ctx.lineWidth = 50; ctx.globalCompositeOperation = "multiply"; // this is like photoshop blend mode let isDrawing = false; //This like a flag //set when drawing let lastX = 0, lastY = 0; //These are the //coordinates of start point let hue = 0; let direction = true; function draw(e) { if (!isDrawing) return; //stop fuction from running // when mouse button is not down ctx.strokeStyle = `hsl(${hue},100%,50%)`; ctx.beginPath(); ctx.moveTo(lastX, lastY); ctx.lineTo(e.offsetX, e.offsetY); ctx.stroke(); [lastX, lastY] = [e.offsetX, e.offsetY]; hue++; if (hue > 360) hue = 0; if (ctx.lineWidth >= 100 || ctx.lineWidth <= 1) { direction = !direction; } if (direction) ctx.lineWidth++; else ctx.lineWidth--; } //setInterval(()=>hue = Math.round(Math.random()*360),500); canvas.addEventListener("mousemove", draw); canvas.addEventListener("mousedown", (e) => { isDrawing = true; [lastX, lastY] = [e.clientX, e.clientY]; draw; }); canvas.addEventListener("mouseup", () => (isDrawing = false)); canvas.addEventListener("mouseout", () => (isDrawing = false));
Python
UTF-8
4,317
3.90625
4
[]
no_license
import random def madlib(dictionaries): ''' creates and prints out three madlibs (unicorn, shakespeare, princess) on 'r' uses preferably known words from the English dictionary the module can be exited by entering 'm' during any input request Parameters ---------- dictionaries : list dictionaries[0] = German dictionary dictionaries[1] = English dictionary ''' inp = "" while inp != "m": inp = input() if inp == "r": noun_all = [] noun_known = [] adjective_all = [] adjective_known = [] verb_all = [] verb_known = [] for entry in dictionaries[1]: if dictionaries[1][entry][1] == "(noun)": noun_all.append(entry) # list of all English nouns in the dictionary if dictionaries[1][entry][2][3] == "k": noun_known.append(entry) # list of all known English nouns in the dictionary elif dictionaries[1][entry][1] == "(adj.)": adjective_all.append(entry) if dictionaries[1][entry][2][3] == "k": adjective_known.append(entry) elif dictionaries[1][entry][1] == "(verb)": verb_all.append(entry) if dictionaries[1][entry][2][3] == "k": verb_known.append(entry) else: print("That's not a type I know.") ### UNICORN MADLIB ### # check if there are enough known words for this madlib in the respective list noun = noun_all if len(noun_known) < 3 else noun_known adjective = adjective_all if len(adjective_known) < 2 else adjective_known verb = verb_all if len(verb_known) < 1 else verb_known print("\nUNICORN MADLIB") print("--------------") print("A unicorn is nothing like a(n) " + (random.choice(noun)) + ". \nThey're " + random.choice(adjective) + " creatures. \nSome have a(n) " + random.choice(noun) + " mane of hair and others \nhave a(n) " + random.choice(adjective) + " " + random.choice(noun) + " on their head. \nI would love " + random.choice(verb) + " a unicorn one day.") ### SHAKESPEARE MADLIB ### noun = noun_all if len(noun_known) < 2 else noun_known adjective = adjective_all if len(adjective_known) < 1 else adjective_known verb = verb_all if len(verb_known) < 1 else verb_known print("\nSHAKESPEARE MADLIB") print("------------------") print ("To be, or not to be, that is the question: \n" "Whether 'tis " + (random.choice(adjective)) + " in the mind " + random.choice(verb) + "\n" + "The slings and " + random.choice(noun) + " of outrageous fortune, \n" "Or to take arms against a " + random.choice(noun) + " of trouble \n" "And by opposing end them.") ### PRINCESS MADLIB ### noun = noun_all if len(noun_known) < 1 else noun_known adjective = adjective_all if len(adjective_known) < 3 else adjective_known verb = verb_all if len(verb_known) < 1 else verb_known print("\nPRINCESS MADLIB") print("---------------") print ("There once lived a " + (random.choice(adjective)) + " princess in a " + (random.choice(adjective)) + " castle. \n" "Her favorite hobby and greatest passion was it " + (random.choice(verb)) + ". \nShe did it every day and night.\n" "One day she won a competition in this discipline. \nThe first prize was a " + random.choice(noun) + " and she war very " + (random.choice(adjective)) + " about it.") elif inp == "m": print("You're back in the main menu.") break else: print("You can't do that here. Chose either r or m.")
Go
UTF-8
2,715
3.046875
3
[]
no_license
package main import ( "bytes" "encoding/csv" "encoding/json" "flag" "fmt" "io/ioutil" "log" "math" "os" "strconv" "time" "github.com/tormoder/fit" ) // print the contents of the obj func PrettyPrint(data interface{}) { var p []byte p, err := json.MarshalIndent(data, "", "\t") if err != nil { fmt.Println(err) return } fmt.Printf("%s \n", p) } func convertToMinutes(m float64) string { minutes, secondsdecimal := math.Modf(m) seconds := secondsdecimal * 60 return fmt.Sprintf("%02.0f:%02.0f", minutes, seconds) } func cInt(i int) string { v := strconv.Itoa(i) return v } func cInt8(i int8) string { v := strconv.Itoa(int(i)) return v } func cUint8(i uint8) string { v := strconv.Itoa(int(i)) return v } func cDecimal(f float64) string { v := strconv.FormatFloat(f, 'f', -1, 64) return v } func cTime(t time.Time) string { v := t.String() return v } func cDuration(d time.Duration) string { v := d.String() return v } func main() { // Read our FIT test file data testFilePtr := flag.String("file", "file.fit", "the FIT file name") flag.Parse() fmt.Println("I will open FIT file:", *testFilePtr) testData, err := ioutil.ReadFile(*testFilePtr) if err != nil { log.Fatalln("error reading fit file:", err) return } // Decode the FIT file data fit, err := fit.Decode(bytes.NewReader(testData)) if err != nil { log.Fatalln("error decoding fir file:", err) return } w := csv.NewWriter(os.Stdout) // Inspect the TimeCreated field in the FileId message log.Println("TIME CREATED:", fit.FileId.TimeCreated) // Inspect the dynamic Product field in the FileId message log.Println("PRODUCT:", fit.FileId.GetProduct()) // Inspect the FIT file type log.Println("FIT TYPE:", fit.Type()) // Get the actual activity activity, err := fit.Activity() if err != nil { log.Fatalln("error writing record to csv:", err) return } idx := 0 t0 := time.Now() for _, record := range activity.Records { idx++ if idx == 1 { t0 = record.Timestamp } x := []string{ cInt(idx), cDecimal(record.PositionLat.Degrees()), cDecimal(record.PositionLong.Degrees()), cInt8(record.Temperature), cTime(record.Timestamp), cDuration(record.Timestamp.Sub(t0)), cUint8(record.Cadence), cDecimal(record.GetDistanceScaled() / 1000), "km", cDecimal(record.GetAltitudeScaled()), "m", cUint8(record.HeartRate), "HR bpm", convertToMinutes(16.666666666667 / record.GetSpeedScaled()), "min/km", cDecimal(record.GetSpeedScaled() * 3.6), "km/h", } w.Write(x) } w.Flush() // Print the sport of the first Session message for _, session := range activity.Sessions { log.Println("SESSION SPORT:", session.Sport) } }
C
SHIFT_JIS
26,667
2.640625
3
[]
no_license
/* ATmega644PpvO */ /* AVR PlayStationController */ /* Dualshock2Ή */ /* SwitchRecv[]̃JbRɂ03܂œB SwitchRecv[]ɂ̓vXẽ{^16i AĂ悤ɂȂĂB ႦΎg{^ƂB if(SwitchRecv[1] == 0x01); Ƃ邱ƂŁ{^Ƃ̖߂Ƃ”\B ̃{^͉L̕\Q SwitchRecv[0] == 0x01 SELECT 0x10 L[ 0x02 L3 0x20 L[ 0x04 R3 0x40 L[ 0x08 START 0x80 L[ SwitchRecv[1] == 0x01 L2 0x10 0x02 R2 0x20 0x04 L1 0x40 ~ 0x08 R1 0x80 SwitchRecv[2] AiOXeBbNLx0`255iS127j SwitchRecv[3] AiOXeBbNLy0`255iS127j */ #ifndef F_CPU #define F_CPU 8000000UL #endif #include <avr/io.h> #include <avr/interrupt.h> #include <util/delay.h> #include <stdlib.h> #include <stdbool.h> /* PSRg[[{^` */ #define l1 SwitchRecv[1]==0x04 #define r1 SwitchRecv[1]==0x08 #define l2 SwitchRecv[1]==0x01 #define r2 SwitchRecv[1]==0x02 #define l3 SwitchRecv[0]==0x02 //L3, R3̓AiOXeBbN̉݃{^ #define r3 SwitchRecv[0]==0x04 #define start SwitchRecv[0]==0x08 #define select SwitchRecv[0]==0x01 #define analog_r_x SwitchRecv[2] // 0 < S127 < E255 #define analog_r_y SwitchRecv[3] // 0 < S127 < 255 #define analog_l_x SwitchRecv[4] // 0 < S127 < E255 #define analog_l_y SwitchRecv[5] // 0 < S127 < 255 volatile uint16_t SwitchRecv[8]; //SwitchRecv[]O[oϐŐ錾 // ========================================================================== // PlayStation Rg[[ ֐ // ========================================================================== #define PS_UP 4 #define PS_RIGHT 5 #define PS_DOWN 6 #define PS_LEFT 7 #define PS_L2 0 #define PS_R2 1 #define PS_L1 2 #define PS_R1 3 #define PS_TRIANGLE 4 #define PS_CIRCLE 5 #define PS_CROSS 6 #define PS_SQUARE 7 // L[Ă邩Ԃ inline bool ps_top(void){ return SwitchRecv[0] & _BV(PS_UP); } // EL[Ă邩Ԃ inline bool ps_right(void){ return SwitchRecv[0] & _BV(PS_RIGHT); } // L[Ă邩Ԃ inline bool ps_bottom(void){ return SwitchRecv[0] & _BV(PS_DOWN); } // L[Ă邩Ԃ inline bool ps_left(void){ return SwitchRecv[0] & _BV(PS_LEFT); } // L2 L[Ă邩Ԃ inline bool ps_l2(void){ return SwitchRecv[1] & _BV(PS_L2); } // R2 L[Ă邩Ԃ inline bool ps_r2(void){ return SwitchRecv[1] & _BV(PS_R2); } // L1 L[Ă邩Ԃ inline bool ps_l1(void){ return SwitchRecv[1] & _BV(PS_L1); } // R1 L[Ă邩Ԃ inline bool ps_r1(void){ return SwitchRecv[1] & _BV(PS_R1); } // L[Ă邩Ԃ inline bool ps_triangle(void){ return SwitchRecv[1] & _BV(PS_TRIANGLE); } // ~L[Ă邩Ԃ inline bool ps_cross(void){ return SwitchRecv[1] & _BV(PS_CROSS); } // L[Ă邩Ԃ inline bool ps_circle(void){ return SwitchRecv[1] & _BV(PS_CIRCLE); } // L[Ă邩Ԃ inline bool ps_square(void){ return SwitchRecv[1] & _BV(PS_SQUARE); } /**********^b`ZT[֘A**********/ bool up_touch(void){ return PINB & _BV(0); } bool down_touch(void){ return PINB & _BV(1); } bool right_touch(void){ return PINB & _BV(2); } bool left_touch(void){ return PINB & _BV(5); } /** UARTݒ **/ // Ho׎CKDIV8(1/8MHz)ƂȂĂ̂FusesCKDIV8͂ #define FOSC 8000000 // 8MHz #define BAUD 38400 // 38400bpsȂATTiny2313MMłȂ #define MYUBRR FOSC/16/BAUD-1 // UART /* USARTݒ */ void usart_init(unsigned int ubrr){ UBRR0H = (unsigned char)(ubrr>>8); // {[[g8bit UBRR0L = (unsigned char)ubrr; // {[[g8bit UCSR0A = (0<<U2X0); // UCSR0B = (1<<RXEN0)|(1<<TXEN0)|(1<<RXCIE0); // MAM荞݋ UCSR0C = (0<<UMSEL00)|(3<<UCSZ00)|(1<<USBS0)|(0<<UPM00); // t[ݒ 񓯊ʐM 8rbg 1Xgbvrbg peB } /* NoOperation */ void nop(int count){ int i; for(i = 0; i < count; i++){ _delay_ms(100); } } /* inťԂ */ char getDigit(int n){ char i; i = 0; while(n>0){ n /= 10; i++; } return i; } /* int->Stringϊ */ char *intToStr(int n, char *buf){ // ϊ鐔AƗ̈ int i, digit; if(n == 0){ buf[0] = '0'; buf[1] = '\0'; return buf; } digit = getDigit(n); // for(i = digit-1; i >= 0; i--){ // int͍ő5 buf[i] = n%10+'0'; n /= 10; } buf[digit] = '\0'; // ss return buf; } /* USARTŕ񑗐M */ void usart_sendStr(char *str){ while(*str != '\0'){ loop_until_bit_is_set(UCSR0A,UDRE0); // Mf[^WX^󂫂܂őҋ@ UDR0 = *str++; // 1MA1i } } /* ATTiny2313PSRg[[̐MM */ ISR(USART0_RX_vect){ static uint16_t buff; uint16_t data,temp; data = UDR0; if(!(data & 0x08)){ buff = data; return; } if((data & 0x07)==(buff & 0x07)){ temp = buff & 0xF0; temp |= data >> 4; SwitchRecv[data & 0x07] = temp; } } int A0_number; int A0_number, B0_number; int A1_number, B1_number; int A2_number, B2_number; char buf[6]; /*----------------------胂[^[֐---------------------------*/ //0A,0B: E[^[ //2A,2B: [^[ void strat0(int s, int st){ int i, a = 0; A0_number = s; B0_number = 0; A2_number = s; B2_number = 0; for(i = 0; i < st; i++){ /* usart_sendStr(" "); usart_sendStr("0A:"); usart_sendStr(intToStr(A0_number,buf)); usart_sendStr(" "); usart_sendStr("0B:"); usart_sendStr(intToStr(B0_number,buf)); usart_sendStr(" "); usart_sendStr("2A:"); usart_sendStr(intToStr(A2_number,buf)); usart_sendStr(" "); usart_sendStr("2B:"); usart_sendStr(intToStr(B2_number,buf));; usart_sendStr("\r\n"); // s */ A0_number = A0_number + 1; A2_number = A2_number + 1; // a = a + 1; /* if(a > 10){ A2_number = A2_number + 1; } */ OCR0A = A0_number; OCR0B = B0_number; PORTB |= _BV(1); PORTB |= _BV(2); OCR2A = A2_number; OCR2B = B2_number; PORTD |= _BV(2); PORTD |= _BV(3); _delay_ms(2); if(!ps_top()){ break; } } } void strat1(int s){ /* usart_sendStr(" "); usart_sendStr("0A:"); usart_sendStr(intToStr(A0_number,buf)); usart_sendStr(" "); usart_sendStr("0B:"); usart_sendStr(intToStr(B0_number,buf)); usart_sendStr(" "); usart_sendStr("2A:"); usart_sendStr(intToStr(A2_number,buf)); usart_sendStr(" "); usart_sendStr("2B:"); usart_sendStr(intToStr(B2_number,buf));; usart_sendStr("\r\n"); // s */ A0_number = s - 5; B0_number = 0; A2_number = s; B2_number = 0; OCR0A = A0_number; OCR0B = B0_number; PORTB |= _BV(1); PORTB |= _BV(2); OCR2A = A2_number; OCR2B = B2_number; PORTD |= _BV(2); PORTD |= _BV(3); } void strat_stop(){ int i; A0_number = 255; B0_number = 0; A2_number = 255; B2_number = 0; for(i = 0; i < 128; i++){ /* usart_sendStr(" "); usart_sendStr("0A:"); usart_sendStr(intToStr(A0_number,buf)); usart_sendStr(" "); usart_sendStr("0B:"); usart_sendStr(intToStr(B0_number,buf)); usart_sendStr(" "); usart_sendStr("2A:"); usart_sendStr(intToStr(A2_number,buf)); usart_sendStr(" "); usart_sendStr("2B:"); usart_sendStr(intToStr(B2_number,buf));; usart_sendStr("\r\n"); // s */ B0_number = B0_number + 2; B2_number = B2_number + 2; OCR0A = A0_number; OCR0B = B0_number; PORTB &= ~_BV(1); PORTB &= ~_BV(2); OCR2A = A2_number; OCR2B = B2_number; PORTD &= ~_BV(2); PORTD &= ~_BV(3); _delay_ms(1); } } void back0(int s, int bt){ int i, a = 0; A0_number = 0; B0_number = s; A2_number = 0; B2_number = s; for(i = 0; i < bt; i++){ B0_number = B0_number + 1; B2_number = B2_number + 1; // a = a + 1; /* if(a > 10){ B2_number = B2_number + 1; } */ OCR0A = A0_number; OCR0B = B0_number; PORTB |= _BV(1); PORTB |= _BV(2); OCR2A = A2_number; OCR2B = B2_number; PORTD |= _BV(2); PORTD |= _BV(3); _delay_ms(2); if(!ps_bottom()){ break; } } } void back1(int s){ A0_number = 0; B0_number = s; A2_number = 0; B2_number = s - 5; OCR0A = A0_number; OCR0B = B0_number; PORTB |= _BV(1); PORTB |= _BV(2); OCR2A = A2_number; OCR2B = B2_number; PORTD |= _BV(2); PORTD |= _BV(3); } void back_stop(){ int i; A0_number = 0; B0_number = 255; A2_number = 0; B2_number = 255; for(i = 0; i < 128; i++){ A0_number = A0_number + 2; A2_number = A2_number + 2; OCR0A = A0_number; OCR0B = B0_number; PORTB &= ~_BV(1); PORTB &= ~_BV(2); OCR2A = A2_number; OCR2B = B2_number; PORTD &= ~_BV(2); PORTD &= ~_BV(3); _delay_ms(1); } } void left0(int s, int t){ int i; A0_number = s; B0_number = 0; A2_number = 0; B2_number = s; for(i = 0; i < t; i++){ A0_number = A0_number + 1; B2_number = B2_number + 1; OCR0A = A0_number; OCR0B = B0_number; PORTB |= _BV(1); PORTB |= _BV(2); OCR2A = A2_number; OCR2B = B2_number; PORTD |= _BV(2); PORTD |= _BV(3); _delay_ms(2); if(!ps_left()){ break; } } } void left1(int s){ A0_number = s; B0_number = 0; A2_number = 0; B2_number = s; OCR0A = A0_number; OCR0B = B0_number; PORTB |= _BV(1); PORTB |= _BV(2); OCR2A = A2_number; OCR2B = B2_number; PORTD |= _BV(2); PORTD |= _BV(3); } void left_stop(){ int i; A0_number = 255; B0_number = 0; A2_number = 0; B2_number = 255; for(i = 0; i < 128; i++){ B0_number = B0_number + 2; A2_number = A2_number + 2; OCR0A = A0_number; OCR0B = B0_number; PORTB &= ~_BV(1); PORTB &= ~_BV(2); OCR2A = A2_number; OCR2B = B2_number; PORTD &= ~_BV(2); PORTD &= ~_BV(3); _delay_ms(1); } } void right0(int s, int t){ int i; A0_number = 0; B0_number = s; A2_number = s; B2_number = 0; for(i = 0; i < t; i++){ B0_number = B0_number + 1; A2_number = A2_number + 1; OCR0A = A0_number; OCR0B = B0_number; PORTB |= _BV(1); PORTB |= _BV(2); OCR2A = A2_number; OCR2B = B2_number; PORTD |= _BV(2); PORTD |= _BV(3); _delay_ms(2); if(!ps_right()){ break; } } } void right1(int s){ A0_number = 0; B0_number = s; A2_number = s; B2_number = 0; OCR0A = A0_number; OCR0B = B0_number; PORTB |= _BV(1); PORTB |= _BV(2); OCR2A = A2_number; OCR2B = B2_number; PORTD |= _BV(2); PORTD |= _BV(3); } void right_stop(){ int i; A0_number = 0; B0_number = 255; A2_number = 255; B2_number = 0; for(i = 0; i < 128; i++){ A0_number = A0_number + 2; B2_number = B2_number + 2; OCR0A = A0_number; OCR0B = B0_number; PORTB &= ~_BV(1); PORTB &= ~_BV(2); OCR2A = A2_number; OCR2B = B2_number; PORTD &= ~_BV(2); PORTD &= ~_BV(3); _delay_ms(1); } } void stop(){ A0_number = 255; B0_number = 255; A2_number = 255; B2_number = 255; OCR0A = A0_number; OCR0B = B0_number; PORTB &= ~_BV(1); PORTB &= ~_BV(2); OCR2A = A2_number; OCR2B = B2_number; PORTD &= ~_BV(1); PORTD &= ~_BV(2); } /*--------------A[[^֐---------------*/ void arm_one_strat0(int s, int t){ int i; A1_number = 0; B1_number = s; for(i = 0; i < t; i++){ B1_number = B1_number + 1; OCR1A = A1_number; OCR1B = B1_number; PORTB |= _BV(6); PORTB |= _BV(7); _delay_ms(2); } } void arm_one_strat1(int s){ A1_number = 0; B1_number = s; OCR1A = A1_number; OCR1B = B1_number; PORTB |= _BV(6); PORTB |= _BV(7); } void arm_one_strat_stop(){ int i; A1_number = 0; B1_number = 255; for(i = 0; i < 128; i++){ A1_number = A1_number + 2; OCR1A = A1_number; OCR1B = B1_number; PORTB &= ~_BV(6); PORTB &= ~_BV(7); _delay_ms(1); } } void arm_one_back0(int s, int t){ int i; A1_number = s; B1_number = 0; for(i = 0; i < t; i++){ A1_number = A1_number + 1; OCR1A = A1_number; OCR1B = B1_number; PORTB |= _BV(6); PORTB |= _BV(7); _delay_ms(2); } } void arm_one_back1(int s){ A1_number = s; B1_number = 0; OCR1A = A1_number; OCR1B = B1_number; PORTB |= _BV(6); PORTB |= _BV(7); } void arm_one_back_stop(){ int i; A1_number = 255; B1_number = 0; for(i = 0; i < 128; i++){ B1_number = B1_number + 2; OCR1A = A1_number; OCR1B = B1_number; PORTB &= ~_BV(6); PORTB &= ~_BV(7); _delay_ms(1); } } void arm_twe_strat1(){ PORTC &= ~_BV(0); PORTC |= _BV(1); PORTC |= _BV(2); PORTC &= ~_BV(3); } void arm_twe_back1(){ PORTC |= _BV(0); PORTC &= ~_BV(1); PORTC &= ~_BV(2); PORTC |= _BV(3); } void stop2(){ A1_number = 255; B1_number = 255; OCR1A = A1_number; OCR1B = B1_number; PORTB &= ~_BV(6); PORTB &= ~_BV(7); PORTC |= _BV(0); PORTC |= _BV(1); PORTC &= ~_BV(2); PORTC &= ~_BV(3); } /* void strat0_srow2(int t){ int i; A0_number = 100; B0_number = 100; A2_number = 100; B2_number = 100; for(i = 0; i < t; i++){ usart_sendStr(" "); usart_sendStr("0A:"); usart_sendStr(intToStr(A0_number,buf)); usart_sendStr(" "); usart_sendStr("0B:"); usart_sendStr(intToStr(B0_number,buf)); usart_sendStr(" "); usart_sendStr("2A:"); usart_sendStr(intToStr(A2_number,buf)); usart_sendStr(" "); usart_sendStr("2B:"); usart_sendStr(intToStr(B2_number,buf));; B0_number = B0_number - 1; B2_number = B2_number - 1; OCR0A = A0_number; OCR0B = B0_number; PORTB |= _BV(1); PORTB |= _BV(2); OCR2A = A2_number; OCR2B = B2_number; PORTD |= _BV(2); PORTD |= _BV(3); _delay_ms(3); } } */ void strat0_srow(int t){ int i; // A0_number = s; B0_number = 0; // A2_number = s; B2_number = 0; for(i = 0; i < t; i++){ /* usart_sendStr(" "); usart_sendStr("0A:"); usart_sendStr(intToStr(A0_number,buf)); usart_sendStr(" "); usart_sendStr("0B:"); usart_sendStr(intToStr(B0_number,buf)); usart_sendStr(" "); usart_sendStr("2A:"); usart_sendStr(intToStr(A2_number,buf)); usart_sendStr(" "); usart_sendStr("2B:"); usart_sendStr(intToStr(B2_number,buf));; usart_sendStr("\r\n"); // s */ A0_number = A0_number - 1; A2_number = A2_number - 1; OCR0A = A0_number; OCR0B = B0_number; PORTB |= _BV(1); PORTB |= _BV(2); OCR2A = A2_number; OCR2B = B2_number; PORTD |= _BV(2); PORTD |= _BV(3); _delay_ms(3); } } void back0_srow(int t){ int i; A0_number = 0; // B0_number = 0; A2_number = 0; // B2_number = 0; for(i = 0; i < t; i++){ B0_number = B0_number - 1; B2_number = B2_number - 1; OCR0A = A0_number; OCR0B = B0_number; PORTB |= _BV(1); PORTB |= _BV(2); OCR2A = A2_number; OCR2B = B2_number; PORTD |= _BV(2); PORTD |= _BV(3); _delay_ms(3); } } void left0_srow(int t){ int i; // A0_number = 0; B0_number = 0; A2_number = 0; // B2_number = 0; for(i = 0; i < t; i++){ A0_number = A0_number - 1; B2_number = B2_number - 1; OCR0A = A0_number; OCR0B = B0_number; PORTB |= _BV(1); PORTB |= _BV(2); OCR2A = A2_number; OCR2B = B2_number; PORTD |= _BV(2); PORTD |= _BV(3); _delay_ms(3); } } void right0_srow(int t){ int i; A0_number = 0; // B0_number = 0; // A2_number = 0; B2_number = 0; for(i = 0; i < t; i++){ B0_number = B0_number - 1; A2_number = A2_number - 1; OCR0A = A0_number; OCR0B = B0_number; PORTB |= _BV(1); PORTB |= _BV(2); OCR2A = A2_number; OCR2B = B2_number; PORTD |= _BV(2); PORTD |= _BV(3); _delay_ms(3); } } int flag_stop1 = 0; int flag_stop2 = 0; /*---------------------X[-----------------*/ void slow_move(){ while(ps_l1()){ leaf(); if(ps_top()){ /* usart_sendStr(" "); usart_sendStr("L["); usart_sendStr("\r\n"); // s */ if(flag_stop1 == 1){ A0_number = 100; B0_number = 100; A2_number = 100; B2_number = 100; // strat0(0,1); } flag_stop1 = 0; if(A0_number > 110){ strat0_srow(A0_number - 100); }else{ strat0(0, 100); //(PWMl, JE^[) } while(1){ strat1(100); //(PWM) if(!ps_top()){ strat_stop(); break; } if(!ps_l1()){ strat0(100,155); break; } } }else if(ps_bottom()){ if(flag_stop1 == 1){ A0_number = 100; B0_number = 100; A2_number = 100; B2_number = 100; // strat0(0,1); } flag_stop1 = 0; if(B0_number > 110){ back0_srow(B0_number - 100); }else{ back0(0, 100); //(PWMl, JE^[) } while(1){ back1(100); //(PWM) if(!ps_bottom()){ back_stop(); break; } if(!ps_l1()){ back0(100,155); break; } } }else { flag_stop1 = 1; stop(); } if(ps_left()){ if(flag_stop2 == 1){ A0_number = 100; B0_number = 100; A2_number = 100; B2_number = 100; // strat0(0,1); } flag_stop2 = 0; if(A0_number > 110){ left0_srow(A0_number - 100); }else{ left0(0, 100); //(PWMl, JE^[) } while(1){ left1(100); if(!ps_left()){ left_stop(); break; } if(!ps_l1()){ left0(100,155); break; } } }else if(ps_right()){ if(flag_stop2 == 1){ A0_number = 100; B0_number = 100; A2_number = 100; B2_number = 100; // strat0(0,1); } flag_stop2 = 0; if(B0_number > 110){ right0_srow(B0_number - 100); }else{ right0(0, 100); //(PWMl, JE^[) } while(1){ right1(100); if(!ps_right()){ right_stop(); break; } if(!ps_l1()){ right0(100,155); break; } } }else { flag_stop2 = 1; stop(); } if(ps_triangle()){ // arm_twe_strat1(); arm_one_strat0(0, 255); //(PWMl, JE^[) while(1){ arm_one_strat1(255); //(PWM) // arm_twe_strat1(); if(ps_r2()){ arm_twe_back1(); }else if(ps_r1()){ arm_twe_strat1(); } if(!ps_triangle()){ arm_one_strat_stop(); break; } } }else if(ps_cross()){ arm_one_back0(0, 255); // arm_twe_back1(); while(1){ arm_one_back1(255); // arm_twe_back1(); if(ps_r2()){ arm_twe_back1(); }else if(ps_r1()){ arm_twe_strat1(); } if(!ps_cross()){ arm_one_back_stop(); break; } } }else { // stop2(); } if(ps_triangle()){ arm_one_strat1(255); //(PWM) }else if(ps_cross()){ arm_one_back1(255); } if(ps_r2()){ arm_twe_back1(); }else if(ps_r1()){ arm_twe_strat1(); }else { stop2(); } } } void leaf_on(){ PORTC |= _BV(7); _delay_ms(600); PORTC &=~_BV(7); } void leaf_off(){ PORTC |= _BV(6); _delay_ms(600); PORTC &=~_BV(6); } bool token = false; // g[NƂĂ邩 // bool basket = false; // ĂƂĂ邩 void leaf(){ if(ps_circle()){ // g[N͂łꍇ if(token){ leaf_off(); token = false; } // g[N͂łȂꍇ else { leaf_on(); token = true; } while(ps_circle()); } } /**********PORTzu**********/ // 644P̂Ƃ // PA0 // PA1 // PA2 // PA3 // PA4 // PB0: // PB1: BHS (E[^[) // PB2: AHS (E[^[) // PB3: ALS (E[^[) // PB4: BLS (E[^[) // PB5: // PB6: AHS (S[^[) // PB7: BHS (S[^[) // PC0: ALS (C[[^[) // PC1: BLS (C[[^[) // PC2: AHS (C[[^[) // PC3: BHS (C[[^[) // PC4: // PC5: // PC6: // PC7: // PD0: Rg[[M // PD1: // PD2: AHS ([^[) // PD3: BHS ([^[) // PD4: BLS (S[^[) // PD5: ALS (S[^[) // PD6: BLS ([^[) // PD7: ALS ([^[) /**********C֐**********/ int main(){ token = false; // g[NƂĂ邩 DDRA = 0b11111111; DDRB = 0b11111111; DDRD = 0b11111111; DDRC = 0b11111111; usart_init(MYUBRR); // USARTݒ //adc_init(); // ADConverterݒ //int ad,ad2,ad3; // char buf[6]; /* int s = 255;// [^[l int sig_up = 0, sig_side = 0; int center_r_x = 118; //127 //125 //118 //131 //184 //Rg[[ɂčł̂ŔKv int center_r_y = 132; //127 //127 //122 //132 //138@@//Rg[[ɂčł̂ŔKv int center_l_x = 118; //127 //125 //118 //131 //184 //Rg[[ɂčł̂ŔKv int center_l_y = 132; //127 //127 //122 //132 //138@@//Rg[[ɂčł̂ŔKv int analog_l_up, analog_l_down, analog_l_right, analog_l_left; int analog_r_up, analog_r_down, analog_r_right, analog_r_left; */ TCCR0A = 0b10100011; // OCR0A OCR0B ̐ݒ TCCR0B = 0b00000001; TCCR1A = 0b10100001; // OCR1A OCR1B ̐ݒ TCCR1B = 0b00000011; TCCR2A = 0b10100011; // OCR2A OCR2B ̐ݒ TCCR2B = 0b00000001; sei(); //荞݋(‚ȂPSRg[[̐M󂯂Ȃ) //ANALOGĂȂƃmCŶANALOGX^[g܂ł͑ҋ@. while(analog_r_x == 0 || analog_r_y == 0)usart_sendStr("PUSH ANALOG\r\n"); while(start == 0){ usart_sendStr("PUSH START\r\n"); } /* //mF̂߃uU[g(ÉE)!!H PORTB = _BV(0); _delay_ms(1000); PORTB ^= _BV(0); */ // wwww(s); int sum; int flag_sro = 0; while(1){ leaf(); //A[J /*-------------------A[-------------------*/ if(ps_cross()){ // arm_twe_strat1(); arm_one_strat0(0, 255); //(PWMl, JE^[) while(1){ arm_one_strat1(255); //(PWM) // arm_twe_strat1(); if(ps_r2()){ arm_twe_back1(); }else if(ps_r1()){ arm_twe_strat1(); } if(!ps_cross()){ arm_one_strat_stop(); break; } } }else if(ps_triangle()){ arm_one_back0(0, 255); // arm_twe_back1(); while(1){ arm_one_back1(255); // arm_twe_back1(); if(ps_r2()){ arm_twe_back1(); }else if(ps_r1()){ arm_twe_strat1(); } if(!ps_triangle()){ arm_one_back_stop(); break; } } }else { // stop2(); } /* if(ps_triangle()){ arm_one_strat1(255); //(PWM) }else if(ps_cross()){ arm_one_back1(255); } */ if(ps_r2()){ arm_twe_back1(); }else if(ps_r1()){ arm_twe_strat1(); }else { stop2(); } if(!(SwitchRecv[0] == 0xff)){ flag_stop1 = 1; flag_stop2 = 1; stop(); } flag_sro = 0; if(ps_l1()){ slow_move();// X[ flag_sro = 1; } /*-------------------MAX------------------*/ if(ps_top()){ /* usart_sendStr(" "); usart_sendStr("L["); usart_sendStr("\r\n"); // s */ flag_stop1 = 0; if(flag_sro == 0){ strat0(0,255); //(PWMl, JE^[) } while(1){ strat1(255); //(PWMl) if(!ps_top()){ strat_stop(); break; } if(ps_l1()){ slow_move(); } } }else if(ps_bottom()){ flag_stop1 = 0; if(flag_sro == 0){ back0(0,255); //(PWMl, JE^[) } while(1){ back1(255); if(!ps_bottom()){ back_stop(); break; } if(ps_l1()){ slow_move(); } } }else { flag_stop1 = 1; stop(); } if(ps_left()){ flag_stop2 = 0; if(flag_sro == 0){ left0(0, 255); } while(1){ left1(255); if(!ps_left()){ left_stop(); break; } if(ps_l1()){ slow_move(); } } }else if(ps_right()){ flag_stop2 = 0; if(flag_sro == 0){ right0(0, 255); } while(1){ right1(255); if(!ps_right()){ right_stop(); break; } if(ps_l1()){ slow_move(); } } }else { flag_stop2 = 1; stop(); } /*----ړ----*/ // SELECT+STARTŁAAiOXeBbNX, Y̒Sʒu /* if(SwitchRecv[0]==0x09){ usart_sendStr("Initialize center\r\n"); center_r_x = 118; center_r_y = 132; center_l_x = 118; center_l_y = 132; } // AiOXeBbN̒SʒuύX if(select){ usart_sendStr("PUSH SELECT"); center_r_x = analog_r_x; center_r_y = analog_r_y; center_l_x = analog_l_x; center_l_y = analog_l_y; } // 艺vXeRg[[䖽 if(analog_l_y <= center_l_y - 60)//center_y80Ă̂ͱ۸޽è45‚ŕ邽 { sig_up = 1; // analog_l_up = 0xff - (analog_l_y * 2); top(s); usart_sendStr("UP "); } else if(analog_l_y >= center_l_y + 60) { sig_up = 1; // analog_l_down = (analog_l_y * 2) - 0xff; down(s); usart_sendStr("DOWN "); } else { sig_up = 0; stop_up(); usart_sendStr("STOP "); } if(analog_l_x <= center_l_x - 60)//center_y80Ă̂ͱ۸޽è45‚ŕ邽 { sig_side = 1; // analog_l_left = 0xff - (analog_l_x * 2); left(s); usart_sendStr("UP "); } else if(analog_l_x >= center_l_x + 60) { sig_side = 1; // analog_l_right = (analog_l_x * 2) - 0xff; right(s); usart_sendStr("DOWN "); } else { sig_side = 0; stop_side(); usart_sendStr("STOP "); } */ } }
JavaScript
UTF-8
3,380
3.703125
4
[]
no_license
function generateWinningNumber (){ return Math.ceil(Math.random()*100); }; function shuffle(array) { var m = array.length, t, i; // While there remain elements to shuffle… while (m) { // Pick a remaining element… i = Math.floor(Math.random() * m--); // And swap it with the current element. t = array[m]; array[m] = array[i]; array[i] = t; } return array; }; function Game(){ this.playersGuess=null; this.pastGuesses = []; this.winningNumber=generateWinningNumber(); } Game.prototype.difference=function(){ return Math.abs(this.playersGuess - this.winningNumber); }; Game.prototype.isLower=function(){ return this.playersGuess<this.winningNumber; }; Game.prototype.playersGuessSubmission = function(guess) { if(typeof guess !== 'number' || guess < 1 || guess > 100) { throw "That is an invalid guess."; } this.playersGuess = guess; return this.checkGuess(); }; Game.prototype.checkGuess = function() { if(this.playersGuess===this.winningNumber) { $('#hint, #submit').prop("disabled",true); $('#title').text("Press the Reset button to play again!") return 'You Win! You are the Guess Master!' } else { if(this.pastGuesses.indexOf(this.playersGuess) > -1) { return 'Seriously, you already guessed that number.'; } else { this.pastGuesses.push(this.playersGuess); $('#guesses li:nth-child('+ this.pastGuesses.length +')').text(this.playersGuess); if(this.pastGuesses.length === 5) { $('#hint, #submit').prop("disabled",true); return 'You lose. Press RESET to play again!'; } else { var diff = this.difference(); if (this.isLower()){ $('#title').text("Come on, guess higher") }else{ $('#title').text("Not quite, guess lower!") } if(diff < 10) return'You\'re burning up! Oh, so close!'; else if(diff < 25) return'You\'re lukewarm. Getting closer!'; else if(diff < 50) return'You\'re a bit chilly. Come on, guess again!'; else return'You\'re ice cold! Guess again.'; } } } }; function newGame(){ return new Game(); }; Game.prototype.provideHint=function(){ var hint=[]; hint.push(this.winningNumber, generateWinningNumber(), generateWinningNumber()) return shuffle(hint); } function makeAGuess(game) { var guess = $('#player-guess').val(); $('#player-guess').val(""); var output = game.playersGuessSubmission(parseInt(guess,10)); $('#title').text(output); } $(document).ready(function() { var game = new Game(); $('#submit-btn').click(function(e) { makeAGuess(game); }) $('#player-guess').keypress(function(event) { if ( event.which == 13 ) { makeAGuess(game); } }) $('#hint').click(function() { var hints = game.provideHint(); $('#title').text('The winning number is '+hints[0]+', '+hints[1]+', or '+hints[2]); }); $('#reset').click(function() { game = newGame(); $('#title').text('Guess a number between 1-100!'); $('.guess').text('-'); $('#hint, #submit').prop("disabled",false); }) })
JavaScript
UTF-8
530
3.0625
3
[]
no_license
/** * 1. Singleton (Based on Classes and class uses with extends for inheritance) * 2. Observers (Event Emitter) * 3. Factories (IIFE Immidiate Invoked function Expression, Instance of function) * 4. Dependency Injections * 5. Middleware -- App level, Route level * 6. Streams * 7. async/await */ /** * How to define Static variables? * Define a function. * Make a variable and return a function. * function abc(){ * let number = 0; * return functoin(){ * number++; * return number; * } * } * abc(); */
C#
UTF-8
1,516
3.5625
4
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Altcoins { class Program { static void Main(string[] args) { var bitcoins = double.Parse(Console.ReadLine()); var bitcoinStartPrice = double.Parse(Console.ReadLine()); var bitcoinCurrentPrice = double.Parse(Console.ReadLine()); var etheriumCount = double.Parse(Console.ReadLine()); var neoCount = double.Parse(Console.ReadLine()); var bitcoinProfit = bitcoins * bitcoinCurrentPrice - bitcoins * bitcoinStartPrice; var etheriumPrice = bitcoinCurrentPrice * 7.5 / 100; var neoPrice = etheriumPrice * 40 / 100; var totalPrice = etheriumCount * etheriumPrice + neoPrice * neoCount; var moneyLeft = bitcoinProfit - totalPrice; if (bitcoinProfit > totalPrice) { Console.WriteLine($"Stefcho bought {etheriumCount:f4} Ethereum at a price of {etheriumPrice:f4}"); Console.WriteLine($"Stefcho bought {neoCount:f4} Neo at a price of {neoPrice:f4}"); Console.WriteLine($"Stefcho has {moneyLeft:f2} profits left to spend."); } else { Console.WriteLine("Stefcho does not have enough money to make this investment."); Console.WriteLine($"He needs {-moneyLeft:f2} more in profits."); } } } }
Java
UTF-8
15,459
1.796875
2
[ "Apache-2.0", "LicenseRef-scancode-indiana-extreme" ]
permissive
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.modules; import java.io.File; import java.io.FilePermission; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.UndeclaredThrowableException; import java.nio.file.Files; import java.nio.file.Path; import java.security.AccessControlContext; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import java.util.function.Predicate; import org.jboss.modules.filter.PathFilter; import org.jboss.modules.filter.PathFilters; import org.jboss.modules.xml.ModuleXmlParser; import static java.security.AccessController.doPrivileged; import static org.jboss.modules.Utils.MODULE_FILE; /** * A module finder which locates module specifications which are stored in a local module * repository on the filesystem, which uses {@code module.xml} descriptors. * * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> * @author <a href="mailto:ropalka@redhat.com">Richard Opalka</a> */ public final class LocalModuleFinder implements IterableModuleFinder, AutoCloseable { private static final File[] NO_FILES = new File[0]; private final File[] repoRoots; private final PathFilter pathFilter; private final AccessControlContext accessControlContext; private final List<ResourceLoader> resourceLoaderList = new ArrayList<>(64); private final ModuleXmlParser.ResourceRootFactory resourceRootFactory; private static final ResourceLoader TERMINATED_MARKER = new ResourceLoader() { public String getRootName() { return null; } public ClassSpec getClassSpec(final String fileName) throws IOException { return null; } public PackageSpec getPackageSpec(final String name) throws IOException { return null; } public Resource getResource(final String name) { return null; } public String getLibrary(final String name) { return null; } public Collection<String> getPaths() { return null; } }; private LocalModuleFinder(final File[] repoRoots, final PathFilter pathFilter, final boolean cloneRoots) { this.repoRoots = cloneRoots && repoRoots.length > 0 ? repoRoots.clone() : repoRoots; final SecurityManager sm = System.getSecurityManager(); if (sm != null) { for (File repoRoot : this.repoRoots) { if (repoRoot != null) sm.checkPermission(new FilePermission(new File(repoRoot, "-").getPath(), "read")); } } this.pathFilter = pathFilter; this.accessControlContext = AccessController.getContext(); resourceRootFactory = (rootPath, loaderPath, loaderName) -> { final ResourceLoader loader = ModuleXmlParser.ResourceRootFactory.getDefault().createResourceLoader(rootPath, loaderPath, loaderName); final List<ResourceLoader> list = this.resourceLoaderList; synchronized (list) { if (list.size() == 1 && list.get(0) == TERMINATED_MARKER) { safeClose(loader); throw new IllegalStateException("Module finder is closed"); } list.add(loader); } return loader; }; } /** * Construct a new instance. * * @param repoRoots the repository roots to use * @param pathFilter the path filter to use */ public LocalModuleFinder(final File[] repoRoots, final PathFilter pathFilter) { this(repoRoots, pathFilter, true); } /** * Construct a new instance. * * @param repoRoots the repository roots to use */ public LocalModuleFinder(final File[] repoRoots) { this(repoRoots, PathFilters.acceptAll()); } /** * Construct a new instance, using the {@code module.path} system property or the {@code JAVA_MODULEPATH} environment variable * to get the list of module repository roots. * <p> * This is equivalent to a call to {@link LocalModuleFinder#LocalModuleFinder(boolean) LocalModuleFinder(true)}. * </p> */ public LocalModuleFinder() { this(true); } /** * Construct a new instance, using the {@code module.path} system property or the {@code JAVA_MODULEPATH} environment variable * to get the list of module repository roots. * * @param supportLayersAndAddOns {@code true} if the identified module repository roots should be checked for * an internal structure of child "layer" and "add-on" directories that may also * be treated as module roots lower in precedence than the parent root. Any "layers" * subdirectories whose names are specified in a {@code layers.conf} file found in * the module repository root will be added in the precedence of order specified * in the {@code layers.conf} file; all "add-on" subdirectories will be added at * a lower precedence than all "layers" and with no guaranteed precedence order * between them. If {@code false} no check for "layer" and "add-on" directories * will be performed. * */ public LocalModuleFinder(boolean supportLayersAndAddOns) { this(getRepoRoots(supportLayersAndAddOns), PathFilters.acceptAll(), false); } static File[] getRepoRoots(final boolean supportLayersAndAddOns) { return supportLayersAndAddOns ? LayeredModulePathFactory.resolveLayeredModulePath(getModulePathFiles()) : getModulePathFiles(); } private static File[] getModulePathFiles() { return getFiles(System.getProperty("module.path", System.getenv("JAVA_MODULEPATH")), 0, 0); } private static File[] getFiles(final String modulePath, final int stringIdx, final int arrayIdx) { if (modulePath == null) return NO_FILES; final int i = modulePath.indexOf(File.pathSeparatorChar, stringIdx); final File[] files; if (i == -1) { files = new File[arrayIdx + 1]; files[arrayIdx] = new File(modulePath.substring(stringIdx)).getAbsoluteFile(); } else { files = getFiles(modulePath, i + 1, arrayIdx + 1); files[arrayIdx] = new File(modulePath.substring(stringIdx, i)).getAbsoluteFile(); } return files; } public ModuleSpec findModule(final String name, final ModuleLoader delegateLoader) throws ModuleLoadException { final String child = PathUtils.basicModuleNameToPath(name); if (child == null) { return null; // not valid, so not found } final PathFilter pathFilter = this.pathFilter; if (pathFilter.accept(child + "/")) { try { return doPrivileged((PrivilegedExceptionAction<ModuleSpec>) () -> parseModuleXmlFile(resourceRootFactory, name, delegateLoader, repoRoots), accessControlContext); } catch (PrivilegedActionException e) { try { throw e.getCause(); } catch (IOException e1) { throw new ModuleLoadException(e1); } catch (RuntimeException | Error | ModuleLoadException e1) { throw e1; } catch (Throwable t) { throw new UndeclaredThrowableException(t); } } } return null; } /** * Parse a {@code module.xml} file and return the corresponding module specification. * * @param identifier the identifier to load * @param delegateLoader the delegate module loader to use for module specifications * @param roots the repository root paths to search * @return the module specification * @throws IOException if reading the module file failed * @throws ModuleLoadException if creating the module specification failed (e.g. due to a parse error) * @deprecated Use {@link #parseModuleXmlFile(String, ModuleLoader, File...)} instead. */ @Deprecated public static ModuleSpec parseModuleXmlFile(final ModuleIdentifier identifier, final ModuleLoader delegateLoader, final File... roots) throws IOException, ModuleLoadException { return parseModuleXmlFile(identifier.toString(), delegateLoader, roots); } /** * Parse a {@code module.xml} file and return the corresponding module specification. * * @param name the name of the module to load * @param delegateLoader the delegate module loader to use for module specifications * @param roots the repository root paths to search * @return the module specification * @throws IOException if reading the module file failed * @throws ModuleLoadException if creating the module specification failed (e.g. due to a parse error) */ public static ModuleSpec parseModuleXmlFile(final String name, final ModuleLoader delegateLoader, final File... roots) throws IOException, ModuleLoadException { return parseModuleXmlFile(ModuleXmlParser.ResourceRootFactory.getDefault(), name, delegateLoader, roots); } static ModuleSpec parseModuleXmlFile(final ModuleXmlParser.ResourceRootFactory factory, final String name, final ModuleLoader delegateLoader, final File... roots) throws IOException, ModuleLoadException { final String child = PathUtils.basicModuleNameToPath(name); if (child == null) { return null; // not valid, so not found } for (File root : roots) { File file = new File(root, child); File moduleXml = new File(file, MODULE_FILE); if (moduleXml.exists()) { final ModuleSpec spec = ModuleXmlParser.parseModuleXml(factory, delegateLoader, name, file, moduleXml); if (spec == null) break; return spec; } } return null; } private static final Path MODULE_FILE_PATH = new File(MODULE_FILE).toPath(); private static final Predicate<Path> ITER_FILTER = new Predicate<Path>() { public boolean test(final Path path) { final Path fileName = path.getFileName(); return fileName != null && fileName.equals(MODULE_FILE_PATH); } }; public Iterator<String> iterateModules(final String baseName, final boolean recursive, final ModuleLoader delegateLoader) { return new Iterator<>() { private final Iterator<File> rootIter = Arrays.asList(repoRoots).iterator(); private final Set<String> found = new HashSet<>(); private Iterator<Path> pathIter; private String next; public boolean hasNext() { while (next == null) { while (pathIter == null) { if (! rootIter.hasNext()) { return false; } Path path = rootIter.next().toPath(); if (baseName != null && ! baseName.isEmpty()) { path = path.resolve(PathUtils.basicModuleNameToPath(baseName)); } try { pathIter = Files.walk(path, recursive ? Integer.MAX_VALUE : 1).filter(ITER_FILTER).iterator(); } catch (IOException ignored) { pathIter = null; continue; } } if (pathIter.hasNext()) { final Path nextPath = pathIter.next(); if (nextPath.getParent() == null) { continue; } try (InputStream stream = Files.newInputStream(nextPath)) { final ModuleSpec moduleSpec = ModuleXmlParser.parseModuleXml(ModuleXmlParser.ResourceRootFactory.getDefault(), nextPath.getParent().toString(), stream, nextPath.toString(), delegateLoader, (String)null); if (moduleSpec != null) { this.next = moduleSpec.getName(); if (found.add(this.next)) { return true; } this.next = null; } } catch (IOException | ModuleLoadException e) { // ignore } } else { pathIter = null; } } return true; } public String next() { if (! hasNext()) throw new NoSuchElementException(); try { return next; } finally { next = null; } } }; } public String toString() { final StringBuilder b = new StringBuilder(); b.append("local module finder @").append(Integer.toHexString(hashCode())).append(" (roots: "); final int repoRootsLength = repoRoots.length; for (int i = 0; i < repoRootsLength; i++) { final File root = repoRoots[i]; b.append(root); if (i != repoRootsLength - 1) { b.append(','); } } b.append(')'); return b.toString(); } /** * Close this module loader and release all backing files. Note that subsequent load attempts will fail with an * error after this method is called. */ public void close() { final List<ResourceLoader> list = this.resourceLoaderList; final ArrayList<ResourceLoader> toClose; synchronized (list) { if (list.size() == 1 && list.get(0) == TERMINATED_MARKER) { return; } toClose = new ArrayList<>(list); list.clear(); list.add(TERMINATED_MARKER); } for (ResourceLoader resourceLoader : toClose) { safeClose(resourceLoader); } } private static void safeClose(AutoCloseable closeable) { if (closeable != null) try { closeable.close(); } catch (Throwable ignored) {} } }
PHP
UTF-8
6,780
2.921875
3
[]
no_license
<?php // require_once('config/home-laptop.config.php'); require_once('config/ubuntu-server.config.php'); class DB { public $db; private $db_user; private $db_pass; private $db_database; public $conn; public function __construct() { $this->db_user = DB_USER; $this->db_pass = DB_PASS; $this->db_database = DB_NAME; $this->db_host = DB_HOST; $this->conn = mysqli_connect($this->db_host, $this->db_user, $this->db_pass, $this->db_database); } public function registerUser($username, $password) { $stmt = $this->conn->prepare("INSERT INTO users (name, password) VALUES (?, ?)"); $stmt->bind_param('ss', $username, $password); try { if (!$stmt->execute()) { throw new Exception('Error: failed to execute query'); } $id = $stmt->insert_id; if (!$id) { throw new Exception('Error: failed to retrieve userid'); } $stmt->close(); } catch (Exception $e) { return $e->getMessage(); } return $id; } public function loginUser($username, $password) { $stmt = $this->conn->prepare("SELECT id FROM users WHERE name = ? AND password = ?"); $stmt->bind_param('ss', $username, $password); try { if (!$stmt->execute()) { throw new Exception('Error: failed to execute query'); } } catch (Exception $e) { return $e->getMessage(); } $stmt->store_result(); $stmt->bind_result($id); while ($stmt->fetch()); $stmt->close(); return $id; } public function getUsername($userid) { $stmt = $this->conn->prepare("SELECT name FROM users WHERE id = ?"); $stmt->bind_param('i', $userid); try { if (!$stmt->execute()) { throw new Exception('Error: failed to execute query'); } } catch (Exception $e) { return $e->getMessage(); } $stmt->store_result(); $stmt->bind_result($name); while ($stmt->fetch()); $stmt->close(); return $name; } public function getChallenges() { $stmt = $this->conn->prepare("SELECT id, name, score FROM challenges WHERE active = 1"); try { if (!$stmt->execute()) { throw new Exception('Error: failed to execute query'); } } catch (Exception $e) { return $e->getMessage(); } $stmt->store_result(); $stmt->bind_result($id, $name, $score); $out = array(); while ($stmt->fetch()) { $out[$id] = array( 'name' => $name, 'score' => $score ); } $stmt->close(); return $out; } public function getChallengeDetails($challengeid, $userid) { $stmt = $this->conn->prepare("SELECT C.id, C.score, COUNT(S.challengeid) AS passed FROM challenges AS C INNER JOIN score AS S ON C.id = S.challengeid WHERE C.id = ? AND S.userid = ?"); $stmt->bind_param('ii', $challengeid, $userid); try { if (!$stmt->execute()) { throw new Exception('Error: failed to execute query'); } } catch (Exception $e) { return $e->getMessage(); } $stmt->store_result(); $stmt->bind_result($id, $score, $passed); while ($stmt->fetch()); $stmt->close(); return array( 'id' => $id, 'score' => $score, 'passed' => $passed ); } public function setCompleted($userid, $challengeid) { $stmt = $this->conn->prepare("INSERT INTO score (userid, challengeid) VALUES (?, ?)"); $stmt->bind_param('ii', $userid, $challengeid); try { if (!$stmt->execute()) { throw new Exception('Error: failed to execute query'); } $id = $stmt->insert_id; if (!$id) { throw new Exception('Error: failed to get id'); } } catch (Exception $e) { return $e->getMessage(); } $stmt->close(); return $id; } public function getCompleted($userid) { $stmt = $this->conn->prepare("SELECT C.id, C.name, C.score FROM challenges AS C INNER JOIN score AS S ON C.id = S.challengeid WHERE S.userid = ? AND C.active = 1"); $stmt->bind_param('i', $userid); try { if (!$stmt->execute()) { throw new Exception('Error: failed to execute query'); } } catch (Exception $e) { return $e->getMessage(); } $stmt->store_result(); $stmt->bind_result($id, $name, $score); $out = array(); while ($stmt->fetch()) { $out[$id] = array( 'name' => $name, 'score' => $score ); } $stmt->close(); return $out; } public function getAnswer($challengeid) { $stmt = $this->conn->prepare("SELECT answer FROM challenges WHERE id = ?"); $stmt->bind_param('i', intval($challengeid)); try { if (!$stmt->execute()) { throw new Exception('Error: failed to execute query'); } } catch (Exception $e) { return $e->getMessage(); } $stmt->store_result(); $stmt->bind_result($answer); while ($stmt->fetch()); $stmt->close(); return $answer; } public function getHint($challengeid) { $stmt = $this->conn->prepare("SELECT hint FROM challenges WHERE id = ?"); $stmt->bind_param('i', intval($challengeid)); try { if (!$stmt->execute()) { throw new Exception('Error: failed to execute query'); } } catch (Exception $e) { return $e->getMessage(); } $stmt->store_result(); $stmt->bind_result($hint); while ($stmt->fetch()); $stmt->close(); return $hint; } public function getAllScores() { $stmt = $this->conn->prepare("SELECT id, name FROM users WHERE id > 1"); try { if (!$stmt->execute()) { throw new Exception('Error: failed to execute query'); } } catch (Exception $e) { return $e->getMessage(); } $users = array(); $stmt->store_result(); $stmt->bind_result($id, $name); while ($stmt->fetch()) { $users[$id] = array( 'name' => $name ); } $stmt->close(); foreach ($users as $id => $user) { $users[$id]['challenges'] = $this->getCompleted($id); } return $users; } }
C++
UTF-8
2,451
2.53125
3
[ "Apache-2.0" ]
permissive
#ifndef _HOMOMORPHINE_UTIL_H_ #define _HOMOMORPHINE_UTIL_H_ #include <limits> #include <ctime> #include <iostream> #include <utility> #include <sstream> #include <string> #include <boost/log/trivial.hpp> #include <boost/log/utility/setup.hpp> #include <boost/archive/iterators/base64_from_binary.hpp> #include <boost/archive/iterators/binary_from_base64.hpp> #include <boost/archive/iterators/insert_linebreaks.hpp> #include <boost/archive/iterators/transform_width.hpp> #include <boost/archive/iterators/ostream_iterator.hpp> #include <boost/archive/iterators/remove_whitespace.hpp> #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int_distribution.hpp> #include "clang_types.hpp" using namespace std; using namespace boost::archive::iterators; namespace homomorphine { /*! /brief Utility class * * This class provides a various utility functions. At this moment it * supports UUEncoding/UUDecoding of the binary string streams used * to serialize various binary objects for external usage and standardization * of the interface. */ class Util { public: /*! * Encodes the binary string stream to string * * \param string_stream string stream to be UUEncoded * \return UUEncoded string */ static const string uuencodeStream(stringstream &string_stream); /*! * Decodes UUEncoded string to a binary string stream * * \param content UUENcoded string * \param string_stream stream containing a decoded stream */ static const void uudecodeString(string content, stringstream &string_stream); /*! * Generates a vector of random values * * \param size size of vector * \return vector of random numbers */ static const vector<int> getRandomVector(int &size); /*! * Returns total size of input stream in bytes * * \param stream input stream size * \return stream size in bytes */ static const long getStreamSize(istream &stream); /*! * Loads the content of stream to bytes structure - required for handling * byte streams that can't be simply copied into strings, or char arrays * without additional encoding * * \param stream input stream * \return blob POD structure */ static const Blob copyStreamToBlob(istream& stream); }; } #endif
C++
UTF-8
417
3.6875
4
[]
no_license
#include <iostream> #include <algorithm> #include <vector> long sumTwoSmallestNumbers(std::vector<int> numbers) { std::sort(numbers.begin(), numbers.end()); return (long)numbers[0] + (long)numbers[1]; } int main() { std::vector<int> nums; nums.push_back(8); nums.push_back(22); nums.push_back(19); nums.push_back(5); long sum = sumTwoSmallestNumbers(nums); std::cout << sum; }
C++
UTF-8
707
2.671875
3
[ "MIT" ]
permissive
//This is the sol if we will be given any set of numbers instead od a series of 1-10 #include<iostream> #include<algorithm> #include<vector> #include<string.h> #include<set> #include<cmath> #include<numeric> #define LL long long using namespace std; int main() { int tc; cin>>tc; while(tc--) { int i=9,c=0; int a,b; cin>>a>>b; int diff = abs(a-b); if(diff!=0) { int no[] = {1,2,3,4,5,6,7,8,9,10}; while(diff>0) { int val = diff/no[i]; diff = diff%no[i]; c+=val; i--; } } cout<<c<<endl; } return 0; }
Python
UTF-8
1,114
2.71875
3
[]
no_license
import numpy as np from simulationtools import room from utils import processing from utils import plotting #==================================================# mic_location1 = np.c_[ [1.00, 4.02, 1.5], # mic1 [1.00, 3.98, 1.5], # mic2 [1.04, 4.02, 1.5], # mic3 [1.04, 3.98, 1.5], # mic4 ] mic_location2 = np.c_[ [4.02, 1.54, 1.5], # mic1 [4.02, 1.50, 1.5], # mic2 [3.98, 1.50, 1.5], # mic3 [3.98, 1.54, 1.5], # mic4 ] source_location1 = [2.6, 5.7, 1.8] source_location2 = [2.0, 1.5, 1.8] angle_from_first_pair = room.receive_angles(mic_location1, source_location1, source_location2) angle_from_second_pair = room.receive_angles(mic_location2, source_location1, source_location2) found_crossings = processing.find_intersections(angle_from_first_pair, angle_from_second_pair, [1.02, 4.0], [4.0, 1.52]) print(found_crossings) plotting.plot_crossings(found_crossings, [source_location1, source_location2], [6., 8., 3.5], [[1.02, 4.], [4., 1.52]], [angle_from_first_pair, angle_from_second_pair])
Python
UTF-8
2,100
3.3125
3
[]
no_license
import unittest import os from github import Github class GithubTest(unittest.TestCase): def test_deve_retornar_todos_repos_do_usuario(self): usuario = 'gpsilva' github = Github() repositorios = github.obter_repositorios_do(usuario) self.assertEqual(10, len(repositorios)) def test_obter_dados_dos_repositorios(self): repo1 = { 'name': 'repo1', 'stargazers_count': 2, 'language': 'python', 'html_url': 'http://', 'owner': { 'login': 'usuario1' } } repositorios = [repo1] github = Github() resultado = github.obter_dados_dos(repositorios) dados = resultado[0] self.assertEqual(repo1.get('name'), dados.get('nome_repositorio')) self.assertEqual(repo1.get('stargazers_count'), dados.get('estrelas')) self.assertEqual(repo1.get('language'), dados.get('linguagem')) self.assertEqual(repo1.get('html_url'), dados.get('url_repositorio')) self.assertEqual(repo1.get('owner').get('login'), dados.get('usuario')) def test_converter_dados_para_salvar_no_csv(self): repositorios = [ { 'nome_repositorio': 'repo1', 'estrelas': 2, 'linguagem': 'python', 'url_repositorio': 'http://', 'usuario': 'usuario1' } ] github = Github() lista = github.converter_para_lista(repositorios) self.assertEqual(1, len(lista)) primeiro = lista[0] self.assertEqual('repo1', primeiro[0]) self.assertEqual(2, primeiro[1]) self.assertEqual('python', primeiro[2]) def test_deve_criar_arquivo_csv(self): nome_arquivo = '/tmp/repositorios.csv' conteudo = [['repo1', 2, 'python', 'http://', 'usuario1']] github = Github() arquivo_gerado = github.salvar(arquivo=nome_arquivo, conteudo=conteudo) self.assertTrue(os.path.exists(arquivo_gerado)) if __name__ == '__main__': unittest.main()
Markdown
UTF-8
2,748
2.6875
3
[]
no_license
# Pytorch Implementation of A2C This repo implements the A2C algorithm for reinforcement learning with emphasis on speed and modularity. A2C is the synchronized version of [Asynchronous advantage actor-critic(A3C)](https://arxiv.org/pdf/1602.01783.pdf). A2C has been implemented and studied by many AI researchers and notablely been part of the [OpenAI baseline](https://blog.openai.com/baselines-acktr-a2c/). However, the detailed description of A2C is hard to find online. In this project, we implement our own version with reference to the [OpenAI baseline](https://github.com/openai/baselines/tree/master/baselines/a2c) and write down some key design choices to help understand the codebase. ## Design In the original A3C, N instances of the enviroment, e.g. an Atari game, run asynchronously and each instance has its own actor to produce trajactories (sequences of game play timesteps) used for asynchronous parameter updates. In A2C, a batch of environments are sychronized at every step, meaning that they produce a batch of states, the agent consume that batch and produce a batch of actions, and then the environments perform corresponding actions to produce the next batch of states. This method can increase the utilization of GPU and thus increase speed. In A3C, each enviroment collect a trajectory of maximum length T and the trajectory may be shorter if end state is encountered. In A2C, we naturally repeat the batched step T times to collect N trajectories of length T. However, end states may appear in one or more trajactories. In those cases, the trajectory is simply a concatenation of two shorter trajectories. For example, if T = 5, it may happen that the first 2 nodes in the trajectory record the information of the last two frames of one episode and the last 3 nodes in the trajactory record the begining of a new episode. In this way, we can easily convert N trajectories if length T into N * T pairs of (input, target) tuples to maximize the training speed. ## Performance This implementation is very fast. It runs at 2300 frames/s on my 4 core CPU + GTX1080 desktop to train on Pong with 16 environments/processes, which is more than 20% faster than some [existing implementation](https://github.com/ikostrikov/pytorch-a2c-ppo-acktr) running on the same machine. Benchmarking on machines with more CPU cores will be added. <img src="figs/pong.png" width="425"/> <img src="figs/space_invaders.png" width="425"/> ## Usage ``` python3 main.py --env_name SpaceInvadersNoFrameskip-v4 --num_envs 16 --exp_name run1 ``` See main.py for a complete list of optional command line arguments. ## Future Work 1. [NoisyNet for exploration](https://arxiv.org/abs/1706.10295) 2. [ACKTR](https://arxiv.org/abs/1708.05144)
JavaScript
UTF-8
10,661
2.671875
3
[]
no_license
$(document).ready(function() { function updateScroll() { var scrollDiv = document.getElementById("main"); scrollDiv.scrollTop = scrollDiv.scrollHeight; } /* * Enables ability to search through existing chats for desired recipients username */ $('#search_box').keyup(function(){ var chatSearch = $('#search_box').val(); var chats = document.querySelectorAll('.thumbnail'); for(var i = 0; i < chats.length; i++){ var id = "#".concat(chats[i].id); var thumb_class = ".".concat(chats[i].className); // see if the innerhtml of any of the buttons w/ class 'thumbnail' match the search box input // if theres a match, show the button using its respective id if(chats[i].innerHTML.includes(chatSearch)){ $(id).show("slow", function(){ $(id).click(function(){ $(thumb_class).show(); }) }); } // if field is empty, show all the thumbnails else if ($("#search_box").val() == "") { $(thumb_class).show(); } // if there are no matches, hide all of the thumbnails else { $(id).hide(); } } }); /* * Enables chat button if recipient exists, otherwise unable to create new message */ $('#feedback').load('welcome_helper.php').show(); $('#recipient_input').keyup(function() { var recipient_input = $("#recipient_input").val(); $.post('welcome_helper.php', { recipient: recipient_input, type: "recipientCheck" }, function(data){ $('#feedback').html(data).show(); // Responsible for disabling/enabling chat button if(!$('#feedback:contains("Recipient Exists")').length > 0){ document.getElementById("chat_button").disabled = true; } else{ document.getElementById("chat_button").disabled = false; } }); }); /* * Acquires recipients name after chat button is clicked, adds it to Group and User_Group tables * Also used to pass an array in JSON containing group id, user id, recipient id * in that order as a hidden field to the message form */ var interval; $('#chat_button').click(function() { var recipient = $("#recipient_input").val(); $.post('welcome_helper.php', { data : recipient, type: "groupChat" }, function(data){ var id_array = data; // Responsible for resetting new message container if($('#feedback:contains("Recipient Exists")').length > 0){ document.getElementById("recipient_input").value = ""; document.querySelector(".bg-modal").style.display = "none"; document.getElementById("feedback").innerHTML = ""; document.getElementById("messagebar_container").style.display = "block"; } // Here we have to load the chat if the theres an existing chat var id_array = JSON.parse(id_array); var recip_id = id_array[2]; var group_id = id_array[0]; var chatRecip_selector = "#thumbnail" + recip_id; // if the chat thumbnail exists, proceed loading the messages for that chat if($(chatRecip_selector).length){ // responsible for removing dynamically created HTML messages when another thumbnail is clicked // pretty much clearing the message area $(".user_messages").remove(); $(".recip_messages").remove(); $("#message_area > br").remove(); if(interval){ clearInterval(interval); interval = setTimeout(updateMessages, 100, recip_id, group_id); interval = setInterval(updateMessages, 5000, recip_id, group_id); } else{ interval = setTimeout(updateMessages, 100, recip_id, group_id); interval = setInterval(updateMessages, 5000, recip_id, group_id); } } }); }); /* * Loads chat thumbnails in the sidebar by using recipients username, user id, and group id * Proceeds with creating HTML strings for each thumbnail */ $.post('welcome_helper.php', {login_username: login_username, type: "chatThumbs"}, function(data){ // data holds JSON representation as string // ex. "[{"username":"charliegeorge","user_id":3,"group_id":1},...]" //var obj = JSON.parse(data); // converts string to JSON object // ex. 0 : {username: "charliegeorge", user_id: 3, group_id: 1} //var i, usernames = ""; /* for (i = 0; i < obj.length ; i++){ usernames += "<button id='thumbnail" + obj[i].group_id + "' class='thumbnail' data-value='" + obj[i].user_id + "' value='" + obj[i].group_id + "'>" + obj[i].username + "</button>"; // we concatenate all usernames within JSON object } $("#message_list").html(usernames).show(); */ /* * Loads chat messages specific to recipient/chat after clicking recipient's thumbnail * Proceeds with creating HTML strings for each message pertaining to the chat */ /* $('.thumbnail').click(function() { // responsible for removing dynamically created HTML messages when another thumbnail is clicked // pretty much clearing the message area $(".user_messages").remove(); $(".recip_messages").remove(); $("#message_area > br").remove(); document.getElementById("messagebar_container").style.display = "block"; var recip_id = $(this).attr("data-value"); var group_id = $(this).attr("value"); */ /* if(interval){ //clear it clearInterval(interval); //setTimeout for faster load of chat interval = setTimeout(updateMessages, 100, recip_id, group_id); //setInterval to start new interval for current chat interval = setInterval(updateMessages, 5000, recip_id, group_id); } //if no interval is running, then carryout same process else{ interval = setTimeout(updateMessages, 100, recip_id, group_id); interval = setInterval(updateMessages, 5000, recip_id, group_id); } */ //}); //console.log(data); }); /* * Responsible for displaying recently sent message in the main message area * by adding concatenating HTML string to messages variable */ $('#send_button').click(function() { var id_array = $("#hidden_array").val(); var message = $("#message_input").val(); if (message.localeCompare("") == 0){ alert("Cannot send an empty message"); } else{ $.post('welcome_helper.php', {message: message, id_array: id_array, type: "sendMessage"}, function(data){ $("#message_area").append("<p class='user_messages'>" + JSON.parse(data) + "</p><br>"); document.getElementById("message_input").value = ""; updateScroll(); }); } }); function updateMessages(recip_id, group_id){ $.post('welcome_helper.php', {recip_id: recip_id, group_id: group_id, type: "loadChat"}, function(data) { $(".user_messages").remove(); $(".recip_messages").remove(); $("#message_area > br").remove(); var obj = JSON.parse(data); $("#hidden_array").val(obj["id_array"]); var i; var id_array = JSON.parse(obj["id_array"]); var user_id = id_array[1]; var recipient_id = id_array[2]; for(i = 0; i < obj["chat_messages"].length; i++){ // so here we have to separate what the users and recipients messages are so they can // be divided on the main message area // if (user_id is == to obj["chat_messages"][i].creator_id) if (user_id == obj["chat_messages"][i].creator_id){ // messages += "..." -> positioning has to be on right side $("#message_area").append("<p class='user_messages'>" + obj["chat_messages"][i].message_body + "</p><br>"); } // else if (recipient_id is == to obj["chat_messages"][i].creator_id) else if (recipient_id == obj["chat_messages"][i].creator_id){ // messages += "..." -> positioning has to be on the left side $("#message_area").append("<p class='recip_messages'>" + obj["chat_messages"][i].message_body + "</p><br>"); } } updateScroll(); }); } });
C#
UTF-8
396
3.21875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SumOfTwoIntegers { // Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. internal class Program { private static void Main(string[] args) { Solution.GetSum(0, 3); } } }
Markdown
UTF-8
2,481
2.546875
3
[ "MIT" ]
permissive
## Installation in stand-alone Tomcat We assume Tomcat 7 in unzipped in `$TOMCAT_HOME` and that the `tomcat` user (group `tomcat`) is used to run Tomcat. Change accordingly to your own settings. ### Tomcat configuration In `$TOMCAT_HOME/lib`, put the following libraries: * H2 database driver - downloaded from http://search.maven.org/#artifactdetails%7Ccom.h2database%7Ch2%7C1.3.174%7Cjar * Java mail libraries - downloaded from http://www.oracle.com/technetwork/java/index-138643.html ### Configuration for ontrack Create the home directory: ``` sudo mkdir /opt/ontrack sudo chown tomcat:tomcat /opt/ontrack ``` Create the `$TOMCAT_HOME/conf/Catalina/localhost/ontrack.xml` file by copying the file from GitHub at `pipeline/config/tomcat7/context.xml`. In the `$TOMCAT_HOME/conf/catalina.properties` configuration file, add the following section at the end: ``` # Global custom system properties spring.profiles.active=prod # ontrack system properties ontrack.home=/opt/ontrack/home ``` ### Deployment Upload `ontrack.war` into `$TOMCAT_HOME/webapps`. ### Stopping & starting Stop the server by using: ``` sudo /etc/init.d/tomcat stop ``` Start the server by using: ``` sudo /etc/init.d/tomcat start ``` Tomcat logs are available at `$TOMCAT_HOME/logs`. ## Installation on Ubuntu ### Tomcat installation Install tomcat 7 by running: ``` sudo apt-get install tomcat7 ``` This should make sure to install the JDK 7 as well. ### Tomcat configuration In `/usr/share/tomcat7/lib`, put the following libraries: * H2 database driver - downloaded from http://search.maven.org/#artifactdetails%7Ccom.h2database%7Ch2%7C1.3.174%7Cjar * Java mail libraries - downloaded from http://www.oracle.com/technetwork/java/index-138643.html ### Configuration for ontrack Create the home directory: ``` sudo mkdir /opt/ontrack sudo chown tomcat7:tomcat7 /opt/ontrack ``` In the `/etc/default/tomcat7` configuration file, change the first `JAVA_OPTS` line into: ``` JAVA_OPTS="-Djava.awt.headless=true -Dspring.profiles.active=prod -Dontrack.home=/opt/ontrack/home -Xmx256m -XX:+UseConcMarkSweepGC" ``` Create the `/etc/tomcat7/Catalina/localhost/ontrack.xml` file by copying the file from GitHub at `pipeline/config/tomcat7/context.xml`. ### Deployment Upload `ontrack.war` into `/var/lib/tomcat7/webapps`. ### Stopping & starting Stop the server by using: ``` sudo /etc/init.d/tomcat7 stop ``` Start the server by using: ``` sudo /etc/init.d/tomcat7 start ```
C++
UTF-8
1,370
3.328125
3
[]
no_license
#pragma once #include "ncurses.h" /*! * \brief Adapter klasy bibliotecznej ncurses * \details Jest to klasa konwertujaca proceduralny interfejs (obslugujacy kolory) biblioteki ncurses na interfejs obiektowy, o wiele wygodniejszy w uzyciu * \author Mateusz Winiarski * \version v1.0 * \date 2015 * \warning Zaimplementowane tylko metody potrzebne w naszym projekcie */ class ColorPair { public: /*! * \brief Konstruktor klasy ColorPair * \details Tworzy na podstawie zliczania ilosci wystapien nowa pare kolorow. * @param text Reprezentacja koloru tekstu * @param background Reprezentacja koloru tla */ ColorPair(short text, short background); /*! * \brief Funkcja konwertujaca oboekt typu ColorPair na biblioteczna reprezentacje * \return Biblioteczna reprezentacja obiektu */ operator chtype(); /*! * \brief Funkcja zwracajaca biblioteczna reprezentacje koloru tekstu * \return Biblioteczna reprezentacae koloru tekstu */ short text() { return _text; } /*! * \brief Funkcja zwracajaca biblioteczna reprezentacje koloru tla * \return Biblioteczna reprezentacja koloru tla */ short background() { return _background; } private: static short count; short _text; short _background; short _number; }; extern ColorPair textColor; extern ColorPair specialTextColor;
JavaScript
UTF-8
1,479
2.90625
3
[]
no_license
function solve() { class Post { constructor(postTitle, postContent) { this.title = postTitle; this.content = postContent; } toString() { return `Post: ${this.title}\nContent: ${this.content}` } } class SocialMediaPost extends Post { constructor(postTitle, postContent, likes, dislikes) { super(postTitle, postContent); this.postLikes = likes; this.postDislikes = dislikes; this.comments = []; } addComment(comment) { this.comments.push(comment); } toString() { let result = super.toString(); result += `\nRating: ${this.postLikes - this.postDislikes}`; if (this.comments.length) { result += '\nComments:'; for (let comment of this.comments) { result += '\n * ' + comment; } } return result; } } class BlogPost extends Post { constructor(postTitle, postContent, postViews) { super(postTitle, postContent); this.postViews = postViews; } view() { ++this.postViews; return this; } toString() { return `${super.toString()}\nViews: ${this.postViews}`; } } return { Post, SocialMediaPost, BlogPost } }
Java
UTF-8
249
1.695313
2
[]
no_license
package ru.vsu.noidle_server.model.dto; import lombok.*; @Getter @Setter @AllArgsConstructor @NoArgsConstructor @EqualsAndHashCode(of = "email") @ToString public class UserDtoForNotification { private String email; private String name; }
C++
UTF-8
248
3.65625
4
[]
no_license
// WAP to calculate area of square using pass by refrence #include<iostream> using namespace std; void area(int &a){ a=a*a; } int main(){ int l; cout<< "Enter side of square\t"; cin>> l; area(l); cout<< "Area of square is"<<l; return 0; }
Markdown
UTF-8
3,702
3.015625
3
[ "Apache-2.0" ]
permissive
# The PDOStatement class I don&apos;t know why PDOStatement don&apos;t return "execution time" and "found rows" so here I created an extended class of PDOStatement with these attributes.<br><br>Just have to "setAttribute" of PDO&apos;s object to $PDO-&gt;setAttribute(\PDO::ATTR_STATEMENT_CLASS , [&apos;\customs\PDOStatement&apos;, [&amp;$this]]);<br><br> ``` <?php /** * * * */ namespace customs; /** * * * */ final class PDOStatement extends \PDOStatement { /** * * * */ protected $PDO = null; protected $inputParams = []; protected $executionTime = 0; protected $resultCount = 0; /** * * * */ protected function __construct(PDO &amp;$PDO) { $this->PDO = $PDO; $this->executionTime = microtime(true); } /** * * * */ final public function getExecutionError(int $i = 2) { $executionError = $this->errorInfo(); if (isset($executionError[$i])) return $executionError[$i]; return $executionError; } /** * * * */ final public function getExecutionTime($numberFormat = false, $decPoint = '.', $thousandsSep = ',') { if (is_numeric($numberFormat)) return number_format($this->executionTime, $numberFormat, $decPoint, $thousandsSep); return $this->executionTime; } /** * * * */ final public function getResultCount($numberFormat = false, $decPoint = '.', $thousandsSep = ',') { if (is_numeric($numberFormat)) return number_format($this->resultCount, $numberFormat, $decPoint, $thousandsSep); return $this->resultCount; } /** * * * */ final public function getLastInsertId() { return $this->PDO->lastInsertId(); } /** * * * */ final public function bindValues(array $inputParams) { foreach ($this->inputParams = array_values($inputParams) as $i => $value) { $varType = is_null($value) ? \PDO::PARAM_NULL : is_bool($value) ? \PDO::PARAM_BOOL : is_int($value) ? \PDO::PARAM_INT : \PDO::PARAM_STR; if (!$this->bindValue(++ $i, $value, $varType)) return false; } return true; } /** * * * */ final public function execute($inputParams = null) { if ($inputParams) $this->inputParams = $inputParams; if ($executed = parent::execute($inputParams)) $this->executionTime = microtime(true) - $this->executionTime; return $executed; } /** * * * */ final public function fetchAll($how = null, $className = null, $ctorArgs = null) { $resultSet = parent::fetchAll(... func_get_args()); if (!empty($resultSet)) { $queryString = $this->queryString; $inputParams = $this->inputParams; if (preg_match('/(.*)?LIMIT/is', $queryString, $match)) $queryString = $match[1]; $queryString = sprintf('SELECT COUNT(*) AS T FROM (%s) DT', $queryString); if (($placeholders = substr_count($queryString, '?')) < count($inputParams)) $inputParams = array_slice($inputParams, 0, $placeholders); if (($sth = $this->PDO->prepare($queryString)) &amp;&amp; $sth->bindValues($inputParams) &amp;&amp; $sth->execute()) $this->resultCount = $sth->fetchColumn(); $sth = null; } return $resultSet; } } ?> ``` --- [Official documentation page](https://www.php.net/manual/en/class.pdostatement.php) **[To root](/README.md)**
Java
UTF-8
3,402
4.125
4
[]
no_license
package Interviews.Nextdoor; import java.util.HashMap; public class Longest_Equal_SubArray { /** * Given an array containing only 0s and 1s, find the largest subarray which contain * equal no of 0s and 1s. Expected time complexity is O(n). * Examples: * * Input: arr[] = {1, 0, 1, 1, 1, 0, 0} * Output: 1 to 6 (Starting and Ending indexes of output subarray) * * Input: arr[] = {1, 1, 1, 1} * Output: No such subarray * * Input: arr[] = {0, 0, 1, 1, 0} * Output: 0 to 3 Or 1 to 4 * * https://www.geeksforgeeks.org/largest-subarray-with-equal-number-of-0s-and-1s/ */ /** * Approach: The concept of taking cumulative sum, taking 0’s as -1 will help us in * optimising the approach. While taking the cumulative sum, there are two cases when * there can be a sub-array with equal number of 0’s and 1’s. * * One, when cumulative sum=0, which signifies that sub-array from index (0) till present * index has equal number of 0’s and 1’s. * Two, when we encounter a cumulative sum value which we have already encountered before, * which means that sub-array from the previous index+1 till the present index has equal * number of 0’s and 1’s as they give a cumulative sum of 0 . * * In a nutshell this problem is equivalent to finding two indexes i & j in array[] such * that array[i] = array[j] and (j-i) is maximum. To store the first occurrence of each * unique cumulative sum value we use a hash_map wherein if we get that value again we can * find the sub-array size and compare it with maximum size found till now. */ public static int maxLen(int arr[], int n) { // Creates an empty hashMap hM HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int sum = 0; // Initialize sum of elements int max_len = 0; // Initialize result int ending_index = -1; int start_index = 0; for (int i = 0; i < n; i++) { arr[i] = (arr[i] == 0) ? -1 : 1; } // Traverse through the given array for (int i = 0; i < n; i++) { // Add current element to sum sum += arr[i]; if (sum == 0) { max_len = i + 1; ending_index = i; } // if (map.containsKey(sum + n)) { // if (max_len < i - map.get(sum + n)) { // max_len = i - map.get(sum + n); // ending_index = i; // } // } else {// Else put this sum in hash table // map.put(sum + n, i); // } if (map.containsKey(sum)) { if (max_len < i - map.get(sum)) { max_len = i - map.get(sum); ending_index = i; } } else {// Else put this sum in hash table map.put(sum, i); } } for (int i = 0; i < n; i++) { arr[i] = (arr[i] == -1) ? 0 : 1; } int end = ending_index - max_len + 1; System.out.println(end + " to " + ending_index); return max_len; } public static void main(String[] args) { int arr[] = {1, 0, 0, 1, 0, 1, 1}; int n = arr.length; System.out.println(maxLen(arr, n)); } }
Markdown
UTF-8
1,449
2.625
3
[]
no_license
<h1 align="center"> Enviar E-mails com C# via SMTP | <strong><a href="https://www.youtube.com/channel/UCHeVeHuy4m3HorYWirak2dg">Artigo Tech</a></strong> </h1> <div align="center"> ## Sobre o Projeto <p> Este projeto foi desenvolvido no 5º Episódio do quadro C# Na Prática no Canal do YouTube - <strong><a href="https://www.youtube.com/channel/UCHeVeHuy4m3HorYWirak2dg">Artigo Tech</a></strong>, nele te ensinei a desenvolver uma aplicação em Windows Forms que realiza o envio de e-mail com a linguagem de programação C#, utilizando o famoso protocolo SMTP. <br /> </p> </div> <div align="center"> ## Link do EP5 no YouTube <p> <strong>Aprenda a Enviar E-mails com C# via SMTP - EP5 C# Na Prática</strong> | <a href="https://www.youtube.com/watch?v=OGuQu13OiZk">Clique aqui para assistir!</a> <br /> <br /> <img src="https://i.ytimg.com/vi/OGuQu13OiZk/maxresdefault.jpg" alt="Aprenda a Enviar E-mails com C# via SMTP - EP5 C# Na Prática" /> </p> </div> <div align="center"> ## 🚀 Tecnologias usadas: ✔️ C# ✔️ .NET Framework ✔️ Windows Forms ✔️ SMTP </div> <hr /> <div align="center"> Feito com <span role="img" aria-label="coração">❤️</span> por <strong><a href="https://github.com/ivisconfessor">Ivís Confessor</a></strong> do Canal <strong><a href="https://www.youtube.com/channel/UCHeVeHuy4m3HorYWirak2dg">Artigo Tech</a></strong> </div>
SQL
UTF-8
1,085
3.34375
3
[]
no_license
DROP TABLE IF EXISTS users CASCADE; CREATE TABLE users( user_id VARCHAR(50) PRIMARY KEY, password VARCHAR(32) NOT NULL, email_address VARCHAR(256) NOT NULL, user_type VARCHAR(2) NOT NULL, enrol_date DATE NOT NULL, last_access DATE NOT NULL ); ALTER TABLE users OWNER TO group17_admin; INSERT INTO users VALUES( 'abala', md5('password1'), 'abala@dcmail.ca', 's', '2017-1-1', '2018-2-2'); INSERT INTO users(user_id, password, email_address, user_type, enrol_date, last_access) VALUES( 'johnsmith', md5('password2'), 'jsmith@dcmail.ca', 'a', '2017-1-1', '2018-2-2'); INSERT INTO users(user_id, password, email_address, user_type, enrol_date, last_access) VALUES( 'marysmith', md5('password3'), 'msmith@dcmail.ca', 'c', '2017-1-1', '2018-2-2'); INSERT INTO users VALUES( 'samclark', md5('password4'), 'samc@dcmail.ca', 'p', '2017-1-1', '2018-2-2'); INSERT INTO users VALUES( 'savaliyad', md5('password5'), 'savaliyad@dcmail.ca', 'a', '2016-1-1', '2018-2-2'); INSERT INTO users VALUES( 'savaliyan', md5('password6'), 'savaliyan@dcmail.ca', 'pa', '2018-1-1', '2018-2-2'); SELECT * FROM users;
Python
UTF-8
1,291
3.53125
4
[]
no_license
# -*- coding: utf-8 -*- __author__ = 'Olav Espenes' __email__ = 'olaves@nmbu.no' class LCGRand: def __init__(self, seed): self.seed = seed self.a = 7**5 self.m = 2 ** 31 - 1 def rand(self): while True: self.seed = (self.a * self.seed) % self.m return self.seed def random_sequence(self, length): return RandIter(self, length) def infinite_random_sequence(self): return RandIter(self, -1) class RandIter: def __init__(self, random_number_generator, length): self.generator = random_number_generator self.length = length self.num_generated_numbers = None def __iter__(self): print('Initialising iterator') if self.num_generated_numbers is not None: raise RuntimeError( 'Can only be initialised as an iterator once' ) self.num_generated_numbers = -1 return self def __next__(self): self.num_generated_numbers += 1 if self.num_generated_numbers is None: raise RuntimeError( 'Cannot call `next`before iter is initialised' ) if self.num_generated_numbers == self.length: raise StopIteration return self.generator.rand()
Markdown
UTF-8
7,710
2.6875
3
[ "Apache-2.0" ]
permissive
# Contributing to Otoroshi These guidelines apply to all Otoroshi projects living in the the `MAIF/otoroshi` repository. These guidelines are meant to be a living document that should be changed and adapted as needed. We encourage changes that make it easier to achieve our goals in an efficient way. ## Codebase * [docker](https://github.com/MAIF/otoroshi/docker): contains various Dockerfiles * [docs](https://github.com/MAIF/otoroshi/docs): contains the Otoroshi website, avoid modification as its generated * [manual](https://github.com/MAIF/otoroshi/manual): the otoroshi user manual that will be generated with [Paradox](https://github.com/lightbend/paradox) * [otoroshi](https://github.com/MAIF/otoroshi/otoroshi): the otoroshi server app * [resources](https://github.com/MAIF/otoroshi/resources): various static resources * [scripts](https://github.com/MAIF/otoroshi/scripts): various scripts used by Travis and devs ## Workflow The steps below describe how to get a patch into a main development branch (e.g. `master`). The steps are exactly the same for everyone involved in the project (be it core team, or first time contributor). We follow the standard GitHub [fork & pull](https://help.github.com/articles/using-pull-requests/#fork--pull) approach to pull requests. Just fork the official repo, develop in a branch, and submit a PR! 1. To avoid duplicated effort, it might be good to check the [issue tracker](https://github.com/MAIF/otoroshi/issues) and [existing pull requests](https://github.com/MAIF/otoroshi/pulls) for existing work. - If there is no ticket yet, feel free to [create one](https://github.com/MAIF/otoroshi/issues/new) to discuss the problem and the approach you want to take to solve it. 1. [Fork the project](https://github.com/MAIF/otoroshi#fork-destination-box) on GitHub. You'll need to create a feature-branch for your work on your fork, as this way you'll be able to submit a pull request against the mainline Otoroshi. 1. Create a branch on your fork and work on the feature. For example: `git checkout -b wip-awesome-new-feature` - Please make sure to follow the general quality guidelines (specified below) when developing your patch. - Please write additional tests covering your feature and adjust existing ones if needed before submitting your pull request. 1. Once your feature is complete, prepare the commit with a good commit message, for example: `Adding canary mode support for services #42` (note the reference to the ticket it aimed to resolve). 1. If it's a new feature, or a change of behaviour, document it on the [Otoroshi docs](https://github.com/MAIF/otoroshi/tree/master/manual), remember, an undocumented feature is not a feature. 1. Now it's finally time to [submit the pull request](https://help.github.com/articles/using-pull-requests)! - Please make sure to include a reference to the issue you're solving *in the comment* for the Pull Request, this will cause the PR to be linked properly with the Issue. Examples of good phrases for this are: "Resolves #1234" or "Refs #1234". 1. Now both committers and interested people will review your code. This process is to ensure the code we merge is of the best possible quality, and that no silly mistakes slip through. You're expected to follow-up these comments by adding new commits to the same branch. The commit messages of those commits can be more loose, for example: `Removed debugging using printline`, as they all will be squashed into one commit before merging into the main branch. - The community and team are really nice people, so don't be afraid to ask follow up questions if you didn't understand some comment, or would like clarification on how to continue with a given feature. We're here to help, so feel free to ask and discuss any kind of questions you might have during review! 1. After the review you should fix the issues as needed (pushing a new commit for new review etc.), iterating until the reviewers give their thumbs up–which is signalled usually by a comment saying `LGTM`, which means "Looks Good To Me". 1. If the code change needs to be applied to other branches as well (for example a bugfix needing to be backported to a previous version), one of the team will either ask you to submit a PR with the same commit to the old branch, or do this for you. 1. Once everything is said and done, your pull request gets merged. You've made it! The TL;DR; of the above very precise workflow version is: 1. Fork Otoroshi 2. Hack and test on your feature (on a branch) 3. Document it 4. Submit a PR 6. Keep polishing it until received thumbs up from the core team 7. Profit! ## External dependencies All the external runtime dependencies for the project, including transitive dependencies, must have an open source license that is equal to, or compatible with, [Apache 2](http://www.apache.org/licenses/LICENSE-2.0). This must be ensured by manually verifying the license for all the dependencies for the project: 1. Whenever a committer to the project changes a version of a dependency (including Scala) in the build file. 2. Whenever a committer to the project adds a new dependency. 3. Whenever a new release is cut (public or private for a customer). Which licenses are compatible with Apache 2 are defined in [this doc](http://www.apache.org/legal/3party.html#category-a), where you can see that the licenses that are listed under ``Category A`` are automatically compatible with Apache 2, while the ones listed under ``Category B`` need additional action: > Each license in this category requires some degree of [reciprocity](http://www.apache.org/legal/3party.html#define-reciprocal); therefore, additional action must be taken in order to minimize the chance that a user of an Apache product will create a derivative work of a reciprocally-licensed portion of an Apache product without being aware of the applicable requirements. Each project must also create and maintain a list of all dependencies and their licenses, including all their transitive dependencies. This can be done either in the documentation or in the build file next to each dependency. You must add the dependency and its licence in https://github.com/MAIF/otoroshi/blob/master/licences.md ## Documentation if you add features to Otoroshi, don't forget to modify the user manual, the swagger file * https://github.com/MAIF/otoroshi/tree/master/manual/src/main/paradox * https://github.com/MAIF/otoroshi/blob/master/otoroshi/app/controllers/SwaggerController.scala to build the documentation, run the following command at the root of the repository ```sh sh ./scripts/doc.sh ``` ## Tests Every new feature should provide corresponding tests to ensure everything is working and will still working in future releases. To run the tests, just run ```sh sbt test ``` you can also run the tests using other datastores ```sh TEST_STORE=inmemory sbt test TEST_STORE=redis sbt test TEST_STORE=cassandra sbt test ``` cassandra and redis tests will try to connect to local instance of cassandra and redis running on standard ports. ```sh docker run -d -p 9042:9042 -p 7000:7000 --env CASSANDRA_LISTEN_ADDRESS=127.0.0.1 cassandra:3.11 docker run -d -p 6379:6379 redis:4.0.8 redis-server --appendonly yes ``` ## Source style The whole code of Otoroshi is automatically formatted using * prettier * rust_fmt * scalafmt before pushing your code, don't forget to run the following command at the root of the repository ```sh sh ./scripts/fmt.sh ``` ## Continuous integration Every commit and PR to Otoroshi is built by [Travis](https://travis-ci.org/MAIF/otoroshi). Travis will also check your pull request to prevent merging code that does not build.
Ruby
UTF-8
355
2.84375
3
[]
no_license
# Modules class Math def add(a, b) a + b end def subtract(a, b) a - b end end math = Math.new sum = math.add(2, 2) module Math def add(a, b) a + b end def subtract(a, b) a - b end end class CashRegister include Math def calculate_change(total_cost, amount_paid) subtract(amount_paid, total_cost) end end
Python
UTF-8
1,812
3
3
[]
no_license
""" Tests the custom user model """ from django.test import TestCase from django.contrib.auth import get_user_model class UserModelTest(TestCase): """ Tests the default user model """ def test_create_user_with_email_successful(self): """ Test creating user model with email is successful. """ email = "test@example.com" password = "testpassword123" user = get_user_model().objects.create_user( email=email, password=password ) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password)) def test_new_user_email_normalized(self): """ Test email is normalized for new users """ sample_emails = [ ["test1@EXAMPLE.COM", "test1@example.com"], ["Test2@EXAMPLE.com", "Test2@example.com"], ["TEST3@EXAMPLE.COM", "TEST3@example.com"], ["test4@example.COM", "test4@example.com"], ] for email, expected in sample_emails: user = get_user_model().objects.create_user(email, "sample123") self.assertEqual(user.email, expected) def test_new_user_without_email_raises_error(self): """ Test creating a user without email raises a ValueError """ with self.assertRaises(ValueError) as ve: _ = get_user_model().objects.create_user( email="", password="password123" ) self.assertEqual( str(ve.exception), "Email must be provided for all users." ) def test_create_superuser(self): """ Test creating a superuser """ user = get_user_model().objects.create_superuser( email="test@example.com", password="test123" ) self.assertTrue(user.is_superuser) self.assertTrue(user.is_staff)
Markdown
UTF-8
3,274
2.859375
3
[]
no_license
JS获取body及屏幕的高宽: 参考文档: http://www.cnblogs.com/dolphinX/archive/2012/11/19/2777756.html http://www.ruanyifeng.com/blog/2009/09/find_element_s_position_using_javascript.html http://www.cnblogs.com/rubylouvre/archive/2009/08/24/1552862.html http://itindex.net/detail/51490-js-%E9%BC%A0%E6%A0%87-%E4%BD%8D%E7%BD%AE 1. clientHeight和clientWidth用于描述元素内尺寸,是指 元素内容+内边距大小,不包括边框(IE下实际包括)、外边距、滚动条部分 2. offsetHeight和offsetWidth用于描述元素外尺寸,是指 元素内容+内边距+边框,不包括外边距和滚动条部分 3. clientTop和clientLeft返回内边距的边缘和边框的外边缘之间的水平和垂直距离,也就是左,上边框宽度 4. offsetTop和offsetLeft表示该元素的左上角(边框外边缘)与已定位的父容器(offsetParent对象)左上角的距离 5. offsetParent对象是指元素最近的定位(relative,absolute)祖先元素,递归上溯,如果没有祖先元素是定位的话,会返回null 6. scrollWidth和scrollHeight是元素的内容区域加上内边距加上溢出尺寸,当内容正好和内容区域匹配没有溢出时,这些属性与clientWidth和clientHeight相等 7. scrollLeft和scrollTop是指元素滚动条位置,它们是可写的 获取文档坐标位置: 任何HTML元素都拥有offectLeft和offectTop属性返回元素的X和Y坐标,对于很多元素,这些值是文档坐标,但是对于以定位元素后代及一些其他元素(表格单元),返回相对于祖先的坐标。 x += e.offsetLeft; y += e.offsetTop; e = e.offsetParent; 获取div可视区域的位置: 通过getBoundingClientRect(); var topicsObj = document.getElementById("topics"); topics.getBoundingClientRect().top 网页可见区域宽:document.body.clientWidth 或者 document.documentElement.clientWidth 网页可见区域宽:document.body.offsetWidth 网页正文全文宽:document.body.scrollWidth 网页被卷去的高:document.body.scrollTop 屏幕分辨率的高:window.screen.height 屏幕可用工作区高度:window.screen.availHeight 鼠标位置: 相对于屏幕: function getMousePos(event) { var e = event || window.event; return {'x':e.screenX,'y':screenY} } 相对浏览器窗口 function getMousePos(event) { var e = event || window.event; return {'x':e.clientX,'y':clientY} } 相对文档 function getMousePos(event) { var e = event || window.event; var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; var scrollY = document.documentElement.scrollTop || document.body.scrollTop; var x = e.pageX || e.clientX + scrollX; var y = e.pageY || e.clientY + scrollY; return { 'x': x, 'y': y }; } Firefox支持属性pageX,与pageY属性,这两个属性已经把页面滚动计算在内了。 在Chrome可以通过document.body.scrollLeft,document.body.scrollTop计算出页面滚动位移, 而在IE下可以通过document.documentElement.scrollLeft ,document.documentElement.scrollTop
PHP
UTF-8
1,287
3
3
[ "MIT" ]
permissive
<?php namespace Calculator\Dao; /** * Class CalculatorLog * * @package Calculator\Dao */ class Memory { /** * @var \PDO */ protected $dbm; /** * @param \PDO $dbm */ public function setDbm(\PDO $dbm) { $this->dbm = $dbm; } /** * @param int $calculator_id * @return int */ public function retrieveLatestMemoryEntry($calculator_id) { $query = 'SELECT entry FROM Memory WHERE calculator_id = :calculator_id ORDER BY date_added DESC LIMIT 1'; $statement = $this->dbm->prepare($query); $statement->execute(['calculator_id' => $calculator_id]); $result = $statement->fetchColumn(); return $result; } /** * @param int $calculator_id * @param int $entry */ public function insertMemoryEntry($calculator_id, $entry) { $query = 'INSERT INTO Memory (calculator_id, entry) VALUES (:calculator_id, :entry)'; $statement = $this->dbm->prepare($query); $statement->execute([ 'calculator_id' => $calculator_id, 'entry' => $entry ]); } }
Markdown
UTF-8
394
2.515625
3
[]
no_license
# Olymbic-Data-Analysis ETG Intern ## About the repo? I have analysed the summer olymbics dataset and performed some operations. You'll learn how to handle the data. ## Features Required operations are made and vizualised. ## Implementation I have used colab for this project. "Summer_Olympics.ipynb" contains the code. ## LinkedIn profile https://www.linkedin.com/in/darshini-r-381771193/
Python
UTF-8
4,317
2.8125
3
[]
no_license
# Copyright (C) 2014 SensorLab, Jozef Stefan Institute # http://sensorlab.ijs.si # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. */ # Authors: Mihai Suciu # import time import math class PlayerTransmitLayer: """ The application part of a game player. It is responsible for signal generation. It uses a player and powerAllocation object. """ # time when transmission starts [s]. A new signal is generated only when the old transmission stops. timeStartTx = 0 # transmission duration [s]. How many seconds the player will transmit signal. Can change. transmissionDuration = 6 # frequency used for transmitting signal [Hz] txFrequency = 2420e6 # current transmission power [dBm]. Usually this is updated before transmitting data. currentTransmPower = 0.00 def __init__(self, physicalLayerObjectForTxLayer, gameFrequency=2420e6): """ Constructor for player application layer. Keyword arguments: playerObject -- Reference to player object. Used to get tx and rx nodes. gameFrequency -- Transmission frequency (default 2420e6 Hz). """ self.physicalLayer = physicalLayerObjectForTxLayer self.txFrequency = gameFrequency def printPlayerTxLayerInfo(self): """Just print player id and some info""" print "Transmission layer associated to player %d" % (self.physicalLayer.playerObject.playerNumber) def getTransmissionPower(self): """Return current transmission power""" return self.physicalLayer.currentTxPower def isSendingData(self): """Return True if player is transmitting data""" if time.time() - self.timeStartTx < self.transmissionDuration: return True else: return False def sleepUntilSignalGenerationStops(self): """Wait for previous transmission to stop.""" if time.time() - self.timeStartTx < self.transmissionDuration: # wait for transmission to stop print "Player %d wait for %f seconds until previous transmission ends." % (self.physicalLayer.playerObject.playerNumber, math.ceil(self.transmissionDuration - (time.time() - self.timeStartTx))) time.sleep(math.ceil(self.transmissionDuration - (time.time() - self.timeStartTx))) return def sendData(self, txDuration): """Transmit data for a certain amount of time. Keyword arguments: txDuraiton -- transmission duration. """ self.transmissionDuration = txDuration # wait for previous transmission to stop self.sleepUntilSignalGenerationStops() # get current tx power self.currentTransmPower = self.physicalLayer.getCrtTxPower() attempts = 0 while True: try: self.physicalLayer.txNode.setGeneratorConfiguration(self.txFrequency, self.currentTransmPower) self.physicalLayer.txNode.generatorStart(time.time(), self.transmissionDuration) self.timeStartTx = time.time() print "Player %d is transmitting for %.3f seconds with %.d dBm.\n" % (self.physicalLayer.playerObject.playerNumber, self.transmissionDuration, self.currentTransmPower) break except: attempts += 1 if attempts >= 10: print "Player %d cannot transmit at current configuration, number of attempts %d.\n" % (self.physicalLayer.playerObject.playerNumber, attempts) break print "Player %d failed to transmit at current configuration. Retry number %d.\n" % (self.physicalLayer.playerObject.playerNumber, attempts) continue return
TypeScript
UTF-8
2,626
3.5
4
[ "MIT" ]
permissive
/** * Created by syjmac on 2017/8/23. * *开关器 可以设置任意位数的开关位 并且灵活控制每位的开关状态 * * 参数不与许空字符串和 0 之类本身为false的值 * * let a=new Switcher("over","xx","v","a") a.on("over").on("v").on("a").off("v").off() console.log(a.isOn("a")); console.log(a.isOn("over")); console.log(a.isOn()); console output _readable 1 _readable 101 _readable 1101 _readable 1001 _readable 1001 true true true */ import {IBitSwitcher} from "./BitSwitcher"; export default class LongBitSwitcher<T> implements IBitSwitcher<T> { readonly MAX_LEN: number = Infinity; private map: Map<T,boolean>; constructor(...keys: T[]) { // if (!keys || keys.length == 0){throw new Error("开关不能空,需要至少一个位");} this.map = new Map(keys.map((e): [T, boolean] => [e, false])) } getKeys() { return this.map.keys(); } isAllOn() { let values = [...this.map.values()] return values.indexOf(false) == -1; } /*有一个开即为开*/ isOn(flag?: T) { if (flag) { return !!(this.map.has(flag) ? this.map.get(flag) : false) } return [...this.map.values()].indexOf(true) != -1 } on(flag?: T) { if (flag && this.map.has(flag)) { this.map.set(flag, true) } return this; } off(flag: T) { if (flag && this.map.has(flag)) { this.map.set(flag, false) } return this; } /*把自己的key对应的状态位从目标对象上拷贝下来*/ copyFrom(from: IBitSwitcher<T>) { let fromKeysArr = [...from.getKeys()] for (let key of this.getKeys()) { if (fromKeysArr.indexOf(key) !== -1) { let isOn = from.isOn(key); isOn ? (this.on(key)) : (this.off(key)); } } return this; } /*对比是否有一样的开关位,返回不同的数组*/ switcherDiff(target: IBitSwitcher<T>|Array<T>) { let thisK = this.getKeys(), arr1 = [...thisK].sort(), arr2; if (target instanceof Array) { arr2 = target.sort() } else { let targetK = target.getKeys(); arr2 = [...targetK].sort(); } let added: T[] = [],//自己没有的但是target里有 deleted: T[] = [];//自己原本有但是target里面没有了 if (arr1.join("-") == arr2.join("-"))return { added, deleted, diff: false }; let uniqueAll = new Set(arr1.concat(arr2)); for (let unique of uniqueAll) { let originHas = arr1.includes(unique); let nowHas = arr2.includes(unique); if (originHas != nowHas) {//不是都有就是不同 (originHas ? deleted : added).push(unique) } } return { added, deleted, diff: !(added.length == deleted.length && deleted.length == 0) } } }
JavaScript
UTF-8
2,274
4.65625
5
[]
no_license
// scope : 변수 혹은 함수를 선언하게 될 때 해당 변수 또는 함수가 유효한 범위 //1. Global (전역) Scope : 코드의 모든 범위에서 사용이 가능 //2. Function (함수) Scope : 함수 안에서만 사용이 가능 //3. Block (블록) Scope : if, for, switch 등 특정 블록 내부에서만 사용이 가능 //2,3 지역변수라고도함 //예시1 const value = "hello!"; //Global Scope function myFunction() { console.log("myFunction: "); console.log(value); } function otherFunction() { console.log("otherFunction: "); const value = "bye!"; console.log(value); // Function Scope -> Global 에는 영향을 주지않음 } myFunction(); otherFunction(); console.log("global scope: "); console.log(value); //Global Scope 출력 //예시2 const value = "hello!"; function myFunction() { const value = "bye!"; const anotherValue = "world"; function functionInside() { console.log("functionInside: "); console.log(value); //bye! console.log(anotherValue); //world } functionInside(); } myFunction() console.log("global scope: "); console.log(value); //hello! console.log(anotherValue); //not defined //예시3 - 함수안에 조건문 안에 블록변수 사용 const value = 'hello!'; function myFunction() { const value = 'bye!'; if (true) { const value = 'world'; console.log('block scope: '); console.log(value); //world } console.log('function scope: '); console.log(value); //bye! } myFunction(); console.log('global scope: '); console.log(value); //hello! //예시4 - var 을 사용했을때 var value = 'hello!'; function myFunction() { var value = 'bye!'; if (true) { var value = 'world'; console.log('block scope: '); console.log(value); //world } console.log('function scope: '); console.log(value); //world } myFunction(); console.log('global scope: '); console.log(value); //hello! //var로 선언시 : 블록단위로 보는게 아니라 함수단위로 보기떄문에 다른 블록이더라도 영향이 감 //let으로 선언시 : 블록단위로 보기때문에 블록 밖에는 영향ㅇ ㅣ가지 않음 //var 보단 let을 사용 해야하는 이유!!!
JavaScript
UTF-8
3,079
2.578125
3
[]
no_license
// Aetna Custom Widget to create an email custom condition for forms Aetna.EmailCondition = CQ.Ext.extend(CQ.form.CompositeField, { /** * @private * @type CQ.Ext.form.Hidden */ hiddenField : null, /** * @private * @type CQ.Ext.form.TextField */ inputValue : null, /** * @private * @type CQ.Ext.form.TextField */ emailAddress : null, constructor : function(config) { config = config || {}; var defaults = { "border" : true, "labelWidth" : 45, "layout" : "form" }; config = CQ.Util.applyDefaults(config, defaults); Aetna.EmailCondition.superclass.constructor.call(this, config); }, // overriding CQ.Ext.Component#initComponent initComponent : function() { Aetna.EmailCondition.superclass.initComponent.call(this); // Hidden field this.hiddenField = new CQ.Ext.form.Hidden({ name : this.name }); this.add(this.hiddenField); // inputValue this.inputValue = new CQ.Ext.form.TextField({ cls : "inputValue", allowBlank : false, fieldLabel : "Input Value: ", width : "90%", maxLength : 90, fieldDescription : "Selected value to compare", labelStyle : "margin-left : 5px;", listeners : { change : { scope : this, fn : this.updateHidden } } }); this.add(this.inputValue); // emailAddress this.emailAddress = new CQ.Ext.form.TextField({ cls : "emailAddress", allowBlank : false, fieldLabel : "Email Address: ", width : "90%", maxLength : 500, fieldDescription : "Email address to use when the value is selected", labelStyle : "margin-left : 5px;", listeners : { change : { scope : this, fn : this.updateHidden } } }); this.add(this.emailAddress); }, processInit : function(path, record) { this.inputValue.processInit(path, record); this.emailAddress.processInit(path, record); }, setValue : function(value) { var emailCondition = JSON.parse(value); this.inputValue.setValue(emailCondition.inputValue); this.emailAddress.setValue(emailCondition.emailAddress); this.hiddenField.setValue(value); }, getValue : function() { return this.getRawValue(); }, getRawValue : function() { var emailCondition = { "inputValue" : this.inputValue.getValue(), "emailAddress" : this.emailAddress.getValue(), }; return JSON.stringify(emailCondition); }, updateHidden : function() { this.hiddenField.setValue(this.getValue()); } }); CQ.Ext.reg('aetna.emailcondition', Aetna.EmailCondition);
TypeScript
UTF-8
17,857
2.96875
3
[ "MIT" ]
permissive
/** * Tests for ParameterValidation. */ import * as Chai from "chai"; import * as Sinon from "sinon"; import { ParameterValidation } from "../../../../src/helpers/parameterValidation"; import { ILogger } from "../../../../src/interfaces/ILogger"; describe("ParameterValidation", () => { let sandbox: Sinon.SinonSandbox; let loggerStub: ILogger; let spiedErrorMethod: Sinon.SinonSpy; let spiedInfoMethod: Sinon.SinonSpy; beforeEach(() => { sandbox = Sinon.createSandbox(); loggerStub = <ILogger>{}; loggerStub.error = () => {}; loggerStub.info = () => {}; spiedErrorMethod = sandbox.spy(loggerStub, "error"); spiedInfoMethod = sandbox.spy(loggerStub, "info"); }); afterEach(() => { sandbox.restore(); }); it("can be created", () => { const obj = new ParameterValidation(); Chai.should().exist(obj); }); describe("checkPackageName", () => { it("can fail when called with null", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", null)).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail when called with undefined", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", undefined)).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail when called with empty string", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail when called with string > 214", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "a".repeat(215))).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can succeed when called with string === 214", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "a".repeat(214))).to.equal(true); Chai.expect(spiedInfoMethod.called).to.equal(true); }); it("can fail with upper case character", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "packageName")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can succeed with only lower case characters", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "packagename", "a")).to.equal(true); Chai.expect(spiedInfoMethod.called).to.equal(true); }); it("can fail if starts with .", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", ".packagename")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if starts with -", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "-packagename")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if starts with _", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "_packagename")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if contains \\", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package\\name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if contains /", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package/name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if contains (", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package(name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if contains )", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package)name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if contains &", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package&name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if contains ?", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package?name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if contains #", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package#name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if contains |", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package|name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if contains <", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package<name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if contains >", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package>name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if contains @", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package@name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if contains :", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package:name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if contains %", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package%name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if contains whitespace", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if contains *", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package*name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if contains '", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package'name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if contains \"", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package\"name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if contains !", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package!name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if contains ~", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package~name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if contains `", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package`name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if non url safe characters ,", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package,name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if non url safe characters +", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package+name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if non url safe characters ;", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package;name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if non url safe characters $", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package$name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if non url safe characters =", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package=name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if non url safe characters [", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package[name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if non url safe characters ]", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package]name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail if non url safe characters ^", () => { Chai.expect(ParameterValidation.checkPackageName(loggerStub, "param", "package^name")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); }); describe("checkPattern", () => { it("can fail when called with null", () => { Chai.expect(ParameterValidation.checkPattern(loggerStub, "param", null, /a/, "message")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail when called with undefined", () => { Chai.expect(ParameterValidation.checkPattern(loggerStub, "param", undefined, /a/, "message")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail when called with empty string", () => { Chai.expect(ParameterValidation.checkPattern(loggerStub, "param", "", /a/, "message")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail when called with null pattern", () => { Chai.expect(ParameterValidation.checkPattern(loggerStub, "param", "a", null, "message")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail when called with undefined pattern", () => { Chai.expect(ParameterValidation.checkPattern(loggerStub, "param", "a", undefined, "message")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail when called with no pattern match", () => { Chai.expect(ParameterValidation.checkPattern(loggerStub, "param", "b", /a/, "message")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can succeed when called with pattern match", () => { Chai.expect(ParameterValidation.checkPattern(loggerStub, "param", "a", /a/, "message")).to.equal(true); Chai.expect(spiedInfoMethod.called).to.equal(true); }); }); describe("checkOneOf", () => { it("can fail when called with null", () => { Chai.expect(ParameterValidation.checkOneOf(loggerStub, "param", null, [])).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail when called with undefined", () => { Chai.expect(ParameterValidation.checkOneOf(loggerStub, "param", undefined, [])).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail when called with empty string", () => { Chai.expect(ParameterValidation.checkOneOf(loggerStub, "param", "", [])).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail when called with empty null values", () => { Chai.expect(ParameterValidation.checkOneOf(loggerStub, "param", "a", null)).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail when called with empty undefined values", () => { Chai.expect(ParameterValidation.checkOneOf(loggerStub, "param", "a", undefined)).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail when called with value not in values", () => { Chai.expect(ParameterValidation.checkOneOf(loggerStub, "param", "b", ["a"])).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail when called with value not in values custom error", () => { Chai.expect(ParameterValidation.checkOneOf(loggerStub, "param", "b", ["a"], "err")).to.equal(false); Chai.expect(spiedErrorMethod.calledWith("param", "err")).to.equal(true); }); it("can succeed when called with value in values", () => { Chai.expect(ParameterValidation.checkOneOf(loggerStub, "param", "a", ["a"])).to.equal(true); Chai.expect(spiedInfoMethod.called).to.equal(true); }); }); describe("notEmpty", () => { it("can fail when called with null", () => { Chai.expect(ParameterValidation.notEmpty(loggerStub, "param", null)).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail when called with undefined", () => { Chai.expect(ParameterValidation.notEmpty(loggerStub, "param", undefined)).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail when called with empty string", () => { Chai.expect(ParameterValidation.notEmpty(loggerStub, "param", "")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail when called with empty string array", () => { Chai.expect(ParameterValidation.notEmpty(loggerStub, "param", [])).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can succeed when called with string value", () => { Chai.expect(ParameterValidation.notEmpty(loggerStub, "param", "a")).to.equal(true); Chai.expect(spiedInfoMethod.called).to.equal(true); }); it("can succeed when called with string array value", () => { Chai.expect(ParameterValidation.notEmpty(loggerStub, "param", ["a"])).to.equal(true); Chai.expect(spiedInfoMethod.called).to.equal(true); }); }); describe("notEmptyNumber", () => { it("can fail when called with null", () => { Chai.expect(ParameterValidation.notEmptyNumber(loggerStub, "param", null)).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail when called with undefined", () => { Chai.expect(ParameterValidation.notEmptyNumber(loggerStub, "param", undefined)).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail when called with 0", () => { Chai.expect(ParameterValidation.notEmptyNumber(loggerStub, "param", 0)).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can succeed when called with > 0", () => { Chai.expect(ParameterValidation.notEmptyNumber(loggerStub, "param", 1)).to.equal(true); Chai.expect(spiedInfoMethod.called).to.equal(true); }); }); describe("isColor", () => { it("can fail when called with null", () => { Chai.expect(ParameterValidation.isColor(loggerStub, "param", null)).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail when called with undefined", () => { Chai.expect(ParameterValidation.isColor(loggerStub, "param", undefined)).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail when called with empty string", () => { Chai.expect(ParameterValidation.isColor(loggerStub, "param", "")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can fail when called with non color string", () => { Chai.expect(ParameterValidation.isColor(loggerStub, "param", "a")).to.equal(false); Chai.expect(spiedErrorMethod.called).to.equal(true); }); it("can succeed when called with color string", () => { Chai.expect(ParameterValidation.isColor(loggerStub, "param", "#123")).to.equal(true); Chai.expect(spiedInfoMethod.called).to.equal(true); }); }); });
PHP
UTF-8
1,074
2.59375
3
[ "Zlib" ]
permissive
<?php /** * Created by PhpStorm. * User: morontt * Date: 16.09.17 * Time: 10:42 */ namespace Mtt\BlogBundle\Command\Telegram; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class WebhookCommand extends AbstractTelegramCommand { protected function configure() { $this ->setName('mtt:telegram:webhook') ->setDescription('Set webhook for telegram bot') ->addArgument('url', InputArgument::REQUIRED, 'Webhook URL') ->addArgument('certificate', InputArgument::OPTIONAL, 'Path to certificate') ; } /** * @param InputInterface $input * @param OutputInterface $output */ protected function execute(InputInterface $input, OutputInterface $output) { $result = $this->bot->setWebhook($input->getArgument('url'), $input->getArgument('certificate')); if ($result->isOk()) { $output->writeln($result->getDescription()); } } }
Python
UTF-8
3,022
2.6875
3
[]
no_license
import numpy as np import pandas as pd import glob import matplotlib.pyplot as plt def ReadInputCSVFiles(filename): print(filename) df = pd.read_csv(filename) return df def ReadInputTXTFiles(filename): print(filename) info = pd.read_csv(filename, nrows=0) sta = info.columns[0].split() df = pd.read_fwf(filename, skiprows=[0]) col = ['Date', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] df.columns = col years = df[df['Date']>1900],['Date'] # 2. Extract year list and create date range date_start = str(years.iloc[0])+'-01-01' date_end = str(years.iloc[-1])+'-12-31' daterng = pd.date_range(start=date_start, end=date_end, freq='D') data = np.nan * np.zeros(daterng.size) df2 = pd.DataFrame(data, columns = [sh], index=daterng) # 3. Convert table to 1D array for yr in years: ind1 = np.where(df['Date']==yr)[0][0] ind2 = np.where(df2.index==str(yr)+'-01-01')[0][0] k = 0 for mon in range(1,13): num_day_month = pd.Period(str(yr)+'-'+str(mon)).days_in_month for day in range(1, num_day_month+1): df2.iloc[ind2+k][sh] = df.iloc[ind1+day][df.columns[mon]] k += 1 return sta, df def HeatWaveIdentification(df,col,quant): # Idenfify quantile df = df[df['YEAR']==2014] hw_thres = df[col].quantile(quant) print('thres:', hw_thres) # HEATWAVE DETECTION # tag rows based on the threshold df['tag'] = df[col] > hw_thres # first row is a True preceded by a False (first month of an event) fst = df.index[df['tag'] & ~ df['tag'].shift(1).fillna(False)] # last row is a True followed by a False (last month of an event) lst = df.index[df['tag'] & ~ df['tag'].shift(-1).fillna(False)] durations = lst - fst + 1 durations = durations[durations>=3] num_years = df.iloc[-1]['YEAR'] - df.iloc[0]['YEAR'] + 1. print('Number of heat wave:', len(durations)) print('Number of heat wave per year:', len(durations)/num_years) return durations, df if __name__ == '__main__': filelist = glob.glob('T*.csv') f = 'Tx_R3.txt' sta, dfn = ReadInputTXTFiles(f) for f in filelist: # Doc du lieu tu file df = ReadInputCSVFiles(f) # Xac dinh heat wave durations, df2 = HeatWaveIdentification(df,'MAX_TMP',0.9) #df = pd.read_fwf('Tx_R3.txt',skiprows=1121,nrows=500) # y=a*x+b # plt.figure() # plt.plot(R_ann,'o') # plt.plot(x,y,ls='-') # plt.title(file) # plt.figure() # plt.plot(x, R_ann,'o') # plt.plot(x, res[1] + res[0] * x, 'r-') # plt.plot(x, res[1] + res[2] * x, 'r--') # plt.plot(x, res[1] + res[3] * x, 'r--') # plt.plot(x, lsq_res[1] + lsq_res[0] * x, 'g-') # plt.title(file) # plt.plot(df_tram['rainfall'].values) # plt.show()
Java
UTF-8
2,074
2.59375
3
[]
no_license
package mechanics.system.jar; import com.beust.jcommander.Parameter; import mechanics.system.readers.Variables; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Created by Alex Storm on 16.05.2017. */ public class Args { @Parameter private List<String> parameters = new ArrayList<>(); @Parameter(names = { "-stage", "-s" }, description = "Environment to test: dev/stage/other") public static String stage = "dev"; @Parameter(names = { "-file", "-f"}, description = "Test suite .xml file in xml/ folder") public static String file = "testng.xml"; @Parameter(names = {"-browser", "-b"}, description = "Browser name for selenium") public static String browser = "chrome"; @Parameter(names = {"-grid", "-g"}, description = "Use selenium grid?") public static boolean grid = false; @Parameter(names = {"-help", "-h"}, help = true) private boolean help; public void help(){ if (help){ System.out.println("'-s' or '-stage' - sets stage to run on (dev/prod/etc.)"); System.out.println("'-f' or '-file' - sets test suite .xml file (in folder xml/), default is testng.xml"); System.out.println("'-b' or '-browser' - sets browser to run UI part of the test, default is chrome"); System.out.println("'-g' or '-grid' - with value 'true' enables selenium grid connection, default is false"); System.out.println("'-h' or '-help' - displays this message"); System.out.println("example of launch command: java -javaagent:aspectjweaver.jar -jar iot-auto-fat.jar -s wstaging -f api.xml"); System.exit(0); } } public void setStage(){ Variables variables = new Variables(); variables.findAndAssembleStage(stage); } public void print() { System.out.println("Stage: "+stage); System.out.println("Browser: "+browser); System.out.println("Selenium grid: "+grid); System.out.println("File: "+new File(file).getAbsoluteFile()); } }
Java
UTF-8
2,275
2.328125
2
[]
no_license
package com.example.manoel.maratoneia1.ResultsMovie; import android.os.AsyncTask; import android.view.View; import com.airbnb.lottie.LottieAnimationView; import com.example.manoel.maratoneia1.Movies.MovieAdapterCategory; import com.example.manoel.maratoneia1.Movies.MovieFragment; import com.google.gson.Gson; import java.util.ArrayList; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MovieTask extends AsyncTask<String,Void,DataMovie> { private OkHttpClient clientHttp = new OkHttpClient(); private Gson gson = new Gson(); private Response response = null; private Request request = null; private MovieAdapterCategory adapterCategory; private ArrayList<ResultMovie> movieList = null; private DataMovie resultRequest = null; private LottieAnimationView lottieAnimationView = null; MovieFragment movieFragment; public MovieTask(MovieFragment fragment, LottieAnimationView lottieAnimationView) { this.movieFragment = fragment; this.lottieAnimationView = lottieAnimationView; } @Override protected DataMovie doInBackground(String... strings) { try{ movieList = new ArrayList<>(); request = new Request.Builder().url(strings[0]).build(); response = clientHttp.newCall(request).execute(); String json = response.body().string(); resultRequest = gson.fromJson(json, DataMovie.class); }catch (Exception e){ System.out.println("Error in processing request"); } movieList = (ArrayList<ResultMovie>) resultRequest.getResults(); return resultRequest; } @Override protected void onPreExecute() { super.onPreExecute(); lottieAnimationView.setVisibility(View.INVISIBLE); lottieAnimationView.playAnimation(); } @Override protected void onPostExecute(DataMovie dataMovie) { super.onPostExecute(dataMovie); ArrayList<ResultMovie> results = new ArrayList<>(); results = (ArrayList<ResultMovie>) dataMovie.getResults(); movieFragment.setAdapeter(results); lottieAnimationView.cancelAnimation(); lottieAnimationView.setVisibility(View.INVISIBLE); } }
C
UTF-8
4,915
2.515625
3
[]
no_license
#include "httpd.h" //void* accept_request(void *arg) //{ // int connfd = (int)arg; // pthread_detach(pthread_self()); // return accept_handler(connfd); //} int turn = 1; int send_data = 1; const char *log_path = "log/httpd.log"; int logfd = 0; int set_non_blocking(int fd) { int oldoption, newoption; oldoption = fcntl(fd, F_GETFL); newoption = oldoption | O_NONBLOCK; fcntl(fd, F_SETFL, newoption); return oldoption; } void addfd(int epollfd, int fd) { struct epoll_event event; event.data.fd = fd; event.events = EPOLLIN | EPOLLET; epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event); set_non_blocking(fd); } void delfd(int epollfd, int fd) { epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, NULL); } void worker_do(int listenfd, struct ConnPipe *conn_pipe, int index) { close(conn_pipe[index]._pipe[1]); //printf("%d\n", conn_pipe[index]._pipe[0]); int anoy_pipe = conn_pipe[index]._pipe[0]; int epollfd = epoll_create(256); struct epoll_event revent[ARRAYSIZE]; addfd(epollfd, anoy_pipe); //addfd(epollfd, listenfd); while(1) { int ret = epoll_wait(epollfd, revent, ARRAYSIZE, -1); if(ret < 0) { // continue ; } //printf("worker epill_wait over!!!\n"); for(int i = 0; i < ret; i++) { int sockfd = revent[i].data.fd; if(sockfd == anoy_pipe) { //printf("worker accpet!!!\n"); printlog("worker start to accept", FATAL); while(1) { char buf[128]; recv(sockfd, buf, sizeof(buf), 0); struct sockaddr_in clientAddr; socklen_t len = sizeof(clientAddr); int connfd = accept(listenfd, (struct sockaddr*)&clientAddr, &len); if(connfd < 0) { printlog("worker accept error", FATAL); break; } addfd(epollfd, connfd); dprintf(logfd, "come a newer : ip<%s> port<%d> sockfd<%d> date:%s", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port), connfd, get_cur_time()); } printlog("worker accept over", FATAL); } // else { //char *msg = "received\n"; //send(sockfd, msg, strlen(msg), 0); //printf("handler sockfd!!!\n"); accept_handler(sockfd); printlog("deal over", FATAL); delfd(epollfd, sockfd); close(sockfd); dprintf(logfd, "sockfd<%d> quit date:%s", sockfd, get_cur_time()); } } } } void master_do(int listenfd, struct ConnPipe *conn_pipe, int worker_nums) { int epollfd = epoll_create(256); struct epoll_event revent[ARRAYSIZE]; addfd(epollfd, listenfd); while(1) { int ret = epoll_wait(epollfd, revent, ARRAYSIZE, -1); if(ret < 0) { //printf("WARNING: epoll_wait\n"); continue ; } for(int i = 0 ; i < ret; i++) { int sockfd = revent[i].data.fd; if(sockfd == listenfd) { //printf("master listen!!!\n"); int tmp = turn; do { if(conn_pipe[turn]._pid != -1) break; turn++; if(turn >= worker_nums+1) { turn %= worker_nums; } }while(turn != tmp); if(conn_pipe[turn]._pid == -1) { dprintf(logfd, "no workers!\n"); continue; } send(conn_pipe[turn++]._pipe[1], (char*)&send_data, sizeof(send_data), 0); //printf("master send over!!!\n"); if(turn >= worker_nums+1) { turn %= worker_nums; } char bf[128]; sprintf(bf, "turn's value is %d", turn); printlog(bf, FATAL); } else { // } } } } int main(int argc, char *argv[]) { if(argc != 4) { dprintf(logfd, "usage: %s [local_ip] [local_port] [cpu_cores]\n", basename(argv[0])); return 1; } if(logfd == 0) { logfd = open(log_path, O_WRONLY | O_CREAT | O_TRUNC); } int listenfd = startup(argv[1], atoi(argv[2])); struct sockaddr_in clientaddr; socklen_t len; int worker_nums = atoi(argv[3]); if(worker_nums <= 0) { return 7; } struct ConnPipe *conn_pipe = (struct ConnPipe*)malloc(sizeof(struct ConnPipe)*(worker_nums+1)); for(int i = 1; i <= worker_nums; i++) { socketpair(AF_UNIX, SOCK_STREAM, 0, conn_pipe[i]._pipe); conn_pipe[i]._pid = -1; } for(int i = 1; i <= worker_nums; i++) { pid_t pid = fork(); if(pid < 0) { return 8; } else if(pid == 0) { worker_do(listenfd, conn_pipe, i); exit(0); } close(conn_pipe[i]._pipe[0]); conn_pipe[i]._pid = pid; } daemon(1, 0); master_do(listenfd, conn_pipe, worker_nums); free(conn_pipe); close(listenfd); close(logfd); return 0; //daemon(1, 0); //create daemon //int count = 0; //while(1) //{ // len = sizeof(clientaddr); // int connfd = accept(listenfd, (struct sockaddr*)&clientaddr, &len); // if(connfd < 0) // { // printlog("accept", FATAL); // continue; // } // pthread_t tid; // int ret = pthread_create(&tid, NULL, accept_request, (void*)connfd); // if(ret != 0) // { // printlog("pthread_create", WARNING); // char *buf = "server is too busy!"; // send(connfd, buf, strlen(buf), 0); // close(connfd); // printf("%d\n", count); // continue ; // } // count++; // //pthread_detach(tid); //} }
Java
UTF-8
705
3.625
4
[]
no_license
package advanced.lambdademo.anonymous; /* * If an anonymous class implements an interface which has only one abstract method then we can use lambda * Anonymous class can extend interface which has more than one abstract method. * Anonymous class can extend from normal class and an abstract class. */ public class Test { public static void main(String[] args) { Interface2 i2 = new Interface2(){ @Override public void m1() { // TODO Auto-generated method stub System.out.println("m1 --- interface"); } @Override public void m2() { // TODO Auto-generated method stub System.out.println("m2 --- interface"); } }; i2.m1(); i2.m2(); } }
JavaScript
UTF-8
1,454
2.6875
3
[]
no_license
(function () { "use strict"; angular.module('common') .service('UserService', UserService); UserService.$inject = ['$q']; function UserService($q) { var service = this; var cookie_name = "coursera-test5"; function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+JSON.stringify(value)+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return JSON.parse(c.substring(nameEQ.length,c.length)); } return null; } function deleteCookie(name){ document.cookie = name + '=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT;'; } service.saveUser = function (user) { var deferred = $q.defer(); createCookie(cookie_name, user,1); deferred.resolve(user); return deferred.promise; }; service.getUser = function (user) { var deferred = $q.defer(); var c = readCookie(cookie_name); deferred.resolve(c); return deferred.promise; }; service.reset = function () { var deferred = $q.defer(); deleteCookie(cookie_name); deferred.resolve("ok"); return deferred.promise; }; } })();
Python
UTF-8
1,301
2.765625
3
[]
no_license
import cv2 import numpy as np; # Read image im = cv2.imread("data/milestone.jpg", cv2.IMREAD_GRAYSCALE) # Set up the detector with default parameters. params = cv2.SimpleBlobDetector_Params() #increasing minThreshold gets rid of tiny blobs params.minThreshold = 150; params.maxThreshold = 175; #use blobColor = 255 to find light blobs and blobColor = 0 to find dark blobs params.filterByColor = True params.blobColor = 255 # Filter by Area params.filterByArea = True params.minArea = 1 params.maxArea = 100000 params.filterByCircularity = False; params.minDistBetweenBlobs = 1000 detector = cv2.SimpleBlobDetector(params) keypoints = detector.detect(im) pt1 = 0 pt2 = 0 size = 0 for kp in keypoints: size = int(kp.size) kp.size *= 2.2 pt1 = kp.pt scale = size pt1 = (int(pt1[0] - scale), int(pt1[1]) - scale) pt2 = (pt1[0] + 2*scale, pt1[1] + 2*scale) # Draw detected blobs as red circles. # cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the circle corresponds to the size of blob im_with_keypoints = cv2.drawKeypoints(im, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) cv2.rectangle(im, pt1, pt2, 0, thickness=2) cv2.imshow("rectangle", im) cv2.waitKey(0) # Show keypoints cv2.imshow("Keypoints", im_with_keypoints) cv2.waitKey(0)
Python
UTF-8
504
3.328125
3
[]
no_license
#Pandigital 생성 import itertools p=list() permutations=list(itertools.permutations(list(range(0,10)),10)) for t in permutations: s="".join(str(n) for n in t) p.append(s) sum_of_result = 0 rule = {1:2, 2:3, 3:5, 4:7, 5:11, 6:13, 7:17} for pandigital in p: isRight = True for k in rule.keys(): if not int(pandigital[k:k+3]) % rule[k] == 0: isRight = False break if isRight: sum_of_result += int(pandigital) print (sum_of_result)
Rust
UTF-8
1,308
2.625
3
[]
no_license
use std::{ env, path::{Path, PathBuf}, }; use actix_files::NamedFile; use actix_web::{guard, web, App, Error, HttpRequest, HttpResponse, HttpServer}; use actix_web_actors::ws; mod demo_ws; async fn handle_ws(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> { ws::start(demo_ws::WebSocketActor::default(), &req, stream) } async fn index(req: HttpRequest) -> Result<NamedFile, Error> { let mut path: PathBuf = req.match_info().query("filename").parse().unwrap(); if path == Path::new("") { path = path.join("index.html"); } let path = PathBuf::from("../../frontend").join(path); Ok(NamedFile::open(path)?) } #[actix_web::main] async fn main() -> std::io::Result<()> { let port = env::var("PORT") .map(|port| port.parse::<u32>().expect("Invalid PORT env variable")) .unwrap_or(3000); let addr = format!("127.0.0.1:{}", port); let server = HttpServer::new(|| { App::new() .route( "/", web::get() .guard(guard::Header("Upgrade", "websocket")) .to(handle_ws), ) .route("/{filename:.*}", web::get().to(index)) }) .bind(&addr)?; println!("Listening on {}", addr); server.run().await }
Python
UTF-8
6,372
2.875
3
[]
no_license
"""Google Earth Engine methods to extract data.""" import json from pathlib import Path from typing import List, Tuple import ee from tqdm import tqdm from time import sleep from src.radix_co2_reduction.earth_engine.datasets import ( CroplandCollection, Landsat7Collection, Landsat8Collection, Sentinel1Collection, Sentinel2Collection, ) from src.radix_co2_reduction.earth_engine.utils import create_polygon def sample_field( coordinate: Tuple[float, float], boundary: List[Tuple[float, float]], cache_path: Path, year: int, startdate_postfix: str = "-11-01", enddate_postfix: str = "-04-30", n_pixels: int = 100, overwrite: bool = False, ) -> None: """ Sample the field, as specified by its boundary polygon. :param coordinate: Field coordinate (lat,lng) :param boundary: Field's boundary polygon as a list of (lat,lng) coordinates :param cache_path: Directory of data cache :param startdate_postfix: Starting date postfix of the previous year (month and day) :param enddate_postfix: Ending date postfix of the previous year (month and day) :param year: The year of interest :param n_pixels: Number of pixels to sample per time-period (day) over the given field :param overwrite: Overwrite previously stored data """ # Write down in folder (cache) write_f = cache_path / f"{coordinate[0]}-{coordinate[1]}/samples" write_f.mkdir(parents=True, exist_ok=True) if not overwrite and (write_f / "sentinel2.json").is_file(): return # Create an Earth Engine polygon for the field-coordinates boundary = [(b, a) for a, b in boundary] # Input should be in (lng,lat) field_polygon = create_polygon([boundary]) # Load in all relevant datasets over the specified timeframe startdate = f"{year - 1}{startdate_postfix}" enddate = f"{year}{enddate_postfix}" # Landsat 7 data: https://developers.google.com/earth-engine/datasets/catalog/LANDSAT_LE07_C01_T1_SR landsat7 = Landsat7Collection() landsat7.load_collection( region=field_polygon, startdate=startdate, enddate=enddate, filter_clouds=True, filter_perc=0.75, ) # Landsat 8 data: https://developers.google.com/earth-engine/datasets/catalog/LANDSAT_LC08_C01_T1_SR landsat8 = Landsat8Collection() landsat8.load_collection( region=field_polygon, startdate=startdate, enddate=enddate, filter_clouds=True, filter_perc=0.75, ) # Sentinel-1 SAR GRD data: https://developers.google.com/earth-engine/datasets/catalog/COPERNICUS_S1_GRD sentinel1 = Sentinel1Collection() sentinel1.load_collection( region=field_polygon, startdate=startdate, enddate=enddate, ) # Sentinel-2 L2A data: https://developers.google.com/earth-engine/datasets/catalog/COPERNICUS_S2_SR sentinel2 = Sentinel2Collection() sentinel2.load_collection( region=field_polygon, startdate=startdate, enddate=enddate, filter_clouds=True, filter_perc=0.75, ) # Add Cropland data layer to all image collections and use it as a mask cropland = CroplandCollection() cropland.load_collection( region=field_polygon, startdate=f"{year}-01-01", enddate=f"{year}-12-31", ) cropland_im = cropland.collection.first().select("cropland") landsat7.mask_cropland(cropland_im=cropland_im, region=field_polygon) landsat8.mask_cropland(cropland_im=cropland_im, region=field_polygon) sentinel1.mask_cropland(cropland_im=cropland_im, region=field_polygon) sentinel2.mask_cropland(cropland_im=cropland_im, region=field_polygon) # Collect pixels to sample over pixels = ee.FeatureCollection.randomPoints( region=field_polygon, points=n_pixels, seed=42, maxError=50, ) # Sample the collections s_landsat7 = landsat7.sample(pixels=pixels) with open(write_f / "landsat7.json", "w") as f: json.dump(s_landsat7, f) s_landsat8 = landsat8.sample(pixels=pixels) with open(write_f / "landsat8.json", "w") as f: json.dump(s_landsat8, f) s_sentinel1 = sentinel1.sample(pixels=pixels) with open(write_f / "sentinel1.json", "w") as f: json.dump(s_sentinel1, f) s_sentinel2 = sentinel2.sample(pixels=pixels) with open(write_f / "sentinel2.json", "w") as f: json.dump(s_sentinel2, f) sleep(5) # Prevent getting blocked by GEE # TODO: Intermediate check, might be removed later on shapes = set() for coll in (s_landsat7, s_landsat8, s_sentinel1, s_sentinel2): for value in coll.values(): for v in value.values(): shapes.add(len(v)) shapes -= {1,} if len(shapes) > 1: raise Exception(f"Found shapes {shapes} for coordinate {coordinate}") print(f"Resulting shapes:", shapes) def sample_fields( coordinates: List[Tuple[float, float]], boundaries: List[List[Tuple[float, float]]], years: List[int], cache_path: Path, startdate_postfix: str = "-11-01", enddate_postfix: str = "-04-30", n_pixels: int = 100, overwrite: bool = False, ) -> None: """ Sample all the requested lists, as specified by their boundaries and year. :param coordinates: Field coordinates (lat,lng) used to link to correct cache-file :param boundaries: Field boundary polygons as a list of (lat,lng) coordinates :param years: List of years corresponding each field :param cache_path: Directory of data cache :param startdate_postfix: Starting date postfix of the previous year (month and day) :param enddate_postfix: Ending date postfix of the previous year (month and day) :param n_pixels: Number of pixels to sample per time-period (day) :param overwrite: Overwrite previously stored data """ for coor, year, boundary in tqdm( zip(coordinates, years, boundaries), total=len(coordinates), desc="Sampling fields...", ): sample_field( coordinate=coor, year=year, boundary=boundary, cache_path=cache_path, startdate_postfix=startdate_postfix, enddate_postfix=enddate_postfix, n_pixels=n_pixels, overwrite=overwrite, )
Markdown
UTF-8
676
2.96875
3
[ "MIT" ]
permissive
--- layout: about title: About permalink: /about/ --- I am a graduate student at Johns Hopkins. I am interested in the computational challenges associated with Bayesian statistics, which I focus on in this blog. While I enjoy working with many types of data, my passion is working with genomic, clinical, and healthcare data. Before Hopkins, I studied Mathematics at Virginia Tech. After undergrad, I worked as a data analyst at Deloitte in the federal consulting space. Following Deloitte, I took a position at Marriott in their digital analytics team. Here I worked on statistical models that included sort order algorithms and natural language processing of review data.
C
UTF-8
777
4.03125
4
[]
no_license
#include "lists.h" /** * delete_nodeint_at_index - Entry Point * * @head: a pointer to a pointer to the first node in the linked list * @index: the index at which a node is deleted * * Description: Deletes a node at an index in a linked list * * Return: 1, or -1 if it fails */ int delete_nodeint_at_index(listint_t **head, unsigned int index) { unsigned int count; listint_t *temp1, *temp2; if (head == NULL || *head == NULL) return (-1); if (index == 0) { if (*head != NULL) { temp1 = *head; *head = (*head)->next; free(temp1); return (1); } } else { temp1 = *head; for (count = 0; temp1 && (count < index - 1); count++) temp1 = temp1->next; if (temp1 != NULL) { temp2 = temp1; temp1 = temp1->next; temp2->next = temp1->next; free(temp1); } else return (-1); } return (1); }
Markdown
UTF-8
2,175
3.28125
3
[ "MIT" ]
permissive
--- title: Menu --- ## Demo ```jsx_demo {/* Lower left */} <div style={{position: 'relative'}}> <IconButton name="more_vert" id="demo-menu-lower-left" /> <Menu target="demo-menu-lower-left"> <MenuItem>Some Action</MenuItem> <MenuItem>Another Action</MenuItem> <MenuItem disabled>Disabled Action</MenuItem> <MenuItem>Yet Another Action</MenuItem> </Menu> </div> {/* Lower right */} <div style={{position: 'relative'}}> <IconButton name="more_vert" id="demo-menu-lower-right" /> <Menu target="demo-menu-lower-right" align="right"> <MenuItem>Some Action</MenuItem> <MenuItem>Another Action</MenuItem> <MenuItem disabled>Disabled Action</MenuItem> <MenuItem>Yet Another Action</MenuItem> </Menu> </div> ``` ```jsx_demo {/* Top left */} <div style={{position: 'relative'}}> <IconButton name="more_vert" id="demo-menu-top-left" /> <Menu target="demo-menu-top-left" valign="top"> <MenuItem>Some Action</MenuItem> <MenuItem>Another Action</MenuItem> <MenuItem disabled>Disabled Action</MenuItem> <MenuItem>Yet Another Action</MenuItem> </Menu> </div> {/* Top right */} <div style={{position: 'relative'}}> <IconButton name="more_vert" id="demo-menu-top-right" /> <Menu target="demo-menu-top-right" valign="top" align="right"> <MenuItem>Some Action</MenuItem> <MenuItem>Another Action</MenuItem> <MenuItem disabled>Disabled Action</MenuItem> <MenuItem>Yet Another Action</MenuItem> </Menu> </div> ``` ## Configuration | Element | Prop | Type | Effect | Remarks | |:----------|:-------------|:----------|:-------------|:-------------| | Menu | align | String (left, right) | Set the horizontal alignment | Optional, default "left" | | Menu | ripple | Boolean | Apply the ripple effect | Optional | | Menu | target | String | ID of the targeted element. A click on the targeted element will open the menu | Required | | Menu | valign | String (top, bottom) | Set the vertical alignment | Optional, default "bottom" |
JavaScript
UTF-8
3,121
3.109375
3
[]
no_license
//Creare un calendario del 2018, inserire poi le festività $(document).ready(function(){ var numeroMese = 1; function mese(numeroMese){ var scrittaMese = moment(numeroMese, "M").format("MMMM"); $("#month").text(scrittaMese); var giorniMese = moment("2018-" + numeroMese + "", "YYYY-MM").daysInMonth(); //Così ottengo il numero dei giorni di gennaio var dayBox = $("#template-calendar").html(); // Queste due righe servono a copiare il template dei box con dentro i giorni del mese var boxCompile = Handlebars.compile(dayBox); // var giornoSettimana = moment("2018-" + numeroMese + "-01", "YYYY-MM-DD").format("e"); var voidBox = { giorno : "", date : "", } var voidAppend = boxCompile(voidBox); for(var w = 0; w < giornoSettimana; w++){ $("#contenitor-box").append(voidAppend); } for(var y = 1; y <= giorniMese; y++){ var meseCorrente = moment("2018-" + numeroMese + "-" + y + "").format("YYYY-MM-DD"); // Così ottengo ogni signolo giorno del mese di gennaio con relatvi giorni console.log(meseCorrente); var ogettoGiorni = { // Oggetto che contiene le cose da inserire nei box del calendario giorno: y, date : meseCorrente, } var boxAppend= boxCompile(ogettoGiorni); $("#contenitor-box").append(boxAppend); // Così stampo il template con i giorni su html } $.ajax({ url: "https://flynn.boolean.careers/exercises/api/holidays", data: { year: 2018, month: numeroMese - 1 }, success: function(success){ var festività = success.response; // Così ottengo i giorni festivi di gennaio for(var a=0; a<festività.length; a++){ //Così ottengo la data singola della festività var giornoSelezionato = $(".box-day[data-date='"+ festività[a].date +"']"); /*$(".box-day").each(function(){ var box = $(this).attr("data-date"); console.log(box); if(box == festività[a].date){ //Se il data date è uguale alla festività, allora coloro il box di rosso $(this).addClass("red"); } })*/ giornoSelezionato.addClass("red"); } }, error: function(error){ console.log(error); } }) } mese(numeroMese); $("#next").click(function(){ if(numeroMese == 12){ numeroMese = 1; } else { numeroMese++; } $(".box-day").remove(); mese(numeroMese); }) $("#back").click(function(){ if(numeroMese == 1){ numeroMese = 12; } else{ numeroMese--; } $(".box-day").remove(); mese(numeroMese); }) })
Java
UTF-8
1,456
2.359375
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 uy.edu.cure.servidor.central.webapp.soap.server; import java.util.List; import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.WebParam; import uy.edu.cure.servidor.central.dto.Ciudad; import uy.edu.cure.servidor.central.lib.CiudadControllerImpl; /** * * @author SCN */ @WebService(endpointInterface = "uy.edu.cure.servidor.central.webapp.soap.server.CiudadWS") public class CiudadWSImpl implements CiudadWS { @Override public boolean crearCiudadWS(String nombreCiudad, String nombrePais) { CiudadControllerImpl ciudadcontroller = new CiudadControllerImpl(); boolean retorno; retorno = ciudadcontroller.crearCiudad(nombreCiudad, nombrePais); return retorno; } @Override public Ciudad obtenerCiudadWS(String nombre){ CiudadControllerImpl ciudadController = new CiudadControllerImpl(); return ciudadController.obtenerCiudad(nombre); } @Override public List<Ciudad> obtenerTodasCiudadesWS() { CiudadControllerImpl ciudadController = new CiudadControllerImpl(); List<Ciudad> CiudadesAux; CiudadesAux = ciudadController.obtenerTodosCiudades(); return CiudadesAux; } }
Markdown
UTF-8
6,912
3.203125
3
[]
no_license
# Charity data Analysis with Neural Network Neural networks are computing systems with interconnected nodes that work much like neurons in the human brain. Using algorithms, they can recognize hidden patterns and correlations in raw data, cluster and classify it, and – over time – continuously learn and improve. Deep learning is a deep neural network with many hidden layers and many nodes in every hidden layer. Deep learning develops deep learning algorithms that can be used to train complex data and predict the output. ![image](https://user-images.githubusercontent.com/85472349/139388057-e1fc5e2f-ae71-4306-949e-6a5fe2bf1315.png) ## Overview The purpose of this project is to use deep-learning neural networks with the TensorFlow platform in Python, to analyze, classify and optimize the success of charitable donations. We use the following methods for the analysis: * Deliverable 1: Preprocessing Data for a Neural Network Model * Deliverable 2: Compile, Train, and Evaluate the Model * Deliverable 3: Optimize the Model ## Resources • Data Source: [charity_data.csv] • Software: Python, Anaconda Navigator, Conda, Jupyter Notebook ## Analysis and Results We will use jupyter notebook with python packages for our Analysis. First we will import the dependencies, define the columns, Load the data. Then we will follow few steps to optimize our model. Below are the deliverable details: ### Deliverable 1: Preprocessing Data for a Neural Network Model With our knowledge of Pandas and the Scikit-Learn’s StandardScaler(), we’ll need to preprocess the dataset in order to compile, train, and evaluate the neural network model later in Deliverable. The following preprocessing steps have been performed: * The EIN and NAME columns have been dropped * Columns with more than 10 unique values have been grouped together * Categorical variables have been encoded using one-hot encoding ![image](https://user-images.githubusercontent.com/85472349/139452116-6ae8bc4d-0fd3-4df5-963b-f2a8ce795d12.png) * Preprocessed data is split into features and target arrays * Preprocessed data is split into training and testing datasets * Numerical values have been standardized using the StandardScaler() module ![image](https://user-images.githubusercontent.com/85472349/139452289-a5ee6112-c9a5-4aa6-8f9a-9f660e1f5500.png) ![image](https://user-images.githubusercontent.com/85472349/139452211-4d5ae8ef-5446-49f1-a727-798add67d7ec.png) ### Deliverable 2: Compile, Train, and Evaluate the Model With our knowledge of TensorFlow, we’ll design a neural network, or deep learning model, to create a binary classification model that can predict if an Alphabet Soup–funded organization will be successful based on the features in the dataset. We’ll need to think about how many inputs there are before determining the number of neurons and layers in our model. Once we’ve completed that step, we’ll compile, train, and evaluate your binary classification model to calculate the model’s loss and accuracy. The neural network model using Tensorflow Keras contains working code that performs the following steps: * The number of layers, the number of neurons per layer, and activation function are defined * An output layer with an activation function is created * There is an output for the structure of the model * There is an output of the model’s loss and accuracy * The model's weights are saved every 5 epochs ![image](https://user-images.githubusercontent.com/85472349/139454790-4261dbca-83c6-4e14-9f7f-01e52caf318b.png) **Neural network model using Tensorflow Keras** hidden_nodes_layer1 = 80 hidden_nodes_layer2 = 30 Activation function (First hidden layer) = relu Activation function (Second hidden layer) = relu Activation function (Output layer) = sigmoid epochs = 100 loss: 0.5355 - accuracy: 0.7411 **Evaluation of Model Test data** Loss: 0.5556238889694214, Accuracy: 0.7254810333251953 **With epoch reduction:** epochs = 30 loss: 0.5342 - accuracy: 0.7423 **Evaluation of Model Test data** Loss: 0.5556238889694214, Accuracy: 0.7254810333251953 **The results are saved to an HDF5 file** ![image](https://user-images.githubusercontent.com/85472349/139456052-a24db45a-500b-47bb-921d-d026b7fc3591.png) ### Deliverable 3: Optimize the Model With our knowledge of TensorFlow, optimize our model in order to achieve a target predictive accuracy higher than 75%. If we can't achieve an accuracy higher than 75%, we'll try different attempts. ### Adding more neurons to a hidden layer ![image](https://user-images.githubusercontent.com/85472349/139519987-99148902-779f-48c1-939c-439465e19783.png) ![image](https://user-images.githubusercontent.com/85472349/139520053-d3d367ed-75ee-4212-85d5-29e598cb9f33.png) ### Adding more hidden layers ![image](https://user-images.githubusercontent.com/85472349/139520069-71788570-9b1b-4511-9613-e00664de4a71.png) ![image](https://user-images.githubusercontent.com/85472349/139520075-0bfb35a9-8872-4c52-a8d9-8eb688fdd695.png) ### Using different activation functions (tanh) for the hidden layers ![image](https://user-images.githubusercontent.com/85472349/139520112-10abaa91-9f49-4355-b8a8-f50f5e6508b5.png) ![image](https://user-images.githubusercontent.com/85472349/139520119-4e5cbf0a-e4f1-4afb-9720-89adb9404dc6.png) ### Using different activation functions for both the hidden layers with increased epoch ![image](https://user-images.githubusercontent.com/85472349/139520164-69eac233-4af7-4a79-ac0c-992bb3c626ec.png) ![image](https://user-images.githubusercontent.com/85472349/139520181-42ae9ed8-5250-4430-a6ef-e480ecec8720.png) ### Adding the number of epochs to the training regimen ![image](https://user-images.githubusercontent.com/85472349/139520210-2f7effa5-83bc-4c9d-a5c8-76e5d8595890.png) ![image](https://user-images.githubusercontent.com/85472349/139520218-28799fcf-08e1-4f6e-acb1-492e82f7611a.png) ### Reducing the number of epochs to the training regimen ![image](https://user-images.githubusercontent.com/85472349/139520697-115d7508-45e5-481b-ba6c-6595b2360131.png) ### Export the module to HDF5 file ![image](https://user-images.githubusercontent.com/85472349/139520721-499cd715-b0b3-49a2-8e43-1ded5635bc46.png) ### Random Forest Classifier ![image](https://user-images.githubusercontent.com/85472349/139520761-8d6ca184-607c-4919-8411-719c2714a983.png) ## Summary The models accuracy ended up around 72% in all scenarios. From the original data set we dropped few irrelevant columns, combined the values and then we tried neural network on different scenarios. We also tried using Random Forest Classifier. Still we ended up with the same level of Accuracy. So, either we need to alter our dataset by removing few items or we need to have more data to get a expected result. Finally having the proper data is very important for any modelling.
Python
UTF-8
4,430
2.71875
3
[]
no_license
import time from concurrent.futures import ThreadPoolExecutor, as_completed from urllib.parse import urlparse, parse_qs import redis import config from .model import RedisModel from utils.exceptions import ResponseTimeOut class RedisConn(object): def __init__(self, **kwargs): conf = config.Config() self.redis_url = 'redis://:%s@%s:%s/0?client_name=python_dev' % \ (conf.REDIS_PASSWORD, conf.REDIS_HOST, conf.REDIS_PORT) self._conn = self.pool_from_url(**kwargs) def __del__(self): self._conn.close() def subscribe(self, key, timeout=5): """ 订阅方法 """ pub = self._conn.pubsub() pub.subscribe(key) # 同时订阅多个频道,要用psubscribe pub.listen() while True: msg = pub.parse_response(block=False, timeout=5) if msg is None: ResponseTimeOut elif msg[0] == 'message': return msg[2] def pool_from_url(self, **kwargs): url_options = dict() url = urlparse(self.redis_url) for name, value in iter(parse_qs(url.query).items()): url_options[name] = value[0] if 'db' not in url_options and url.path: try: url_options['db'] = int(url.path.replace('/', '')) except (AttributeError, ValueError): pass url_options['db'] = int(url_options.get('db', 0)) # 这里我设置为True, 源码默认为false url_options['decode_responses'] = True _url = url.scheme + '://' + url.netloc url_options.update(kwargs) return redis.StrictRedis.from_url(_url, **url_options) def __getattr__(self, command): def _(*args, **kwds): return getattr(self._conn, command)(*args, **kwds) return _ def __enter__(self): return self._conn def __exit__(self, exc_type, exc_value, traceback): if exc_type is None: self._conn.close() else: return True def get_all(self, keys, mini_count=0): """ 批量查询某个key下的所有数据 @param mini_count: 最少返回多少条 @param keys: 模糊查询的key @return: 匹配的结果数组 """ keys = self._conn.keys(keys) if len(keys) < mini_count: return [], [] return keys, self._conn.mget(keys) def del_all(self, keys): """ @param keys: 模糊查询的key @return: 删除的数据条数 """ self._conn.delete(*self._conn.keys(keys)) def hset(self, redis_model): """ @param redis_model: RedisModels 实例 @return: """ # 断言 assert isinstance(redis_model, RedisModel) for key, value in redis_model.obj.items(): self._conn.hset(redis_model.key, key, value) def hget(self, redis_model, attr=''): """ @param redis_model: RedisModels 实例 @param attr: 需要取出的属性值 @return: """ # 断言 assert isinstance(redis_model, RedisModel) if not attr: return self._conn.hgetall(redis_model.key) else: return self._conn.hget(redis_model.key, attr) def set_one(self, redis_model): assert isinstance(redis_model, RedisModel) key = redis_model.key payload = redis_model.json return self._conn.set(key, payload) def get_one(self, redis_model): assert isinstance(redis_model, RedisModel) key = redis_model.key data = self._conn.get(key) return redis_model.load(data) def left_push(self, redis_model): assert isinstance(redis_model, RedisModel) key = redis_model.key payload = redis_model.json return self._conn.lpush(key, payload) def example1(self): """ 短连接示例 """ with RedisConn(db=1) as r: r.set('user:zhangshan', " zhangshan's description") result = r.get('user:zhangshan') print(result) def example2(self): """ 长连接示例 """ r = RedisConn(db=1, client_name='client23414') r.set('user:zhangshan', " zhangshan's description") result = r.get('user:zhangshan') print(result) r.close()
Java
UTF-8
1,192
3.53125
4
[]
no_license
package org.effectivejava.reimplement.chapter06.item30; /** * Created by Administrator on 2016/6/12. */ public enum PayrollDay { MONDAY(PayType.WEEKDAY), TUESDAY(PayType.WEEKDAY), WEDNESDAY(PayType.WEEKDAY), SUNDAY(PayType.WEEKEND); PayrollDay( PayType payType ) { this.payType = payType; } private final PayType payType; public double pay( double hours, double payRate ) { return payType.pay( hours, payRate ); } private enum PayType { WEEKDAY{ @Override double overtimePay(double hours, double payRate) { return hours <= HOURS_PER_SHIFT ? 0 : ( hours - HOURS_PER_SHIFT ) * payRate; } }, WEEKEND{ @Override double overtimePay(double hours, double payRate) { return hours * payRate; } }; private static final int HOURS_PER_SHIFT = 8; abstract double overtimePay( double hours, double payRate ); double pay( double hours, double payRate ) { double basePay = hours * payRate; return basePay + overtimePay( hours, payRate ); } } }
C++
UTF-8
1,741
2.546875
3
[]
no_license
#include "departureinfo.h" #include <QStringRef> #include <QXmlStreamReader> #include <QXmlStreamAttribute> #include <QXmlStreamAttributes> DepartureInfo::DepartureInfo(QXmlStreamReader &xml) { Q_ASSERT(xml.isStartElement() && xml.name() == "Departure"); QXmlStreamAttributes attributes = xml.attributes(); QXmlStreamAttributes::const_iterator it = attributes.constBegin(); while (it != attributes.constEnd()) { QString value(it->value().toString()); if (it->name() == "name") { name = value; } else if (it->name() == "sname") { shortName = value; } else if (it->name() == "type") { type = stringToType(value); } else if (it->name() == "stopid") { stopId = value.toULongLong(); } else if (it->name() == "stop") { stop = value; } else if (it->name() == "time") { time = QTime::fromString(value, "hh':'mm"); } else if (it->name() == "date") { date = QDate::fromString(value, Qt::ISODate); } else if (it->name() == "direction") { direction = value; } else if (it->name() == "track") { track = value; } ++it; } } DepartureInfo::TransportType DepartureInfo::stringToType(const QString &type) { if (type == "VAS") { return VASTTAG; } else if (type == "LDT") { return LONG_DISTANCE_TRAIN; } else if (type == "REG") { return REGIONAL_TRAIN; } else if (type == "BUS") { return BUS; } else if (type == "BOAT") { return BOAT; } else if (type == "TRAM") { return TRAM; } else if (type == "TAXI") { return TAXI; } return UNKNOWN; }
Java
UTF-8
2,168
3.015625
3
[ "MIT" ]
permissive
package ooga.view.engine.utils; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; /** * This Class is responsible for splitting up sprite sheets into multiple images. * @author Kenneth * */ public class SpriteSheet { private String GLOBAL = "resources"; private String MAPTITLES_SAVE_PATH = "/view/textures/2d/cyberpunk/map/subtitles/"; private BufferedImage sheet; /** * This constructor receives the image that needs to be modified. * @param sheet */ public SpriteSheet(BufferedImage sheet){ this.sheet = sheet; } /** * This crops a sprite sheet to get the subimage within the picture. * @param x * @param y * @param width * @param height * @return */ public String crop(int x, int y, int width, int height, boolean isMap) { BufferedImage cropped = sheet.getSubimage(x*width, y*height, width, height); String imageName = String.format("%s_%s.png", String.valueOf(x),String.valueOf(y)); saveCroppedImage(imageName, cropped); return String.format("%s%s", MAPTITLES_SAVE_PATH, imageName); } public void saveCroppedImage(String filename, BufferedImage cropped){ try { File outputfile = new File(String.format("%s%s%s",GLOBAL, MAPTITLES_SAVE_PATH, filename)); ImageIO.write(cropped, "png", outputfile); } catch (IOException e) { System.err.println("Cannot save this cursed image"); } } public String crop(int x, int y, int width, int height, boolean isMap, String tag, String dir) { BufferedImage cropped = sheet.getSubimage(x*width, y*height, width, height); String imageName = String.format("%s_%s_%s.png", tag, String.valueOf(x), String.valueOf(y)); saveCroppedImage(imageName, dir, cropped); return String.format("%s%s", dir, imageName); } public void saveCroppedImage(String filename, String dir, BufferedImage cropped){ try { File outputfile = new File(String.format("%s%s/%s",GLOBAL, dir, filename)); ImageIO.write(cropped, "png", outputfile); } catch (IOException e) { System.err.println("Cannot save this cursed image"); } } }
Markdown
UTF-8
664
3.140625
3
[]
no_license
# Titanic Survival Probability ## Quick Summary In this project, we focus primarily on predicting the probability of survival of passengers who were onboard the Titanic. Here, explore a wide range of predictive models, namely simple decision trees, logistic regression, random forest regression, and gradient boosting techniques. Sensitivity analysis was also conducted to optimize certain parameters of the decision tree models. Another major aspect of the project is its focus on data manipulation techniques, ranging from data imputation to feature engineering. As described in the notebook, these have significant impact on the predictive accuracy of models.
Java
UTF-8
1,371
2.140625
2
[]
no_license
package db; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class mp extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // TODO Auto-generated method stub PrintWriter pw=res.getWriter(); res.setContentType("text/html"); try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","hr","hr"); int acc=Integer.parseInt(req.getParameter("acc")); if(validate.checkUser(acc)){ HttpSession session=req.getSession(); session.setAttribute("acn",acc); PreparedStatement ps=con.prepareStatement("select * from db where rno=?"); ps.setInt(1,acc); ps.execute(); ResultSet rs=ps.executeQuery(); rs.next(); session.setAttribute("name",rs.getString(2)); con.close(); res.sendRedirect("option.jsp"); }else { con.close(); pw.println("<h1>invalid account number<h1>"); } } catch (Exception e) { e.printStackTrace(); } } }
Java
UTF-8
1,252
3.90625
4
[]
no_license
package lcof_offer; /** * 剑指 Offer 10- II. 青蛙跳台阶问题 * 一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。 * * 答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。 * * 示例 1: * 输入:n = 2 * 输出:2 * * 示例 2: * 输入:n = 7 * 输出:21 * * 示例 3: * 输入:n = 0 * 输出:1 * * 提示: * 0 <= n <= 100 * 注意:本题与主站 70 题相同:https://leetcode-cn.com/problems/climbing-stairs/ * * 链接:https://leetcode-cn.com/problems/qing-wa-tiao-tai-jie-wen-ti-lcof */ public class offer10_numWays { /** * 执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户 * 内存消耗:35.3 MB, 在所有 Java 提交中击败了35.93%的用户 */ public int numWays(int n) { if(n==0 || n==1) return 1; if(n==2) return 2; int sum = 0; int pre=0,pre2=1; int i = 0; while(i<n){ sum = (pre + pre2)% 1000000007; i++; pre = pre2; pre2 = sum; } if(sum == 1000000008) return 1; return sum; } }
C++
UTF-8
364
2.765625
3
[]
no_license
#include "Directeur.h" Directeur::Directeur() : nbPersonnes(0) { } Directeur::Directeur(const unsigned nbPersonnes, const char* service): nbPersonnes(nbPersonnes), service(service) { } void Directeur::Afficher(std::ostream& stream) { Salarie::Afficher(stream); stream << "Service : " << service << "\n" << "Nombre de personnes : " << nbPersonnes << "\n"; }
Java
WINDOWS-1250
15,177
2.6875
3
[]
no_license
package old; import java.util.Random; import javax.microedition.lcdui.Canvas; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Graphics; /** Klasa AlonePlayer - wykonuje algorytm w trybie "sam ze sob" * @author Bolesaw Denk * @version 0.77 */ public class AlonePlayer { Object semafor; public Tausend mid; int karta1=0 , karta2=0; int MELD_1=0, MELD_2=0, nMeldunek; public int zaczynajacy; int nA = 11; int n10 = 10; int nK = 4; int nD = 3; int nJ = 2; int n9 = 0; int punktacja[] = {0, 0, 0}; int MELD[] = {0, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280, 290, 300}; int ATUT[] = {100, 80, 60, 40}; //wartosc atutu na pozycji odpow. nazwom kart z NAZWY[] int testA2T[] = {0, 0, 0, 0}; //porownywanie z tablica ATUT, czy jest atut String NAZWY[] = {"S","K","T","P"}; // skrocone nazwy kart boolean BOMBA = false; boolean PODBICIE = false; boolean atut1 = false, atut2 = false; /** Tablica kart pierwszego gracza */ public Karciochy[] gracz1 = new Karciochy[10]; /** Tablica kart drugiego gracza */ public Karciochy[] gracz2 = new Karciochy[10]; Karciochy[] musik1 = new Karciochy[2]; Karciochy[] musik2 = new Karciochy[2]; Karciochy[] sort = new Karciochy[10]; Random random = new Random(); /** Metoda generujca liczb losow z podanego przedziau liczbowego * @param min dolny przedzia liczbowy * @param max gwny przedzia liczbowy */ /** @return zwraca wygenerowan liczb w postaci cakowitej */ private int getRand(int min, int max) { int r = Math.abs(random.nextInt()); return (r % ((max - min + 1))) + min; } /** Metoda obsugujca rozdanie kart do poszczeglnych graczy */ public void rozdanie() { String karty[] = {"Sn9", "Kn9", "Tn9", "Pn9", "SnJ", "KnJ", "TnJ", "PnJ", "SnD", "KnD", "TnD", "PnD", "SnK", "KnK", "TnK", "PnK", "Sn10", "Kn10", "Tn10", "Pn10", "SnA", "KnA", "TnA", "PnA"}; int punkty[] = {n9, n9, n9, n9, nJ, nJ, nJ, nJ, nD, nD, nD, nD, nK, nK, nK, nK, n10, n10, n10, n10, nA ,nA ,nA ,nA}; //T_Img img = new T_Img(); for(int i=0; i<10; i++) /* rozdanie do graczy */ { int rand = getRand(0,23); while(karty[rand] == "nic") { //jeli wylosowany indeks trafi na "nic" to bierz kolejny if(rand==23) rand=0; else rand++; } gracz1[i] = new Karciochy(karty[rand],punkty[rand],0,Img.obrazkiKart[rand]); karty[rand] = "nic"; //a tutaj zamiast znullowa to jest wpisyane "nic" rand = getRand(0,23); while(karty[rand] == "nic") { if(rand==23) rand=0; else rand++; } gracz2[i] = new Karciochy(karty[rand],punkty[rand],0,Img.obrazkiKart[rand]); karty[rand] = "nic"; sort[i] = new Karciochy("nic",0, null); } for(int i=0; i<2; i++) /* rodanie musikow */ { int rand = getRand(0,23); while(karty[rand] == "nic") { if(rand==23) rand=0; else rand++; } musik1[i] = new Karciochy(karty[rand],punkty[rand],0,Img.obrazkiKart[rand]); karty[rand] = "nic"; rand = getRand(0,23); while(karty[rand] == "nic") { if(rand==23) rand=0; else rand++; } musik2[i] = new Karciochy(karty[rand],punkty[rand],0,Img.obrazkiKart[rand]); karty[rand] = "nic"; } } /** Metoda sortujca karty w talii zadanego gracza, by byy poukadane wg kolor i wag punktowych * @param tmp obiekt klasy Karciochy * @param num numer gracza */ public void sortowanie(Karciochy[] tmp, int num) { int next=0, prev=0; char a='1', b='2'; Karciochy tmpBS; for(int i=0; i<10; i++) { sort[i] = new Karciochy("0",0,null); } for(int i=0; i<4; i++)/** sortowanie po kolorach */ { for(int j=0; j<10; j++) { String abc = tmp[j].getKolor(); if(abc.startsWith(NAZWY[i])) { for(int l=0; l<10; l++) { if(sort[l].getKolor()!="0") continue; else if(sort[l].getKolor()=="0") { sort[l].setKart(tmp[j]); break; } } } } } for (int j=0; j<10; j++) /**sortowanie bbelkowe */ { for (int l=0; l<9; l++) { prev = sort[l].getPt(); next = sort[l+1].getPt(); a = sort[l].getKolor(0); b = sort[l+1].getKolor(0); if(prev<next && a==b) { tmpBS = new Karciochy(sort[l].getKolor(), sort[l].getPt(), sort[l].getObrazek()); sort[l] = sort[l+1]; sort[l+1] = new Karciochy(tmpBS.getKolor(), tmpBS.getPt(), tmpBS.getObrazek()); } } //atut_test[i] = new Karciochy(NAZWY[i],ATUT[i]); } przepisanie(sort, num); } /** Metoda przepisujca posortowan tablice z kartami do tablicy danego gracza okreslonego parametrem num * @param ka obiekt klasy Karciochy * @param num numer gracza */ /** Metoda przepisujca posortowane karty do tali odpowiedniego gracza*/ public void przepisanie(Karciochy[] ka, int num) { if(num == 1) { for(int i=0; i<10; i++) { gracz1[i] = sort[i]; if(gracz1[i].getKolor()=="Sn9") zaczynajacy = 1; } } if(num == 2) { for(int i=0; i<10; i++) { gracz2[i] = sort[i]; if(gracz2[i].getKolor()=="Sn9") zaczynajacy = 2; } } } /** Metoda sprawdzajca ilo atutw dla danego gracza - przydatna przy meldunkach * @param num numer gracza*/ public void sprawdzenieA22(int num) { System.out.print("\n"); if(num == 1) { for(int i=0; i<4; i++) { testA2T[i] = 0; for(int j=0; j<10; j++) //szukamy pary K&D do atutu G1 { String abc = gracz1[j].getKolor(); if(abc.startsWith(NAZWY[i]) && (abc.endsWith("K") || abc.endsWith("D"))) { testA2T[i] += ATUT[i]; gracz1[j].setMeld(ATUT[i]); } } testA2T[i] /= 2; if(testA2T[i]==ATUT[i]) //sumujemy atuty G1 do meldunku { System.out.println("Atut G1 za: " + ATUT[i] + " "); MELD_1 += ATUT[i]; //A2TY[i] = 1; //ile_atu1 += 1; //pozycja atutu z tablicy ATUT przep. jest w kolejnosci do pozA22 //if(pozA22[i]==0) pozA22[i] = i; } } } else if(num == 2) { for(int i=0; i<4; i++) { testA2T[i] = 0; for(int j=0; j<10; j++) //szukamy pary K&D do atutu G2 { String abc = gracz2[j].getKolor(); if(abc.startsWith(NAZWY[i]) && (abc.endsWith("K") || abc.endsWith("D"))) { testA2T[i] += ATUT[i]; gracz2[j].setMeld(ATUT[i]); } } testA2T[i] /= 2; if(testA2T[i]==ATUT[i]) //sumujemy atuty G2 do meldunku { System.out.println("Atut G2 za: " + ATUT[i] + " "); MELD_2 += ATUT[i]; /*A2TY[i] = 2; ile_atu2 += 1; for(int j=0; j<4; j++) { if(pozA22[j]==0) pozA22[j] = i; }*/ } } } } public int pobierzWartosc(int num) {//pobiera zalicytowana wartosc od gracza o numerze 'num' if(mid.planszaG2.przedLicytacja == true || mid.planszaG1.przedLicytacja == true) { if(num==1) return mid.planszaG1.nMeldunek; else if(num==2) return mid.planszaG2.nMeldunek; } return 0; } /** Metoda sztucznie wystawijca pierwszego gracza * stworzona na potrzeby obecnej konstrukcji projektu */ public void eliminacje() { if(zaczynajacy==0) zaczynajacy = getRand(1,2); //maly random z zakresu(1,2) sprawdzenieA22(1); sprawdzenieA22(2); } /** Metoda obsugujca licytacj */ public void licytacja() { MELD_1 = 0; MELD_2 = 0; System.out.print("zaczyna gracz: " + zaczynajacy); boolean juzBylo = false; if(zaczynajacy==1) // LICYTUJEMY <---------- { MELD_1 = 100; mid.planszaG2.przedLicytacja = true; mid.switchPlayerDisp(); System.out.println("\nGracz 1 melduje: 100 \nG2 przebijesz?"); MELD_2 = pobierzWartosc(2); if(MELD_2>MELD_1) { while(PODBICIE==false) { mid.planszaG1.przedLicytacja = true; mid.switchPlayerDisp(); System.out.println("\nGracz 2 melduje: " + MELD_2 + "\nG1 przebijesz?"); MELD_1 = pobierzWartosc(1); if(MELD_1==0) break; //inaczej POBICIE=true no ;p mid.planszaG2.przedLicytacja = true; mid.switchPlayerDisp(); System.out.println("\nGracz 1 melduje: " + MELD_1 + "\nG2 przebijesz?"); MELD_2 = pobierzWartosc(2); if(MELD_2==0) break; } } if(MELD_2==0) { zaczynajacy = 1; juzBylo = true; System.out.println("\nGracz 1 zaczyna meldunkiem: " + MELD_1); } else if(MELD_1==0) { zaczynajacy = 2; juzBylo = true; System.out.println("\nGracz 2 zaczyna meldunkiem: " + MELD_2); } } else if(zaczynajacy == 2 && juzBylo==false) { MELD_2 = 100; mid.planszaG1.przedLicytacja = true; mid.switchPlayerDisp(); System.out.println("\nGracz 2 melduje: 100 \nG1 przebijesz? "); MELD_1 = pobierzWartosc(1); if(MELD_1>MELD_2) { while(PODBICIE==false) { mid.planszaG2.przedLicytacja = true; mid.switchPlayerDisp(); System.out.println("\nGracz 1 melduje: " + MELD_1 + "\nG2 przebijesz?"); MELD_2 = pobierzWartosc(2); if(MELD_2==0) break; //inaczej POBICIE=true no ;p mid.planszaG1.przedLicytacja = true; mid.switchPlayerDisp(); System.out.println("\nGracz 2 melduje: " + MELD_2 + "\nG1 przebijesz?"); MELD_1 = pobierzWartosc(1); if(MELD_1==0) break; } } if(MELD_2==0) { zaczynajacy = 1; System.out.println("\nGracz 1 zaczyna meldunkiem: " + MELD_1); } else if(MELD_1==0) { zaczynajacy = 2; System.out.println("\nGracz 2 zaczyna meldunkiem: " + MELD_2); } } } /** Metoda obsugujca gwn czec gry */ public void Gra(int zacz) { int iloscKart = 10; int next=zacz; while(punktacja[1]<=1000 || punktacja[2]<=1000) //glowna petla tysiaca { System.out.print("\n------------------GRA----------------------"); boolean koniecTali = false; int punkty1=0, punkty2=0; while(koniecTali==false) //petla rozdania { char kolor1, kolor2; char nic = '0'; boolean niMa = false; if(next==1) { System.out.print("\nG1 wybierz karte: "); int k1 = GfxGame.selectedItem; kolor1 = gracz1[k1].getKolor(0); karta1 = gracz1[k1].getPt(); /*while(kolor1==nic) { System.out.print("\n" + kolor1 + karta1+ " ju bya wybierz inna: "); k1 = pobierz.GetInt(); kolor1 = gracz1[k1].getKolor(0); karta1 = gracz1[k1].getPt(); }*/ gracz1[k1] = new Karciochy("0",0,null); System.out.print("karta GRACZA 1: " + kolor1 + karta1); niMa=true; for(int i=0; i<10; i++) //sprawdzamy czy G2 ma karte z koloru { kolor2 = gracz2[i].getKolor(0); if(kolor1==kolor2) { niMa=false; break; } if(i==9 && niMa==false && kolor1!=kolor2) niMa=true; else niMa=false; } System.out.print("\nG2 wybierz karte: "); int k2 = pobierz.GetInt(); kolor2 = gracz2[k2].getKolor(0); if(niMa==false || kolor2==nic) { while(kolor1!=kolor2 || kolor2==nic) { if(kolor1!=kolor2) System.out.print("--Wybierz karte z KOLORU " + kolor1 + ": "); else if(kolor2==nic)System.out.print("--TA ju bya wybierz inn karte: "); k2 = pobierz.GetInt(); kolor2 = gracz2[k2].getKolor(0); } } karta2 = gracz2[k2].getPt(); gracz2[k2] = new Karciochy("0",0,null); System.out.print("karta GRACZA 2: " + kolor2 + karta2 +"\n"); if(karta1>karta2 || niMa==true) { punkty1 += (karta1+karta2); next=1; System.out.print("g1 zdoby: " + (karta1+karta2) + " ("+ punkty1+")\n"); } else if(karta2>karta1 && niMa==false) { punkty2 += (karta1+karta2); next=2; System.out.print("g2 zdoby: " + (karta1+karta2) + " ("+ punkty2+")\n"); } iloscKart -= 1; } else if(next==2) { System.out.print("\nG2 wybierz karte: "); int k2 = pobierz.GetInt(); kolor2 = gracz2[k2].getKolor(0); karta2 = gracz2[k2].getPt(); while(kolor2==nic) { System.out.println("TA ju bya wybierz inna: "); k2 = pobierz.GetInt(); kolor2 = gracz2[k2].getKolor(0); karta2 = gracz2[k2].getPt(); } gracz2[k2] = new Karciochy("0",0,null); System.out.print("karta GRACZA 2: " + kolor2 + karta2); niMa=true; for(int i=0; i<10; i++) //sprawdzamy czy G2 ma karte z koloru { kolor1 = gracz1[i].getKolor(0); if(kolor1==kolor2) { niMa=false; break; } if(i==9 && niMa==false && kolor1!=kolor2) niMa=true; else niMa=false; } System.out.print("\nG1 wybierz karte: "); int k1 = pobierz.GetInt(); kolor1 = gracz1[k1].getKolor(0); if(niMa==false || kolor1==nic) { while(kolor1!=kolor2 || kolor1==nic) { if(kolor1!=kolor2) System.out.print("--Wybierz karte z KOLORU " + kolor2 + ": "); else if(kolor1==nic)System.out.print("--TA ju bya wybierz inn karte: "); k1 = pobierz.GetInt(); kolor1 = gracz1[k1].getKolor(0); } } karta1 = gracz1[k1].getPt(); gracz1[k1] = new Karciochy("0",0,null); System.out.print("karta GRACZA 1: " + kolor1 + karta1 +"\n"); if(karta2>karta1 || niMa==true) { punkty2 += (karta1+karta2); next=2; System.out.print("g2 zdoby: " + (karta1+karta2) + " ("+ punkty2+")\n"); } else if(karta1>karta2 && niMa==false) { punkty1 += (karta1+karta2); next=1; System.out.print("g1 zdoby: " + (karta1+karta2) + " ("+ punkty2+")\n"); } iloscKart -= 1; } /*if(zacz==1 && iloscKart==0) { if(punkty1>=MELD_1) punktacja[1] += punkty1; else if(punkty1<MELD_1) punktacja[1] -= MELD_1; } else if(zacz==2 && iloscKart==0) { if(punkty2>=MELD_2) punktacja[2] += punkty2; else if(punkty2<MELD_2) punktacja[2] -= MELD_2; }*/ if(iloscKart==0) { koniecTali = true; iloscKart = 10; } } if(zacz==1) { if(punkty1>=MELD_1) punktacja[1] += punkty1; else if(punkty1<MELD_1) punktacja[1] -= MELD_1; } else if(zacz==2) { if(punkty2>=MELD_2) punktacja[2] += punkty2; else if(punkty2<MELD_2) punktacja[2] -= MELD_2; } System.out.print("\n------G1: " + punktacja[1] + " G2: " + punktacja[2] + "--------\n"); System.out.print("\n"); s1(); } if(punktacja[1]>=1000) { System.out.print("Wygra Gracz 1"); } else if(punktacja[2]>=1000) { System.out.print("Wygra Gracz 2"); } } /*public static void main(String[] args) { new AlonePlayer(); }*/ /** Konstruktor domylny * @param mid pobiera referencje do midletu */ public AlonePlayer(Tausend mid) { super(); this.mid = mid; zaczynajacy = 0; } }
Python
UTF-8
110
3.4375
3
[]
no_license
num=[1,2,3,4,5] sum=0; for val in range(len(num)): print( "NUM =" , val ); sum=sum + val; print(sum)
Java
UTF-8
3,301
3.03125
3
[ "MIT" ]
permissive
package org.jabref.logic.util; import java.util.Scanner; import java.util.regex.Pattern; /** * Provides simple checks to ensure the correct version for JabRef is available. Currently, we need to make sure that we * have Java 1.8 but not Java 9. The functions here are not intended for direct use. Instead, they are called inside * {@link BuildInfo}, which has the required java version string (e.g. 1.8.0_144) available through the build system. * The version check should always happen through the <code>Globals#BUILD_INFO</code> instance which is available at a * very early stage in the JabRef startup. */ public class JavaVersion { // See http://openjdk.java.net/jeps/223 private static final Pattern DELIMITER = Pattern.compile("[._\\-+]"); private final String JAVA_VERSION; public JavaVersion() { // Be adventurous and assume that we can always access this property! JAVA_VERSION = System.getProperty("java.version"); } public JavaVersion(final String version) { JAVA_VERSION = version; } /** * Tries to determine if we are running on Java 9. This test should return false, when we cannot extract the correct * Java version. Note that Java 9 has a different version scheme like "9-internal". * * @return true if Java 9 is used */ public boolean isJava9() { if (JAVA_VERSION != null) { // Since isAtLeast is very optimistic, we first need to check if we have a "number" in the version string // at all. Otherwise we would get false-positives. final Scanner scanner = new Scanner(JAVA_VERSION); scanner.useDelimiter(DELIMITER); if (scanner.hasNextInt()) { return isAtLeast("1.9"); } } return false; } /** * A very optimistic test for ensuring we at least have a minimal required Java version. It will not fail when we * cannot determine the result. In essence, this method splits a version string using {@link * JavaVersion#DELIMITER} and compares two version number by number. * * @param version Should be in the form X.X.X_XXX where X are integers. * @return true if the numbers in version available for comparison are all greater-equals the currently running Java * version. */ public boolean isAtLeast(final String version) { if (JAVA_VERSION == null || version == null) { return true; } final Scanner scannerRunningVersion = new Scanner(JAVA_VERSION); final Scanner scannerRequiredVersion = new Scanner(version); scannerRunningVersion.useDelimiter(DELIMITER); scannerRequiredVersion.useDelimiter(DELIMITER); while (scannerRunningVersion.hasNextInt() && scannerRequiredVersion.hasNextInt()) { final int running = scannerRunningVersion.nextInt(); final int required = scannerRequiredVersion.nextInt(); if (running == required) { continue; } return running >= required; } return true; } public String getJavaVersion() { return JAVA_VERSION; } public String getJavaInstallationDirectory() { return System.getProperty("java.home"); } }
TypeScript
UTF-8
2,786
2.640625
3
[]
no_license
/* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS205: Consider reworking code to avoid use of IIFEs * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import assert from "assert"; import friendsStore from "../src/friends-store"; const manyFriend = (prefix: string, n: number) => (() => { const result: string[] = []; while (n-- > 0) { result.push(`${prefix}${n}`); } return result; })(); describe("friends", function() { let friendsClient: any = null; before(function() { const fakeUsermetaClient = { type: 'fakeUsermetaClient', meta: {}, isValid(key) { return true; }, get(username, key, cb) { return cb(null, this.meta[`${username}:${key}`]); }, set(username, key, value, cb, maxLength) { this.meta[`${username}:${key}`] = value; this.meta[`${username}:${key}:maxLength`] = maxLength; return cb(null); }, getBulk(username, keys, cb) { return cb(null, null); //TODO }, getBulkForUser(params, keys, cb) { return cb(null, null); //TODO }, }; friendsClient = friendsStore.createClient({ usermetaClient: fakeUsermetaClient, maxFriends: 100 }); }); it("Sets friends", done => friendsClient.set("jeko", manyFriend("a", 50), function(err) { assert.ok(!err); return done(); })); it("Gets friends", done => friendsClient.get("jeko", function(err, friends) { assert.ok(!err); assert.equal(50, friends.length, "has 50 friends"); assert.equal("a49", friends[0]); assert.equal("a0", friends[49]); return done(); })); it("Add friends to the list", done => friendsClient.add("jeko", manyFriend("b", 30), function(err) { assert.ok(!err); return friendsClient.get("jeko", function(err, friends) { assert.ok(!err); assert.equal(80, friends.length); return done(); }); })); it("Doesn't add duplicates", done => friendsClient.add("jeko", manyFriend("a", 70), function(err) { assert.ok(!err); return friendsClient.get("jeko", function(err, friends) { assert.ok(!err); assert.equal(100, friends.length); return done(); }); })); it("Doesn't add more that maxFriends", done => friendsClient.add("jeko", manyFriend("c", 100), function(err) { assert.ok(!err); return friendsClient.get("jeko", function(err, friends) { assert.ok(!err); assert.equal(100, friends.length); return done(); }); })); return it("Returns empty if no friends", done => friendsClient.get("none", function(err, value) { assert.ok(!err); assert.equal(0, value.length); return done(); })); }); // vim: ts=2:sw=2:et:
C#
UTF-8
3,506
2.71875
3
[ "Apache-2.0" ]
permissive
/* This class has been written by * Corinna John (Hannover, Germany) * cj@binary-universe.net * * You may do with this code whatever you like, * except selling it or claiming any rights/ownership. * * Please send me a little feedback about what you're * using this code for and what changes you'd like to * see in later versions. (And please excuse my bad english.) * * WARNING: This is experimental code. * Please do not expect "Release Quality". * */ #region Using directives using System; using System.Drawing; using System.Threading; using System.Windows.Forms; #endregion namespace CameraLib.AVI { public class AviPlayer { private VideoStream videoStream; private PictureBox picDisplay; private Control ctlFrameIndexFeedback; private int millisecondsPerFrame; private bool isRunning; private int currentFrameIndex; private Bitmap currentBitmap; private delegate void SimpleDelegate(); public event EventHandler Stopped; /// <summary>Returns the current playback status</summary> public bool IsRunning { get { return isRunning; } } /// <summary>Create a new AVI Player</summary> /// <param name="videoStream">Video stream to play</param> /// <param name="picDisplay">PictureBox to display the video</param> /// <param name="ctlFrameIndexFeedback">Optional Label to show the current frame index</param> public AviPlayer(VideoStream videoStream, PictureBox picDisplay, Control ctlFrameIndexFeedback) { this.videoStream = videoStream; this.picDisplay = picDisplay; this.ctlFrameIndexFeedback = ctlFrameIndexFeedback; this.isRunning = false; } /// <summary>Start the video playback</summary> public void Start() { isRunning = true; millisecondsPerFrame = (int)(1000 / videoStream.FrameRate); Thread thread = new Thread(new ThreadStart(Run)); thread.Start(); } /// <summary>Extract and display the frames</summary> private void Run() { videoStream.GetFrameOpen(); for (currentFrameIndex = 0; (currentFrameIndex < videoStream.CountFrames) && isRunning; currentFrameIndex++) { //show frame currentBitmap = videoStream.GetBitmap(currentFrameIndex); picDisplay.Invoke(new SimpleDelegate(SetDisplayPicture)); picDisplay.Invoke(new SimpleDelegate(picDisplay.Refresh)); //show position if (ctlFrameIndexFeedback != null) { ctlFrameIndexFeedback.Invoke(new SimpleDelegate(SetLabelText)); } //wait for the next frame Thread.Sleep(millisecondsPerFrame); } videoStream.GetFrameClose(); isRunning = false; if (Stopped != null) { Stopped(this, EventArgs.Empty); } } /// <summary>Change the visible frame</summary> private void SetDisplayPicture() { picDisplay.Image = currentBitmap; } /// <summary>Change the frame index feedback</summary> private void SetLabelText() { ctlFrameIndexFeedback.Text = currentFrameIndex.ToString(); } /// <summary>Stop the video playback</summary> public void Stop() { isRunning = false; } } }
Ruby
UTF-8
6,095
2.875
3
[ "MIT" ]
permissive
require 'selkie/fourth/attacker' module Selkie module Monster include Selkie::Attacker attr_accessor :level, :role, :threat def self.included(base) base.extend ClassMethods end def initialize self.class.maker.generate(self) end def abilities @abilities ||= {} end def hp if @threat == :minion 1 else multiplier = 8 if @threat != :solo multiplier = 10 if @role == :brute multiplier = 6 if @role == :lurker || @role == :artillery end base = multiplier * (1 + @level) + abilities[:constitution] if @threat == :solo base * 4 elsif @threat == :elite base * 2 else base end end end def ac case @role when :brute, :artillery 12 + @level when :soldier 16 + @level else 14 + @level end end def fortitude defense(:strength, :constitution) end def reflex defense(:dexterity, :intelligence) end def will defense(:wisdom, :charisma) end def defense(*abs) 12 + @level + (abs.map { |a| abilities[a] }.max - (13 + @level / 2)) / 2 end module ClassMethods def level(l, maker=nil) make_monster(maker) do |m| m.level = l m.threat ||= :standard end end #threat setters def elite(maker = nil) make_monster(maker) { |m| m.set_threat!(:elite) } end def solo(maker = nil) make_monster(maker) { |m| m.set_threat!(:solo) } end def standard(maker = nil) make_monster(maker) { |m| m.set_threat!(:standard) } end def minion(maker = nil) make_monster(maker) { |m| m.set_threat!(:minion) } end #role setters def brute(maker = nil) make_monster(maker) { |m| m.set_role!(:brute) } end def skirmisher(maker = nil) make_monster(maker) { |m| m.set_role!(:skirmisher) } end def soldier(maker = nil) make_monster(maker) { |m| m.set_role!(:soldier) } end def lurker(maker = nil) make_monster(maker) { |m| m.set_role!(:lurker) } end def controller(maker = nil) make_monster(maker) { |m| m.set_role!(:controller) } end def artillery(maker = nil) make_monster(maker) { |m| m.set_role!(:artillery) } end #ability support def primary_ability(ability) modify_monster { |m| m.primary_ability = ability } end def randomize_abilities modify_monster { |m| m.random_ability_modifiers = true } end def pump(attribute, times=nil) times = 1.times if not times times.each do modify_monster { |m| m.ability_mods[attribute] = (m.ability_mods[attribute] or 0) +1 } end end def dump(attribute, times=nil) times = 1.times if not times times.each do modify_monster { |m| m.ability_mods[attribute] = (m.ability_mods[attribute] or 0) -1 } end end #maker support def maker @maker end private def make_monster(maker) if not maker if @maker raise "Cannot define baseline monster statistics" else @maker = MonsterMaker.new end maker = @maker end yield maker @maker end def modify_monster raise "Cannot modify monster without a baseline." if not @maker yield @maker end end class MonsterMaker attr_accessor :level, :role, :threat attr_accessor :primary_ability attr_accessor :random_ability_modifiers def ability_mods @ability_mods ||= {} end def generate(monster) if not (@level and @threat and (@role or @threat == :minion)) raise "Cannot instantiate monsters without a level, role, and threat." end monster.level = @level monster.role = @role monster.threat = @threat generate_abilities monster end def generate_abilities(monster) abilities = [:strength, :dexterity, :constitution, :intelligence, :wisdom, :charisma] primary_index = abilities.index(@primary_ability) spread = [0, 0, 0, 0, 0] if @random_ability_modifiers spread = [[2, 0, 0, 0, -2], [1, 0, 0, 0, -1], [1, 1, 0, 0, -2], [2, 0, 0, -1, -1], [1, 1, 1, -1, -2], [4, 0, 0, -2, -2], [1, 1, 0, -1, -1], [2, 1, 0, -1, -2], [3, 2, 0, -2, -3], [2, 2, 0, -2, -2], [3, 2, 0, -2, -3], [4, 3, 0, -3, -4], [4, 2, 2, -3, -5], [3, 3, -3, -2, -1], [4, 3, 3, -5, -5], [4, 4, 3, -6, -5], [5, 4, -4, -3, -2], [5, 5, -2, -3, -5], [6, 4, -2, -4, -4], [6, 5, -3, -4, -4]].shuffle()[0].shuffle() end spread = spread.insert(primary_index, 3) ability_mods.each { |k, v| spread[abilities.index(k)] += v } abilities.each_index do |index| ability = abilities[index] monster.abilities[ability] = 13 + @level / 2 + spread[index] end end def set_threat!(threat) @threat = threat if @threat == :minion and not @primary_ability @primary_ability = :strength end end def set_role!(role) @role = role if not @primary_ability case role when :soldier @primary_ability = :strength when :skirmisher @primary_ability = :dexterity when :brute @primary_ability = :constitution when :artillery @primary_ability = :intelligence when :lurker @primary_ability = :wisdom when :controller @primary_ability = :charisma else raise "Invalid role value." end end end end end end
C#
UTF-8
1,085
2.625
3
[]
no_license
using Almotkaml.ArtificialLimbs.Core.Domain; using Almotkaml.ArtificialLimbs.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Almotkaml.ArtificialLimbs.Core.Extensions { public static class PatientExtensions { public static IEnumerable<PatientGridRow> ToGrid(this IEnumerable<Patient> patient) => patient.Select(d => new PatientGridRow() { PatientID = d.PatientID, PatientName =d.PatientName , BirthDate =d.BirthDate.ToShortDateString () , Gender =d.Gender, PhoneNumber = d.PhoneNumber , NationalityID =d.NationalityID , Nationality =d.Nationality?.Name , NationalityNumber =d.NationalityNumber , CityID = d.CityID, City=d.City?.Name , PlaceId = d.PlaceId , Place=d.Place?.Name , RegistrationDate =d.RegistrationDate.ToShortDateString (), Note =d.Note , }); } }
C++
UTF-8
787
3.078125
3
[]
no_license
#include "Level.h" Level::Level(sf::RenderWindow* hwnd, Input* in) { window = hwnd; input = in; // initialise game objects circle.setRadius(15); circle.setPosition(300, 300); circle.setFillColor(sf::Color::Green); circle.setOutlineColor(sf::Color::Magenta); circle.setOutlineThickness(2.f); speed = 10.f; } Level::~Level() { } // handle user input void Level::handleInput(float dt) { } // Update game objects void Level::update(float dt) { circle.move(speed *dt, 0); } // Render level void Level::render() { beginDraw(); window->draw(circle); endDraw(); } // clear back buffer void Level::beginDraw() { window->clear(sf::Color(100, 149, 237)); } // Ends rendering to the back buffer, and swaps buffer to the screen. void Level::endDraw() { window->display(); }
C++
UTF-8
683
2.515625
3
[]
no_license
/** \file BeamLogicProcessor.hpp * * Class to handle beam logic signals * To be used with TreeCorrelator * originally develeped for Dubna SHE 2014 */ #ifndef __BEAMLOGICPROCESSOR_HPP_ #define __BEAMLOGICPROCESSOR_HPP_ #include "EventProcessor.hpp" class BeamLogicProcessor : public EventProcessor { public: BeamLogicProcessor(); BeamLogicProcessor(int offset, int range); virtual void DeclarePlots(void); virtual bool PreProcess(RawEvent &event); virtual bool Process(RawEvent &event); private: /** Upper limit in seconds for bad (double) start/stop event */ static const double doubleTimeLimit_ = 1.0e-6; }; #endif // __BEAMLOGICPROCESSOR_HPP_
SQL
UTF-8
913
4
4
[]
no_license
drop table channels; create table channels ( id int auto_increment, name varchar(64), primary key(id) ); drop table messages; create table messages ( id int auto_increment, text varchar(512), created timestamp, primary key (id) ); drop table aggregations; create table aggregations( id int auto_increment, name varchar(64), url varchar(256), primary key(id) ); drop table message_refs; create table message_refs ( id int auto_increment, tweet_id bigint not null, message_id int not null, channel_id int not null, aggregation_id int not null, foreign key (message_id) references messages(id), foreign key (channel_id) references channels(id), foreign key (aggregation_id) references aggregations(id), primary key(id) ); insert into aggregations(name, url) values ('5931', 'http://google.co.jp'); select * from aggregations; delete from aggregations;
PHP
UTF-8
1,429
3.203125
3
[]
no_license
<?php class CRegistry Implements ArrayAccess { private $m_aVars; static private $instance = NULL; static public function GetInstance() { if(self::$instance == NULL) self::$instance = new CRegistry(); return self::$instance; } /** * */ private function __construct() { $this->m_aVars = array(); } private function __clone() { /* ... */ } private function __wakeup() { /* ... */ } /* * */ public function Set($in_sKey, $in_Var) { if(isset($this->m_aVars[$in_sKey])) throw new Exception('Unable to set var `' . $in_sKey . '`. Already set.'); $this->m_aVars[$in_sKey] = $in_Var; return true; } /* * */ public function Get($in_sKey) { if(!isset($this->m_aVars[$in_sKey])) return NULL; return $this->m_aVars[$in_sKey]; } /* * */ public function Remove($in_sKey) { unset($this->m_aVars[$in_sKey]); } /* * */ public function offsetExists($offset) { return isset($this->m_aVars[$offset]); } /* * */ public function offsetGet($offset) { return $this->Get($offset); } /* * */ public function offsetSet($offset, $value) { $this->Set($offset, $value); } /* * */ public function offsetUnset($offset) { $this->Remove($offset); } } ?>
PHP
UTF-8
2,927
2.796875
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace PavelMaca\OpenBanking\Standard\PISP\Parts; use PavelMaca\OpenBanking\Hydratation\HydratationException; trait DomesticPaymentHelper { /** * @var RemittanceInformation|null */ protected $remittanceInformation; public function getVariableSymbol(): ?string { return $this->searchCreditorReferenceInformation('VS:'); } /** * @param string|null $variableSymbol * @throws HydratationException */ public function setVariableSymbol(?string $variableSymbol): void { $this->setCreditorReferenceInformation('VS:', $variableSymbol); } public function getConstantSymbol(): ?string { return $this->searchCreditorReferenceInformation('KS:'); } /** * @param string|null $constantSymbol * @throws HydratationException */ public function setConstantSymbol(?string $constantSymbol): void { $this->setCreditorReferenceInformation('KS:', $constantSymbol); } public function getSpecificSymbol(): ?string { return $this->searchCreditorReferenceInformation('SS:'); } /** * @param string|null $specificSymbol * @throws HydratationException */ public function setSpecificSymbol(?string $specificSymbol): void { $this->setCreditorReferenceInformation('SS:', $specificSymbol); } private function searchCreditorReferenceInformation(string $search): ?string { if ($this->remittanceInformation === null) { return null; } $info = $this->remittanceInformation->getCreditorReferenceInformation(); if (!is_array($info)) { return null; } foreach ($info as $part) { if (strpos($part, $search) === 0) { return substr($part, 3, -1); } } return null; } /** * @param string $key * @param mixed $value * @throws HydratationException */ private function setCreditorReferenceInformation(string $key, $value): void { if ($this->remittanceInformation === null) { $this->remittanceInformation = new RemittanceInformation(); $this->remittanceInformation->setCreditorReferenceInformation([$key . $value]); return; } $info = $this->remittanceInformation->getCreditorReferenceInformation(); if (empty($info)) { $info = []; } if (!is_array($info)) { throw new HydratationException('Invalid value in remittanceInformation.creditorReferenceInformation, expected array'); } foreach ($info as $i => $part) { if (strpos($part, $key) === 0) { $info[$i] = $key . $value; break; } } $this->remittanceInformation->setCreditorReferenceInformation($info); } }
Python
UTF-8
3,430
3.296875
3
[]
no_license
import agents.agent import pygame.event import numpy as np import random class QLearningAgent(agents.agent.agent): """ Q-learning agent """ def __init__(self,pos,size,dim): super().__init__(pos,size) self.name = "Q-learning agent" self.q_table = np.zeros((dim*dim, 4)) #20x20 pixels and 4 actions self.dim = dim #hyperparamaters self.alpha = 0.3 self.gamma = 0.6 self.epsilon = 0.1 self.iterations = 1000 def step(self, move): self.update_pos(move) def generateMove(self, obs): """ Creates and updates the q-table, after which it picks the best value obs: matrix with 1 if goal, -1 if person and 0 otherwise returns: Best value according to the q-table """ #obs = matrix van nullen en +1 als het goal is en -1 als het vijand is self.q_table = np.zeros([21*21, 4]) #20x20 pixels and 4 actions for i in range(self.iterations): #training cycles startX, startY = int((self.dim-1)/2), int((self.dim-1)/2) x,y= int((self.dim-1)/2), int((self.dim-1)/2) done = False max_steps = 250 nr_steps = 0 while not done: state = x*(self.dim-1) + y if random.uniform(0,1) < self.epsilon: #force exploring by sometimes picking a random action action = np.random.randint(4) else: is_all_zero = np.all((self.q_table[state] == 0)) if is_all_zero: action = np.random.randint(4) else: action = np.argmax(self.q_table[state]) #0=left, 1=up, 2=right, 3=down if action == 0 and y>0 and obs[x,y-1] != -10: #no move outside the grid(y>0) and -10 means no outside grid in the "real" world y -= 1 elif action == 1 and x>0 and obs[x,y-1] != -10: x -= 1 elif action == 2 and y<self.dim-1 and obs[x,y-1] != -10: y += 1 elif action == 3 and x<self.dim-1 and obs[x,y-1] != -10: x += 1 reward = obs[x,y] old_value = self.q_table[state, action] next_state = x*(self.dim-1) + y next_max = np.max(self.q_table[next_state]) new_value = (1 - self.alpha) * old_value + self.alpha * (reward + self.gamma * next_max) #q-table update self.q_table[state, action] = new_value state = next_state nr_steps += 1 #if obs[x,y] == 1: # print('goal found') done = obs[x,y] == 1 or nr_steps >= max_steps action = np.argmax(self.q_table[startX*(self.dim-1) + startY]) #return correct action according to move if action == 0: return [-1,0] #x-1 and y doesn't change. Corresponds to moving left elif action == 1: return [0,-1] elif action == 2: return [1,0] elif action == 3: return [0,1] def set_q_table(self, dim): """ Change dimension of q-table, when switching from close view to big view. """ self.q_table = np.zeros((dim,dim)) self.dim = dim
C++
UTF-8
5,602
2.8125
3
[]
no_license
#include <iostream> #include <list> #include <string> #include <cstring> #include <utility> #include <queue> #include <map> #include <algorithm> #include <memory> #include "HuffmanCode.h" //************************************************************************* //Class NodeCmp //************************************************************************* bool NodeCmp::operator()(const std::shared_ptr<Node> first, const std::shared_ptr<Node> second) { return first -> frequency > second -> frequency; } //************************************************************************* //Class HuffmanCode //************************************************************************* std::vector<char> HuffmanCode::Code(const std::vector<char>& text) { //std::cout << "0" << std::endl; this -> DeterminationOfFrequency(text); // std::cout << "1 " << _frequency.size() << std::endl; this -> BuildTree(); // std::cout << "2" << std::endl; this -> BuildCoder(_head_of_tree); //std::cout << "3" << std::endl; auto it = _coder.begin(), end = _coder.end(); while(it != end) { //std::cout << it -> first << std::endl; ++it; } std::vector<char> code; char c; for(auto it_text = text.begin(), end_text = text.end(); it_text != end_text; ++it_text) { auto it_bool = _coder.find(*it_text) -> second.begin(), end_bool = _coder.find(*it_text) -> second.end(); while(it_bool != end_bool) { if(*it_bool) c = '1'; else c = '0'; code.push_back(c); ++it_bool; } } //std::cout << "4" << std::endl; return code; } std::vector<char> HuffmanCode::Decode(const std::vector<char>& code) { std::vector<char> text; std::vector<bool> buf; auto it_code = code.begin(), end_code = code.end(); auto end_decoder = _decoder.end(); while(it_code != end_code) { if(*it_code == '1') buf.push_back(true); else buf.push_back(false); auto it_decoder = _decoder.find(buf); if(it_decoder != end_decoder) { text.push_back(it_decoder -> second); buf.clear(); } ++it_code; } return text; } std::map<char, std::vector<bool> > HuffmanCode::GetCoder() { return _coder; } void HuffmanCode::SetCoder(const std::map<char, std::vector<bool> >& coder) { _coder = coder; } std::vector<char> HuffmanCode::GetDecoder() { std::vector<char> result; char c; auto it = _decoder.begin(), end = _decoder.end(); while(it != end) { auto it_vec = it -> first.begin(), end_vec = it -> first.end(); while(it_vec != end_vec) { if(*it_vec) c = '1'; else c = '0'; result.push_back(c); ++it_vec; } result.push_back(' '); c = it -> second; result.push_back(c); result.push_back('\n'); ++it; } return result; } void HuffmanCode::SetDecoder(const std::vector<char>& decoder) { auto it = decoder.begin(), end = decoder.end(); std::vector<bool> buf_vec; while(it != end && *it != EOF) { buf_vec.clear(); while(*it != ' ' && it != end) { if(*it == '1') buf_vec.push_back(true); else buf_vec.push_back(false); ++it; } ++it; _decoder[buf_vec] = *it; std::cout << *it << std::endl; ++it; while(*it != '\n' && it != end) ++it; ++it; std::cout << "good" << std::endl; } } void HuffmanCode::DeterminationOfFrequency(const std::vector<char>& text) { auto it_text = text.begin(), end_text = text.end(); while(it_text != end_text) { auto it_freq = _frequency.find(*it_text); if(it_freq == _frequency.end()) _frequency[*it_text] = 1; else { ++_frequency[*it_text]; } ++it_text; } } void HuffmanCode::BuildTree() { auto it_freq = _frequency.begin(), end_freq = _frequency.end(); while(it_freq != end_freq) { std::shared_ptr<Node> new_node(new Node); new_node -> c = it_freq -> first; new_node -> frequency = it_freq -> second; _for_tree.push(new_node); ++it_freq; } unsigned long int size = _for_tree.size(); while(--size >= 1) { std::shared_ptr<Node> left_child(new Node); left_child = _for_tree.top(); _for_tree.pop(); std::shared_ptr<Node> right_child(new Node); right_child = _for_tree.top(); _for_tree.pop(); std::shared_ptr<Node> parent(new Node); parent -> left = left_child; parent -> right = right_child; parent -> frequency = left_child -> frequency + right_child -> frequency; _for_tree.push(parent); } _head_of_tree = _for_tree.top(); } void HuffmanCode::BuildCoder(const std::shared_ptr<Node> _head_of_tree) { static std::vector<bool> code; if(_head_of_tree -> left != nullptr) { code.push_back(0); BuildCoder(_head_of_tree -> left); } if(_head_of_tree -> right != nullptr) { code.push_back(1); BuildCoder(_head_of_tree -> right); } if(_head_of_tree -> left == nullptr && _head_of_tree -> right == nullptr) { _coder[_head_of_tree -> c] = code; _decoder[code] = _head_of_tree -> c; } code.pop_back(); }
Java
UTF-8
1,914
3.046875
3
[]
no_license
package Dados; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.GregorianCalendar; /** * * @author n226324633 * *classe:Produto */ public class Produto implements Serializable{ public static int codigogerador = 0; private int codigo; private double preco_unit; private GregorianCalendar dateOfLog; private GregorianCalendar dateOfUpdate; private String nome; public int getCodigo() { return codigo; } public void setCodigo(int codigo) { this.codigo = codigo; } public double getPreco_unit() { return preco_unit; } public void setPreco_unit(double preco_unit) { this.preco_unit = preco_unit; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public GregorianCalendar getDateOfLog() { return dateOfLog; } public void setDateOfLog(GregorianCalendar dateOfLog) { this.dateOfLog = dateOfLog; } public GregorianCalendar getDateOfUpdate() { return dateOfUpdate; } public void setDateOfUpdate(GregorianCalendar dateOfUpdate) { this.dateOfUpdate = dateOfUpdate; } public Produto(String name,double preco_unitp,GregorianCalendar dateOfLogp, GregorianCalendar dateOfUpdate){ setNome(name); setCodigo(++codigogerador); setPreco_unit(preco_unitp); setDateOfLog(dateOfLogp); setDateOfUpdate(dateOfUpdate); } @Override public String toString() { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); String objectString; return "Product's code: "+this.getCodigo()+"\n" + " Product's name: "+ this.getNome() +"\n" + "Unity Price: "+this.getPreco_unit() + "\n Product's date of log: "+ (this.getDateOfLog() == null ? "":sdf.format(this.getDateOfLog().getTime()))+ "\n" + "Product's date of update: "+ (this.getDateOfUpdate() == null ? "" : sdf.format(this.getDateOfUpdate().getTime())) + "\n"; } }
Markdown
UTF-8
1,730
2.546875
3
[ "MIT" ]
permissive
--- layout: page-fullwidth title: "An anonymous face to face dating app" subheadline: "Hi There" meta_teaser: "Make your first move when you see someone attractive, realtime" teaser: "<em>Make your first move when you see someone attractive, realtime</em>" header: image_fullwidth: galaxy.jpg categories: --- <!--more--> ### Features <br /> <ul> <li>No registration required. (anonymous)</li> <li>Works without Internet connectivity.</li> <li>Stores user profile locally.</li> <li>Uses BLE/Wi-Fi P2P to detect a nearby user and send/receive information directly.</li> <li>User profiles will be broadcast only to nearby users.</li> <li>Does not have a server side.</li> <li>Based on the nature of this implementation, it does not collect (and is not able to collect) user information.</li> <li>Utilizes the proximity between mobile phones, instead of location data.</li> <li>Internet Service Providers are not be able to block, slow down, filter, or monitor the service because messages are exchanged directly between nearby mobile phones.</li> <li>The app itself is not able to block or filter user messages either.</li> <li>Bonus: It also fully complies with the new cybersecurity laws enforced by countries like Russia and China, which require certain companies to store personal and “significant data” to servers on their soil if you know what I'm talking about.</li> </ul> <a href="https://play.google.com/store/apps/details?id=ent.ble.wifidirect.sean.wififilesender"> <img src="https://Pie-Pie-Cat.github.io/images/android_app_store.jpg" border="0"> </a> <a href="https://itunes.apple.com/us/app/hi-there-p2p/id1276567474?ls=1&mt=8"> <img src="https://Pie-Pie-Cat.github.io/images/ios_app_store.jpg" border="0"> </a>
C#
UTF-8
4,579
2.75
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data.SqlClient; using System.Linq; using System.Web; namespace WebAppCrudsPrj.DAL { public class DALClassFornecedores { string connectionString = ""; public DALClassFornecedores() { connectionString = ConfigurationManager.ConnectionStrings["SGEDConnectionString"].ConnectionString; } [DataObjectMethod(DataObjectMethodType.Select)] public List<Modelo.Fornecedores> SelectAll() { Modelo.Fornecedores aFornecedores; List<Modelo.Fornecedores> aListFornecedores = new List<Modelo.Fornecedores>(); SqlConnection conn = new SqlConnection(connectionString); conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT * FROM Fornecedor"; SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { while (dr.Read()) { aFornecedores = new Modelo.Fornecedores( Convert.ToInt32(dr["id"].ToString()), dr["nome"].ToString(), dr["email"].ToString(), dr["telefone"].ToString() ); aListFornecedores.Add(aFornecedores); } } dr.Close(); conn.Close(); return aListFornecedores; } [DataObjectMethod(DataObjectMethodType.Delete)] public void Delete(Modelo.Fornecedores obj) { SqlConnection conn = new SqlConnection(connectionString); conn.Open(); SqlCommand com = conn.CreateCommand(); SqlCommand cmd = new SqlCommand("DELETE FROM Fornecedor WHERE id = @id", conn); cmd.Parameters.AddWithValue("@id", obj.id); cmd.ExecuteNonQuery(); } [DataObjectMethod(DataObjectMethodType.Insert)] public void Insert(Modelo.Fornecedores obj) { SqlConnection conn = new SqlConnection(connectionString); conn.Open(); SqlCommand com = conn.CreateCommand(); SqlCommand cmd = new SqlCommand("INSERT INTO Fornecedor (nome, email, telefone) VALUES(@nome, @email, @telefone)", conn); cmd.Parameters.AddWithValue("@nome", obj.nome); cmd.Parameters.AddWithValue("@email", obj.email); cmd.Parameters.AddWithValue("@telefone", obj.telefone); cmd.ExecuteNonQuery(); } [DataObjectMethod(DataObjectMethodType.Update)] public void Update(Modelo.Fornecedores obj) { SqlConnection conn = new SqlConnection(connectionString); conn.Open(); SqlCommand com = conn.CreateCommand(); SqlCommand cmd = new SqlCommand("UPDATE Fornecedor SET nome = @nome, email = @email, telefone = @telefone WHERE id = @id", conn); cmd.Parameters.AddWithValue("@id", obj.id); cmd.Parameters.AddWithValue("@nome", obj.nome); cmd.Parameters.AddWithValue("@email", obj.email); cmd.Parameters.AddWithValue("@telefone", obj.telefone); cmd.ExecuteNonQuery(); } [DataObjectMethod(DataObjectMethodType.Select)] public List<Modelo.Fornecedores> Select(int id) { Modelo.Fornecedores aFornecedores; List<Modelo.Fornecedores> aListFornecedores = new List<Modelo.Fornecedores>(); SqlConnection conn = new SqlConnection(connectionString); conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT * FROM Fornecedor WHERE id = @id"; cmd.Parameters.AddWithValue("@id", id); SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { while (dr.Read()) { aFornecedores = new Modelo.Fornecedores( Convert.ToInt32(dr["id"].ToString()), dr["nome"].ToString(), dr["email"].ToString(), dr["telefone"].ToString() ); aListFornecedores.Add(aFornecedores); } } dr.Close(); conn.Close(); return aListFornecedores; } } }
Python
UTF-8
10,683
2.765625
3
[ "MIT" ]
permissive
#!/usr/bin/env python import re from struct import unpack from os.path import basename # Handle parsing files into sets of addresses, each describing the start of a basic block # Can be invoked as a standalone script for debugging purposes def detect_format(filename): """Return the name of the format based on the start of the file.""" enough_bytes = 0x1000 with open(filename, 'rb') as f: data = f.read(enough_bytes) if isinstance(data, bytes): data = data.decode(errors='replace') if data.startswith('DRCOV VERSION:'): return 'drcov' if '+' in data: # Check for module+offset, skipping any comment lines at start for line in data.split('\n'): if line.strip().startswith(';'): continue pieces = line.split('+') if len(pieces) == 2: try: hex_int = int(pieces[1], 16) return 'module+offset' except ValueError: pass raise Exception('[!] File "%s" doesn\'t appear to be drcov or module+offset format' % filename) def parse_coverage_file(filename, module_name, module_base, module_blocks, debug=False): """Return a set of addresses of covered blocks in the specified module""" file_format = detect_format(filename) if file_format == 'drcov': blocks = parse_drcov_file(filename, module_name, module_base, module_blocks) elif file_format == 'module+offset': blocks = parse_mod_offset_file(filename, module_name, module_base, module_blocks) return blocks def parse_mod_offset_file(filename, module_name, module_base, module_blocks, debug=False): """Return blocks from a file with "module_name+hex_offset" format.""" blocks = set() modules_seen = set() # We do a case-insensitive module name comparison to match Windows behavior module_name = module_name.lower() with open(filename, 'r') as f: for line in f.readlines(): if line.strip().startswith(';'): continue pieces = line.split('+') if len(pieces) != 2: continue name, offset = pieces name = name.lower() if debug: if module_name != name and name not in modules_seen: print('[DBG] module mismatch, expected (%s), encountered (%s)' % (module_name, name)) modules_seen.add(name) block_offset = int(offset, 16) block_addr = module_base + block_offset if block_addr in module_blocks: blocks.add(block_addr) elif debug: print('[!] DBG: address 0x%x not in module_blocks!' % block_addr) return blocks def parse_drcov_header(header, module_name, filename, debug): module_name = module_name.lower() module_table_start = False module_ids = [] for i, line in enumerate(header.split("\n")): # Encountering the basic block table indicates end of the module table if line.startswith("BB Table"): break # The first entry in the module table starts with "0", potentially after leading spaces if line.strip().startswith("0"): module_table_start = True if module_table_start: columns = line.split(",") if debug: print("[DBG] Module table entry: %s" % line.strip()) for col in columns[1:]: if module_name != "" and module_name in basename(col).lower(): module_ids.append(int(columns[0])) if debug: print("[DBG] Target module found (%d): %s" % (int(columns[0]), line.strip())) if not module_table_start: raise Exception('[!] No module table found in "%s"' % filename) if not module_ids and not debug: raise Exception("[!] Didn't find expected target '%s' in the module table in %s" % (module_name, filename)) return module_ids def parse_drcov_binary_blocks(block_data, filename, module_ids, module_base, module_blocks, debug): blocks = set() block_data_len = len(block_data) blocks_seen = 0 remainder = block_data_len % 8 if remainder != 0: print("[!] Warning: %d trailing bytes left over in %s" % (remainder, filename)) block_data = block_data[:-remainder] if debug: module_dict = {} for i in range(0, block_data_len, 8): block_offset = unpack("I", block_data[i:i + 4])[0] block_size = unpack("H", block_data[i + 4:i + 6])[0] block_module_id = unpack("H", block_data[i + 6:i + 8])[0] block_addr = module_base + block_offset blocks_seen += 1 if debug: print("%d: 0x%08x 0x%x" % (block_module_id, block_offset, block_size)) module_dict[block_module_id] = module_dict.get(block_module_id, 0) + 1 if block_module_id in module_ids: cur_addr = block_addr # traces can contain "blocks" that split and span blocks # so we need a fairly comprehensive check to get it right while cur_addr < block_addr + block_size: if cur_addr in module_blocks: blocks.add(cur_addr) cur_addr += module_blocks[cur_addr] else: cur_addr += 1 if debug: print('[DBG] Block count per-module:') for module_number, blocks_hit in sorted(module_dict.items()): print(' %d: %d' % (module_number, blocks_hit)) return blocks, blocks_seen def parse_drcov_ascii_blocks(block_data, filename, module_ids, module_base, module_blocks, debug): blocks = set() blocks_seen = 0 int_base = 0 # 0 not set, 10 or 16 if debug: module_dict = {} for line in block_data.split(b"\n"): # example: 'module[ 4]: 0x0000000000001090, 8' left_bracket_index = line.find(b'[') right_bracket_index = line.find(b']') # skip bad/blank lines if left_bracket_index == -1 or right_bracket_index == -1: continue block_module_id = int(line[left_bracket_index+1: right_bracket_index]) block_offset, block_size = line[right_bracket_index+2:].split(b',') if int_base: block_offset = int(block_offset, int_base) else: if b'x' in block_offset: int_base = 16 else: int_base = 10 block_offset = int(block_offset, int_base) block_size = int(block_size) block_addr = module_base + block_offset blocks_seen += 1 if debug: print("%d: 0x%08x 0x%x" % (block_module_id, block_offset, block_size)) module_dict[block_module_id] = module_dict.get(block_module_id, 0) + 1 if block_module_id in module_ids: cur_addr = block_addr while cur_addr < block_addr + block_size: if cur_addr in module_blocks: blocks.add(cur_addr) cur_addr += module_blocks[cur_addr] else: cur_addr += 1 if debug: print('[DBG] Block count per-module:') for module_number, blocks_hit in sorted(module_dict.items()): print(' %d: %d' % (module_number, blocks_hit)) return blocks, blocks_seen def parse_drcov_file(filename, module_name, module_base, module_blocks, debug=False): """Return set of blocks in module covered (block definitions provided in module_blocks)""" with open(filename, 'rb') as f: data = f.read() # Sanity checks for expected contents drcov_match = re.match(b"DRCOV VERSION: ([0-9])", data) if drcov_match is None: raise Exception("[!] File \"%s\" does not appear to be a drcov format file, " % filename + "it doesn't start with the expected signature: 'DRCOV VERSION: 2'") # Most recent Dynamorio release as of this writing: 9.0.1 supported_versions = [2, 3] drcov_version = int(drcov_match.groups()[0]) if drcov_version not in supported_versions: raise Exception("[!] The drcov version (%d) of \"%s\" is not yet supported (please file a GitHub issue)" % (drcov_version, filename)) header_end_pattern = b"BB Table: " header_end_location = data.find(header_end_pattern) if header_end_location == -1: raise Exception("[!] File \"%s\" does not appear to be a drcov format file, " % filename + "it doesn't contain a header for the basic block table'") header_end_location = data.find(b"\n", header_end_location) + 1 # +1 to skip the newline # Check for ascii vs binary drcov version (binary is the default) binary_file = True ascii_block_header = b"module id, start, size:" block_header_candidate = data[header_end_location:header_end_location + len(ascii_block_header)] if block_header_candidate == ascii_block_header: binary_file = False # Skip the ascii block header line ("module id, start, size:\n") header_end_location = data.find(b"\n", header_end_location) + 1 # +1 to skip the newline # Parse the header header = data[:header_end_location].decode() block_data = data[header_end_location:] module_ids = parse_drcov_header(header, module_name, filename, debug) # Parse the block data itself if binary_file: parse_blocks = parse_drcov_binary_blocks else: parse_blocks = parse_drcov_ascii_blocks if debug: print("[DBG] Detected drcov %s format" % ("binary" if binary_file else "ascii")) print("[DBG] Basic block dump (module_id, block_offset, block_size)") blocks, blocks_seen = parse_blocks(block_data, filename, module_ids, module_base, module_blocks, debug) if debug: if not module_ids: print("[*] %d blocks parsed, no module id specified" % blocks_seen) else: num_blocks_found = len(blocks) print("[*] %d blocks parsed; module_ids %s" % (blocks_seen, module_ids)) return blocks if __name__ == "__main__": import sys import time if len(sys.argv) == 1: print("STANDALONE USAGE: %s <trace_file> [module_name]" % sys.argv[0]) exit() target = sys.argv[1] module_name = "" if len(sys.argv) >= 3: module_name = sys.argv[2] start = time.time() parse_coverage_file(sys.argv[1], module_name, 0, [], debug=True) duration = time.time() - start print('[*] Completed parsing in %.2f seconds' % duration)
Python
UTF-8
895
4.625
5
[]
no_license
''' **2.26 (Turtle: draw a circle) Write a program that prompts the user to enter the center and radius of a circle, and then displays the circle and its area. /** * @author BASSAM FARAMAWI * @email tiodaronzi3@yahoo.com * @since 2018 */ ''' import turtle # Import turtle module import math # Import cmath module # Prompt the user to enter center point centerX, centerY = eval(input("Enter the circle center in X and Y: ")) # Prompt the user to enter the circle radius radius = eval(input("Enter the circle radius: ")) turtle.showturtle() # Show the turtle graphics window # Draw circle turtle.penup() turtle.goto(centerX, centerY - radius) turtle.pendown() turtle.circle(radius) turtle.penup() # Write area inside circle turtle.goto(centerX, centerY) turtle.pendown() area = math.pi * radius ** 2 turtle.write(int(area * 100) / 100) turtle.done() # Don't close the turtle graphics window
Python
UTF-8
247
3.609375
4
[]
no_license
def is_palindrome(n): return str(n) == str(n)[::-1] largest = 0 for n in range(100,1000): for m in range(100,1000): number = n * m if is_palindrome(number) and number > largest: largest = number print largest
Markdown
UTF-8
2,754
2.90625
3
[ "MIT" ]
permissive
# @node-ts/bus-core [![Greenkeeper badge](https://badges.greenkeeper.io/node-ts/bus.svg)](https://greenkeeper.io/) [![CircleCI](https://circleci.com/gh/node-ts/bus/tree/master.svg?style=svg)](https://circleci.com/gh/node-ts/bus/tree/master)[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT) The core messaging framework. This package provides an in-memory queue and persistence by default, but is designed to be used with other @node-ts/bus-* packages that provide compatibility with other transports (SQS, RabbitMQ, Azure Queues) and persistence technologies (PostgreSQL, SQL Server, Oracle). ## Installation Download and install the packages: ```bash npm i inversify @node-ts/bus-core --save ``` Load `BusModule` into your application's inversify container: ```typescript // application-container.ts import { Container } from 'inversify' import { BusModule } from '@node-ts/bus-core' export class ApplicationContainer extends Container { constructor () { this.load(new BusModule()) } } ``` ## Register a message handler Messages are handled by defining and registring a handler class. Each time a message is received by the application, it will be dispatched to each of the registered handlers. Define the handler: ```typescript // send-email-handler.ts import { injectable } from 'inversify' import { HandlesMessage, Handler } from '@node-ts/bus-core' import { SendEmail } from 'my-corporation/commands' import { SERVICE_SYMBOLS, EmailService } from '../services' @HandlesMessage(SendEmail) export class SendEmailHandler implements Handler<SendEmail> { constructor ( @inject(SERVICE_SYMBOLS.EmailService) private readonly emailService: EmailService ) { } async handle (sendEmailCommand: SendEmail): Promise<void> { await this.emailService.send( sendEmailCommand.to, sendEmailCommand.title, sendEmailCommand.body ) } } ``` Register the handler: ```typescript // application.ts import { inject, injectable } from 'inversify' import { BUS_SYMBOLS, ApplicationBootstrap, Bus } from '@node-ts/bus-core' @injectable() export class Application { constructor ( @inject(BUS_SYMBOLS.ApplicationBootstrap) private readonly applicationBootstrap: ApplicationBootstrap, @inject(BUS_SYMBOLS.Bus) private readonly bus: Bus ) { } async initialize (): Promise<void> { this.applicationBootstrap.registerHandler(SendEmailHandler) // Starts the receive loop on the bus to pull messages from the queue and dispatch to handlers await this.applicationBootstrap.initialize() } async stop (): Promise<void> { // Stops the queue polling mechanism so the app shuts down cleanly await this.bus.stop() } } ```
Java
UTF-8
2,100
2.0625
2
[]
no_license
package com.gogoyang.rpgapi.meta.job.service; import com.gogoyang.rpgapi.framework.constant.JobStatus; import com.gogoyang.rpgapi.meta.job.entity.Job; import java.util.ArrayList; import java.util.Map; public interface IJobService { void insertJob(Job job) throws Exception; /** * 读取Job的详细信息,包括jobDetail * * @param jobId * @return * @throws Exception */ Job getJobDetailByJobId(String jobId) throws Exception; /** * 读取job,不带detail * * @param jobId * @return * @throws Exception */ Job getJobTinyByJobId(String jobId) throws Exception; /** * 根据taskId读取job * * @param taskId * @return * @throws Exception */ Job getJobByTaskId(String taskId) throws Exception; /** * 根据jobStatus读取jobs * read jobs by jobStatus * paginate the list * * @param pageIndex * @param pageSize * @return * @throws Exception */ ArrayList<Job> listJobByStatus(JobStatus jobStatus, Integer pageIndex, Integer pageSize) throws Exception; /** * 修改job * * @param job * @throws Exception */ void updateJob(Job job) throws Exception; /** * 读取所有我是甲方的任务 * * @param qIn * @return * @throws Exception */ Map listPartyAJob(Map qIn) throws Exception; /** * 读取我是乙方的所有任务 * * @param qIn * @return * @throws Exception */ Map listPartyBJob(Map qIn) throws Exception; Map listMyPendingJob(String partyAId, Integer pageIndex, Integer pageSize) throws Exception; void deleteJob(String jobId) throws Exception; Map listPublicJob(Integer pageIndex, Integer pageSize) throws Exception; Map listMyPartyAAcceptJob(String userId, Integer pageIndex, Integer pageSize) throws Exception; ArrayList<Job> listMyPartyBAcceptJob(String userId, Integer pageIndex, Integer pageSize) throws Exception; }
Shell
UTF-8
558
3.5625
4
[ "BSD-3-Clause" ]
permissive
#!/usr/bin/env bash set -e SOURCE_PATH=/src/ BUILD_PATH=$HOME/build echo "Transferring the source: $SOURCE_PATH -> $BUILD_PATH. Please wait..." cd $BUILD_PATH && cp -rp $SOURCE_PATH . && cd src echo echo "Compiling PhantomJS..." && sleep 1 python build.py --confirm --release --qt-config="-no-pkg-config" --git-clean-qtbase --git-clean-qtwebkit echo echo "Stripping the executable..." && sleep 1 ls -l bin/phantomjs strip bin/phantomjs echo "Copying the executable..." && sleep 1 ls -l bin/phantomjs cp bin/phantomjs $SOURCE_PATH echo echo "Finished."
JavaScript
UTF-8
1,877
3.296875
3
[]
no_license
// rwd_page.js (function($){ var winW = $(window).width(); var size = $('.size'); // step1 ================================= /* var ViewSize = function(e){ e.preventDefault(); var nowW = $(window).width(); if(winW !== nowW){ location.reload(); } size.text(nowW); }; $(window).on('resize',ViewSize); */ // step1 ================================= /* 각각의 디바이스 환경이 변하면 새로고침 var mob = 480; var tab = 768; var pc = 1366; var myDevice; var product = $('.product'); var Device = function(width){ if(width <= mob){ myDevice = 'mobile'; $('.device').css({bacgroundColor:'#caa'}); }else if(width > mob && width <= tab){ myDevice = 'tablet'; $('.device').css({color:'#f5f'}); }else if(width > tab && width <= pc){ myDevice = 'pc'; $('.device').css({border:'5px solid #fa0'}); }else{ myDevice = 'pcfull'; } product.text(myDevice); console.log(myDevice); return myDevice; }; // Device();함수가 끝남 // return이 필요한 이유 : 반환 되돌려주는것.함수자체가 돌려받아야될것. 각각의 상황에 따른 반환값을 확인(비교)하기위해 ,실제로 함수의 값을 저장하기위해서. var beforeDevice = Device(winW); // 비교할수있는 기존의 디바이스 넓이값을 저장 $(window).on('resize',function(){ var nowW = $(window).width(); var afterDevice = Device(nowW); // 비교할수있는 현재의 디바이스 넓이값을 저장 if(beforeDevice !== afterDevice){ // 기존의 값과 현재의 넓이값을 비교 // 비교값이 다르다면 location.reload(); // 새로고침해라(새로고침 하여 각 디바이스의(넓이) 기능만을 가져라) } // console.log(beforeDevice,afterDevice); }); */ })(jQuery);
Shell
UTF-8
369
3.0625
3
[]
no_license
#!/bin/bash set -e npm i && bower i && npm run build -- -e production if [ "$TRAVIS_BRANCH" == "master" ]; then pushd dist &> /dev/null git init git config user.name "AutoBot" git config user.email "dylan947@gmail.com" git add -A git commit -m "Deploy to GitHub pages" git push --force "https://${GH_TOKEN}@${GH_REF}.git" master popd &> /dev/null fi
C++
UTF-8
962
3.59375
4
[]
no_license
#pragma once template<typename vTy> struct ptr_ref { public: typedef vTy value_type; typedef value_type* pointer; typedef const value_type* const_pointer; ptr_ref() = default; ptr_ref(pointer vptr) : ptr(vptr) { } ptr_ref& operator =(const ptr_ref& o) { ptr = o.ptr; return *this; } ptr_ref& operator =(pointer v) { ptr = v; return *this; } bool operator ==(const ptr_ref& ref) const { return ref.ptr == ptr; } bool operator !=(const ptr_ref& ref) const { return ref.ptr != ptr; } bool operator ==(const_pointer vptr) const { return ptr == vptr; } bool operator !=(const_pointer vptr) const { return ptr != vptr; } operator bool() const { return ptr; } bool operator !() const { return !ptr; } pointer operator ->() { return ptr; } const_pointer operator ->() const { return ptr; } pointer get() { return ptr; } const_pointer get() const { return ptr; } private: pointer ptr; };