language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Rust
UTF-8
1,647
3.140625
3
[ "MIT" ]
permissive
use crate::code::exp::{ExpLoc, Exp, find_range, SourceRange}; use crate::code::translator::Context; use crate::{Encode, write_array}; use std::fmt::Write; use anyhow::Error; /// Return expression. #[derive(Debug)] pub struct Ret<'a> { /// Result tuple. pub ret_list: Vec<ExpLoc<'a>>, /// is explicit return required. pub explicit_keyword: bool, } impl<'a> Ret<'a> { /// Create a new `Ret` expression. #[allow(clippy::needless_collect)] pub fn exp(ret_len: usize, ctx: &mut impl Context<'a>) -> Exp<'a> { let params = (0..ret_len).map(|_| ctx.pop_exp()).collect::<Vec<_>>(); Exp::Ret(Ret { ret_list: params.into_iter().rev().collect(), explicit_keyword: false, }) } /// Returns `true` if the function empty tuple. pub fn is_empty(&self) -> bool { self.ret_list.is_empty() } /// Returns `true` if the explicit return keyword required. pub fn is_explicit(&self) -> bool { self.explicit_keyword } } impl<'a> SourceRange for Ret<'a> { fn source_range(&self) -> Option<(usize, usize)> { find_range(&self.ret_list) } } impl<'a> Encode for Ret<'a> { fn encode<W: Write>(&self, w: &mut W, _: usize) -> Result<(), Error> { if self.explicit_keyword { w.write_str("return ")?; } match self.ret_list.len() { 0 => { //no-op } 1 => { self.ret_list[0].encode(w, 0)?; } _ => { write_array(w, "(", ", ", &self.ret_list, ")")?; } } Ok(()) } }
TypeScript
UTF-8
2,764
2.765625
3
[ "MIT" ]
permissive
/// <reference path='../../Typings/tsd.d.ts' /> module Orckestra.Composer { /** * Separates the logic that retrieves the data and maps it to the entity model from the application services that acts on the model. */ export interface ICartRepository { /** * Get the cart of the current customer. */ getCart(): Q.Promise<any>; /** * Add a line item to the cart of the current customer. */ addLineItem(productId: string, variantId?: string, quantity?: number, recurringOrderFrequencyName?: string, recurringOrderProgramName?: string): Q.Promise<any>; /** * Update the quantity of a line item in the cart of the current customer. */ updateLineItem(lineItemId: string, quantity: number, recurringOrderFrequencyName?: string, recurringOrderProgramName?: string): Q.Promise<any>; /** * Delete a line item from the cart of the current customer. */ deleteLineItem(lineItemId: string): Q.Promise<any>; /** * Update the postal code of the billing method in cart of the current customer. */ updateBillingMethodPostalCode(postalCode: string): Q.Promise<any>; /** * Update the postal code of the shipping method in cart of the current customer. */ updateShippingMethodPostalCode(postalCode: string): Q.Promise<any>; /** * Set the cheapest shipping method in cart of the current customer. */ setCheapestShippingMethod(): Q.Promise<any>; /** * Add a coupon to the cart of the current customer. */ addCoupon(couponCode: string): Q.Promise<any>; /** * Remove a coupon from the cart of the current customer. */ removeCoupon(couponCode: string): Q.Promise<any>; /** * Cleans the cart of invalid line items. */ clean(): Q.Promise<any>; /** * Update the cart of the current customer. */ updateCart(param: any): Q.Promise<IUpdateCartResult>; /** * Complete the checkout, thereby clearing every item in the cart of the current customer. */ completeCheckout(currentStep: number): Q.Promise<ICompleteCheckoutResult>; } export interface IUpdateCartResult { HasErrors: boolean; NextStepUrl: string; Cart: any; } export interface ICompleteCheckoutResult { OrderNumber: string; CustomerEmail: string; CustomerFirstName: string; CustomerLastName: string; NextStepUrl: string; IsUpdatedOrder?: boolean; } }
C++
UTF-8
2,253
3.515625
4
[ "MIT" ]
permissive
/********* -*- Made by VoxelPixel -*- For YouTube Tutorial -*- https://github.com/VoxelPixel -*- Support me on Patreon: https://www.patreon.com/voxelpixel *********/ #include <iostream> #include <sstream> #include <iomanip> #include <stdlib.h> using namespace std; void cipherEncryption(){ string msg; cout << "Enter message: "; getline(cin, msg); string key; cout << "Enter key: "; getline(cin, key); string encrypHexa = ""; int keyItr = 0; stringstream res; for (int i = 0; i < msg.length(); i++){ int temp = msg[i] ^ key[keyItr]; res << hex << setfill('0') << std::setw(2) << (int)temp; keyItr++; if (keyItr >= key.length()){ // once all of key's letters are used, repeat the key keyItr = 0; } } res >> encrypHexa; cout << "Encrypted Text: " << encrypHexa; } void cipherDecryption(){ string msg; cout << "Enter message: "; getline(cin, msg); string key; cout << "Enter key: "; getline(cin, key); string hexToUni = ""; for (int i = 0; i < msg.length()-1; i+=2){ // splitting hex into a pair of two string output = msg.substr(i, 2); // converting hex into unicode int decimal = strtol(output.c_str(), NULL, 16); hexToUni += (char)decimal; } string decrypText = ""; int keyItr = 0; for (int i = 0; i < hexToUni.length(); i++){ int temp = hexToUni[i] ^ key[keyItr]; decrypText += (char)temp; keyItr++; if (keyItr >= key.length()){ // once all of key's letters are used, repeat the key keyItr = 0; } } cout << "Decrypted Text: " << decrypText; } int main() { cout << "1. Encryption\n2. Decryption\nChoose(1,2): "; int choice; cin >> choice; cin.ignore(); if (choice == 1){ cout << endl << "---Encryption---" << endl; cipherEncryption(); } else if (choice == 2){ cout << endl << "---Decryption---" << endl; cipherDecryption(); } else { cout << endl << "Wrong choice" << endl; } return 0; }
Java
UTF-8
1,275
2.734375
3
[]
no_license
package by.bsuir; import by.bsuir.autobase.entity.*; import by.bsuir.autobase.presentation.View; import java.io.*; public class Main { public static void main(String[] args){ View.chooseActionLoop(); } private static AutoBase loadAutoBase() { try( // Reading the object from a file FileInputStream file = new FileInputStream("AutoBase.ser"); ObjectInputStream in = new ObjectInputStream(file); ) { // Method for deserialization of object return (AutoBase)in.readObject(); } catch(IOException | ClassNotFoundException ex) { System.out.println(ex.getMessage()); return null; } } // Method for serialization of object private static void saveAutoBase(AutoBase autoBase) { try( //Saving the object in a file FileOutputStream file = new FileOutputStream("AutoBase.ser"); ObjectOutputStream out = new ObjectOutputStream(file); ) { out.writeObject(autoBase); } catch(IOException ex) { System.out.println(ex.getMessage()); } } }
Markdown
UTF-8
562
2.5625
3
[]
no_license
+++ title = "Awesome terminal emulator for Windows" date = "2014-12-02 21:15:37" categories = [ "CLI" ] +++ Cmder is a software package created out of pure frustration over the absence of nice console emulators on Windows. It is based on amazing software, and spiced up with the Monokai color scheme and a custom prompt layout. Looking sexy from the start. <!--more--> Download [here](http://bliker.github.io/cmder/) [Instruction](https://github.com/cmderdev/cmder/wiki/%5BWindows%5D-%22Open-Cmder-Here%22-in-context-menu) to add `cmder` to context menu.
Python
UTF-8
2,114
2.546875
3
[]
no_license
import torch from torch.nn import Module, Parameter from torchgibbs.log_pdf import normal_log_pdf class DistributionSampler(Module): def sample(self, *inputs): pass class GaussianMixtureMultinomial(DistributionSampler): def __init__(self, means, cov=None): super().__init__() self.means = means self.cov = Parameter(torch.FloatTensor([1.0])) if cov is None else cov def sample(self, xs): assert xs.size(1) == self.means.size(1) pxs = normal_log_pdf(xs, self.means.data, self.cov.data).exp() # [B, K] pks = pxs / pxs.sum(dim=1, keepdim=True) # [B, K] return torch.multinomial(pks, 1).squeeze(1) # [B] def select_k(xs, ids, k): n_batch, n_dim = xs.size() assert ids.size() == (n_batch,) assert isinstance(k, int) mask = ids == k mask = mask.expand(n_dim, xs.size(0)).transpose(0, 1) return torch.masked_select(xs, mask).view(-1, n_dim) class Gaussian(DistributionSampler): def __init__(self, cov=1.0): super().__init__() self.cov = cov def sample(self, xs, sampled_ks, k): x_k = select_k(xs, sampled_ks, k) # [B, D] n_k = 0 if x_k.dim() == 0 else x_k.size(0) x_mean_k = xs.new([0]) if x_k.dim() == 0 else torch.mean(x_k, dim=0) return torch.normal(n_k / (n_k + 1) * x_mean_k, self.cov / (n_k + 1)) class GaussianPriorGaussian(DistributionSampler): def __init__(self, cov, mean_prior_mean, mean_prior_inv_cov_factor): super().__init__() self.cov = cov self.mean_mean = mean_prior_mean self.mean_inv_cov_factor = mean_prior_inv_cov_factor def sample(self, xs, sampled_ks, k): x_k = select_k(xs, sampled_ks, k) # [B, D] n_k = 0 if x_k.dim() == 0 else x_k.size(0) x_mean_k = xs.new([0]) if x_k.dim() == 0 else torch.mean(x_k, dim=0) mean_mean = (n_k * x_mean_k + self.mean_inv_cov_factor * self.mean_mean) / \ (n_k + self.mean_inv_cov_factor) mean_cov = self.cov / (n_k + self.mean_inv_cov_factor) return torch.nomal(mean_mean, mean_cov)
PHP
UTF-8
3,607
2.53125
3
[ "MIT" ]
permissive
<?php namespace App\Controllers; use CodeIgniter\Controller; use App\Models\producto; class Productos extends Controller{ public function index() { $producto=new Producto(); $datos['productos']=$producto->orderBy('codigo','ASC')->findAll(); $datos['cabecera']=view('templates/cabecera'); $datos['pie']=view('templates/piedepagina'); return view('mostrar', $datos); } public function ingresar(){ $datos['cabecera']=view('templates/cabecera'); $datos['pie']=view('templates/piedepagina'); return view('ingresar', $datos); } public function guardar(){ $productos = new producto(); $validacion = $this->validate([ 'Nombre'=>'required|min_length[3]', 'Detalle'=>'required|min_length[3]', 'Fecha_Ingreso'=>'required', 'Precio'=>'required', ]); if(!$validacion){ $session= session(); $session->setFlashdata('mensaje', 'Todos los campos son requeridos'); return redirect()->back()->withInput(); } $datos=[ 'Nombre'=>$this->request->getVar('Nombre'), 'Detalle'=>$this->request->getVar('Detalle'), 'Fecha_Ingreso'=>$this->request->getVar('Fecha_Ingreso'), 'Precio'=>$this->request->getVar('Precio') ]; print_r($datos); $productos->insert($datos); echo "Datos guardados"; return $this->response->redirect(site_url('/mostrar')); } public function borrar($codigo=null){ $productos = new producto(); $datosProducto= $productos->where('codigo',$codigo)->first(); $productos->where('codigo',$codigo)->delete($codigo); return $this->response->redirect(site_url('/mostrar')); } public function editar($codigo=null){ $datos['cabecera']=view('templates/cabecera'); $datos['pie']=view('templates/piedepagina'); //print_r($codigo); $producto=new producto(); $datos['producto']=$producto->where('codigo',$codigo)->first(); return view('modificar',$datos); } public function actualizar(){ $producto= new producto(); $datos=[ 'Nombre'=>$this->request->getVar('Nombre'), 'Detalle'=>$this->request->getVar('Detalle'), 'Fecha_Ingreso'=>$this->request->getVar('Fecha_Ingreso'), 'Precio'=>$this->request->getVar('Precio') ]; $codigo=$this->request->getvar('codigo'); $validacion = $this->validate([ 'Nombre'=>'required|min_length[3]', 'Detalle'=>'required|min_length[3]', 'Fecha_Ingreso'=>'required', 'Precio'=>'required', ]); if(!$validacion){ $session= session(); $session->setFlashdata('mensaje', 'Todos los campos son requeridos'); return redirect()->back()->withInput(); } $producto->update($codigo,$datos); return $this->response->redirect(site_url('/ingresar')); } public function login() { if(isset($_POST['password'])){ $this->load->model('producto'); if($this->producto->inicio($_POST['usuario'],$_POST['password'])){ redirect('index'); }else { redirect('login'); } } $this->load-> view('login#bad-password'); } }
C++
UTF-8
3,354
2.546875
3
[ "MIT" ]
permissive
#include "debug.h" #include "core\concurrency\concurrency.h" #include "core\helper\timer.h" #include "core\string\string.h" #include "core\common\version.h" #include "core\container\staticArray.h" #include "core\platform\platform.h" #include <stdarg.h> #include <stdexcept> #include <fstream> #include <iostream> #include "log.h" namespace Cjing3D { Exception::Exception() : std::exception(), mMsg{} { } Exception::Exception(const char * format, ...) : Exception() { va_list args; va_start(args, format); vsnprintf_s(mMsg, std::size(mMsg), format, args); va_end(args); Logger::Error(mMsg); } Exception::Exception(const char * format, va_list args) : Exception() { vsnprintf_s(mMsg, std::size(mMsg), format, args); Logger::Error(mMsg); } Exception::~Exception() = default; const char* Exception::what() const noexcept { return mMsg; } namespace Debug { namespace { bool ShowDebugConsole = false; bool ShowMsgBox = false; bool AbortOnDie = false; bool DieOnError = false; bool debugWarningPause = true; bool enableBreakOnAssertion_ = true; Concurrency::Mutex mMutex; } void SetDieOnError(bool t) { DieOnError = t; } bool IsDieOnError() { return DieOnError; } void SetPopBoxOnDie(bool t) { ShowMsgBox = t; } void SetAbortOnDie(bool t) { AbortOnDie = t; } void SetDebugConsoleEnable(bool t) { ShowDebugConsole = t; } bool IsDebugConsoleEnable() { return ShowDebugConsole; } void CheckAssertion(bool asertion) { if (!asertion) std::abort(); } void CheckAssertion(bool assertion, const char* errorMsg) { if (!assertion) { Die(errorMsg); } } void ThrowIfFailed(bool result) { if (false == result) { throw Exception(); } } void ThrowIfFailed(bool result, const char * format, ...) { if (false == result) { va_list args; va_start(args, format); Exception exception(format, args); va_end(args); throw exception; } } void ThrowInvalidArgument(const char* format, ...) { char msg[128]; va_list args; va_start(args, format); vsnprintf_s(msg, std::size(msg), format, args); va_end(args); throw std::invalid_argument(msg); } MessageBoxReturn MessageBox(const char* title, const char* message, MessageBoxType type, MessageBoxIcon icon) { return MessageBoxReturn::OK; } bool AssertInternal(const char* Message, const char* File, int Line, ...) { #if defined(DEBUG) char context[4096]; va_list argList; va_start(argList, Line); #if COMPILER_MSVC vsprintf_s(context, sizeof(context), Message, argList); #else vsprintf(context, Message, argList); #endif va_end(argList); Logger::Info("\"%s\" in %s on line %u.\n\nDo you wish to break?", context, File, Line); return enableBreakOnAssertion_; #else return false; #endif } void DebugOuput(const char* msg) { Platform::DebugOutput(msg); } void Die(const char* format, ...) { Concurrency::ScopedMutex lock(mMutex); String128 buffer; va_list args; va_start(args, format); vsprintf_s(buffer.data(), buffer.size(), format, args); va_end(args); if (ShowMsgBox) { MessageBox("ERROR", buffer.c_str(), MessageBoxType::OK, MessageBoxIcon::ICON_ERROR); } if (AbortOnDie) { std::abort(); } } } }
Java
UTF-8
7,007
1.625
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/******************************************************************************* * Copyright 2019 Huawei Technologies Co.,Ltd. * * 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 com.huawei.openstack4j.api.bssintl.v1; import com.huawei.openstack4j.api.AbstractTest; import com.huawei.openstack4j.openstack.OSFactory; import com.huawei.openstack4j.openstack.bssintl.v1.domain.realnameAuth.*; import okhttp3.mockwebserver.RecordedRequest; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.testng.Assert.assertEquals; @Test(suiteName = "bssintl/v1/RealnameAuthService") public class RealnameAuthServiceTest extends AbstractTest { @Override protected Service service() { return Service.BSS_INTLV1; } private static final String realname_individual_realname_auth= "/bssintl/realnameAuth/individualRealnameAuth.json"; private static final String realname_enterprise_realname_auth= "/bssintl/realnameAuth/enterpriseRealnameAuth.json"; private static final String realname_enterprise_realname_change_auth= "/bssintl/realnameAuth/enterpriseRealnameAuth.json"; private static final String realname_auth_review_result= "/bssintl/realnameAuth/enterpriseRealnameAuth.json"; @Test public void individualRealnameAuthTest() throws Exception{ respondWith(realname_individual_realname_auth); String userDomainId = "userDomainId" ; OSFactory.enableHttpLoggingFilter(true); List<String> verifiedFileURL = new ArrayList<>(); verifiedFileURL.add("zhengmian.jpg"); verifiedFileURL.add("fanmian.jpg"); verifiedFileURL.add("chizheng2.jpg"); RealnameAuthReq req = RealnameAuthReq.builder() .customerId("xxxxxxxxxxxxxxxxxx") .identifyType(0) .verifiedType(0) .verifiedFileURL(verifiedFileURL) .name("xxx") .verifiedNumber("xxxxxxxxxxxxxxxxxx") .changeType(-1) .xaccountType("xxxxxxxxx_IDP") .build(); RealnameAuthRsp rsp = osv3().bssintlV1().realnameAuthService().individualRealnameAuth(userDomainId, req); RecordedRequest request = server.takeRequest(); assertEquals(request.getPath(),"/v1.0/userDomainId/partner/customer-mgr/realname-auth/individual"); assertEquals(request.getMethod(),"POST"); assertEquals(rsp.getIsReview().toString(),"1"); } @Test public void enterpriseRealnameAuthTest() throws Exception{ respondWith(realname_enterprise_realname_auth); String userDomainId = "userDomainId" ; OSFactory.enableHttpLoggingFilter(true); List<String> verifiedFileURL = new ArrayList<>(); verifiedFileURL.add("zhengmian.jpg"); verifiedFileURL.add("fanmian.jpg"); verifiedFileURL.add("chizheng2.jpg"); EnterprisePerson enterprisePerson = new EnterprisePerson(); enterprisePerson.setLegelName("xxxxxxx"); enterprisePerson.setLegelIdNumber("xxxxxxxxxxxxxxxxxx"); enterprisePerson.setCertifierRole("legalPerson"); EnterpriseRealnameAuthReq req = EnterpriseRealnameAuthReq.builder() .customerId("xxxxxxxxxxxxxxxxxxx") .identifyType(1) .certificateType(0) .verifiedFileURL(verifiedFileURL) .corpName("xxxxxxx") .verifiedNumber("xxxxxx") .regCountry("CN") .regAddress("nanjing") .xaccountType("xxxxxxxxxx_IDP") .enterprisePerson(enterprisePerson) .build(); RealnameAuthRsp rsp = osv3().bssintlV1().realnameAuthService().enterpriseRealnameAuth(userDomainId, req); RecordedRequest request = server.takeRequest(); assertEquals(request.getPath(),"/v1.0/userDomainId/partner/customer-mgr/realname-auth/enterprise"); assertEquals(request.getMethod(),"POST"); assertEquals(rsp.getIsReview().toString(),"1"); } @Test public void enterpriseRealnameAuthChangeTest() throws Exception{ respondWith(realname_enterprise_realname_change_auth); String userDomainId = "userDomainId" ; OSFactory.enableHttpLoggingFilter(true); List<String> verifiedFileURL = new ArrayList<>(); verifiedFileURL.add("zhengmian.jpg"); verifiedFileURL.add("fanmian.jpg"); verifiedFileURL.add("chizheng2.jpg"); EnterprisePerson enterprisePerson = new EnterprisePerson(); enterprisePerson.setLegelName("xxxxx"); enterprisePerson.setLegelIdNumber("xxxxxxxxxxxxxxxxxx"); enterprisePerson.setCertifierRole("legalPerson"); EnterpriseRealnameAuthChangeReq req = EnterpriseRealnameAuthChangeReq.builder() .customerId("xxxxxxxxxxxxxxxxxxx") .identifyType(1) .certificateType(0) .verifiedFileURL(verifiedFileURL) .corpName("xxxxxxxxxxxx") .verifiedNumber("xxxxxx") .regCountry("CN") .regAddress("nanjing") .changeType(1) .xaccountType("xxxxxxxxxxxx_IDP") .enterprisePerson(enterprisePerson) .build(); RealnameAuthRsp rsp = osv3().bssintlV1().realnameAuthService().enterpriseRealnameAuthChange(userDomainId, req); RecordedRequest request = server.takeRequest(); assertEquals(request.getPath(),"/v1.0/userDomainId/partner/customer-mgr/realname-auth/enterprise"); assertEquals(request.getMethod(),"PUT"); assertEquals(rsp.getIsReview().toString(),"1"); } @Test public void queryRealnameAuthReviewResultTest() throws Exception{ respondWith(realname_auth_review_result); String userDomainId = "userDomainId" ; OSFactory.enableHttpLoggingFilter(true); Map<String, String> filteringParams = new HashMap<>(); filteringParams.put("customerId", "xxxxxxxxxxxxxxxxxxxxx"); QueryRealnameAuthReviewResultRsp rsp = osv3().bssintlV1().realnameAuthService().queryRealnameAuthReviewResult(userDomainId, filteringParams); RecordedRequest request = server.takeRequest(); assertEquals(request.getPath(),"/v1.0/userDomainId/partner/customer-mgr/realname-auth/result?customerId=xxxxxxxxxxxxxxxxxxxxx"); assertEquals(request.getMethod(),"GET"); } }
Python
UTF-8
12,708
2.609375
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 import asyncio from time import sleep from pprint import pprint, pformat from statistics import median from gpiozero import DigitalOutputDevice import json import logging import sys import subprocess import datetime import websockets from w1thermsensor import W1ThermSensor import sispm logging.basicConfig(format='%(asctime)s %(levelname)s\t%(message)s', level=logging.WARNING) logger = logging.getLogger('hm-aquarium') logger.setLevel(logging.INFO) try: from config import * except ImportError as err: print("The configuration file config.py does not exist. Have a look at config.sample.py for reference. (" + str(err) + ")") exit(1) class Fan: """ A fan which cools the aquarium switched by a relay. :param int pin: The GPIO pin (in BCM numbering) that the relay is connected to. :param bool active_high: Whether the relay is active on high or low. Relays are usually active on low, therefore the default is False. """ def __init__(self, pin: int, active_high: bool = False): self._relay = DigitalOutputDevice(pin=pin, active_high=active_high) def on(self): self._relay.value = True def off(self): self._relay.value = False @property def is_on(self) -> bool: return self._relay.value @property def is_off(self): return not self.is_on class TopOffPump: """ A top-off pump which fills water into the aquarium, switched by a relay. :param int pin: The GPIO pin (in BCM numbering) that the relay is connected to. :param bool active_high: Whether the relay is active on high or low. Relays are usually active on low, therefore the default is False. """ def __init__(self, pin: int, active_high: bool = False): self._relay = DigitalOutputDevice(pin=pin, active_high=active_high) def on(self): self._relay.value = True def off(self): self._relay.value = False @property def is_on(self) -> bool: return self._relay.value @property def is_off(self): return not self.is_on class AutomaticAndManualSwitch: """ Wraps a switch for automatic and manual control. """ def __init__(self, switch): self._switch = switch self.is_on = switch.is_on self.is_auto_on = None # initially unknown def switch(self, on: bool): self.is_on = on self._switch.switch(on) def switch_auto(self, on: bool): if self.is_auto_on != on: self.is_auto_on = on self.switch(on) class RemotePowerSocket: """ Allows to control a remote power socket via a 433Mhz sender. """ def __init__(self, name: str, system_code: str, unit_code: str): self.name = name self.system_code = system_code self.unit_code = unit_code self.is_on = None # initially unknown def on(self): self.switch(True) def off(self): self.switch(False) def switch(self, on: bool): logger.info("Turning " + self.name + " " + ("on" if on else "off")) on_off_param = "1" if on else "0" # let's try it three times and also sleep afterwards a bit to not interfere with other calls # (I am probably overly cautious) self.send_signal(self.system_code, self.unit_code, on_off_param) sleep(0.6) self.send_signal(self.system_code, self.unit_code, on_off_param) sleep(0.5) self.send_signal(self.system_code, self.unit_code, on_off_param) sleep(0.5) self.is_on = on @staticmethod def send_signal(system_code: str, unit_code:str, on_off_param: str): # this is the send tool from https://github.com/xkonni/raspberry-remote # (compiled with 'make send') subprocess.call(["/home/pi/software/raspberry-remote/send", system_code, unit_code, on_off_param]) class SisPmPowerSocket: """ Allows to control a remote power socket via a SIS-PM Power Socket (Gembird EG-PM2 in my case). """ def __init__(self, name: str, device, socket_index): self.name = name self.device = device self.socket_index = socket_index self.is_on = None # initially unknown (we could actually also query the device) def on(self): self.switch(True) def off(self): self.switch(False) def switch(self, on: bool): logger.info("Turning " + self.name + " " + ("on" if on else "off")) if on: sispm.switchon(self.device, self.socket_index) else: sispm.switchoff(self.device, self.socket_index) self.is_on = on loop = asyncio.get_event_loop() class Communicator: def __init__(self, command_callback): self.command_callback = command_callback self.websocket = None @asyncio.coroutine def connect(self): delay_reconnect = False while True: try: logger.info("Connecting to: " + server_websocket) self.websocket = yield from websockets.connect(server_websocket) logger.info("WebSocket connected: " + server_websocket) delay_reconnect = False try: while True: command = yield from self.websocket.recv() yield from self.command_callback(json.loads(command)) finally: websocket_local = self.websocket self.websocket = None yield from websocket_local.close() except: logger.exception("Websocket connection error") # if this was already a reconnect, then let's sleep a bit if delay_reconnect: yield from asyncio.sleep(3) delay_reconnect = True @asyncio.coroutine def send(self, measurements): logger.info("Sending measurements: " + str(measurements)) if self.websocket is not None: try: yield from self.websocket.send(json.dumps(measurements)) except: logger.exception("Websocket connection error") else: logger.error("Cannot send measurements. WebSocket is not connected.") def float_to_bool(f): return f == 1 @asyncio.coroutine def main(): logger.info("Hm, Aquarium!") # time between two measurements (seconds) measure_interval = send_measurements_interval / aggregated_measurements_count logger.info("Measuring every %s seconds, aggregating %s values and sending them to the server every %s seconds.", measure_interval, aggregated_measurements_count, send_measurements_interval) values_count = 0 water_temperature_values = [] room_temperature_values = [] sensor = W1ThermSensor() fan = Fan(pin=14) config = { "fan_turn_on_temperature": 26.0, "fan_turn_off_temperature": 25.5 } current_measurements = { "temperature_water": None, "temperature_room": None } sispm_devices = sispm.connect() if len(sispm_devices) == 0: print('No device found') quit() sispm_device = sispm_devices[0] sunlight = AutomaticAndManualSwitch(SisPmPowerSocket("Sunlight", sispm_device, 1)) moonlight = AutomaticAndManualSwitch(SisPmPowerSocket("Moonlight", sispm_device, 2)) top_off_pump = TopOffPump(pin=15) top_off_pump.off() @asyncio.coroutine def top_off(duration): top_off_pump.on() yield from asyncio.sleep(duration) top_off_pump.off() @asyncio.coroutine def handle_command(commands): values = commands["values"]; logger.info("Received commands: " + pformat(values)) if "moonlight" in values: moonlight.switch(float_to_bool(values["moonlight"])) if "sunlight" in values: sunlight.switch(float_to_bool(values["sunlight"])) if "fan_turn_on_temperature" in values: config["fan_turn_on_temperature"] = values["fan_turn_on_temperature"] if "fan_turn_off_temperature" in values: config["fan_turn_off_temperature"] = values["fan_turn_off_temperature"] if "fan_turn_on_temperature" in values or "fan_turn_off_temperature" in values: control_fan() if "top_off_duration" in values: yield from top_off(values["top_off_duration"]) communicator = Communicator(handle_command) # asynchrounsly connect to websocket # All this is written in a way so that even if the server is down main functionality still works loop.create_task(communicator.connect()) def get_water_temperature(): try: return sensor.get_temperature() except KeyboardInterrupt: raise except: logger.exception("Error reading water temperature sensor") return None def control_fan(): current_water_temp = current_measurements["temperature_water"] if current_water_temp is None: if fan.is_on: logger.error("Water temperature unknown. Turning off fan.") fan.off() else: if fan.is_off: if current_water_temp >= config["fan_turn_on_temperature"]: logger.info("Turning fan on") fan.on() else: # fan is on if current_water_temp <= config["fan_turn_off_temperature"]: logger.info("Turning fan off") fan.off() return fan.is_on while True: start_time = loop.time() water_temp = get_water_temperature() logger.info("Water temperature: " + str(water_temp)) if water_temp is not None: water_temperature_values.append(water_temp) room_temp = get_room_temperature() if room_temp is not None: room_temperature_values.append(room_temp) sunlight.switch_auto(sunlight_on_condition()) moonlight.switch_auto(moonlight_on_condition()) values_count += 1 if values_count >= aggregated_measurements_count: measurements = {} median_water_temperature = None median_room_temperature = None # only store values if we have enough to calculate a proper median if len(water_temperature_values) == values_count: median_water_temperature = median(water_temperature_values) measurements["temperature_water"] = median_water_temperature current_measurements["temperature_water"] = median_water_temperature if len(room_temperature_values) == values_count: median_room_temperature = median(room_temperature_values) measurements["temperature_room"] = median_room_temperature current_measurements["temperature_room"] = median_room_temperature fan_is_on = control_fan() measurements["fan"] = 1 if fan_is_on else 0 measurements["sunlight"] = 1 if sunlight.is_on else 0 measurements["moonlight"] = 1 if moonlight.is_on else 0 measurements.update(config) state = { "controllerId": "aqua", "values": measurements } yield from communicator.send(state) water_temperature_values = [] room_temperature_values = [] values_count = 0 processing_time = loop.time() - start_time sleep_time = max(measure_interval - processing_time, 0) yield from asyncio.sleep(sleep_time) def get_room_temperature(): try: # this is the heatmiser-wifi json tool from https://github.com/thoukydides/heatmiser-wifi thermostat_data = subprocess.check_output(["/home/pi/software/heatmiser-wifi/bin/heatmiser_json.pl", "-h", "heat", "-p", "1234"]) thermostat_json = json.loads(thermostat_data.decode(sys.stdout.encoding)) # pprint(thermostat_json) return thermostat_json["heat"]["temperature"]["internal"] except KeyboardInterrupt: raise except: logger.exception("Communication error with thermostat") return None def sunlight_on_condition(): return datetime.time(9, 30) <= datetime.datetime.now().time() <= datetime.time(18, 30) def moonlight_on_condition(): return datetime.time(18, 30) <= datetime.datetime.now().time() <= datetime.time(20, 00) #return False if __name__ == "__main__": loop.create_task(main()) loop.run_forever()
JavaScript
UTF-8
626
2.578125
3
[]
no_license
plugSimpleBar('#trades-table-fixed'); let tds = document.querySelectorAll('td, th'); let t = new Date(); new FlexTable('.trades-table'); t = new Date() - t; let info = document.getElementById('box-info-run'); if (info) { info.innerHTML = `Время работы скрипта: ${t} мс <br> количество ячеек в таблице ${tds.length}`; } // To connect the SimpleBar function plugSimpleBar(selector) { let simpleBarEl = document.querySelector(selector); if (simpleBarEl) { try { new SimpleBar(simpleBarEl); } catch { simpleBarEl.style.ovetflowY = 'auto'; } } }
Markdown
UTF-8
6,153
3.390625
3
[]
no_license
# 撒母耳记上 - 第二十章 1 大卫从拉玛的拿约逃跑而来,在约拿单面前说:「我作了什么?我有什么愆?在你父亲面前我犯的什么罪,他竟寻索我性命呢?」 2 约拿单对他说:「你绝对不至于死:我父亲作的,无论大小事,没有不向我披露的;为什么这事我父亲偏要对我隐瞒呢?决无此理。」 3 大卫回答(传统:又起誓)说:「你父亲准知道你跟我好;故此他心里说:『不如不叫约拿单知道这事,恐怕他担忧。』虽然如此,我指着永活的永恒主,也指着你的性命来起誓:我与死之间,只有一步之隔罢了。」 4 约拿单对大卫说:「你心里切愿(传统:说)着什么?我总要为你作成。」 5 大卫对约拿单说:「看哪,明天是初一,我不(传统:本该)和王一同坐席吃饭;但是求你容我去藏在田野里,到晚上(传统:到第三天晚上)。 6 你父亲若察觉我不在席上,那么你就说:『大卫恳切求我许他跑回他本城伯利恒去;因为在那里他全家有献年祭的事。』 7 你父亲若这样说:『好!』仆人就可以平安无事了;他若大大发怒,你就知道他决定要害我了。 8 求你以忠爱待仆人;因为你曾使仆人在永恒主面前同你结约。我若有什么罪愆,你自己尽管把我杀死;为什么要这样待我带交你父亲呢?」 9 约拿单说:「你绝对不至于如此。我若准知道我父亲决定要加害于你,我还有不告诉你的吗?」 10 大卫对约拿单说:「你父亲若严厉地回答你,谁来告诉我呢?」 11 约拿单对大卫说:「来,我们出去到田野去吧!」二人就出去到田野去。 12 约拿单对大卫说:「愿永恒主以色列的上帝作证。明天大约这时候,就是第三天,我窥察我父亲的意思;若见他对你有好意,那时,我还有不打发人来找你,向你披露的吗? 13 我父亲若有意要加害于你,而我若不向你披露,使你平平安安地走开,愿永恒主这样惩罚我,并且加倍地惩罚。愿永恒主和你同在,如同从前和我父亲同在一样。 14 假使我还活着,那么就求你将永恒主那样的忠爱待我。假使我死了, 15 求你也永不向我家剪断忠爱。但假使永恒主从地上剪灭了大卫每一个仇敌, 16 而约拿单也和扫罗家(传统:大卫家)同被剪除了,那么愿永恒主从大卫家(传统:大卫仇敌)手里追讨这背约的罪。」 17 于是约拿单凭着爱大卫的心,又对(传统:叫)大卫起誓,因为他爱他如同自己的性命。 18 约拿单对他说:「明天是初一;你座位空着,人一定察觉到。 19 第三天尤甚;那么你要迅速下去,到你遇事时候藏身的地方,在那石头堆旁边等着。 20 我呢,要向石头堆旁边射三枝箭,如同射箭靶一样。 21 看吧,我要打发僮仆,说:『去把箭找来。』我若对僮仆说:『看哪,箭在你后头呢;把箭拿来。」那么,你就可以回来;我指着永活的永恒主来起誓,你一定平安无事。 22 但我若对童子说:『看哪,箭在你前头呢。』那么你就可以往前走;因为是永恒主打发你去的。 23 至于你我今天所说的话,看哪,有永恒主在你我之间作证,直到永远。」 24 于是大卫去藏在田间。到了初一日,王坐席要吃饭。 25 王照常坐在他的座位上,就是靠墙的座位;约拿单在对面(传统:侍立着);押尼珥坐在扫罗旁边;大卫的席位空着。 26 然而这一天扫罗没有说什么,因为他心里说:『这是偶然的事,或者他不洁净,因为还没有得洁净(传统:他不洁净)。 27 第二天,就是初二日,大卫的席位还是空着;扫罗就问他儿子约拿单说:「为什么耶西的儿子昨天今天都没有来吃饭呢?」 28 约拿单回答扫罗说:「大卫恳切地求我让他到伯利恒去; 29 他说:『求你容我去;因为我们家在城里有献祭的事;我哥哥吩咐我去。如今我若得到你顾爱,求你容我溜走去见我哥哥。』因此大卫就没有来赴王的筵席。」 30 扫罗便向约拿单发怒,说:「邪曲背逆的妇人生的!难道我不知道你取悦了耶西的儿子,而自取羞辱,以致你母亲的下体蒙羞辱吗? 31 耶西的儿子活在地上一天,你和你的王位就一天不能坚立。现在你要打发人将他拿来交给我;因为他是该死的。」 32 约拿单回答他父亲扫罗说:「他为什么必须死?他作了什么?」 33 扫罗把矛拿起(传统:掷),向着约拿单,要击杀他;约拿单就知道他父亲决定要杀死大卫。 34 于是约拿单气忿忿地从席间起来;在这初二日他没有吃饭;因为见他父亲侮辱了大卫,他就为大卫担忧。 35 次日早晨,约拿单按着他和大卫所约会的出去到田野间,有一个小僮仆跟着他。 36 约拿单对僮仆说:「你跑去,把我所射的箭找来。」僮仆跑去,约拿单就把箭射在僮仆前头。 37 僮仆到了约拿单所射的第一枝箭的地方,约拿单就在僮仆后面喊着说:「箭不是在你前头吗?」 38 约拿单又在僮仆后面喊着说:「加快赶紧吧,不要耽搁。」僮仆就把箭捡起来,回到他主人那里。 39 僮仆却不知道什么意思;只有约拿单和大卫知道。 40 约拿单将他的军器交给僮仆,对僮仆说:「你去吧,带进城去。」 41 僮仆一去,大卫就从石头堆南边起来,面伏于地,连拜三次;二人互相亲嘴,彼此哭泣;大卫哭的更悲惨。 42 约拿单对大卫说:「我们二人曾指着永恒主的名而起誓说:『愿永恒主在你我之间,也在你后裔跟我后裔之间作证,直到永远』,如今你安心去吧。」大卫就起身走;约拿单也进城去。
Python
UTF-8
2,988
2.578125
3
[]
no_license
from math import * class A2_node: def __init__(self, t, l, r): self.t = t self.l = l self.r = r def __str__(self): return "(A2_node: id=" + self.s + str(self.l) +", " + str(self.r) + ")" def __repr__(self): return str(self) def spread(self, s, arr): self.s = s self.l.spread(s+"0", arr) self.r.spread(s+"1", arr) def to_fragment(self): res = "" res += self.l.to_fragment() res += self.r.to_fragment() res += \ ''' wire[A_B_W-1:0] %so; A2_node A2_node_%s( .rst(rst), .clk(clk), .i1(%s0o), .i2(%s1o), .o(%so) );\n''' % (self.s, self.s, self.s, self.s, self.s) return res class in_node: def __init__(self): self.t = 0 def __str__(self): return "(in_node)" def __repr__(self): return str(self) def spread(self, s, arr): self.s = s self.i = arr.pop() def to_fragment(self): res = "" res += " wire[A_B_W-1:0] %so;\n" % (self.s) res += " assign %so = i%d;\n" % (self.s, self.i) return res class z_node: def __init__(self, c): self.t = 0 self.c = c def __str__(self): return "(z_node: id=" + self.s + str(self.c) + ")" def __repr__(self): return str(self) def spread(self, s, arr): self.s = s self.c.spread(s+"_0", arr) def to_fragment(self): res = "" res += self.c.to_fragment() res +=\ ''' wire[A_B_W-1:0] %s_o; z_node z_node_%s( .rst(rst), .clk(clk), .i(%s0o), .o(%so) );''' % (self.s, self.s, self.s, self.s) return res def f(n): if n > 0: return A2_node(n, f(n-1), f(n-1)) else: return in_node() def F(n): N = floor(log(n)/log(2)) lst = [] for i in range(0, N+1): if n&(1<<i): lst.append(f(i)) t = 0 while len(lst) > 1: len_lst = len(lst) _lst = [] ind = 0 while ind < len_lst: if t < lst[ind].t: _lst.append(lst[ind]) else: if ind+1 < len_lst and t >= lst[ind+1].t: _lst.append(A2_node(0, lst[ind], lst[ind+1])) ind += 1 else: _lst.append(z_node(lst[ind])) ind += 1 t += 1 lst = _lst return lst[0] from functools import reduce def gen(n): rt = F(n) # generate header print(\ '''parameter A_B_W = 32; module adder_pyramid_%d( input rst, input clk, %s output reg[A_B_W-1:0] o );\n''' % (n, reduce(lambda a,b: a+b, map(lambda x:" input[A_B_W-1:0] i%d,\n" % x , range(n))))) # generate content rt.spread("a", list(range(n))) print(rt.to_fragment()) # generate footer print("endmodule;") if __name__ == "__main__": import sys gen(int(sys.argv[1]))
C#
UTF-8
3,892
3.3125
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WindowsFormsApp6 { class SuDu { public SuDu() { } public static int[][] arrray1; public static int[][] getSuDu() { arrray1 = new int[9][]; arrray1[0] = new int[9] { 5, 6, 4, 8, 9, 7, 2, 3, 1 }; arrray1[1] = new int[9] { 9, 7, 8, 3, 1, 2, 6, 4, 5 }; arrray1[2] = new int[9] { 3, 1, 2, 6, 4, 5, 9, 7, 8 }; arrray1[3] = new int[9] { 6, 4, 5, 9, 7, 8, 3, 1, 2 }; arrray1[4] = new int[9] { 7, 8, 9, 1, 2, 3, 4, 5, 6 }; arrray1[5] = new int[9] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; arrray1[6] = new int[9] { 4, 5, 6, 7, 8, 9, 1, 2, 3 }; arrray1[7] = new int[9] { 8, 9, 7, 2, 3, 1, 5, 6, 4 }; arrray1[8] = new int[9] { 2, 3, 1, 5, 6, 4, 8, 9, 7 }; List<int> randomList = creatNineRondomArray(9); int[][] result = creatSudokuArray(arrray1, randomList); printArray(result); return result; } /// <summary> /// 打印二维数组,数独矩阵 /// </summary> /// <param name="a"></param> private static void printArray(int[][] a) { string charss = ""; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { charss += a[i][j] + " "; } } Write(charss); } /// <summary> /// 产生一个1-9的不重复长度为9的一维数组 /// </summary> /// <returns></returns> public static List<int> creatNineRondomArray(int length) { List<int> list = new List<int>(); Random random = new Random(); for (int i = 0; i < length; i++) { int randomNum = random.Next(9) + 1; while (true) { if (!list.Contains(randomNum)) { list.Add(randomNum); break; } randomNum = random.Next(9) + 1; } } return list; } /// <summary> /// 通过一维数组和原数组生成随机的数独矩阵遍历二维数组里的数据,在一维数组找到当前值的位置,并把一维数组 ///当前位置加一处位置的值赋到当前二维数组中。目的就是将一维数组为 ///依据,按照随机产生的顺序,将这个9个数据进行循环交换,生成一个随机的数独矩阵。 /// </summary> /// <param name="seedArray"></param> /// <param name="randomList"></param> private static int[][] creatSudokuArray(int[][] seedArray, List<int> randomList) { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { for (int k = 0; k < 9; k++) { if (seedArray[i][j] == randomList[k]) { seedArray[i][j] = randomList[(k + 1) % 9]; break; } } } } return seedArray; } public static void Write(String s) { FileStream fs = new FileStream("E:\\ak.txt", FileMode.Create); StreamWriter sw = new StreamWriter(fs); //开始写入 sw.Write(s); //清空缓冲区 sw.Flush(); //关闭流 sw.Close(); fs.Close(); } } }
Markdown
UTF-8
5,051
2.625
3
[]
no_license
[Return to the index page](/using-cloud/) | [Print this page](https://gitprint.com/alphagov/using-cloud/blob/master/help-for-end-users/Trello/Using-Trello-securely.md) *** ## Using Trello securely Government staff are responsible for checking the applications they use are secure. This guidance will help you use Trello to work securely with colleagues. [Trello](https://trello.com/) is a cloud application for managing projects and sharing tasks. ### Secure your account Secure your Trello account by using: * a password made up of 3 random words * [two-factor authentication](http://help.trello.com/article/993-enabling-two-factor-authentication-for-your-trello-account) * a secure HTTPS connection (ensure this by using a [modern browser](https://whatbrowser.org/) or a [Trello client app](https://trello.com/platforms) Contact your Trello administrator if you: * think someone may have accessed your account (you should also [change your password immediately](https://trello.com/forgot?user=) * lose a device that can access Trello (you should also [sign yourself out of other sessions](http://help.trello.com/article/766-logging-out-of-trello) ### Protect your data To protect your data when using Trello, make sure you: * don't use Trello to store [sensitive, personal](https://ico.org.uk/for-organisations/guide-to-data-protection/key-definitions/), or other high value data (like commercial or financial information) that could cause harm if lost or exposed * create [public and private boards](http://help.trello.com/article/789-changing-the-visibility-of-a-board-to-public-private-or-team) as appropriate * don’t connect Trello to [other services](https://trello.com/integrations) When using Trello, you should also be aware that content can be: * disclosed publicly under the [Freedom of Information Act](https://ico.org.uk/for-organisations/guide-to-freedom-of-information/what-is-the-foi-act/), as could any information held by government * retrieved by board owners or central administrators in paid Trello accounts * seen by Trello staff (card titles show up in Trello system logs, so choose them carefully) Trello [signed-up](https://www.privacyshield.gov/participant?id=a2zt0000000TOWpAAO) to the [EU-US Privacy Shield](https://www.privacyshield.gov/welcome) which requires them to follow European data protection requirements for European customers. [You own the data](https://trello.com/privacy) you put in Trello, and their technical security is similar to other popular public cloud services. ### Managing information You must record or summarise important work in a permanent record at regular intervals or at the end of a piece of work. Make sure you don’t lose content by: * creating a permanent record of shared information at regular intervals or at the end of a piece of work * using your document storage or email service to capture important discussions or decisions (name the data so it can be found later) * including a link to the Trello board in related documents * share boards that may be of historical interest with your information management team * delete old cards of no historical value to reduce the volume of data that needs to be managed - [archived first then delete](http://help.trello.com/customer/portal/articles/935742-archiving-and-deleting-cards) * [close boards](http://help.trello.com/article/801-deleting-a-board) when they are no longer needed You can export data from Trello by: * copying and pasting the text (while noting the date) * [print](http://help.trello.com/article/812-printing-in-trello) to a PDF * [export to CSV](http://help.trello.com/article/747-exporting-data-from-trello-1) if you have a Business Class (paid for) account * taking a screenshot * asking your administrator for [an export](http://help.trello.com/article/747-exporting-data-from-trello-1) ### Getting started Ensure your account looks official and similar to other government Trello accounts by: * setting your username to first_last_organisation (for example alex_black_moj) * use a recognisable profile photo * add your role to the Bio section Your Trello profile [is public](https://trello.com/nick_woodcraft_gds), but doesn’t show up in web searches or include activity, comments, cards, organisation, or other details, except on boards that are public. You can alert others to content you have shared on Trello using @mention in a card comment (for example @alex_black_moj). Take the [Trello tour](https://trello.com/tour) to find out more. ### Getting help For help using Trello, you can use their: * [getting started guide](https://trello.com/guide) * [help pages](http://help.trello.com/) Trello offer support through a: * [support page](https://trello.com/contact) * [status page](http://www.trellostatus.com/) You may also get help from your internal IT team if they have agreed to do it. *** [Return to the index page](/using-cloud/) | [Print this page](https://gitprint.com/alphagov/using-cloud/blob/master/help-for-end-users/Trello/Using-Trello-securely.md)
Markdown
UTF-8
704
2.625
3
[]
no_license
# Учебное API "Test API" ### Установка: 1. Скачать репозиторий 2. Перейти в директорию с проектом 3. `npm install` 4. `npm start` Cервер запустится по адресу http://localhost:7777 ### API документация: - GET /users - список пользователей - GET /users/:id - пользователь с заданным id (от 1001 до 1004) - POST /users - создание нового пользователя. Параметр: `name: string`. Передается в body. В случае успеха возвращает объект созданного пользователя.
Python
UTF-8
702
3.171875
3
[]
no_license
#!/usr/bin/python3 """ Preventing SQL Injection """ import sys import MySQLdb def Selector(): """ Selector with preventing SQL Injection """ username, password, database, state = sys.argv[1:] db = MySQLdb.connect(host="localhost", user=username, passwd=password, db=database) with db.cursor() as cursor: cursor.execute(""" SELECT * FROM states WHERE name LIKE %(state)s """, {'state': state} ) query_rows = cursor.fetchall() for row in query_rows: print(row) db.close() if __name__ == "__main__": Selector()
Python
UTF-8
1,554
2.71875
3
[]
no_license
from tkinter import * from tkinter import ttk from tkinter import messagebox from tkinter.ttk import Notebook from tkcalendar import DateEntry GUI = Tk() GUI.title('Expense and Income Recorder') GUI.geometry('700x500') GUI.state('zoomed') Tab = Notebook(GUI) F1 = Frame(Tab,width=500 , height=500) F2 = Frame(Tab,width=500 , height=500) Tab.add(F1, text='Expense') Tab.add(F2, text='Income') Tab.pack(fill=BOTH , expand=1) #Tab 1 Expense #---------------Row0-------------- LDate = ttk.Label(F1, text='Date',font=(None,18)) LDate.grid(row=0 , column=0 , padx=5 , pady=5,sticky='w') #use date picker EDate = DateEntry(F1, width=18 , background='blue',foregroud='white') EDate.grid(row=0 ,column=1 , padx=5 , pady=5,sticky='w') #---------------Row1-------------- LTitle = ttk.Label(F1, text='Title' , font=(None,18)) LTitle.grid(row=1 , column=0 , padx=5 , pady=5 ,sticky='w') Title = StringVar() ETitle = ttk.Entry(F1 , textvariable=Title,font=(None,18)) ETitle.grid(row=1 , column=1 , padx=5 , pady=5,sticky='w' ) #---------------Row2-------------- LExpense = ttk.Label(F1, text='Expense' , font=(None,18)) LExpense.grid(row=2 , column=0 , padx=5 , pady=5,sticky='w') Expense = StringVar() EExpense = ttk.Entry(F1 , textvariable=Expense,font=(None,18)) EExpense.grid(row=2 , column=1 , padx=5 , pady=5 ,sticky='w') #---------------Row3-------------- BF1Add = ttk.Button(F1 , text='Add') BF1Add.grid(row=3 , column=1 ,padx=5 , pady=5 ,sticky='w',ipadx=10,ipady=10) GUI.mainloop()
Java
UTF-8
620
2.984375
3
[]
no_license
import javax.swing.JOptionPane; public class euclidean { public static void main(String[] args){ int d=0; int i =1; int a= Integer.parseInt(JOptionPane.showInputDialog(" silahkan masukkan bilangan petama = ")); int b= Integer.parseInt(JOptionPane.showInputDialog(" silahkan Masukkan Bilangan Kedua = ")); int min = Math.min(a, b); while(i<=min){ if ((a%i==0)&(b%i==0)){ d=i; } i++; } JOptionPane.showMessageDialog(null, "FPB dari "+a+" & "+b+" = "+d); } }
PHP
UTF-8
3,906
2.703125
3
[ "MIT" ]
permissive
<?php /** * This file is part of the doctrine spatial extension. * * PHP 7.4 | 8.0 * * (c) Alexandre Tranchant <alexandre.tranchant@gmail.com> 2017 - 2021 * (c) Longitude One 2020 - 2021 * (c) 2015 Derek J. Lambert * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * */ namespace LongitudeOne\Spatial\ORM\Query\AST\Functions\PostgreSql; use Doctrine\ORM\Query\Lexer; use Doctrine\ORM\Query\Parser; use Doctrine\ORM\Query\QueryException; use LongitudeOne\Spatial\ORM\Query\AST\Functions\AbstractSpatialDQLFunction; use LongitudeOne\Spatial\ORM\Query\AST\Functions\ReturnsGeometryInterface; /** * ST_SnapToGrid DQL function. * * @see https://postgis.net/docs/ST_SnapToGrid.html * * Possible signatures with 2, 3, 5 or 6 parameters: * geometry ST_SnapToGrid(geometry geomA, float size); * geometry ST_SnapToGrid(geometry geomA, float sizeX, float sizeY); * geometry ST_SnapToGrid(geometry geomA, float originX, float originY, float sizeX, float sizeY); * geometry ST_SnapToGrid(geometry geomA, geometry pointOrigin, float sizeX, float sizeY, float sizeZ, float sizeM); * * @author Dragos Protung * @author Alexandre Tranchant <alexandre.tranchant@gmail.com> * @license https://alexandre-tranchant.mit-license.org */ class SpSnapToGrid extends AbstractSpatialDQLFunction implements ReturnsGeometryInterface { /** * Parse SQL. * * @param Parser $parser parser * * @throws QueryException Query exception */ public function parse(Parser $parser) { $lexer = $parser->getLexer(); $parser->match(Lexer::T_IDENTIFIER); $parser->match(Lexer::T_OPEN_PARENTHESIS); // 1st signature $this->addGeometryExpression($parser->ArithmeticFactor()); $parser->match(Lexer::T_COMMA); $this->addGeometryExpression($parser->ArithmeticFactor()); // 2nd signature if (Lexer::T_COMMA === $lexer->lookahead['type']) { $parser->match(Lexer::T_COMMA); $this->addGeometryExpression($parser->ArithmeticFactor()); } // 3rd signature if (Lexer::T_COMMA === $lexer->lookahead['type']) { $parser->match(Lexer::T_COMMA); $this->addGeometryExpression($parser->ArithmeticFactor()); $parser->match(Lexer::T_COMMA); $this->addGeometryExpression($parser->ArithmeticFactor()); // 4th signature if (Lexer::T_COMMA === $lexer->lookahead['type']) { // sizeM $parser->match(Lexer::T_COMMA); $this->addGeometryExpression($parser->ArithmeticFactor()); } } $parser->match(Lexer::T_CLOSE_PARENTHESIS); } /** * Function SQL name getter. * * @since 2.0 This function replace the protected property functionName. */ protected function getFunctionName(): string { return 'ST_SnapToGrid'; } /** * Maximum number of parameter for the spatial function. * * @since 2.0 This function replace the protected property maxGeomExpr. * * @return int the inherited methods shall NOT return null, but 0 when function has no parameter */ protected function getMaxParameter(): int { return 6; } /** * Minimum number of parameter for the spatial function. * * @since 2.0 This function replace the protected property minGeomExpr. * * @return int the inherited methods shall NOT return null, but 0 when function has no parameter */ protected function getMinParameter(): int { return 2; } /** * Get the platforms accepted. * * @since 2.0 This function replace the protected property platforms. * * @return string[] a non-empty array of accepted platforms */ protected function getPlatforms(): array { return ['postgresql']; } }
Java
UTF-8
5,723
2.234375
2
[]
no_license
package com.group1.booking.impl; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.engine.internal.SessionEventListenerManagerImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.stereotype.Repository; import com.group1.booking.configurations.HibernateContext; import com.group1.booking.dao.AccountDAO; import com.group1.booking.models.Account; import com.group1.booking.returnModels.Login; public class AccountDAOImpl implements AccountDAO { public String sqlQuery; HibernateContext hibernateContext; SessionFactory sessionFactory; public void setHibernateSession(HibernateContext hibernateSession) { hibernateContext = hibernateSession; sessionFactory = hibernateSession.GetSessionFactory(); } // TENGKH 20170905: Login Transaction public Login ToLogin(String Username, String Password) { // TODO Auto-generated method stub Session session = sessionFactory.openSession(); Transaction tx = null; Account account = null; Login login = new Login(); try { tx = session.beginTransaction(); sqlQuery = "FROM Account WHERE USERNAME = '" + Username + "' AND PASSWORD = '" + Password + "'"; List Account = session.createQuery(sqlQuery).list(); if (!Account.isEmpty()) { for (Iterator iterator = Account.iterator(); iterator.hasNext();) { account = (Account) iterator.next(); } if (Username.equals(account.getUsername()) && Password.equals(account.getPassword())) { login.setIsSucces("true"); login.setCustid(account.getCustID()); login.setAccountId(String.valueOf(account.getAcctID())); login.setRole(account.getRole()); login.setUsername(account.getUsername()); } } else { login.setIsSucces("false"); } tx.commit(); } catch (HibernateException e) { if (tx != null) tx.rollback(); e.printStackTrace(); } finally { session.close(); } return login; } // TENGKH 20170906: to search by username for Admin CRUD public Account SearchByAccountBy(String Username) { // TODO Auto-generated method stub Session session = sessionFactory.openSession(); Transaction tx = null; Account account = null; try { tx = session.beginTransaction(); sqlQuery = "FROM Account WHERE USERNAME = '" + Username + "'"; List Account = session.createQuery(sqlQuery).list(); for (Iterator iterator = Account.iterator(); iterator.hasNext();) { account = (Account) iterator.next(); } tx.commit(); } catch (HibernateException e) { if (tx != null) tx.rollback(); e.printStackTrace(); } finally { session.close(); } return account; } // TENGKH: to create an account // NOTE: before creating an account, customer must first be created in the // CUSTOMER_DETAILS table public String CreateAccount(Account account) { // TODO Auto-generated method stub String isSuccess; Session session = sessionFactory.openSession(); Transaction tx = null; Account Account = account; try { tx = session.beginTransaction(); session.save(Account); session.flush(); tx.commit(); isSuccess = "true"; } catch (HibernateException e) { if (tx != null) tx.rollback(); isSuccess = "false"; e.printStackTrace(); } finally { session.close(); } return isSuccess; } public String UpdateAccountBy(Account account) { // TODO Auto-generated method stub Session session = sessionFactory.openSession(); Transaction tx = null; String isUpdated = "false"; try { tx = session.beginTransaction(); sqlQuery = "FROM Account WHERE ACCT_ID = " + account.getAcctID(); List AccountInfo = session.createQuery(sqlQuery).list(); Account OldAccount = (Account) AccountInfo.iterator().next(); OldAccount.setAccount(account); tx = session.getTransaction(); tx.commit(); isUpdated = "true"; } catch (HibernateException e) { if (tx != null) { tx.rollback(); isUpdated = "false"; e.printStackTrace(); } } finally { session.close(); } return isUpdated; } public ArrayList<Account> searchAllAccounts() { // TODO Auto-generated method stub Session session = sessionFactory.getCurrentSession(); Transaction tx = null; ArrayList<Account> account = null; List query; try { tx = session.beginTransaction(); query = session.createQuery("FROM Account").list(); account = (ArrayList<Account>) query; tx.commit(); } catch (HibernateException e) { if (tx != null) tx.rollback(); e.printStackTrace(); } finally { session.close(); } return account; } public String DeleteAccountBy(String accountId) { // TODO Auto-generated method stub Session session = sessionFactory.openSession(); Transaction tx = null; Account account = null; String isDeleted = "false"; sqlQuery = "FROM Account WHERE ACCT_ID = " + accountId; try { tx = session.beginTransaction(); List Account = session.createQuery(sqlQuery).list(); for (Iterator iterator = Account.iterator(); iterator.hasNext();) { account = (Account) iterator.next(); } session.delete(account); tx = session.getTransaction(); tx.commit(); isDeleted = "true"; } catch (HibernateException e) { if (tx != null) isDeleted = "false"; tx.rollback(); e.printStackTrace(); } finally { session.close(); } return isDeleted; } }
JavaScript
UTF-8
8,335
2.609375
3
[]
no_license
/* The code to build the resume will go here. */ //here bio object var bio = { "name" : "Modhi Saleh", "role" : "front end Ninja", "contacts" : { "mobile": "0555555555", "email": "modhi_saleh_92@hotmail.com", "github": "ModhiSaleh", "location": "Saudi Arabia-Riyadh" }, "biopic": "images/devPic.png", "welcomeMessage": "Hello web developers lover!!", "skills": ["Systems analysis and design" , "Front-end development" , "LeaderShip" , "Administration" ,"Teamwork" , "English language -Good-"] }; bio.display = function() { var formattedName = HTMLheaderName.replace("%data%",bio.name); var formattedRole = HTMLheaderRole.replace("%data%",bio.role); $("#header").prepend(formattedName + formattedRole); var formattedMobile = HTMLmobile.replace("%data%",bio.contacts.mobile); var formattedEmail = HTMLemail.replace("%data%",bio.contacts.email); var formattedGithub = HTMLgithub.replace("%data%",bio.contacts.github); var formattedLocation = HTMLlocation.replace("%data%",bio.contacts.location); var formattedWelcomeMsg = HTMLwelcomeMsg.replace("%data%",bio.welcomeMessage); var formattedBioPic = HTMLbioPic.replace("%data%",bio.biopic); $("#header").append(formattedWelcomeMsg); $("#header").append(formattedBioPic); $("#topContacts, #footerContacts").append(formattedMobile); $("#topContacts, #footerContacts").append(formattedEmail); $("#topContacts, #footerContacts").append(formattedGithub); $("#topContacts, #footerContacts").append(formattedLocation); $("#header").append(HTMLskillsStart); for (var skillsCount = 0; skillsCount < bio.skills.length; skillsCount++) { var formattedSkills = HTMLskills.replace("%data%",bio.skills[skillsCount]); $("#skills").append(formattedSkills); } }; //here work object var work = { "jobs": [{ "employer": "ItCompany", "title": "frontend dev", "location": "Riyadh", "dates": "August2017", "description": "Utilize HTML, CSS and jQuery to develop effective user interfaces on the company website and mobile apps." }, { "employer": "Jazeel", "title": "Administration", "location": "Riyadh", "dates": "August2015 - now", "description": "responsible for supporting organisation in a variety of ways including communications, scheduling, data entry, secretarial services and much more." }] }; work.display = function() { for (var jobCount = 0; jobCount < work.jobs.length; jobCount++) { $("#workExperience").append(HTMLworkStart); var formattedEmployer = HTMLworkEmployer.replace("%data%",work.jobs[jobCount].employer); var formattedTitle = HTMLworkTitle.replace("%data%",work.jobs[jobCount].title); var formattedLocation = HTMLworkLocation.replace("%data%",work.jobs[jobCount].location); var formattedDates = HTMLworkDates.replace("%data%",work.jobs[jobCount].dates); var formattedDescription = HTMLworkDescription.replace("%data%",work.jobs[jobCount].description); $(".work-entry:last").append(formattedEmployer + formattedTitle); $(".work-entry:last").append(formattedLocation); $(".work-entry:last").append(formattedDates); $(".work-entry:last").append(formattedDescription); } }; //here education object var education = { "schools": [{ "name": "Imam Muhammad Ibn Saud Islamic University", "location": "Riyadh, Imam Muhammad Ibn Saud Islamic University", "degree": "Bachelor's degrees", "majors": ["Computer science department: Information management"], "dates": "2011-2015", "url": "https://imamu.edu.sa/en/Pages/default.aspx" }, { "name": "Al-ola secondry school", "location": "Riyadh, Hamzah Ibn Abdul Mutalib, Al Hazm", "degree": "secondry", "majors": ["scientific"], "dates": "2009-2011", "url": "https://twitter.com/alola_alarabia?lang=ar" }], "onlineCourses": [{ "title": "Front-End Web Developer Nanodegree", "school": "Udacity", "dates": "25-02-2017 Until 20-05-2017", "url": "https://www.udacity.com/course/front-end-web-developer-nanodegree--nd001" }, { "title": "Programming websites using html5 with CSS3 and JavaScript", "school": "rwaq.org", "dates": "2015", "url":"https://www.rwaq.org/" },] }; education.schools.display = function() { $("#education").append(HTMLschoolStart); $("#education").append(HTMLonlineClasses); for (var eduSchool = 0; eduSchool < education.schools.length; eduSchool++) { var formattedSchoolName = HTMLschoolName.replace("%data%",education.schools[eduSchool].name); var formattedSchoolDegree = HTMLschoolDegree.replace("%data%",education.schools[eduSchool].degree); var formattedSchoolDates = HTMLschoolDates.replace("%data%",education.schools[eduSchool].dates); var formattedSchoolLocation = HTMLschoolLocation.replace("%data%",education.schools[eduSchool].location); var formattedSchoolMajor = HTMLschoolMajor.replace("%data%",education.schools[eduSchool].majors); var formattedSchoolURL = HTMLschoolURL.replace("%data%",education.schools[eduSchool].url); $(".education-entry:last").append(formattedSchoolName + formattedSchoolDegree); $(".education-entry:last").append(formattedSchoolDates); $(".education-entry:last").append(formattedSchoolLocation); $(".education-entry:last").append(formattedSchoolMajor); $(".education-entry:last").append(formattedSchoolURL); } }; education.onlineCourses.display = function() { //$("#education").append(HTMLonlineClasses); $("#education").append(HTMLschoolStart); for (var eduCourses = 0; eduCourses < education.onlineCourses.length; eduCourses++) { var formattedOnlineTitle = HTMLonlineTitle.replace("%data%",education.onlineCourses[eduCourses].title); var formattedOnlineSchool = HTMLonlineSchool.replace("%data%",education.onlineCourses[eduCourses].school); var formattedOnlineDates = HTMLonlineDates.replace("%data%",education.onlineCourses[eduCourses].dates); var formattedOnlineURL = HTMLonlineURL.replace("%data%",education.onlineCourses[eduCourses].url); $(".education-entry:last").append(formattedOnlineTitle); $(".education-entry:last").append(formattedOnlineSchool); $(".education-entry:last").append(formattedOnlineDates); $(".education-entry:last").append(formattedOnlineURL); } }; education.display = function(){ education.schools.display(); education.onlineCourses.display(); }; //here projects object var projects = { "projects": [ {"title": "Online pharmacy", "dates": "Augast2015", "description": "Convert pharmacy to online service as web site", "images": ["images/onlinepharmacy.png"] }, {"title": "Hotel database", "dates": "May2014", "description": "create DB by sql to storge an information of hotels", "images": ["images/db.png"] }, {"title": "Animal trading card", "dates": "March2017", "description": "Convert the prototyp design to my trading card", "images": ["images/animalcard.png"] }] }; projects.display = function(){ for (var pro = 0; pro < projects.projects.length; pro++) { $("#projects").append(HTMLprojectStart); $(".project-entry:last").append(HTMLprojectTitle.replace("%data%", projects.projects[pro].title)); $(".project-entry:last").append(HTMLprojectDates.replace("%data%", projects.projects[pro].dates)); $(".project-entry:last").append(HTMLprojectDescription.replace("%data%", projects.projects[pro].description)); for (var image = 0; image < projects.projects[pro].images.length; image++){ // format projects.projects[pro].images[image] var formattedImage = HTMLprojectImage.replace("%data%", projects.projects[pro].images[image]); // display formatted image $(".project-entry:last").append(formattedImage); } } }; education.display(); work.display(); bio.display(); projects.display(); //$("#main").append(internationalizeButton); //map $("#mapDiv").append(googleMap);
Markdown
UTF-8
685
2.703125
3
[]
no_license
--- layout: singleidea authors: [aosdict] category: [vanilla] tags: [luck, code internals] --- Fuzz the turn on which Luck times out by hashing ubirthday together with (turns/300), and taking the result modulo 300. This means that Luck will still time out once every 300 turns, but the player can't predict the exact turn on which it happens, and figuring out the exact turn it happens in one iteration is unhelpful for any future iterations. If Luck is timing out once per 600 turns, still do the above, but do nothing on every other iteration. Determining which set of "every other" iterations to use could also be done by hashing ubirthday and seeing if the result is odd or even.
Java
UTF-8
1,212
3.390625
3
[]
no_license
package filter; import java.io.PrintWriter; import java.io.StringWriter; public class ResponseBufferWriter extends PrintWriter{ public ResponseBufferWriter() { super(new StringWriter(4096)); //이 super가 의미 하는 것은 PrintWriter.PrintWriter(Writer out)생성자이다. //new StringWriter는 StringWriter 객체를 생성하면서 기본 객체인 out의 데이터를 끌어온다. 애초에 out의 정보를 가져오는 코드를 작성할 필요가 없다. } //out은 기본객체로 JSP가 실행되는 시점에 이미 out기본 객체로 모든 데이터를 넘김. out엔 이미 데이터가 들어가 있는 상태 //가정1 Writer out = new StringWriter(4096); 조상 타입 Writer 자손객체 new StringWriter //가정2 new로 만든 StringWriter객체를 Writer타입으로 받기 떄문에 밑에서 다시 StringWriter로 캐스팅 하는게 아닐까? //사실은 Writer out 안에 StringWriter객체가 들어간다. out의 타입은 변하지 않은 상태로 자손 객체 보관. //out이 Writer이기 때문에 toString을 쓰는 시점에서 StringWriter로 형변환 해 준다. public String toString() { return ((StringWriter)super.out).toString(); } }
C#
UTF-8
951
2.9375
3
[]
no_license
private System.Windows.Forms.PictureBox[] imgVictim = new PictureBox[3]; //array for victim images public void victimsRun() { victimTimer.Enabled = true; //starts the timer string fileName = ""; PictureBox[] victim = new PictureBox[3]; for (int i = 0; i < imgVictim.Length; i++) // 0 - 2 { try { fileName = "victim" + i.ToString() + ".png"; if (System.IO.File.Exists(fileName)) { imgVictim[i] = new PictureBox(); imgVictim[i].Image = Image.FromFile("victim" + i.ToString() + ".png"); } else { // file does not exist or needs a path in front of it } } catch (NullReferenceException) { MessageBox.Show("NULL EXECEPTION!"); } } }
C#
UTF-8
1,533
2.75
3
[]
no_license
namespace JiuJitsuNotes.Migrations { using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; using JiuJitsuNotes.Models; using jiujitsuNotes.Models.NotesModel; internal sealed class Configuration : DbMigrationsConfiguration<JiuJitsuNotes.Models.ApplicationDbContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(JiuJitsuNotes.Models.ApplicationDbContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // context.Positions.AddOrUpdate( p => p.PositionName, new Positions { PositionID = 1, PositionName = "Standing" }, new Positions { PositionID = 2, PositionName = "Full Gaurd" }, new Positions { PositionID = 3, PositionName = "Mount", Techniques = new List<Techniques>() { new Techniques { TechniqueName="Test", DateAdded=DateTime.Now, CommonMistakes="TestMistake", EndPositionID=2, StartPositionID=3, KeyPoints="TestPoint", StartingCondition="Start cond", Steps="Test Steps", TechniqueType = TechniqueType.Escape } } }); } } }
Rust
UTF-8
407
2.921875
3
[]
no_license
use std::thread; use std::sync::{Arc, Mutex}; fn main() { let data = Arc::new(Mutex::new(0)); let mut handles = vec![]; for _ in 0..5 { let data = data.clone(); handles.push(thread::spawn(move || { let mut data = data.lock().unwrap(); *data += 1; })); } for h in handles { let _ = h.join(); } println!("{:?}", data); }
JavaScript
UTF-8
620
3.46875
3
[]
no_license
function f (array) { let result = []; for (let i = 0; i < array.length; i++) { let currentRow = array[i].split(" -> "); let currName = currentRow[0]; let currAge = Number(currentRow[1]); let currGrade = currentRow[2]; let currStudent = { name:currName, age:currAge, grade: currGrade }; result.push(currStudent); } for (let stu of result){ console.log(`Name: ${stu.name}\nAge: ${stu.age}\nGrade: ${stu.grade}`); } } f([ "Pesho -> 13 -> 6.00", "Ivan -> 12 -> 5.57", "Toni -> 13 -> 4.90" ])
Markdown
UTF-8
6,386
2.578125
3
[ "MIT" ]
permissive
--- title: "구글 스프레드시트로 주식 정보 불러오기 완전 쉬워요~ (w/ Yahoo Finance)" date: 2023-02-14 author: Astro36 category: javascript tags: [google_sheets, google_finance, google_apps_script, gas, javascript] thumbnail: /assets/posts/2023-02-14-google-sheet-stock-price/thumbnail.jpg --- [구글 스프레드시트](https://www.google.com/intl/ko/sheets/about/)는 마이크로소프트의 **엑셀**과 같은 서비스입니다. **구글 드라이브**와 연동되며, 엑셀의 **VBA** 같은 **구글 앱스 스크립트**(Google Apps Script) 기능이 있기 때문에 자동으로 웹에서 데이터를 가져오는 등의 기능을 구현할 수도 있습니다. 참고: [[VBA] 엑셀 매크로 시작 완벽 가이드](https://kukuta.tistory.com/397) **구글 앱스 스크립트**는 **자바스크립트**로 작성하기 때문에 VBA보다 진입장벽이 낮고, 다양한 **유틸 함수**와 **사용법 문서**를 제공하기 때문에 원하는 기능을 구현하기도 쉽습니다. 참고: [Apps Script - Google Developers](https://developers.google.com/apps-script/reference?hl=ko) ## Google Finance [Google Finance](https://www.google.com/finance/)는 구글의 **주식 정보** 시스템입니다. ![samsung](/assets/posts/2023-02-14-google-sheet-stock-price/samsung.png) > "삼성전자" 검색 `삼성전자`를 검색하게 되면 **삼성전자 주식**의 현재 **가격**과 **배당수익률** 등을 모아서 보여주게 됩니다. 검색창의 `KRX: 005930`은 삼성전자 주식의 식별자입니다. **KRX**는 KoRea eXchange의 약자로 **한국거래소**에서 거래되고 있다는 의미이며, `NAVER`는 `035420`, `카카오`는 `035720`과 같이 `005930`는 주식마다 부여되는 고유한 아이디로, **티커**(Ticker)라고 불립니다. ![apple](/assets/posts/2023-02-14-google-sheet-stock-price/apple.png) > "애플" 검색 미국의 "애플"을 검색하면 `NASDAQ: AAPL`으로 검색됩니다. 삼성전자와 동일하게 `:`을 기준으로 앞 쪽은 **거래소**를 의미하며 뒤는 주식의 **티커**를 의미합니다. `NASDAQ`은 미국의 **나스닥 증권거래소**를 의미하고, `AAPL`은 애플(APPLE)의 **티커**입니다. 미국은 숫자를 사용하는 한국과 다르게 **알파벳**을 이용해 **티커**를 만듭니다. **구글 스프레드시트**에는 **Google Finance**의 정보를 가져오는 **함수**를 제공합니다. `=GOOGLEFINANCE( ticker )`를 통해 현재 주식 가격을 불러올 수 있습니다. ![spreadsheets_aapl](/assets/posts/2023-02-14-google-sheet-stock-price/spreadsheets_aapl.png) ![spreadsheets_aapl_output](/assets/posts/2023-02-14-google-sheet-stock-price/spreadsheets_aapl_output.png) 참고: [GOOGLEFINANCE 도움말](https://support.google.com/docs/answer/3093281?hl=ko) ![spreadsheets_table](/assets/posts/2023-02-14-google-sheet-stock-price/spreadsheets_table.png) 이런식으로 **표** 형태로도 만들 수 있습니다. 한국, 미국 뿐만 아니라 다른 나라도 가능합니다. ![mbg](/assets/posts/2023-02-14-google-sheet-stock-price/mbg.png) 메르세데스-벤츠(님이 생각하는 독일 외제차 회사 맞음)의 모회사인 `다임러 AG`를 검색하면 `ETR: MBG`으로 검색됩니다. `ETR`은 유럽의 **도이체 뵈르제 XETRA 거래소**를 의미합니다. 유럽 주식은 **티커** 앞에 **거래소 명칭**까지 넣어야 제대로 값을 불러올 수 있습니다: `=GOOGLEFINANCE("ETR:MBG")` ![spreadsheets_table_mbg](/assets/posts/2023-02-14-google-sheet-stock-price/spreadsheets_table_mbg.png) 거래소 명칭은 [Finance 데이터 목록 및 면책 조항](https://www.google.com/googlefinance/disclaimer/)를 참고하면 됩니다. ## Yahoo Finance 하지만, `GOOGLEFINANCE`를 통해 모든 나라의 주식 정보를 불러올 수는 없습니다. 대표적으로 일본 주식은 `GOOGLEFINANCE` 함수를 지원하지 않습니다. ![nintendo](/assets/posts/2023-02-14-google-sheet-stock-price/nintendo.png) ![spreadsheets_table_nintendo](/assets/posts/2023-02-14-google-sheet-stock-price/spreadsheets_table_nintendo.png) 스프레드시트에 일본 **닌텐도** 주식 정보 불러오고자 한다면, Google Finance가 아닌 다른 출처를 이용해야 합니다. [Yahoo Finance](https://finance.yahoo.com/)는 대표적인 **주식 정보** 사이트로, Google Finance보다 더 다양한 주식 정보를 볼 수 있습니다. 다만, **스프레드시트**에는 Yahoo Finance 정보를 가져오는 함수가 없기 때문에, **Apps Script**를 이용해 직접 함수를 만들어야 합니다. ![apps_script_menu](/assets/posts/2023-02-14-google-sheet-stock-price/apps_script_menu.png) `확장 프로그램 > Apps Script`를 열어줍니다. 그리고 `YAHOOFINANCE` 함수를 만드는 아래 코드를 입력하고 파일을 저장합니다. ```js /** * Fetch stock price from Yahoo Finance * @param {string} ticker Stock ticker * @customfunction */ function YAHOOFINANCE(ticker) { const response = UrlFetchApp.fetch(`https://finance.yahoo.com/quote/${ticker}`); let data = response.getContentText(); data = data.substring(data.search('data-field="regularMarketPrice" data-trend="none" data-pricehint="2" value="') + 76); data = data.substring(0, data.search('" active=')); return parseInt(data); } ``` 참고: [UrlFetchApp - Apps Script - Google Developers](https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app?hl=ko) 다시 **스프레드시트**로 돌아와서 닌텐도 주식을 불러오도록 명령합니다: `=YAHOOFINANCE("7974.T")` ![spreadsheets_nintendo](/assets/posts/2023-02-14-google-sheet-stock-price/spreadsheets_nintendo.png) **Yahoo Finance**는 주식 정보를 검색하는 **방법**이 조금 다릅니다. `7974` 티커를 먼저 쓰고, `.` 뒤에 거래소 이름을 입력합니다. `T`는 **도쿄 증권거래소**라는 의미입니다. 정보 사이트마다 거래소를 가리키는 이름이 **다르기** 때문에 주의해서 작성해야 합니다. 만약, `YAHOOFINANCE`를 이용해 `다임러 AG` 주가를 불러오려면 아래와 같이 작성합니다. ![spreadsheets_mbg](/assets/posts/2023-02-14-google-sheet-stock-price/spreadsheets_mbg.png) `DE`는 독일 거래소 정보라는 뜻입니다.
Markdown
UTF-8
2,215
3.328125
3
[]
no_license
# Instructable Read.me Part 1 ## Ellen Morningstar (Previously Kearns, I know this is probably confusing) **Overview** - I found this week to be a little more difficult due to proper structure. I struggled with getting my code to look perfect. I also have these weird large gap breaks between my codes that appear on my preview. I'm not sure how to fix it. I did google it, but the answers online read to me like japanese. So that was complicated! **Improvements** - I know I can improve on proper structure and how it should look on screen in a text edit type formart. I think my biggest confusion was going through the class materials as they only reference structure when showing how to display something. For example: and the example of an Unordered List tag only shows the unordered list. It doesn't show how it would look inside of a full webpage. That's where I got caught up between the heading, the body and the end. # Instructable Read.me Part 2 ## Ellen Morningstar (Previously Kearns, I know this is probably confusing) **Overview** - This week was filled with an overload of information, I'm a little burnt out. It's good to know how submit forms work and the hierarchy of going to and from pages within the directory. It wasn't a terrible week, just way more information that I was able to process for one project. **Improvements** - I'm still trying to get use to the preview on atom vs the published website. I feel like my structure is better this time around, however working between forms in the directory can be confusing. I guess it's all part of the learning curve! # Instructable Read.me Part 3 ## Ellen Morningstar (Kearns) **Overview** - I'm glad we have finished up this project, I did enjoy learning everything, but my brain is officially exhausted. I enjoyed learning how to frame audio/video and maps this is very useful! However, Atom has proven to be quite challenging with it's on-again, off-again attitude if it wants you to see a successful preview! **Improvements** - Coding...in general, it makes me feel old. As much as it pains me to have to code, I really do wish I could be better at it. I seem to struggle and even though the struggle is all a means of learning, struggling can be frustrating!
Java
UTF-8
364
1.84375
2
[]
no_license
package com.zuoyueer.dao; import com.zuoyueer.domain.Departments; import org.apache.ibatis.annotations.Select; import java.util.List; /** * @author Zuoyueer * Date: 2019/12/1 * Time: 14:53 * @projectName Framework * @description: TODO */ public interface DepartmentsDao { @Select("select * from departments") public List<Departments> findAll(); }
Python
UTF-8
3,765
2.953125
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- """.""" import tkinter as tk from tkinter.messagebox import showerror, showinfo from style.material_design_colors import red class UpdateUser(tk.Toplevel): def __init__(self, master=None, data=None): super().__init__(master) self.master = master self.user_data = data self.title(string='Adicionar Usuário') icon_png = tk.PhotoImage(file='assets/icons/person.png') self.iconphoto(False, icon_png) width = round(number=self.winfo_screenwidth() / 2) height = round(number=self.winfo_screenheight() / 2) self.geometry(newGeometry=f'{width}x{height}') self.minsize(width=width, height=height) self.grab_set() self.user_id_value = tk.StringVar(value=self.user_data['text']) self.ent_name_value = tk.StringVar(value=self.user_data['values'][0]) self.ent_age_value = tk.StringVar(value=self.user_data['values'][1]) self.ent_gender_value = tk.StringVar(value=self.user_data['values'][2]) self.create_widgets() def create_widgets(self): main_frame = tk.Frame(master=self) main_frame.pack(expand=True, fill=tk.BOTH, padx=10, pady=10) lbl_name = tk.Label( master=main_frame, text='Nome (Campo obrigatório):', ) lbl_name.pack(anchor=tk.W) ent_name = tk.Entry( master=main_frame, bg=red['100'], textvariable=self.ent_name_value, validate='key', validatecommand=(self.master.vcmd_empty_field, '%P', '%W'), ) ent_name.pack(fill=tk.X, pady=(0, 15)) lbl_age = tk.Label( master=main_frame, text='Idade (Valores de 18 até 120):', ) lbl_age.pack(anchor=tk.W) ent_age = tk.Entry( master=main_frame, textvariable=self.ent_age_value, validate='key', validatecommand=(self.master.vcmd_age, '%P', '%W'), ) ent_age.pack(fill=tk.X, pady=(0, 15)) lbl_gender = tk.Label( master=main_frame, text='Genero (Campo obrigatório):', ) lbl_gender.pack(anchor=tk.W) ent_gender = tk.Entry( master=main_frame, bg=red['100'], textvariable=self.ent_gender_value, validate='key', validatecommand=(self.master.vcmd_empty_field, '%P', '%W'), ) ent_gender.pack(fill=tk.X, pady=(0, 15)) btn_add_record = tk.Button( master=main_frame, text='Atualizar registro', command=self.update_data, ) btn_add_record.pack() def update_data(self): user_id = self.user_id_value.get() name = self.ent_name_value.get() age = int(self.ent_age_value.get()) gender = self.ent_gender_value.get() if name and gender and self.master.check_age(age=age): data = (name, age, gender, user_id) self.master.database.change_row(data=data) showinfo( parent=self, title='Usuário atualizado com sucesso', message='Usuário atualizado com sucesso', ) self.destroy() else: showerror( parent=self, title='Formulário possui campos incorretos', message='Formulário possui campos incorretos!', ) if __name__ == '__main__': from MainWindow import MainWindow app = MainWindow() data = app.database.find_by_id(rowid=1) user = { 'text': data[0], 'values': [data[1], data[2], data[3]], } UpdateUser(master=app, data=user) app.mainloop()
Java
UTF-8
4,791
2.109375
2
[]
no_license
/** * This class is generated by jOOQ */ package am.ik.gitbucketoauth.jooq.tables.records; import am.ik.gitbucketoauth.jooq.tables.IssueLabel; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.Record4; import org.jooq.Row4; import org.jooq.impl.UpdatableRecordImpl; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.7.0" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class IssueLabelRecord extends UpdatableRecordImpl<IssueLabelRecord> implements Record4<String, String, Integer, Integer> { private static final long serialVersionUID = 107495057; /** * Setter for <code>PUBLIC.ISSUE_LABEL.USER_NAME</code>. */ public void setUserName(String value) { setValue(0, value); } /** * Getter for <code>PUBLIC.ISSUE_LABEL.USER_NAME</code>. */ public String getUserName() { return (String) getValue(0); } /** * Setter for <code>PUBLIC.ISSUE_LABEL.REPOSITORY_NAME</code>. */ public void setRepositoryName(String value) { setValue(1, value); } /** * Getter for <code>PUBLIC.ISSUE_LABEL.REPOSITORY_NAME</code>. */ public String getRepositoryName() { return (String) getValue(1); } /** * Setter for <code>PUBLIC.ISSUE_LABEL.ISSUE_ID</code>. */ public void setIssueId(Integer value) { setValue(2, value); } /** * Getter for <code>PUBLIC.ISSUE_LABEL.ISSUE_ID</code>. */ public Integer getIssueId() { return (Integer) getValue(2); } /** * Setter for <code>PUBLIC.ISSUE_LABEL.LABEL_ID</code>. */ public void setLabelId(Integer value) { setValue(3, value); } /** * Getter for <code>PUBLIC.ISSUE_LABEL.LABEL_ID</code>. */ public Integer getLabelId() { return (Integer) getValue(3); } // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Record4<String, String, Integer, Integer> key() { return (Record4) super.key(); } // ------------------------------------------------------------------------- // Record4 type implementation // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Row4<String, String, Integer, Integer> fieldsRow() { return (Row4) super.fieldsRow(); } /** * {@inheritDoc} */ @Override public Row4<String, String, Integer, Integer> valuesRow() { return (Row4) super.valuesRow(); } /** * {@inheritDoc} */ @Override public Field<String> field1() { return IssueLabel.ISSUE_LABEL.USER_NAME; } /** * {@inheritDoc} */ @Override public Field<String> field2() { return IssueLabel.ISSUE_LABEL.REPOSITORY_NAME; } /** * {@inheritDoc} */ @Override public Field<Integer> field3() { return IssueLabel.ISSUE_LABEL.ISSUE_ID; } /** * {@inheritDoc} */ @Override public Field<Integer> field4() { return IssueLabel.ISSUE_LABEL.LABEL_ID; } /** * {@inheritDoc} */ @Override public String value1() { return getUserName(); } /** * {@inheritDoc} */ @Override public String value2() { return getRepositoryName(); } /** * {@inheritDoc} */ @Override public Integer value3() { return getIssueId(); } /** * {@inheritDoc} */ @Override public Integer value4() { return getLabelId(); } /** * {@inheritDoc} */ @Override public IssueLabelRecord value1(String value) { setUserName(value); return this; } /** * {@inheritDoc} */ @Override public IssueLabelRecord value2(String value) { setRepositoryName(value); return this; } /** * {@inheritDoc} */ @Override public IssueLabelRecord value3(Integer value) { setIssueId(value); return this; } /** * {@inheritDoc} */ @Override public IssueLabelRecord value4(Integer value) { setLabelId(value); return this; } /** * {@inheritDoc} */ @Override public IssueLabelRecord values(String value1, String value2, Integer value3, Integer value4) { value1(value1); value2(value2); value3(value3); value4(value4); return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached IssueLabelRecord */ public IssueLabelRecord() { super(IssueLabel.ISSUE_LABEL); } /** * Create a detached, initialised IssueLabelRecord */ public IssueLabelRecord(String userName, String repositoryName, Integer issueId, Integer labelId) { super(IssueLabel.ISSUE_LABEL); setValue(0, userName); setValue(1, repositoryName); setValue(2, issueId); setValue(3, labelId); } }
Java
UTF-8
1,703
1.921875
2
[ "Apache-2.0" ]
permissive
package com.mysticcoders.mysticpaste.web.pages.history; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.navigation.paging.AjaxPagingNavigator; import org.apache.wicket.markup.html.navigation.paging.IPageable; import org.apache.wicket.markup.html.navigation.paging.IPagingLabelProvider; import org.apache.wicket.markup.html.navigation.paging.PagingNavigation; import org.apache.wicket.markup.html.navigation.paging.PagingNavigator; /** * Created with IntelliJ IDEA. * User: kinabalu * Date: 11/12/12 * Time: 11:15 AM * To change this template use File | Settings | File Templates. */ public class PastePagingNavigator extends AjaxPagingNavigator { public PastePagingNavigator(String id, IPageable pageable) { super(id, pageable); } public PastePagingNavigator(String id, IPageable pageable, IPagingLabelProvider labelProvider) { super(id, pageable, labelProvider); } private PastePagingNavigator dependentNavigator; public void setDependentNavigator(PastePagingNavigator dependentNavigator) { this.dependentNavigator = dependentNavigator; } protected void onAjaxEvent(AjaxRequestTarget target) { super.onAjaxEvent(target); if(dependentNavigator!=null) { target.add(dependentNavigator); } } /* protected PagingNavigation newNavigation(final String id, final IPageable pageable, final IPagingLabelProvider labelProvider) { PagingNavigation navigation = super.newNavigation(id, pageable, labelProvider); navigation.setRenderBodyOnly(true); navigation.setOutputMarkupPlaceholderTag(false); return navigation; } */ }
PHP
UTF-8
778
2.78125
3
[ "Apache-2.0" ]
permissive
<?php namespace Identimo\Storage; use Identimo\Storage\Iterator\UserIterator; use Identimo\User; use YPHP\Storage\EntityStorage; class UserStorage extends EntityStorage{ /** * Create a new iterator from an ArrayObject instance * * @return UserIterator */ public function getIterator() { return new UserIterator($this->storage); } /** * Get the value of storage * * @return User[] */ public function getStorage() { return $this->storage; } /** * Set the value of storage * * @param \Identimo\User[] $storage * * @return self */ public function setStorage($storage = []) { return parent::setStorage($storage); } }
C++
GB18030
637
3.3125
3
[]
no_license
/* ģ ɸ*/ /*dzŵ㷨*/ #include<iostream> #include<cmath> using namespace std; bool flag[10000000]; int main() { int n,m,a; cin>>n>>m;; flag[1]=1; flag[0]=1; for(int i=2;i<=sqrt(n)+1;i++)// { if(flag[i]==0)//flag[i]ûбκɸ { for(int j=i*2;j<=n;j+=i) flag[j]=1;//ÿiıΪ ɸiΪĺ } } for(int i=1;i<=m;i++) { cin>>a; if(flag[a]) cout<<"No"<<endl; else cout<<"Yes"<<endl; } }
Java
UTF-8
610
2.265625
2
[ "MIT" ]
permissive
package seedu.address.model; import javafx.collections.ObservableList; import seedu.address.model.module.Module; import seedu.address.model.module.student.Student; /** * Unmodifiable view of a TAB. */ public interface ReadOnlyTeachingAssistantBuddy { /** * Returns an unmodifiable view of the modules list. * This list will not contain any duplicate modules. */ ObservableList<Module> getModuleList(); /** * Returns an unmodifiable view of the students list. * This list will not contain any duplicate students. */ ObservableList<Student> getStudentList(); }
Markdown
UTF-8
1,133
2.9375
3
[]
no_license
# 자바 기초 ## CQRS > CQRS는 Command and Query Responsibility Segregation(명령과 조회의 책임 분리)을 나타낸다. 이름처럼 시스템에서 명령을 처리하는 책임과 조회를 처리하는 책임을 분리하는 것이 CQRS의 핵심이다. <img src = "https://blog.nebrass.fr/wp-content/uploads/cqrs-simple-diagram-886x1024.png" height="500"> - 명령(Command) : 시스템의 상태를 변경하는 작업 - ex) 주문 취소, 배송 완료 - 쿼리(Query) : 시스템의 상태를 반환하는 작업 - ex) 주문 목록 - 책임(Responsibility) : 구성 요소의 역할 - 구성 요소 : 클래스, 함수, 모듈/패키지, 웹서버/DB - 분리(Segregation) : 역할에 따라 구성 요소 나누기 ### 명령과 조회에 단일 모델을 사용한다면? 🔍 명령과 쿼리가 다루는 데이터가 다르기 때문에 이도 저도 아닌 잡탕이 된다. - 코드 역할/책임 모호 - 의미/가독성 등 나빠짐 - 유지보수성이 떨어짐 - 명령과 쿼리는 코드 변경 빈도/사용자가 다르기 때문 - 기능마다 요구하는 성능이 다르기 때문
C++
UTF-8
11,377
2.765625
3
[]
no_license
#ifndef _OBJECTS_HPP_ #define _OBJECTS_HPP_ #include "GlobalDefines.hpp" #include "VectorClass.hpp" #include "SortedLists.hpp" #include <vector> #include <iostream> namespace Objects { namespace Abstract { class Color; class SpatialData; }; namespace Concepts { namespace Core { class Camera; class Screen; class Ray; class Polygon; }; namespace Lights { class Light; class AmbientLight; class PointLight; }; }; namespace Physical { class Sphere; }; }; namespace Objects { namespace Abstract { class Color { public: //Get// virtual _BYTE GetRed() { return m_rgbData.red; } virtual _BYTE GetBlue() { return m_rgbData.blue; } virtual _BYTE GetGreen() { return m_rgbData.green; } virtual _BYTE GetAlpha() { return m_rgbData.alpha; } virtual RGBData GetRGBData() { return m_rgbData; } //Set// virtual void SetRed(_BYTE red) { m_rgbData.red = red; } virtual void SetBlue(_BYTE blue) { m_rgbData.blue = blue; } virtual void SetGreen(_BYTE green) { m_rgbData.green = green; } virtual void SetAlpha(_BYTE alpha) { m_rgbData.alpha = alpha; } protected: Color(RGBData rgbData) : m_rgbData(rgbData) { } private: RGBData m_rgbData; }; class SpatialData { public: //Get// virtual VectorClass::v3d::Point GetPoint(); virtual VectorClass::v3d::Vector GetVectorX(); virtual VectorClass::v3d::Vector GetVectorY(); virtual VectorClass::v3d::Vector GetVectorZ(); //Set// virtual void SetPoint(VectorClass::v3d::Point p); virtual void SetVectorX(VectorClass::v3d::Vector v); virtual void SetVectorY(VectorClass::v3d::Vector v); virtual void SetVectorZ(VectorClass::v3d::Vector v); protected: //Constructors// SpatialData(); SpatialData(SpatialData& spatialData); SpatialData( VectorClass::v3d::Point point, VectorClass::v3d::Vector xVector, VectorClass::v3d::Vector yVector, VectorClass::v3d::Vector zVector ); SpatialData(VectorClass::v3d::Point point); SpatialData( VectorClass::v3d::Vector xVector, VectorClass::v3d::Vector yVector, VectorClass::v3d::Vector zVector ); //Destructor// ~SpatialData(); //Get Functions// bool GotPoint() { return m_gotPoint; } bool GotVectors() { return m_gotVectors; } private: VectorClass::v3d::Point* m_point; VectorClass::v3d::Vector* m_xVector; VectorClass::v3d::Vector* m_yVector; VectorClass::v3d::Vector* m_zVector; bool m_gotPoint; bool m_gotVectors; }; }; namespace Concepts { ////////// // Core // ////////// namespace Core { // == Camera == // class Camera : public Objects::Abstract::SpatialData { public: Camera( VectorClass::v3d::Point point ) : m_distFromScreen(0.0), Objects::Abstract::SpatialData( point, VectorClass::v3d::Vector(), VectorClass::v3d::Vector(), VectorClass::v3d::Vector() ) { } void AttachScreen(Objects::Concepts::Core::Screen& screen); //Get// double GetScreenDistance() { return m_distFromScreen; } private: double m_distFromScreen; }; // == Screen == // class Screen : public Objects::Abstract::SpatialData { public: Screen( VectorClass::v3d::Point point, unsigned int width, unsigned int height ); //Get// unsigned int GetWidth() { return m_width; } unsigned int GetHeight() { return m_height; } RGBData GetPixel(unsigned int row, unsigned int col); //Set// void SetPixel(RGBData rgbData, unsigned int row, unsigned int col); private: unsigned int m_width, m_height; std::vector<std::vector<RGBData> > m_screenData; }; // == Ray == // class Ray { public: Ray(); Ray(VectorClass::v3d::Point pointFrom, VectorClass::v3d::Point pointTo); Ray(Ray& ray); ~Ray(); //Get// VectorClass::v3d::Vector GetVector(); VectorClass::v3d::Point GetPointFrom() { return *m_pointFrom; } VectorClass::v3d::Point GetPointTo() { return *m_pointTo; } //Move// void MovePointFrom(VectorClass::v3d::Vector v) { *m_pointFrom = *m_pointFrom + v; } void MovePointTo(VectorClass::v3d::Vector v) { *m_pointTo = *m_pointTo + v; } //Set// void SetPointFrom(VectorClass::v3d::Point p) { *m_pointFrom = p; } void SetPointTo(VectorClass::v3d::Point p) { *m_pointTo = p; } private: VectorClass::v3d::Point* m_pointFrom; VectorClass::v3d::Point* m_pointTo; VectorClass::v3d::Vector* m_vector; }; // == Polygon == // class Polygon : public Objects::Abstract::Color { public: Polygon(); Polygon(RGBData rgbData); Polygon(Polygon& poly); ~Polygon(); bool FoundIntersections() { return m_foundIntersections; } virtual bool Intersected(VectorClass::v3d::Point& p, VectorClass::v3d::Vector& v) = 0; virtual bool FindIntersections(VectorClass::v3d::Point& p, VectorClass::v3d::Vector& v) = 0; virtual VectorClass::v3d::Vector GetNormal(VectorClass::v3d::Point p) = 0; virtual VectorClass::v3d::Point GetFrontIntersect() { return *m_frontIntersect; } virtual VectorClass::v3d::Point GetBackIntersect() { return *m_backIntersect; } protected: void SetFrontIntersect(VectorClass::v3d::Point p) { *m_frontIntersect = p; } void SetBackIntersect(VectorClass::v3d::Point p) { *m_backIntersect = p; } void FoundIntersections(bool b) { m_foundIntersections = b; } private: bool m_foundIntersections; VectorClass::v3d::Point* m_frontIntersect; VectorClass::v3d::Point* m_backIntersect; Polygon* m_next; }; }; //////////// // Lights // //////////// namespace Lights { class Light : public Objects::Abstract::Color { public: Light(double luminosity, RGBData rgbData) : Objects::Abstract::Color(rgbData), m_luminosity(luminosity) { } virtual bool LightSurface( Objects::Concepts::Core::Polygon* polyArray, unsigned int numOfPolygons, unsigned int currentIndex, RGBData& rgbData ) = 0; double GetLuminosity() { return m_luminosity; } private: double m_luminosity; }; class AmbientLight : public Objects::Abstract::Color { public: AmbientLight(double luminosity, RGBData rgbData) : Objects::Abstract::Color(rgbData), m_luminosity(luminosity) { } double GetLuminosity() { return m_luminosity; } private: double m_luminosity; }; class PointLight : public Objects::Concepts::Lights::Light, public Objects::Abstract::SpatialData { public: PointLight ( VectorClass::v3d::Point point, double luminosity, RGBData rgbData ) : Objects::Concepts::Lights::Light(luminosity, rgbData), Objects::Abstract::SpatialData(point) { } bool LightSurface( Objects::Concepts::Core::Polygon* polyArray, unsigned int numOfPolygons, unsigned int currentIndex, RGBData& rgbData ); }; }; }; namespace Physical { class Sphere : public Objects::Concepts::Core::Polygon, public Objects::Abstract::SpatialData { public: Sphere( VectorClass::v3d::Point point, RGBData rgbData, double radius ) : m_radius(radius), Objects::Concepts::Core::Polygon(rgbData), Objects::Abstract::SpatialData(point) { } Sphere( VectorClass::v3d::Point point, VectorClass::v3d::Vector xVector, VectorClass::v3d::Vector yVector, VectorClass::v3d::Vector zVector, RGBData rgbData, double radius ) : m_radius(radius), Objects::Concepts::Core::Polygon(rgbData), Objects::Abstract::SpatialData( point, xVector, yVector, zVector ) { } bool Intersected(VectorClass::v3d::Point& p, VectorClass::v3d::Vector& v); bool FindIntersections(VectorClass::v3d::Point& p, VectorClass::v3d::Vector& v); double GetRadius() { return m_radius; } VectorClass::v3d::Vector GetNormal(VectorClass::v3d::Point p) { VectorClass::v3d::Vector v = p - GetPoint(); v = v.Normalize(); return v; } private: double m_radius; }; }; }; #endif
C#
UTF-8
3,893
3.5625
4
[]
no_license
using System; using System.Text; internal enum Direction { Horizontal, Vertical, SlashDiag, BackSlashDiag } class FindLongestSequenceOfEqualStringsInMatrix { static void Main() { string[,] matrix = new string[,] { {"ff", "mm", "mm", "vv"}, {"gg", "ff", "mm", "vv"}, {"gg", "mm", "ff", "vv"}, {"ff", "mm", "vv", "ff"}, {"gg", "vv", "ff", "vv"}, }; int bestRowSeq = 0; int bestColSeq = 0; int bestLen = 0; int currentLen = 0; Direction direction = Direction.BackSlashDiag; for (int row = 0; row < matrix.GetLength(0); row++) { for (int col = 0; col < matrix.GetLength(1); col++) { currentLen = CheckRow(matrix, row, col); if (currentLen > bestLen) { bestLen = currentLen; bestRowSeq = row; bestColSeq = col; direction = Direction.Horizontal; } currentLen = CheckCol(matrix, row, col); if (currentLen > bestLen) { bestLen = currentLen; bestRowSeq = row; bestColSeq = col; direction = Direction.Vertical; } currentLen = CheckBackSlashDiag(matrix, row, col); if (currentLen > bestLen) { bestLen = currentLen; bestRowSeq = row; bestColSeq = col; direction = Direction.BackSlashDiag; } currentLen = CheckSlashDiag(matrix, row, col); if (currentLen > bestLen) { bestLen = currentLen; bestRowSeq = row; bestColSeq = col; direction = Direction.SlashDiag; } } } int count = 0; StringBuilder sb = new StringBuilder(); while (count < bestLen) { sb.Append(matrix[bestRowSeq, bestColSeq] + " "); sb.Append(Environment.NewLine); count++; } Console.Write(sb.ToString()); } private static int CheckRow(string[,] matrix, int row, int startCol) { int seqLen = 0; for (int col = startCol; col < matrix.GetLength(1); col++) { if (matrix[row, col] != matrix[row, startCol]) { break; } seqLen++; } return seqLen; } private static int CheckCol(string[,] matrix, int startRow, int col) { int seqLen = 0; for (int row = startRow; row < matrix.GetLength(0); row++) { if (matrix[row, col] != matrix[startRow, col]) { break; } seqLen++; } return seqLen; } private static int CheckBackSlashDiag(string[,] matrix, int startRow, int startCol) { int seqLen = 0; for (int row = startRow, col = startCol; row < matrix.GetLength(0) && col < matrix.GetLength(1); row++, col++) { if (matrix[row, col] != matrix[startRow, startCol]) { break; } seqLen++; } return seqLen; } private static int CheckSlashDiag(string[,] matrix, int startRow, int startCol) { int seqLen = 0; for (int row = startRow, col = startCol; row < matrix.GetLength(0) && col >= 0; row++, col--) { if (matrix[row, col] != matrix[startRow, startCol]) { break; } seqLen++; } return seqLen; } }
JavaScript
UTF-8
2,572
2.703125
3
[]
no_license
/** * Namespace of notifications management **/ var SecurityNamespace = function(ko, koPurple) { var self = this; // // Private // var privateKey = ko.observable(null); //This needs to be an observable for the computed function IsLogged var baseServiceUrl = null; var AuthenticationCallbackFunction = null; /** Callback after try to login the user */ var UserLoginCallBack = function(data) { // Manage the bad authentication return if (data == "IncorrectAuthParameters") { AuthenticationCallbackFunction('Incorrect username/password'); return; } // Set the private key locally privateKey(data.PrivateKey); // Notify user AuthenticationCallbackFunction('Logged in'); } /** Get the hash on an object **/ var getObjectHash = function(data) { if (privateKey() == null) { alert('Please login'); return; } var clientQueryString = koPurple.serialize(data); var hash = CryptoJS.HmacSHA256(clientQueryString, privateKey()); return hash; } // // Public // self.User = { username:ko.observable('eka808'), password:ko.observable('foobar') }; /** Default constructor **/ self.init = function(serviceUrl, callbackFunction) { baseServiceUrl = serviceUrl; AuthenticationCallbackFunction = callbackFunction; }; /** Check if a user has got a private key **/ self.IsLogged = ko.computed(function() { return privateKey() != null; }); /** Make the login call **/ self.UserLogin = function() { var params = { action:'GETPRIVATEKEY', username:self.User.username, encryptedPassword:"" + CryptoJS.SHA1(self.User.password()) //Encrypt the password before passing }; koPurple.jsonCall( baseServiceUrl, ko.toJS(params), function(data) { UserLoginCallBack(data); }, 'GET' ); } /** Get the hash for the data sent **/ self.getEncryptedParamsForData = function(data) { data = ko.toJS(data); var params = { username : self.User.username(), hash : '' + getObjectHash(data), data : data }; return params; }; }; //Require Js stuff var dependencies = ['tools/knockout','purple/purpleFunctions']; define(dependencies, function (ko, koPurple) { return new SecurityNamespace(ko, koPurple); });
Java
UTF-8
1,753
2.015625
2
[]
no_license
package org.example; import org.openqa.selenium.By; public class RegisterPage extends Util { LoadProp loadProp = new LoadProp(); //LoadProp Object Created private By _firstName = By.xpath("//input[@id=\"FirstName\"]"); private By _lastName = By.xpath("//input[@id=\"LastName\"]"); private By _dateOfBirthday = By.xpath("//select[@name=\"DateOfBirthDay\"]"); private By _dateOfBirthMonth = By.xpath("//select[@name=\"DateOfBirthMonth\"]"); private By _dateOfBirthyear = By.xpath("//select[@name=\"DateOfBirthYear\"]"); private By _emailField = By.name("Email"); private By _CompanyName = By.id("Company"); private By _password = By.xpath("//input[@name=\"Password\"]"); private By _confirmpassword = By.xpath("//input[@name=\"ConfirmPassword\"]"); private By _registerSubmitButton = By.id("register-button"); public void userEnterRegistrationDetails() { TypeText(_firstName,loadProp.getProperty("firstName")); TypeText(_lastName,loadProp.getProperty("lastName")); selectFromDropDownByIndex(_dateOfBirthday,loadProp.getProperty("dateOfBirthday")); selectFromDropDownByVisibleText(_dateOfBirthMonth,loadProp.getProperty("dateOfBirthMonth")); selectFromDropDownByValue(_dateOfBirthyear,loadProp.getProperty("dateOfBirthyear")); TypeText(_emailField, loadProp.getProperty("emailField")+timestamp()+loadProp.getProperty("emailid")); TypeText(_CompanyName,loadProp.getProperty("CompanyName")); TypeText(_password,loadProp.getProperty("password")); TypeText(_confirmpassword,loadProp.getProperty("confirmpassword")); } public void userClickOnRegisterSubmitButton() { clickOnElement(_registerSubmitButton, 30); } }
Java
UTF-8
498
1.773438
2
[ "MIT" ]
permissive
package com.infinityraider.elementalinvocations.reference; import com.infinityraider.elementalinvocations.registry.ItemRegistry; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemStack; public class InventoryTabs { public static final CreativeTabs ELEMENTAL_INVOCATIONS = new CreativeTabs(Reference.MOD_ID) { @Override public ItemStack getTabIconItem() { return new ItemStack(ItemRegistry.getInstance().itemDebugger); } }; }
Java
GB18030
466
3.796875
4
[]
no_license
package com.baguaxingqiu.array; public class StrengthenForLoop { /** * @param args * ǿforѭҳǸ */ public static void main(String[] args) { int a[] = new int[5]; for (int i = 0; i < a.length; i++) { a[i] = (int)(Math.random()*100); System.out.println(a[i]); } int b = 0; for(int each:a){ if (b<each) { b = each; } } System.out.println("Ϊ"+b); } }
C++
UTF-8
4,014
2.546875
3
[]
no_license
#include <cstdio> using namespace std; const int maxn = 150010; struct edge { int to, nxt; }; edge G[maxn << 1]; int head[maxn], cnt; void dfs(const int&); int c[maxn], dfn[maxn]; void build(const int&, const int&, const int&); long long query(const int&, const int&, const int&); inline void access(int); int main() { freopen("color.in", "r", stdin); freopen("color.out", "w", stdout); int n; scanf("%d", &n); int u, v; for (int i = 1; i < n; i++) { scanf("%d %d", &u, &v), u++, v++; G[++cnt] = { v, head[u] }, head[u] = cnt; G[++cnt] = { u, head[v] }, head[v] = cnt; } dfs(1); build(1, n, 1); int q; scanf("%d", &q); char opt; while (q--) { opt = getchar(); while (opt != 'q' && opt != 'O') opt = getchar(); scanf("%d", &u), u++; switch (opt) { case 'q': printf("%.10Lf\n", (long double)query(dfn[u], dfn[u] + c[u] - 1, 1) / c[u]); break; case 'O': access(u); break; default: break; } } return 0; } int fa[maxn], dep[maxn]; int clock, rev[maxn]; void dfs(const int& u) { c[u] = 1; dfn[u] = ++clock, rev[clock] = u; for (int i = head[u]; i; i = G[i].nxt) if (G[i].to != fa[u]) { fa[G[i].to] = u; dep[G[i].to] = dep[u] + 1; dfs(G[i].to); c[u] += c[G[i].to]; } return; } struct node { int l, r; long long sum, tag; }; node t[maxn << 2]; inline int ls(const int& u) { return u << 1; } inline int rs(const int& u) { return u << 1 | 1; } inline void pushup(const int& u) { t[u].sum = t[ls(u)].sum + t[rs(u)].sum; return; } inline void pushdown(const int& u) { if (!t[u].tag) return; t[ls(u)].tag += t[u].tag, t[ls(u)].sum += t[u].tag * (t[ls(u)].r - t[ls(u)].l + 1); t[rs(u)].tag += t[u].tag, t[rs(u)].sum += t[u].tag * (t[rs(u)].r - t[rs(u)].l + 1); t[u].tag = 0; return; } void build(const int& l, const int& r, const int& u) { t[u].l = l, t[u].r = r; if (l == r) { t[u].sum = dep[rev[l]]; return; } int mid = (l + r) >> 1; build(l, mid, ls(u)); build(mid + 1, r, rs(u)); pushup(u); return; } void modify(const int& l, const int& r, const int& u, const int& val) { if (l <= t[u].l && t[u].r <= r) { t[u].tag += val, t[u].sum += val * (t[u].r - t[u].l + 1); return; } pushdown(u); if (l <= t[ls(u)].r) modify(l, r, ls(u), val); if (t[rs(u)].l <= r) modify(l, r, rs(u), val); pushup(u); return; } long long query(const int& l, const int& r, const int& u) { if (l <= t[u].l && t[u].r <= r) return t[u].sum; pushdown(u); long long ret = 0; if (l <= t[ls(u)].r) ret += query(l, r, ls(u)); if (t[rs(u)].l <= r) ret += query(l, r, rs(u)); return ret; } int son[maxn][2]; inline int get(const int& u) { return son[fa[u]][1] == u; } inline bool isroot(const int& u) { return son[fa[u]][0] != u && son[fa[u]][1] != u; } inline void rotate(const int& u) { int x = fa[u], y = fa[x], k = get(u); fa[u] = y; if (!isroot(x)) son[y][get(x)] = u; son[x][k] = son[u][k ^ 1]; fa[son[u][k ^ 1]] = x; son[u][k ^ 1] = x; fa[x] = u; return; } inline void splay(const int& u) { for (int f; f = fa[u], !isroot(u); rotate(u)) if (!isroot(f)) rotate(get(u) == get(f) ? f : u); return; } inline int find(int u) { while (son[u][0]) u = son[u][0]; return u; } inline void access(int u) { int v; for (int f = 0; u; u = fa[f = u]) { splay(u); if (son[u][1]) { v = find(son[u][1]); modify(dfn[v], dfn[v] + c[v] - 1, 1, 1); } son[u][1] = f; if (f) { v = find(f); modify(dfn[v], dfn[v] + c[v] - 1, 1, -1); } } return; }
Python
UTF-8
675
3.09375
3
[]
no_license
#!/usr/local/bin/ python3 # -*- coding:utf-8 -*- # __author__ = "zenmeder" class Solution(object): def minPathSum(self, grid): """ :type grid: List[List[int]] :rtype: int """ if not grid or not grid[0]: return 0 dp = [[0 for j in range(len(grid[i]))] for i in range(len(grid))] for i in range(len(grid)): for j in range(len(grid[i])): if i == 0 and j == 0: dp[i][j] = grid[0][0] elif i == 0 and j != 0: dp[i][j] = grid[i][j]+dp[i][j-1] elif i != 0 and j == 0: dp[i][j] = grid[i][j]+dp[i-1][j] else: dp[i][j] = grid[i][j]+min(dp[i][j-1], dp[i-1][j]) return dp[-1][-1] print(Solution().minPathSum([[1,2,3],[4,5,6]]))
PHP
UTF-8
853
2.703125
3
[]
no_license
<?php require_once 'manageDiscourseUser.php'; class LinkUser extends ManageDiscourseUser { public function __construct() { parent::__construct(); $this->addArg( 'muser', self::$mUserDescription, true ); $this->addArg( 'duser', self::$dUserDescription, true ); } public function execute() { $mUser = $this->getMuser($this->getArg(0)); $dUser = $this->getDuser($this->getArg(1)); $ret = $this->getDiscourseUserService()->linkUserById($mUser->getId(), $dUser); if($ret){ $output = "Link Succeed!"; }else{ $output = "Link Failed!"; } $this->output($output."\n"); } } $maintClass = LinkUser::class; require_once RUN_MAINTENANCE_IF_MAIN;
Go
UTF-8
191
3.015625
3
[]
no_license
package main import ("fmt" "time" ) func main(){ go hello() time.Sleep(1*time.Second) fmt.Println("Hi from main") } func hello(){ fmt.Println("Hello all good morning from goroutine") }
PHP
UTF-8
734
2.78125
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace EMS\CommonBundle\Exception; final class DateTimeCreationException extends \RuntimeException { private function __construct(string $message = '', int $code = 0, \Throwable $previous = null) { parent::__construct($message, $code, $previous); } /** * @param array<mixed> $data */ public static function fromArray(array $data, string $key, int $code = 0, \Throwable $previous = null): DateTimeCreationException { $input = $data[$key] ?? '[ERROR: key out of bound]'; $message = \sprintf('Could not create a DateTime from input value: "%s", with key: "%s"', $input, $key); return new static($message, $code, $previous); } }
Java
UTF-8
570
2.84375
3
[]
no_license
package com.javarush.task.task04.task0443; /* Как назвали, так назвали */ import java.io.*; import java.util.Scanner; public class Solution { public static void main(String[] args) throws Exception { String name = new Scanner(System.in).nextLine(); int y = new Scanner(System.in).nextInt(); int m = new Scanner(System.in).nextInt(); int d = new Scanner(System.in).nextInt(); System.out.println("Меня зовут "+name+"."); System.out.println("Я родился "+d+"."+m+"."+y); } }
Shell
UTF-8
750
4.0625
4
[ "Apache-2.0", "MIT", "BSD-3-Clause" ]
permissive
#! /bin/bash # docker-tag.sh - Create a new tag for a set of Agoric Docker images set -xe SRCTAG=$1 DSTTAG=$2 DOCKERUSER=${3-agoric} if [ -z "$DSTTAG" ]; then echo 1>&2 "Usage: $0 SRCTAG DSTTAG" exit 1 fi for img in agoric-sdk cosmic-swingset-setup cosmic-swingset-solo deployment; do SRC="ghcr.io/$DOCKERUSER/$img:$SRCTAG" DST="ghcr.io/$DOCKERUSER/$img:$DSTTAG" if manifest=$(docker manifest inspect "$SRC"); then AMENDS=$(jq -r .manifests[].digest <<<"$manifest" | sed -e "s!^!--amend $DOCKERUSER/$img@!") docker manifest create "$DST" $AMENDS docker manifest push "$DST" elif docker pull "$SRC"; then docker tag "$SRC" "$DST" docker push "$DST" else echo 1>&2 "Failed to find image $img:$SRCTAG" fi done
TypeScript
UTF-8
615
2.90625
3
[ "MIT" ]
permissive
import RequiredFieldValidator from '../validators/required'; import Validator from '../validator'; import {MessageHandler} from '../messages'; /** * Marks the field as required. * @param message [Optional] Overrides the default validation error message. * @returns {function(Object, string): void} A field validation decorator. */ export default function Required(message?: string|MessageHandler<RequiredFieldValidator>): PropertyDecorator { return function (targetClass: Object, property: string): void { Validator.addValidator(targetClass, property, new RequiredFieldValidator(message)); }; }
Java
UTF-8
19,093
1.835938
2
[]
no_license
package saioapi.app.web; //import java.io.File; //import java.io.FileInputStream; //import java.util.Arrays; // //import saioapi.base.Update; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.util.Log; import android.webkit.JavascriptInterface; import saioapi.service.utility.EppInfo; import saioapi.service.utility.EppInfo.ModuleInfo; import saioapi.service.utility.MsgBase; import saioapi.service.utility.PrinterInfo; import saioapi.service.utility.UpdateReq; import saioapi.service.utility.UpdateRsp; final public class UpdateJsInterface implements SaioJsInterface { final static public String ALIAS = "UpdateJsInterface"; final static private String TAG = ALIAS; final static private int EVENT_EPP_VERSION = 0; final static private int EVENT_PRINTER_VERSION = 1; final static private int EVENT_EPP_MODULE = 2; final static private int EVENT_EPP_KCV = 3; final static private int EVENT_UPDATE_REQUEST = 4; final static private int EVENT_UPDATE_RESPONSE = 5; final static private int EVENT_SERVICE_STATE = 6; private JsCallback mCallback = null; private Context mContext = null; private String mJsListener = null; private Handler mEventHandler = new Handler(); private int mEvent = 0; private int mEventResult = 0; // private Update mUpdate = null; // private String mCertPath = null; private Messenger mLocalMessenger = null; private Messenger mServiceMessenger = null; private SaioUtilityServiceConnection mConnection = null; private boolean mIsServiceBound = false; // private PrinterInfo.FirmwareVersion mPrinterFwVer = null; private EppInfo.FirmwareVersion mEppFwVer = null; private Bundle mEppModBundle = null; private int mEppModSize = 0; private String mEppKCV = null; private UpdateRsp mUpdRsp = null; public UpdateJsInterface(Context c) { mContext = c; // mUpdate = new Update(); mLocalMessenger = new Messenger(mMsgHandler); mConnection = new SaioUtilityServiceConnection(); } @JavascriptInterface public boolean bindService() { if(!mIsServiceBound) { boolean ret = mContext.bindService(new Intent(MsgBase.SERVICE_NAME), mConnection, Context.BIND_AUTO_CREATE); //Log.v(TAG, "bind SaioUtilityService: " + ret); return ret; } Log.v(TAG, "already bind SaioUtilityService"); return true; } @JavascriptInterface public void unbindService() { if(mIsServiceBound) { mContext.unbindService(mConnection); mServiceMessenger = null; mIsServiceBound = false; Log.v(TAG, "unbind SaioUtilityService"); } else { Log.v(TAG, "already unbind SaioUtilityService"); } } @JavascriptInterface public boolean requestServiceState() { if(null == mServiceMessenger || null == mLocalMessenger || !mIsServiceBound) return false; Message reqMsg = Message.obtain(null, MsgBase.MSG_SERVICE_STATE, 0, 0); reqMsg.replyTo = mLocalMessenger; try{ mServiceMessenger.send(reqMsg); }catch(RemoteException e){ e.printStackTrace(); return false; } mPrinterFwVer = null; return true; } @JavascriptInterface public boolean requestPrinterVersion() { if(null == mServiceMessenger || null == mLocalMessenger || !mIsServiceBound) return false; Message reqMsg = Message.obtain(null, MsgBase.MSG_PRINTER, EppInfo.ACTION_VERSION, 0); reqMsg.replyTo = mLocalMessenger; try{ mServiceMessenger.send(reqMsg); }catch(RemoteException e){ e.printStackTrace(); return false; } return true; } @JavascriptInterface public boolean requestEppVersion() { if(null == mServiceMessenger || null == mLocalMessenger || !mIsServiceBound) return false; Message reqMsg = Message.obtain(null, MsgBase.MSG_EPP, EppInfo.ACTION_VERSION, 0); reqMsg.replyTo = mLocalMessenger; try{ mServiceMessenger.send(reqMsg); }catch(RemoteException e){ e.printStackTrace(); return false; } mEppFwVer = null; return true; } @JavascriptInterface public boolean requestEppModuleInfo() { if(null == mServiceMessenger || null == mLocalMessenger || !mIsServiceBound) return false; Message reqMsg = Message.obtain(null, MsgBase.MSG_EPP, EppInfo.ACTION_MODULE, 0); reqMsg.replyTo = mLocalMessenger; try{ mServiceMessenger.send(reqMsg); }catch(RemoteException e){ e.printStackTrace(); return false; } mEppModBundle = null; mEppModSize = 0; return true; } @JavascriptInterface public boolean requestKCV(String key) { if(null == mServiceMessenger || null == mLocalMessenger || !mIsServiceBound) return false; Message reqMsg = Message.obtain(null, MsgBase.MSG_EPP, EppInfo.ACTION_KCV, 0); reqMsg.replyTo = mLocalMessenger; Bundle b = reqMsg.getData(); EppInfo.setKcv(b, key); reqMsg.setData(b); try{ mServiceMessenger.send(reqMsg); }catch(RemoteException e){ e.printStackTrace(); return false; } mEppKCV = null; return true; } @JavascriptInterface public boolean updateSystem(String dir, String file) { if(null == mServiceMessenger || null == mLocalMessenger || !mIsServiceBound) return false; Message reqMsg = Message.obtain(null, MsgBase.MSG_UPDATE, UpdateReq.ACTION_SYSTEM, 0); reqMsg.replyTo = mLocalMessenger; Bundle b = reqMsg.getData(); UpdateReq req = new UpdateReq(dir, file, false, false); UpdateReq.setBundleData(b, req); reqMsg.setData(b); try{ mServiceMessenger.send(reqMsg); }catch(RemoteException e){ e.printStackTrace(); return false; } mEppFwVer = null; return true; } @JavascriptInterface public boolean updatePrinter(String dir, String file, boolean skipIfSameVer, boolean delSrcIfOk) { if(null == mServiceMessenger || null == mLocalMessenger || !mIsServiceBound) return false; Message reqMsg = Message.obtain(null, MsgBase.MSG_UPDATE, UpdateReq.ACTION_PRINTER, 0); reqMsg.replyTo = mLocalMessenger; Bundle b = reqMsg.getData(); UpdateReq req = new UpdateReq(dir, file, skipIfSameVer, delSrcIfOk); UpdateReq.setBundleData(b, req); reqMsg.setData(b); try{ mServiceMessenger.send(reqMsg); }catch(RemoteException e){ e.printStackTrace(); return false; } mEppFwVer = null; return true; } @JavascriptInterface public boolean updateEpp(String dir, String file, boolean skipIfSameVer, boolean delSrcIfOk) { if(null == mServiceMessenger || null == mLocalMessenger || !mIsServiceBound) return false; Message reqMsg = Message.obtain(null, MsgBase.MSG_UPDATE, UpdateReq.ACTION_EPP, 0); reqMsg.replyTo = mLocalMessenger; Bundle b = reqMsg.getData(); UpdateReq req = new UpdateReq(dir, file, skipIfSameVer, delSrcIfOk); UpdateReq.setBundleData(b, req); reqMsg.setData(b); try{ mServiceMessenger.send(reqMsg); }catch(RemoteException e){ e.printStackTrace(); return false; } mEppFwVer = null; return true; } @JavascriptInterface public String getPrinterVersion() { if(null != mPrinterFwVer) return mPrinterFwVer.getVersion(); return null; } @JavascriptInterface public String getPrinterBuild() { if(null != mPrinterFwVer) return mPrinterFwVer.getBuild(); return null; } // @JavascriptInterface // public String getPrinterCID() // { // if(null != mPrinterFwVer) // return mPrinterFwVer.getCID(); // // return null; // } // // @JavascriptInterface // public String getPrinterModelName() // { // if(null != mPrinterFwVer) // return mPrinterFwVer.getModelName(); // // return null; // } // // @JavascriptInterface // public String getPrinterSN() // { // if(null != mPrinterFwVer) // return mPrinterFwVer.getSN(); // // return null; // } // @JavascriptInterface public String getEppVersion() { if(null != mEppFwVer) return mEppFwVer.getVersion(); return null; } @JavascriptInterface public String getEppBuild() { if(null != mEppFwVer) return mEppFwVer.getBuild(); return null; } @JavascriptInterface public String getEppCID() { if(null != mEppFwVer) return mEppFwVer.getCID(); return null; } @JavascriptInterface public String getEppModelName() { if(null != mEppFwVer) return mEppFwVer.getModelName(); return null; } @JavascriptInterface public String getEppSN() { if(null != mEppFwVer) return mEppFwVer.getSN(); return null; } @JavascriptInterface public String getKCV() { return mEppKCV; } @JavascriptInterface public int getEppModuleCount() { return mEppModSize; } @JavascriptInterface public String getEppModuleBuild(int index) { ModuleInfo mod = _getEppMod(index); if(null != mod) return mod.getModuleBuild(); return null; } @JavascriptInterface public String getEppModuleChecksum(int index) { ModuleInfo mod = _getEppMod(index); if(null != mod) return mod.getModuleChecksum(); return null; } @JavascriptInterface public String getEppModuleID(int index) { ModuleInfo mod = _getEppMod(index); if(null != mod) return mod.getModuleID(); return null; } @JavascriptInterface public String getEppModuleName(int index) { ModuleInfo mod = _getEppMod(index); if(null != mod) return mod.getModuleName(); return null; } @JavascriptInterface public String getEppModuleVersion(int index) { ModuleInfo mod = _getEppMod(index); if(null != mod) return mod.getModuleVersion(); return null; } @JavascriptInterface public int getUpdateFinishCount() { if(null != mUpdRsp) return mUpdRsp.getRunFinishCount(); return 0; } @JavascriptInterface public int getUpdateTotalCount() { if(null != mUpdRsp) return mUpdRsp.getTotalCount(); return 0; } @JavascriptInterface public int getUpdatePercentage() { if(null != mUpdRsp) return (int)mUpdRsp.getUpdatePercentage(); return 0; } @JavascriptInterface public String getUpdateMessage() { if(null != mUpdRsp) return mUpdRsp.getMessage(); return null; } // @JavascriptInterface // public int getPubkeyNum() // { // return mUpdate.getPubkeyNum(); // } // // @JavascriptInterface // public int getPubkeyCert(int idx, byte[] cert) // { // return mUpdate.getPubkeyCert(idx, cert); // } // // @JavascriptInterface // public int getCertificate(byte[] spk, byte[] cert) // { // //return mUpdate.certificate(cert, certInfo); // return 0; // } // // @JavascriptInterface // public int install(String srcDir) // { // // get the full certificate path // mCertPath = UPDATE_BASE + srcDir; // // // certificate it // File f = new File(mCertPath); // byte[] buffer = new byte[(int) f.length()]; // Log.d(TAG, "File '" + mCertPath + "' size: " + f.length()); // // try // { // int nIndex = 0; // int nRead = 0; // byte[] tmp = new byte[200]; // Arrays.fill(buffer, (byte) 0); // FileInputStream is = new FileInputStream(f); // // // while (-1 != (nRead = is.read(tmp))) // { // System.arraycopy(tmp, 0, buffer, nIndex, nRead); // nIndex = nIndex + nRead; // } // is.close(); // } // catch(Exception e) // { // Log.e(TAG, "Read file '" + mCertPath + "' error: " + e.getMessage()); // return -1; // } // // return mUpdate.install(UPDATE_BASE, buffer); // } // // //TODO: install app // @JavascriptInterface public void setOnEventListener(String listener) { mJsListener = listener; } @Override public void setCallback(JsCallback cb) { mCallback = cb; } private Handler mMsgHandler = new Handler() { @Override public void handleMessage(Message msg) { //Log.d(TAG, "MsgHandler.handleMessage(" + msg.what + ", " + msg.arg1 + ", " + msg.arg2 + ")"); if(MsgBase.MSG_EPP == msg.what) { if(EppInfo.ACTION_VERSION == msg.arg1) { mEppFwVer = EppInfo.getFirmwareVersion(msg.getData()); _sendEvent(EVENT_EPP_VERSION, msg.arg2); } else if(EppInfo.ACTION_MODULE == msg.arg1) { mEppModBundle = msg.getData(); for(mEppModSize = 0;;) { ModuleInfo mod = EppInfo.getModuleInfo(mEppModBundle, mEppModSize); if(null != mod) { mEppModSize++; if(mod.isLast()) break; } else break; } _sendEvent(EVENT_EPP_MODULE, msg.arg2); } else if(EppInfo.ACTION_KCV == msg.arg1) { mEppKCV = EppInfo.getKcv(msg.getData()); _sendEvent(EVENT_EPP_KCV, msg.arg2); } else { Log.w(TAG, "Unknown action (" + msg.arg1 + ") of message (" + msg.what + ")"); } } else if(MsgBase.MSG_PRINTER == msg.what) { if (PrinterInfo.ACTION_VERSION == msg.arg1) { mPrinterFwVer = PrinterInfo.getFirmwareVersion(msg.getData()); _sendEvent(EVENT_PRINTER_VERSION, msg.arg2); } else { Log.w(TAG, "Unknown action (" + msg.arg1 + ") of message (" + msg.what + ")"); } } else if(MsgBase.MSG_UPDATE_INFO == msg.what) { mUpdRsp = UpdateRsp.getBundleData(msg.getData()); _sendEvent(EVENT_UPDATE_RESPONSE, msg.arg2); } else if(MsgBase.MSG_UPDATE == msg.what) { _sendEvent(EVENT_UPDATE_REQUEST, msg.arg2); } else if(MsgBase.MSG_SERVICE_STATE == msg.what) { _sendEvent(EVENT_SERVICE_STATE, msg.arg2); } else { Log.w(TAG, "Unknown msg (" + msg.what + ")"); } } }; private class SaioUtilityServiceConnection implements ServiceConnection { @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.i(TAG, "Connected to SaioUtilityService"); mIsServiceBound = true; mServiceMessenger = new Messenger(service); } @Override public void onServiceDisconnected(ComponentName name) { Log.i(TAG, "Disonnected to SaioUtilityService"); mServiceMessenger = null; mIsServiceBound = false; } }; private void _sendEvent(int event, int result) { if(null != mCallback) { mEvent = event; mEventResult = result; mEventHandler.post(new Runnable() { @Override public void run() { //Log.d(TAG, "onEvent(javascript:" + mJsListener + "('" + mEvent + "', '" + mEventResult + "'))"); if(null != mJsListener) mCallback.onLoadUrl("javascript:" + mJsListener + "('" + mEvent + "', '" + mEventResult + "')"); } }); } } private ModuleInfo _getEppMod(int index) { if(null != mEppModBundle) { ModuleInfo mod = EppInfo.getModuleInfo(mEppModBundle, index); return mod; } return null; } }
C++
UTF-8
610
2.59375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define ll long long int int adjust(int k,int s){ if(k<=s){ return k; } else{ return adjust(k-s,s); } } int main() { int t; cin>>t; while(t--){ ll n,k; cin>>n>>k; ll *a=new ll[n]; for(int i=0;i<n;i++){ cin>>a[i]; } k=adjust(k,n); for(int i=1;i<n-1;i++){ swap(a[i],a[i+k]); for(int j=0;j<n;j++){ cout<<a[j]<<", "; } cout<<endl; } } return 0; }
Java
UTF-8
2,131
3.375
3
[]
no_license
import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** https://www.codewars.com/kata/55084d3898b323f0aa000546 */ public class CaesarTwo { private static final int NUM_OF_SPLITS = 5; public static List<String> encodeStr(String s, int shift) { String encrypted = encryptString(s, shift); return splitString(encrypted); } public static String decode(List<String> s) { String encrypted = s.stream().collect(Collectors.joining()); int shift = encrypted.charAt(0) - encrypted.charAt(1); return encryptString(encrypted, shift).substring(4); } private static String encryptString(String s, int shift) { int offset = shift >= 0 ? shift % 26 : 26 + (shift % 26); char firstChar = Character.toLowerCase(s.charAt(0)); char shifted = (char) (firstChar + offset); StringBuilder sb = new StringBuilder(s.length() + 2) .append(firstChar) .append(shifted); s.chars() .map(c -> shiftChar(c, offset)) .forEach(c -> sb.append((char) c)); return sb.toString(); } private static int shiftChar(int c, int shift) { if (!Character.isAlphabetic(c)) return c; if (Character.isLowerCase(c)) return ((c - 'a' + shift) % 26) + 'a'; return ((c - 'A' + shift) % 26) + 'A'; } private static List<String> splitString(String s) { int splitSize; int restSize = 0; if (0 == s.length() % NUM_OF_SPLITS) { splitSize = s.length() / NUM_OF_SPLITS; } else { splitSize = (s.length() + NUM_OF_SPLITS) / NUM_OF_SPLITS; restSize = s.length() % splitSize; } List<String> substrings = new ArrayList<>(); for (int i = 0; (i + 1) * splitSize <= s.length(); i++) { substrings.add(s.substring(i * splitSize, (i + 1) * splitSize)); } if (restSize > 0) { substrings.add(s.substring(s.length() - restSize, s.length())); } return substrings; } }
Markdown
UTF-8
973
2.6875
3
[ "MIT" ]
permissive
# Security Policy ## Supported Versions Currently, only one supported version of the software is supported at any one time. Should an update become available, you should be able to automatically roll up to the next version. Version 1.x.x will fail to update. | Version | Supported | Automatic updates | | ------- | ------------------ | ------------------ | | 2.0.2 | :white_check_mark: | :white_check_mark: | | 2.0.1 | :x: | :white_check_mark: | | 2.0.0 | :x: | :white_check_mark: | | 1.x.x | :x: | :x: | ## Reporting a Vulnerability Spotted a flaw in the code? Bypassed a security prompt? Perhaps you gained virtual cash when you weren't supposed to... Feel free to report the bug report in the "security" section of the repository, we will be happy to take a look into it! If your security report is declined, it won't be fixed. If it's accepted, we might need more information from you.
TypeScript
UTF-8
3,457
2.890625
3
[ "MIT" ]
permissive
import * as ns from '../../ns' import { commentStyle, formHeadingStyle, formGroupStyle } from '../../style' export type FieldParamsObject = { size?: number, // input element size attribute type?: string, // input element type attribute. Default: 'text' (not for Comment and Heading) element?: string, // element type to use (Comment and Heading only) style?: string, // style to use dt?: string, // xsd data type for the RDF Literal corresponding to the field value. Default: xsd:string uriPrefix?: string, // e.g. 'mailto:', will be removed when displaying value to user. Overrides dt. namedNode?: boolean, // if true, field value corresponds to the URI of an RDF NamedNode. Overrides dt and uriPrefix. pattern?: RegExp // for client-side input validation; field will go red if violated, green if ok } /** * The fieldParams object defines various constants * for use in various form fields. Depending on the * field in questions, different values may be read * from here. */ export const fieldParams: { [ fieldUri: string ]: FieldParamsObject } = { /** * Text field * * For possible date popups see e.g. http://www.dynamicdrive.com/dynamicindex7/jasoncalendar.htm * or use HTML5: http://www.w3.org/TR/2011/WD-html-markup-20110113/input.date.html */ [ns.ui('ColorField').uri]: { size: 9, type: 'color', style: 'height: 3em;', // around 1.5em is padding dt: 'color', pattern: /^\s*#[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]([0-9a-f][0-9a-f])?\s*$/ }, // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/color [ns.ui('DateField').uri]: { size: 20, type: 'date', dt: 'date', pattern: /^\s*[0-9][0-9][0-9][0-9](-[0-1]?[0-9]-[0-3]?[0-9])?Z?\s*$/ }, [ns.ui('DateTimeField').uri]: { size: 20, type: 'datetime-local', // See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime dt: 'dateTime', pattern: /^\s*[0-9][0-9][0-9][0-9](-[0-1]?[0-9]-[0-3]?[0-9])?(T[0-2][0-9]:[0-5][0-9](:[0-5][0-9])?)?Z?\s*$/ }, [ns.ui('TimeField').uri]: { size: 10, type: 'time', dt: 'time', pattern: /^\s*([0-2]?[0-9]:[0-5][0-9](:[0-5][0-9])?)\s*$/ }, [ns.ui('IntegerField').uri]: { size: 12, style: 'text-align: right;', dt: 'integer', pattern: /^\s*-?[0-9]+\s*$/ }, [ns.ui('DecimalField').uri]: { size: 12, style: 'text-align: right;', dt: 'decimal', pattern: /^\s*-?[0-9]*(\.[0-9]*)?\s*$/ }, [ns.ui('FloatField').uri]: { size: 12, style: 'text-align: right;', dt: 'float', pattern: /^\s*-?[0-9]*(\.[0-9]*)?((e|E)-?[0-9]*)?\s*$/ }, [ns.ui('SingleLineTextField').uri]: { }, [ns.ui('NamedNodeURIField').uri]: { namedNode: true }, [ns.ui('TextField').uri]: { }, [ns.ui('PhoneField').uri]: { size: 20, uriPrefix: 'tel:', pattern: /^\+?[\d-]+[\d]*$/ }, [ns.ui('EmailField').uri]: { size: 30, uriPrefix: 'mailto:', pattern: /^\s*.*@.*\..*\s*$/ // @@ Get the right regexp here }, [ns.ui('Group').uri]: { style: formGroupStyle }, /** * Non-interactive fields */ [ns.ui('Comment').uri]: { element: 'p', style: commentStyle // was `padding: 0.1em 1.5em; color: ${formHeadingColor}; white-space: pre-wrap;` }, [ns.ui('Heading').uri]: { element: 'h3', style: formHeadingStyle // was: `font-size: 110%; font-weight: bold; color: ${formHeadingColor}; padding: 0.2em;` } }
Markdown
UTF-8
4,184
3.015625
3
[ "MIT" ]
permissive
# wp media regenerate Regenerates thumbnails for one or more attachments. ### OPTIONS [&lt;attachment-id&gt;...] : One or more IDs of the attachments to regenerate. [\--image_size=&lt;image_size&gt;] : Name of the image size to regenerate. Only thumbnails of this image size will be regenerated, thumbnails of other image sizes will not. [\--skip-delete] : Skip deletion of the original thumbnails. If your thumbnails are linked from sources outside your control, it's likely best to leave them around. Defaults to false. [\--only-missing] : Only generate thumbnails for images missing image sizes. [\--yes] : Answer yes to the confirmation message. Confirmation only shows when no IDs passed as arguments. ### EXAMPLES # Regenerate thumbnails for given attachment IDs. $ wp media regenerate 123 124 125 Found 3 images to regenerate. 1/3 Regenerated thumbnails for "Vertical Image" (ID 123). 2/3 Regenerated thumbnails for "Horizontal Image" (ID 124). 3/3 Regenerated thumbnails for "Beautiful Picture" (ID 125). Success: Regenerated 3 of 3 images. # Regenerate all thumbnails, without confirmation. $ wp media regenerate --yes Found 3 images to regenerate. 1/3 Regenerated thumbnails for "Sydney Harbor Bridge" (ID 760). 2/3 Regenerated thumbnails for "Boardwalk" (ID 757). 3/3 Regenerated thumbnails for "Sunburst Over River" (ID 756). Success: Regenerated 3 of 3 images. # Re-generate all thumbnails that have IDs between 1000 and 2000. $ seq 1000 2000 | xargs wp media regenerate Found 4 images to regenerate. 1/4 Regenerated thumbnails for "Vertical Featured Image" (ID 1027). 2/4 Regenerated thumbnails for "Horizontal Featured Image" (ID 1022). 3/4 Regenerated thumbnails for "Unicorn Wallpaper" (ID 1045). 4/4 Regenerated thumbnails for "I Am Worth Loving Wallpaper" (ID 1023). Success: Regenerated 4 of 4 images. # Re-generate only the thumbnails of "large" image size for all images. $ wp media regenerate --image_size=large Do you really want to regenerate the "large" image size for all images? [y/n] y Found 3 images to regenerate. 1/3 Regenerated "large" thumbnail for "Sydney Harbor Bridge" (ID 760). 2/3 No "large" thumbnail regeneration needed for "Boardwalk" (ID 757). 3/3 Regenerated "large" thumbnail for "Sunburst Over River" (ID 756). Success: Regenerated 3 of 3 images. ### GLOBAL PARAMETERS These [global parameters](https://make.wordpress.org/cli/handbook/config/) have the same behavior across all commands and affect how WP-CLI interacts with WordPress. | **Argument** | **Description** | |:----------------|:-----------------------------| | `--path=<path>` | Path to the WordPress files. | | `--url=<url>` | Pretend request came from given URL. In multisite, this argument is how the target site is specified. | | `--ssh=[<scheme>:][<user>@]<host\|container>[:<port>][<path>]` | Perform operation against a remote server over SSH (or a container using scheme of "docker", "docker-compose", "docker-compose-run", "vagrant"). | | `--http=<http>` | Perform operation against a remote WordPress installation over HTTP. | | `--user=<id\|login\|email>` | Set the WordPress user. | | `--skip-plugins[=<plugins>]` | Skip loading all plugins, or a comma-separated list of plugins. Note: mu-plugins are still loaded. | | `--skip-themes[=<themes>]` | Skip loading all themes, or a comma-separated list of themes. | | `--skip-packages` | Skip loading all installed packages. | | `--require=<path>` | Load PHP file before running the command (may be used more than once). | | `--exec=<php-code>` | Execute PHP code before running the command (may be used more than once). | | `--context=<context>` | Load WordPress in a given context. | | `--[no-]color` | Whether to colorize the output. | | `--debug[=<group>]` | Show all PHP errors and add verbosity to WP-CLI output. Built-in groups include: bootstrap, commandfactory, and help. | | `--prompt[=<assoc>]` | Prompt the user to enter values for all command arguments, or a subset specified as comma-separated values. | | `--quiet` | Suppress informational messages. |
C++
UTF-8
1,829
2.671875
3
[]
no_license
#include "asc_hip_force/ASCHipForce.hpp" namespace atrias { namespace controller { ASCHipForce::ASCHipForce(AtriasController *parent, string name) : AtriasController(parent, name), flightPD(this, "flightPD"), stancePD(this, "stancePD"), toeDecode(this, "toeDecode") { // Initialize our gains to something safe. this->flightP = 150.0; this->flightD = 10.0; this->stanceP = 0.0; this->stanceD = 10.0; // Copy over defaults from the toe decode controller this->toeFilterGain = this->toeDecode.filter_gain; this->toeThreshold = this->toeDecode.threshold; } double ASCHipForce::operator()(const atrias_msgs::robot_state_leg &leg) { double output; // Set toe decoding gains. this->toeDecode.filter_gain = this->toeFilterGain; this->toeDecode.threshold = this->toeThreshold; // The "&& false" temporarily disables stance phase control, // so the atc_hip_force controller can safely be run. (And the // toe decoding controller debugged). if (this->toeDecode(leg.toeSwitch) && false) { // We're on the ground, run stance phase control // Set stance gains this->stancePD.P = this->stanceP; this->stancePD.D = this->stanceD; // Run the controller output = this->stancePD(1.5 * M_PI, leg.hip.legBodyAngle, 0.0, leg.hip.legBodyVelocity); } else { // We're in flight, hold the leg vertical // Set flight controller gains this->flightPD.P = this->flightP; this->flightPD.D = this->flightD; // Run the controller // This is not a true PD controller on knee strain, but instead it sums a proportional // strain control term with a term proportional to the hip velocity (to act as a damper). output = this->flightPD(0.0, leg.kneeForce, 0.0, leg.hip.legBodyVelocity); } return output; } bool ASCHipForce::onGround() { return this->toeDecode.onGround(); } } } // vim: noexpandtab
Java
UTF-8
1,428
2.328125
2
[ "Apache-2.0" ]
permissive
package com.bfsi.egalite.util; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import com.bfsi.egalite.view.R; /** * To access the customer details in general mode * @author Ashish * */ public class PopUpActivity extends Activity implements OnClickListener { Button ok_btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.custdetailsactivitypopup); ok_btn = (Button) findViewById(R.id.btn_custdetail_popup_ok); ok_btn.setOnClickListener(this); TextView mName = (TextView) findViewById(R.id.txv_custall_name); TextView mDob = (TextView) findViewById(R.id.txv_custall_dob); TextView mPhNo = (TextView) findViewById(R.id.txv_custall_phoneno); TextView mCustId = (TextView) findViewById(R.id.txv_custall_custid); Bundle bundle = getIntent().getExtras(); mName.setText(bundle.getString(Constants.NAME)); mDob.setText(bundle.getString(Constants.DOB)); mPhNo.setText(bundle.getString(Constants.PHONE)); mCustId.setText(bundle.getString(Constants.CUSTID)); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_custdetail_popup_ok: this.finish(); break; } } }
Rust
UTF-8
1,930
2.796875
3
[]
no_license
use serde::{Deserialize, Deserializer, Serialize}; use serde_json::Value; use crate::{ net_config::NetConfig, tournament::{ round_robin::RoundRobin, single_elim::SingleElim, }, local_remote::{IPlayer, RemotePlayer}, }; use std::net::TcpListener; #[derive(Debug)] pub struct TournConfig { players: u64, port: Value, ev_type: TType, } impl TournConfig { pub fn new(players: u64, port: Value, ev_type: TType) -> TournConfig { TournConfig { players, port, ev_type, } } pub fn to_tournament(&self) -> Box<dyn Tournament> { let listener = NetConfig::connect_listener(self.port.clone()).unwrap(); match self.ev_type { TType::SingleElim => Box::new(SingleElim::new(self.players as usize, listener)), TType::RndRbn => Box::new(RoundRobin::new(self.players as usize, listener)) } } } #[derive(Serialize, Debug)] pub enum TType { RndRbn, SingleElim, } impl<'de> Deserialize<'de> for TType { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let s = String::deserialize(deserializer)?.to_lowercase(); let state = match s.as_str() { "round robin" => TType::RndRbn, "single elimination" => TType::SingleElim, other => { panic!("Invalid tournament type {}", other); } }; Ok(state) } } pub trait Tournament { fn moderate_tournament(&mut self); fn report_winner(&mut self) -> Value; } pub fn accept_players(players: &mut Vec<Box<dyn IPlayer>>, count: &usize, listener: &TcpListener) { for _ in 0..*count { match listener.accept() { Ok((socket, _)) => players.push(Box::new(RemotePlayer::new(socket))), Err(_) => panic!("failed to connect") }; } }
Java
UTF-8
3,718
2.09375
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package com.songsy.iframe.core.persistence.provider.service; import com.songsy.iframe.core.persistence.datasource.annotation.BindingDataSources; import com.songsy.iframe.core.persistence.provider.Page; import com.songsy.iframe.core.persistence.provider.entity.BaseEntity; import com.songsy.iframe.core.persistence.provider.exception.UpdateException; import com.songsy.iframe.core.persistence.provider.exception.VersionException; import com.songsy.iframe.core.persistence.provider.mapper.BaseCurdMapper; import com.songsy.iframe.core.persistence.provider.utils.IDGeneratorUtils; import com.songsy.iframe.core.persistence.provider.utils.ReflectionUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import java.io.Serializable; import java.util.Date; import java.util.List; /** * 抽象service基类 * * @author songsy * @Date 2018/131 17:17 */ @Slf4j public abstract class AbstractBaseService<T extends BaseEntity, ID extends Serializable> { public abstract BaseCurdMapper<T, ID> getRepository(); @BindingDataSources("slave") public List<T> findAll() { return getRepository().findAll(); } public T findById(ID id) { return getRepository().findById(id); } public int updateNull(T entity) { return getRepository().updateNull(entity); } public int deleteOne(ID id) { return getRepository().deleteOne(id); } public int logicDeleteOne(ID id) { return getRepository().logicDeleteOne(id); } /** * 通用插入更新方法 * * @param entity * @return */ @Transactional public T saveSelective(T entity) { return saveSelective(entity, false); } @Transactional public T saveSelective(T entity, Boolean hasId) { if (hasId) { // 之前已经生成了id insertSelective(entity); } else if (!StringUtils.isEmpty(entity.getId())) { updateSelective(entity); // 插入数据库之后 实体类乐观锁字段自增 entity.setVersion(entity.getVersion() + 1); } else { Class idClass = ReflectionUtils.getPrimarykeyClassType(entity.getClass()); // 如果主键是字符类型,则采用32位随机字符作为主键 if (idClass.equals(String.class)) { entity.setId(IDGeneratorUtils.generateID()); } else { // 默认主键由数据库自动生成(主要是自动增长型) } insertSelective(entity); } return entity; } public List<T> findAutoByPage (Page<T> page) { return getRepository().findAutoByPage(page); } private void insertSelective(T entity) { entity.setCreatedDate(new Date()); entity.setLastModifiedDate(new Date()); entity.setVersion(new Long(1)); // 设置当前登录人 // if (null == entity.getCreatedBy()) { // entity.setCreatedBy(""); // } // if (null == entity.getLastModifiedBy()) { // entity.setLastModifiedBy(""); // } getRepository().insert(entity); } private void updateSelective(T entity) { if (entity.getVersion() == null) { throw new VersionException(); } entity.setLastModifiedDate(new Date()); // 设置当前登录人 // if (null == entity.getLastModifiedBy()) { // entity.setLastModifiedBy(""); // } Integer flag = getRepository().update(entity); if (flag == 0) { throw new UpdateException(); } } }
Go
UTF-8
547
3.4375
3
[]
no_license
package tictactoe import ( "math/rand" "time" ) func init() { rand.Seed(time.Now().Unix()) } type Player interface { Play(ttt *TicTacToe) Position Mark() Mark } type RandomPlayer struct { mark Mark } func NewRandomPlayer(mark Mark) *RandomPlayer { return &RandomPlayer{ mark: mark, } } func (r *RandomPlayer) Play(ttt *TicTacToe) (pos Position) { for { pos.X = rand.Intn(width) pos.Y = rand.Intn(height) if ttt.GetMark(&pos) == EMPTY { break } } return pos } func (r *RandomPlayer) Mark() Mark { return r.mark }
C#
UTF-8
3,432
2.71875
3
[ "BSD-2-Clause" ]
permissive
using System; using System.Xml.Linq; using NUnit.Framework; using twopointzero.Lml.Importers; namespace twopointzero.LmlTests.Importers.AppleITunesXmlImporterTests { [TestFixture] public class GetPrimitiveValue { private static void AssertPrimitiveEntryIsEqual(string input, object expected) { object actual = GetPrimitiveEntry(input); Assert.AreEqual(expected, actual); } private static void AssertPrimitiveEntryIsEqual(string input, double expected, double delta) { object actual = GetPrimitiveEntry(input); Assert.AreEqual(expected, (double)actual, delta); } private static void AssertPrimitiveEntryIsEqual<T>(string input, T[] expected) { var actual = (T[])GetPrimitiveEntry(input); CollectionAssert.AreEqual(expected, actual); } private static object GetPrimitiveEntry(string input) { var valueNode = XDocument.Parse(input).FirstNode; var value = AppleITunesXmlImporter.GetPrimitiveValue(valueNode); Assert.IsNotNull(value); return value; } [Test] public void GivenNullShouldThrowArgumentNullException() { Assert.Throws<ArgumentNullException>(() => AppleITunesXmlImporter.GetPrimitiveEntries(null)); } [Test] public void GivenOneDataValueShouldReturnIt() { const string input = @"<data>AQID</data>"; var expected = new byte[] { 1, 2, 3 }; AssertPrimitiveEntryIsEqual(input, expected); } [Test] public void GivenOneDateValueShouldReturnIt() { const string input = @"<date>2010-03-23T20:58:52Z</date>"; var expected = new DateTime(2010, 03, 23, 20, 58, 52, DateTimeKind.Utc); AssertPrimitiveEntryIsEqual(input, expected); } [Test] public void GivenOneFalseValueShouldReturnIt() { const string input = @"<false/>"; const bool expected = false; AssertPrimitiveEntryIsEqual(input, expected); } [Test] public void GivenOneIntegerValueShouldReturnIt() { const string input = @"<integer>1</integer>"; const int expected = 1; AssertPrimitiveEntryIsEqual(input, expected); } [Test] public void GivenOneRealScientificValueShouldReturnIt() { const string input = @"<real>-0.42E+2</real>"; const double expected = -42.0; AssertPrimitiveEntryIsEqual(input, expected, 0.001); } [Test] public void GivenOneRealValueShouldReturnIt() { const string input = @"<real>0.42</real>"; const double expected = 0.42; AssertPrimitiveEntryIsEqual(input, expected, 0.001); } [Test] public void GivenOneStringValueShouldReturnIt() { const string input = @"<string>1</string>"; const string expected = "1"; AssertPrimitiveEntryIsEqual(input, expected); } [Test] public void GivenOneTrueValueShouldReturnIt() { const string input = @"<true/>"; const bool expected = true; AssertPrimitiveEntryIsEqual(input, expected); } } }
Java
UTF-8
500
1.953125
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 com.leapfrog.DAO; import com.leapfrog.Entity.Client; import java.net.Socket; import java.util.List; /** * * @author BkoNod */ public interface ClientDAO { public void addUser(Client c); List<Client> getALL(); Client getBySocket(Socket socket); Client getByUserName(String username); }
Java
UTF-8
1,552
1.78125
2
[]
no_license
package com.ynpulse.hht_juai; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.LinearLayout; import com.ynpulse.hht_juai.dropdown_menu.DropDownMenu; public class BiosignatureActivity extends AppCompatActivity { private Toolbar mToolbar; private ActionBar mActionBar; private LinearLayout layout; private View listItem; private View listView; private DropDownMenu dropDownMenu; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_biosignature); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); setupToolbar(); } protected void initView(){ layout= (LinearLayout) getLayoutInflater().inflate(R.layout.pup_selectlist,null,false); } protected void setupToolbar(){ mToolbar= findViewById(R.id.toolbar); setSupportActionBar(mToolbar); mActionBar=getSupportActionBar(); mActionBar.setDisplayHomeAsUpEnabled(true); mActionBar.setDisplayShowHomeEnabled(true); mToolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); } }
Java
UTF-8
606
2.15625
2
[]
no_license
package br.com.lojamodel.daogeneric; import java.sql.PreparedStatement; import java.util.Calendar; import java.util.List; public class DAOGenericJDBC<T> implements DAO<T> { @Override public void inserir(T t) { } @Override public void remover(T t) { // TODO Auto-generated method stub } @Override public void atualizar(T t) { // TODO Auto-generated method stub } @Override public List<T> buscar(Integer id) { // TODO Auto-generated method stub return null; } @Override public List<T> buscarTodos(Integer id) { // TODO Auto-generated method stub return null; } }
C++
UTF-8
1,058
2.65625
3
[]
no_license
#pragma once #include <vector> #include <iostream> #include "entt.hpp" //all the component includes #include <Header/Camera.h> #include <Header/Mesh.h> #include <Header/Transform.h> #include <Header/Material.h> #include <Header/LightSource.h> class ECS { public: static void AttachRegistry(entt::registry* reg); static void Create(unsigned int EntId) { entt::entity id = m_Registry->create(); EntList.push_back(id); EntList[EntId] = id; } template<typename T, typename... Args> static void Add(Args&&... args, unsigned int EntityNum) { m_Registry->emplace<T>(EntList[EntityNum], std::forward<Args>(args)...); } template<typename T> static T& Get(unsigned int EntityNum) { return m_Registry->get<T>(EntList[EntityNum]); } static entt::registry* GetReg() { return m_Registry; } template<typename T> static bool Has(unsigned int EntityNum) { if (m_Registry->has<T>(EntList[EntityNum])) return true; else return false; } private: static entt::registry* m_Registry; static std::vector<entt::entity> EntList; };
Java
UTF-8
465
1.976563
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 javaapplication23; import java.util.EventObject; /** * * @author Vladimir */ public class ReservoirEvent extends EventObject{ String msg; public ReservoirEvent(Object source, String msg) { super(source); this.msg=msg; } }
Java
UTF-8
9,787
2.375
2
[]
no_license
package com.kwon.notice.model.dao; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Properties; import static com.kwon.common.JDBCTemplate.*; import com.kwon.member.model.dao.MemberDao; import com.kwon.notice.model.vo.Notice; public class NoticeDao { private Properties prop; public NoticeDao() { prop = new Properties(); String filePath = NoticeDao.class.getResource("/config/notice-query.properties").getPath(); try { prop.load(new FileReader(filePath)); }catch(FileNotFoundException e) { e.printStackTrace(); }catch(IOException e) { e.printStackTrace(); } } /** * 페이징처리용 전체 글 개수 가져오기 * @param conn * @return */ public int getListCount(Connection conn) { int listCount = 0; Statement stmt = null; ResultSet rset = null; String sql = prop.getProperty("listCount"); try { stmt = conn.createStatement(); rset = stmt.executeQuery(sql); if(rset.next()) { listCount = rset.getInt(1); System.out.println("[Dao] listCount : " + listCount); } } catch(SQLException e) { e.printStackTrace(); } finally { close(rset); close(stmt); } return listCount; } /** * Notice 리스트 가져오기 * @param conn * @param limit * @param currentPage * @return */ public ArrayList<Notice> noticeList(Connection conn, int currentPage, int limit) { ArrayList<Notice> list = null; PreparedStatement pstmt = null; ResultSet rset = null; String sql = prop.getProperty("selectList"); try { pstmt = conn.prepareStatement(sql); int startRow = (currentPage-1)*limit +1; int endRow = startRow + limit -1; pstmt.setInt(1, endRow); pstmt.setInt(2, startRow); rset = pstmt.executeQuery(); list = new ArrayList<>(); while(rset.next()) { Notice n = new Notice(); n.setNno(rset.getInt("N_NO")); n.setnTitle(rset.getString("N_TITLE")); n.setnUserName(rset.getString("N_USERNAME")); n.setnUserId(rset.getString("N_USERID")); n.setnContent(rset.getString("N_CONTENT")); n.setnCount(rset.getInt("N_COUNT")); n.setnDate(rset.getDate("N_DATE")); n.setnStatus(rset.getString("N_STATUS")); list.add(n); } } catch(SQLException e) { e.printStackTrace(); } finally { close(rset); close(pstmt); } return list; } /** * 게시글 1개 불러오기 * 2020.02.28 Kwon * @param conn * @param nno * @return */ public Notice noticeSelectOne(Connection conn, int nno) { Notice n = null; PreparedStatement pstmt = null; ResultSet rset = null; String sql = prop.getProperty("selectOne"); try { pstmt = conn.prepareStatement(sql); pstmt.setInt(1, nno); rset = pstmt.executeQuery(); if(rset.next()) { n = new Notice(); n.setNno(rset.getInt("N_NO")); n.setnTitle(rset.getString("N_TITLE")); n.setnUserName(rset.getString("N_USERNAME")); n.setnUserId(rset.getString("N_USERID")); n.setnContent(rset.getString("N_CONTENT")); n.setnCount(rset.getInt("N_COUNT")); n.setnDate(rset.getDate("N_DATE")); n.setnStatus(rset.getString("N_STATUS")); } } catch(SQLException e) { e.printStackTrace(); } finally { close(rset); close(pstmt); } return n; } /** * 게시글 추가하기 * 2020.02.27 Kwon * @param conn * @param n * @return */ public int insertNotice(Connection conn, Notice n) { int result = 0; PreparedStatement pstmt = null; String sql = prop.getProperty("insertNotice"); try { pstmt = conn.prepareStatement(sql); pstmt.setString(1, n.getnTitle()); pstmt.setString(2, n.getnUserName()); pstmt.setString(3, n.getnUserId()); pstmt.setString(4, n.getnContent()); pstmt.setDate(5, n.getnDate()); result = pstmt.executeUpdate(); } catch(SQLException e) { e.printStackTrace(); } finally { close(pstmt); } return result; } /** * 공지사항 수정 보여주기 * 2020.03.01 Kwon * @param conn * @return */ public Notice updateViewNotice(Connection conn, int nno) { Notice n = null; PreparedStatement pstmt = null; ResultSet rset = null; String sql = prop.getProperty("selectOne"); try { pstmt = conn.prepareStatement(sql); pstmt.setInt(1, nno); rset = pstmt.executeQuery(); if(rset.next()) { n = new Notice(); n.setNno(nno); n.setnTitle(rset.getString("N_TITLE")); n.setnUserName(rset.getString("N_USERNAME")); n.setnUserId(rset.getString("N_USERID")); n.setnContent(rset.getString("N_CONTENT")); n.setnDate(rset.getDate("N_DATE")); n.setnStatus(rset.getString("N_STATUS")); } } catch(SQLException e) { e.printStackTrace(); } finally { close(rset); close(pstmt); } return n; } /** * 공지사항 조회수 증가 메소드 * 2020.03.01 Kwon * @param nno * @return */ public int noticeCount(Connection conn, int nno) { int result = 0; PreparedStatement pstmt = null; String sql = prop.getProperty("countUp"); try { pstmt = conn.prepareStatement(sql); pstmt.setInt(1, nno); result = pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { close(pstmt); } return result; } /** * 공지사항 수정하기 * 2020.03.01 kwon * @param conn * @param n * @return */ public int updateNotice(Connection conn, Notice n) { int result = 0; PreparedStatement pstmt = null; String sql = prop.getProperty("updateNotice"); try { pstmt = conn.prepareStatement(sql); pstmt.setString(1, n.getnTitle()); pstmt.setString(2, n.getnUserName()); pstmt.setString(3, n.getnUserId()); pstmt.setString(4, n.getnContent()); pstmt.setDate(5, n.getnDate()); pstmt.setInt(6, n.getNno()); result = pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { close(pstmt); } return result; } /** * 공지사항 삭제하기 (STATUS = N으로 변경하기) * 2020.03.01 Kwon * @param conn * @param nno * @return */ public int deleteNotice(Connection conn, int nno) { int result = 0; PreparedStatement pstmt = null; String sql = prop.getProperty("deleteNotice"); try { pstmt = conn.prepareStatement(sql); pstmt.setInt(1, nno); result = pstmt.executeUpdate(); } catch(SQLException e) { e.printStackTrace(); } finally { close(pstmt); } return result; } /** * 공지사항 검색 숫자 가져오기 * @param conn * @param category * @param keyword * @param currentPage * @param limit * @return */ public int getListSearchCount(Connection conn, String category, String keyword) { int result = 0; PreparedStatement pstmt = null; ResultSet rset = null; String sql = null; switch(category) { case "userName" : sql = prop.getProperty("searchUserNameNoticeCount"); break; case "title" : sql = prop.getProperty("searchTitleNoticeCount"); break; case "content" : sql = prop.getProperty("searchContentNoticeCount"); break; } try { pstmt = conn.prepareStatement(sql); pstmt.setString(1, keyword); rset = pstmt.executeQuery(); if(rset.next()) { result = rset.getInt(1); System.out.println("[Dao] 검색한 글 갯수 : " + result); } } catch(SQLException e) { e.printStackTrace(); } finally { close(rset); close(pstmt); } return result; } /** * 공지사항 검색하기 * 2020.03.01 Kwon * @param conn * @param con * @param keyword * @return */ public ArrayList<Notice> searchNoticeList(Connection conn, String category, String keyword, int currentPage, int limit) { ArrayList<Notice> list = null; PreparedStatement pstmt = null; ResultSet rset = null; String sql = null; switch(category) { case "userName" : sql = prop.getProperty("searchUserNameNotice"); break; case "title" : sql = prop.getProperty("searchTitleNotice"); break; case "content" : sql = prop.getProperty("searchContentNotice"); break; } try { pstmt = conn.prepareStatement(sql); int startRow = (currentPage-1)*limit +1; int endRow = startRow + limit -1; pstmt.setString(1, keyword); pstmt.setInt(2, endRow); pstmt.setInt(3, startRow); rset = pstmt.executeQuery(); list = new ArrayList<Notice>(); System.out.println("검색한 카테고리 : " + category + " , 검색한 키워드 : " + keyword); while(rset.next()) { Notice n = new Notice(); n.setNno(rset.getInt("N_NO")); n.setnTitle(rset.getString("N_TITLE")); n.setnUserName(rset.getString("N_USERNAME")); n.setnUserId(rset.getString("N_USERID")); n.setnContent(rset.getString("N_CONTENT")); n.setnCount(rset.getInt("N_COUNT")); n.setnDate(rset.getDate("N_DATE")); n.setnStatus(rset.getString("N_STATUS")); list.add(n); } } catch(SQLException e) { e.printStackTrace(); } finally { close(rset); close(pstmt); } return list; } }
Java
UTF-8
1,310
2.5625
3
[]
no_license
package agent; import java.util.ArrayList; import java.util.HashMap; import negotiator.AgentID; import negotiator.Bid; import negotiator.BidHistory; import negotiator.bidding.BidDetails; import negotiator.issue.Issue; import negotiator.issue.IssueDiscrete; import negotiator.issue.ValueDiscrete; import negotiator.utility.AdditiveUtilitySpace; import negotiator.utility.UtilitySpace; public class Opponent { public AgentID opponentID; public BidHistory bidHistory = new BidHistory(); public double acceptanceThreshold; public Bid acceptedBid; public HashMap<Bid, Integer> bidMap = new HashMap<Bid, Integer>(); public HashMap<IssueDiscrete, Double> issueMap = new HashMap<IssueDiscrete, Double>(); public HashMap<IssueDiscrete, HashMap<ValueDiscrete, Integer>> IssueValuesMap = new HashMap<IssueDiscrete, HashMap<ValueDiscrete, Integer>>(); public String opponentType = null; // Constructor. public Opponent(AgentID id) { this.opponentID = id; } // Get the opponent's bid history. public BidHistory getBidHistory() { return this.bidHistory; } // Add a bid to the opponent's bid history. public void addToHistory(BidDetails bid) { this.bidHistory.add(bid); } public void setType(String opType) { this.opponentType = opType; } }
C++
UTF-8
366
2.5625
3
[]
no_license
#include "waitcondition.h" void Wait::run(){ qDebug()<<Wait::currentThreadId(); waitcondition.wait(&mutex); qDebug()<<Wait::currentThreadId()<<"global:"<<global; Wait::sleep(2); } void Wakeup::run(){ mutex.lock(); global = global + 5; Wakeup::sleep(2); mutex.unlock(); // waitcondition.wakeAll(); waitcondition.wakeOne(); }
Go
UTF-8
333
3.234375
3
[]
no_license
package main import ( "fmt" "strings" ) func strStr(haystack string, needle string) int { temp := strings.Split(haystack, needle) if len(temp) == 1 && needle != "" { return -1 } if len(temp) > 1 { if len(temp[0]) != 0 { return len(temp[0]) } } return 0 } func main() { t := strStr("a", "") fmt.Println(t) }
Java
UTF-8
2,290
2.625
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package GameFiles; import java.util.Random; /** * * @author Connor */ public class Randomizer { /** * Generate whole numbers between the given ranges. Start is minimum number. End is max number. * Altered code by: Connor Belanger. Original code by: Hirondelle Systems * @param Start * @param End * @param random * @return */ public static float RandomInteger(int Start, int End) { Random random = new Random(); long range = (long)End - (long)Start + 1; long fraction = (long)(range * random.nextDouble()); float randomNumber = (float)(fraction + Start); return randomNumber; } } // Copyright (c) 2002-2009, Hirondelle Systems //All rights reserved. // Redistribution and use in source and binary forms, with or without //modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Hirondelle Systems nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY HIRONDELLE SYSTEMS ''AS IS'' AND ANY // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL HIRONDELLE SYSTEMS BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES //(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Markdown
UTF-8
932
2.703125
3
[]
no_license
Topic: Advanced Time Series Case: Walker Advertising: Los Defensores and 1-800-THE-LAW2 (QA-0912.pdf) Data: Areas_Master.csv, CallsTable.zip, MediaPlacement.zip Code: WalkerStarter.ipynb Assignment: 1. Read Walker Advertising: Los Defensores and 1-800-THE-LAW2 Click for more options * What is Walker’s traditional business model? -Selling advertising for attorneys * What are the challenges to bringing that business model to new markets? -optimizing outreach to potential clients, ef * Who is their customer? - Lawyers 3. What kind of challenges does Walker face in leveraging their data? Does your firm face similar challenges? If you were Quentin, how would you approach the transition to a data centric decision-making process considering the context in which he is operating? 3. Further instructions for preparation are available in the starter code.
C++
UTF-8
1,104
3.984375
4
[]
no_license
/* Exercise 2-4. For your birthday you’ve been given a long tape measure and an instrument that measures angles (the angle between the horizontal and a line to the top of a tree, for instance). If you know the distance, d, you are from a tree, and the height, h, of your eye when peering into your angle-measuring device, you can calculate the height of the tree with the formula h + d*tan(angle). Create a program to read h in inches, d in feet and inches, and angle in degrees from the keyboard, and output the height of the tree in feet. */ #include <iostream> #include <cmath> int main() { unsigned int distance {}; std::cout << "Enter the distance: "; std::cin >> distance; unsigned int angle {}; std::cout << "Enter the angle: "; std::cin >> angle; unsigned int height_of_the_eye {}; std::cout << "Enter height of the eye: "; std::cin >> height_of_the_eye; double height_of_the_tree { abs(height_of_the_eye + (distance * std::tan(angle) )) }; std::cout << "height of the tree: " << height_of_the_tree << " feets" << std::endl; return 0; }
Java
UTF-8
536
2.109375
2
[]
no_license
package repositories.model; import models.Brand; import models.Model; import play.mvc.Http; import java.util.Optional; import java.util.concurrent.CompletionStage; import java.util.stream.Stream; public interface IModelRepository { CompletionStage<Stream<Model>> list(); CompletionStage<Optional<Model>> getByID(Long id); CompletionStage<Optional<Model>> updateByID(Long id, Http.Request request); CompletionStage<Optional<Integer>> deleteByID(Long id); CompletionStage<Model> create(Http.Request request); }
C++
UTF-8
41,192
2.671875
3
[ "MIT" ]
permissive
#include "FileUtilities_TD.h" internal b32 WriteEntireFile(bucket_allocator *Bucket, u8 *Filename, u32 MemorySize, void *Memory) { b32 Result = false; string_w FileNameWide = {}; ConvertString8To16(&Bucket->Transient, Filename, &FileNameWide); Result = WriteEntireFile(&FileNameWide, MemorySize, Memory); DeleteStringW(&Bucket->Transient, &FileNameWide); return Result; } internal b32 WriteEntireFile(string_w *Filename, u32 MemorySize, void *Memory) { b32 Result = false; HANDLE FileHandle = CreateFileW(Filename->S, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0); if(FileHandle != INVALID_HANDLE_VALUE) { DWORD BytesWritten; if(WriteFile(FileHandle, Memory, MemorySize, &BytesWritten, 0)) { Result = (BytesWritten == MemorySize); //File write successfully } else { //Could not write the file } CloseHandle(FileHandle); } else { //Could not open File } return(Result); } internal void FreeFileMemory(memory_bucket_container *BucketContainer, void *Memory) { if(Memory && !BucketContainer->IsFixedBucket) { PopFromTransientBucket(BucketContainer, Memory); } } internal b32 ReadEntireFile(memory_bucket_container *BucketContainer, read_file_result *FileData, u8 *Filename) { b32 Result = false; string_w FileNameWide = {}; ConvertString8To16(&BucketContainer->Parent->Transient, Filename, &FileNameWide); Result = ReadEntireFile(BucketContainer, FileData, &FileNameWide); DeleteStringW(&BucketContainer->Parent->Transient, &FileNameWide); return Result; } internal b32 ReadEntireFile(memory_bucket_container *BucketContainer, read_file_result *FileData, string_w *Filename) { b32 Result = false; HANDLE FileHandle = CreateFileW(Filename->S, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0); if (FileHandle != INVALID_HANDLE_VALUE) { LARGE_INTEGER FileSize; if (GetFileSizeEx(FileHandle, &FileSize)) { u32 FileSize32 = SafeTruncateUInt64(FileSize.QuadPart); //FileData->Contents = (char *)VirtualAlloc(0, FileSize32, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); FileData->Data = (u8 *)PushSizeOnBucket(BucketContainer, FileSize32+1); if (FileData->Data) { DWORD BytesRead; if (ReadFile(FileHandle, FileData->Data, FileSize32, &BytesRead, 0) && (FileSize32 == BytesRead)) { FileData->Size = FileSize32+1; FileData->Data[FileData->Size-1] = 0; Result = true; } else { FreeFileMemory(BucketContainer, FileData->Data); FileData->Data = 0; printf("Could not read the file.\n"); } } else { printf("Could not get Memory for file.\n"); } } else { printf("Could not get file size.\n"); } CloseHandle(FileHandle); } else { //printf("Could not open File: \"%s\".\n", Filename); } return(Result); } internal b32 ReadBeginningOfFile(memory_bucket_container *Bucket, read_file_result *FileData, u8 *Filename, i32 ReadAmount) { b32 Result = false; string_w FileNameWide = {}; ConvertString8To16(&Bucket->Parent->Transient, Filename, &FileNameWide); Result = ReadBeginningOfFile(Bucket, FileData, &FileNameWide, ReadAmount); DeleteStringW(&Bucket->Parent->Transient, &FileNameWide); return Result; } internal b32 ReadBeginningOfFile(memory_bucket_container *Bucket, read_file_result *FileData, string_w *Filename, i32 ReadAmount) { b32 Result = false; HANDLE FileHandle = CreateFileW(Filename->S, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0); if (FileHandle != INVALID_HANDLE_VALUE) { LARGE_INTEGER FileSize; if (GetFileSizeEx(FileHandle, &FileSize)) { u32 FileSize32 = SafeTruncateUInt64(FileSize.QuadPart); FileData->Data = (u8 *)PushSizeOnBucket(Bucket, ReadAmount); if (FileData->Data) { DWORD BytesRead; if (ReadFile(FileHandle, FileData->Data, ReadAmount, &BytesRead, 0)) { FileData->Size = BytesRead; Result = true; } else { FreeFileMemory(Bucket, FileData->Data); FileData->Data = 0; printf("Could not read the file.\n"); } } else { printf("Could not get Memory for file.\n"); } } else { printf("Could not get file size.\n"); } CloseHandle(FileHandle); } else { //printf("Could not open File: \"%s\".\n", Filename); } return(Result); } internal b32 AppendToFile(memory_bucket_container *BucketContainer, u8 *FileName, u32 MemorySize, void *Memory) { b32 Result = false; read_file_result FileData = {}; if(ReadEntireFile(BucketContainer, &FileData, FileName)) { MemorySize += FileData.Size; char AllData[10000]; sprintf_s(AllData, "%s\n%s\n\0",FileData.Data, (char *)Memory); if(WriteEntireFile(BucketContainer->Parent, FileName, MemorySize, AllData)) { Result = true; } PopFromTransientBucket(BucketContainer, FileData.Data); } return Result; } inline bit_scan_result FindLeastSignificantSetBit(u32 Value) { bit_scan_result Result = {}; #if COMPILER_MSVC Result.Found = _BitScanForward((unsigned long *)&Result.Index, Value); #else for(u32 Test = 0; Test < 32; ++Test) { if(Value & (1 << Test)) { Result.Index = Test; Result.Found = true; break; } } #endif return(Result); } internal loaded_bitmap LoadBMPImage(memory_bucket_container *BucketContainer, u8 *FileName) { loaded_bitmap Result = {}; Result.WasLoaded = false; read_file_result FileData = {}; if(ReadEntireFile(BucketContainer, &FileData, FileName)) { Result.WasLoaded = true; bitmap_header *Header = (bitmap_header *)FileData.Data; u32 *Pixels = (u32 *)((u8 *)FileData.Data + Header->BitmapOffset); Result.Pixels = Pixels; Assert(Header->Height >= 0); Result.Width = Header->Width; Result.Height = Header->Height; if(Header->Compression == 3) { // NOTE:: Byte order in memory is determined by Header // so we have to read out masks and convert the pixels u32 RedMask = Header->RedMask; u32 GreenMask = Header->GreenMask; u32 BlueMask = Header->BlueMask; u32 AlphaMask = ~(RedMask | GreenMask | BlueMask); bit_scan_result RedShift = FindLeastSignificantSetBit(RedMask); bit_scan_result GreenShift = FindLeastSignificantSetBit(GreenMask); bit_scan_result BlueShift = FindLeastSignificantSetBit(BlueMask); bit_scan_result AlphaShift = FindLeastSignificantSetBit(AlphaMask); Assert(RedShift.Found); Assert(GreenShift.Found); Assert(BlueShift.Found); Assert(AlphaShift.Found); u32 *SourceDest = Pixels; for(i32 Y = 0; Y < Header->Height; ++Y) { for(i32 X = 0; X < Header->Width; ++X) { u32 C = *SourceDest; #if 0 *SourceDest++ = ((((C >> RedShift.Index) & 0xFF) << 24) | (((C >> GreenShift.Index) & 0xFF) << 16) | (((C >> BlueShift.Index) & 0xFF) << 8) | (((C >> AlphaShift.Index) & 0xFF) << 0)); #else *SourceDest++ = ((((C >> AlphaShift.Index) & 0xFF) << 24) | (((C >> BlueShift.Index) & 0xFF) << 16) | (((C >> RedShift.Index) & 0xFF) << 8) | (((C >> GreenShift.Index) & 0xFF) << 0)); #endif } } Result.ColorFormat = colorFormat_RGBA; } else if(Header->Compression == 0) { if(Header->BitsPerPixel == 24) { Result.ColorFormat = colorFormat_BGR; } } else { Assert(Header->Compression == -1); } } return Result; } inline u32 ProcessVectorLine(r32 *Results, u32 VectorDim, u8 *LineChar) { u32 EndOfLineCount = 0; for(u32 XYZCount = 0; XYZCount < VectorDim; ++XYZCount) { r32 *NewVal = Results + XYZCount; u8 NumberLength = 0; *NewVal = ProcessNextR32InString(LineChar, ' ', NumberLength); LineChar += NumberLength; EndOfLineCount += NumberLength; } return EndOfLineCount; } inline face_type IdentifyFaceType(u8 *Character) { face_type Result = NO_VALUE; u8 AdvanceChar = 0; i32 Position = FirstOccurrenceOfCharacterInString('/', Character, '\n'); if(Position == -1) { Result = VERTEX; // Only vertice } else { ProcessNextU32InString(Character, '/', AdvanceChar); Character += AdvanceChar + 1; if(*Character == '/') { Result = VERTEX_NORMAL; // Vertice + normal } else { ProcessNextU32InString(Character, ' ', AdvanceChar); u8 CheckAdvance = 0; ProcessNextU32InString(Character, '/', CheckAdvance); if(AdvanceChar < CheckAdvance) { Result = VERTEX_TEXCOORD; // Vertice + texcoord } else { Result = VERTEX_TEXCOORD_NORMAL; // Vertice + texcoord + normal } } } return Result; } internal void EvaluateNextFaceWithNormal(hash_table *FaceTable, obj_data *Object, obj_material_group *CurrentGroup, u8 *Character, v3 *Vertice, v2 *TexCoords, v3 *Normals) { u32 NextVertI[4]; u32 NextTexI[4]; u8 *KeyPosition[4]; u8 KeyLength[4]; u8 Counter = 0; u8 AdvanceChar = 0; for(u32 Index = 0; Index < 4; ++Index) { Counter++; KeyPosition[Index] = Character; KeyLength[Index] = (u8)StringLengthUntilChar(Character, ' '); Assert(KeyLength[Index] < 15); // NOTE:: obj to big for KeyLength. Need to adjust! switch(Object->FaceType) { case VERTEX: { NextVertI[Index] = ProcessNextU32InString(Character, ' ', AdvanceChar)-1; Character += AdvanceChar; } break; case VERTEX_TEXCOORD: { NextVertI[Index] = ProcessNextU32InString(Character, '/', AdvanceChar)-1; Character += AdvanceChar + 1; NextTexI[Index] = ProcessNextU32InString(Character, ' ', AdvanceChar)-1; Character += AdvanceChar; } break; } Character = AdvanceAfterConsecutiveGivenChar(Character, ' '); if(*Character == '\n' && Index == 2) { break; } } v3 P0 = *(Vertice + NextVertI[0]); v3 P1 = *(Vertice + NextVertI[1]); v3 P2 = *(Vertice + NextVertI[2]); v3 Normal = Normalize(Cross(P1 - P0, P2 - P0)); u8 NormalKey[15]; ConvertV3To15Char(Normal, NormalKey); for(u8 Index = 0; Index < Counter; ++Index) { if(Index == 3) { *(CurrentGroup->Indices + CurrentGroup->IndiceCount) = *(CurrentGroup->Indices + (CurrentGroup->IndiceCount - 3)); *(CurrentGroup->Indices + (CurrentGroup->IndiceCount + 1)) = *(CurrentGroup->Indices + (CurrentGroup->IndiceCount - 1)); CurrentGroup->IndiceCount += 2; } u8 Key[HASH_TABLE_KEY_LENGTH]; CopyString(Key, KeyPosition[Index], KeyLength[Index]); CombineStrings(Key, Key, (u8 *)"/"); CombineStrings(Key, Key, NormalKey); //sprintf_s((char *)Key, HASH_TABLE_KEY_LENGTH, "%s/%s", Key, NormalKey); switch(Object->FaceType) { case VERTEX: { if(AddToHashTable(FaceTable, Key, Object->Count)) { *(Object->Vertice + Object->Count) = *(Vertice + NextVertI[Index]); *(Object->Normals + Object->Count) = Normal; *(CurrentGroup->Indices + CurrentGroup->IndiceCount++) = Object->Count++; } else { u32 FaceIndex; GetFromHashTable(FaceTable, Key, FaceIndex); *(CurrentGroup->Indices + CurrentGroup->IndiceCount++) = FaceIndex; } } break; case VERTEX_TEXCOORD: { if(AddToHashTable(FaceTable, Key, Object->Count)) { *(Object->Vertice + Object->Count) = *(Vertice + NextVertI[Index]); *(Object->TexCoords + Object->Count) = *(TexCoords + NextTexI[Index]); *(Object->Normals + Object->Count) = Normal; *(CurrentGroup->Indices + CurrentGroup->IndiceCount++) = Object->Count++; } else { u32 FaceIndex; GetFromHashTable(FaceTable, Key, FaceIndex); *(CurrentGroup->Indices + CurrentGroup->IndiceCount++) = FaceIndex; } } break; } } } internal u8 * EvaluateNextFaceIndexGroup(hash_table *FaceTable, obj_data *Object, obj_material_group *CurrentGroup, u8 *Character, v3 *Vertice, v2 *TexCoords, v3 *Normals) { u8 AdvanceChar = 0; switch(Object->FaceType) { case VERTEX: { u32 VertexIndex = ProcessNextU32InString(Character, ' ', AdvanceChar)-1; Character += AdvanceChar; *(Object->Vertice + Object->Count) = *(Vertice + VertexIndex); *(CurrentGroup->Indices + CurrentGroup->IndiceCount++) = Object->Count++; } break; case VERTEX_TEXCOORD: { u32 KeyLength = StringLengthUntilChar(Character, ' '); u8 Key[HASH_TABLE_KEY_LENGTH]; CopyString(Key, Character, KeyLength); if(AddToHashTable(FaceTable, Key, Object->Count)) { u32 VertexIndex = ProcessNextU32InString(Character, '/', AdvanceChar)-1; Character += AdvanceChar + 1; u32 TexCoordIndex = ProcessNextU32InString(Character, ' ', AdvanceChar)-1; Character += AdvanceChar; *(Object->Vertice + Object->Count) = *(Vertice + VertexIndex); *(Object->TexCoords + Object->Count) = *(TexCoords + TexCoordIndex); *(CurrentGroup->Indices + CurrentGroup->IndiceCount++) = Object->Count++; } else { Character += KeyLength; u32 FaceIndex; GetFromHashTable(FaceTable, Key, FaceIndex); *(CurrentGroup->Indices + CurrentGroup->IndiceCount++) = FaceIndex; } } break; case VERTEX_NORMAL: { u32 KeyLength = StringLengthUntilChar(Character, ' '); u8 Key[HASH_TABLE_KEY_LENGTH]; CopyString(Key, Character, KeyLength); if(AddToHashTable(FaceTable, Key, Object->Count)) { u32 VertexIndex = ProcessNextU32InString(Character, '/', AdvanceChar)-1; Character += AdvanceChar + 2; u32 NormalIndex = ProcessNextU32InString(Character, ' ', AdvanceChar)-1; Character += AdvanceChar; *(Object->Vertice + Object->Count) = *(Vertice + VertexIndex); *(Object->Normals + Object->Count) = *(Normals + NormalIndex); *(CurrentGroup->Indices + CurrentGroup->IndiceCount++) = Object->Count++; } else { Character += KeyLength; u32 FaceIndex; GetFromHashTable(FaceTable, Key, FaceIndex); *(CurrentGroup->Indices + CurrentGroup->IndiceCount++) = FaceIndex; } } break; case VERTEX_TEXCOORD_NORMAL: { u32 KeyLength = StringLengthUntilChar(Character, ' '); u8 Key[HASH_TABLE_KEY_LENGTH]; CopyString(Key, Character, KeyLength); if(AddToHashTable(FaceTable, Key, Object->Count)) { u32 VertexIndex = ProcessNextU32InString(Character, '/', AdvanceChar)-1; Character += AdvanceChar + 1; u32 TexCoordIndex = ProcessNextU32InString(Character, '/', AdvanceChar)-1; Character += AdvanceChar + 1; u32 NormalIndex = ProcessNextU32InString(Character, ' ', AdvanceChar)-1; Character += AdvanceChar; *(Object->Vertice + Object->Count) = *(Vertice + VertexIndex); *(Object->TexCoords + Object->Count) = *(TexCoords + TexCoordIndex); *(Object->Normals + Object->Count) = *(Normals + NormalIndex); *(CurrentGroup->Indices + CurrentGroup->IndiceCount++) = Object->Count++; } else { Character += KeyLength; u32 FaceIndex; GetFromHashTable(FaceTable, Key, FaceIndex); *(CurrentGroup->Indices + CurrentGroup->IndiceCount++) = FaceIndex; } } break; } return Character; } internal b32 LoadOBJFile(obj_data *Object, u8 *Filename, bucket_allocator *BucketAlloc) { // TODO(TD): This does not yet really work with the new bucket allocator. // could use some work! b32 Result = false; read_file_result File = {}; if(ReadEntireFile(&BucketAlloc->Transient, &File, Filename)) { u8 MaterialPath[MAX_PATH]; u8 CurrentSurfaceName[MAX_PATH]; u8 *TMPName = (u8 *)"Unnamed Object"; CopyString(CurrentSurfaceName, TMPName, StringLength(TMPName)); u32 CurrentSmoothingValue = 0; hash_table FaceTable = {}; Object->Infos.MinBound = V3(MAX_REAL32, MAX_REAL32, MAX_REAL32); Object->Infos.MaxBound = V3(MIN_REAL32, MIN_REAL32, MIN_REAL32); // NOTE:: Memory footprint is at least 8 times the original filesize // during processing. For every new material it increases Assert(BucketAlloc->Transient.Bucket[0].Size > File.Size*8); u32 VertexCount = 0, TexCoordCount = 0, NormalCount = 0; u32 ArraySizes = File.Size; memory_bucket_container *Container = &BucketAlloc->Transient; v3 *Vertice = (v3 *)PushSizeOnBucket(Container, ArraySizes); v2 *TexCoords = (v2 *)PushSizeOnBucket(Container, ArraySizes); v3 *Normals = (v3 *)PushSizeOnBucket(Container, ArraySizes); Object->Vertice = (v3 *)PushSizeOnBucket(Container, ArraySizes); Object->TexCoords = (v2 *)PushSizeOnBucket(Container, ArraySizes); Object->Normals = (v3 *)PushSizeOnBucket(Container, ArraySizes); Object->SurfaceGroups = PushArrayOnBucket(Container, ArraySizes/10, obj_material_group); obj_material_group *CurrentGroup = &Object->SurfaceGroups[Object->GroupCount]; CurrentGroup->IndiceCount = 0; CurrentGroup->Indices = (u32 *)PushSizeOnBucket(Container, ArraySizes); u32 MaxV3ArraySize = ArraySizes/sizeof(v3); u32 MaxV2ArraySize = ArraySizes/sizeof(v2); u32 MaxObjMaterialGroupArraySize = ArraySizes/10; u32 MaxUint32ArraySize = ArraySizes/sizeof(u32); u8 *Character = (u8 *)File.Data; FaceTable = HashTable(Container, File.Size/10); u8 CutPath[MAX_PATH]; while(*Character != '\0') { switch(*Character) { case '#': // Comment in file, ignore. { Character = AdvanceToNextLine(Character); } break; case 'm': // Path to material file { Character += 7; u32 CutPathCount = LastOccurrenceOfCharacterInString('\\', (u8 *)Filename, '\0') + 1; CopyString(CutPath, Filename, CutPathCount); CutPath[CutPathCount] = '\0'; CopyString(MaterialPath, CutPath, CutPathCount); u8 *Path = (u8 *)MaterialPath + CutPathCount; while(*Character != '\n') { *Path++ = *Character++; } *Path = '\0'; Object->Materials.NameIndex = HashTable(&BucketAlloc->Transient, 100); } break; case 'o': // Arbitrary name of object { Character += 2; u8 *Path = (u8 *)Object->Name; while(*Character != '\n') { *Path++ = *Character++; } *Path = '\0'; } break; case 'v': // Some form of vector { Character++; if(*Character == ' ') // Vector is a vertex { Character = AdvanceAfterConsecutiveGivenChar(Character, ' '); Character += ProcessVectorLine(Vertice[VertexCount].E, 3, Character); if(Object->Infos.MinBound.x > Vertice[VertexCount].x) { Object->Infos.MinBound.x = Vertice[VertexCount].x; } if(Object->Infos.MinBound.y > Vertice[VertexCount].y) { Object->Infos.MinBound.y = Vertice[VertexCount].y; } if(Object->Infos.MinBound.z > Vertice[VertexCount].z) { Object->Infos.MinBound.z = Vertice[VertexCount].z; } if(Object->Infos.MaxBound.x < Vertice[VertexCount].x) { Object->Infos.MaxBound.x = Vertice[VertexCount].x; } if(Object->Infos.MaxBound.y < Vertice[VertexCount].y) { Object->Infos.MaxBound.y = Vertice[VertexCount].y; } if(Object->Infos.MaxBound.z < Vertice[VertexCount].z) { Object->Infos.MaxBound.z = Vertice[VertexCount].z; } VertexCount++; Assert(VertexCount < MaxV3ArraySize); } else if(*Character == 't') // Vector is a texture coordinate { Character++; Character = AdvanceAfterConsecutiveGivenChar(Character, ' '); v2 *NewTex = (TexCoords + TexCoordCount++); Character += ProcessVectorLine(NewTex->E, 2, Character); Assert(TexCoordCount < MaxV2ArraySize); } else // Vector is a normal { Character++; Character = AdvanceAfterConsecutiveGivenChar(Character, ' '); Character += ProcessVectorLine(Normals[NormalCount++].E, 3, Character); Assert(NormalCount < MaxV3ArraySize); } } break; case 'g': // Arbitrary name of a group { Character += 2; u8 *Path = (u8 *)CurrentSurfaceName; while(*Character != '\n') { *Path++ = *Character++; } *Path = '\0'; } break; case 'u': // Name of a Material for following group + new surface group { Character += 7; Assert(Object->GroupCount < MaxObjMaterialGroupArraySize); u8 NewMat[50]; u32 MatNameLength = 0; u8 *Name = NewMat; while(*Character != '\n') { *Name++ = *Character++; MatNameLength++; } *Name = '\0'; MatNameLength++; if(AddToHashTable(&Object->Materials.NameIndex, NewMat, MAX_UINT32)) { if(Object->GroupCount++ > 0) { CurrentGroup = Object->SurfaceGroups + (Object->GroupCount - 1); CurrentGroup->IndiceCount = 0; CurrentGroup->Indices = (u32 *)PushSizeOnBucket(Container, ArraySizes); } CopyString((u8 *)CurrentGroup->MatName, NewMat, MatNameLength); } else { // TODO:: Can we find the group without linearly going through // the list and string-comparing everything? for(u32 Index = 0; Index < Object->GroupCount; ++Index) { if(StringCompare(NewMat, (Object->SurfaceGroups + Index)->MatName, 0, MatNameLength)) { CurrentGroup = Object->SurfaceGroups + Index; break; } } } } break; case 's': // Smoothing group :: most likely not working properly { //InvalidCodePath; printf("InvalidCodePath"); // TODO:: Smoothing value is currently not being integrated. Character += 2; if(*Character != 'o') // Smoothing value { CurrentSmoothingValue = CharToU32(*Character++); if(*Character != '\n' && *Character != '\0') { CurrentSmoothingValue *= 10; CurrentSmoothingValue += CharToU32(*Character++); } } else // turn off current smoothing { CurrentSmoothingValue = 0; Character += 3; } } break; case 'f': // Description of a surface { Character += 2; Assert(CurrentGroup); // If this happens, we need another/different place for creating groups other than usemtl Assert(Object->Count < MaxV3ArraySize); Assert(CurrentGroup->IndiceCount < MaxUint32ArraySize); if(Object->FaceType == NO_VALUE) { Object->FaceType = IdentifyFaceType(Character); } switch(Object->FaceType) { case VERTEX: case VERTEX_TEXCOORD: { EvaluateNextFaceWithNormal(&FaceTable, Object, CurrentGroup, Character, Vertice, TexCoords, Normals); } break; case VERTEX_NORMAL: case VERTEX_TEXCOORD_NORMAL: { for(u32 Index = 0; Index < 3; ++Index) { Character = EvaluateNextFaceIndexGroup(&FaceTable, Object, CurrentGroup, Character, Vertice, TexCoords, Normals); // // NOTE:: Currently supporting max 4 Vertice per face. If triggered, need to implement something for that! Character = AdvanceAfterConsecutiveGivenChar(Character, ' '); if(*Character != '\n' && Index == 2) { *(CurrentGroup->Indices + CurrentGroup->IndiceCount) = *(CurrentGroup->Indices + (CurrentGroup->IndiceCount - 3)); *(CurrentGroup->Indices + (CurrentGroup->IndiceCount + 1)) = *(CurrentGroup->Indices + (CurrentGroup->IndiceCount - 1)); CurrentGroup->IndiceCount += 2; Character = EvaluateNextFaceIndexGroup(&FaceTable, Object, CurrentGroup, Character, Vertice, TexCoords, Normals); } } } break; } Character = AdvanceToLineEnd(Character); } break; default: { Character = AdvanceToNextLine(Character); } break; } } FreeFileMemory(&BucketAlloc->Transient, File.Data); DeleteHashTableTransient(BucketAlloc, &FaceTable); PopFromTransientBucket(BucketAlloc, Vertice); PopFromTransientBucket(BucketAlloc, TexCoords); PopFromTransientBucket(BucketAlloc, Normals); Object->Vertice = PushArrayFromTransientToFixedBucket(BucketAlloc, Object->Vertice, Object->Count, v3, false); Object->Normals = PushArrayFromTransientToFixedBucket(BucketAlloc, Object->Normals, Object->Count, v3, false); switch(Object->FaceType) { case VERTEX_TEXCOORD: { Object->TexCoords = PushArrayFromTransientToFixedBucket(BucketAlloc, Object->TexCoords, Object->Count, v2, false); } break; case VERTEX_NORMAL: { PopFromTransientBucket(BucketAlloc, Object->TexCoords); } break; case VERTEX_TEXCOORD_NORMAL: { Object->TexCoords = PushArrayFromTransientToFixedBucket(BucketAlloc, Object->TexCoords, Object->Count, v2, false); } } for(u32 Index = 0; Index < Object->GroupCount; ++Index) { obj_material_group *Group = Object->SurfaceGroups + Index; Group->Indices = PushArrayFromTransientToFixedBucket(BucketAlloc, Group->Indices, Group->IndiceCount, u32, false); } Object->SurfaceGroups = PushArrayFromTransientToFixedBucket(BucketAlloc, Object->SurfaceGroups, Object->GroupCount, obj_material_group, false); Result = LoadMtlFile(&Object->Materials, BucketAlloc, MaterialPath, CutPath); } return Result; } internal obj_material_group CollectAllGroupsInOne(obj_data *Object, bucket_allocator *BucketAlloc) { obj_material_group Result = {}; for(u32 Index = 0; Index < Object->GroupCount; ++Index) { Result.IndiceCount += Object->SurfaceGroups[Index].IndiceCount; } Result.Indices = PushArrayOnBucket(&BucketAlloc->Fixed, Result.IndiceCount, u32); u32 PersCounter = 0; for(u32 GroupIndex = 0; GroupIndex < Object->GroupCount; ++GroupIndex) { obj_material_group Group = Object->SurfaceGroups[GroupIndex]; for(u32 IndiceIndex = 0; IndiceIndex < Group.IndiceCount; ++IndiceIndex) { Result.Indices[PersCounter++] = Group.Indices[IndiceIndex]; } } return Result; } internal b32 LoadMtlFile(mtl_data *Materials, bucket_allocator *BucketAlloc, u8 *Path, u8 *CutPath) { b32 Result = false; read_file_result FileData; if(ReadEntireFile(&BucketAlloc->Transient, &FileData, Path)) { Materials->Count = -1; u32 MCount = Materials->NameIndex.Count; Materials->Ka = PushArrayOnBucket(&BucketAlloc->Fixed, MCount, v3); SetReal32ArrayToGiven((r32 *)Materials->Ka, MCount*3, -1.0); Materials->Kd = PushArrayOnBucket(&BucketAlloc->Fixed, MCount, v3); SetReal32ArrayToGiven((r32 *)Materials->Kd, MCount*3, -1.0); Materials->Ks = PushArrayOnBucket(&BucketAlloc->Fixed, MCount, v3); SetReal32ArrayToGiven((r32 *)Materials->Ks, MCount*3, -1.0); Materials->Tf = PushArrayOnBucket(&BucketAlloc->Fixed, MCount, v3); SetReal32ArrayToGiven((r32 *)Materials->Tf, MCount, -1.0); Materials->Ns = PushArrayOnBucket(&BucketAlloc->Fixed, MCount, r32); Materials->Ni = PushArrayOnBucket(&BucketAlloc->Fixed, MCount, r32); Materials->Tr = PushArrayOnBucket(&BucketAlloc->Fixed, MCount, r32); Materials->Illum = PushArrayOnBucket(&BucketAlloc->Fixed, MCount, u32); Materials->Map_Ka = (u8 *)PushSizeOnBucket(&BucketAlloc->Fixed, MCount*sizeof(u8)*MAX_PATH); Materials->Map_Kd = (u8 *)PushSizeOnBucket(&BucketAlloc->Fixed, MCount*sizeof(u8)*MAX_PATH); Materials->Map_bump = (u8 *)PushSizeOnBucket(&BucketAlloc->Fixed, MCount*sizeof(u8)*MAX_PATH); ClearToGiven(Materials->Map_Ka, MCount*sizeof(u8)*MAX_PATH, 0); ClearToGiven(Materials->Map_Kd, MCount*sizeof(u8)*MAX_PATH, 0); ClearToGiven(Materials->Map_bump, MCount*sizeof(u8)*MAX_PATH, 0); u8 *Character = (u8 *)FileData.Data; u32 CutPathLength = StringLength(CutPath); while(*Character != '\0') { if(*Character == '\t') { Character++; } switch(*Character) { case 'n': // New material { Character += 7; u8 Name[MAX_PATH]; Character += CopyStringUntilChar(Name, Character, '\n'); UpdateValueInHashTable(&Materials->NameIndex, Name, ++Materials->Count); } break; case 'N': { Character++; switch(*Character) { case 's': // Specular exponent { Character += 2; u8 Length = 0; *(Materials->Ns + Materials->Count) = ProcessNextR32InString(Character, '\n', Length); Character += Length; } break; case 'i': // Refraction index { Character += 2; u8 Length = 0; *(Materials->Ni + Materials->Count) = ProcessNextR32InString(Character, '\n', Length); Character += Length; } break; } } break; case 'K': { u8 *NextChar = ++Character; v3 NewVec = {}; Character += 2; Character += ProcessVectorLine(NewVec.E, 3, Character); Character = AdvanceToLineEnd(Character); switch(*NextChar) { case 'a': // Ambient { *(Materials->Ka + Materials->Count) = NewVec; } break; case 'd': // Diffuse { *(Materials->Kd + Materials->Count) = NewVec; } break; case 's': // Specular { *(Materials->Ks + Materials->Count) = NewVec; } break; case 'e': { /*Nothing, ingore*/ } break; } } break; case 'T': { Character++; switch(*Character) { case 'f': // Transmission filter { Character += 2; Character += ProcessVectorLine((Materials->Tf + Materials->Count)->E, 3, Character); Character = AdvanceToLineEnd(Character); } break; case 'r': // Transparency { Character += 2; u8 Length = 0; *(Materials->Tr + Materials->Count) = ProcessNextR32InString(Character, '\n', Length); Character += Length; } break; } } break; case 'm': { Character += 5; switch(*Character) { case 'a': // Ambient texture map { Character += 2; u8 *MapKa = Materials->Map_Ka + (Materials->Count*MAX_PATH); CopyString(MapKa, CutPath, CutPathLength); MapKa += CutPathLength; Character += CopyStringUntilChar(MapKa, Character, '\n'); } break; case 'd': // Diffuse texture map { Character += 2; u8 *MapKd = Materials->Map_Kd + (Materials->Count*MAX_PATH); CopyString(MapKd, CutPath, CutPathLength); MapKd += CutPathLength; Character += CopyStringUntilChar(MapKd, Character, '\n'); } break; case 'u': // Bumpmap { Character += 4; u8 *MapBump = Materials->Map_bump + (Materials->Count*MAX_PATH); CopyString(MapBump, CutPath, CutPathLength); MapBump += CutPathLength; Character += CopyStringUntilChar(MapBump, Character, '\n'); } break; } } break; case 'b': // Bumpmap, again { Character += 4; u8 *MapBump = Materials->Map_bump + (Materials->Count*MAX_PATH); CopyString(MapBump, CutPath, CutPathLength); MapBump += CutPathLength; Character += CopyStringUntilChar(MapBump, Character, '\n'); } break; case 'i': // Illumination model { Character += 6; u8 Length; *(Materials->Illum + Materials->Count) = ProcessNextU32InString(Character, '\n', Length); Character += Length; } break; default: { Character = AdvanceToNextLine(Character); } } } FreeFileMemory(&BucketAlloc->Transient, FileData.Data); Materials->Count++; // Starting at -1, needs to increment to rectify value Result = true; } return Result; } internal loaded_bitmap ConvertBMPToBlackWhiteTransparent(memory_bucket_container *BucketContainer, loaded_bitmap *ExistingBitmap) { loaded_bitmap Result = {}; u32 Count = ExistingBitmap->Width*ExistingBitmap->Height; Result.ColorFormat = colorFormat_RGBA; Result.Width = ExistingBitmap->Width; Result.Height = ExistingBitmap->Height; Result.Pixels = PushArrayOnBucket(BucketContainer, Count, u32); ClearToGiven(Result.Pixels, Count, 0); u8 *AlphaMap = (u8 *)ExistingBitmap->Pixels; u32 BitAlign = 4 - ((3*ExistingBitmap->Width)%4); For(Count) { u8 P = *AlphaMap; Result.Pixels[It] = ((0xFF-P)<<24)|(P<<16)|(P<<8)|P; AlphaMap += 3; if(It%ExistingBitmap->Width == 0) { AlphaMap += BitAlign; } } return Result; }
C#
UTF-8
19,189
2.609375
3
[]
no_license
using Extensions; using Extensions.Enums; using Finances.Classes.Categories; using Finances.Classes.Data; using Finances.Classes.Database; using Finances.Classes.Sorting; using Finances.Pages; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; namespace Finances.Classes { /// <summary>Represents the current state of the application.</summary> internal static class AppState { private static readonly SQLiteDatabaseInteraction DatabaseInteraction = new SQLiteDatabaseInteraction(); internal static List<Account> AllAccounts = new List<Account>(); internal static List<string> AllAccountTypes = new List<string>(); internal static List<Category> AllCategories = new List<Category>(); internal static List<Transaction> AllTransactions = new List<Transaction>(); internal static List<Month> AllMonths = new List<Month>(); internal static List<Year> AllYears = new List<Year>(); #region Navigation /// <summary>Instance of MainWindow currently loaded</summary> internal static MainWindow MainWindow { get; set; } /// <summary>Width of the Page currently being displayed in the MainWindow</summary> internal static double CurrentPageWidth { get; set; } /// <summary>Height of the Page currently being displayed in the MainWindow</summary> internal static double CurrentPageHeight { get; set; } /// <summary>Calculates the scale needed for the MainWindow.</summary> /// <param name="grid">Grid of current Page</param> internal static void CalculateScale(Grid grid) { CurrentPageHeight = grid.ActualHeight; CurrentPageWidth = grid.ActualWidth; MainWindow.CalculateScale(); Page newPage = MainWindow.MainFrame.Content as Page; if (newPage != null) newPage.Style = (Style)MainWindow.FindResource("PageStyle"); } /// <summary>Navigates to selected Page.</summary> /// <param name="newPage">Page to navigate to.</param> internal static void Navigate(Page newPage) => MainWindow.MainFrame.Navigate(newPage); /// <summary>Navigates to the previous Page.</summary> internal static void GoBack() { if (MainWindow.MainFrame.CanGoBack) MainWindow.MainFrame.GoBack(); } #endregion Navigation #region Load /// <summary>Loads all information from the database.</summary> /// <returns>Returns true if successful</returns> internal static async Task LoadAll() { DatabaseInteraction.VerifyDatabaseIntegrity(); AllAccounts = await DatabaseInteraction.LoadAccounts(); AllAccountTypes = await DatabaseInteraction.LoadAccountTypes(); AllCategories = await DatabaseInteraction.LoadCategories(); foreach (Account account in AllAccounts) foreach (Transaction trans in account.AllTransactions) AllTransactions.Add(trans); AllAccountTypes.Sort(); AllTransactions = AllTransactions.OrderByDescending(transaction => transaction.Date).ThenByDescending(transaction => transaction.ID).ToList(); LoadMonths(); LoadYears(); } /// <summary>Loads all credit scores from the database.</summary> /// <returns>List of all credit scores</returns> public static Task<List<CreditScore>> LoadCreditScores() => DatabaseInteraction.LoadCreditScores(); /// <summary>Loads all the Months from AllTransactions.</summary> private static void LoadMonths() { AllMonths.Clear(); if (AllTransactions.Count > 0) { int months = ((DateTime.Now.Year - AllTransactions[AllTransactions.Count - 1].Date.Year) * 12) + DateTime.Now.Month - AllTransactions[AllTransactions.Count - 1].Date.Month; DateTime startMonth = new DateTime(AllTransactions[AllTransactions.Count - 1].Date.Year, AllTransactions[AllTransactions.Count - 1].Date.Month, 1); int start = 0; do { AllMonths.Add(new Month(startMonth.AddMonths(start), new List<Transaction>())); start++; } while (start <= months); foreach (Transaction transaction in AllTransactions) { AllMonths.Find(month => month.MonthStart <= transaction.Date && transaction.Date <= month.MonthEnd.Date).AddTransaction(transaction); } AllMonths = AllMonths.OrderByDescending(month => month.FormattedMonth).ToList(); } } /// <summary>Loads all the Months from AllTransactions.</summary> internal static void LoadYears() { AllYears.Clear(); if (AllTransactions.Count > 0) { int years = (DateTime.Now.Year - AllTransactions[AllTransactions.Count - 1].Date.Year); DateTime startYear = new DateTime(AllTransactions[AllTransactions.Count - 1].Date.Year, 1, 1); int start = 0; do { AllYears.Add(new Year(startYear.AddYears(start), new List<Transaction>())); start++; } while (start <= years); foreach (Transaction transaction in AllTransactions) { AllYears.Find(year => year.YearStart <= transaction.Date && transaction.Date <= year.YearEnd.Date).AddTransaction(transaction); } AllYears = AllYears.OrderByDescending(year => year.FormattedYear).ToList(); } } #endregion Load #region Account Manipulation /// <summary>Adds an account to the database.</summary> /// <param name="newAccount">Account to be added</param> /// <returns>Returns true if successful</returns> internal static async Task<bool> AddAccount(Account newAccount) { bool success = false; if (await DatabaseInteraction.AddAccount(newAccount)) { AllAccounts.Add(newAccount); AllAccounts = AllAccounts.OrderBy(account => account.Name).ToList(); AllTransactions.Add(newAccount.AllTransactions[0]); AllTransactions = AllTransactions.OrderByDescending(transaction => transaction.Date).ThenByDescending(transaction => transaction.ID).ToList(); success = true; } return success; } /// <summary>Deletes an account from the database.</summary> /// <param name="account">Account to be deleted</param> /// <returns>Returns true if successful</returns> internal static async Task<bool> DeleteAccount(Account account) { bool success = false; if (await DatabaseInteraction.DeleteAccount(account)) { foreach (Transaction transaction in account.AllTransactions) AllTransactions.Remove(transaction); AllAccounts.Remove(account); success = true; } return success; } /// <summary>Renames an account in the database.</summary> /// <param name="account">Account to be renamed</param> /// <param name="newAccountName">New account's name</param> /// <returns>Returns true if successful</returns> internal static async Task<bool> RenameAccount(Account account, string newAccountName) { bool success = false; string oldAccountName = account.Name; if (await DatabaseInteraction.RenameAccount(account, newAccountName)) { account.Name = newAccountName; foreach (Transaction transaction in AllTransactions) { if (transaction.Account == oldAccountName) transaction.Account = newAccountName; } success = true; } return success; } #endregion Account Manipulation #region Category Management /// <summary>Inserts a new Category into the database.</summary> /// <param name="selectedCategory">Selected Major Category</param> /// <param name="newName">Name for new Category</param> /// <param name="isMajor">Is the category being added a Major Category?</param> /// <returns>Returns true if successful.</returns> internal static async Task<bool> AddCategory(Category selectedCategory, string newName, bool isMajor) { bool success = false; if (await DatabaseInteraction.AddCategory(selectedCategory, newName, isMajor)) { if (isMajor) { AllCategories.Add(new Category( newName, new List<MinorCategory>())); } else selectedCategory.MinorCategories.Add(new MinorCategory(newName)); AllCategories = AllCategories.OrderBy(category => category.Name).ToList(); success = true; } return success; } /// <summary>Rename a category in the database.</summary> /// <param name="selectedCategory">Category to rename</param> /// <param name="newName">New name of the Category</param> /// <param name="oldName">Old name of the Category</param> /// <param name="isMajor">Is the category being renamed a Major Category?</param> /// <returns></returns> internal static async Task<bool> RenameCategory(Category selectedCategory, string newName, string oldName, bool isMajor) { bool success = false; if (await DatabaseInteraction.RenameCategory(selectedCategory, newName, oldName, isMajor)) { if (isMajor) { selectedCategory = AllCategories.Find(category => category.Name == selectedCategory.Name); selectedCategory.Name = newName; AllTransactions.Select(transaction => transaction.MajorCategory == oldName ? newName : oldName).ToList(); } else { selectedCategory = AllCategories.Find(category => category.Name == selectedCategory.Name); MinorCategory minor = selectedCategory.MinorCategories.Find(category => category.Name == oldName); minor.Name = newName; AllTransactions.Select(transaction => transaction.MinorCategory == oldName ? newName : oldName).ToList(); } AllCategories = AllCategories.OrderBy(category => category.Name).ToList(); success = true; } return success; } /// <summary>Removes a Major Category from the database, as well as removes it from all Transactions which utilize it.</summary> /// <param name="selectedCategory">Selected Major Category to delete</param> /// <returns>Returns true if operation successful</returns> internal static async Task<bool> RemoveMajorCategory(Category selectedCategory) { bool success = false; if (await DatabaseInteraction.RemoveMajorCategory(selectedCategory)) { foreach (Transaction transaction in AllTransactions) { if (transaction.MajorCategory == selectedCategory.Name) { transaction.MajorCategory = ""; transaction.MinorCategory = ""; } } AllCategories.Remove(AllCategories.Find(category => category.Name == selectedCategory.Name)); success = true; } return success; } /// <summary>Removes a Major Category from the database, as well as removes it from all Transactions which utilize it.</summary> /// <param name="selectedCategory">Selected Major Category</param> /// <param name="minorCategory">Selected Minor Category to delete</param> /// <returns>Returns true if operation successful</returns> internal static async Task<bool> RemoveMinorCategory(Category selectedCategory, string minorCategory) { bool success = false; if (await DatabaseInteraction.RemoveMinorCategory(selectedCategory, minorCategory)) { foreach (Transaction transaction in AllTransactions) { if (transaction.MajorCategory == selectedCategory.Name && transaction.MinorCategory == minorCategory) transaction.MinorCategory = ""; } selectedCategory = AllCategories.Find(category => category.Name == selectedCategory.Name); selectedCategory.MinorCategories.Remove(new MinorCategory(minorCategory)); success = true; } return success; } #endregion Category Management #region Credit Score Management /// <summary>Adds a new credit score to the database.</summary> /// <param name="newScore">Score to be added</param> /// <returns>True if successful</returns> public static Task<bool> AddCreditScore(CreditScore newScore) => DatabaseInteraction.AddCreditScore(newScore); /// <summary>Deletes a credit score from the database</summary> /// <param name="deleteScore">Score to be deleted</param> /// <returns>True if successful</returns> public static Task<bool> DeleteCreditScore(CreditScore deleteScore) => DatabaseInteraction.DeleteCreditScore(deleteScore); /// <summary>Modifies a credit score in the database.</summary> /// <param name="oldScore">Original score</param> /// <param name="newScore">Modified score</param> /// <returns>True if successful</returns> public static Task<bool> ModifyCreditScore(CreditScore oldScore, CreditScore newScore) => DatabaseInteraction.ModifyCreditScore(oldScore, newScore); #endregion Credit Score Management #region Notification Management /// <summary>Displays a new Notification in a thread-safe way.</summary> /// <param name="message">Message to be displayed</param> /// <param name="title">Title of the Notification window</param> internal static void DisplayNotification(string message, string title) => Application.Current.Dispatcher.Invoke( () => new Notification(message, title, NotificationButtons.OK, MainWindow).ShowDialog()); /// <summary>Displays a new Notification in a thread-safe way and retrieves a boolean result upon its closing.</summary> /// <param name="message">Message to be displayed</param> /// <param name="title">Title of the Notification window</param> /// <returns>Returns value of clicked button on Notification.</returns> internal static bool YesNoNotification(string message, string title) => Application.Current.Dispatcher.Invoke(() => (new Notification(message, title, NotificationButtons.YesNo, MainWindow).ShowDialog() == true)); #endregion Notification Management #region Transaction Manipulation /// <summary>Adds a transaction to an account and the database</summary> /// <param name="transaction">Transaction to be added</param> /// <param name="account">Account the transaction will be added to</param> /// <returns>Returns true if successful</returns> internal static async Task<bool> AddTransaction(Transaction transaction, Account account) { bool success = false; if (await DatabaseInteraction.AddTransaction(transaction, account)) { if (AllMonths.Any(month => month.MonthStart <= transaction.Date && transaction.Date <= month.MonthEnd.Date)) AllMonths.Find(month => month.MonthStart <= transaction.Date && transaction.Date <= month.MonthEnd.Date).AddTransaction(transaction); else { Month newMonth = new Month(new DateTime(transaction.Date.Year, transaction.Date.Month, 1), new List<Transaction>()); newMonth.AddTransaction(transaction); AllMonths.Add(newMonth); } AllMonths = AllMonths.OrderByDescending(month => month.FormattedMonth).ToList(); success = true; } else DisplayNotification("Unable to process transaction.", "Finances"); return success; } /// <summary>Gets the next Transaction ID autoincrement value in the database for the Transactions table.</summary> /// <returns>Next Transactions ID value</returns> public static Task<int> GetNextTransactionsIndex() => DatabaseInteraction.GetNextTransactionsIndex(); /// <summary>Modifies the selected Transaction in the database.</summary> /// <param name="newTransaction">Transaction to replace the current one in the database</param> /// <param name="oldTransaction">Current Transaction in the database</param> /// <returns>Returns true if successful</returns> internal static async Task<bool> ModifyTransaction(Transaction newTransaction, Transaction oldTransaction) { bool success = false; if (await DatabaseInteraction.ModifyTransaction(newTransaction, oldTransaction)) { AllTransactions[AllTransactions.IndexOf(oldTransaction)] = newTransaction; AllTransactions = AllTransactions.OrderByDescending(transaction => transaction.Date).ThenByDescending(transaction => transaction.ID).ToList(); LoadMonths(); LoadYears(); success = true; } return success; } /// <summary>Deletes a transaction from the database.</summary> /// <param name="transaction">Transaction to be deleted</param> /// <param name="account">Account the transaction will be deleted from</param> /// <returns>Returns true if successful</returns> internal static async Task<bool> DeleteTransaction(Transaction transaction, Account account) { bool success = false; if (await DatabaseInteraction.DeleteTransaction(transaction, account)) { AllTransactions.Remove(transaction); success = true; } return success; } #endregion Transaction Manipulation } }
TypeScript
UTF-8
4,164
2.921875
3
[ "Apache-2.0" ]
permissive
import CryptoSuite from '../../lib/interfaces/CryptoSuite'; import { TestPublicKey } from './TestPublicKey'; /** * A {@link CryptoSuite} used for unit testing */ export default class TestCryptoSuite implements CryptoSuite { private readonly id: number; private static called: {[id: number]: number} = {}; private static readonly ENCRYPT = 0x1; private static readonly DECRYPT = 0x2; private static readonly SIGN = 0x4; private static readonly VERIFY = 0x8; private static readonly SYMENCRYPT = 0xF; private static readonly SYMDECRYPT = 0x10; getKeyConstructors () { return { test: () => { return new TestPublicKey(); } }; } constructor () { this.id = Math.round(Math.random() * Number.MAX_SAFE_INTEGER); } private encrypt (id: number): (data: Buffer, key: object) => Promise<Buffer> { return (data, _) => { TestCryptoSuite.called[id] |= TestCryptoSuite.ENCRYPT; return Promise.resolve(data); }; } private decrypt (id: number): (data: Buffer, key: object) => Promise<Buffer> { return (data, _) => { TestCryptoSuite.called[id] |= TestCryptoSuite.DECRYPT; return Promise.resolve(data); }; } private sign (id: number): ({}, {}) => Promise<string> { return (_, __) => { TestCryptoSuite.called[id] |= TestCryptoSuite.SIGN; return Promise.resolve(''); }; } private verify (id: number): ({}, {}, {}) => Promise<boolean> { return (_, __, ___) => { TestCryptoSuite.called[id] |= TestCryptoSuite.VERIFY; return Promise.resolve(true); }; } private symEncrypt (id: number): (plaintext: Buffer, _: Buffer) => Promise<{ciphertext: Buffer, initializationVector: Buffer, key: Buffer, tag: Buffer}> { return (plaintext: Buffer, _) => { TestCryptoSuite.called[id] |= TestCryptoSuite.SYMENCRYPT; return Promise.resolve({ ciphertext: plaintext, initializationVector: Buffer.alloc(0), key: Buffer.alloc(0), tag: Buffer.alloc(0) }); }; } private symDecrypt (id: number): (ciphertext: Buffer, additionalAuthenticatedData: Buffer, initializationVector: Buffer, key: Buffer, tag: Buffer) => Promise<Buffer> { return (ciphertext: Buffer, _, __, ___, ____) => { TestCryptoSuite.called[id] |= TestCryptoSuite.SYMDECRYPT; return Promise.resolve(ciphertext); }; } /** Encryption algorithms */ getEncrypters () { return { test: { encrypt: this.encrypt(this.id), decrypt: this.decrypt(this.id) } }; } /** Signing algorithms */ getSigners () { return { test: { sign: this.sign(this.id), verify: this.verify(this.id) } }; } getSymmetricEncrypters () { return { test: { encrypt: this.symEncrypt(this.id), decrypt: this.symDecrypt(this.id) } }; } /** * Returns true when encrypt() was called since last reset() */ wasEncryptCalled (): boolean { return (TestCryptoSuite.called[this.id] & TestCryptoSuite.ENCRYPT) > 0; } /** * Returns true when decrypt() was called since last reset() */ wasDecryptCalled (): boolean { return (TestCryptoSuite.called[this.id] & TestCryptoSuite.DECRYPT) > 0; } /** * Returns true when sign() was called since last reset() */ wasSignCalled (): boolean { return (TestCryptoSuite.called[this.id] & TestCryptoSuite.SIGN) > 0; } /** * Returns true when verify() was called since last reset() */ wasVerifyCalled (): boolean { return (TestCryptoSuite.called[this.id] & TestCryptoSuite.VERIFY) > 0; } /** * Returns true when Symmetric Encrypt was called since last reset() */ wasSymEncryptCalled (): boolean { return (TestCryptoSuite.called[this.id] & TestCryptoSuite.SYMENCRYPT) > 0; } /** * Returns true when Symmetric Decrypt was called since last reset() */ wasSymDecryptCalled (): boolean { return (TestCryptoSuite.called[this.id] & TestCryptoSuite.SYMDECRYPT) > 0; } /** * Resets visited flags for encrypt, decrypt, sign, and verify */ reset () { TestCryptoSuite.called[this.id] = 0; } }
Python
UTF-8
73,721
2.796875
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # weather.py # A.1.0 '''weather script for Pontis Weather Station ''' # Rev A.1.0 - Field test release 10/10/19 import time from datetime import datetime import RPi.GPIO as GPIO import math import random # files required in folder import I2C_LCD_driver3 import tsl2591 import HIH6121 import RPiUtilities import config import EnglishSpanish class stationData(): '''class container for data used throughout system and recorded note: variables only used within timing, not recorded, are part of the weatherStation class not the stationData sensorError{TempError, RHError, LuxError} periodWeatherVariables{tempCurrent, RHCurrent, windAvrPeriod, windGust, windCurrent, windList, solarLux} ''' def __init__(self): self.clearSensorError() def clearSensorError(self): self.sensorError = { 'TempError': '', 'RHError': '', 'LuxError': '' } self.sensorOrder = ('TempError', 'RHError', 'LuxError') def resetPeriodVariables(self): ''' sets the period variables list note: period is time for recording weatherData and designated in timing note: although rainTotal is recorded every period, it is cleared daily so is part of dayWeatherVariables[] ''' tempCurrent = 0 RHCurrent = 0 windAvrPeriod = 0 windGust = 0 windCurrent = 0 solarLux = 0 self.periodWeatherVariables = { 'tempCurrent': tempCurrent, 'RHCurrent': RHCurrent, 'windAvrPeriod': windAvrPeriod, 'windGust': windGust, 'windCurrent': windCurrent, 'solarLux': solarLux } self.periodOrder = ('tempCurrent', 'RHCurrent', 'rainTotalDay', 'windAvrPeriod', 'windGust', 'solarLux') self.periodLabels = ('Temp', 'RH', 'Rain total (mm)', 'Wind avr', 'Wind gust', 'Solar', 'Water loss (mm)', 'Cum loss (mm)') def printPeriodVariables(self): print('periodVariables: ', end='') for datum in self.periodOrder: if datum == 'rainTotalDay': print('{:.2f}'.format(self.dayWeatherVariables['rainTotalDay']), ' / ', end='') else: print('{:.2f}'.format(self.periodWeatherVariables[datum]), ' / ', end='') print('') def resetDayVariables(self, forceDefaults, ignoreSomeDefaults, ignoreSomeBackups): '''checks SD card for backup file, uses, or sets defaults - forceDefaults is used at midnight to clear variables, it precludes using the backup file values - ignoreSomeDefaults allows some variables to stay when others are cleared - ignoreSomeBackups is not currently used ''' useDefaults = True # check SD for weatherDataBackup filePathName = config.SDFilePath + '/' + 'weatherDataBackup' try: with open(filePathName, newline='') as file: # read full file fileText = file.read() # split into lines lines = fileText.split('\n') # import backupData as a string backupData = lines[0] if len(backupData) < 12 or backupData.isspace() == True: useDefaults = True else: # check if backupData is from today today = datetime.now().strftime('%Y-%m-%d') backupDate = backupData[:10] print(today, ' / ', backupDate) if backupDate == today: useDefaults = False except FileNotFoundError: useDefaults = True if forceDefaults is True: useDefaults = True if useDefaults is True: print('useDefaults') # assign default values tempMax = 0 tempMin = 100 RHMax = 0 RHMin = 100 rainTotalDay = 0 windAvrMax = 0 windAvrMin = 100 windGustMax = 0 solarTotalDay = 0 if ignoreSomeDefaults is False: self.waterLossCumulative = 0 else: print('use backupData') # clip the date and time off backup data and convert to list of data backupDataList = backupData[17:].split(',') #use data from backup tempMax = int(backupDataList[0]) if(tempMax > 100 or tempMax < -32): tempMax = 0 tempMin = int(backupDataList[1]) if(tempMin > 100 or tempMin < -32): tempMin = 100 RHMax = int(backupDataList[2]) if(RHMax > 100 or RHMax < 0): RHMax = 0 RHMin = int(backupDataList[3]) if(RHMin > 100 or RHMin < 0): RHMin = 100 rainTotalDay = float(backupDataList[4]) if(rainTotalDay > 100 or rainTotalDay < 0): rainTotalDay = 0 windAvrMax = int(backupDataList[5]) if(windAvrMax > 200 or windAvrMax < 0): windAvrMax = 0 windAvrMin = int(backupDataList[6]) if(windAvrMin > 200 or windAvrMin < 0): windAvrMin = 100 windGustMax = int(backupDataList[7]) if(windGustMax > 200 or windGustMax < 0): windGustMax = 0 solarTotalDay = float(backupDataList[8]) if(solarTotalDay > 100000 or solarTotalDay < 0): solarTotalDay = 0 if ignoreSomeBackups is False: self.waterLossCumulative = float(backupDataList[9]) if(self.waterLossCumulative > 1000 or self.waterLossCumulative < 0): self.waterLossCumulative = 0 self.dayWeatherVariables = { 'tempMax': tempMax, 'tempMin': tempMin, 'RHMax': RHMax, 'RHMin': RHMin, 'rainTotalDay': rainTotalDay, 'windAvrMax': windAvrMax, 'windAvrMin': windAvrMin, 'windGustMax': windGustMax, 'solarTotalDay': solarTotalDay } self.dayOrder = ('tempMax', 'tempMin', 'RHMax', 'RHMin', 'rainTotalDay', 'windAvrMax', 'windAvrMin', 'windGustMax', 'solarTotalDay') self.dayLabels = ('Temp max', 'Temp min', 'RH max', 'RH min', 'Rain total', 'Wind max', 'Wind min', 'Wind gust', 'Solar total') def writeDataBackupSD(self): ''' write weather backup file (one line) ''' filePathName = config.SDFilePath + '/' + 'weatherDataBackup' with open(filePathName, 'w') as file: dateTimeNow = '{:%Y-%m-%d:%_H:%M}'.format(datetime.now()) file.write(dateTimeNow + ',') # write data from dayWeatherVariables for datum in self.dayOrder: file.write(str('{:.0f}'.format(self.dayWeatherVariables[datum])) + ',') file.write(str('{:.3f}'.format(self.waterLossCumulative))) file.write('\n') class weatherStation(): def __init__(self): '''set up initial parameters and sensors ''' self.debugON = True self.debug2ON = config.debug2 #### SET KEY OPERATING PARAMETERS #### self.historyFileName = config.historyFileName self.dataFileName = config.dataFileName self.comment = '' #### UI - Display, LED, BUTTONS #### # initialize rpi gpio GPIO.setmode(GPIO.BOARD) self.powerLEDpin = 8 self.powerOFFinputpin = 10 self.powerOFFholdpin = 12 # Green pulse LED on Jim Hawkins board GPIO.setup(self.powerLEDpin, GPIO.OUT, initial=GPIO.LOW) # buttonState: 0 is no button pressed, 99 is any button when backlight is off, (1-3) button pressed self.buttonState = 0 # buttonAction indicates whether the requested action is complete (1) or yet to be completed (0) self.buttonAction = 0 # buttons self.pinButton1 = 33 self.pinButton2 = 31 self.pinButton3 = 29 GPIO.setup([self.pinButton1, self.pinButton2, self.pinButton3], GPIO.IN) # debounce time in milliseconds self.buttonDebounce = 300 #### INTERRUPTS - BUTTONS #### GPIO.add_event_detect(self.pinButton1, GPIO.RISING, bouncetime=self.buttonDebounce, callback=self.reactToButton) GPIO.add_event_detect(self.pinButton2, GPIO.RISING, bouncetime=self.buttonDebounce, callback=self.reactToButton) GPIO.add_event_detect(self.pinButton3, GPIO.RISING, bouncetime=self.buttonDebounce, callback=self.reactToButton) # backlight timer (backlightOFFTime is also used for screen time outs) self.backlightTimer = 0 self.backlightOffTime = config.backlightOffTime # LCD self.pollingDelay = .100 # this delays the polling of constant functions self.restartLCD() #### START ROUTINES #### self.usbPath = RPiUtilities.findUSB() # check for no USB then error if self.usbPath is None: self.comment = self.comment + 'USB/' self.mylcd.lcd_display_string('No USB Drive!', 1, 0) self.mylcd.lcd_display_string('replace USB', 2, 2) self.mylcd.lcd_display_string('and Reboot', 3, 0) time.sleep(5) self.MXscreenSelect(8) # goes to MX screen then to reboot if self.debugON == True: print('usbPath: ', self.usbPath) # Display start screen to use initialization time self.startScreen(config.updateFilePath) #### WEATHER VARIABLES #### data.resetPeriodVariables() data.resetDayVariables(False, False, False) self.comment = '/' # windAvrCount used to calculate windAvr self.windAvrCount = 0 #### START SENSORS data.clearSensorError() # TSL2561 light sensor try: self.lightSensor = tsl2591.Tsl2591() except OSError: if self.debugON == True: print('no light sensor detected') self.lightSensor = 0 data.updateLuxError('no Solar/') # HIH6121 temp and humidity self.tempSensor = HIH6121.HIH6121sensor() self.readTempRH() if self.debugON == True: print('data.sensorError: ', data.sensorError.values()) if data.sensorError['TempError'] == '' and\ data.sensorError['RHError'] == '' and\ data.sensorError['LuxError'] == '': if self.debugON == True: print('no errors at startup') self.mylcd.lcd_display_string(EnglishSpanish.getWord('no errors'), 3, 0) else: self.comment = self.comment + data.sensorError['TempError']\ + data.sensorError['RHError'] + data.sensorError['LuxError'] # Battery Low Power Monitor (Captain Smollett) self.lowBattery = 0 GPIO.setup(self.powerOFFinputpin, GPIO.IN) GPIO.setup(self.powerOFFholdpin, GPIO.OUT) GPIO.output(self.powerOFFholdpin, GPIO.HIGH) #latch power on #### INTERRUPTS - SENSORS #### # anemometer self.windCounter = 0 GPIO.setup(18, GPIO.IN) GPIO.add_event_detect(18, GPIO.RISING, bouncetime=self.buttonDebounce, callback=self.windCount) self.rainCounter = 0 self.rainThisPeriod = 0 GPIO.setup(16, GPIO.IN) GPIO.add_event_detect(16, GPIO.RISING, bouncetime=self.buttonDebounce, callback=self.rainCount) #### Set Up Data Files #### self.initializeDataFiles() #### START SCREEN ERROR DISPLAY #### if self.comment != '/': self.mylcd.lcd_display_string(self.comment, 3, 0) # Animation for 8 second delay self.runFunGrowAnimation(1, 8, 6, 4) time.sleep(4) # Clear comments, sensor errors will re-add during a read self.comment = 'power up/' if self.usbPath is None: self.systemError('NO USB or Ejected', 'Re-Insert USB') # LCD - first mainscreen self.readTempRH() self.mylcd.lcd_clear() self.mainScreen() self.mainScreenRefresh() # DEV reset anenometer just before timer self.windCounter = 0 if self.debugON == True: data.printPeriodVariables() #### TIMER FUNCTIONS #### def runTimer(self): '''main operating loop for weather station ''' # set timer variables lastSecond = 0 lastFloatSecond = 0 lastMinute = 0 yesterday = datetime.now().strftime('%Y-%m-%d') self.readTempRH() self.readSolar() runWeather = True while runWeather is True: #### CONTINUOUS POLLING #### # too fast of polling causes LCD problems, so this sets the timing thisSecond = float(datetime.now().strftime('%S.%f')) thisMinute = int(datetime.now().strftime('%M')) today = datetime.now().strftime('%Y-%m-%d') if lastFloatSecond + self.pollingDelay >= 60: lastFloatSecond = 0 #### PACED POLLING #### if thisSecond > lastFloatSecond + self.pollingDelay: if self.debug2ON == True: print(datetime.now().strftime('%H:%M:%S.%f')) # index the timer lastFloatSecond = thisSecond # check and react to buttonState if self.buttonState != 0 and self.buttonAction == 0: if self.buttonState == 1: self.buttonAction = 1 # take action self.rainScreen() self.irrigation() self.Iirrigated() # refresh LCD self.mylcd.lcd_clear() self.mainScreen() self.clockRefresh() self.mainScreenRefresh() # set for polling lastFloatSecond = float(datetime.now().strftime('%S.%f')) elif self.buttonState == 2: self.buttonAction = 1 # take action self.MXscreenSelect(0) # refresh LCD self.mylcd.lcd_clear() self.mainScreen() self.clockRefresh() self.mainScreenRefresh() # set for polling lastFloatSecond = float(datetime.now().strftime('%S.%f')) elif self.buttonState == 3: self.buttonAction = 1 pass elif self.buttonState == 99: self.backlightON() else: pass # Require buttons to be released before next press self.buttonCheckRelease() if self.debug2ON == True: print('before Every Second') #### EVERY SECOND ACTIONS #### thisSecond = int(thisSecond) if thisSecond != lastSecond: # flash the pulse green LED on JH board, all of the time) if thisSecond % 2 == 0: GPIO.output(self.powerLEDpin, GPIO.LOW) else: GPIO.output(self.powerLEDpin, GPIO.HIGH) if self.debug2ON == True: print('after pulse') # turn backlight off (1 indicates ON) if self.backlightTimer < self.backlightOffTime: # Display actions self.backlightTimer += 1 # flash the pulse (on LCD) if thisSecond % 2 == 0: # self.mylcd.lcd_display_string('*', 1, 19) self.mylcd.lcd_display_string('', 1, 19) self.mylcd.lcd_write_char(self.custom['flower']) else: self.mylcd.lcd_display_string(' ', 1, 19) elif self.backlightTimer == self.backlightOffTime: self.mylcd.backlight(0) self.backlightTimer += 1 else: pass if self.debug2ON == True: print('end every second') #### EVERY 5 SECONDS #### if thisSecond % 5 == 0 or thisSecond == 0: self.readWind(5) self.readSolar() if self.debug2ON == True: print('every 5 second') # rain total counts (resets rainCounter) workingRainIncrement = (self.rainCounter * config.rainGageVolume) data.dayWeatherVariables['rainTotalDay'] = data.dayWeatherVariables['rainTotalDay'] + workingRainIncrement self.rainThisPeriod = self.rainThisPeriod + workingRainIncrement self.rainCounter = 0 # Total solar for the day (kilojoules) if data.sensorError['LuxError'] != 'no Solar/': solarEnergyK = (config.luminousEff * data.periodWeatherVariables['solarLux'] * 5) / 1000 data.dayWeatherVariables['solarTotalDay'] = data.dayWeatherVariables['solarTotalDay'] + solarEnergyK # Display actions if self.backlightTimer < self.backlightOffTime: self.mainScreen() self.mainScreenRefresh() # Low Battery check if(GPIO.input(10) == False): if self.debugON == True: print('low battery ',self.lowBattery) self.lowBattery = self.lowBattery + 1 self.batteryCheck() if self.debug2ON == True: print('end every 5 second') #### EVERY 30 SECONDS #### if thisSecond == 30 or thisSecond == 0: if self.debug2ON == True: print('every 30 second') self.readTempRH() lastSecond = thisSecond if self.debug2ON == True: print('end full every second') #### MINUTE ACTIONS #### if thisMinute != lastMinute: #### 30 MINUTE ACTIONS #### if self.debug2ON == True: print('every minute') if thisMinute % 30 == 0 or thisMinute == 0: ## reset lowBattery (this makes it have to go over 3 within 30 minutes) self.lowBattery = 0 if self.debug2ON == True: print('end every minute') #### ON THE HOUR ACTIONS #### if thisMinute == 0: if self.debug2ON == True: print('every hour') if self.debugON == True: print('record weatherData at ', '{:%_H:%M}'.format(datetime.now())) if self.debugON == True: data.printPeriodVariables() print('rainThisPeriod: ', self.rainThisPeriod) ##################################################### #### PERFORM PERIOD ACTIONS ######################### ##################################################### if self.debug2ON == True: print('period actions') # use Penman-Monteith to calculate water loss during this period workingPrintFactor = False if self.debugON == True: workingPrintFactor = True waterLoss = self.penmanMonteith( data.periodWeatherVariables['tempCurrent'], data.periodWeatherVariables['RHCurrent'], data.periodWeatherVariables['windAvrPeriod'], data.periodWeatherVariables['solarLux'], workingPrintFactor) # add this waterloss to the cumulative water loss data.waterLossCumulative = data.waterLossCumulative + waterLoss # subtract rain during this period from waterLoss data.waterLossCumulative = data.waterLossCumulative - self.rainThisPeriod self.rainThisPeriod = 0 # limit water loss to when soil is fully dry if data.waterLossCumulative > config.maximumDry: data.waterLossCumulative = config.maximumDry # water loss can't be negative (soil can only be saturated) if data.waterLossCumulative < config.maximumAbsorption: data.waterLossCumulative = config.maximumAbsorption if self.debugON == True: print('waterLoss: ', waterLoss, ' / ', data.waterLossCumulative) # Record weather variables to weatherData self.writePeriodDataLine(waterLoss) ## Clear averaging variables data.periodWeatherVariables['windAvrPeriod'] = 0 self.windAvrCount = 0 data.periodWeatherVariables['windGust'] = 0 if self.debug2ON == True: print('end period actions') #### END PERIOD ACTIONS #### lastMinute = thisMinute #### MIDNIGHT ACTIONS #### if today != yesterday: if self.debug2ON == True: print('midnight actions') self.writeDailySummary(yesterday) data.resetDayVariables(True, True, True) self.rainCounter = 0 yesterday = today ############################################################## ############################################################## #### WATER LOSS and IRRIGATION #### def penmanMonteith(self, hourTemp, hourRH, hourWindAvr, hourLux, printFactor): ''' Calculates mm water lost in 1 hour ONLY WORKS FOR 1 HOUR PERIOD ''' if printFactor is True: print(hourTemp, 'deg C, ', hourRH, '% ', hourWindAvr, 'km/hr, ', hourLux, 'Lux') # Solar Radiation solarRadiation = hourLux * config.luminousEff * (3600/1e6) # (MJ/m^2-hr) outgoingRadiation = 0 # equation 39 but am assuming this is small netRadiation = ((1 - .23) * solarRadiation) - outgoingRadiation # equation 38 gives the .23 constant if printFactor is True: print('netRadiation: ', '{:3.6f}'.format(netRadiation)) #Ground Heat Flux if hourLux > 3000: soilHeatFlux = .1 * netRadiation # Daytime Gn MJ/m^-hr else: soilHeatFlux = .5 * netRadiation # Night Gn MJ/m^-hr #psychometric constant is .067 at sea level and .060 at 3000 feet in kPa/deg C psychometricConstant = .0665 # (kPa/deg C) # e sub zero(T) saturation vapor pressure at air temp T saturationVaporPressure = .6108 * (math.exp((17.27 * hourTemp)/(hourTemp + 273))) # (kPa/deg C) # saturation slope vapor pressure at air temperature saturationVaporSlope = (4098 * saturationVaporPressure) / ((hourTemp +237.3)**2) # KPa/deg C vaporPressure = saturationVaporPressure * (hourRH/100) # e sub a kPa windSpeed = hourWindAvr * .278 # wind speed converted to m/sec # Penman Monteith Equation in three parts then the whole solarComponent = ((.408 * saturationVaporSlope) * (netRadiation - soilHeatFlux)) if printFactor is True: print('solar component: ', '{:4.3f}'.format(solarComponent)) windComponent = (psychometricConstant * (37 / (hourTemp + 273))) * windSpeed * (saturationVaporPressure - vaporPressure) if printFactor is True: print('wind component: ', '{:4.3f}'.format(windComponent)) workingDenominator = saturationVaporSlope + (psychometricConstant * (1 + (.34 * windSpeed))) if printFactor is True: print('denominator: ', '{:4.3f}'.format(workingDenominator)) if printFactor is True: print('') # final Penman-Monteith evapoTranspiration = (solarComponent + windComponent) / workingDenominator return evapoTranspiration # mm of water lost in that one hour #### POWER MANAGEMENT #### def batteryCheck(self): '''uses Capt Smollett power management board - latches power on then shuts off when below low battery - Capt Smollett incorporates delay in power off ''' if(self.lowBattery > 3): if self.debugON == True: print('low battery shutdown') self.mylcd.lcd_clear() self.mylcd.lcd_display_string(EnglishSpanish.getWord('Low Battery Shutdown'), 1, 0) #### Write last line of data including lowBattery comment self.comment = self.comment + 'LOW BATTERY SHUTDOWN/' self.writePeriodDataLine(0) time.sleep(5) GPIO.output(self.powerOFFholdpin, GPIO.LOW) #turn power off GPIO.cleanup() RPiUtilities.shutdownRPI() #### DATA FUNCTIONS #### def initializeDataFiles(self): '''check for files on SD card and USB, add new file if required ''' # check USB for weatherHistory, create if not there try: filePathName = self.usbPath + '/' + self.historyFileName open(filePathName) except FileNotFoundError: try: with open(filePathName, 'w') as file: file.write('DateTime' + ',') for label in data.dayLabels: file.write(label + ',') #file.write('DateTime,Temp max,Temp min,RH max,RH min,Rain total, Wind max, Wind min, Wind gust,solar') file.write('\n') except OSError: self.systemError('wrong USB', 'format') # check USB for weatherData, create if not there try: filePathName = self.usbPath + '/' + self.dataFileName open(filePathName) except FileNotFoundError: try: with open(filePathName, 'w') as file: file.write('DateTime' + ',') for label in data.periodLabels: file.write(label + ',') #file.write('DateTime,Temp,RH,Wind avr,Wind gust,solar,Rain total') file.write('\n') except OSError: self.systemError('wrong USB', 'format') def writePeriodDataLine(self, periodWaterLoss): '''writes one line of data to weatherData.CSV ''' # update wind min and max if data.periodWeatherVariables['windAvrPeriod'] > data.dayWeatherVariables['windAvrMax']: data.dayWeatherVariables['windAvrMax'] = data.periodWeatherVariables['windAvrPeriod'] if data.periodWeatherVariables['windAvrPeriod'] < data.dayWeatherVariables['windAvrMin']: data.dayWeatherVariables['windAvrMin'] = data.periodWeatherVariables['windAvrPeriod'] # create comments for sensor errors self.comment = self.comment + data.sensorError['TempError'] + data.sensorError['RHError'] + data.sensorError['LuxError'] data.writeDataBackupSD() filePathName = self.usbPath + '/' + self.dataFileName try: open(filePathName) except FileNotFoundError: self.systemError(self, 'No USB data file', 'Check USB and reboot') else: with open(filePathName, 'a') as file: dateTimeNow = '{:%Y-%m-%d:%_H:%M}'.format(datetime.now()) file.write(dateTimeNow + ',') # write data from periodWeatherVariables for datum in data.periodOrder: if datum == 'rainTotalDay': file.write(str('{:.0f}'.format(data.dayWeatherVariables['rainTotalDay'])) + ',') else: file.write(str('{:.0f}'.format(data.periodWeatherVariables[datum])) + ',') # waterLoss and cumulative file.write(str('{:.3f}'.format(periodWaterLoss)) + ',') file.write(str('{:.3f}'.format(data.waterLossCumulative)) + ',') # comment file.write(str(self.comment) + ',') # clear comment self.comment = '/' file.write('\n') def writeDailySummary(self, yesterday): ''' writes one line to weather history files ''' filePathName = self.usbPath + '/' + self.historyFileName try: open(filePathName) except FileNotFoundError: self.systemError(self, 'No USB history file', 'Check USB and reboot') else: with open(filePathName, 'a') as file: file.write(yesterday + ',') # write data from dayWeatherVariables for datum in data.dayOrder: file.write(str('{:.0f}'.format(data.dayWeatherVariables[datum])) + ',') file.write('\n') def getFileSummary(self, fileName): '''get summary of file for MX screen ''' filePathName = self.usbPath + '/' + fileName # count rows and get last line with open(filePathName,'r') as file: opened_file = file.readlines() rowsInFile = len(opened_file) - 1 # subtract 1 for header lastLine = opened_file[-1].split(',')[0] if fileName == self.dataFileName: dataFileMessage = str(rowsInFile) + 'L ' + lastLine[5:19] else: dataFileMessage = str(rowsInFile) + 'L ' + lastLine[:14] return dataFileMessage def getRainList(self, lengthRainList): filePathName = self.usbPath + '/weatherHistory.csv' rainList = [] # count rows and get last line with open(filePathName,'r') as file: opened_file = file.readlines() rowsInFile = len(opened_file) - 1 # subtract 1 for header for i, row in enumerate(reversed(opened_file)): if i > (lengthRainList - 1): return rainList if i < rowsInFile: rainList.append(row.split(',')[5]) else: rainList.append('ND') if i < lengthRainList: for j in range ((lengthRainList - 1) - i): rainList.append('ND') return rainList #### SENSOR CALLS AND WEATHER FUNCTIONS #### def readWind(self, timeUnit): '''calculate wind speed, update history, display on LCD ''' # convert revelutions to distance (meters) windDist = self.windCounter * 3.1415 * (2 * config.anemometerRadius) * .00001 # convert distance to speed (km/hr) windCurrent = windDist / (timeUnit / 3600) # calculate running average data.periodWeatherVariables['windAvrPeriod'] = ((data.periodWeatherVariables['windAvrPeriod'] * self.windAvrCount) + windCurrent) / (self.windAvrCount + 1) self.windAvrCount +=1 # check for gust if windCurrent > data.periodWeatherVariables['windGust']: data.periodWeatherVariables['windGust'] = windCurrent if data.periodWeatherVariables['windGust'] > data.dayWeatherVariables['windGustMax']: data.dayWeatherVariables['windGustMax'] = data.periodWeatherVariables['windGust'] self.windCounter = 0 data.periodWeatherVariables['windCurrent'] = windCurrent def readTempRH(self): '''reads tempurature, humidity, sets variables, determines min/max ''' try: RHCurrent, tempCurrent, tempF = self.tempSensor.returnTempRH() except OSError: if self.debugON == True: print('tempSensor OSError') tempCurrent = 0 if data.sensorError['TempError'] != 'no Temp/': self.comment = self.comment + 'temp or RH sensor fail/' data.sensorError['TempError'] = 'no Temp/' RHCurrent = 0 data.sensorError['RHError'] = 'no RH/' # React to no sensor read (NoneType) if RHCurrent is None: RHCurrent = 0 data.updateRHError('no RH/') else: if RHCurrent > data.dayWeatherVariables['RHMax']: data.dayWeatherVariables['RHMax'] = RHCurrent if RHCurrent < data.dayWeatherVariables['RHMin']: data.dayWeatherVariables['RHMin'] = RHCurrent if tempCurrent is None: tempCurrent = 0 data.sensorError['TempError'] = 'no Temp/' else: if tempCurrent > data.dayWeatherVariables['tempMax']: data.dayWeatherVariables['tempMax'] = tempCurrent if tempCurrent < data.dayWeatherVariables['tempMin']: data.dayWeatherVariables['tempMin'] = tempCurrent data.periodWeatherVariables['tempCurrent'] = tempCurrent data.periodWeatherVariables['RHCurrent'] = RHCurrent def readSolar(self): '''reads solar sensor ''' if self.lightSensor != 0: full, ir = self.lightSensor.get_full_luminosity() # read raw values (full spectrum and ir spectrum) solarLux = self.lightSensor.calculate_lux(full, ir) # convert raw values to lux data.sensorError['LuxError'] = '' else: solarLux = 0 data.sensorError['LuxError'] = 'no Solar/' data.periodWeatherVariables['solarLux'] = solarLux #### SCREEN FUNCTIONS #### def restartLCD(self): '''re-initializes LCD, can be used at various times in case there was an ESD event at the LCD ''' self.mylcd = I2C_LCD_driver3.lcd() # turn backlight on (1 indicates ON) if self.backlightTimer < self.backlightOffTime: self.mylcd.backlight(1) else: self.mylcd.backlight(0) customWeatherCharacters = [ # Char 0 - flower [0x4, 0xa, 0x4, 0x0, 0x0, 0x1f, 0xe, 0xe], # Char 1 - water drop [0x0, 0x4, 0x4, 0xa, 0x11, 0x11, 0x11, 0xe], # Char 2 - maiz 1 [0x0,0x0,0x0,0x0,0x0,0x0, 0x4, 0x1f], # Char 3 - maiz 2 [0x0,0x0, 0x0,0x4, 0xc, 0x6, 0x4, 0x1f], # Char 4 - maiz 3 [0x0, 0x4, 0xc, 0x5, 0x16, 0xc, 0x4, 0x1f], # Char 5 - maiz 4 [0x4, 0xc, 0x5, 0x16, 0xd, 0x6, 0x4, 0x1f], # Char 6 - up arrow [0x0, 0x4, 0xe, 0x1f, 0x0, 0x1f, 0x0, 0x0], # Char 7 - down arrow [0x0, 0x0, 0x1f, 0x0, 0x1f, 0xe, 0x4, 0x0] ] self.custom = { 'flower': 0, 'water drop': 1, 'maiz1': 2, 'maiz2': 3, 'maiz3': 4, 'maiz4': 5, 'up arrow': 6, 'down arrow': 7} # load custom characters self.mylcd.lcd_load_custom_chars(customWeatherCharacters) def startScreen(self, programFilePathName): '''screen during startup then goes away ''' self.mylcd.lcd_clear() self.mylcd.lcd_display_string('Pontis', 1, 0) self.mylcd.lcd_display_string(EnglishSpanish.getWord('Weather Station'), 2, 0) # get software rev from weather.py file swNow, swNew = self.getSWrev(config.updateFilePath) message = 's/w ' + swNow self.mylcd.lcd_display_string(message, 4, 0) def runGrowAnimation(self, line, space, repeats, totalTime): '''animation of plants growing in unison ''' for plant in ('maiz1', 'maiz2', 'maiz3', 'maiz4'): self.mylcd.lcd_display_string(' ', line, space) for spaceGap in range(0, repeats): thisSpace = space + (spaceGap * 2) self.mylcd.lcd_display_string('', line, thisSpace) self.mylcd.lcd_write_char(self.custom[plant]) time.sleep(totalTime/4) def runFunGrowAnimation(self, line, space, repeats, totalTime): '''animation of plants growing randomly ''' plant = [None] * 10 for plantNumber in range (0, repeats): plant[plantNumber] = 1; thisSpace = space + (plantNumber * 2) self.mylcd.lcd_display_string('', line, thisSpace) self.mylcd.lcd_write_char(self.custom['maiz1']) grow = True while grow is True: whichPlant = random.randint(0, repeats - 1) if(plant[whichPlant] < 4): plant[whichPlant] +=1 thisSpace = space + (whichPlant * 2) self.mylcd.lcd_display_string('', line, thisSpace) if(plant[whichPlant] == 2): self.mylcd.lcd_write_char(self.custom['maiz2']) elif(plant[whichPlant] == 23): self.mylcd.lcd_write_char(self.custom['maiz3']) else: self.mylcd.lcd_write_char(self.custom['maiz4']) time.sleep(totalTime/12) else: workingTest = 0 for plantNumber in range (0, repeats): if(plant[plantNumber] < 4): pass else: workingTest += 1 if workingTest >= repeats: grow = False def mainScreen(self): '''writes the main screen on LCD minus the variables ''' # Line 1 date self.mylcd.lcd_display_string('{:%b %d}'.format(datetime.now()), 1, 0) # Line 4 navigation self.mylcd.lcd_display_string('', 4, 0) self.mylcd.lcd_write_char(127) self.mylcd.lcd_display_string(EnglishSpanish.getWord("page"), 4, 2) self.mylcd.lcd_display_string('MX ', 4, 16) self.mylcd.lcd_write_char(126) def clockRefresh(self): '''LCD prints clock display ''' self.mylcd.lcd_display_string('{:%_I:%M %p}'.format(datetime.now()), 1, 10) def mainScreenRefresh(self): ''' writes the temp and RH lines with data ''' # Time display self.mylcd.lcd_display_string('{:%_I:%M %p}'.format(datetime.now()), 1, 10) # Temp display if data.sensorError['TempError'] == 'no Temp/': self.mylcd.lcd_display_string('NT', 2, 0) self.mylcd.lcd_write_char(223) self.mylcd.lcd_display_string('C ', 2, 3) else: self.mylcd.lcd_display_string('{:2.0f}'.format(data.periodWeatherVariables['tempCurrent']), 2, 0) self.mylcd.lcd_write_char(223) self.mylcd.lcd_display_string('C ', 2, 3) # RH display if data.sensorError['RHError'] == 'no RH/': self.mylcd.lcd_display_string('NR', 2, 6) self.mylcd.lcd_display_string('% ', 2, 8) else: self.mylcd.lcd_display_string('{:2.0f}'.format(data.periodWeatherVariables['RHCurrent']), 2, 6) self.mylcd.lcd_display_string('% ', 2, 8) # Wind Display self.mylcd.lcd_display_string('{:3.0f}'.format(data.periodWeatherVariables['windCurrent']), 2, 11) self.mylcd.lcd_display_string(' km/h', 2, 14) # Rain Display self.mylcd.lcd_display_string('{:5.0f}'.format(data.dayWeatherVariables['rainTotalDay']), 3, 0) self.mylcd.lcd_display_string(' mm', 3, 5) # Solar Display if data.sensorError['LuxError'] != 'no Solar/': self.mylcd.lcd_display_string('{:5.0f}'.format(data.periodWeatherVariables['solarLux']), 3, 10) else: self.mylcd.lcd_display_string(' NS', 3, 10) self.mylcd.lcd_display_string('lux', 3, 16) # Irrigation water drops if data.waterLossCumulative >= 2: self.mylcd.lcd_display_string('', 4, 9) self.mylcd.lcd_write_char(self.custom['water drop']) if data.waterLossCumulative >= 4: self.mylcd.lcd_display_string('', 4, 10) self.mylcd.lcd_write_char(self.custom['water drop']) if data.waterLossCumulative >= 6: self.mylcd.lcd_display_string('', 4, 11) self.mylcd.lcd_write_char(self.custom['water drop']) if data.waterLossCumulative >= 8: self.mylcd.lcd_display_string('', 4, 12) self.mylcd.lcd_write_char(self.custom['water drop']) if data.waterLossCumulative >= 12: self.mylcd.lcd_display_string('', 4, 13) self.mylcd.lcd_write_char(self.custom['water drop']) def rainScreen(self): '''Rain screen displays previous week's rain ''' sixDayRainList = self.getRainList(6) self.buttonState = 0 self.mylcd.lcd_clear() self.mylcd.lcd_display_string(EnglishSpanish.getWord('Rain (mm)'), 1, 0) self.mylcd.lcd_display_string(EnglishSpanish.getWord('Today'), 2, 0) self.mylcd.lcd_display_string('{:4.0f}'.format(data.dayWeatherVariables['rainTotalDay']), 2, 4) self.mylcd.lcd_display_string(EnglishSpanish.getWord('Ystrdy'), 2, 10) self.mylcd.lcd_display_string(sixDayRainList[0], 2, 17) self.mylcd.lcd_display_string(sixDayRainList[1], 3, 0) self.mylcd.lcd_display_string(sixDayRainList[2], 3, 6) self.mylcd.lcd_display_string(sixDayRainList[3], 3, 12) self.mylcd.lcd_display_string(sixDayRainList[4], 3, 17) self.mylcd.lcd_display_string('', 4, 0) self.mylcd.lcd_write_char(127) self.mylcd.lcd_display_string(EnglishSpanish.getWord("page"), 4, 2) # XXXX DEV XXXX self.mylcd.lcd_display_string('{:2.3f}'.format(data.waterLossCumulative), 4, 12) lastSecond = 0 lastFloatSecond = 0 screenTimer = 0 i = True while i is True: #### CONTINUOUS POLLING #### # too fast of polling causes LCD problems, so this sets the timing thisSecond = float(datetime.now().strftime('%S.%f')) if lastFloatSecond + self.pollingDelay >= 60: lastFloatSecond = 0 if thisSecond > lastFloatSecond + self.pollingDelay: # index the timer lastFloatSecond = thisSecond # check and react to buttonState if self.buttonState != 0 and self.buttonAction == 0: if self.buttonState == 1: self.buttonAction = 1 screenTimer = 0 if self.debugON == True: print('exit rain screen') i = False # set for polling lastFloatSecond = float(datetime.now().strftime('%S.%f')) elif self.buttonState == 2: self.buttonAction = 1 screenTimer = 0 pass elif self.buttonState == 3: self.buttonAction = 1 screenTimer = 0 pass else: pass # Require buttons to be released before next press self.buttonCheckRelease() #### EVERY SECOND FUNCTIONS AND SCREEN TIMEOUT #### # use int of the float thisSecond if int(thisSecond) != lastSecond: # screen time out if screenTimer > self.backlightOffTime: i = False lastSecond = int(thisSecond) screenTimer += 1 def irrigation(self): '''Irrigation screen, runs through them sequentially ''' self.buttonState = 0 self.mylcd.lcd_clear() irrigationScreenNumber = 0 irrigationScreenList = ( 'Beans (mm)', 'Beans (l)', 'Corn (mm)', 'Corn (l)' ) # line 1 is displayed below as it changes with crops self.mylcd.lcd_display_string('', 2, 0) self.mylcd.lcd_write_char(self.custom['maiz1']) self.mylcd.lcd_display_string('', 2, 8) self.mylcd.lcd_write_char(self.custom['maiz2']) self.mylcd.lcd_display_string('', 3, 0) self.mylcd.lcd_write_char(self.custom['maiz3']) self.mylcd.lcd_display_string('', 3, 8) self.mylcd.lcd_write_char(self.custom['maiz4']) self.mylcd.lcd_display_string('', 4, 0) self.mylcd.lcd_write_char(127) self.mylcd.lcd_display_string(EnglishSpanish.getWord("page"), 4, 2) # initialize with first screen self.irrigationCropRefresh(irrigationScreenList[irrigationScreenNumber]) lastSecond = 0 lastFloatSecond = 0 screenTimer = 0 i = True while i is True: #### CONTINUOUS POLLING #### # too fast of polling causes LCD problems, so this sets the timing thisSecond = float(datetime.now().strftime('%S.%f')) if lastFloatSecond + self.pollingDelay >= 60: lastFloatSecond = 0 if thisSecond > lastFloatSecond + self.pollingDelay: # index the timer lastFloatSecond = thisSecond # check and react to buttonState if self.buttonState != 0 and self.buttonAction == 0: if self.buttonState == 1: self.buttonAction = 1 screenTimer = 0 irrigationScreenNumber +=1 if(irrigationScreenNumber >= len(irrigationScreenList)): if self.debugON == True: print('exit irrigation screen') i = False # set for polling lastFloatSecond = float(datetime.now().strftime('%S.%f')) else: self.irrigationCropRefresh(irrigationScreenList[irrigationScreenNumber]) elif self.buttonState == 2: self.buttonAction = 1 screenTimer = 0 pass elif self.buttonState == 3: self.buttonAction = 1 screenTimer = 0 pass else: pass # Require buttons to be released before next press self.buttonCheckRelease() #### EVERY SECOND FUNCTIONS AND SCREEN TIMEOUT #### # use int of the float thisSecond if int(thisSecond) != lastSecond: # screen time out if screenTimer > self.backlightOffTime: i = False lastSecond = int(thisSecond) screenTimer += 1 def Iirrigated(self): '''last irrigation screen, can indicate irrigation was completed ''' self.buttonState = 0 self.mylcd.lcd_clear() # line 1 is displayed below as it changes with crops self.mylcd.lcd_display_string('Irrigation Action', 1, 2) self.mylcd.lcd_display_string(EnglishSpanish.getWord('Irrigation Action'), 1, 0) self.mylcd.lcd_display_string(EnglishSpanish.getWord('partial'), 2, 10) self.mylcd.lcd_display_string('', 2, 19) self.mylcd.lcd_write_char(126) self.mylcd.lcd_display_string(EnglishSpanish.getWord('full'), 3, 10) self.mylcd.lcd_display_string('', 3, 19) self.mylcd.lcd_write_char(126) self.mylcd.lcd_display_string('', 4, 0) self.mylcd.lcd_write_char(127) self.mylcd.lcd_display_string(EnglishSpanish.getWord("page"), 4, 2) lastSecond = 0 lastFloatSecond = 0 screenTimer = 0 i = True while i is True: #### CONTINUOUS POLLING #### # too fast of polling causes LCD problems, so this sets the timing thisSecond = float(datetime.now().strftime('%S.%f')) if lastFloatSecond + self.pollingDelay >= 60: lastFloatSecond = 0 if thisSecond > lastFloatSecond + self.pollingDelay: # index the timer lastFloatSecond = thisSecond # check and react to buttonState if self.buttonState != 0 and self.buttonAction == 0: if self.buttonState == 1: self.buttonAction = 1 screenTimer = 0 if self.debugON == True: print('exit irrigation screen') i = False # set for polling lastFloatSecond = float(datetime.now().strftime('%S.%f')) elif self.buttonState == 2: # full irrigation self.buttonAction = 1 screenTimer = 0 # full irrigation puts waterLoss at 0 data.waterLossCumulative = 0 if self.debugON == True: print('full irrigation') self.mylcd.lcd_clear() self.mylcd.lcd_display_string(EnglishSpanish.getWord('Full Irrigation'), 1, 0) self.mylcd.lcd_display_string(EnglishSpanish.getWord('Complete'), 2, 5) self.comment = self.comment + 'Full Irrigation/' time.sleep(5) i = False # set for polling lastFloatSecond = float(datetime.now().strftime('%S.%f')) elif self.buttonState == 3: # partial irrigation self.buttonAction = 1 screenTimer = 0 data.waterLossCumulative = data.waterLossCumulative - config.partialIrrigation if self.debugON == True: print('partial irrigation') self.mylcd.lcd_clear() self.mylcd.lcd_display_string(EnglishSpanish.getWord('Partial Irrigation'), 1, 0) self.mylcd.lcd_display_string(EnglishSpanish.getWord('Complete'), 2, 5) self.comment = self.comment + 'Partial Irrigation/' time.sleep(5) i = False # set for polling lastFloatSecond = float(datetime.now().strftime('%S.%f')) else: pass # Require buttons to be released before next press self.buttonCheckRelease() #### EVERY SECOND FUNCTIONS AND SCREEN TIMEOUT #### # use int of the float thisSecond if int(thisSecond) != lastSecond: # screen time out if screenTimer > self.backlightOffTime: i = False lastSecond = int(thisSecond) screenTimer += 1 def irrigationCropRefresh(self, crop): ''' refreshes crops in irrigation screen ''' cropFactorLookup = { 'Beans (mm)': (config.kBeans, 1), 'Beans (l)': (config.kBeans, config.fManzana), 'Corn (mm)': (config.kCorn, 1), 'Corn (l)': (config.kCorn, config.fManzana) } if crop[-4:] == '(mm)': landFactor = 1 elif config.landArea == 'acre': landFactor = config.fAcre elif config.landArea == 'hectare': landFactor = config.fHectare else: landFactor = config.fManzana self.mylcd.lcd_display_string(' ', 1, 0) self.mylcd.lcd_display_string(' ', 2, 2) self.mylcd.lcd_display_string(' ', 2, 10) self.mylcd.lcd_display_string(' ', 3, 2) self.mylcd.lcd_display_string(' ', 3, 10) self.mylcd.lcd_display_string(EnglishSpanish.getWord(crop), 1) kList = cropFactorLookup[crop][0] if(data.waterLossCumulative >= config.minimumIrrigation): self.mylcd.lcd_display_string('{:3.0f}'.format(landFactor * kList[0] * data.waterLossCumulative), 2, 2) self.mylcd.lcd_display_string('{:3.0f}'.format(landFactor * kList[1] * data.waterLossCumulative), 2, 10) self.mylcd.lcd_display_string('{:3.0f}'.format(landFactor * kList[2] * data.waterLossCumulative), 3, 2) self.mylcd.lcd_display_string('{:3.0f}'.format(landFactor * kList[3] * data.waterLossCumulative), 3, 10) else: self.mylcd.lcd_display_string('0', 2, 2) self.mylcd.lcd_display_string('0', 2, 10) self.mylcd.lcd_display_string('0', 3, 2) self.mylcd.lcd_display_string('0', 3, 10) #### MX SCREENS #### def MXscreenSelect(self, mxFunction): '''first maintenance screen where others can be selected, generally the mxFunction is set at 0 but others can be sent ''' self.buttonState = 0 self.MXscreenRefresh() tempRainCounter = self.rainCounter # used to reset if rain gage is tested lastSecond = 0 lastFloatSecond = 0 screenTimer = 0 # mxFunction = 8 is referenced in s/w update to change to reboot mxFunctionList = [ 'QUITE MX', 'USB eject', 'check Data File', 'check History', 'set clock', 'anemometer', 'rain gage', 's/w update', 'reboot', 'shutdown'] lastmxFunction = 999 i = 1 while i < 10: #### CONTINUOUS POLLING #### # too fast of polling causes LCD problems, so this sets the timing thisSecond = float(datetime.now().strftime('%S.%f')) if lastFloatSecond + self.pollingDelay >= 60: lastFloatSecond = 0 if thisSecond > lastFloatSecond + self.pollingDelay: # index the timer lastFloatSecond = thisSecond #### DISPLAYS DATA ON MAINTENANCE SCREEN #### if config.language == 'Spanish': mxDisplayList = [ 'SALIR MX', 'expulsar USB', 'mira datos', 'mira historia', 'configuar reloj', 'anemometro', 'pluviometro', 'actualizar update', 'reiniciar', 'apagar'] else: mxDisplayList = mxFunctionList if mxFunction != lastmxFunction: self.MXscreenRefresh() # update line self.mylcd.lcd_display_string(' ', 2, 0) self.mylcd.lcd_display_string(' ', 3, 0) self.mylcd.lcd_display_string(mxDisplayList[mxFunction], 2, 1) # some MX function require an init: if mxFunctionList[mxFunction] == 'anemometer': self.windCounter = 0 self.mylcd.lcd_display_string(EnglishSpanish.getWord('sensor count: '), 3, 0) elif mxFunctionList[mxFunction] == 'rain gage': self.rainCounter = 0 self.mylcd.lcd_display_string(EnglishSpanish.getWord('sensor count: '), 3, 0) elif mxFunctionList[mxFunction] == 'set clock': self.mylcd.lcd_display_string('{:%Y-%m-%d %_H:%M}'.format(datetime.now()), 3, 0) elif mxFunctionList[mxFunction] == 'check Data File': dataFileMessage = self.getFileSummary(self.dataFileName) self.mylcd.lcd_display_string(dataFileMessage, 3, 0) elif mxFunctionList[mxFunction] == 'check History': dataFileMessage = self.getFileSummary(self.historyFileName) self.mylcd.lcd_display_string(dataFileMessage, 3, 0) elif mxFunctionList[mxFunction] == 's/w update': swNow, swNew = self.getSWrev(config.updateFilePath) message = swNow + ' to ' + swNew self.mylcd.lcd_display_string(message, 3, 0) lastmxFunction = mxFunction # Display values for sensor troubleshooting if mxFunctionList[mxFunction] == 'anemometer': self.mylcd.lcd_display_string('{:.0f}'.format(self.windCounter), 3, 14) elif mxFunctionList[mxFunction] == 'rain gage': self.mylcd.lcd_display_string('{:.0f}'.format(self.rainCounter), 3, 14) # check and react to buttonState if self.buttonState != 0 and self.buttonAction == 0: if self.buttonState == 1: self.buttonAction = 1 screenTimer = 0 if mxFunctionList[mxFunction] == 'QUITE MX': # clear counters used in sensor troubleshooting to avoid # inaccurate data self.windCounter = 0 self.rainCounter = tempRainCounter i = 999 elif mxFunctionList[mxFunction] == 'USB eject': RPiUtilities.ejectUSB(self.usbPath) self.mylcd.lcd_display_string(EnglishSpanish.getWord('Reboot Required!'), 1, 0) self.mylcd.lcd_display_string(EnglishSpanish.getWord('replace USB'), 2, 2) self.mylcd.lcd_display_string(EnglishSpanish.getWord('and Reboot'), 3, 0) time.sleep(5) mxFunction = 8 elif mxFunctionList[mxFunction] == 'set clock': self.clockSet() #self.mylcd.lcd_display_string(mxFunctionList[mxFunction], 2, 2) # this forces display to refresh lastmxFunction = 999 elif mxFunctionList[mxFunction] == 's/w update': self.mylcd.lcd_clear() self.mylcd.lcd_display_string(EnglishSpanish.getWord('Loading new s/w'), 1, 0) self.mylcd.lcd_display_string(EnglishSpanish.getWord('please wait'), 2, 2) self.mylcd.lcd_display_string(EnglishSpanish.getWord('will reboot'), 3, 0) RPiUtilities.copySW(self.usbPath) RPiUtilities.rebootRPI() elif mxFunctionList[mxFunction] == 'reboot': self.mylcd.lcd_clear() self.mylcd.lcd_display_string(EnglishSpanish.getWord('Reboot System'), 1, 0) self.mylcd.lcd_display_string(EnglishSpanish.getWord('please wait'), 2, 2) GPIO.cleanup() RPiUtilities.rebootRPI() elif mxFunctionList[mxFunction] == 'shutdown': self.mylcd.lcd_clear() self.mylcd.lcd_display_string(EnglishSpanish.getWord('Shutdown System'), 1, 0) self.mylcd.lcd_display_string(EnglishSpanish.getWord('must restart'), 2, 2) GPIO.cleanup() RPiUtilities.shutdownRPI() elif self.buttonState == 2: self.buttonAction = 1 screenTimer = 0 mxFunction = mxFunction - 1 if mxFunction < 0: mxFunction = len(mxFunctionList) - 1 elif self.buttonState == 3: self.buttonAction = 1 screenTimer = 0 mxFunction = mxFunction + 1 if mxFunction > len(mxFunctionList) - 1: mxFunction = 0 else: pass # Require buttons to be released before next press self.buttonCheckRelease() #### EVERY SECOND FUNCTIONS AND SCREEN TIMEOUT #### # use int of the float thisSecond if int(thisSecond) != lastSecond: # screen time out if screenTimer > self.backlightOffTime: i = 999 lastSecond = int(thisSecond) screenTimer += 1 def MXscreenRefresh(self): '''LCD init and refresh for MX screen ''' self.mylcd.lcd_clear() self.mylcd.lcd_display_string(EnglishSpanish.getWord('MX pages'), 1, 0) self.mylcd.lcd_display_string('', 2, 19) self.mylcd.lcd_write_char(self.custom['up arrow']) #self.mylcd.lcd_display_string('', 2, 19) #self.mylcd.lcd_write_char(94) self.mylcd.lcd_display_string('', 3, 19) self.mylcd.lcd_write_char(self.custom['down arrow']) #self.mylcd.lcd_display_string('', 3, 19) #self.mylcd.lcd_write_char(118) self.mylcd.lcd_display_string('', 4, 0) self.mylcd.lcd_write_char(127) self.mylcd.lcd_display_string(EnglishSpanish.getWord('do it'), 4, 2) def getSWrev(self, programFilePathName): '''get current and new s/w rev ''' # grabs current rev from its own .py file try: with open(programFilePathName, newline='') as file: # read full file fileText = file.read() # split into lines lines = fileText.split('\n') line2 = lines[3] swNow = line2[2:] except FileNotFoundError as e: swNow = 'none' # count rows and get last line try: with open(self.usbPath + '/weatherUPDATE/readME') as file: swNew = file.readline() swNew = swNew[:-1] except FileNotFoundError: swNew = "none" if self.debugON == True: print('swNew: ', swNew) if self.debugON == True: print('getSWrev now/new: ',swNow, ' / ', swNew) return swNow, swNew def clockSet(self): '''Maintenance screen for setting real time clock ''' # get timing variables from RTC (DS1307) year = int(datetime.now().strftime('%Y')) month = int(datetime.now().strftime('%m')) date = int(datetime.now().strftime('%d')) hour = int(datetime.now().strftime('%H')) minute = int(datetime.now().strftime('%M')) # set buttonState self.buttonState = 0 # initialize LCD self.mylcd.lcd_clear() self.mylcd.lcd_display_string(EnglishSpanish.getWord('Clock set'), 1, 0) self.mylcd.lcd_display_string('', 2, 19) self.mylcd.lcd_write_char(self.custom['up arrow']) self.mylcd.lcd_display_string('', 3, 19) self.mylcd.lcd_write_char(self.custom['down arrow']) self.mylcd.lcd_display_string('', 4, 0) self.mylcd.lcd_write_char(127) self.mylcd.lcd_display_string(EnglishSpanish.getWord('next'), 4, 2) # set timing variables lastSecond = 0 lastFloatSecond = 0 screenTimer = 0 # set lists for screen control screenList = ['YEAR', 'MONTH', 'DATE', 'HOUR', 'MINUTE', 'exit and set clock'] if config.language == "Spanish": screenList = ['ANO', 'MES', 'FECHA', 'HORA', 'MINUTO', 'configurar el reloj'] varList = [year, month, date, hour, minute, 999] setScreen = 0 i = 1 while i < 10: #### CONTINUOUS POLLING #### # too fast of polling causes LCD problems, so this sets the timing # pollingDelay is the timing and is set in init thisSecond = float(datetime.now().strftime('%S.%f')) # update set time on LCD if setScreen == 5: self.mylcd.lcd_display_string(EnglishSpanish.getWord('Set Clock and Exit '), 1, 0) else: self.mylcd.lcd_display_string(screenList[setScreen] + ' ', 1, 10) year = varList[0] month = varList[1] date = varList[2] hour = varList[3] minute = varList[4] setDate = '{:}'.format(year) + '-' + '{:02d}'.format(month) + '-' + '{:02d}'.format(date) setTime = '{:02d}'.format(hour) + ':' + '{:02d}'.format(minute) self.mylcd.lcd_display_string(setDate, 2, 0) self.mylcd.lcd_display_string(setTime, 3, 0) if setScreen == 5: self.mylcd.lcd_display_string(EnglishSpanish.getWord('exit'), 2, 14) self.mylcd.lcd_display_string(EnglishSpanish.getWord('exit'), 3, 14) self.mylcd.lcd_display_string(EnglishSpanish.getWord('set clock'), 4, 2) if lastFloatSecond + self.pollingDelay >= 60: lastFloatSecond = 0 if thisSecond > lastFloatSecond + self.pollingDelay: # index the timer lastFloatSecond = thisSecond # check and react to buttonState if self.buttonState != 0 and self.buttonAction == 0: if self.buttonState == 1: self.buttonAction = 1 screenTimer = 0 setScreen = setScreen + 1 if setScreen > 5: # this is to alert due to delay in clock setting self.mylcd.lcd_clear() self.mylcd.lcd_display_string(EnglishSpanish.getWord('WAIT'), 1, 0) self.mylcd.lcd_display_string(EnglishSpanish.getWord('while clock sets'), 2, 2) # this sets the RTC to the variables RPiUtilities.setRTC(year, month, date, hour, minute) i = 999 # set for polling lastFloatSecond = float(datetime.now().strftime('%S.%f')) elif self.buttonState == 2: self.buttonAction = 1 screenTimer = 0 if setScreen == 5: i = 999 else: varList[setScreen] = varList[setScreen] - 1 if screenList[setScreen] == 'MONTH' and varList[setScreen] < 1: varList[setScreen] = 12 elif screenList[setScreen] == 'DATE' and varList[setScreen] < 1: varList[setScreen] = 31 elif screenList[setScreen] == 'HOUR' and varList[setScreen] < 0: varList[setScreen] = 23 elif screenList[setScreen] == 'MINUTE' and varList[setScreen] < 0: varList[setScreen] = 59 elif screenList[setScreen] == 'exit and set clock': i = 999 screenTimer = 0 elif self.buttonState == 3: self.buttonAction = 1 screenTimer = 0 if setScreen == 5: i = 999 else: varList[setScreen] = varList[setScreen] + 1 if screenList[setScreen] == 'MONTH' and varList[setScreen] > 12: varList[setScreen] = 1 elif screenList[setScreen] == 'DATE' and varList[setScreen] > 31: varList[setScreen] = 1 elif screenList[setScreen] == 'HOUR' and varList[setScreen] > 23: varList[setScreen] = 0 elif screenList[setScreen] == 'MINUTE' and varList[setScreen] > 59: varList[setScreen] = 0 elif screenList[setScreen] == 'exit and set clock': i = 999 screenTimer = 0 else: pass # Require buttons to be released before next press self.buttonCheckRelease() #### EVERY SECOND FUNCTIONS AND SCREEN TIMEOUT #### # use int of the float thisSecond if int(thisSecond) != lastSecond: # screen time out (backlightOffTime is time out for screen) if screenTimer > self.backlightOffTime: i = 999 lastSecond = int(thisSecond) screenTimer += 1 def systemError(self, errorMessage2, errorMessage3): '''dead end screen requiring reboot with message for error ''' self.mylcd.lcd_clear() self.mylcd.lcd_display_string('Act and Reboot', 1, 0) self.mylcd.lcd_display_string(errorMessage2, 2, 0) self.mylcd.lcd_display_string(errorMessage3, 3, 0) self.mylcd.lcd_display_string('reboot', 4, 13) self.mylcd.lcd_write_char(126) i = 1 while i < 10: # check and react to buttonState if self.buttonState != 0: if self.buttonState == 1: self.buttonAction = 1 pass elif self.buttonState == 2: self.buttonAction = 1 self.mylcd.lcd_clear() self.mylcd.lcd_display_string('Reboot System', 1, 0) self.mylcd.lcd_display_string('please wait', 2, 2) RPiUtilities.rebootRPI() elif self.buttonState == 3: self.buttonAction = 1 pass else: pass # return buttonState to no pressed state self.buttonState = 0 #### INTERRUPT FUNCTIONS #### def windCount(self, pin): '''interrupt call from anemometer to increment the windCounter ''' self.windCounter += 1 def rainCount(self, pin): '''interrupt call from tipping bucket rain gage to increment the windCounter ''' self.rainCounter += 1 def backlightON(self): '''combined function for turning backlight on and refreshing screen ''' # refresh LCD (in case of scramble) and turn backlight on self.backlightTimer = 0 #self.restartLCD() # restartLCD() includes backlight(1) self.mylcd.backlight(1) #self.mainScreen() self.mainScreenRefresh() time.sleep(.5) #self.buttonState = 0 def reactToButton(self, buttonPin): '''function call from button 2 interrupt ''' time.sleep(.01) # this is part of the debounce # if backlight is off, then turn on only for this press if self.backlightTimer > self.backlightOffTime: self.buttonState = 99 else: if buttonPin == self.pinButton1: self.buttonState = 1 elif buttonPin == self.pinButton2: self.buttonState = 2 elif buttonPin == self.pinButton3: self.buttonState = 3 else: self.buttonState = 0 if self.debugON == True: print('button ', self.buttonState, ' pressed') def buttonCheckRelease(self): '''sets self.buttonState to 0 only if all buttons are not pressed - this is the only place self.buttonState can be set to 0 - self.buttonState is the button pressed ''' time.sleep(.01) # this is part of the debounce button1 = GPIO.input(self.pinButton1) button2 = GPIO.input(self.pinButton2) button3 = GPIO.input(self.pinButton3) if button1 == False and button2 == False and button3 == False: self.buttonState = 0 self.buttonAction = 0 if __name__ == '__main__': print('start weather') data = stationData() app = weatherStation() app.runTimer() print('end weather station script')
Go
UTF-8
2,935
2.78125
3
[ "MIT" ]
permissive
package models import ( "encoding/json" "fmt" "math/rand" "time" "github.com/dtop/go.ginject" "github.com/google/go-querystring/query" "gopkg.in/redis.v4" ) type ( // Session interface Session interface { New() Session FromSessionID(sessID string) error Store(sessID ...string) error GetSessionID() string GetUserID() string AssignUserID(userID string) Assemble() (string, error) } // sess is the Session implementation sess struct { SessID string `json:"-" url:"-"` UserID string `json:"user_id" url:"-"` ClientID string `json:"client_id" url:"client_id" form:"client_id" binding:"required"` RedirectURI string `json:"redirect_uri" url:"redirect_uri" form:"redirect_uri" binding:"required"` Scope string `json:"scope" url:"scope" form:"scope"` State string `json:"state" url:"state" form:"state"` ResponseType string `json:"response_type" url:"response_type" form:"response_type" binding:"required"` deps ginject.Injector `json:"-" url:"-"` Redis *redis.Client `inject:"redis" json:"-" url:"-"` } ) // NewSession creates a new session item func NewSession(deps ginject.Injector) Session { sess := &sess{deps: deps} if err := deps.Apply(sess); err != nil { panic(err) } return sess } // ################## Session // New creates a brand new session item func (s *sess) New() Session { return NewSession(s.deps) } // FromSessionID loads a stored session and applies it on the object func (s *sess) FromSessionID(sessID string) error { raw, err := s.Redis.Get(fmt.Sprintf("sess_%v", sessID)).Result() if err != nil { return err } if err := json.Unmarshal([]byte(raw), s); err != nil { return err } s.SessID = sessID return nil } // Store stores the session func (s *sess) Store(sessID ...string) error { var _sessid string if len(sessID) > 0 { _sessid = sessID[0] } if _sessid == "" && s.SessID != "" { _sessid = s.SessID } if _sessid == "" { _sessid = randStr(32) } raw, err := json.Marshal(s) if err != nil { return err } key := fmt.Sprintf("sess_%v", _sessid) val := string(raw) dur := 7200 * time.Second if _, err := s.Redis.Set(key, val, dur).Result(); err != nil { return err } s.SessID = _sessid return nil } // GetSessionID returns the session id func (s *sess) GetSessionID() string { return s.SessID } // GetUserID returns the user ID func (s *sess) GetUserID() string { return s.UserID } func (s *sess) AssignUserID(userID string) { s.UserID = userID } func (s *sess) Assemble() (string, error) { v, err := query.Values(s) if err != nil { return "", err } return v.Encode(), nil } // #################### Helpers func randStr(length int) string { rand.Seed(time.Now().UnixNano()) abc := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") b := make([]rune, length) for i := range b { b[i] = abc[rand.Intn(len(abc))] } return string(b) }
Python
UTF-8
2,197
3.171875
3
[]
no_license
import requests from requests.auth import HTTPBasicAuth import sys import time def downloadFile(url, directory) : """Downloads the file given in url displaying a nice progress bar during the process. """ # Define local filename from url last part localFilename = url.split('/')[-1] # Download file into local file with open(directory + '/' + localFilename + '.zip', 'wb') as f: # Start counting process time start = time.process_time() # Get response object ready for stream r = requests.get(url, auth=HTTPBasicAuth('kokyuhoapi', 'simple123'), stream=True) # Get total length in bits, init downloaded counter total_length = r.headers.get('content-length') dl = 0 # Check file is not empty if total_length is None: # no content length header f.write(r.content) # Download file in chunks and keep updating stdout with a progress bar else: i = 0 for chunk in r.iter_content(1024): dl += len(chunk) f.write(chunk) done = int(50 * dl / int(total_length)) if i%100 == 0: sys.stdout.write("\r[%s%s] Downloading %s of %s MB; %s Mbps" % ( '=' * done, ' ' * (50-done), str(round(dl/1024/1024,2)), str(round(int(total_length)/1024/1024, 2)), round((dl//(time.process_time() - start))/1024/1024, 2))) print('') i += 1 return (time.process_time() - start) def main() : """Sets the url and directory and runs the downloadFile function, passing these values. """ # Define url and target directory url = "https://scihub.copernicus.eu/dhus/odata/v1/Products('bc88e6f3-7934-407a-82ab-2bbb26ec2cfe')/$value" directory = "." # Call function time_elapsed = downloadFile(url, directory) print("Download complete...") print("Time Elapsed:", time_elapsed) if __name__ == "__main__" : main()
Python
UTF-8
75
3.1875
3
[]
no_license
n = list(input().split()) print(n[-1]) #последний элемент
Java
UTF-8
215
1.5625
2
[]
no_license
package spring.s4.datasmap.repositories; import org.springframework.data.jpa.repository.JpaRepository; import spring.s4.datasmap.model.Place; public interface PlaceRepo extends JpaRepository<Place,Integer > { }
JavaScript
UTF-8
816
2.53125
3
[]
no_license
import axios from "axios"; import React, { useState } from "react"; import "./FileUpload.scss"; export default function FileUpload() { const [file, setFiles] = useState(null); const handleChange = (event) => { console.log(event.target.files); setFiles({ file: event.target.files[0] }); }; const handleSubmit = async (event) => { event.preventDefault(); console.log("file", setFiles.file); const data = new FormData(); data.append("file", setFiles(file)); const upload_res = await axios({ method: "POST", url: "http://localhost:1337/recipes", data: data, }); console.log(upload_res); }; return ( <div className="fileUpload"> <div onSubmit={handleSubmit}> <input onChange={handleChange} type="file" /> <button type="submit">Submit</button> </div> </div> ); }
C
UTF-8
817
3.8125
4
[]
no_license
/*Design, Develop and Implement a Program in C for the following Stack Applications a. Evaluation of Suffix expression with single digit operands and operators:+, -, *, /, %, ^ b. Solving Tower of Hanoi problem with n disks*/ #include<stdio.h> #include<stdlib.h> void towerOfHanoi(int n,char fromTower,char toTower,char auxTower){ if(n==1){ printf("\nMove disc 1 from tower %c to tower %c\n",fromTower,toTower); return; } towerOfHanoi(n-1,fromTower,auxTower,toTower); printf("\nMove disc %d from tower %c to tower %c\n",n,fromTower,toTower); towerOfHanoi(n-1,auxTower,toTower,fromTower); } int main(){ int n; printf("\nEnter the no. of disks\n"); scanf("%d",&n); printf("\nThe steps to be performed\n"); towerOfHanoi(n,'a','c','b'); }
Python
UTF-8
672
2.6875
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 import random from Crypto.Util.number import * FLAG = open('./flag', 'rb').read() def pad(data, block_size): padlen = block_size - len(data) - 2 if padlen < 8: raise ValueError return b'\x00' + bytes([random.randint(1, 255) for _ in range(padlen)]) + b'\x00' + data def main(): p = getPrime(512) q = getPrime(512) n = p * q e = 65537 d = inverse(e, (p - 1) * (q - 1)) m = bytes_to_long(pad(FLAG, 128)) c = pow(m, e, n) print(f'n = {n}') print(f'c = {c}') while True: c = int(input()) m = pow(c, d, n) print(f'm & 1 = {m & 1}') try: main() except: ...
C
UTF-8
927
3.296875
3
[]
no_license
#include <stdio.h> #include<stdlib.h> #include<math.h> //print all prime number between low and high , including them void printPrime(int low, int high) { if(high == 1) return; if(low > high) return; char *arr = (char*)malloc(sizeof(char)*(high+1)); int index=0; arr[0] = '0'; arr[1] = '0'; for(index=2;index<high+1;index++) { arr[index] = '1'; } int i=2; for(;i<sqrt(high+1);i++) { if(arr[i]-'0' == 1) { int count = 0; // if(i >= low) //printf("%d ",i); int tmp = i*i; int j = 0; for( j=tmp;j<high+1;j=tmp+count*i) { arr[j] = '0'; count++; } } } for(index=2;index<high+1;index++) { if(arr[index]-'0' == 1) { printf("%d ",index); } } /*if(arr[1]-'0' == 1) printf("true"); printf("%d ",arr[1]); */ } int main(void) { // your code goes here printPrime(9,100); return 0; }
TypeScript
UTF-8
227
2.984375
3
[ "MIT" ]
permissive
export class Base { a: string = ''; constructor() {} } export class D extends Base { // D overwrites a property coming from the base class. a: any; constructor(a: string) { super(); this.a = a + '!!!'; } }
Markdown
UTF-8
15,015
2.53125
3
[]
no_license
#第94章 互咬<br />    正在李丰话不成话的时候,旁边那位鹰甲终于将铁面罩推了上去,不慌不忙地露了个石破天惊的面:“皇上,乱臣贼子都已经束手就擒,还请您多保重龙体,天子为社稷呕心沥血,何需为几个反贼伤身?”    那声音太耳熟了,李丰扭头一看,呆住了,扶着他的那鹰甲竟是本该在南边的顾昀。    顾昀突然出现吓坏了一帮人。    吕常脑子里“嗡”一声,杨荣桂跟他保证过,说那边行动万般小心,安定侯完全被他们瞒过去了!    在他原计划里,所有的布置都要在雁王离京的这段时间内完成——刘崇山那他说东不往西的蠢货是颗棋子,给个棒棰就当针,只要诱得他杀了李丰,杨荣桂不必出头,叫刘崇山将雁王接手推出来,到时候雁王是自愿的也好,是被杨荣桂胁迫的也好,只要他一露面,谋反重罪立刻落实,京郊北大营一旦反应过来,马上会进京平叛,将雁王与刘崇山一锅端了,让他们死在乱军中,就成了死无对证。    宫里没有太后,皇后是个见不得风的病秧子,凤印都提不动,太子还在吃奶,而吕妃的皇长子已经十一岁,江山是谁家的不言而喻。    顾昀远在江北,等他知道的时候皇帝和反贼都死了,京城中早已经尘埃落定,除非他无视四境之危,冒天下之大不韪为两个死人起兵——就算是吕常这个小人也不相信顾昀能干得出来,顾昀要叛国早在北大营哗变的时候……甚至更早以前,他知道当年玄铁营之变真相的时候就叛了,王裹那老不死还能苟延残喘地活到今天?    此事只有两处关键,第一要看杨荣桂能不能在自己的地盘上切断京城和江北的联系,瞒住顾昀,第二要看刘崇山能不能顺利杀李丰。    前者有杨荣桂以身家性命作保,后者更是本来万无一失,谁知不知是谁走漏消息,老百姓里居然埋伏了好多高手侍卫,北大营提前赶到,顾昀也从天而降!    至此,吕常就算再怎么样也反应过来了,他最信任的人里,有人背叛了,不是杨荣桂就是方钦……杨荣桂这番自己也落不了好,那会不会是方钦?    如果真是姓方的,那他可太歹毒了,借力打力,将他们的形迹泄露给北大营,又拖来顾昀,浑水摸鱼。不但能争个保皇的头功,此时除掉吕家,往后满京城各大世家中再无能与方家抗衡者!    吕常想着想着脑子就开豁了,一惊一乍地想道:“那方钦会不会从一开始就是雁王党?”    而莫名变成“雁王党”的方大人见了顾昀,脸色也是一变,顿时就笑不下去了。    他本以为凭杨荣桂重大疫情也能一手遮天的本领,至少能趁顾昀赶往前线的时候把事情办利索,从头到尾,他的计划里并没有这尊杀神,虽然凭着北大营救驾之功,顾昀来与不来都不影响他的布置……可是莫名其妙的,方钦突然有种万事失控的预感。    这群人各怀鬼胎,唯有沈易是真的大大松了一口气,见顾昀如见救星,小凉风从他被划开的朝服里钻进去,直接扫到他汗哒哒的肉皮上,让他结结实实地打了个哆嗦。    然而他这口气松得太早了,腥风血雨还没完。    只见顾昀将李丰交到赶来的内侍手上,后退一步跪在石阶上,不等李丰发问,便率先有条有理地回禀道:“臣与雁王和徐大人在扬州城分开后,便将亲卫留在雁王身边,同葛灵枢去了往江北大营查看军务,不料在江北大营的时候突然接到亲卫密信求救,说杨荣桂竟敢私屯兵马,挟持雁王意图不轨,臣情急之下,只好跟钟老将军调用了几台江北驻军的鹰甲,赶到扬州城时,发现那杨荣桂以平暴民之乱为名,将扬州府围了个水泄不通,臣带人在周围探查良久,乃至于趁夜潜进总督府,这才发现此人故意制造迷雾,杨本人已经不知所踪,而雁王下落不明,臣想到亲兵所言‘谋反’一事,唯恐京城有失,只好先往回赶,未能护雁王周全,有负使命,请皇上责罚。”    顾昀话一出口,其中惊心动魄处将周遭震得一片寂静。    方钦悄悄冲王裹递了个眼色,王裹会意,开口插话道:“皇上,臣有一事不明想请教顾帅……顾帅的鹰甲一路从江北追到京城,怎么竟也未能截住那杨荣桂吗?”    这句话可谓是王国舅超常发挥了,看似无意一提,实则勾起李丰好多疑虑——究竟是那杨荣桂神通广大,还是顾昀故意将杨荣桂等人放进京城?安定侯到底是一路风驰电掣地救驾而来,还是本来就另有图谋,到了京城见北大营早有准备才临阵倒戈?    更不用提那“下落不明”的雁王,倘若他真的和城外叛党在一起,究竟是被劫持的还是别有内情可就说不清了。    众人的目光意味不明地落在顾昀身上,顾昀却仿佛无知无觉,坦然回道:“惭愧,臣接到消息的时候已经丢了杨荣桂的行踪,扬州城内寻找雁王、沿途搜索叛党又耽搁了许久,险些误了大事。”    这句话在场文官基本没听明白,被两个人扶着的张奉函却适时地插话道:“皇上、诸位大人有所不知,鹰甲在天上的时候速度极快,只能阵前或是在小范围内搜捕目标,从江北到京城这么远的一段,倘若不是事先知道搜寻的目标走了哪条路,目标也不是什么大队人马,三两只鹰甲找人根本就是大海捞针。”    然而事已至此,方钦一党绝不肯轻易放过顾昀,情急之下,王国舅紧逼道:“那既然知道事态紧急,顾帅为何不从江北大营多借调一些人手?”    顾昀侧过头看了他们一眼,从方钦的角度看过去,安定侯那双桃花眼的弧度格外明显,眼角几乎带钩,配上那一颗小痣,无端有点似笑非笑的意思,方钦心里顿时一突——王裹说错话了,自己抽了自己一巴掌!    果然头一句是超常发挥,这一句才是王国舅的水平。    可是顾昀平时不争归不争,人又不傻,此时断然不会给他再找补的机会。    “国舅爷的意思我有点不明白,”顾昀不温不火道,“那江北大营是我顾昀的私兵吗?我说调就调,吃紧的前线供给,虎视眈眈的洋人都不管了?敢问国舅爷,我朝除了皇上,谁能一句话兴师动众地将江北大营拉到京城来,劳烦指给我看一看,我亲手斩了那乱臣贼子!”    他隐含煞气的一句话把李丰说得回过了神来,顿时察觉到自己方才险些被王裹那芝麻绿豆大的心胸带进沟里——顾昀手握玄铁虎符,就算要造反,犯得上跟在杨荣桂这种货色后面捡漏吗?    顾昀:“皇上,臣这次反应不及,罪该万死,找到杨荣桂等人踪迹时已近京城,得知雁王很可能已被此乱臣劫持,投鼠忌器,未敢打草惊蛇,本想向北大营求援,谁知正遇见北大营在九门外严阵以待,才知道京中可能出事,好在北大营事先得了方大人的提醒,臣仓促之下只好命九门暂下禁空网,同时放北大营入城,幸而皇上洪福齐天,有惊无险——也多亏方大人准备周全。”    方钦脸皮一抽,感觉吕家党的眼神已经快把自己烧穿了,他从头到尾又是装病、又是匿名,甚至让王裹冲到前头,就是为了低调行事,藏在别人后面才是最安全的,最好让吕常根本想不出这里头有自己的事。    谁知顾昀一把软刀子捅过来,直接把他穿在了火上烤,吕常方才只是胡乱怀疑,被这一句话坐实了,震惊之余,恨得想把方钦剥皮抽筋。    李丰这才知道北大营不是跑得快,而是早就在九门外等着了,一时更懵:“北大营又是怎么回事?”    方钦只好暂时将顾昀这个巨大的意外搁置在一边,连同一位北大营偏将,斟词酌句地从其妹方氏的家书讲起,旁边有个瞠目欲裂的吕常,李丰又多疑心重,方钦虽然自信此事计划深远,自己绝没有留下一点不利证据,但一个弄不好还是可能引火烧身,只得打起十二分精神应对。    李丰越听越头大,越听越惊心,此事牵涉之广、内情之复杂隆安年间绝无仅有,文武百官大气也不敢出地跪了一片,北大营已经临时将街边戒严,以免不该有的话流传到市井之中。    而方钦的赤胆忠心还没有表达完,北大营便收拾了杨荣桂一干人等。    杨荣桂在约定的地方没等到吕常的捷报,却等来了北大营的包围圈,当时就知道大势已去,刚开始本想以雁王为质,谁知新任北大营统领铁面无私,只道雁王自己的嫌疑还没洗干净呢,不管不顾地一箭放倒了挟持雁王的反贼,不管三七二十一地一起带进了城中。    除“雁王”这位皇亲国戚有特别优待之外,其余人等一律五花大绑,押上祈明坛。    杨荣桂一路都在琢磨怎么办,此时膝盖还没着地,他已经开始先声夺人地喊起冤来。    江充上前一步喝道:“你勾结反贼起兵叛乱,有什么脸面喊冤?”    杨荣桂以头触地,嚎哭道:“冤枉,皇上!罪臣世受隆恩,岂敢有负圣上?此事从最开始就是朝中雁王党污蔑臣等,罪臣家中金银相加没有百两,国家危难时全已经换成了烽火票,所谓贪墨祸国殃民根本无稽之谈,不信您下令抄罪臣的家!臣待皇上一片忠心天地可表,请皇上明鉴!”    李丰的声音低得仿佛从喉咙里挤出来的:“哦?照你这么说,你私自上京,难不成是来救驾的?”    杨荣桂当场颠倒黑白道:“朝中雁王一党,一手遮天,欺君结党,无所不为,罪臣清白无辜,被小人搬弄是非,连内弟吕侍郎都不肯相信罪臣,几次来信逼问,为小人所趁,竟被奸王一党撺掇着犯下大错,臣远在江北,知道此事时已晚,情急之下只好扣下雁王,一路押解上京……”    李丰截口打断他:“小人是谁?”    杨荣桂大声道:“就是那户部尚书方钦为内弟献上‘黄袍加身’之计!”    方钦怒道:“皇上,叛党怀恨在心,无凭无据,分明是含血喷人!    王裹忙跟着帮腔:“杨大人倘若真的上京勤王,身边就带这么几个人吗?方才安定侯分明说扬州城内官兵聚集!”    吕常痛哭流涕:“臣冤枉!”    沈易:“……”    他头层冷汗方才被凉风吹飞,目睹隆安年间最规模庞大的一场狗咬狗,整个人已经惊呆了,第二层冷汗忙不迭地排队而出,简直不知道晕头巴脑的自己到底是怎么全须全尾地穿过这些层层叠叠的阴谋诡计的。    李丰:“都给我闭嘴!带雁王!”    被人遗忘已久的“雁王”与“徐令”被人推到御前,李丰目光阴沉的注视着面前的人,冷冷地道:“阿旻,朕要听你说,怎么回事。”    那“雁王”弓着肩缩着脖,整个人哆嗦成了一团,往日俊秀深沉的五官气质一变,竟凭空带了几分猥琐气,吓成了一只人形鹌鹑。    别人没什么,张奉函先急了,上前猛一推“雁王”肩头,急道:“您倒是说句话呀!”    这时,离奇的事发生了,当年踩在玄鹰背上一箭射死东瀛奸细了痴的雁王居然被奉函公这么个糟老头子推了个大跟头,踉跄着匍匐在地,一侧的肩膀摔变形了!    众人都惊呆了,不知是奉函公喝了紫流金还是雁王变成了泥捏的。    好半晌,北大营统领壮着胆子上前一步,试探着伸手在“雁王”变形的肩膀上碰了碰,回道:“皇上,此物好像……”    李丰:“什么?”    北大营统领道:“……是个垫肩!”    说话间,“雁王”抬起了头来,只见那张脸上涕泪齐下,鼻子和下巴分兵两路,各自往左右歪曲,一张俊脸南辕北辙地分裂开来——哪里是“雁王”,分明是个不知哪里来的妖魔鬼怪!    北大营统领震惊之余,上手三下五除二地将此人外袍扒开,只见他两侧肩膀,胸口后背都塞了可以以假乱真的软垫,脚下靴子中至少藏了五六寸的内垫,假鼻梁、假下巴与□□往下一扯,分明是个五短身材、獐头鼠目的陌生男子。    李丰这辈子没见过这种大变活人,倒抽了一口凉气:“你是何……何人?”    沈易觉得皇上中间有一瞬间大概是想喊“你是何方妖孽”的。    那男的张开嘴,却说不出话来,只见他口中舌头已经被割去了。    再看旁边那“徐令”,扒开头发,头皮上也能找到一层□□的接缝。    吕常:“……”    杨荣桂:“……”    那两人是杨荣桂派去看守雁王和徐令的,什么时候被人割了舌头弄成了这样?真的雁王呢?莫非这么长时间以来,真正的雁王和徐令一直混在他手下队伍里假装侍从!    杨荣桂惶急地回头去找寻,后面一堆被北大营押来的随从里果然少了两个人!    什么时候没的他一点也不知道!    一时间,连方钦都不知道说什么好了,满心阴谋的方大人不由自主地怀疑起来,杨荣桂别是真的早跟吕常拆伙了吧?    李丰实在看不下去了,抬脚要走,脚什么时候麻的都不知道,一迈步就晃了一下,要不是旁边还有个顾昀,当今天子就要斯文扫地地摔个狗啃泥了。    “皇上,”顾昀在旁边耳语道:“臣背着您下去吧。”    李丰心头狠狠地一震,当他看向顾昀的时候,一时几乎有些恍惚,身边这个人好像这么多年都没怎么变过——并不是说顾昀还保持着十来岁的半大孩子面貌,而是他那眼神。    经年以往,所有人都搀了不知几多算计与深沉,只有那双熟悉的桃花眼里,依稀存着当年身在一片鳞甲中偷偷冲他笑的促狭与风流。    李丰摇摇头,不肯让在众目睽睽之下示弱让人背着走,只是扶着顾昀一只手臂,缓缓走下一片狼藉的祈明坛。    内侍掐着尖细的嗓子叫道:“起驾,回宫——”    苍茫夕照,悠悠地垂到皇城边缘,将万万千鳞次栉比的琉璃瓦映得一片血红。    终于还是落下去了。
Java
UTF-8
1,605
2.140625
2
[]
no_license
/** * */ package io.assignment.account.api.v1; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.stereotype.Component; import io.assignment.account.client.TransactionV1; import io.assignment.account.entity.v1.AccountEntityV1; import lombok.Data; /** * @author Deepak Muthekar * */ public class AccountResponseV1 { private Long id; private Date openingDate; private List<TransactionV1> transactions = new ArrayList<>(); private BigDecimal balance; public AccountResponseV1(AccountEntityV1 account, List<TransactionV1> transactions) { this.id = account.getId(); this.openingDate = account.getOpeningDate(); if (transactions != null) this.transactions = transactions; this.balance = this.balance(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getOpeningDate() { return openingDate; } public void setOpeningDate(Date openingDate) { this.openingDate = openingDate; } public List<TransactionV1> getTransactions() { return transactions; } public void setTransactions(List<TransactionV1> transactions) { this.transactions = transactions; } public BigDecimal getBalance() { return balance; } private BigDecimal balance() { BigDecimal totalBalance = new BigDecimal(0); for (TransactionV1 transaction : transactions) { if (transaction.getAmount() != null) totalBalance = totalBalance.add(transaction.getAmount()); } return totalBalance; } }
C++
UTF-8
1,501
2.84375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #include <unistd.h> int i4c(char a) { return a-48; } int Isthe2DigNumOk(char a,char b) { if (i4c(a)== 1 || (i4c(a) == 2 && i4c(b) >= 0 && i4c(b) <= 6)) { return 1; } else { return 0; } } int findWrongDecodes(char* num) { int len = strlen(num); int res[len]; int j = 0; for(int i=0;i<len;i++) { res[i] =0; //consecutive Zeros if((i <= len-2) && i4c(num[i])== 0 && i4c(num[i+1]) == 0) { return 0; } //anything like 50,70 in string if((i >= 1) && i4c(num[i])== 0 && i4c(num[i-1]) > 2) { return 0; } } for(int i = len-1; i >= 0; i--) { if (j==0) { if(i4c(num[i]) >= 1 && i4c(num[i]) <= 9) res[i] = 1; else res[i] = 0; j++; continue; } if (j==1) { if(Isthe2DigNumOk(num[i],num[i+1])) res[i] = res[i+1] + 1; else if(i4c(num[i]) == 0) { res[i] = 0; } else { res[i] = res[i+1]; } j++; continue; } if (Isthe2DigNumOk(num[i],num[i+1])) { res[i] = res[i+1] + res[i+2]; } else { if(i4c(num[i]) == 0) { res[i] = 0; } else { res[i] = res[i+1]; } } } return res[0]; } int main(int argc, char const *argv[]) { while(1) { char *num = (char*)malloc(5001*sizeof(char)); cin>>num; if(strlen(num) == 1 && num[0] == '0') { break; } int result = findWrongDecodes(num); delete(num); cout<<result; cout<<"\n"; } return 0; }
Python
UTF-8
1,065
2.671875
3
[]
no_license
# html session css # http://docs.cherrypy.org/en/latest/tutorials.html import os, os.path import random import string import cherrypy class StringGenerator(object): @cherrypy.expose def index(self): return """ <html> <head> <link href="/static/css/style.css" rel="stylesheet"> </head> <body> <form method="get" action="generate"> <input type="text" value="8" name="length" /> <button type="submit">Give it now</button> </form> </body> </html>""" @cherrypy.expose def generate(self, length=8): rd_string = ''.join(random.sample(string.hexdigits, int(length))) cherrypy.session['rdstring'] = rd_string return rd_string @cherrypy.expose def display(self): return cherrypy.session['rdstring'] if __name__ == '__main__': conf = { '/': { 'tools.sessions.on': True, 'tools.staticdir.root': os.path.abspath(os.getcwd()) }, '/static': { 'tools.staticdir.on': True, 'tools.staticdir.dir': './public' } } cherrypy.quickstart(StringGenerator(), '/', conf)
Python
UTF-8
2,804
2.8125
3
[]
no_license
import unittest from unittest.mock import patch import requests from bs4 import BeautifulSoup from crawler_world import ( get_page, page_is_404, assemble_url_page, get_search_page_links, num_search_pages, request_redirected, ) def search_results_counter(bs_search_obj) -> int: counter = bs_search_obj.find('span', {'class': 'fleft tab selected'}).find('span', class_='counter').get_text() result_num = ''.join([char for char in counter if char.isdigit()]) return int(result_num) def test_search_html(): with open('test_search.html') as f: data = f.read() return data def test_offer_html(): with open('test_offer.html') as f: data = f.read() return data class SearchPageTest(unittest.TestCase): def setUp(self): self.valid_url = 'https://www.otomoto.pl/osobowe/audi/a4/' self.valid_url_resp = requests.get(self.valid_url) self.page_404 = 'https://www.otomoto.pl/osobowe/kaudi/a4/' self.page_404_resp = requests.get(self.page_404) self.page_redirected = 'https://www.otomoto.pl/osobowe/audi/jibrish/' self.static_search_page = test_search_html() self.static_search_page_bs_obj = BeautifulSoup(self.static_search_page, 'html.parser') self.offer_page = test_offer_html() self.offer_page_bs_obj = BeautifulSoup(self.offer_page, 'html.parser') def test_page_is_404(self): self.assertTrue(page_is_404(self.page_404_resp)) self.assertFalse(page_is_404(self.valid_url_resp)) def test_request_redirected(self): res = requests.get(self.valid_url) redirected = requests.get(self.page_redirected) self.assertTrue(request_redirected(self.page_redirected, redirected)) self.assertFalse(request_redirected(self.valid_url, res)) def test_get_page(self): self.assertIsInstance(get_page(self.valid_url), BeautifulSoup) @patch('crawler_world.ask_for_manufacturer', return_value='audi') @patch('crawler_world.ask_for_model', return_value='a4') def test_assemble_url_page(self, manuf, model): res = assemble_url_page() self.assertEqual(res, self.valid_url) self.assertIsInstance(res, str) def test_get_search_page_links(self): bs_obj = BeautifulSoup(requests.get(self.valid_url).text, 'html.parser') links = get_search_page_links(bs_obj) self.assertIsInstance(links, list) for link in links: self.assertEqual(requests.get(link).status_code, 200) def test_num_search_pages(self): page_obj = self.static_search_page_bs_obj res = num_search_pages(page_obj) self.assertTrue(res.isdigit()) self.assertIsInstance(res, str) self.assertEqual(res, str(2)) if __name__ == '__main__': unittest.main()
Ruby
UTF-8
1,053
2.515625
3
[ "MIT" ]
permissive
require 'sge_tagger' include SGETagger describe Tagger do TEMP_DIR = 'tmp' DIR1 = 'dir1' context 'tmp dir containing one file and one dir' do before(:each) do # make a dir containing one file and one dir FileUtils.rm_rf(TEMP_DIR) Dir.mkdir TEMP_DIR Dir.chdir TEMP_DIR do File.open('sge.txt', 'w+') { |file| file << "sge owned" } Dir.mkdir(DIR1) end end after(:each) do Dir.chdir '..' FileUtils.rm_rf(TEMP_DIR) end describe "#taggable_files" do it 'does not count directories' do tf = Tagger.taggable_files(TEMP_DIR) tf.count.should == 1 end context 'file nested in a dir' do it 'includes files in nested dir' do # add folder one level down file = File.join(TEMP_DIR, DIR1) file = File.join(file, "inner_file.txt") File.open(file, 'w+') { |f| f << "inner file" } tf = Tagger.taggable_files(TEMP_DIR) tf.count.should == 2 end end end end end
Java
UTF-8
1,446
1.921875
2
[ "Apache-2.0", "Elastic-2.0", "SSPL-1.0", "LicenseRef-scancode-other-permissive" ]
permissive
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.health.node; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.core.Nullable; import org.elasticsearch.health.HealthStatus; import java.io.IOException; /** * The health status of the disk space of this node along with the cause. */ public record DiskHealthInfo(HealthStatus healthStatus, @Nullable Cause cause) implements Writeable { DiskHealthInfo(HealthStatus healthStatus) { this(healthStatus, null); } public DiskHealthInfo(StreamInput in) throws IOException { this(in.readEnum(HealthStatus.class), in.readOptionalEnum(Cause.class)); } @Override public void writeTo(StreamOutput out) throws IOException { healthStatus.writeTo(out); out.writeOptionalEnum(cause); } public enum Cause { NODE_OVER_HIGH_THRESHOLD, NODE_OVER_THE_FLOOD_STAGE_THRESHOLD, FROZEN_NODE_OVER_FLOOD_STAGE_THRESHOLD, NODE_HAS_NO_DISK_STATS } }
Java
UTF-8
1,413
2.890625
3
[]
no_license
package gyakorlat2; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; public class Client2 { public static void main(String[] args) throws IOException { Socket socket = new Socket("localhost", 12345); System.out.println("A kliens csatlakozott a szerverhez."); PrintWriter pw = new PrintWriter(socket.getOutputStream(), true); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); Scanner sc = new Scanner(System.in); System.out.println("Adja meg a nevet: "); String name = sc.nextLine(); pw.println(name); String message = ""; String receive = ""; do { receive = br.readLine(); receive = receive.trim(); System.out.println(name+" - szervertol kapott uzenet: "+receive); if (!receive.contains("quit")) { System.out.println("Irja be az elkuldendo uzenetet: "); message = sc.nextLine(); message = message.trim(); pw.println(message); System.out.println(name+" - kuldott uzenet: "+message); } } while(!receive.contains("quit") && !message.equals("quit")); socket.close(); } }
TypeScript
UTF-8
1,475
2.59375
3
[]
no_license
import { ActionsTestData } from '../../shared/interfaces/actionTestData'; import { testTopDebts } from '../test-data'; import { DebtsListActionTypes, DebtsListActions } from './types'; import { loadDebtsStart, loadDebtsSuccess, loadDebtsError } from './actions'; describe('Debts Filter Actions', () => { const testData: ActionsTestData<DebtsListActions, DebtsListActionTypes> = [ { action: loadDebtsStart(), expectedType: DebtsListActionTypes.loadDebtsStart }, { action: loadDebtsSuccess({ debts: testTopDebts }), expectedType: DebtsListActionTypes.loadDebtsSuccess, expectedPayload: { debts: testTopDebts } }, { action: loadDebtsSuccess({ debts: testTopDebts, totalDebtsCount: 99 }), expectedType: DebtsListActionTypes.loadDebtsSuccess, expectedPayload: { debts: testTopDebts, totalDebtsCount: 99 } }, { action: loadDebtsError(), expectedType: DebtsListActionTypes.loadDebtsFailed, expectedPayload: { errorMessage: undefined } }, { action: loadDebtsError('Sample error'), expectedType: DebtsListActionTypes.loadDebtsFailed, expectedPayload: { errorMessage: 'Sample error' } } ]; testData.forEach(({ action, expectedType, expectedPayload }) => { it(`should create an action of type ${expectedType}`, () => { expect(action.type).toEqual(expectedType); expect((action as any).payload).toEqual(expectedPayload); }); }); });
Python
UTF-8
105
3.609375
4
[]
no_license
def factorial1(x): if x==0: return 1 else: return x*factorial1(x-1) print(factorial1(4))