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
Java
UTF-8
971
1.875
2
[]
no_license
package e.datvo_000.jp9shop.Model.Object; import android.content.Intent; public class SoDiaChi { String email,name,phone,address; int ma; int macdinh; public int getMa() { return ma; } public void setMa(int ma) { this.ma = ma; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getMacdinh() { return macdinh; } public void setMacdinh(int macdinh) { this.macdinh = macdinh; } }
Python
UTF-8
82
3.234375
3
[]
no_license
pemrograman = ["Java", "PHP", "Python", "C++"] for x in pemrograman: print(x)
Java
UTF-8
670
2.4375
2
[]
no_license
package com.cinema.services.impl; /** * * @author Valentin Fadloun * **/ import org.springframework.stereotype.Service; import com.cinema.models.Salle; import com.cinema.repositories.SalleRepository; import com.cinema.services.SalleService; import com.cinema.services.crud.impl.CRUDServiceImpl; /** * * Création de la classe Service pour les Salles qui implément l'interface Salle Service * */ @Service public class SalleServiceImpl extends CRUDServiceImpl<Salle> implements SalleService{ /** * Constructeur permettant de donner le repository utilisé au CRUD Général * @param repo */ public SalleServiceImpl(SalleRepository repo) { super(repo); } }
Java
UTF-8
13,408
1.828125
2
[]
no_license
package com.equivi.mailsy.service.mailgun; import com.equivi.mailsy.service.constant.dEmailerWebPropertyKey; import com.equivi.mailsy.service.mailgun.response.MailgunResponseEventMessage; import com.equivi.mailsy.service.mailgun.response.MailgunResponseMessage; import com.equivi.mailsy.service.mailgun.response.UnsubscribeResponse; import com.equivi.mailsy.service.mailgun.response.UnsubscribeResponseItems; import com.equivi.mailsy.service.rest.client.DemailerRestTemplate; import com.equivi.mailsy.util.MailsyStringUtil; import com.equivi.mailsy.web.constant.WebConfiguration; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import gnu.trove.map.hash.THashMap; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.HttpClientErrorException; import javax.annotation.Resource; import java.io.IOException; import java.util.List; import java.util.Map; @Service("mailgunRestTemplateEmailService") public class MailgunRestTemplateEmailServiceImpl implements MailgunService { private static final Logger LOG = LoggerFactory.getLogger(MailgunRestTemplateEmailServiceImpl.class); private static final String API_USERNAME = "api"; private static final String DOMAIN_SANDBOX = "sandbox80dd6c12cf4c4f99bdfa256bfea7cfeb.mailgun.org"; private static final ObjectMapper objectMapper = new ObjectMapper(); static { objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } @Resource private WebConfiguration webConfiguration; @Resource private DemailerRestTemplate demailerRestTemplate; @Override public String sendMessage(String campaignId, String domain, String from, List<String> recipientList, List<String> ccList, List<String> bccList, String subject, String message) { String mailgunWebURLApi = buildSendMessageURL(campaignId, getDomain(domain), from, recipientList, ccList, bccList, subject, message); setupHttpClientCredentials(mailgunWebURLApi); ResponseEntity<String> response = demailerRestTemplate.postForEntity(mailgunWebURLApi, buildHttpEntity(), String.class); if (response != null) { try { LOG.debug("HTTP Status code :" + response.getStatusCode()); String responseBody = response.getBody(); LOG.debug("Response From mailgun:" + responseBody); MailgunResponseMessage mailgunResponseMessage = objectMapper.readValue(responseBody, MailgunResponseMessage.class); return mailgunResponseMessage.getId(); } catch (JsonMappingException e) { LOG.error(e.getMessage(), e); } catch (JsonParseException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } } else { LOG.error("Unable to get Response during send message"); } return null; } private void setupHttpClientCredentials(String mailgunWebURLApi) { String mailgunAPIKey = webConfiguration.getWebConfig(dEmailerWebPropertyKey.MAILGUN_API_KEY); demailerRestTemplate.setCredentials(API_USERNAME, mailgunAPIKey) .setHostName(mailgunWebURLApi); demailerRestTemplate.setHttpClientFactory(); } @Override public MailgunResponseEventMessage getEventForMessageId(String messageId) { String mailgunEventAPIURL = formatMailgunHostUrl(getMailgunBaseAPIURL(), DOMAIN_SANDBOX, MailsyStringUtil.buildQueryParameters(buildEventParameter(messageId)), MailgunAPIType.EVENTS.getValue()); setupHttpClientCredentials(mailgunEventAPIURL); ResponseEntity<String> response = demailerRestTemplate.getForEntity(mailgunEventAPIURL, String.class); if (response != null) { try { LOG.debug("HTTP Status code :" + response.getStatusCode()); String responseBody = response.getBody(); LOG.debug("Response From mailgun:" + responseBody); MailgunResponseEventMessage mailgunResponseEventMessage = objectMapper.readValue(responseBody, MailgunResponseEventMessage.class); return mailgunResponseEventMessage; } catch (JsonMappingException e) { LOG.error(e.getMessage(), e); } catch (JsonParseException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } } else { LOG.error("Unable to get Response during send message"); } return null; } @Override public String sendMessageWithAttachment(String campaignId, String domain, String from, List<String> recipientList, List<String> ccList, List<String> bccList, String subject, String message) { return null; } private String buildSendMessageURL(String campaignId, String domain, String from, List<String> recipientList, List<String> ccList, List<String> bccList, String subject, String message) { Map<String, String> mailParameter = buildSendParameters(campaignId, from, recipientList, ccList, bccList, subject, message); return formatMailgunHostUrl(getMailgunBaseAPIURL(), domain, MailsyStringUtil.buildQueryParameters(mailParameter), MailgunAPIType.MESSAGES.getValue()); } String formatMailgunHostUrl(String mailgunBaseURL, String domain, String queryParameters, String resource) { StringBuilder builderMailgunURL = new StringBuilder(); builderMailgunURL.append(mailgunBaseURL); builderMailgunURL.append("/"); builderMailgunURL.append(domain); builderMailgunURL.append("/"); builderMailgunURL.append(resource); if (!StringUtils.isEmpty(queryParameters)) { builderMailgunURL.append("?"); builderMailgunURL.append(queryParameters); } return builderMailgunURL.toString(); } HttpEntity buildHttpEntity() { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON); return new HttpEntity(httpHeaders); } Map<String, String> buildSendParameters(String campaignId, String from, List<String> recipientList, List<String> ccList, List<String> bccList, String subject, String message) { Map<String, String> mailParameter = new THashMap<>(); mailParameter.put(MailgunParameters.FROM.getValue(), from); mailParameter.put(MailgunParameters.TO.getValue(), MailsyStringUtil.buildStringWithSeparator(recipientList, ',')); mailParameter.put(MailgunParameters.CC.getValue(), MailsyStringUtil.buildStringWithSeparator(ccList, ',')); mailParameter.put(MailgunParameters.BCC.getValue(), MailsyStringUtil.buildStringWithSeparator(bccList, ',')); mailParameter.put(MailgunParameters.SUBJECT.getValue(), subject); mailParameter.put(MailgunParameters.HTML.getValue(), StringEscapeUtils.unescapeHtml4(message)); mailParameter.put(MailgunParameters.TRACKING.getValue(), "yes"); mailParameter.put(MailgunParameters.TRACKING_CLICKS.getValue(), "yes"); mailParameter.put(MailgunParameters.TRACKING_OPEN.getValue(), "yes"); return mailParameter; } Map<String, String> buildEventParameter(String messageId) { Map<String, String> mailParameter = new THashMap<>(); mailParameter.put(MailgunParameters.MESSAGE_ID.getValue(), messageId); return mailParameter; } Map<String, String> buildUnsubscribeParameter(String emailAddress) { Map<String, String> mailParameter = new THashMap<>(); mailParameter.put(MailgunParameters.ADDRESS.getValue(), emailAddress); mailParameter.put(MailgunParameters.TAG.getValue(), "*"); return mailParameter; } @Override public void deleteUnsubscribe(String domain, String emailAddress) { String deleteUnsubscribeURL = buildUnsubscribeUrl(domain, emailAddress); setupHttpClientCredentials(deleteUnsubscribeURL); try { LOG.info("Delete unsubscribe :" + emailAddress); demailerRestTemplate.delete(deleteUnsubscribeURL, String.class); } catch (HttpClientErrorException hex) { if (hex.getStatusCode().equals(HttpStatus.NOT_FOUND)) { LOG.error("Email address:" + emailAddress + " not found in unsubscribe list"); } else { LOG.error(hex.getMessage(), hex); throw new RuntimeException(hex); } } } @Override public void registerUnsubscribe(String domain, String emailAddress) { String registerUnsubscribeUrl = buildRegisterUnsubscribeUrl(domain, emailAddress); setupHttpClientCredentials(registerUnsubscribeUrl); ResponseEntity<String> response = demailerRestTemplate.postForEntity(registerUnsubscribeUrl, buildHttpEntity(), String.class); if (response != null) { LOG.debug("Register unsubscribe :" + emailAddress + " ,HTTP Status code :" + response.getStatusCode()); String responseBody = response.getBody(); LOG.debug("Response From mailgun:" + responseBody); } else { LOG.error("Unable to get Response during send message"); } } @Override public List<String> getUnsubscribeList(String domain) { String getUnsubscibeListUrl = buildUnsubscribeUrl(getDomain(domain), null); setupHttpClientCredentials(getUnsubscibeListUrl); ResponseEntity<UnsubscribeResponse> response = demailerRestTemplate.getForEntity(getUnsubscibeListUrl, UnsubscribeResponse.class); if (response != null) { UnsubscribeResponse responseBody = response.getBody(); return getUnsubscribeEmailAddress(responseBody); } else { LOG.error("Unable to get Response during send message"); } return Lists.newArrayList(); } private List<String> getUnsubscribeEmailAddress(UnsubscribeResponse responseBody) { List<String> unsubscribeEmailAddressList = Lists.newArrayList(); if (responseBody.getTotal() > 0) { for (UnsubscribeResponseItems item : responseBody.getItems()) { unsubscribeEmailAddressList.add(item.getAddress()); } return unsubscribeEmailAddressList; } return Lists.newArrayList(); } @Override public boolean checkIfEmailAddressHasBeenUnsubscribed(String domain, String emailAddress) { String unsubscribeUrl = buildRegisterUnsubscribeUrl(getDomain(domain), emailAddress); setupHttpClientCredentials(unsubscribeUrl); ResponseEntity<String> response = demailerRestTemplate.getForEntity(unsubscribeUrl, String.class); if (response != null) { LOG.debug("Check is unsubscribe :" + emailAddress + " ,HTTP Status code :" + response.getStatusCode()); String responseBody = response.getBody(); LOG.debug("Response From mailgun:" + responseBody); try { UnsubscribeResponse unsubscribeResponse = objectMapper.readValue(responseBody, UnsubscribeResponse.class); return unsubscribeResponse.getTotal() > 0; } catch (IOException e) { LOG.error("Unable to get Response during send message"); } LOG.debug("Response From mailgun:" + responseBody); } else { LOG.error("Unable to get Response during send message"); } return false; } private String buildUnsubscribeUrl(String domain, String emailAddress) { StringBuilder sbUnsubscriberURL = new StringBuilder(); String mailgunEventAPIURL = formatMailgunHostUrl(getMailgunBaseAPIURL(), getDomain(domain), null, MailgunAPIType.UNSUBSCRIBES.getValue()); sbUnsubscriberURL.append(mailgunEventAPIURL); if (!StringUtils.isEmpty(emailAddress)) { sbUnsubscriberURL.append("/"); sbUnsubscriberURL.append(emailAddress); } return sbUnsubscriberURL.toString(); } private String buildRegisterUnsubscribeUrl(String domain, String emailAddress) { String mailgunEventAPIURL = formatMailgunHostUrl(getMailgunBaseAPIURL(), getDomain(domain), MailsyStringUtil.buildQueryParameters(buildUnsubscribeParameter(emailAddress)), MailgunAPIType.UNSUBSCRIBES.getValue()); return mailgunEventAPIURL; } private String getDomain(String domain) { if (StringUtils.isEmpty(domain)) { domain = DOMAIN_SANDBOX; } return domain; } String getMailgunBaseAPIURL() { return webConfiguration.getWebConfig(dEmailerWebPropertyKey.MAILGUN_WEB_URL); } }
Markdown
UTF-8
833
2.609375
3
[]
no_license
# 最终状态 ## 视频示例 <video controls height='100%' width='100%' src="https://encooacademy.oss-cn-shanghai.aliyuncs.com/activity/FinalState.mp4"></video> ## 概述 “最终状态”组件是状态机中使用的组件,是状态机工作流的基础组成部分。状态机工作流中必须包含一个“最终状态”组件。 > **说明:** >“状态”组件必须放置在“状态机”组件中。 “最终状态”组件包括一个可编辑区域: - Entry 区域:包含在 Entry 区域的组件会在工作流进入该*最终状态*组件时被执行。 ## 属性 ### 基本 参见 [通用配置项](../../Appendix/CommonConfigurationItems.md)。 ## 使用示例 一般与**状态机**组件搭配使用,操作样例可参见[状态机](../../WorkflowControl/StateMachine/StateMachine.md)。
Rust
UTF-8
7,545
2.640625
3
[]
no_license
use crate::ast::*; use crate::target; use crate::target::currency::Currency; #[derive(Debug, Default)] pub struct Context { pub environment: crate::environment::Environment, pub contract_declaration_context: Option<ContractDeclarationContext>, pub contract_behaviour_declaration_context: Option<ContractBehaviourDeclarationContext>, pub struct_declaration_context: Option<StructDeclarationContext>, pub function_declaration_context: Option<FunctionDeclarationContext>, pub special_declaration_context: Option<SpecialDeclarationContext>, pub trait_declaration_context: Option<TraitDeclarationContext>, pub scope_context: Option<ScopeContext>, pub asset_context: Option<AssetDeclarationContext>, pub block_context: Option<BlockContext>, pub function_call_receiver_trail: Vec<Expression>, pub is_property_default_assignment: bool, pub is_function_call_context: bool, pub is_function_call_argument: bool, pub is_function_call_argument_label: bool, pub external_call_context: Option<ExternalCall>, pub is_external_function_call: bool, pub in_assignment: bool, pub in_if_condition: bool, pub in_become: bool, pub is_lvalue: bool, pub in_subscript: bool, pub is_enclosing: bool, pub in_emit: bool, pub pre_statements: Vec<Statement>, pub post_statements: Vec<Statement>, pub target: Target, } impl Context { pub fn enclosing_type_identifier(&self) -> Option<&Identifier> { self.contract_behaviour_declaration_context .as_ref() .map(|c| &c.identifier) .or_else(|| { self.struct_declaration_context .as_ref() .map(|c| &c.identifier) .or_else(|| { self.contract_declaration_context .as_ref() .map(|c| &c.identifier) .or_else(|| self.asset_context.as_ref().map(|c| &c.identifier)) }) }) } pub fn is_trait_declaration_context(&self) -> bool { self.trait_declaration_context.is_some() } pub(crate) fn in_function_or_special(&self) -> bool { self.function_declaration_context.is_some() || self.special_declaration_context.is_some() } pub fn scope_context(&self) -> Option<&ScopeContext> { self.scope_context.as_ref() } pub fn type_states(&self) -> &[TypeState] { self.contract_behaviour_declaration_context .as_ref() .map(|c| &*c.type_states) .unwrap_or(&[]) } pub fn caller_protections(&self) -> &[CallerProtection] { self.contract_behaviour_declaration_context .as_ref() .map(|c| &*c.caller_protections) .unwrap_or(&[]) } pub fn scope_or_default(&self) -> &ScopeContext { self.scope_context.as_ref().unwrap_or_default() } pub fn declaration_context_type_id(&self) -> Option<&str> { self.contract_behaviour_declaration_context .as_ref() .map(|c| &*c.identifier.token) .or_else(|| { self.struct_declaration_context .as_ref() .map(|c| &*c.identifier.token) .or_else(|| self.asset_context.as_ref().map(|c| &*c.identifier.token)) }) } } #[derive(Clone, Debug, Default)] pub struct Target { pub name: &'static str, pub currency: Currency, } impl From<&target::Target> for Target { fn from(target: &target::Target) -> Self { Target { name: target.name, currency: target.currency.clone(), } } } #[derive(Debug)] pub struct ContractDeclarationContext { pub identifier: Identifier, } #[derive(Debug, Clone)] pub struct ContractBehaviourDeclarationContext { pub identifier: Identifier, pub caller: Option<Identifier>, pub type_states: Vec<TypeState>, pub caller_protections: Vec<CallerProtection>, } #[derive(Debug, Clone)] pub struct StructDeclarationContext { pub identifier: Identifier, } #[derive(Debug, Default, Clone)] pub struct FunctionDeclarationContext { pub declaration: FunctionDeclaration, pub local_variables: Vec<VariableDeclaration>, } impl FunctionDeclarationContext { pub fn mutates(&self) -> Vec<Identifier> { self.declaration.mutates() } } #[derive(Debug, Clone)] pub struct SpecialDeclarationContext { pub declaration: SpecialDeclaration, pub local_variables: Vec<VariableDeclaration>, } #[derive(Debug, Clone)] pub struct TraitDeclarationContext { pub identifier: Identifier, } #[derive(Debug, Clone)] pub struct BlockContext { pub scope_context: ScopeContext, } #[derive(Debug, Default, Clone, PartialEq)] pub struct ScopeContext { pub parameters: Vec<Parameter>, pub local_variables: Vec<VariableDeclaration>, pub counter: u64, } impl ScopeContext { fn first_local_or_parameter<P: Fn(&VariableDeclaration) -> bool>( &self, predicate: P, ) -> Option<VariableDeclaration> { self.local_variables .iter() .find(|&p| predicate(p)) .cloned() .or_else(|| { self.parameters .iter() .map(Parameter::as_variable_declaration) .find(predicate) }) } pub fn is_declared(&self, name: &str) -> bool { self.declaration(name).is_some() } pub fn declaration(&self, name: &str) -> Option<VariableDeclaration> { self.first_local_or_parameter(|v: &VariableDeclaration| v.identifier.token.as_str() == name) } pub fn type_for(&self, variable: &str) -> Option<Type> { self.first_local_or_parameter(|v| v.identifier.token == variable) .map(|i| i.variable_type) } pub fn contains_variable_declaration(&self, name: &str) -> bool { self.local_variables .iter() .map(|v| &*v.identifier.token) .any(|id| id == name) } pub fn contains_parameter_declaration(&self, name: &str) -> bool { self.parameters .iter() .map(|p| &*p.identifier.token) .any(|id| id == name) } pub fn fresh_identifier(&mut self, line_info: LineInfo) -> Identifier { self.counter += 1; let count = self.local_variables.len() + self.parameters.len() + self.counter as usize; let name = format!("temp__{}", count); Identifier { token: name, enclosing_type: None, line_info, } } pub fn enclosing_parameter(&self, expression: &Expression, type_id: &str) -> Option<String> { let expression_enclosing = expression.enclosing_type().unwrap_or_default(); if expression_enclosing == type_id { if let Some(enclosing_identifier) = expression.enclosing_identifier() { if self.contains_parameter_declaration(&enclosing_identifier.token) { return Some(enclosing_identifier.token.clone()); } } } None } } const DEFAULT_SCOPE_CONTEXT_REF: &ScopeContext = &ScopeContext { parameters: vec![], local_variables: vec![], counter: 0, }; impl Default for &ScopeContext { fn default() -> Self { DEFAULT_SCOPE_CONTEXT_REF } } #[derive(Debug, Clone)] pub struct AssetDeclarationContext { pub identifier: Identifier, }
Python
UTF-8
4,025
3.34375
3
[]
no_license
from time import sleep import random hanger=[''' _____ | | | | | _|_''', ''' _____ | | O | | | _|_''', ''' _____ | | O | | | | | _|_''', ''' _____ | | O | /| | | | _|_''', ''' _____ | | O | /|\ | | | _|_''', ''' _____ | | O | /|\ | | | / _|_''', ''' _____ | | O | ~Loser~ /|\ | ~Loser~ | | / \ _|_''',''' ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ \O/ ~WINNER~ | ~WINNER~ | / \ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆'''] #Variable assign #Wrong is what contorls the graphics global wrong wrong = -1 #The word being found name_number = (random.SystemRandom().randint(0, 212)) file_open = open('wrds.txt', 'r') all_lines = file_open.readlines() random_name = (all_lines[name_number]) word = random_name print(word) #Loser count controls the break out of the loop is the player never guesses correctly and loses global losercount losercount = 0 #Asking for a letter, this is in function becasue it is used repetitvley def asker(): global guess guess = (input("What is your letter guess? ")) #The lenght of the world, later used to see the amount of blanks global wordlenth wordlenth = (len(word)) #The amount of blanks needed global blank wordwrite = wordlenth - 1 blank = ["_"]*wordwrite global calc calc = 1 # Finder runs through each character of the word and searches for the guess letter that was inputted. def finder(): Letter_list.append(guess) #Letter is used when searching through the word letter = 0 #Wroner is a counter which is only counted for when the guess letter is not found in a postion of the word wroner = 0 while letter < wordlenth: if guess == (word[letter]): #print(word[letter]) #print (letter) blank[letter] = guess #print(blank) letter = letter + 1 global calc calc = calc + 1 else: letter = letter + 1 wroner = wroner + 1 global losercount losercount = losercount + 1 if wroner == wordlenth: global wrong wrong = wrong + 1 #wrong counts what graphic to display from the array hanger if wrong != 7: print(hanger[wrong]) #converts array to a string print ('' .join(blank)) global blanks blanks = (''.join(blank)) #asker and finder are the fucntions and must be ran before once because they give calues for the loop Letter_list = [] asker() finder() #The while loop controlling everything while 1: #If the blanks dont equal the word ask for another letter and run finder if blanks != word: asker() if guess in Letter_list: print("Letter has already been used before!") else: finder() #If los if wrong == 6: print(word) break if calc == wordlenth: #Prints winner when the blank and word match print(hanger[7]) break
TypeScript
UTF-8
2,678
2.609375
3
[ "MIT" ]
permissive
import { Deferred } from 'concurrency.libx.js'; import { helpers } from '../helpers'; import { IDeferred, Mapping } from '../types/interfaces'; import { log } from './log'; class QueueWorkerItem<T> { item: T; promises: Deferred<any>[]; } export class QueueWorker<TIn, TOut> { private queue: Mapping<QueueWorkerItem<TIn>> = {}; private current: Mapping<QueueWorkerItem<TIn>> = {}; private faultsCountDown: number; private processor: (item: TIn, id?: string) => Promise<TOut> = null; private maxConcurrent: number; private context: any; constructor(_processor: (item: TIn, id?: String) => Promise<TOut>, context?: any, _maxConcurrent = 1, _faultsCountDown = 3) { this.processor = _processor; this.context = context; this.faultsCountDown = _faultsCountDown; this.maxConcurrent = _maxConcurrent; } public async enqueue(item: TIn, id?: string): Promise<TOut> { let p = helpers.newPromise<TOut, any>(); id = id || helpers.randomNumber().toString(); let handler = this.queue[id]; if (handler == null) handler = this.queue[id] = { item: item, promises: [] }; handler.promises.push(p); this.cycle(); return p; } private async cycle(): Promise<void> { let keys = Object.keys(this.queue); if (keys.length == 0) { return; } if (this.maxConcurrent > 0 && Object.keys(this.current).length >= this.maxConcurrent) { return; } let id = keys[0]; let job = this.queue[id]; delete this.queue[id]; this.current[id] = job; this.processor .apply(this.context, [job.item, id]) .catch((ex) => { log.w('QueueWorker:cycle: Error processing item', job.item, ex); this.faultsCountDown--; if (this.faultsCountDown == 0) { job.promises.forEach((x) => x.reject(new Error('QueueWorker:cycle: Could not recover from repeated failures! ex: ' + ex.response)) ); return; } this.enqueue(job.item, id); // push it back to the queue }) .then((out) => { delete this.current[id]; job.promises.forEach((x) => x.resolve(out)); }) .finally(() => { this.tickNext(); }); this.tickNext(); } private async tickNext() { if (typeof setImmediate != 'undefined') setImmediate(this.cycle.bind(this)); else setTimeout(this.cycle.bind(this), 1); } }
Java
UTF-8
422
2.53125
3
[ "Apache-2.0" ]
permissive
package co.speedar.infra.itcool.love; public class LoveXiaominMoreEveryDay { public static void main(String[] args) { Runnable loveXiaominMoreEveryDay = () -> { int theDayWeMet = 18126; int myLoveToYou = 10; int endOfWorld = Integer.MAX_VALUE; for (int day = theDayWeMet; day < endOfWorld; day++) { myLoveToYou++; } }; Thread t = new Thread(loveXiaominMoreEveryDay, "Xuanbin"); t.start(); } }
Shell
UTF-8
350
3.140625
3
[]
no_license
#!/bin/bash function run_test() { for ((i=1;i<=1000;i+=1)); do echo Round $i wrk -t 10 -c 10 --latency http://localhost:8080/empty-test-app/empty/index if [ $? -ne 0 ]; then exit 1 fi let modulus=$i%3 if [ $modulus -eq 0 ]; then echo Wait 10 secs sleep 10 fi done } run_test
Java
UTF-8
498
1.671875
2
[]
no_license
package rocksdb.constant; import com.lightgraph.graph.constant.GraphConstant; public class RocksConstant { public static final String ROCKSDB_DATA_PATH = "rocksdb.data.path"; public static final String ROCKSDB_DATA_PATH_DEFAULT = GraphConstant.GRAPH_HOME + "/data"; public static final String ROCKSDB_ALLOCATE_PATH_STRATEGY = "rocksdb.allocate.path.strategy"; public static final String ROCKSDB_ALLOCATE_PATH_STRATEGY_DEFAULT = "rocksdb.strategy.HashAllocateStorageStrategy"; }
C++
UTF-8
2,669
3.140625
3
[]
no_license
#include <stdio.h> #include <iostream> using namespace std; const int NODES = 6; const int ARCS = 9; //these are the start and end point for the graph traversal const int START = 0; const int END = 3; void FillAdjacencyMatrix( int A[NODES][NODES], int G[ARCS*2+NODES][3] ); //fills the adjacency matrix with the distances between nodes of the graph void Dijkstras( int A[NODES][NODES] ); //finds the shortest path of the graph, using the adjacency matrix for distances int main( int argc, char** argv ) { int A[NODES][NODES]; int G[ARCS*2+NODES][3] ; //initialize the adjacency matrix with -1 for( int i = 0; i < NODES; i++ ) { for( int j = 0; j < NODES; j++ ) { A[i][j] = -1; } } printf( "%s", "Please enter your graph\n" ); for( int i = 0; i < ARCS*2+NODES; i++ ) { for( int j = 0; j < 3; j++ ) { cin>>G[i][j]; } } //fill A with the adjacencies from G FillAdjacencyMatrix( A, G ); Dijkstras( A ); return 0; } void FillAdjacencyMatrix( int A[NODES][NODES], int G[ARCS*2+NODES][3] ) { int pseudoPtr; int temp; int child; for( int n = 0; n < NODES; n++ ) { temp = n; while( G[temp][2] != -1 ) { pseudoPtr = G[temp][2]; child = G[pseudoPtr][0]; A[n][child] = G[pseudoPtr][1]; temp = pseudoPtr; } } } void Dijkstras( int A[NODES][NODES] ) { //this holds the values of the distances between nodes int IN[NODES]; int p; int d[NODES]; int s[NODES]; int dI; //initialize all elements of IN to -1 for( int i = 0; i < NODES; i++ ) { IN[i] = -1; } //put START in IN IN[START] = START; //fill the d array with the distances from the start for( int i = 0; i < NODES; i++ ) { d[i] = A[START][i]; s[i] = START; } //distance from START to START is always 0 d[START] = 0; //while the end hasnt been reached while( IN[END] != END ) { //set first node not in IN to p for( int i = 0; i < NODES; i++ ) { if( IN[i] == -1 ) { p = i; dI = d[i]; break; } } //compare to ensure shortest distance is next p for( int i = 0; i < NODES; i++ ) { //if not in IN if( d[i] > 0 ) { //if i has the shortest distance, i not in IN if( d[i] < d[p] && IN[i] == -1 ) { p = i; dI = d[i]; } } } IN[p] = p; //find the distances of the nodes not in IN for( int i = 1; i < NODES; i++ ) { if( IN[i] == -1 ) { if( ( ( d[i] > dI + A[p][i] ) || d[i] == -1 ) && A[p][i] > 0 ) { d[i] = dI + A[p][i]; s[i] = p; } } } } int i = END; printf( "%s %d %c","The shortest path is: ", END, ' ' ); while( i != START ) { printf( "%d %c", s[i], ' ' ); i = s[i]; } cout<<endl; }
JavaScript
UTF-8
381
2.515625
3
[]
no_license
//quantity //currentPrice //updateBalance() -->puts currentPrice in avePrice send buy function to chris myApp.controller('BuyController', ['fleaMarketService', function(fleaMarketService) { console.log("BuyController sourced!"); var buy = this; buy.submit = function(){ console.log('in BuyController'); }; buy.currentPrice = fleaMarketService.currentPrice; }]);
Java
UTF-8
393
2.578125
3
[]
no_license
@Test public void testInterceptorIsInvokedWithNoTarget() throws Throwable { // Test return value final int age = 25; MethodInterceptor mi = (invocation -> age); AdvisedSupport pc = new AdvisedSupport(ITestBean.class); pc.addAdvice(mi); AopProxy aop = createAopProxy(pc); ITestBean tb = (ITestBean) aop.getProxy(); assertEquals("correct return value", age, tb.getAge()); }
Python
UTF-8
1,314
2.515625
3
[]
no_license
# -*- coding: UTF-8 -*- ''' @Project :bmTest_fastapi @File :dubbo_schemas.py @IDE :PyCharm @Author :junjie @Date :2021/3/4 22:17 ''' from pydantic import BaseModel,validator,Field from typing import Optional import re #创建数据模型 class DubboListBody(BaseModel): url : str = Field(..., title="dubbo接口IP地址",description="必传,格式为IP:端口") serviceName :str=Field(..., title="dubbo接口服务名",description="必传") methodName :str=Field(None, title="dubbo接口方法名",description="不传方法名查全部,否则查对应方法名下的传值类型") @validator('url','serviceName') def checkEmpty(cls,value): if value =='': raise ValueError('必须有值') return value @validator('url') def checkFormat(cls, value): result = re.match(r'(?:(?:[0,1]?\d?\d|2[0-4]\d|25[0-5])\.){3}(?:[0,1]?\d?\d|2[0-4]\d|25[0-5]):\d{0,5}', value) if not result: raise ValueError('不符合格式') return value #继承DubboListBody模型,提高复用性 class DubboInvokeBody(DubboListBody): methodName : str data : dict @validator('methodName') def checkEmpty(cls, value): if value == '': raise ValueError('必须有值') return value
C#
UTF-8
1,484
2.578125
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace Bookstore.Models { public class EmployeeMetadata { [Required] [StringLength(9)] [Display(Name = "Employee's id")] [RegularExpression("[A-Z][A-Z][A-Z][1-9][0-9][0-9][0-9][0-9][FM]+$", ErrorMessage = "ID example: ZZZxyyyyF or ZZZxyyyyM where Z is capital A-Z, x is a number from 1-9 and y from 0-9.")] public string emp_id; [Required] [StringLength(20, ErrorMessage = "The maxlenght of your input is 20 chars")] [Display(Name = "Firstname")] [RegularExpression("^[a-zA-Z _]+$", ErrorMessage = "Only letters accepted.")] public string fname; [StringLength(1, ErrorMessage = "The maxlenght of your input is 1 char")] [Display(Name = "Minit")] [RegularExpression("^[a-zA-Z _]+$", ErrorMessage = "Only letters accepted.")] public string minit; [Required] [StringLength(30,ErrorMessage = "The maxlenght of your input is 30 chars")] [Display(Name = "Lastname")] [RegularExpression("^[a-zA-Z _]+$", ErrorMessage = "Only letters accepted.")] public string lname; [Required] [Display(Name = "Job id")] public int job_id; //[Required] [StringLength(4)] [Display(Name = "Pub id")] public string pub_id; } }
Java
UTF-8
641
1.757813
2
[ "Apache-2.0" ]
permissive
package cn.lilq.smilodon.properties; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.boot.context.properties.ConfigurationProperties; /* * @auther: Li Liangquan * @date: 2021/1/8 16:13 * smilodon.client 客户端配置类 */ @Data @AllArgsConstructor @NoArgsConstructor @ConfigurationProperties(prefix = "smilodon.client") public class SmilodonClientProperties { private Boolean registerWithSmilodon;//是否使用smilodon注册 private Boolean fetchRegistry;//获取注册表-是否启用缓存. private String serviceUrl;//注册中心地址-url. 不为null }
TypeScript
UTF-8
5,806
2.640625
3
[]
no_license
class Main extends egret.DisplayObjectContainer { /** * 加载进度界面 * Process interface loading */ private loadingView: LoadingUI; public constructor() { super(); this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this); } private onAddToStage(event: egret.Event) { //设置加载进度界面 //Config to load process interface this.loadingView = new LoadingUI(); this.stage.addChild(this.loadingView); //初始化Resource资源加载库 //initiate Resource loading library RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this); RES.loadConfig("resource/default.res.json", "resource/"); } /** * 配置文件加载完成,开始预加载preload资源组。 * configuration file loading is completed, start to pre-load the preload resource group */ private onConfigComplete(event: RES.ResourceEvent): void { RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this); RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this); RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this); RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this); RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this); RES.loadGroup("preload"); } /** * preload资源组加载完成 * Preload resource group is loaded */ private onResourceLoadComplete(event: RES.ResourceEvent) { if (event.groupName == "preload") { this.stage.removeChild(this.loadingView); RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this); RES.removeEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this); RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this); RES.removeEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this); this.createGameScene(); } } /** * 资源组加载出错 * The resource group loading failed */ private onItemLoadError(event: RES.ResourceEvent) { console.warn("Url:" + event.resItem.url + " has failed to load"); } /** * 资源组加载出错 * The resource group loading failed */ private onResourceLoadError(event: RES.ResourceEvent) { //TODO console.warn("Group:" + event.groupName + " has failed to load"); //忽略加载失败的项目 //Ignore the loading failed projects this.onResourceLoadComplete(event); } /** * preload资源组加载进度 * Loading process of preload resource group */ private onResourceProgress(event: RES.ResourceEvent) { if (event.groupName == "preload") { this.loadingView.setProgress(event.itemsLoaded, event.itemsTotal); } } private table:egret.DisplayObjectContainer; /** * 创建游戏场景 * Create a game scene */ private createGameScene() { let stageWidth = this.stage.stageWidth; let stageHeight = this.stage.stageHeight; let bg = new egret.Bitmap(); let data: egret.Texture = RES.getRes("back_jpg"); bg.texture = data; bg.width = stageWidth; bg.height = stageHeight; this.addChild(bg); this.table = new egret.DisplayObjectContainer(); this.addChild(this.table); this.refresh(); let simon = new egret.Bitmap(); simon.texture = RES.getRes("simon_png"); simon.width = 110; simon.height = 110; this.addChild(simon); simon.touchEnabled = true; simon.addEventListener(egret.TouchEvent.TOUCH_TAP,this.refresh,this); simon.x = 50; simon.y = 720; // 创建提示信息 let msg:egret.TextField = new egret.TextField(); msg.text = "不开心的时候就捏捏这个,希望你每天都过得开心~~" msg.width = 350; msg.height = 300; msg.textColor = 0x000000; this.addChild(msg); msg.x = 180; msg.y = 730; // 创建版本标志 let vers: egret.TextField = new egret.TextField(); vers.text = "version:1.0\n\nauthor:Simon\n"; vers.width = 200; vers.height = 300; vers.size = 16; vers.x = 10; vers.y = 890; this.addChild(vers); let info:egret.TextField = new egret.TextField(); info.text = "power by egret"; info.width = 200; info.height = 100; info.size = 16; info.x = 400; info.y = 920; this.addChild(info); // let } private refresh(){ this.table.removeChildren(); let r = 50; for(let i = 0;i<6;i++){ for(let j = 0;j<5;j++){ let x:number = 20+r*2*j; let y:number = 40+r*2*i; let circle = new Circle(x,y,r); this.table.addChild(circle); } } } /** * 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。 * Create a Bitmap object according to name keyword.As for the property of name please refer to the configuration file of resources/resource.json. */ private createBitmapByName(name: string) { let result = new egret.Bitmap(); let texture: egret.Texture = RES.getRes(name); result.texture = texture; return result; } }
Java
UTF-8
2,640
2.71875
3
[]
no_license
package com.kimkihwan.me.imagelist.util; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.MappingJsonFactory; import com.kimkihwan.me.imagelist.logger.Log; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; /** * Created by jamie on 1/13/17. */ /** * Jackson tokenizer 파싱 결과 300,000개의 객체를 생성하여 오랜 시간이 걸림. (약 40초) * * #USAGE * * StreamJsonArrayTokenizer tokenizer = new StreamJsonArrayTokenizer.Builder() .setSource(in) .build(); if (tokenizer.isExpectedStartArrayToken()) { while (tokenizer.hasNext()) { StreamJsonArrayTokenizer.Element e = tokenizer.next(); } */ @Deprecated public class StreamJsonArrayTokenizer implements Iterator<StreamJsonArrayTokenizer.Element> { private JsonParser parser; private Element element = null; private StreamJsonArrayTokenizer(Builder builder) { this.parser = builder.parser; this.element = new Element(); } public JsonToken nextToken() throws IOException { return parser.nextToken(); } public boolean isExpectedStartArrayToken() throws IOException { return nextToken() == JsonToken.START_ARRAY; } @Override public boolean hasNext() { try { return nextToken() != JsonToken.END_ARRAY; } catch (IOException ignored) { } return false; } @Override public Element next() { if (element == null) { element = new Element(); } try { element.node = parser.readValueAsTree(); } catch (IOException e) { Log.e(this, "Failed to parse", e); } return element; } @Deprecated public static class Element { JsonNode node; public String getValue(String key) { return node.get(key).toString(); } } public static class Builder<S extends InputStream> { private JsonFactory factory; private JsonParser parser; private S src; public Builder() { this.factory = new MappingJsonFactory(); } public Builder setSource(S src) throws IOException { this.src = src; this.parser = factory.createParser(src); return this; } public StreamJsonArrayTokenizer build() { return new StreamJsonArrayTokenizer(this); } } }
Java
UTF-8
1,238
2.15625
2
[]
no_license
/* * Copyright (c) 2015, Samith Dassanayake. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.buddycode.jaxrs.samplejaxrs.authentication; import java.util.Map; /** * Authentication Handler interface */ public interface AuthenticationHandler { /** * Returns whether the authenticator can handle the request * * @param httpHeaders * @return Return true if the request can be handled, false otherwise */ public boolean canHandle(Map httpHeaders); /** * Process the request and return the result * * @param httpHeaders * @return true if authentication successful, false otherwise */ public boolean isAuthenticated(Map httpHeaders); }
Markdown
UTF-8
2,421
3.1875
3
[]
no_license
# Link-state-protocol-in-python This project implenments the OSPF using Dijkstra algorithm (Open Shortest Path First) network protocol in python. Link-State Routing protocol is a main class of routing protocols. It is performed by every switching node/router in the network. The basic concept of link-state routing is that every node constructs a map of the connectivity to the network, in the form of a Graph, showing which nodes are connected to which other nodes. Each node then independently calculates the next best logical path from it to every possible destination in the network. The collection of best paths will then form the node's routing table. OSPF: ----- Open Shortest Path First (OSPF) is a link-state routing protocol for Internet Protocol (IP) networks. It uses a link state routing algorithm and falls into the group of interior routing protocols, operating within a single autonomous system (AS). OSPF is perhaps the most widely used interior gateway protocol (IGP) in large enterprise networks. IS-IS, another link-state dynamic routing protocol, is more common in large service provider networks. The most widely used exterior gateway protocol is the Border Gateway Protocol (BGP), the principal routing protocol between autonomous systems on the Internet. * Advantages of link state routing (as opposed to distance vector routing) include that link state routing converges rather quickly and * is not subject to the count-to-infinity problem; hence, no measures to combat this problem need to be taken. As the full network topology * is known to every node, rather advanced routing techniques can be implemented. * Disadvantages include that the link state information needs to be flooded through the network, causing higher overhead than link state protocols. * The memory and computational requirements are also higher. OSPF is an interior gateway protocol that routes Internet Protocol (IP) packets solely within a single routing domain (autonomous system). It gathers link state information from available routers and constructs a topology map of the network. The topology determines the routing table presented to the Internet Layer which makes routing decisions based solely on the destination IP address found in IP packets. OSPF was designed to support variable-length subnet masking (VLSM) or Classless Inter-Domain Routing (CIDR) addressing models.
Markdown
UTF-8
2,646
3.1875
3
[ "BSD-2-Clause" ]
permissive
# Memory ### Where's my data? With Cepl your data can exist in 3 different places: - lisp memory - The regular lisp data in your program. This get's GC'd (garbage collected) - c memory - Data stored in block of cffi memory. This does not get GC'd - gpu memory - Data stored on the GPU. This does not get GC'd A lot of work done in cepl is about making moving data between these places easy. ### GC Garbage collection is our friend in lisp. It let's us use our repls for experimental bliss and makes possible the kinds of data structures that would be a knightmare to keep in order without a very special data ownership model. However in realtime graphics the GC *can* be a problem. One of the things we end up working very hard for is a stable frame rate which makes spikes in GC activity a problem. It clearly is possible to have a GC and make games but the core system have to be written sensibly to ensure they arent adding load. On top of this, communication with the gpu can be very expensive if done at the wrong time. Deciding to free a bunch of gpu memory without being very aware of the current render state is a recipe for disaster. To this end, by default, none of the data in c-memory or gpu-memory is GC'd. This obviously means you need to free this data yourself or you end up with memory leaks. We say by default as there are certain times you don't mind paying the cost. For example when you are playing with ideas in the repl. To this end we are looking into ways of providing this without compromising any performance in the rest of cepl. This is WIP so this doco will be updated when that is in place. ### #'free and #'free-* To release memory we have two options, firstly we can use the generic function #'free as in ``` (free some-cepl-data) ``` However you may not want to pay the dispatch cost in performance critical code, so there are a number of `free-*` functions (e.g. #'free-c-array #'free-gpu-array etc). These specific functions will be covered in their respective chapters. ### #'pull-g & #'push-g These are two very helpful generic functions that let you move data between lisp, c-memory & gpu-memory with ease! `push-g` will take a lisp array or lisp list and push the data into a c-array or a gpu-array (dont worry if you dont know what these are yet) `pull-g` will pull data from c-array & gpu-arrays and bring it back into lisp. Obviously the generic dispatch and working out how to upload the data to a given target takes time, so these are generally used in non performance critical places, like the repl! There is also a bit more to this but we will revisit these in a later chapter.
JavaScript
UTF-8
1,643
2.671875
3
[]
no_license
const NTask = require('../ntask.js'); const Template = require('../templates/tasks.js'); class Tasks extends NTask { constructor(body) { super(); this.body = body; } render() { this.renderTaskList(); } addEventListener() { this.taskDoneCheckbox(); this.taskRemoveClick(); } renderTaskList() { this.request.get('/tasks') .then(res => { this.body.innerHTML = Template.render(res.data); this.addEventListener(); }) .catch(err => this.emit('error', err)) ; } taskDoneCheckbox() { const dones = this.body.querySelectorAll('[data-done]'); for(let i = 0; i < dones.length; i++) { dones[i].addEventListener('click', (e) => { e.preventDefault(); const id = e.target.getAttribute('data-task-id'); const done = e.target.getAttribute('data-task-done'); const body = { done: !done }; this.request.put(`/tasks/${id}`, body) .then(() => this.emit('update')) .catch(err => this.emit('update-error', err)) ; }); } } taskRemoveClick() { const removes = this.body.querySelectorAll('[data-remove]'); for(let i = 0; i < removes.length; i++) { removes[i].addEventListener('click', (e) => { e.preventDefault(); if (confirm('Deseja excluir esta tarefa?')) { const id = e.target.getAttribute('data-task-id'); this.request.delete(`/tasks/${id}`) .then(() => this.emit('remove')) .catch(err => this.emit('remove-error', err)) ; } }); } } } module.exports = Tasks;
Markdown
UTF-8
8,475
2.578125
3
[]
no_license
# cypress-dynamic-data It showcases the use of:- - Typescript - The Cypress GUI tool - The Cypress command line tool - Cypress custom commands `cy.foo()` - PageObject Models on a Login Site - Resuable Web Selectors - CircleCI integration - Slack reporting - Mochawesome for fancy HTML reporting - DevTools console log output on test fail - Integration with Cypress' Dashboard Service for project recording - Docker to self contain the application and require no pre-requisites on the host machine, bar Docker. ## Dynamically generate data from CSV or XLS files To convert Excel files to JSON `make convertXLStoJSON` or `npm run convertXLStoJSON` * File:- `testData/convertXLStoJSON.ts` * Input:- `testData/testData.xlsx` * Output:- `cypress/fixtures/testData.json` To convert CSV to JSON `make convertCSVtoJSON` or `yarn run convertCSVtoJSON` * File:- `testData/convertCSVtoJSON.ts` * Input:- `testData/testData.csv` * Output:- `cypress/fixtures/testDataFromCSV.json` To see the test in action * `export CYPRESS_SUT_URL=https://the-internet.herokuapp.com` * `npx cypress open --env configFile=development` or `make test-local-gui` Open the script `login.spec.ts` which will generate a test for every entry in the CSV or XLS (default) file. If you wish to read from the CSV, in the file `cypress/integration/login.spec.ts` Change `const testData = require("../fixtures/testData.json");` to `const testData = require("../fixtures/testDataFromCSV.json");` ## Installation - Clone the project ### Local Installation - Run `yarn install` to install cypress - We can slot this into any project easily and isolate its dependencies from your project - View the `Makefile` for available commands ### Docker Installation - Run `make docker-build` in the project - View the `Makefile` for available docker commands ## Configuration The main cypress configuration file - `cypress.json` It can contain configuration options applicable to all environments Environment specific config files are stored in `config/<environment.json>` These will override any configurations specific environment vars set in `cypress.json` these can be set on the command line by - `--env configFile=<environment.json>` Currently supported environments are - development - production - staging - qa If no option is provided is will default to the baseUrl defined in `config.json` In order to setup development, you will need a website locally running and your CYPRESS_SUT_URL should be set. `export CYPRESS_SUT_URL=<your_root_url>` If you are using docker then please set your CYPRESS_SUT_URL in your docker-compose file, it is set in this example ``` environment: - CYPRESS_SUT_URL=https://docker.for.mac.localhost ``` If it's CYPRESS_SUT_URL is not, and you select `--env configFile=development` the application will error, and ask you to set it. ## Running tests in Docker via Make - `make docker-build` - Build the image - `make docker-test-local` - Run the tests - `make docker-bash` - Access the bash shell in the container For more, see the Makefile ## Running tests locally via Make - `make test-local` - `make test-qa` - `make test-staging` - `make test-production` ## Direct from the command line - `yarn run cypress:open` - runs test via gui - `yarn run cypress:run` - run tests via command line - `--env configFile=<env>` - select an environment specific config - `-s '<pathToFile>'` path for the spec files you wish to run - `-s 'cypress/integration/commands.spec.js'` example ### GUI - Any changes made to test files are automatically picked up by the GUI and executed, post file save - `make test-local-gui` Opens the GUI with the development configuration selection - `make test-qa-gui` Opens the GUI with the qa configuration selection The GUI can be opened by `npx cypress open` but requires a `--env configFile=<env>` option in order to set the correct BaseURL ### Reporting Videos of each run are stored in `cypress/videos` Screenshots of failing tests are stored in `cypress/screenshots` Reports of test runs are generated with MochaAwesome are stored in `cypress/reports` - One report is generated per spec file - A report bundler is provided which will process each report in `cypress/reports` and combine them into a single HTML document with a random uuid title in `mochareports` - The report bundler can be run with `make combine-reports && make generate-report` ``` combine-reports: npx mochawesome-merge --reportDir cypress/reports/mocha > mochareports/report-$$(date +'%Y%m%d-%H%M%S').json ``` ``` generate-report: npx marge mochareports/*.json -f report-$$(date +'%Y%m%d-%H%M%S') -o mochareports ``` ## Typescript - Spec (test) files are written as `example.spec.ts` and contained in `cypress/integration` - There is a `tsconfig.json` file - It includes the paths for the `.ts` files. If you add other paths for yours, include them here. - It contains the typescript options and includes the Cypress typings for code completion. - use visual studio code (if you aren't already) - it's free and comes feature packed. - There is a `tslint.json` file - Contains some rules for code linting - Tests are compiled with browserify typescript pre-processor. - It is loaded in `cypress/plugins/index.js`, hooking into cypress's `on` event. ## Intellisense Add the following to your settings.json in VSCode for intellisense in `cypress.json` ```json "json.schemas": [ { "fileMatch": [ "/cypress.json" ], "url": "https://raw.githubusercontent.com/cypress-io/cypress/develop/cli/schema/cypress.schema.json" } ] ``` ## CircleCI This project is building in CircleCI See the `.circleci` folder - `config.yml` - Contains the CircleCI build configuration The circle config is setup to run `make circle-ci-qa` which will run tests against a specific environment We can initiate the job via an API, passing in a cypress_sut variable, which should evaluate to a Makefile target. ```bash curl -u ${CIRCLE_TOKEN} -X POST --header "Content-Type: application/json" -d '{ "build_parameters": { "cypress_sut": "circle-ci-staging" } } ' https://circleci.com/api/v1.1/project/<vcs-type>/<org>/<repo>/tree/<branch> ``` The following will trigger this repo, running the command `make circle-ci-staging` The bash condition is as follows ```bash if [ -z ${cypress_sut+x} ]; then make circle-ci-qa else make $cypress_sut fi ``` ### Slack Reporting A bash file has been written in order to publish results - `.circleci/slack-alert.sh` It provides the following distinct message types - Build Failure / Cypress error - Test Failure - Test Success It provides the following information - CircleCI Build Status - Test Stats (Total Tests / Passes / Failures) - Author with link to Github commit - Branch name - Pull Request number and link to PR (only if PR) And the following build/test artefacts - CircleCI Build Log button - HTML Test report button (only on build success) - Videos of test runs (one link per test) - Screenshots of failed tests (one link per failing test) You will need to set up a couple of things in order to use this. First build a Slack app & create an incoming webhook - https://api.slack.com/slack-apps Set the following environment variable in your localhost or CI configuration - `$SLACK_WEBHOOK_URL` - The full URL you created in the last step - `$SLACK_API_CHANNEL` - The channel ref you wish to publish to (right-click on your channel and click copy link, check the link, its the digits after the last / ) ### Cypress Dashboard Recording CircleCI builds pass in a `CYPRESS_RECORD_KEY` in order to publish the results to the Cypress Dashboard. We run `make test-record` to set the `--record` flag and publish the results to the dashboard. ## Accessibility Testing We are using [Axe-Core](https://github.com/dequelabs/axe-core) for accessiblity testing via [Cypress-Axe](https://github.com/avanslaars/cypress-axe) It can be actioned by doing the following ensuring that a `cy.visit()` operation has taken place prior, either in the test, or via a `beforeEach` hook ``` it('passes accessibility check', () => { cy.injectAxe(); cy.checkA11y(); }) ``` Rules can be viewed [here](https://github.com/dequelabs/axe-core/blob/develop/doc/rule-descriptions.md) at a high level and in more detail [here](https://dequeuniversity.com/rules/axe/3.1) ## TODO - Applitools Integration
Java
UTF-8
943
2.03125
2
[]
no_license
package com.fonality.test.dao; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; import com.fonality.dao.AddressDAO; import com.fonality.dao.ContactDAO; /** * @author Fonality * */ @ContextConfiguration(locations = "classpath:application-context.xml") public class TestAddressDAO extends AbstractTransactionalJUnit4SpringContextTests { @Autowired public AddressDAO addressDAO; @Test public void testAddress() { assertTrue(addressDAO.getAddressList().size() > 0); assertNull(addressDAO.loadAddress(-1)); assertNotNull(addressDAO.loadAddress(1)); } }
Markdown
UTF-8
958
2.734375
3
[]
no_license
--- sutra: वर्षाल्लुक् च vRtti: द्विगोरित्येव । वर्षान्ताद् द्विगोर्निर्वृत्तादिष्वर्थेषु वा खः प्रत्ययो भवति । पक्षे ठञ् । तयोश्च वा लुग्भवति ॥ vRtti_eng: The above affixes _kha_ and _than_ may also be elided after a _Dvigu_ ending in _varsha_. --- The affix ख as well as ठञ् come in the five fold senses (5.1.79), (5.1.80), after the word वर्षा forming a _Dvigu_; and these two affixes may also be elided optionally. Thus we have three forms; द्विवर्षीणो, द्विवार्षिकी or द्विवर्षो व्याधिः 'a disease that lasted two years'. Compare (7.3.16); but when the sense is that of भावी, the form will be द्वैवर्षिकः ॥
Java
UTF-8
1,409
2.28125
2
[ "Apache-2.0" ]
permissive
package io.bootique.tools.template.processor; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import com.google.inject.Inject; import io.bootique.tools.template.PropertyService; import io.bootique.tools.template.TemplateException; import org.w3c.dom.Document; import org.w3c.dom.Node; public class MavenProcessor extends XMLTemplateProcessor { @Inject PropertyService propertyService; @Override protected Document processDocument(Document document) { XPath xpath = XPathFactory.newInstance().newXPath(); try { Node artefactId = (Node)xpath.evaluate("/project/artifactId", document, XPathConstants.NODE); artefactId.setTextContent(propertyService.getProperty("maven.artifactId")); Node groupId = (Node)xpath.evaluate("/project/groupId", document, XPathConstants.NODE); groupId.setTextContent(propertyService.getProperty("maven.groupId")); Node version = (Node)xpath.evaluate("/project/version", document, XPathConstants.NODE); version.setTextContent(propertyService.getProperty("maven.version")); } catch (XPathExpressionException ex) { throw new TemplateException("Unable to modify xml, is template a proper maven xml?", ex); } return document; } }
Java
UTF-8
1,141
2.703125
3
[]
no_license
package me.damiankaras.ev3cubesolver.brick.Motors; public class MotorManager { private static final MotorManager instance = new MotorManager(); public static MotorManager getInstance() { return instance; } // public static final int MOTOR_BASKET = 0; // public static final int MOTOR_SENSOR = 1; // public static final int MOTOR_ARM = 2; private ArmMotor armMotor; private BasketMotor basketMotor; private SensorMotor sensorMotor; private MotorManager() { armMotor = new ArmMotor(); basketMotor = new BasketMotor(); sensorMotor = new SensorMotor(); } // public RegulatedMotor getMotor(int motor) { // switch (motor) { // case MOTOR_BASKET: return basketMotor; // case MOTOR_SENSOR: return sensorMotor; // case MOTOR_ARM: return armMotor; // default: return null; // } // } public ArmMotor getArmMotor() { return armMotor; } public BasketMotor getBasketMotor() { return basketMotor; } public SensorMotor getSensorMotor() { return sensorMotor; } }
Markdown
UTF-8
789
2.53125
3
[]
no_license
### Hi there 👋 🌱 I’m a Software Engineer at BigBinary. 👨🏽‍💻 I graduated my BTech in Computer Science from Federal Institute of Science And Technology. <!-- 🔭 I’m currently working on my final year BTech Project in Python, Django and React. --> 📫 How to reach me: alanloovees@gmail.com "There's always a better way" ~ Barry Allen, The Flash ⚡ <!-- **AlanLoovees/AlanLoovees** is a ✨ _special_ ✨ repository because its `README.md` (this file) appears on your GitHub profile. Here are some ideas to get you started: - 🔭 I’m currently working on ... - 🌱 I’m currently learning ... - 👯 I’m looking to collaborate on ... - 🤔 I’m looking for help with ... - 💬 Ask me about ... - 📫 How to reach me: ... - 😄 Pronouns: ... - ⚡ Fun fact: ... -->
PHP
UTF-8
5,732
2.71875
3
[]
no_license
<?php /** * This file contains the RWC\Features\Fundraisers\ReportingMetabox class. * * @author Brian Reich <breich@reich-consulting.net> * @copyright Copyright (C) 2017 Reich Web Consulting * @package RWC */ namespace RWC\Features\Fundraisers { /** * An Exception class for Fundraiser feature related errors. * * @author Brian Reich <breich@reich-consulting.net> * @copyright Copyright (C) 2017 Reich Web Consulting * @package RWC */ class ReportingMetabox extends \RWC\Object { private $aggregate = []; private $aggregate_price = 0; public function set_fundraisers_feature( \RWC\Features\Fundraisers $feature ) { $this->set_option( 'fundraisersFeature', $feature ); } public function get_fundraisers_feature() { return $this->get_option( 'fundraisersFeature', null ); } public function __construct( $options = array() ) { parent::__construct( $options ); add_action( 'add_meta_boxes', array( $this, 'register_metabox' ) ); add_action( 'wp_ajax_rwc_fundraiser_report_pdf', array( $this, 'rwc_fundraiser_report_pdf' ) ); add_action( 'wp_ajax_rwc_fundraiser_report_csv', array( $this, 'rwc_fundraiser_report_csv' ) ); add_action('wp_ajax_rwc_fundraiser_customer_list', [ $this, 'rwc_fundraiser_customer_list' ]); } public function rwc_fundraiser_report_pdf() { $fundraiserId = intval( $_REQUEST[ 'fundraiser' ] ); $feature = $this->get_fundraisers_feature(); $fundraiser = $feature->get_fundraiser( $fundraiserId ); $orderIds = $fundraiser->get_order_ids(); $library = $this->get_option( 'library' ); echo \RWC\Utility::get_include_content( '/features/fundraisers/fundraising-report.php', [ 'fundraiser' => $fundraiser, 'cssDirectory' => $library->get_uri(), 'feature' => $feature, 'orderIds' => $orderIds, 'library' => $library ] ); exit(); } /** * Returns a CSV list of contact information for fundraiser customers. * * When the request for the fundraiser customer list is made, the * request must contain a request parameter called "fundraiser" which * specifies the unique id of the fundraiser whose customer list is * desired. The fundraiser value must map to an existing Fundraiser. * * * @return void */ public function rwc_fundraiser_customer_list() { // Make sure required option was specified. if(! isset($_REQUEST['fundraiser'])) { throw new Exception('Request parameter "fundraiser" not set.'); } // Get the unique id of the fundraiser. $fundraiserId = intval( $_REQUEST[ 'fundraiser' ] ); $feature = $this->get_fundraisers_feature(); $fundraiser = $feature->get_fundraiser( $fundraiserId ); // Make sure it exists. if(is_null($fundraiser)) { throw new Exception($fundraiserId . ' is not a valid fundraiser.'); } // Get a list of orders in the fundraiser. $orderIds = $fundraiser->get_order_ids(); $library = $this->get_option( 'library' ); // Output in CSV format. header('Content-type: text/csv'); header('Content-Disposition: attachment; filename=fundraiser_' . $fundraiserId . '_customers.csv'); echo \RWC\Utility::get_include_content( '/features/fundraisers/customer-list.php', [ 'fundraiser' => $fundraiser, 'cssDirectory' => $library->get_uri(), 'feature' => $feature, 'orderIds' => $orderIds, 'library' => $library ] ); exit(); } public function rwc_fundraiser_report_csv() { $fundraiserId = intval( $_REQUEST[ 'fundraiser' ] ); $fundraiser = $this->get_fundraisers_feature()->get_fundraiser(); die(); } public function register_metabox() { \add_meta_box( 'rwc-features-fundraisers-reporting', 'Reporting Options', array( $this, 'render' ), $this->get_fundraisers_feature()->get_post_type(), 'side' ); } /** * Renders the contents of the Reporting Metabox. * * This method renders the contents of the Reporting Metabox, which * provides the interface for downloading reports associated with the * currently selected fundraiser. * * @return void */ public function render() { $base = 'ajaxurl + \'?action=rwc_fundraiser_report_%s&fundraiser=%s\''; $csvUrl = sprintf('ajaxurl + \'?action=rwc_fundraiser_customer_list&fundraiser=%s\'',get_the_ID() ); $pdfUrl = sprintf( $base, 'pdf', get_the_ID() ); ?> <a class="button button-large button-secondary" href="#" onclick="window.open(<?php echo $pdfUrl ; ?>); return false;">Download Report (PDF)</a> <a class="button button-large button-secondary" href="#" onclick="window.open(<?php echo $csvUrl ; ?>) ; return false">Download Customer List (CSV)</a> <?php } } }
JavaScript
UTF-8
7,041
2.6875
3
[]
permissive
var assert = require('assert'); var fs = require('fs'); var blend = require('..'); var utilities = require('./support/utilities'); // Polyfill buffers. if (!Buffer) { var Buffer = require('buffer').Buffer; var SlowBuffer = require('buffer').SlowBuffer; SlowBuffer.prototype.fill = Buffer.prototype.fill = function(fill) { for (var i = 0; i < this.length; i++) { this[i] = fill; } }; } var images = [ fs.readFileSync('test/fixture/1.png'), fs.readFileSync('test/fixture/2.png'), fs.readFileSync('test/fixture/32.png'), fs.readFileSync('test/fixture/1293.jpg'), fs.readFileSync('test/fixture/1294.png') ]; describe('invalid arguments', function() { it('should throw with a bogus first argument', function() { assert.throws(function() { blend(true, function(err) {}); }, /First argument must be an array of Buffers/); }); it('should throw with an empty first argument', function() { assert.throws(function() { blend([], function(err) {}); }, /First argument must contain at least one Buffer/); }); it('should throw if the first argument contains bogus elements', function() { assert.throws(function() { blend([1, 2, 3], function(err) {}); }, /All elements must be Buffers or objects with a 'buffer' property/); }); it('should not allow unknown formats', function() { assert.throws(function() { blend([ fs.readFileSync('test/fixture/1c.jpg'), fs.readFileSync('test/fixture/2.png') ], { format: 'xbm' }, function() {}); }, /Invalid output format/); }); it('should not allow negative quality', function() { assert.throws(function() { blend([ fs.readFileSync('test/fixture/1c.jpg'), fs.readFileSync('test/fixture/2.png') ], { format: 'jpeg', quality: -10 }, function() {}); }, /JPEG quality is range 0-100/); }); it('should not allow quality above 100', function() { assert.throws(function() { blend([ fs.readFileSync('test/fixture/1c.jpg'), fs.readFileSync('test/fixture/2.png') ], { format: 'jpeg', quality: 110 }, function() {}); }, /JPEG quality is range 0-100/); }); it('should not allow compression level above what zlib supports', function() { assert.throws(function() { blend([ fs.readFileSync('test/fixture/1c.jpg'), fs.readFileSync('test/fixture/2.png') ], { compression:10 }, function() {}); }, /Compression level must be between 0 and 9/); }); it('should not allow negative image dimensions', function() { assert.throws(function() { blend(images, { width: -20 }, function() {}); }, /Image dimensions must be greater than 0/); }); it('should not allow negative image dimensions', function() { assert.throws(function() { blend(images, { height: -20 }, function() {}); }, /Image dimensions must be greater than 0/); }); it('should not allow empty objects', function() { assert.throws(function() { blend([ { buffer: images[1] }, { } ], function() {}); }, /All elements must be Buffers or objects with a 'buffer' property/); }); it('should not allow objects that don\'t have a Buffer', function() { assert.throws(function() { blend([ { buffer: images[1] }, { buffer: false } ], function() {}); }, /All elements must be Buffers or objects with a 'buffer' property/); }); }); describe('invalid images', function() { it('should report an unknown image format with bogus buffers', function(done) { var buffer = new Buffer(1024); buffer.fill(0); blend([ buffer, buffer ], function(err, data) { if (!err) return done(new Error('Error expected')); assert.equal(err.message, "image_reader: can't determine type from input data"); done(); }); }); it('should report an invalid chunk type with a semi-bogus buffer', function(done) { var buffer = new Buffer('\x89\x50\x4E\x47\x0D\x0A\x1A\x0A' + Array(48).join('\0'), 'binary'); blend([ buffer, images[1] ], function(err, data) { if (!err) return done(new Error('Error expected')); assert.ok(err.message.indexOf('[00][00][00][00]: invalid chunk type') > -1); done(); }); }); it('should report a read error with a buffer that only contains the header', function(done) { var buffer = new Buffer('\x89\x50\x4E\x47\x0D\x0A\x1A\x0A', 'binary'); blend([ buffer, images[1] ], function(err, data) { if (!err) return done(new Error('Error expected')); assert.ok(err.message.indexOf('Read Error') > -1); done(); }); }); it('should error out with "Incorrect bKGD chunk index value"', function(done) { blend([ images[2] ], { reencode: true }, function(err, data) { if (err) return done(err); assert.ok(data.length > 600 && data.length < 1200, 'reencoding bogus image yields implausible size'); // Check that we don't reencode the error. blend([ data ], { reencode: true }, function(err, data2) { if (err) return done(err); assert.deepEqual(data, data2); done(); }); }); }); it('should report a bogus Huffman table definition', function(done) { blend([ images[2], images[3] ], function(err, data, warnings) { if (!err) return done(new Error('expected error')); assert.equal(err.message, 'JPEG Reader: libjpeg could not read image: Bogus Huffman table definition'); // Test working state after error. blend([ images[2] ], { reencode: true }, done); }); }); it('should error out on blending an invalid JPEG image', function(done) { var buffer = new Buffer(32); buffer.fill(0); buffer[0] = 0xFF; buffer[1] = 0xD8; blend([ buffer, fs.readFileSync('test/fixture/2.png') ], function(err, data) { assert.ok(err); assert.ok(err.message); done(); }); }); it('should error out on blending a malformed JPEG image', function(done) { blend([ fs.readFileSync('test/fixture/1d.jpg'), fs.readFileSync('test/fixture/2.png') ], function(err, data) { assert.ok(err); assert.ok(err.message); done(); }); }); });
Java
UTF-8
632
1.992188
2
[]
no_license
package br.jus.cnj.inova.validators; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ValidatorsConfig { @Bean ValidatorsManager getValidatorsManager(ApplicationContext context) { final var validatorsManager = new ValidatorsManager(); context.getBeansWithAnnotation(Validator.class).values().stream() .map(bean -> (ProcessoValidator) bean) .forEach(validatorsManager::register); return validatorsManager; } }
C++
UTF-8
975
2.984375
3
[ "MIT" ]
permissive
#include <process.h> Process :: Process(string pid) { this->Pid_ = pid; this->User_ = ProcessParser::getProcUser(pid); this->Command_ = ProcessParser::getCmd(pid); this->CpuUtilization_ = ProcessParser::getCpuPercent(pid); this->Ram_ = ProcessParser::getVmSize(pid); this->UpTime_ = ProcessParser::getProcUpTime(pid); } // Return this process's ID string Process::getPid() { return this->Pid_; } // Return the user (name) that generated this process string Process::getUser() { return this->User_; } // Return this process's CPU utilization float Process::getCpuUtilization() { return this->CpuUtilization_; } // Return this process's memory utilization float Process::getRam() { return this->Ram_; } // Return the age of this process (in seconds) long Process::getUpTime() { return this->UpTime_; } // Return the command that generated this process string Process::getCommand() { return this->Command_; }
PHP
UTF-8
124
2.546875
3
[]
no_license
<?php # Usando argumentos en archivos # para probar: # php 01-args.php Juan $nombre= $argv[1]; echo "Hola ".$nombre; ?>
PHP
UTF-8
2,751
3.796875
4
[]
no_license
<?php class Map { /* $table = [ * 'encrypt' => * ['A' => 'A', 'B' => 'B', ...], * ['A' => 'B', 'B' => 'C', ...], * ... * 'decrypt' => * ['A' => 'A', 'B' => 'B', ...], * ['B' => 'A', 'C' => 'B', ...], * ... */ protected $table; /* index of each character: * $index = ['A' => 0, 'B' => 1, ...] */ protected $index; public function __construct() { $row = $keys = range('A', 'Z'); $this->index = array_flip($keys); for ($i = 0; $i < count($keys); $i++) { $table = array_combine($keys, $row); $this->table['encrypt'][$i] = $table; $this->table['decrypt'][$i] = array_flip($table); array_push($row, array_shift($row)); } } // remove non-alpha characters and convert to uppercase. public function clean($string) { return preg_replace('/[^A-Z]/', '', strtoupper($string)); } // retrieve the index of a character. public function index($symbol) { return $this->index[$symbol]; } // encode a character using the mapping table. public function encrypt($symbol, $shift) { return $this->table['encrypt'][$shift][$symbol]; } // decode a character using the mapping table. public function decrypt($symbol, $shift) { return $this->table['decrypt'][$shift][$symbol]; } } class Cipher { protected $map; public function __construct(Map $map) { $this->map = $map; } public function encrypt($string, $shift) { return $this->convert($string, $shift); } public function decrypt($string, $shift) { return $this->convert($string, $shift, $action = 'decrypt'); } } class Vigenere extends Cipher { protected function convert($string, $keyword, $action = 'encrypt') { // prepare the input and the cipher key. $stream = $this->map->clean($string); $secret = $this->map->clean($keyword); $length = count($secret); // prepare the output. $output = ''; for ($i = 0, $j = 0; $i < strlen($stream); $i++, $j++) { // calculate the shift by rotating the keyword. $shift = $this->map->index($secret[$j % $length]); // translate each character of the input stream. $output .= $this->map->$action($stream[$i], $shift); } return $output; } } // example: echo "<style>body {font-family: monospace; word-break: break-all; white-space: pre;}</style>"; // plaintext. $p = "Attack at dawn."; // vigenere keyword. $k = "LEMON"; // caesar shift. $i = 3; $m = new Map(); $v = new Vigenere($m); $e2 = $v->encrypt($p, $k); $d2 = $v->decrypt($e2, $k); echo "<h3>vigenere</h3>"; echo "<p>keyword: " . $k . "</p>"; echo "<p>plaintext: " . $p . "</p>"; echo "<p>encrypted: " . $e2 . "</p>"; echo "<p>decrypted: " . $d2 . "</p>";
Shell
UTF-8
924
4.125
4
[]
no_license
#!/bin/bash man="\ USAGE $(basename $0) [HOST:][docs|flash] [OPTIONS] OPTIONS -n dry run -r restore instead of backup -h this help " function sync() { from=$1; to=$2; n=$3 mkdir -p $to rsync -av --delete $n $from $to } function restore() { from=$1; to=$2; n=$3 sync $to $from $n } flash=$FLASH_ROOT/flash home=$HOME command=sync IFS=$':'; target=($1); IFS=$' ' if [ -z "${target[1]}" ]; then name="${target[0]}" else host="${target[0]}:" name="${target[1]}" fi for ((i=0;++i<=$#;)); do case ${@:$i:1} in -n) n=-n ;; -r) command=restore ;; -h) echo "$man"; exit 0 ;; esac done if [ -z "$FLASH_ROOT" ]; then echo "\$FLASH_ROOT is empty."; exit 1; fi if [ ! -d "$FLASH_ROOT" ]; then echo "$FLASH_ROOT is not found."; exit 1; fi case "$name" in docs) $command $host$home/Documents/ $flash/docs/ $n ;; flash) $command $flash/ $host$home/flash/ $n ;; *) $command $flash/ $home/flash/ $n ;; esac
Swift
UTF-8
380
2.546875
3
[ "MIT" ]
permissive
// // ActivationFunctions.swift // Simple-Swift-AI // // Created by Arjun Gupta on 7/29/16. // Copyright © 2016 ArjunGupta. All rights reserved. // import Foundation class ActivationFunctions { class func linear(x: Double) -> Double { return x } class func sigmoid(val: Double) -> Double { return 1 / (1 + exp(-val)) } }
JavaScript
UTF-8
2,968
2.71875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// Webhook for LINE function doPost(e) { var token = PropertiesService.getScriptProperties().getProperty('CHANNEL_ACCESS_TOKEN'); var reply_token= JSON.parse(e.postData.contents).events[0].replyToken; var user_id= JSON.parse(e.postData.contents).events[0].source.userId; var group_id= JSON.parse(e.postData.contents).events[0].source.groupId; if (user_id != undefined ) { var profile = get_profile(user_id); } switch (JSON.parse(e.postData.contents).events[0].type) { case 'follow': // follow event postSlackMessage('Followed', profile['displayName'] ,profile['pictureUrl']); break; case 'unfollow': //unfollo event postSlackMessage('Unollowed', profile['displayName'] ,profile['pictureUrl']); break; case 'join': //join event postSlackMessage('Join group: ' + group_id); break; case 'leave': //leave event postSlackMessage('Leave group: ' + group_id); break; case 'message': //message event var user_message = JSON.parse(e.postData.contents).events[0].message.text; postSlackMessage(user_message, profile['displayName'] ,profile['pictureUrl']); if ( user_message.indexOf('元気') != -1 ) { var bot_message = "元気です"; postSlackMessage(bot_message); var url = 'https://api.line.me/v2/bot/message/reply'; UrlFetchApp.fetch(url, { 'headers': { 'Content-Type': 'application/json; charset=UTF-8', 'Authorization': 'Bearer ' + token, }, 'method': 'post', 'payload': JSON.stringify({ 'replyToken': reply_token, 'messages': [{ 'type': 'text', 'text': bot_message, }], }), }); } else{ // 指定文章以外をこ↑こ↓に書く } default: break; } } // Send Slack function postSlackMessage(mes, name, image_url) { var token = PropertiesService.getScriptProperties().getProperty('SLACK_API'); var slackApp = SlackApp.create(token); if (name == undefined){ name = 'LINE_BOT'; } var options = { channelId: "#random", userName: name, message: mes, url: image_url }; if (image_url == undefined){ slackApp.postMessage(options.channelId, options.message, {username: options.userName}); } else { slackApp.postMessage(options.channelId, options.message, {username: options.userName, icon_url: options.url}); } } // Get Profile for LINE function get_profile(userid) { var token = PropertiesService.getScriptProperties().getProperty('CHANNEL_ACCESS_TOKEN'); var url = 'https://api.line.me/v2/bot/profile/' + userid; var headers = { 'Authorization': 'Bearer ' + token }; var options = { 'headers' : headers }; var response = UrlFetchApp.fetch(url, options); var content = JSON.parse(response.getContentText()); return content; }
Markdown
UTF-8
4,208
3.296875
3
[ "MIT", "Apache-2.0" ]
permissive
--- layout: post title: 'iPhone/Mac Objective-C内存管理教程和原理剖析(二)口诀与范式' date: 2010-07-29 wordpress_id: 628 permalink: /blogs/628 comments: true categories: - iPhone - Mac tags: - iPhone - Mac - objective-c - 内存管理 --- 二 口诀与范式 1 口诀。 1.1 谁创建,谁释放(类似于“谁污染,谁治理”)。如果你通过alloc、new或copy来创建一个对象,那么你必须调用release或autorelease。换句话说,不是你创建的,就不用你去释放。 例如,你在一个函数中alloc生成了一个对象,且这个对象只在这个函数中被使用,那么你必须在这个函数中调用release或autorelease。如果你在一个class的某个方法中alloc一个成员对象,且没有调用autorelease,那么你需要在这个类的dealloc方法中调用release;如果调用了autorelease,那么在dealloc方法中什么都不需要做。 1.2 除了alloc、new或copy之外的方法创建的对象都被声明了autorelease。 1.3 谁retain,谁release。只要你调用了retain,无论这个对象是如何生成的,你都要调用release。有时候你的代码中明明没有retain,可是系统会在默认实现中加入retain。不知道为什么苹果公司的文档没有强调这个非常重要的一点,请参考范式2.7和第三章。 2 范式。 范式就是模板,就是依葫芦画瓢。由于不同人有不同的理解和习惯,我总结的范式不一定适合所有人,但我能保证照着这样做不会出问题。 2.1 创建一个对象。 <pre class="prettyprint linenums"> ClassA *obj1 = [[ClassA alloc] init]; </pre> 2.2 创建一个autorelease的对象。 <pre class="prettyprint linenums"> ClassA *obj1 = [[[ClassA alloc] init] autorelease]; </pre> 2.3 Release一个对象后,立即把指针清空。(顺便说一句,release一个空指针是合法的,但不会发生任何事情) <pre class="prettyprint linenums"> [obj1 release]; obj1 = nil; </pre> 2.4 指针赋值给另一个指针。 <pre class="prettyprint linenums"> ClassA *obj2 = obj1; [obj2 retain]; //do something [obj2 release]; obj2 = nil; </pre> 2.5 在一个函数中创建并返回对象,需要把这个对象设置为autorelease <pre class="prettyprint linenums"> ClassA *Func1() { ClassA *obj = [[[ClassA alloc]init]autorelease]; return obj; } </pre> 2.6 在子类的dealloc方法中调用基类的dealloc方法 <pre class="prettyprint linenums"> -(void) dealloc { … [super dealloc]; } </pre> 2.7 在一个class中创建和使用property。 2.7.1 声明一个成员变量。 <pre class="prettyprint linenums"> ClassB *objB; </pre> 2.7.2 声明property,加上retain参数。 <pre class="prettyprint linenums"> @property (retain) ClassB* objB; </pre> 2.7.3 定义property。(property的默认实现请看第三章) <pre class="prettyprint linenums"> @synthesize objB; </pre> 2.7.4 除了dealloc方法以外,始终用.操作符的方式来调用property。 self.objB 或者objA.objB 2.7.5 在dealloc方法中release这个成员变量。 <pre class="prettyprint linenums"> [objB release]; </pre> 示例代码如下(详细代码请参考附件中的memman-property.m,你需要特别留意对象是在何时被销毁的。): <pre class="prettyprint linenums"> @interface ClassA : NSObject { ClassB* objB; } @property (retain) ClassB* objB; @end @implementation ClassA @synthesize objB; -(void) dealloc { [objB release]; [super dealloc]; } @end </pre> 2.7.6 给这个property赋值时,有手动release和autorelease两种方式。 <pre class="prettyprint linenums"> void funcNoAutorelease() { ClassB *objB1 = [[ClassB alloc]init]; ClassA *objA = [[ClassA alloc]init]; objA.objB = objB1; [objB1 release]; [objA release]; } void funcAutorelease() { ClassB *objB1 = [[[ClassB alloc]init] autorelease]; ClassA *objA = [[[ClassA alloc]init] autorelease]; objA.objB = objB1; } </pre> 摘自: http://www.cnblogs.com/VinceYuan/
TypeScript
UTF-8
6,295
2.5625
3
[ "MIT" ]
permissive
import { Page, Browser, Response, EvaluateFn, SerializableOrJSHandle, PageFnOptions, } from "puppeteer-core"; import { iResponse } from "../interfaces/iresponse"; import { BrowserControl } from "./browser-control"; import { toType } from "../util"; import { wrapAsValue } from "../helpers"; import { ValuePromise } from "../value-promise"; import { BrowserScenario } from "./browser-scenario"; import { ExtJsScenario } from "./extjs-scenario"; import { ScreenshotOpts } from "../interfaces/screenshot"; import { iHttpRequest } from "../interfaces/http"; import { iValue } from "../interfaces/ivalue"; import { ProtoResponse } from "../response"; const DEFAULT_WAITFOR_TIMEOUT = 30000; export abstract class PuppeteerResponse extends ProtoResponse implements iResponse { constructor(public readonly scenario: BrowserScenario | ExtJsScenario) { super(scenario); this.scenario = scenario; } public get browserControl(): BrowserControl | null { return this.scenario.browserControl; } public get page(): Page | null { return this.scenario.browserControl?.page || null; } public get browser(): Browser | null { return this.scenario.browserControl?.browser || null; } public get response(): Response | null { return this.scenario.browserControl?.response || null; } public get currentUrl(): iValue { const page = this.scenario.page; let url: string | null = null; if (page) { url = page.url(); } return wrapAsValue(this.context, url, "Current URL"); } protected get _page(): Page { if (this.page === null) { throw "Puppeteer page object was not found."; } return this.page; } /** * Run this code in the browser */ public async eval( js: EvaluateFn<any>, ...args: SerializableOrJSHandle[] ): Promise<any> { return this._page.evaluate.apply(this._page, [js, ...args]); } /** * Wait for network to be idle for 500ms before continuing * * @param timeout */ public async waitForNetworkIdle(timeout?: number): Promise<void> { await this._page.waitForNavigation({ timeout: this.getTimeoutFromOverload(timeout), waitUntil: "networkidle0", }); return; } /** * Wait for network to have no more than two connections for 500ms before continuing * * @param timeout */ public async waitForNavigation( timeout?: number, waitFor?: string | string[] ): Promise<void> { const allowedOptions: string[] = [ "load", "domcontentloaded", "networkidle0", "networkidle2", ]; // @ts-ignore VS Code freaks out about this, but it's valid return output for LoadEvent const waitForEvent: LoadEvent[] = (() => { if (typeof waitFor == "string" && allowedOptions.indexOf(waitFor) >= 0) { return [waitFor]; } else if ( toType(waitFor) == "array" && (<string[]>waitFor).every((waitForItem) => { return allowedOptions.indexOf(waitForItem) >= 0; }) ) { return waitFor; } else { return ["networkidle2"]; } })(); await this._page.waitForNavigation({ timeout: this.getTimeoutFromOverload(timeout), waitUntil: waitForEvent, }); return; } /** * Wait for everything to load before continuing * * @param timeout */ public async waitForLoad(timeout?: number): Promise<void> { await this._page.waitForNavigation({ timeout: this.getTimeoutFromOverload(timeout), waitUntil: "load", }); return; } public async waitForFunction( js: EvaluateFn<any>, opts?: PageFnOptions, ...args: SerializableOrJSHandle[] ): Promise<void> { await this._page.waitForFunction.apply(this._page, [js, opts, ...args]); return; } /** * Wait for DOM Loaded before continuing * * @param timeout */ public async waitForReady(timeout?: number): Promise<void> { await this._page.waitForNavigation({ timeout: this.getTimeoutFromOverload(timeout), waitUntil: "domcontentloaded", }); return; } public screenshot(): Promise<Buffer>; public screenshot(localFilePath: string): Promise<Buffer>; public screenshot( localFilePath: string, opts: ScreenshotOpts ): Promise<Buffer>; public screenshot(opts: ScreenshotOpts): Promise<Buffer>; public screenshot( a?: string | ScreenshotOpts, b?: ScreenshotOpts ): Promise<Buffer> { const localFilePath = typeof a == "string" ? a : undefined; const opts: ScreenshotOpts = (typeof a !== "string" ? a : b) || {}; return this._page.screenshot({ path: localFilePath || opts.path, encoding: "binary", omitBackground: opts.omitBackground || false, clip: opts.clip || undefined, fullPage: opts.fullPage || false, }); } public clearThenType( selector: string, textToType: string, opts: any = {} ): ValuePromise { return ValuePromise.execute(async () => { const el = await this.clear(selector); await el.type(textToType, opts); return el; }); } public type( selector: string, textToType: string, opts: any = {} ): ValuePromise { return ValuePromise.execute(async () => { const el = await this.find(selector); await el.type(textToType, opts); return el; }); } public clear(selector: string): ValuePromise { return ValuePromise.execute(async () => { const el = await this.find(selector); await el.clear(); return el; }); } public async scrollTo(point: { x: number; y: number }): Promise<iResponse> { await this._page.evaluate( (x, y) => { window.scrollTo(x, y); }, point.x || 0, point.y || 0 ); return this; } protected getTimeoutFromOverload(a: any, b?: any): number { return typeof b == "number" ? b : typeof a == "number" ? a : DEFAULT_WAITFOR_TIMEOUT; } protected getContainsPatternFromOverload(contains: any): RegExp | null { return contains instanceof RegExp ? contains : typeof contains == "string" ? new RegExp(contains) : null; } public async navigate(req: iHttpRequest) { if (req.uri) { await this.page?.goto(req.uri); } } }
Python
UTF-8
6,690
2.734375
3
[]
no_license
#!/usr/bin/python # Python file to monitor pastebin for pastes containing the passed regex # Eventually this should be run by nagios every 5 mins ### TODO ### 1. allow more than one searchterm ### 2. implement exit codes (to be used as a nagios check) ### 3. implement distinct alert destinations based on each searchterm via config file sections ### 4. scrape other pastebin-like sites, as well as twitter(privatepaste.com, pastie.org, etc.) ### 5. best value would be to be able to use the search function of each site and scrape results (pastebin: http://pastebin.com/search?cx=partner-pub-7089230323117142%3A2864958357&cof=FORID%3A10&ie=UTF-8&q=lolwut&sa.x=-1284&sa.y=-33&sa=Search) ### 6. debug mode (which determines how verbose this crap gets, since nagios only needs an exit code [0,1,2,3,4] and a short status text); example debug(0-nagios mode, 1-cli mode, 2-verbose mode like now) import sys import time import urllib.request, urllib.parse, urllib.error import re import configparser import argparse ### # UTILITY FUNCTIONS SECTION ### def debug(message): if args.debug: print("[DEBUG]: !" + message + "!") return else: return def info(message): print("[INFO]: " + message) def warn(message): print("[WARN]: " + message) def crit(message): print("[CRIT]: " + message + " ... Bailing out ...") def checkconfigfile(): # sanity check for the existence of the config file if args.config != "": path = args.config else: path = "pypaste.cfg" # defaults to this file in the same folder as the script try: tmpfile = open(path) except IOError as e: crit("cannot open configuration file ") debug("Opening the config file failed") sys.exit(e) if tmpfile: info("found config file: " + path) debug("Config file exists and we can open it") return tmpfile def init_config(): global config, args config = configparser.ConfigParser() config.read(args.config) return config def checkconfig_value(val, config): debug("Testing configuration file critical keys...for key: " + val) found = False for section in config.sections(): if config.has_option(section, val): found = True if not found: crit("one of the critical keys was not present in the config file: %s" % val) debug("\t%s value not found" % val) return False else: return True def checkconfig_siteurls(site, config): url_list = [config.get(site, 'latest_url'), config.get(site, 'trends_now_url'), config.get(site, 'trends_week_url'), config.get(site, 'trends_month_url'), config.get(site, 'trends_year_url'), config.get(site, 'trends_all_url')] return url_list def checkconfig_searchterms(config): searchterm_list = [] for option in config.options('search'): searchterm_list.append(config.get('search', option) return searchterm_list ### # SITE-SPECIFIC FUNCTIONS ### def search_raw(needle, haystack, linkid): if re.search(r'' + needle, haystack): info('\t *** FOUND \'' + needle + '\' in link ' + linkid + '\n') def read_site(url, matchstr, paste_ids_position): raw_paste = '' link_id = '' info('read_site() got called with url: ' + url) try: info("we're in the try open url block") lnk = urllib.request.urlopen(url) htm = lnk.read() lnk.close() htm_lines = htm.split('\n') for line in htm_lines: if re.search(matchstr, line): link_id = line[paste_ids_position] info('Link_id: ' + link_id) if re.search('pastebin', url): info('we\'re on pastebin.com') url_2 = urllib.request.urlopen("http://pastebin.com/raw.php?i=" + link_id) else: url_2 = urllib.request.urlopen("http://pastie.org/pastes/" + link_id + "/text") raw_paste = url_2.read() url_2.close() except IOError: print("can\'t connect to url: %s" % url) return raw_paste, link_id if __name__ == "__main__": global args, regex_weblink_string, paste_ids_position argparser = argparse.ArgumentParser(description='Pastebin&Co. string checker script') argparser.add_argument('-c', '--config', type=str, default='pypaste.cfg', help='/path/to/config.cfg ; it defaults to \'pypaste.cfg\' in the same path as the script') argparser.add_argument('-d', '--debug', default=False, action='store_true', help='Debug mode(1=True, 0=False), defaults to False') argparser.add_argument('-s', '--searchterm', type=str, help='the search term you want to look for on these paste sites') args = argparser.parse_args() if not checkconfigfile(): exit(2) cfg = init_config() if args.searchterm and not args.config: # if you only specify -searchterm and don't specify explicitly a config file it means you want only that term searched, ignoring rest of terms in config. search_term = args.searchterm cliterm = True # using this to let the logic know to only compare this to raw text, and not cycle through a bunch of terms expected from config. checkconfig_value('dryrun', config) checkconfig_value('debug', config) srch_terms = '' if not (args.searchterm or checkconfig_value('term1', config): # we should have at least one search term either coming from the config file or the command line, otherwise bail with crit exit(2) crit('no search terms specified') else: info('search terms are:') srch_terms = checkconfig_searchterms(config) for term in srch_terms: info('\t' + term) dryrun = config.get('system', 'dryrun') info('dryrun is: ' + dryrun) # main loop basically print('entered main loop') for url in checkconfig_siteurls('pastebin', config): time.sleep(10) info('main loop url read from config: ' + url) paste_ids_position = config.get('pastebin', 'paste_ids_position') matchstrings = '\'' + config.get('pastebin', 'paste_ids_match_string') + '\'' # shit like '<td><img src=\"/i/t.gif\" class=\"i_p0\" alt=\"\" border=\"0\" /><a href=\"/[0-9a-zA-Z]{8}">.*</a></td>' from config, site dependent, obviously raw, linkid = read_site(url, matchstrings, paste_ids_position) time.sleep(2) for item in srch_terms: search_raw(item, raw, linkid)
Java
UTF-8
133
1.664063
2
[]
no_license
class Program{ public static void main(String[] args) { ExamplePerson a = new ExamplePerson("Joonas", 12, true); } }
Java
UTF-8
2,720
2.375
2
[]
no_license
package net.sf.ehcache.constructs.scheduledrefresh; import junit.framework.Assert; import org.junit.Test; import java.util.Calendar; import java.util.GregorianCalendar; /** * Created with IntelliJ IDEA. * User: cschanck * Date: 6/17/13 * Time: 12:06 PM * To change this template use File | Settings | File Templates. */ public class ScheduledRefreshConfigurationTest { // OK. we want to create an ehcache, then programmitically decorate it with // locks. @Test public void testMisconfiguration() { try { ScheduledRefreshConfiguration config = new ScheduledRefreshConfiguration() .batchSize(-10) .quartzThreadCount(4) .parallelJobCount(5) .pollTimeMs(100) .cronExpression("0/5 * * * * ?").build(); Assert.fail(); } catch(IllegalArgumentException e) { } try { ScheduledRefreshConfiguration config = new ScheduledRefreshConfiguration() .batchSize(10) .quartzThreadCount(0) .parallelJobCount(5) .pollTimeMs(100) .cronExpression("0/5 * * * * ?").build(); Assert.fail(); } catch(IllegalArgumentException e) { } try { ScheduledRefreshConfiguration config = new ScheduledRefreshConfiguration() .batchSize(10) .quartzThreadCount(4) .parallelJobCount(1) .pollTimeMs(100) .cronExpression("0/5 * * * * ?").build(); Assert.fail(); } catch(IllegalArgumentException e) { } try { ScheduledRefreshConfiguration config = new ScheduledRefreshConfiguration() .batchSize(10) .quartzThreadCount(4) .parallelJobCount(5) .pollTimeMs(10000000) .cronExpression("0/5 * * * * ?").build(); Assert.fail(); } catch(IllegalArgumentException e) { } try { ScheduledRefreshConfiguration config = new ScheduledRefreshConfiguration() .batchSize(10) .quartzThreadCount(4) .parallelJobCount(5) .pollTimeMs(-100) .cronExpression("0/5 * * * * ?").build(); Assert.fail(); } catch(IllegalArgumentException e) { } try { ScheduledRefreshConfiguration config = new ScheduledRefreshConfiguration() .batchSize(10) .quartzThreadCount(4) .parallelJobCount(5) .pollTimeMs(100) .cronExpression(null).build(); Assert.fail(); } catch(IllegalArgumentException e) { } } }
Java
UTF-8
2,904
3.078125
3
[]
no_license
package webLesson01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; public class NoteDAO { Connection con = null; PreparedStatement st = null; ResultSet rs = null; static final String URL = "jdbc:mysql://localhost/dictionaly"; static final String USER = "root"; static final String PW = ""; //insert public int registNote(List<Note> lists){ int result = 0; try { //ドライバーのロード Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost/dictionaly?useUnicode=true&characterEncoding=utf8", "root", ""); //DB接続 if( con != null ){ System.out.println("DB接続完了 \r\n---"); } else{ System.out.println("DB接続失敗\r\n---"); return result; } for(int i = 0 ; i < lists.size() ; i++){ String SQL = "INSERT INTO java(id, title, naiyou, answer, site) VALUES(NULL, ?, ?, ?, ?)"; Note nt = lists.get(i); st = con.prepareStatement(SQL); st.setString(2, nt.getTitle()); st.setString(3, nt.getNaiyou()); st.setString(4, nt.getAnswer()); st.setString(5, nt.getSite()); result = result + st.executeUpdate(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if ( st != null) { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } if ( con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } return result; // 結果を返す } //select 件数だけ public int notes(List<Note> notes){ int res = 0; try { //ドライバーのロード Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost/dictionaly", "root", ""); //DB接続 if( con != null ){ System.out.println("登録済み"); } else{ System.out.println("DB接続失敗\r\n---"); return res; } // 単語の読み出し String SQL = "SELECT * FROM java"; st = con.prepareStatement(SQL); rs = st.executeQuery(); while(rs.next()){ Note nt = new Note(rs.getString("title"), rs.getString("naiyou"), rs.getString("answer"), rs.getString("site")); notes.add( nt ); } System.out.println(res + "件"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if ( st != null) { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } if ( con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } return res; // 結果を返す } }
Markdown
UTF-8
2,490
2.78125
3
[]
permissive
# Markdown-CLI [![GitHub issues](https://img.shields.io/github/issues/margual56/Markdown-CLI?style=for-the-badge)](https://github.com/margual56/Markdown-CLI/issues) [![GitHub](https://img.shields.io/github/license/margual56/Markdown-CLI?style=for-the-badge)](https://github.com/margual56/Markdown-CLI/blob/main/docs/LICENSE) [![GitHub followers](https://img.shields.io/github/followers/margual56?style=for-the-badge)](https://github.com/margual56?tab=followers) [![GitHub contributors](https://img.shields.io/github/contributors/margual56/Markdown-CLI?style=for-the-badge)](https://github.com/margual56/Markdown-CLI/graphs/contributors) A markdown CLI renderer in C++ (Still in development) *this is italic* and _this is also italic_, while this is not _this is italic_ **this is bold** __this is bold__ `this is code` and `this is code too` > And this is a quote From my friend inoricat ## Goal Simple syntax, concise commands and versatile while _trying_ to be suckless. Command | Description --- | --- `markdown -i input.md output.html` | Reads the markdown from the file and outputs to another file. `markdown output.html` | Reads the markdown from the stdin (optional). `markdown -i input.md` | Reads the markdown from the file and writes the output to the stdout. `markdown -i input.md -s style.css output.html` | Reads the markdown from the file and outputs to another file, applying the styling rules specified in the css (includes a `<style></style>` tag in the html head). `markdown -h` or `markdown --help` | Display the help (manual) ## Manual The goal is to have here a wiki, implement the manual page and add it to the [tldr pages](https://github.com/tldr-pages/tldr). ## Contributing First of all, thank you for giving us part of your time!<br/> You can contribute by: * [Reporting a bug](https://github.com/margual56/Markdown-CLI/issues/new?assignees=margual56&labels=bug&template=bug_report.md&title=%5BBUG%5D+-+short+description+of+problem) * [Suggesting a new feature](https://github.com/margual56/Markdown-CLI/issues/new?assignees=margual56&labels=enhancement&template=feature_request.md&title=%5BFEATURE%5D+-+short+description+of+the+feature+or+request) * Completing the documentation or the wiki * Fork this project and contribute! Also, check out [the license](https://github.com/margual56/Markdown-CLI/blob/main/docs/LICENSE) and the [code of conduct](https://github.com/margual56/Markdown-CLI/blob/main/docs/CODE_OF_CONDUCT.md)
JavaScript
UTF-8
497
2.765625
3
[]
no_license
let admin = prompt('Кто пришел?'); if (admin == null){ alert("Вход отменен!"); }else if (admin == "Админ") { let password = prompt('Пароль?'); if (password == "Админ"){ alert("Привет чувырло!"); } else if (password == null){ close.prompt; } else{ alert("Пароль неверен") } }else if(admin="Хуило") { alert("Сам такий") } else{ alert("Я вас не знаю"); }
Java
GB18030
1,464
2.625
3
[]
no_license
package com.nonfamous.commom.util.html.filter; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; /** * * @author fish * updateinsert,removeùķΣ * ùjavastringԵhtml * */ public class BeanHtmlFilterInterceptor implements MethodInterceptor { private String[] methodPrefix; private TextPropertiesFilter textPropertiesFilter; public String[] getMethodPrefix() { return methodPrefix; } public void setMethodPrefix(String[] methodPrefix) { this.methodPrefix = methodPrefix; } public TextPropertiesFilter getTextPropertiesFilter() { return textPropertiesFilter; } public void setTextPropertiesFilter( TextPropertiesFilter textPropertiesFilter) { this.textPropertiesFilter = textPropertiesFilter; } public Object invoke(MethodInvocation invocation) throws Throwable { String methodName = invocation.getMethod().getName(); if (needInterceptor(methodName)) { Object[] args = invocation.getArguments(); if (args != null && args.length > 0) { for (Object arg : args) { if (arg != null) { textPropertiesFilter.filterProperties(arg); } } } } return invocation.proceed(); } private boolean needInterceptor(String methodName) { for (String prefix : this.methodPrefix) { if (methodName.startsWith(prefix)) { return true; } } return false; } }
C++
UTF-8
1,566
3.28125
3
[]
no_license
#pragma once #include <Constraint.h> #include <math.h> /*============================================================================\\ | Any constraint that has a parameter that shapes the probabilty of a tile to | be placed depending of the value returned by the constraint. | | As the strength gets closer to infinity, the more sever this constraint is. | The doNegate parameter indicate if the value returned by the child class | should be negated before computed. |-----------------------------------------------------------------------------|| | Parameters: | - Strength : how critical is the effect of this constraint | - Do Negate: Means that the more the "simple" weight is big, the less | probable the tile will be placed \=============================================================================*/ class ConstraintWithStrength : public virtual Constraint { public: // CONSTRUCTOR/DESTRUCTOR ConstraintWithStrength(const Map& i_Map, double i_Strength, bool i_DoNegate) : Constraint(i_Map), m_Strength(i_Strength), m_DoNegate(i_DoNegate) {} // WEIGHT double getWeightFor(Coord i_Coord) const { if (m_DoNegate) { return pow(1 - getSimpleWeightFor(i_Coord), m_Strength); } else { return pow(getSimpleWeightFor(i_Coord), m_Strength); } } virtual double getSimpleWeightFor(Coord i_Coord) const = 0; private: double m_Strength; bool m_DoNegate; };
Swift
UTF-8
903
2.90625
3
[]
no_license
import RxSwift /// Cached repository for repository protocol class CachedRepository: RepositoryProtocol { // MARK: Properties private let moyaRepository: MoyaRepository private let realmRepository: RealmRepository // MARK: Initialization init(moyaRepository: MoyaRepository, realmRepository: RealmRepository) { self.moyaRepository = moyaRepository self.realmRepository = realmRepository } /// Gets all public repositories from cache /// /// - Parameter since: Repository identifier offset /// - Returns: List of repositories func getAll(since: Int) -> Single<[Repository]> { let moyaSingle = moyaRepository .getAll(since: since) let realmSingle = realmRepository .getAll(since: since) return moyaSingle .catchError { _ in return realmSingle } } }
Java
UTF-8
3,112
2.125
2
[]
no_license
package app.prac.monthlykhata.Activity; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.FirebaseFirestore; import java.util.HashMap; import java.util.Map; import app.prac.monthlykhata.Extra.Utils; import app.prac.monthlykhata.MonthlyKhataApp; import app.prac.monthlykhata.R; import butterknife.BindView; import butterknife.ButterKnife; public class AddBusinessDetail extends AppCompatActivity { @BindView(R.id.edt_bus_name) EditText edt_bus_name; @BindView(R.id.edt_name) EditText edt_name; @BindView(R.id.btnProceed) Button btnProceed; private String b_name, name; String TAG = "Firebase Message"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_business_detail); ButterKnife.bind(this); btnProceed.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { b_name = edt_bus_name.getText().toString(); name = edt_name.getText().toString(); if (b_name.isEmpty()) { Utils.snackBarText(AddBusinessDetail.this, "Please enter Business name!").show(); } else if (name.isEmpty()) { Utils.snackBarText(AddBusinessDetail.this, "Please enter Name!").show(); } else { FirebaseUser mCurrentAcount = MonthlyKhataApp.getFireBaseAuth().getCurrentUser(); FirebaseFirestore db = FirebaseFirestore.getInstance(); Map<String, Object> account = new HashMap<>(); account.put("name", name); account.put("b_name", b_name); account.put("phone", mCurrentAcount.getPhoneNumber()); db.collection("Account").document(mCurrentAcount.getUid()) .set(account).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.e(TAG, "DocumentSnapshot added "); Intent intent = new Intent(AddBusinessDetail.this, MainActivity.class); startActivity(intent); finish(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.e(TAG, "DocumentSnapshot error "); } }); } } }); } }
C
UTF-8
180
3.046875
3
[]
no_license
#include <stdio.h> int main() { int a,b,c; printf("addition"); printf("1st number"); scanf("%d",&a); printf("2st number"); scanf("%d",&b); c=a+b; printf("%d",c); return 0; }
Java
UTF-8
659
2.421875
2
[]
no_license
package com.example.soc_macmini_15.musicplayer.Model; public class SongsList { private String title; private String subTitle; private String path; public String getPath() { return path; } public void setPath(String path) { this.path = path; } public SongsList(String title, String subTitle, String path) { this.title = title; this.subTitle = subTitle; this.path = path; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSubTitle() { return subTitle; } }
C
UTF-8
2,407
3.421875
3
[]
no_license
// karekök bulan fonsiyonu dogrusal ent kullanarak yazınız #include <stdio.h> #include <math.h> /* --ALGORİTMA-- 1. Start 2. Verileri al 3. Verilen iki kökü fonksiyona koy ve çıkan değerleri çarp 4. Sonucun sıfırdan küçük olup olmadığını kontrol et küçükse bu aralıkta kök vardır. Adım 5' e geç. Küçük değilse aralıkta kök yoktur adım 16'ya git. 5. En son bulunan iki kök arasındaki farkı bul.Bulunan değer hatapayıdır.son kökü değikene al ezilip kaybolmaması için 6. Hata payı toleranstan büyükse döngüye gir(Adım 7 den devam).Değilse Adım 15 e git. 7. Yeni kökü (xlower * f(xupper) - xupper * f(xlower)) / (f(xupper) - f(xlower) formülünü kullanarak bul. 8. Lower kök ile yeni bulunan kökün fonksiyonlardaki değerlerini çarp 9. Sonuç sıfırdan küçükse upper kökü yeni bulunan kök olarak kabul et. 10. Büyükse lower kökü yeni bulunan kök olarak kabul et. 11. Sıfıra eşitse kök zaten bulunmuş demektir.adım 15'e git. 12. Son iki kökün farkını alarak hata payını bul. 13. Son bulunan kökü değişkende tut. 14. Adım 6 ya git. 15. Bulunan kökü yazdır. 16. Stop */ // Algoritma Aynıdır tek farklılık kullanılan fonsiyondaki sabit değer // kullanıcıdan alınarak dinamiklik kazandırılmıştır. double f(double x, double a) { return pow(x, 2) - a; } double karekokbul(double a) { double xlower = 0.0, xupper = a, xr = 0.0, hata = 0.0, tolerans = 0.1; if (a >= 0) { hata = fabs(xupper - xlower); double sonkok = xupper; while (hata > tolerans) { xr = (xlower * f(xupper, a) - xupper * f(xlower, a)) / (f(xupper, a) - f(xlower, a)); if (f(xlower, a) * f(xr, a) < 0) { xupper = xr; } else if (f(xlower, a) * f(xr, a) > 0) { xlower = xr; } else { sonkok = xr; break; } hata = fabs(sonkok - xr); sonkok = xr; } } else printf("Verilen sayının real bir karakökü yoktur\n"); return xr; } int main(int argc, char const *argv[]) { double sayi; printf("hangi sayının karekökünü bulmak istiyorsunuz : "); scanf("%lf", &sayi); printf("\n%lf\n", karekokbul(sayi)); return 0; }
Python
UTF-8
4,093
2.71875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Thu 7-Oct-2021 Link : ANN regression model : https://colab.research.google.com/drive/1eje9zILprgVmohMN7cKykI3fn4FBRPnF Onehot encoder : https://towardsdatascience.com/columntransformer-in-scikit-for-labelencoding-and-onehotencoding-in-machine-learning-c6255952731b https://stackoverflow.com/questions/58087238/valueerror-setting-an-array-element-with-a-sequence-when-using-onehotencoder-on Evaluation : https://thinkingneuron.com/using-artificial-neural-networks-for-regression-in-python/ @author: 41162395 """ def main(): import numpy as np import pandas as pd # import seaborn as sns from ballshear_reg_train import ann_create df = pd.read_json('df.json') # read cleasing dataset # One hot encoder to numpy array X as below 9 columns or features # Parameter.BondType,Parameter.Group,Parameter.No,Parameter.No_1,WIRE_SIZE,Parameter.Max,Parameter.Min,Parameter.Value, MEANX from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder ct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(handle_unknown='ignore'), [0,1,2,3,4,5])], remainder='passthrough') X = ct.fit_transform(df).toarray() # upper case 'X' #X0 = ct.transform(dfx).toarray() # upper case 'X0' # Split X to 2 arrays as x inputFeatures and y outputResponse selector = [i for i in range(X.shape[1]) if i != 47] #Column 35 is 'MEANX' x = X[:,selector] # lower case 'x' all column except 'MEANX' y = X[:,47] # lower case 'y' for 'MEANX' # Splitting the dataset into the Training set and Test set""" from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, random_state = 0) ann = ann_create() input_shape = x.shape ann.build(input_shape) ann.load_weights('save.hdf5') ann.summary() # Predicting the results of the Test set y_pred = ann.predict(X_test) y_pred_2 = np.ravel(y_pred) # Reduce shape of y_pred compare = pd.DataFrame(y_test) compare['y_pred'] = y_pred_2.tolist() compare.to_csv('compare.csv') # printing the results of the current iteration np.set_printoptions(precision=2) compare = np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1) print(compare) MAPE = np.mean(100 * (np.abs(y_test-ann.predict(X_test))/y_test)) print('Accuracy:', 100-MAPE) #add 'Y' array as new column in df DataFrame PRED = ann.predict(x) PRED_2 = np.ravel(PRED) # Reduce shape of y_pred df['PRED'] = PRED_2.tolist() #Export output to csv df.to_csv('ballshear_regression.csv') if __name__ == '__main__': main() ############################# # Common command #------------------------- # df.describe # df.info() # df.index # df.columns # dfx[:5] # du1=ds1.unstack() # df.isna().sum() # dfx = df.set_index(['C_RISTIC','PT','Parameter.CreateTime','Parameter.BondType','Parameter.No']) # df.loc[25024] # for i in range (len(Y)): # if Y[i] == -1: # print (df.loc[i]) # # selected_columns = df[["col1","col2"]] # new_df = selected_columns.copy() # # sns.scatterplot(x='sepal_length', y='sepal_width', hue='class', data=iris) # sns.scatterplot(x='MEANX', y='SD', data=temp) # # df0 = pd.read_json(jsonstr,orient="index") # df0 = pd.read_json('input.json',orient="index") # df0.drop(to_drop, inplace=True) # df0 = df0.transpose() # # df_org[Y==-1] #List Row for Y = -1 # # df0 = df[:1] #For dummy prediction of testing data # df0json = df0.to_json() # file1 = open("x_input.json","w") # file1.writelines(df0json) # file1.close() # # df.groupby('C_RISTIC').count() #pandas count categories # df.groupby('Parameter.Group').count() # # cpare = pd.DataFrame(compare) #np array to dataframe # cpare.to_csv('compare.csv') # # df.rename(columns={"A": "a", "B": "c"})
Java
UTF-8
436
2.421875
2
[]
no_license
package info.germanvaldesdev.demo.scaffoltasks.tasks; public abstract class Task { private TaskProcessor<Task> taskProcessor; Task() { taskProcessor = TaskProcessorUtil.getTaskProcessorFor(getClass()); } public void processRequest(String req) { taskProcessor.processRequest(req, this); } public void processResponse(String resp) { taskProcessor.processResponse(resp, this); } }
JavaScript
UTF-8
347
2.546875
3
[ "MIT" ]
permissive
suite('Using JSONP', function () { test('Requesting a callback with text runs the callback.', function (done) { // Introduce a global function called 'verify'. This is by intention. verify = function (text) { expect(text).to.eql('http.js'); done(); }; http.get('/usingJsonp/text', { jsonp: 'verify' }); }); });
Java
UTF-8
14,898
1.773438
2
[]
no_license
package reactive.ui; import android.view.*; import android.app.*; import android.content.*; import android.graphics.*; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.util.*; import android.view.*; import android.widget.*; import java.util.*; import reactive.ui.*; import android.content.res.*; import android.view.View.MeasureSpec; import android.view.animation.*; import tee.binding.properties.*; import tee.binding.task.*; import tee.binding.it.*; import tee.binding.*; import tee.binding.properties.ToggleProperty; import android.net.*; import java.io.*; import java.text.*; import android.database.*; import android.database.sqlite.*; public class Layoutless extends RelativeLayout implements Rake { public final static int NONE = 0; public final static int DRAG = 1; public final static int ZOOM = 2; private int mode = NONE; private float lastEventX = 0; private float lastEventY = 0; private float initialShiftX = 0; private float initialShiftY = 0; private float initialSpacing; private float currentSpacing; //private int mw = 320; //private int mh = 240; private ToggleProperty<Rake> hidden = new ToggleProperty<Rake>(this); private NumericProperty<Rake> left = new NumericProperty<Rake>(this); private NumericProperty<Rake> top = new NumericProperty<Rake>(this); private NumericProperty<Rake> width = new NumericProperty<Rake>(this); private NumericProperty<Rake> height = new NumericProperty<Rake>(this); public NumericProperty<Layoutless> innerWidth = new NumericProperty<Layoutless>(this); public NumericProperty<Layoutless> innerHeight = new NumericProperty<Layoutless>(this); public NumericProperty<Layoutless> shiftX = new NumericProperty<Layoutless>(this); public NumericProperty<Layoutless> shiftY = new NumericProperty<Layoutless>(this); public NumericProperty<Layoutless> lastShiftX = new NumericProperty<Layoutless>(this); public NumericProperty<Layoutless> lastShiftY = new NumericProperty<Layoutless>(this); public NumericProperty<Layoutless> zoom = new NumericProperty<Layoutless>(this); public NumericProperty<Layoutless> maxZoom = new NumericProperty<Layoutless>(this); public NumericProperty<Layoutless> tapX = new NumericProperty<Layoutless>(this); public NumericProperty<Layoutless> tapY = new NumericProperty<Layoutless>(this); public ToggleProperty<Layoutless> solid = new ToggleProperty<Layoutless>(this); public ItProperty<Layoutless, Task> afterTap = new ItProperty<Layoutless, Task>(this); public ItProperty<Layoutless, Task> afterShift = new ItProperty<Layoutless, Task>(this); public ItProperty<Layoutless, Task> afterZoom = new ItProperty<Layoutless, Task>(this); //private static TextView colorTest; private boolean initialized = false; public Vector<Rake> children = new Vector<Rake>(); //private boolean measured = false; protected void init() { //System.out.println("init " + initialized); if (!initialized) { initialized = true; solid.is(true); Auxiliary.initThemeConstants(this.getContext()); setFocusable(true); setFocusableInTouchMode(true); hidden.property.afterChange(new Task() { @Override public void doTask() { if (hidden.property.value()) { setVisibility(View.INVISIBLE); } else { setVisibility(View.VISIBLE); } } }); } } @Override public ToggleProperty<Rake> hidden() { return hidden; } public Layoutless(Context context) { super(context); init(); } public Layoutless(Context context, AttributeSet attrs) { super(context, attrs); init(); } public Layoutless(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public Layoutless child(Rake v) { this.addView(v.view()); children.add(v); return this; } public Layoutless input(Context context, double row, double left, Note label, Rake content, Numeric contentWidth) { this.child(new Decor(context).labelText.is(label)// .left().is(this.shiftX.property.plus(left))// .top().is(this.shiftY.property.plus(1.5 * row * Auxiliary.tapSize))// .width().is(contentWidth)// .height().is(0.5 * Auxiliary.tapSize)// ); this.child(content// .left().is(this.shiftX.property.plus(left))// .top().is(this.shiftY.property.plus((0.5 + 1.5 * row) * Auxiliary.tapSize))// .width().is(contentWidth)// .height().is(0.8 * Auxiliary.tapSize)// ); return this; } public Layoutless input(Context context, double row, double left, Note label, Rake content) { return input(context, row, left, label, content, new Numeric().value(5 * Auxiliary.tapSize)); } public Layoutless input(Context context, double row, double left, Note label, Rake content, int contentWidth) { return input(context, row, left, label, content, new Numeric().value(contentWidth)); } public Layoutless input(Context context, double row, double left, String label, Rake content) { return input(context, row, left, new Note().value(label), content, new Numeric().value(5 * Auxiliary.tapSize)); } public Layoutless input(Context context, double row, double left, String label, Rake content, int contentWidth) { return input(context, row, left, new Note().value(label), content, new Numeric().value(contentWidth)); } public Layoutless input(Context context, double row, double left, String label, Rake content, Numeric contentWidth) { return input(context, row, left, new Note().value(label), content, contentWidth); } public Layoutless field(Context context, double row, Note label, Rake content, Numeric contentWidth) { this.child(new Decor(context).labelText.is(label)// .labelAlignRightCenter()// .left().is(this.shiftX.property)// .top().is(this.shiftY.property.plus(0.2 * Auxiliary.tapSize).plus(0.8 * row * Auxiliary.tapSize))// .width().is(this.width().property.multiply(0.3))// .height().is(0.8 * Auxiliary.tapSize)// ); this.child(content// .left().is(this.shiftX.property.plus(this.width().property.multiply(0.3).plus(0.1 * Auxiliary.tapSize)))// .top().is(this.shiftY.property.plus(0.2 * Auxiliary.tapSize).plus(0.8 * row * Auxiliary.tapSize))// .width().is(contentWidth)// .height().is(0.8 * Auxiliary.tapSize)// ); return this; } public Layoutless field(Context context, double row, Note label, Rake content) { return field(context, row, label, content, new Numeric().value(5 * Auxiliary.tapSize)); } public Layoutless field(Context context, double row, Note label, Rake content, int contentWidth) { return field(context, row, label, content, new Numeric().value(contentWidth)); } public Layoutless field(Context context, double row, String label, Rake content) { return field(context, row, new Note().value(label), content, new Numeric().value(5 * Auxiliary.tapSize)); } public Layoutless field(Context context, double row, String label, Rake content, int contentWidth) { return field(context, row, new Note().value(label), content, new Numeric().value(contentWidth)); } public Layoutless field(Context context, double row, String label, Rake content, Numeric contentWidth) { return field(context, row, new Note().value(label), content, contentWidth); } public Rake child(int nn) { if (nn < children.size()) { return children.get(nn); } else { return null; } } public int count() { return children.size(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); /*System.out.println("Layoutless.onSizeChanged: " + oldw + "x" + oldh + " => " + w + "x" + h + ", measured "// + this.getMeasuredWidth() + "x" + this.getMeasuredHeight()// + " at " + this.getLeft() + ":" + this.getTop()// );*/ //if (w > mw && h > mh) { if (w > width.property.value() && h>height.property.value()) { width.is(w); height.is(h); } //} /*try { int n = 0; n = 1 / n; } catch (Throwable t) { t.printStackTrace(); }*/ } /*String maskName(int mask){ if(mask==android.view.View.MeasureSpec.AT_MOST){ return "AT_MOST"; } if(mask==android.view.View.MeasureSpec.EXACTLY){ return "EXACTLY"; } if(mask==android.view.View.MeasureSpec.UNSPECIFIED){ return "UNSPECIFIED"; } return "?"+mask; }*/ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { /*int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); System.out.println("onMeasure: " + widthSize + ":" + maskName(MeasureSpec.getMode(widthMeasureSpec)) // + " x " + heightSize + ":" + maskName(MeasureSpec.getMode(heightMeasureSpec))// + ", measured "+this.getMeasuredWidth() + "x" + this.getMeasuredHeight() // );*/ //int exw=MeasureSpec.makeMeasureSpec(widthSize,android.view.View.MeasureSpec.EXACTLY); //int exh=MeasureSpec.makeMeasureSpec(heightSize,android.view.View.MeasureSpec.EXACTLY); super.onMeasure(widthMeasureSpec, heightMeasureSpec); /*if(widthSize>width.property.value()){ //width.property.value(widthSize); } if(heightSize>height.property.value()){ //height.property.value(heightSize); }*/ //setMeasuredDimension(width.property.value().intValue(), height.property.value().intValue()); //onMeasureX(); } /*protected void onMeasureX() { System.out.println("onMeasureX: measured "// + this.getMeasuredWidth() + "x" + this.getMeasuredHeight() // + ", properties " // + this.width().property.value() + "x" + this.height().property.value()// +" - "+this// ); //if (!measured) { // measured = true; // width.is(getMeasuredWidth()); // height.is(getMeasuredHeight()); //} int w = getMeasuredWidth(); int h = getMeasuredHeight(); //if (w > mw && h > mh) { width.is(w); height.is(h); System.out.println("now: properties " // + this.width().property.value() + "x" + this.height().property.value()// ); //} }*/ @Override public boolean onTouchEvent(MotionEvent event) { if (!solid.property.value()) { return false; } if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN) { initialShiftX = shiftX.property.value().floatValue(); initialShiftY = shiftY.property.value().floatValue(); lastEventX = event.getX(); lastEventY = event.getY(); mode = DRAG; } else { if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_MOVE) { if (event.getPointerCount() > 1) { if (mode == ZOOM) { currentSpacing = spacing(event.getX(0), event.getY(0), event.getX(1), event.getY(1)); } else { initialSpacing = spacing(event.getX(0), event.getY(0), event.getX(1), event.getY(1)); currentSpacing = initialSpacing; mode = ZOOM; } } else { setShift(event.getX(), event.getY()); lastEventX = event.getX(); lastEventY = event.getY(); } } else { if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP) { if (mode == DRAG) { finishDrag(event.getX(), event.getY()); } else { if (mode == ZOOM) { finishZoom(); } else { // } } } else { // } } } return true; } public static float spacing(float x0, float y0, float x1, float y1) { float x = x0 - x1; float y = y0 - y1; return FloatMath.sqrt(x * x + y * y); } void setShift(float x, float y) { double newShiftX = shiftX.property.value() + x - lastEventX; double newShiftY = shiftY.property.value() + y - lastEventY; shiftX.property.value(newShiftX); shiftY.property.value(newShiftY); } void finishDrag(float x, float y) { setShift(x, y); if (Math.abs(initialShiftX - shiftX.property.value()) < 1 + 0.1 * Auxiliary.tapSize// && Math.abs(initialShiftY - shiftY.property.value()) < 1 + 0.1 * Auxiliary.tapSize) { finishTap(x, y); } else { double newShiftX = shiftX.property.value(); double newShiftY = shiftY.property.value(); if (innerWidth.property.value() > width.property.value()) { if (newShiftX < width.property.value() - innerWidth.property.value()) { newShiftX = width.property.value() - innerWidth.property.value(); } } else { newShiftX = 0; } if (innerHeight.property.value() > height.property.value()) { if (newShiftY < height.property.value() - innerHeight.property.value()) { newShiftY = height.property.value() - innerHeight.property.value(); } } else { newShiftY = 0; } if (newShiftX > 0) { newShiftX = 0; } if (newShiftY > 0) { newShiftY = 0; } if (afterShift.property.value() != null) { lastShiftX.property.value(newShiftX); lastShiftY.property.value(newShiftY); afterShift.property.value().start(); } else { shiftX.property.value(newShiftX); shiftY.property.value(newShiftY); } } mode = NONE; } void finishTap(float x, float y) { shiftX.property.value((double) initialShiftX); shiftY.property.value((double) initialShiftY); tapX.property.value((double) x); tapY.property.value((double) y); if (afterTap.property.value() != null) { afterTap.property.value().start(); } } void finishZoom() { if (currentSpacing > initialSpacing) { if (zoom.property.value() < maxZoom.property.value()) { zoom.is(zoom.property.value() + 1); } } else { if (zoom.property.value() > 0) { zoom.is(zoom.property.value() - 1); } } shiftX.property.value((double) initialShiftX); shiftY.property.value((double) initialShiftY); if (afterZoom.property.value() != null) { afterZoom.property.value().start(); } mode = NONE; } @Override public NumericProperty<Rake> left() { return left; } @Override public NumericProperty<Rake> top() { return top; } @Override public NumericProperty<Rake> width() { return width; } @Override public NumericProperty<Rake> height() { return height; } @Override public View view() { return this; } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); left.property.unbind(); top.property.unbind(); width.property.unbind(); height.property.unbind(); innerWidth.property.unbind(); innerHeight.property.unbind(); shiftX.property.unbind(); shiftY.property.unbind(); zoom.property.unbind(); maxZoom.property.unbind(); tapX.property.unbind(); tapY.property.unbind(); solid.property.unbind(); afterTap.property.unbind(); afterShift.property.unbind(); afterZoom.property.unbind(); } }
Markdown
UTF-8
4,701
2.578125
3
[ "BSD-2-Clause" ]
permissive
daru ==== Data Analysis in RUby [![Gem Version](https://badge.fury.io/rb/daru.svg)](http://badge.fury.io/rb/daru) [![Build Status](https://travis-ci.org/v0dro/daru.svg)](https://travis-ci.org/v0dro/daru) ## Introduction daru (Data Analysis in RUby) is a library for storage, analysis, manipulation and visualization of data. daru is inspired by pandas, a very mature solution in Python. Written in pure Ruby so should work with all ruby implementations. Tested with MRI 2.0, 2.1, 2.2. ## Features * Data structures: - Vector - A basic 1-D vector. - DataFrame - A 2-D spreadsheet-like structure for manipulating and storing data sets. This is daru's primary data structure. * Compatible with [IRuby notebook](https://github.com/SciRuby/iruby), [statsample](https://github.com/SciRuby/statsample) and [statsample-glm](). * Singly and hierarchially indexed data structures. * Flexible and intuitive API for manipulation and analysis of data. * Easy plotting, statistics and arithmetic. * Plentiful iterators. * Optional speed and space optimization on MRI with [NMatrix](https://github.com/SciRuby/nmatrix) and GSL. * Easy splitting, aggregation and grouping of data. * Quickly reducing data with pivot tables for quick data summary. * Import and exports dataset from and to Excel, CSV, Databases and plain text files. ## Notebooks ### Usage * [Basic Creation of Vectors and DataFrame](http://nbviewer.ipython.org/github/SciRuby/sciruby-notebooks/blob/master/Data%20Analysis/Creation%20of%20Vector%20and%20DataFrame.ipynb) * [Detailed Usage of Daru::Vector](http://nbviewer.ipython.org/github/SciRuby/sciruby-notebooks/blob/master/Data%20Analysis/Usage%20of%20Vector.ipynb) * [Detailed Usage of Daru::DataFrame](http://nbviewer.ipython.org/github/SciRuby/sciruby-notebooks/blob/master/Data%20Analysis/Usage%20of%20DataFrame.ipynb) * [Visualizing Data With Daru::DataFrame](http://nbviewer.ipython.org/github/SciRuby/sciruby-notebooks/blob/master/Visualization/Visualizing%20data%20with%20daru%20DataFrame.ipynb) * [Grouping, Splitting and Pivoting Data](http://nbviewer.ipython.org/github/SciRuby/sciruby-notebooks/blob/master/Data%20Analysis/Grouping%2C%20Splitting%20and%20Pivoting.ipynb) ### Case Studies * [Logistic Regression Analysis with daru and statsample-glm](http://nbviewer.ipython.org/github/SciRuby/sciruby-notebooks/blob/master/Data%20Analysis/Logistic%20Regression%20with%20daru%20and%20statsample-glm.ipynb) * [Finding and Plotting most heard artists from a Last.fm dataset](http://nbviewer.ipython.org/github/SciRuby/sciruby-notebooks/blob/master/Data%20Analysis/Finding%20and%20plotting%20the%20most%20heard%20artists%20on%20last%20fm.ipynb) ## Blog Posts * [Data Analysis in RUby: Basic data manipulation and plotting](http://v0dro.github.io/blog/2014/11/25/data-analysis-in-ruby-basic-data-manipulation-and-plotting/) * [Data Analysis in RUby: Splitting, sorting, aggregating data and data types](http://v0dro.github.io/blog/2015/02/24/data-analysis-in-ruby-part-2/) ## Documentation Docs can be found [here](https://rubygems.org/gems/daru). ## Roadmap * Enable creation of DataFrame by only specifying an NMatrix/MDArray in initialize. Vector naming happens automatically (alphabetic) or is specified in an Array. * Basic Data manipulation and analysis operations: - DF concat * Assignment of a column to a single number should set the entire column to that number. * == between daru_vector and string/number. * Multiple column assignment with []= * Multiple value assignment for vectors with []=. * #find\_max function which will evaluate a block and return the row for the value of the block is max. * Function to check if a value of a row/vector is within a specified range. * Create a new vector in map_rows if any of the already present rows dont match the one assigned in the block. * Sort by index. * Statistics on DataFrame over rows and columns. * Cumulative sum. * Calculate percentage change. * Have some sample data sets for users to play around with. Should be able to load these from the code itself. * Sorting with missing data present. * Change internals of indexes to raise errors when a particular index is missing and the passed key is a Fixnum. Right now we just return the Fixnum for convienience. ## Contributing Pick a feature from the Roadmap or the issue tracker or think of your own and send me a Pull Request! ## Acknowledgements * Google and the Ruby Science Foundation for the Google Summer of Code 2015 grant for further developing daru and integrating it with other ruby gems. * Thank you [last.fm](http://www.last.fm/) for making user data accessible to the public. Copyright (c) 2015, Sameer Deshmukh All rights reserved
Java
UTF-8
1,045
3.46875
3
[]
no_license
package com.leetcode.array; /* 给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。 说明:你不能倾斜容器。   示例 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/container-with-most-water 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public class MaxArea { public int maxArea(int[] height) { int size = height.length - 1; int i = 0; int max = 0; while (i < size) { int tmp = Math.min(height[size], height[i]) * (size - i); if (tmp > max) { max = tmp; } if (height[size] < height[i]) { size--; } else { i++; } } return max; } }
Java
UTF-8
1,243
3.4375
3
[]
no_license
package IceCreamFactory; public class Children { private String name; private IceCream iceCream; private String favouritColor; private String favouritTaste; private int favouritWeight; private int favouritSize; public String getName() { return name; } public IceCream getIceCream() { return iceCream; } public String getFavouritColor() { return favouritColor; } public String getFavouritTaste() { return favouritTaste; } public int getFavouritWeight() { return favouritWeight; } public int getFavouritSize() { return favouritSize; } public Children(){ this("red","strawberry",2,3,"Paula"); } public Children(String color,String taste, int weight,int size,String name){ this.favouritColor=color; this.favouritTaste=taste; this.favouritWeight=weight; this.favouritSize=size; this.name =name; } public void acceptIceCream(IceCream iceCream) throws Exception{ if(iceCream.getColor()==favouritColor&&iceCream.getTaste()==favouritTaste &&iceCream.getWeight()==favouritWeight&&iceCream.getSize()==favouritSize){ System.out.println(name + " says <<I like it so much>>"); this.iceCream = iceCream; }else{ throw new Exception(); } } }
PHP
UTF-8
3,473
2.9375
3
[]
no_license
<?php require_once 'Framework/Modele.php'; /** * Fournit les services d'accès aux genres musicaux * * @author Baptiste Pesquet */ class Place extends Modele { // Renvoie la liste des places associés à un transaction public function getPlaces($idTransaction = NULL) { if ($idTransaction == NULL) { $sql = 'SELECT p.id,' . ' p.transaction_id,' . ' p.Description,' . ' p.Adresse,' . ' p.auteur,' . ' p.efface,' . ' t.Daate as DaateTransaction' . ' FROM places p' . ' INNER JOIN transactions t' . ' ON p.transaction_id = t.id' . ' ORDER BY id desc';; } else { $sql = 'SELECT * from places' . ' WHERE transaction_id = ?' . ' ORDER BY id desc';; } $places = $this->executerRequete($sql, [$idTransaction]); return $places; } // Renvoie la liste des places publics associés à un transaction public function getPlacesPublics($idTransaction = NULL) { if ($idTransaction == NULL) { $sql = 'SELECT p.id,' . ' p.transaction_id,' . ' p.Adresse,' . ' p.Description,' . ' p.auteur,' . ' p.efface,' . ' t.Daate as DaateTransaction' . ' FROM places p' . ' INNER JOIN transactions t' . ' ON p.transaction_id = t.id' . ' WHERE p.efface = 0 ' . ' ORDER BY id desc'; } else { $sql = 'SELECT * FROM places' . ' WHERE transaction_id = ? AND efface = 0' . ' ORDER BY id desc';; } $places = $this->executerRequete($sql, [$idTransaction]); return $places; } // Renvoie un place spécifique public function getPlace($id) { $sql = 'SELECT * FROM places' . ' WHERE id = ?'; $place = $this->executerRequete($sql, [$id]); if ($place->rowCount() == 1) { return $place->fetch(); // Accès à la première ligne de résultat } else { throw new Exception("Aucune place ne correspond à l'identifiant '$id'"); } } // Supprime un place public function deletePlace($id) { $sql = 'UPDATE places' . ' SET efface = 1' . ' WHERE id = ?'; $result = $this->executerRequete($sql, [$id]); return $result; } // Réactive un place public function restorePlace($id) { $sql = 'UPDATE places' . ' SET efface = 0' . ' WHERE id = ?'; $result = $this->executerRequete($sql, [$id]); return $result; } // Ajoute un place associés à un transaction public function setPlace($place) { $sql = 'INSERT INTO places (' . 'transaction_id,' . ' Adresse,' . ' Description,' . ' auteur)' . ' VALUES(?, ?, ?, ?)'; $result = $this->executerRequete($sql, [ $place['transaction_id'], $place['Adresse'], $place['Description'], $place['auteur'] ] ); return $result; } }
Java
UTF-8
1,957
2.328125
2
[]
no_license
/* * Copyright 2009 LugIron Software, Inc. All Rights Reserved. * * $Id$ */ package io.pgmigrate; import java.sql.Timestamp; public class Migration implements Comparable<Migration> { private String name; private Integer ordinal; private Timestamp created; private Boolean production; private String filepath; public String getName() { return name; } public void setName(final String name) { this.name = name; } public Integer getOrdinal() { return ordinal; } public void setOrdinal(final Integer ordinal) { this.ordinal = ordinal; } public Timestamp getCreated() { return created; } public void setCreated(final Timestamp created) { this.created = created; } public Boolean getProduction() { return production; } public void setProduction(final Boolean production) { this.production = production; } public String getFilepath() { return filepath; } public void setFilepath(final String filepath) { this.filepath = filepath; } public Migration(final Integer ordinal, final String name, final String filepath) { this.ordinal = ordinal; this.name = name; this.filepath = filepath; } @Override public int compareTo(final Migration migration) { return this.ordinal.compareTo(migration.getOrdinal()); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Migration migration = (Migration) o; if (name != null ? !name.equals(migration.name) : migration.name != null) { return false; } return true; } @Override public int hashCode() { return name != null ? name.hashCode() : 0; } }
C++
UTF-8
423
2.65625
3
[]
no_license
#pragma once #include <string> class Shader { public: Shader(const char* vertexPath, const char* fragmentPath); void use(); void setBool(const std::string &name, bool value) const; void setInt(const std::string &name, int value) const; void setFloat(const std::string &name, float value) const; void setFloat4(const std::string &name, float v1, float v2, float v3, float v4) const; private: unsigned int _id; };
PHP
UTF-8
776
2.828125
3
[]
no_license
<?php include_once "koneksi-db-andri.php"; try { // perintah untuk membuat sebuah tabel bernama kawan_main_ff $sql = "CREATE TABLE kawan_main_ff ( id INT(6) AUTO_INCREMENT PRIMARY KEY, nama VARCHAR(30) NOT NULL, kelas VARCHAR(30) NOT NULL, tgl_lahir date NULL )"; // eksekusi perintah diatas, simpan status berhasil atau tidak dalam variabel $hasil $hasil = $conn->query($sql); // cek status pembuatan tabel , apakah berhasil atau tidak if ($hasil) { echo "Berhasil membuat tabel<br>"; } else { echo "Gagal membuat tabel<br>"; } } catch (PDOException $exception) { echo "error : " . $exception->getMessage() . "<br>"; } echo "<a href='/'>kembali</a>";
Markdown
UTF-8
1,550
2.8125
3
[]
no_license
## High Efficiency High Power Density Multi-level PFC Converter #### Project Type: ARÇELİK #### Project Duration: 33 months ### Brief Summary Power factor correction (PFC) is a term given to a technology that has been used since the turn of the 20th century to restore the power factor to as close to unity as is economically viable. Conventional methods for this purpose include adding capacitors to the electrical grid which compensate for the reactive power demand of the inductive load and thus reduce the burden on the supply. But the problem of passive PFC methods is that they require line frequency filters which are bulky and heavy. By improvement in the semiconductor technology, power electronics-based solutions have emerged in the past few decades which effectively follow the PFC aim which is regulating the output voltage and input current shaping. In the past few years, research efforts have focused on single-stage multilevel topologies as a low-cost AC-DC stage for AC-DC power supply. Multi-level converters produce more voltage levels decreasing the voltage and current harmonics significantly while operating at lower switching frequency. In this project we are planning to design and build multi-level PFC power converter which have following ratings; * 3.7 kW power rating * Si-based high efficiency (>99%) * high power density (>85 W/in3) * bi-directional power flow capability for various applications such as electric vehicle (EV) battery charger and DC home applications. ![pfc1](/PFC.png) ![pfc1](/PFC2.jpg)
Python
UTF-8
293
3.15625
3
[]
no_license
S = input() #문장 N = len(S) #문장 길이 a = [0,0] #연속된 값 갯수 a_indx = 0 # for i in range(N-1) : if S[i] == S[i+1] : a[a_indx] += 1 else : a_indx = 1 - a_indx print(min(a))
JavaScript
UTF-8
1,691
3.328125
3
[]
no_license
function createMenuItem (name, price, description) { const menuItem = document.createElement('div'); menuItem.classList.add('menu-item'); const itemName = document.createElement('h3'); itemName.textContent = name; itemName.classList.add('menu-item-name'); const itemPrice = document.createElement('h3'); itemPrice.textContent = `£${price}` itemPrice.classList.add('menu-item-price'); const itemDescription = document.createElement('p'); itemDescription.textContent = description; itemDescription.classList.add('menu-item-description'); menuItem.appendChild(itemName); menuItem.appendChild(itemPrice); menuItem.appendChild(itemDescription); return menuItem; } function createMenu () { const menu = document.createElement('div'); menu.classList.add('menu'); const menuItems = [ createMenuItem( 'Space Pie', '3.99', 'The tastiest pie in space' ), createMenuItem( 'Old Pie', '7.99', 'An old pie we found' ), createMenuItem( 'Cheese pie', '300.99', 'Made with the last known piece of cheese in the western hemisphere' ), createMenuItem( 'Treacle Pie', '7.00', 'Sticky. Very sticky. Stuck right now actually, maybe you can\'t order it' ) ] menuItems.forEach(item => { menu.appendChild(item); }); return menu; } const loadMenu = () => { const main = document.getElementById('main'); main.textContent = ""; main.appendChild(createMenu()); } export { loadMenu }
Java
UTF-8
292
3.15625
3
[]
no_license
public class Sunflower extends Plant { //コンストラクタ public Sunflower(String name, String color){ super(name, color); } //実装メソッド public void live(){ System.out.println(this.name + "は太陽の方向を向いて光合成をして生きる"); } }
Shell
UTF-8
4,655
3.65625
4
[]
no_license
#!/bin/bash function usage { cat <<EOF Usage: kubectl switch -m <MODE> [-s <SERVICES>(postgres | odoo)] -n <NAMESPACE> Options: -m <MODE> # Mode of execution (ON/OFF) activate or deactivate the environment of test -s <SERVICES> # Concrete service to activate or deactivate -n <NAMESPACE> # Namespace that we want modify EOF exit 2 } #set -x function scaler () { MODE=$1 SERVICE=$2 NAMESPACE=$3 environments=$4 on_off_env=$5 if [[ $(echo "$environments" | wc -c) != 1 && $MODE == on ]]; then for env in $environments ; do sleep 2 if [[ $(echo "$env" | cut -d , -f 2) == 0 && $(echo "$SERVICE") == 'ALL' ]]; then echo "Activating $(echo $env | cut -d , -f 1 | cut -d / -f 2) of the namespace $NAMESPACE" kubectl scale $(echo "$env" | cut -d , -f 1) --replicas=1 -n $NAMESPACE scale='true' elif [[ $(echo "$env" | cut -d , -f 2) == 0 && $( echo "$env" | cut -d , -f 1 | grep -o "$SERVICE") == $(echo "$SERVICE") ]]; then echo "Activating $(echo $env | cut -d , -f 1 | cut -d / -f 2) of the namespace $NAMESPACE" kubectl scale $(echo "$env" | cut -d , -f 1) --replicas=1 -n $NAMESPACE scale='true' elif [[ $(echo "$environments" | grep -o "$SERVICE") != $(echo "$SERVICE") && $scale != 'not_exist' && $(echo "$SERVICE") != 'ALL' ]]; then echo "The service indicated is not exist, please indicate the name correctly or not indicate the option -s for activate all services" scale='not_exist' elif [[ $(echo "$env" | cut -d , -f 2) == 1 && $( echo "$env" | cut -d , -f 1 | grep -o "$SERVICE") == $(echo "$SERVICE") ]] || [[ $(echo "$env" | cut -d , -f 2) == 1 && $(echo "$SERVICE") == 'ALL' && $scale != 'up' ]]; then echo "Error, it is not can activate the environment because already is activate" scale='up' else : fi sleep 2 done elif [[ $(echo "$environments" | wc -c) != 1 && $MODE == off ]]; then for env in $environments ; do sleep 2 if [[ $(echo "$env" | cut -d , -f 2) == 1 && $(echo "$SERVICE") == 'ALL' ]]; then echo "Desactivating $(echo $env | cut -d , -f 1 | cut -d / -f 2) of the namespace $NAMESPACE" kubectl scale $(echo "$env" | cut -d , -f 1) --replicas=0 -n $NAMESPACE scale='true' elif [[ $(echo "$env" | cut -d , -f 2) == 1 && $( echo "$env" | cut -d , -f 1 | grep -o "$SERVICE") == $(echo "$SERVICE") ]]; then echo "Desactivating $(echo $env | cut -d , -f 1 | cut -d / -f 2) of the namespace $NAMESPACE" kubectl scale $(echo "$env" | cut -d , -f 1) --replicas=0 -n $NAMESPACE scale='true' elif [[ $(echo "$environments" | grep -o "$SERVICE") != $(echo "$SERVICE") && $scale != 'not_exist' && $(echo "$SERVICE") != 'ALL' ]]; then echo "The service indicated is not exist, please indicate the name correctly or not indicate the option -s for activate all services" scale='not_exist' elif [[ $(echo "$env" | cut -d , -f 2) == 0 && $( echo "$env" | cut -d , -f 1 | grep -o "$SERVICE") == $(echo "$SERVICE") ]] || [[ $(echo "$env" | cut -d , -f 2) == 1 && $(echo "$SERVICE") == 'ALL' && $scale != 'down' ]]; then echo "Error, it is not can deactivate the environment because already is deactivate" scale='down' else : fi done else on_off_env=$((on_off_env + 1)) return $on_off_env fi } SERVICE='ALL' if [[ $# -eq 0 ]]; then usage else while getopts ":hm:s:hn:h:" OPTIONS; do case "${OPTIONS}" in m) MODE=${OPTARG} ;; s) SERVICE=${OPTARG} ;; n) NAMESPACE=${OPTARG} ;; h) usage ;; *) usage ;; esac done fi on_off_env='0' check_namespace=$(kubectl get namespace $NAMESPACE 2>&1) find_namespace=$(echo $check_namespace | echo $?) if [[ $find_namespace == 0 ]]; then #all_components=$(kubectl get rc,deploy -n $NAMESPACE) all_components=$(kubectl get rc,deploy -n $NAMESPACE -o custom-columns=TYPE:.kind,NAME:.metadata.name,DESIRED:.spec.replicas \ | grep -v TYPE | awk '{end = $1"/"$2","$3; print tolower(end)}') #rcs=$(echo "$all_components" | grep 'replicationcontroller' | tr -s ' ' ',' | cut -d , -f 1-2) rcs=$(echo "$all_components" | grep 'replicationcontroller') scaler "$MODE" "$SERVICE" "$NAMESPACE" "$rcs" "$on_off_env" on_off_env=$? #deployments=$(echo "$all_components" | grep 'deployment' | tr -s ' ' ',' | cut -d , -f 1-2) deployments=$(echo "$all_components" | grep 'deployment') scaler "$MODE" "$SERVICE" "$NAMESPACE" "$deployments" "$on_off_env" on_off_env=$? if [[ $scale == 'true' ]]; then echo "Changes Finished" elif [[ $on_off_env == '2' ]]; then echo "Please, indicate the option of mode in 'on' or 'off' and check that the namespace exist" else : fi else echo "Error, the namespace indicated is not exist" fi
C#
UTF-8
2,706
3.4375
3
[]
no_license
using System; namespace Lists { class MainClass { public static void Main() { MyListObject<int> myList = new MyListObject<int>(); //Appending Console.WriteLine("Appending:"); Console.WriteLine($"list: {myList.GetString()}, length: {myList.Count}"); myList.Append(1); Console.WriteLine($"list: {myList.GetString()}, length: {myList.Count}"); myList.Append(2); myList.Append(3); Console.WriteLine($"list: {myList.GetString()}, length: {myList.Count}"); myList.Append(4); myList.Append(5); myList.Append(6); myList.Append(7); Console.WriteLine($"list: {myList.GetString()}, length: {myList.Count}"); Console.WriteLine(); //Reverting myList.Revert(); Console.WriteLine("Reverting:"); Console.WriteLine($"list: {myList.GetString()}, length: {myList.Count}"); Console.WriteLine(); //Get item Console.WriteLine("Indexing:"); int index = 1; Console.WriteLine($"Geting item index {index}:"); Console.WriteLine($"Vale: {myList.Get(index)}"); index = 10; try { Console.WriteLine($"Geting item index {index}:"); Console.WriteLine($"Vale: {myList.Get(index)}"); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine(); //Remove item index = 3; myList.Remove(index); Console.WriteLine($"Removing item index {index}:"); Console.WriteLine($"list: {myList.GetString()}, length: {myList.Count}"); index = 0; myList.Remove(index); Console.WriteLine($"Removing item index {index}:"); Console.WriteLine($"list: {myList.GetString()}, length: {myList.Count}"); index = myList.Count - 1; myList.Remove(index); Console.WriteLine($"Removing item index {index}:"); Console.WriteLine($"list: {myList.GetString()}, length: {myList.Count}"); index = 5; //Out of range myList.Remove(index); Console.WriteLine($"Removing item index {index}:"); Console.WriteLine($"list: {myList.GetString()}, length: {myList.Count}"); Console.WriteLine(); //Revert myList.Revert(); Console.WriteLine("Reverting:"); Console.WriteLine($"list: {myList.GetString()}, length: {myList.Count}"); } } }
PHP
UTF-8
205
2.609375
3
[]
no_license
<?php class Controller { public function CreateView($viewName) { require "View/" . $viewName . ".php"; } public function isLogined() { return !empty($_SESSION['id']); } }
Java
UTF-8
1,974
2.109375
2
[]
no_license
package com.pureland.common.db.data; import java.util.List; import com.pureland.common.enums.Entity; import com.pureland.common.util.DataObject; public class User extends DataObject { private static final long serialVersionUID = 8799515651436886728L; private Long id; private String account; private String passwd; private String telephone; private String email; private List<UserRace> userRaces; public static String generatorIdKey(String singleMark) { return generatorIdKey(Entity.USER, Entity.User.ID.getName(), singleMark); } public static String generatorFieldKey(Long id, String field) { return generatorFieldKey(Entity.USER, id, field); } /** * @return the id */ public Long getId() { return id; } /** * @param id * the id to set */ public void setId(Long id) { this.id = id; } /** * @return the account */ public String getAccount() { return account; } /** * @param account * the account to set */ public void setAccount(String account) { this.account = account; } /** * @return the passwd */ public String getPasswd() { return passwd; } /** * @param passwd * the passwd to set */ public void setPasswd(String passwd) { this.passwd = passwd; } /** * @return the telephone */ public String getTelephone() { return telephone; } /** * @param telephone * the telephone to set */ public void setTelephone(String telephone) { this.telephone = telephone; } /** * @return the email */ public String getEmail() { return email; } /** * @param email * the email to set */ public void setEmail(String email) { this.email = email; } /** * @return the userRaces */ public List<UserRace> getUserRaces() { return userRaces; } /** * @param userRaces * the userRaces to set */ public void setUserRaces(List<UserRace> userRaces) { this.userRaces = userRaces; } }
Markdown
UTF-8
1,497
3.640625
4
[]
no_license
# A command-line node.js word guess game # Requires * npm install - dependencies: random-words and inquirer * word.js requires letter.js * index.js requires word.js # Functionality * Game starts with "node index" from the console * Presents with underscore in place of secret word * User is allowed 10 guesses to guess the secret word * When a correct letter is guessed, it is shown in the console in the context of the letters that have not been guessed * If the word is not guessed in ten guesses, the player loses the game and is prompted to play another * If the word is guessed, the user is prompted to play another game * Wins and losses are tracked * The user is presented with a list of all the letters guessed after each guess # Program Structure * Three files 1. letter.js * Constructor which contains the underlying letter, boolean "corr" to indicate if that letter has been guessed, a function to write an underscore or a letter based on second attribute, a function which accepts a letter parameter which changes the second attribute if it matches the first 2. word.js * Constructor which contains an array of letter objects, a function to show an entire word with guessed letters shown and unguessed letters with an underscore, a function which calls the method in letter.js which changes the "corr" attribute for each letter of the word, and a function which checks if the word has been guessed yet 3. index.js * Game logic including user interface from inquirer calls # Enjoy!
C#
UTF-8
820
3.90625
4
[ "MIT" ]
permissive
using System; using System.Linq; namespace _03._Count_Uppercase_Words { class Program { static void Main(string[] args) { //string[] text = Console.ReadLine().Split(); //foreach (var word in text) //{ // // if (Char.IsUpper(ch)) // { // Console.WriteLine(word); // continue; // } // //} Func<string, bool> filterUppercase = s => Char.IsUpper(s[0]); Console.ReadLine() .Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries) .Where(filterUppercase) .ToList() .ForEach(w => Console.WriteLine(w)); } } }
C++
UTF-8
1,201
2.96875
3
[]
no_license
#include "myClockHand.h" myClockHand::myClockHand() { this->angle = 0; } void myClockHand::draw() { //// back face //glBegin(GL_POLYGON); // glNormal3f(0,0,-1); // glVertex3f(-0.1,0,-0.1); // glVertex3f(0,1,0); // glVertex3f(0.1,0,-0.1); //glEnd(); //// bottom face //glBegin(GL_POLYGON); // glNormal3f(0,-1,0); // glVertex3f(-0.1,0,0.1); // glVertex3f(-0.1,0,-0.1); // glVertex3f(0.1,0,-0.1); // glVertex3f(0.1,0,0.1); //glEnd(); //// right face //glBegin(GL_POLYGON); // glNormal3f(1,0.1,0); // glVertex3f(0.1,0,-0.1); // glVertex3f(0,1,0); // glVertex3f(0.1,0,0.1); //glEnd(); //// left face //glBegin(GL_POLYGON); // glNormal3f(-1,0.1,0); // glVertex3f(-0.1,0,0.1); // glVertex3f(0,1,0); // glVertex3f(-0.1,0,-0.1); //glEnd(); // front face glBegin(GL_POLYGON); glNormal3f(0,0,1); glVertex3f(0.1,0,0); glVertex3f(0,1,0); glVertex3f(-0.1,0,0); glEnd(); glPopMatrix(); } void myClockHand::setAngle(double angle) { this->angle = angle; } void myClockHand::incrementAngle() { if(angle == 359) angle = 0; else angle++; } double myClockHand::getAngle() { return this->angle; } void myClockHand::add(double angle) { this->angle += angle; }
C#
UTF-8
3,933
2.6875
3
[ "Apache-2.0" ]
permissive
#region Copyright & License // Copyright © 2012 - 2021 François Chabot // // 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. #endregion using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; namespace Be.Stateless.IO { /// <summary> /// Transform an <see cref="IEnumerable{T}"/> of either <see cref="string"/>s or arrays of <see cref="byte"/>s into a /// readonly, non-seekable <see cref="Stream"/> of <see cref="byte"/>s. /// </summary> /// <remarks> /// When <see cref="string"/>s are used as the underlying type of the <see cref="IEnumerable{T}"/>, the <see /// cref="Encoding.Unicode"/> encoding is assumed to convert them to <see cref="byte"/>s. /// </remarks> [SuppressMessage("ReSharper", "UnusedType.Global", Justification = "Public API.")] public class EnumerableStream : Stream { /// <summary> /// Transform an <see cref="IEnumerable{T}"/> of arrays of <see cref="byte"/>s into a <see cref="Stream"/>. /// </summary> /// <param name="enumerable"> /// The <see cref="IEnumerable{T}"/> over the arrays of <see cref="byte"/>s. /// </param> [SuppressMessage("ReSharper", "MemberCanBePrivate.Global", Justification = "Public API.")] public EnumerableStream(IEnumerable<byte[]> enumerable) { if (enumerable == null) throw new ArgumentNullException(nameof(enumerable)); _enumerator = enumerable.GetEnumerator(); } /// <summary> /// Transform an <see cref="IEnumerable{T}"/> of <see cref="string"/>s into a <see cref="Stream"/>. /// </summary> /// <param name="enumerable"> /// The <see cref="IEnumerable{T}"/> over the <see cref="string"/>s. /// </param> /// <remarks> /// The <see cref="Encoding.Unicode"/> encoding will be assumed to transform the <see cref="string"/>s into their /// <see cref="byte"/> equivalent. /// </remarks> [SuppressMessage("ReSharper", "MemberCanBeProtected.Global", Justification = "Public API.")] public EnumerableStream(IEnumerable<string> enumerable) : this(enumerable.Select(s => Encoding.Unicode.GetBytes(s))) { } #region Base Class Member Overrides public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => false; public override void Flush() { throw new NotSupportedException(); } public override long Length => throw new NotSupportedException(); public override long Position { get => _position; set => throw new NotSupportedException(); } public override int Read(byte[] buffer, int offset, int count) { var bufferController = new BufferController(buffer, offset, count); // try to exhaust backlog if any while keeping any extra of it _backlog = bufferController.Append(_backlog); while (bufferController.Availability > 0 && _enumerator.MoveNext()) { _backlog = bufferController.Append(_enumerator.Current); } _position += bufferController.Count; return bufferController.Count; } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } #endregion private readonly IEnumerator<byte[]> _enumerator; private byte[] _backlog; private int _position; } }
PHP
UTF-8
1,268
2.578125
3
[ "MIT" ]
permissive
<?php namespace App\Entity; use App\Repository\ProduitsRepository; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=ProduitsRepository::class) */ class Produits { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) */ private $nom_generique; /** * @ORM\Column(type="string", length=255) */ private $forme; /** * @ORM\Column(type="string", length=255) */ private $dose; public function getId(): ?int { return $this->id; } public function getNomGenerique(): ?string { return $this->nom_generique; } public function setNomGenerique(string $nom_generique): self { $this->nom_generique = $nom_generique; return $this; } public function getForme(): ?string { return $this->forme; } public function setForme(string $forme): self { $this->forme = $forme; return $this; } public function getDose(): ?string { return $this->dose; } public function setDose(string $dose): self { $this->dose = $dose; return $this; } }
Python
UTF-8
1,497
3.125
3
[]
no_license
# import csv # import sys # # with open('output_gsmarena_clean.csv') as csvfile: # readCSV = csv.reader(csvfile, delimiter='|') # dates = [] # colors = [] # i = 0 # for row in readCSV: # if (i == 0): # print(row) # else: # sys.exit(1) # i = i + 1; # color = row[3] # date = row[0] # # dates.append(date) # colors.append(color) # print(dates) # print(colors) # !/usr/bin/env python import csv import re import sys import pprint # Function to convert a csv file to a list of dictionaries. Takes in one variable called "variables_file" def csv_dict_list(variables_file): # Open variable-based csv, iterate over the rows and map values to a list of dictionaries containing key/value pairs reader = csv.DictReader(open(variables_file, 'rb'), delimiter='|') dict_list = [] for line in reader: dict_list.append(line) return dict_list # Calls the csv_dict_list function, passing the named csv device_values = csv_dict_list('output_gsmarena_clean.csv') # Prints the results nice and pretty like total_rows = 0 for row in device_values: if (total_rows < 10): #print(row['os']) #print(re.search('v[0-9]',row['os']).group(0)) print(re.sub(',[ ()a-zA-Z0-9.]*','',row['os'])) #print(re.sub(' [a-zA-Z0-9]*','',row['DeviceName'])) # replace spasi+(huruf/angka yg ada isinya atau lebih) total_rows = total_rows + 1
C#
UTF-8
2,772
2.578125
3
[ "MIT" ]
permissive
#r "Microsoft.WindowsAzure.Storage" using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; using Newtonsoft.Json; using System; using System.Collections.Generic; class AnalyzeTweetsTable { public enum AnalyzeType { Picture = 0, Text = 1 } public class AnalyzeTweetsStats { [JsonProperty(PropertyName = "totalText")] public int TotalText { get; set; } [JsonProperty(PropertyName = "totalPicture")] public int TotalPicture { get; set; } [JsonProperty(PropertyName = "text")] public Dictionary<string, int> Text { get; private set; } [JsonProperty(PropertyName = "picture")] public Dictionary<string, int> Picture { get; private set; } public AnalyzeTweetsStats() { Text = new Dictionary<string, int>(); Picture = new Dictionary<string, int>(); } } class AnalyzeTweets : TableEntity { public string Type { get; set; } public string Text { get; set; } public AnalyzeTweets(string type, string text) { PartitionKey = "AnalyzeTweets"; RowKey = Guid.NewGuid().ToString(); Timestamp = DateTime.Now; Type = type.ToLowerInvariant(); Text = text; } public AnalyzeTweets() { } } private CloudTable table; public AnalyzeTweetsTable(string connectionString) { var account = CloudStorageAccount.Parse(connectionString); var client = account.CreateCloudTableClient(); table = client.GetTableReference("AnalyzeTweets"); } public void Add(string type, string text) { if (!type.Equals("text", StringComparison.OrdinalIgnoreCase) && !type.Equals("image", StringComparison.OrdinalIgnoreCase)) { return; } var newInfo = new AnalyzeTweets(type, text); var insert = TableOperation.Insert(newInfo); table.Execute(insert); } public AnalyzeTweetsStats GetStats() { var query = new TableQuery<AnalyzeTweets>(); var stats = new AnalyzeTweetsStats(); foreach (var info in table.ExecuteQuery(query)) { if (info.Type.Equals("text", StringComparison.OrdinalIgnoreCase)) { stats.TotalText++; if (!stats.Text.ContainsKey(info.Text)) stats.Text[info.Text] = 0; stats.Text[info.Text]++; } else { stats.TotalPicture++; if (!stats.Picture.ContainsKey(info.Text)) stats.Picture[info.Text] = 0; stats.Picture[info.Text]++; } } return stats; } }
C++
UTF-8
2,961
4.40625
4
[]
no_license
#include <iostream> #include <vector> /* Operator Overloading cannot access Private Data Members, we can access it through Public function so, we use Friend Function */ class User { std::string status = "Gold"; static int user_count; public: static int get_user_count() { return user_count; } std::string first_name; std::string last_name; std::string get_status() { return status; } void set_status(std::string status) { if(status == "Gold" || status == "Silver" || status == "Bronze") { this->status = status; } else { this->status = "Undetermined Status"; } } User() { user_count++; } User(std::string first_name, std::string last_name) { this->first_name = first_name; this->last_name = last_name; user_count++; } User(std::string first_name, std::string last_name, std::string status) { this->first_name = first_name; this->last_name = last_name; this->status = status; user_count++; } ~User() { user_count--; } friend void output_status(User user); // Stupid Example :)) // NOTE: friend function can access the private data member of the class; ************** // NOTE: it is better to access the private data member through getter or setter. friend std::istream& operator >> (std::istream& input, User &user) ; friend std::ostream& operator << (std::ostream& output, const User user) ; }; void output_status(User user) { std::cout << user.status << std::endl; } int User::user_count = 0; std::ostream& operator << (std::ostream& output, const User user) { //output << "First name: " << user.first_name <<"\nLast name: " << user.last_name; // NOTE: we can access Private Data Members now. output << "First name: " << user.first_name <<"\nLast name: " << user.last_name << "\nStatus: " << user.status; return output; } std::istream& operator >> (std::istream& input, User &user) { //input >> user.first_name >> user.last_name; // NOTE: we cannot access the private part. we must access Private Data Members throught public function.****************** input >> user.first_name >> user.last_name >> user.status; // NOTE: we can access Private Data Members now. return input; } int main() { User user; // Stupid Example output_status(user); // Gold : default value user.first_name = "Caleb"; user.last_name = "Curry"; user.set_status("Gold"); // Output std::cout << user << std::endl; // Input std::cin >> user; std::cout << user << std::endl; }
C++
UTF-8
1,993
3.296875
3
[]
no_license
#include <stdio.h> #include <sys/time.h> #include <iostream> void timeval_normalize(struct timeval &tv, time_t sec, suseconds_t us) { constexpr suseconds_t max_tv_usec {999999}; if(sec < 0) { sec = 0; us = 0; std::cerr << __func__ << " negative time input (sec)\n"; } else { if(us < 0) { sec = 0; us = 0; std::cerr << __func__ << " negative time input (usec)\n"; } else if(us > max_tv_usec) { constexpr suseconds_t _1sec_in_tv_usec {1000000}; const time_t s {us / _1sec_in_tv_usec}; sec += s; us = us - s * _1sec_in_tv_usec; } } tv.tv_sec = sec; tv.tv_usec = us; } void print_timeval(struct timeval &t) { printf("tv_sec : %ld\n", t.tv_sec); printf("tv_usec: %d\n", t.tv_usec); } void test_timeval_normailize(time_t s, suseconds_t us) { printf("Non-normalized sec.us: %ld.%d\n", s, us); struct timeval t; timeval_normalize(t, s, us); print_timeval(t); } int main(int argc, char *argv[]) { test_timeval_normailize(-1, 999); test_timeval_normailize(-1, -1); test_timeval_normailize(0, 0); test_timeval_normailize(0, 999999); test_timeval_normailize(0, 1000000); test_timeval_normailize(0, 4000000); test_timeval_normailize(0, 1000000000); test_timeval_normailize(0, 2000); test_timeval_normailize(-1, 999); test_timeval_normailize(-1, -1); test_timeval_normailize(4, 0); test_timeval_normailize(3, 999999); test_timeval_normailize(6, 1000000); test_timeval_normailize(7, 4000000); test_timeval_normailize(8, 1000000000); test_timeval_normailize(1000, 2000); return 0; }
Java
UTF-8
247
1.96875
2
[]
no_license
package junit.suitMathTest; import org.junit.Assert; import org.junit.Test; public class MathTest2 extends Assert { @Test public void testSqrt() { assertTrue(Math.sqrt(1) == 1); assertTrue(Math.sqrt(1000000) == 1000); } }
C#
UTF-8
4,405
2.53125
3
[ "Apache-2.0" ]
permissive
using System; using System.Data; using System.Collections; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using System.Drawing; using System.Drawing.Imaging; using Aspose.Cells; using Aspose.Cells.Drawing; using System.IO; using QM.Core.Exception; using QM.Core.Files; namespace QM.Core.Excel { /// <summary> /// EXCEL Asponse操作类 /// </summary> public class QMExcelAsponse { /// <summary> /// DataTable导出Excel /// </summary> /// <param name="dt">DataTable数据源</param> /// <param name="filepath">导出路径</param> /// <param name="error">错误信息</param> /// <returns></returns> public bool DataTableToExcel(DataTable dt, string filepath, out string error) { bool result = false; int iRow = 0; error = ""; try { if (dt == null) { error = "QMExcel->DataTableToExcel:dt为空"; return result; } new License().SetLicense("Aspose.Cells.lic"); //创建工作薄 Workbook workbook = new Workbook(); //为单元格添加样式 Style style = workbook.CreateStyle(); //设置单元格式居中 style.HorizontalAlignment = TextAlignmentType.Center; //设置背景颜色 style.ForegroundColor = Color.FromArgb(205, 205, 222); style.Pattern = BackgroundType.Solid; style.Font.IsBold = true; //创建工作表 Worksheet worksheet = workbook.Worksheets[0]; Cells cells = worksheet.Cells; //列名 for (int i = 0; i < dt.Columns.Count; i++) { DataColumn col = dt.Columns[i]; string columnName = col.Caption ?? col.ColumnName; workbook.Worksheets[0].Cells[iRow, i].PutValue(columnName); workbook.Worksheets[0].Cells[iRow, i].SetStyle(style); } iRow++; //行值 foreach (DataRow dr in dt.Rows) { for (int i = 0; i < dt.Columns.Count; i++) { workbook.Worksheets[0].Cells[iRow, i].PutValue(dr[i].ToString()); } iRow++; } //自适应列宽 for (int i = 0; i < dt.Columns.Count; i++) { workbook.Worksheets[0].AutoFitColumn(i, 0, 150); } workbook.Worksheets[0].FreezePanes(1, 0, 1, dt.Columns.Count); workbook.Save(filepath); result = true; } catch (QMException ex) { error = ex.Message; throw ex; } return result; } /// <summary> /// Excel导入DataTable /// </summary> /// <param name="filepath">文件路径</param> /// <param name="dt">DataTable</param> /// <param name="error"></param> /// <returns></returns> public bool ExcelToDataTable(string filepath, out DataTable dt, out string error) { bool result = false; dt = null; error = ""; try { if (QMFile.FileExists(filepath) == false) { error = "QMExcel->ExcelToDataTable:filepath文件不存在"; return result; } Workbook workbook = new Workbook(filepath); Worksheet worksheet = workbook.Worksheets[0]; dt = worksheet.Cells.ExportDataTable(0, 0, worksheet.Cells.MaxRow + 1, worksheet.Cells.MaxColumn + 1); result = true; } catch (QMException ex) { error = ex.Message; throw ex; } return result; } } }
PHP
UTF-8
6,192
3.28125
3
[]
no_license
<?php class menu_builder { private $current_item; private $menu_items; private $menu; private $post_id; /** * Construct the object by supplying required parameters. */ public function __construct($params) { $this->set_post_id( $params['post_id'] ); $this->set_menu_items( $params['menu_items'] ); $this->set_current_item( $params['post_id']); } /** * Sets the post_id variable */ public function set_post_id($post_id) { $this->post_id = $post_id; } /** * Sets the item data that will be used to build the menu. */ public function set_menu_items($menu_items) { $this->menu_items = $menu_items; } /** * Uses the supplied object id to set the current menu item. */ public function set_current_item($object_id) { foreach ($this->menu_items as $item) { if ($item->object_id == $object_id && $item->post_title == "") { $this->current_item = $item; return; } if ($item->object_id == $object_id) { $this->current_item = $item; return; } } } /** * Determine if current item has an associated menu to build. */ public function has_menu() { $post_id = $this->post_id; $in_menu = false; foreach ($this->menu_items as $item) { if ($item->object_id == $post_id) { if ($item->menu_item_parent != 0) { return true; } else { $in_menu = true; $menu_id = $item->ID; } } } if ($in_menu) { foreach ($this->menu_items as $item) { if ($item->menu_item_parent == $menu_id) { return true; } } } return false; } /** * Invokes the menu building algorithm. */ public function build() { $this->menu = $this->process_menu($this->current_item); return $this->menu; } /** * Recursively builds a hierarchical menu from the inside-out, * starting with the current item, and working towards the root parent. * * * The finished menu will show the following: * a) All immediate children of the current menu item ($current_item) * * b) All immediate children of the current item's parent, grandparent, * great-grandparent, and so on, until we eventually reach the root parent. * * * Here are the steps involved in the algorithm: * * 1) Create the current menu. This is an array with distinct keys for its elements. * * 2) If a child menu was passed into the function call, merge it into the current menu. * This is how the nested menu structures are created. * * 3) If the current menu item has a parent, recurse another level deeper ("outward"). * Each parent menu wraps its child menu, until eventually we arrive at the root parent. * * 4) At the root parent level, the final menu is returned back to its invoking function, * eventually being passed back out to the original (external) invoking function. * */ private function process_menu($item, $child_menu = null) { $menu['self'] = $item; $children = $this->get_immediate_children($item); if (count($children)) { $menu['children'] = $children; } if ($child_menu) { $menu = $this->merge_child_menu($menu, $child_menu); } if (isset($item->menu_item_parent)) { if ($item->menu_item_parent != 0) { $parent_item = $this->get_parent($item); $menu = $this->process_menu($parent_item, $menu); } } return $menu; } /** * Get all the immediate children (not nested children) for the supplied parent item. */ private function get_immediate_children($parent_item) { $children = array(); foreach ($this->menu_items as $item) { if (isset($item->menu_item_parent) && isset($parent_item->ID)) { if ($item->menu_item_parent == $parent_item->ID) { $children[] = array('self' => $item); } } } return $children; } /** * Get the parent item for the supplied item. */ private function get_parent($item) { foreach ($this->menu_items as $parent_item) { if ($parent_item->ID == $item->menu_item_parent) { return $parent_item; } } } /** * Merge a child menu into a parent menu by matching the child to one of * the parent's children. This creates and returns a nested menu structure. */ private function merge_child_menu($menu, $child_menu) { foreach ($menu['children'] as &$child) { if ($child['self']->ID == $child_menu['self']->ID) { $child = $child_menu; return $menu; } } } public function to_html($menu = null, $level = 1, $html = null) { /* Did we pass in a menu? If not, we'll use the menu generated by build() as our default */ if (!$menu) { $menu = $this->menu; } /* This is the item object at our current level within the menu */ $item = $menu['self']; /* Here are the different conditions that affect our class names */ $is_parent = isset($menu['children']); $is_active = $item->object_id == $this->current_item->object_id; $is_child = $item->menu_item_parent != 0; /* Do some stuff with the above item object and conditions to build an html snippet */ if (($is_parent)&&($level==1)) { $html .= '<ul class="subnav"><li class="root-parent'; } elseif ($is_parent) { $html .= '<li class="parent'; if ($is_child) $html .= ' level-' . $level; } elseif ($is_child) { $html .= '<li class="child level-' . $level; } else { return false; } if ($is_active) { $html .= ' active"><a href="' . $item->url . '">' . $item->title . '</a></li>'; } else { $html .= '"><a href="' . $item->url . '">' . $item->title . '</a></li>'; } /* If the item we're looking at is a parent, deal with its children */ if ($is_parent && is_array($menu['children'])) { $html .='<li class="children level-' . $level . '"><ul class="children level-' . $level . '">'; foreach ($menu['children'] as $child) { //recursion //Handle the children in the same way we handle the parents... by calling to_html() $html .= $this->to_html($child, $level+1); } $html .='</ul></li>'; } return $html; } }
Shell
UTF-8
347
3.265625
3
[]
no_license
#!/usr/bin/bash read -p "enter the no of array1 elements" n for (( i=0; i<n; i++ )) do read -p "enter element:" val arr[$i]=$val done read -p "enter the no of array2 elements" n for (( i=0; i<n; i++ )) do read -p "enter element:" val arr1[$i]=$val done echo "merged array is:" for (( i=0; i<n; i++ )) do echo "${arr[$i]} ${arr1[$i]}" done
Java
UTF-8
1,204
3.078125
3
[]
no_license
package com.wd.tst; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import com.wd.file.FileUtil; public class Tst1 { public static void main(String[] args) { File file = new File("data/1.txt"); StringBuilder sb = new StringBuilder(""); String ret = read(file); //System.out.println(ret); sb.append(ret); String data = sb.toString(); //data = data.replaceAll("GET", "\\\\r\\\\nGET"); System.out.println(data); } public static String read(File file) { BufferedReader bufferedReader = null; StringBuilder sb = new StringBuilder(""); try { if (file.isFile() && file.exists()) { // 判断文件是否存在 bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8")); String lineTxt = null; while ((lineTxt = bufferedReader.readLine()) != null) { sb.append(lineTxt); // System.out.println(lineTxt); } } } catch (IOException e) { e.printStackTrace(); } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { } } } return sb.toString(); } }
Java
UTF-8
5,015
1.648438
2
[]
no_license
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.ndcwebservices.controllers; import de.hybris.platform.commerceservices.enums.SalesApplication; import de.hybris.platform.ndcfacades.constants.NdcfacadesConstants; import de.hybris.platform.ndcfacades.ndc.ErrorsType; import de.hybris.platform.ndcfacades.ndc.ServiceListRQ; import de.hybris.platform.ndcfacades.ndc.ServiceListRS; import de.hybris.platform.ndcfacades.servicelist.ServiceListFacade; import de.hybris.platform.ndcwebservices.constants.Ndc171webservicesConstants; import de.hybris.platform.ndcwebservices.constants.NdcwebservicesConstants; import de.hybris.platform.ndcwebservices.validators.ServiceListRQValidator; import de.hybris.platform.ndcwebservices.validators.ServiceListRSValidator; import de.hybris.platform.servicelayer.dto.converter.ConversionException; import de.hybris.platform.servicelayer.exceptions.ModelNotFoundException; import de.hybris.platform.servicelayer.session.SessionService; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.springframework.context.annotation.Scope; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; /** * Controller for ServiceListRQ */ @Controller @Scope("request") @RequestMapping(value = "/v171/servicelist") public class ServiceListController extends NDCAbstractController { private static final Logger LOG = Logger.getLogger(ServiceListController.class); @Resource(name = "serviceListRQValidator") private ServiceListRQValidator serviceListRQValidator; @Resource(name = "serviceListRSValidator") private ServiceListRSValidator serviceListRSValidator; @Resource(name = "serviceListFacade") private ServiceListFacade serviceListFacade; @Resource(name = "sessionService") private SessionService sessionService; @RequestMapping(method = RequestMethod.POST) @ResponseBody @Secured({ "ROLE_TRAVELAGENCYGROUP" }) public ServiceListRS handleRequest(@RequestBody final ServiceListRQ serviceListRQ) { ServiceListRS serviceListRS = new ServiceListRS(); final ErrorsType errorsType = new ErrorsType(); if (!serviceListRQValidator.validateServiceListRQ(serviceListRQ, serviceListRS)) { serviceListRS.setVersion(NdcwebservicesConstants.NDC_VERSION); return serviceListRS; } try { sessionService.setAttribute(Ndc171webservicesConstants.SESSION_SALES_APPLICATION, SalesApplication.NDC); serviceListRS = serviceListFacade.getServiceList(serviceListRQ); serviceListRS.setVersion(NdcwebservicesConstants.NDC_VERSION); if (!serviceListRSValidator.validateServiceListRS(serviceListRS)) { final ServiceListRS serviceListRSError = new ServiceListRS(); serviceListRSError.setErrors(serviceListRS.getErrors()); return serviceListRSError; } } catch (final ConversionException conversionException) { if (StringUtils.isEmpty(conversionException.getMessage())) { final String offerUnavailableMsg = configurationService.getConfiguration() .getString(NdcfacadesConstants.SERVICE_UNAVAILABLE); addError(errorsType, offerUnavailableMsg); } else { addError(errorsType, conversionException.getMessage()); } LOG.warn(conversionException.getMessage()); LOG.debug(conversionException); serviceListRS.setErrors(errorsType); } catch (final ModelNotFoundException e) { LOG.error(configurationService.getConfiguration().getString(NdcwebservicesConstants.GENERIC_ERROR), e); final String invalidSegmentKeyMsg = configurationService.getConfiguration() .getString(NdcfacadesConstants.SERVICE_UNAVAILABLE); final String invalidODKeyMsg = configurationService.getConfiguration() .getString(NdcfacadesConstants.INVALID_ORIGIN_DESTINATION_KEY); if (StringUtils.equals(e.getMessage(), invalidSegmentKeyMsg)) { addError(errorsType, invalidSegmentKeyMsg); } else if (StringUtils.equals(e.getMessage(), invalidODKeyMsg)) { addError(errorsType, invalidODKeyMsg); } serviceListRS.setErrors(errorsType); } catch (final Exception e) { LOG.error(configurationService.getConfiguration().getString(NdcwebservicesConstants.GENERIC_ERROR), e); addError(errorsType, configurationService.getConfiguration().getString(NdcwebservicesConstants.GENERIC_ERROR)); serviceListRS.setErrors(errorsType); } return serviceListRS; } }
Java
UTF-8
3,542
2.453125
2
[]
no_license
package it.intecs.pisa.develenv.ui.widgets; import java.io.File; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; public class FileInsertion extends Composite { private static final String LABEL_BROWSE = "Browse.."; private Text fileText=null; private Button fileBrowseButton=null; private Label label=null; private String labelStr=null; private String[] admittedExtensions=null; public FileInsertion(Composite parent, int style) { super(parent, style); init(parent); } public FileInsertion(Composite parent, int style,String labelToDisplay) { super(parent, style); labelStr=labelToDisplay; init(parent); } @Override public void setEnabled(boolean enabled) { // TODO Auto-generated method stub super.setEnabled(enabled); this.fileBrowseButton.setEnabled(enabled); this.fileText.setEnabled(enabled); if(label!=null) label.setEnabled(enabled); } private void init(Composite parent) { GridData gd=null; GridLayout layout = new GridLayout(); if(labelStr==null) layout.numColumns=2; else layout.numColumns=3; this.setLayout(layout); if(labelStr!=null) { label=new Label(this,SWT.NULL); label.setText(labelStr); } fileText=new Text(this,SWT.BORDER); gd = new GridData(SWT.FILL,SWT.NULL,true,false); fileText.setLayoutData(gd); fileText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { FileInsertion.this.checkPath(); } }); fileBrowseButton=new Button(this,SWT.NULL); fileBrowseButton.setText(LABEL_BROWSE); fileBrowseButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(final SelectionEvent e) { } public void widgetSelected(final SelectionEvent e){ FileInsertion.this.browseForFile(); } }); } public String getSelectedFile() { if(fileText!=null) { return fileText.getText(); } else { return null; } } private void checkPath() { String newPath=null; Event event=null; newPath=this.fileText.getText(); final File pathFile=new File(newPath); event=new Event(); if(pathFile.exists()==false) { event.text="The file doesn't exists!"; this.notifyListeners(SWT.Modify, event); } this.notifyListeners(SWT.Modify, event); } public void browseForFile() { final Shell s = new Shell(); final FileDialog fd = new FileDialog(s, SWT.OPEN); if(admittedExtensions!=null) fd.setFilterExtensions(admittedExtensions); fd.setText("Select file"); final String selected = fd.open(); if(selected!=null) { this.fileText.setText(selected); } checkPath(); } /** * @param admittedExtension the admittedExtension to set */ public void setAdmittedExtension(String[] admittedExtension) { admittedExtensions = admittedExtension; } }
C++
UTF-8
1,102
2.59375
3
[]
no_license
// 056b-2 解説AC/bitset型を用いる // 想定解法: (個数)*(金額)で2次元DP // 水diff #include <bits/stdc++.h> using namespace std; using ll = long long; #define rep(i, n) for (int i=0; i<(int)(n); ++(i)) #define rep3(i, m, n) for (int i=(m); (i)<(int)(n); ++(i)) #define repr(i, n) for (int i=(int)(n)-1; (i)>=0; --(i)) #define rep3r(i, m, n) for (int i=(int)(n)-1; (i)>=(int)(m); --(i)) #define all(x) (x).begin(), (x).end() int main() { int n, s; cin >> n >> s; vector<int> a(n), b(n); rep(i, n) cin >> a[i] >> b[i]; vector<bitset<100001>> dp(n+1, bitset<100001>(0)); dp[0][0] = 1; rep(i, n) dp[i+1] = (dp[i]<<a[i]) | (dp[i]<<b[i]); if (!dp[n][s]) cout << "Impossible" << endl; else { int pos = s; string res; repr(i, n) { if (pos-a[i]>=0 && dp[i][pos-a[i]]) { pos -= a[i]; res += 'A'; } else { pos -= b[i]; res += 'B'; } } reverse(all(res)); cout << res << endl; } return 0; }
Shell
UTF-8
752
2.515625
3
[]
no_license
v=$1 v=${v:-9} echo Installing LLVM v${v} lsb_release || sudo apt-get install lsb-release -yqq code=$(lsb_release -c -s) echo ""; echo "DEBs" echo " deb http://apt.llvm.org/$code/ llvm-toolchain-$code main deb-src http://apt.llvm.org/$code/ llvm-toolchain-$code main deb http://apt.llvm.org/$code/ llvm-toolchain-$code-$v main deb-src http://apt.llvm.org/$code/ llvm-toolchain-$code-$v main " | sudo tee /etc/apt/sources.list.d/llvm.list sudo apt-get update -q apt-cache policy llvm sudo apt-get install -yq clang-format clang-tidy clang libc++-dev libc++1 libc++abi-dev libc++abi1 libclang-dev libclang1 libllvm-ocaml-dev libomp-dev libomp5 lld lldb llvm-dev llvm-runtime llvm sudo apt-get install -yq clang-tools clangd liblldb-dev python-clang
Python
UTF-8
1,457
3.640625
4
[]
no_license
from collections import defaultdict class Graph: def __init__(self): self.graph=defaultdict(list) self.startime={} self.endtime={} self.time=0 def addedge(self,x,y): self.graph[x].append(y) self.graph[y].append(x) def dfscon(self,s,visited): #time=0 visited[s]=True #self.startime[s]=time+1 print(s,end=" ") for i in self.graph[s]: if visited[i]==False: self.dfscon(i,visited) def dfs(self,s): visited=[False]*(len(self.graph)) self.dfscon(s,visited) #time=0 def timestamp1(self,s,visited): #time=0 #global time visited[s]=True self.startime[s]=self.time+1 self.time+=1 #print(s,end=" ") for i in self.graph[s]: if visited[i]==False: #self.time+=1 self.timestamp1(i,visited) self.endtime[s]=self.time+1 self.time=self.time+1 def timestamp(self,s): visited=[False]*(len(self.graph)) #time=0 self.timestamp1(s,visited) def printime(self,v): for i in range(v): string="Time stamp of {}:[{},{}]." print(string.format(i,self.startime[i],self.endtime[i])) def main(): print("Enter the no. of vertices") v=int(input()) g=Graph() print("Enter the no. of edges") e=int(input()) print("Enter the edges") for i in range(e): x,y=input().split() g.addedge(int(x),int(y)) print("Enter the source vertex") s=int(input()) print("The dfs traversal is:") g.dfs(s) g.timestamp(s) print("The time stamps:") g.printime(v) if __name__ == '__main__': main()
PHP
UTF-8
525
2.625
3
[]
no_license
<?php /** * Description of DeleteDados * * @author Júnior */ class DeleteDados { public function deleteEspecialidades(especialidades $Esp){ $deleteEsp = new Delete(); $deleteEsp->ExeDelete("especialidades", "WHERE cod = :id", 'id='.$Esp->getId_especialidade()); } public function deleteMedico(medico $Medicos){ $deleteEsp = new Delete(); $deleteEsp->ExeDelete("medicos", "WHERE id = :id", 'id='.$Medicos->getId_medico()); } }
Java
UTF-8
2,595
2.375
2
[]
no_license
package mx.com.televisa.derechocorporativo.daos; import java.io.InputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import mx.com.televisa.derechocorporativo.bean.GlosarioBean; import mx.com.televisa.derechocorporativo.bean.SessionBean; import mx.com.televisa.derechocorporativo.data.ConnectionWrapper; public class GlosarioDAO { ConnectionWrapper puConnectionWrapper; GlosarioBean glosarioBean; public boolean insertGlosarioPdf(String nomArchivo,InputStream archivo,SessionBean sessionBean){ boolean paso = false; String sql = "INSERT INTO DERCORP_AYUDA_GLOSARIO_TAB(ID_AYUDA_GLOSARIO,\n"+ " NOM_ARCHIVO,\n"+ " COD_ARCHIVO_BLOB,\n"+ " NUM_CREATED_BY,\n"+ " FEC_CREATION_DATE)\n"+ " VALUES (1,?,?,?,SYSDATE)"; String delete = "DELETE FROM DERCORP_AYUDA_GLOSARIO_TAB WHERE ID_AYUDA_GLOSARIO = 1"; PreparedStatement psmt = null; PreparedStatement psmt2 = null; Connection con = null; try { puConnectionWrapper = new ConnectionWrapper(); con = puConnectionWrapper.getConnection(); psmt = con.prepareStatement(sql); psmt2 = con.prepareStatement(delete); psmt2.executeUpdate(); psmt.setString(1, nomArchivo); psmt.setBinaryStream(2,archivo); psmt.setString(3, sessionBean.getIdUser()); psmt.executeUpdate(); paso = true; } catch (Exception e) { e.printStackTrace(); }finally{ try { psmt.close(); psmt2.close(); puConnectionWrapper.close(); } catch (SQLException e) { e.printStackTrace(); } } return paso; } public GlosarioBean dameArchivoGlosario(){ String sql = "SELECT NOM_ARCHIVO,\n"+ " COD_ARCHIVO_BLOB\n"+ " FROM DERCORP_AYUDA_GLOSARIO_TAB\n"+ " WHERE ID_AYUDA_GLOSARIO = 1"; PreparedStatement psmt = null; Connection con = null; ResultSet rs = null; try { puConnectionWrapper = new ConnectionWrapper(); con = puConnectionWrapper.getConnection(); psmt = con.prepareStatement(sql); rs = psmt.executeQuery(); while(rs.next()){ glosarioBean = new GlosarioBean(rs.getString(1),rs.getBinaryStream(2)); } }catch (Exception e) { e.printStackTrace(); }finally{ try { rs.close(); psmt.close(); con.close(); puConnectionWrapper.close(); } catch (SQLException e) { e.printStackTrace(); } } return glosarioBean; } }
Markdown
UTF-8
567
2.6875
3
[ "Apache-2.0", "MIT" ]
permissive
--- layout: post title: "Game-Archiver" date: 2020-05-18 02:28:27 +0000 permalink: game-archiver --- About this Project. I actually found this one to be easier than the last as I didnt have to code around someone elses coding structure for data. Being able to controll the format of my information the whole way through was nice. A challange I faced was being able to direct someone into their account if they forgot they had one and tried to signup. After a little while it became obvious and I no longer had any issues but it was still tricky to work.
Ruby
UTF-8
162
3.078125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def my_collect(collection) i = 0 returnedArr = [] while i < collection.size do returnedArr << yield(collection[i]) i += 1 end returnedArr end
Python
UTF-8
6,159
2.859375
3
[ "MIT" ]
permissive
import numpy as np import pandas as pd from scipy import sparse import argparse import os import json parser = argparse.ArgumentParser(description='Prepare datasets.') parser.add_argument('--dataset', type=str, nargs='?', default='assistments12') parser.add_argument('--min_interactions', type=int, nargs='?', default=10) parser.add_argument('--remove_nan_skills', type=bool, nargs='?', const=True, default=False) options = parser.parse_args() def prepare_assistments12(min_interactions_per_user, remove_nan_skills): """Preprocess ASSISTments 2012-2013 dataset. Arguments: min_interactions_per_user -- minimum number of interactions per student remove_nan_skills -- if True, remove interactions with no skill tag Outputs: df -- preprocessed ASSISTments dataset (pandas DataFrame) Q_mat -- corresponding q-matrix (item-skill relationships sparse array) """ df = pd.read_csv("data/assistments12/data.csv") df["timestamp"] = df["start_time"] df["timestamp"] = pd.to_datetime(df["timestamp"]) df["timestamp"] = df["timestamp"] - df["timestamp"].min() #df["timestamp"] = df["timestamp"].apply(lambda x: x.total_seconds() / (3600*24)) df["timestamp"] = df["timestamp"].apply(lambda x: x.total_seconds()).astype(np.int64) df.sort_values(by="timestamp", inplace=True) df.reset_index(inplace=True, drop=True) df = df.groupby("user_id").filter(lambda x: len(x) >= min_interactions_per_user) if remove_nan_skills: df = df[~df["skill_id"].isnull()] else: df.ix[df["skill_id"].isnull(), "skill_id"] = -1 df["user_id"] = np.unique(df["user_id"], return_inverse=True)[1] df["item_id"] = np.unique(df["problem_id"], return_inverse=True)[1] df["skill_id"] = np.unique(df["skill_id"], return_inverse=True)[1] df.reset_index(inplace=True, drop=True) # Add unique identifier of the row df["inter_id"] = df.index # Build Q-matrix Q_mat = np.zeros((len(df["item_id"].unique()), len(df["skill_id"].unique()))) item_skill = np.array(df[["item_id", "skill_id"]]) for i in range(len(item_skill)): Q_mat[item_skill[i,0],item_skill[i,1]] = 1 df = df[['user_id', 'item_id', 'timestamp', 'correct', "inter_id"]] df = df[df.correct.isin([0,1])] # Remove potential continuous outcomes df['correct'] = df['correct'].astype(np.int32) # Cast outcome as int32 # Save data sparse.save_npz("data/assistments12/q_mat.npz", sparse.csr_matrix(Q_mat)) df.to_csv("data/assistments12/preprocessed_data.csv", sep="\t", index=False) return df, Q_mat def prepare_kddcup10(data_name, min_interactions_per_user, kc_col_name, remove_nan_skills, drop_duplicates=True): """Preprocess KDD Cup 2010 datasets. Arguments: data_name -- "bridge_algebra06" or "algebra05" min_interactions_per_user -- minimum number of interactions per student kc_col_name -- Skills id column remove_nan_skills -- if True, remove interactions with no skill tag drop_duplicates -- if True, drop duplicates from dataset Outputs: df -- preprocessed ASSISTments dataset (pandas DataFrame) Q_mat -- corresponding q-matrix (item-skill relationships sparse array) """ folder_path = os.path.join("data", data_name) df = pd.read_csv(folder_path + "/data.txt", delimiter='\t').rename(columns={ 'Anon Student Id': 'user_id', 'Problem Name': 'pb_id', 'Step Name': 'step_id', kc_col_name: 'kc_id', 'First Transaction Time': 'timestamp', 'Correct First Attempt': 'correct' })[['user_id', 'pb_id', 'step_id' ,'correct', 'timestamp', 'kc_id']] df["timestamp"] = pd.to_datetime(df["timestamp"]) df["timestamp"] = df["timestamp"] - df["timestamp"].min() #df["timestamp"] = df["timestamp"].apply(lambda x: x.total_seconds() / (3600*24)) df["timestamp"] = df["timestamp"].apply(lambda x: x.total_seconds()).astype(np.int64) df.sort_values(by="timestamp",inplace=True) df.reset_index(inplace=True,drop=True) df = df.groupby("user_id").filter(lambda x: len(x) >= min_interactions_per_user) # Create variables df["item_id"] = df["pb_id"]+":"+df["step_id"] df = df[['user_id', 'item_id', 'kc_id', 'correct', 'timestamp']] if drop_duplicates: df.drop_duplicates(subset=["user_id", "item_id", "timestamp"], inplace=True) if remove_nan_skills: df = df[~df["kc_id"].isnull()] else: df.ix[df["kc_id"].isnull(), "kc_id"] = 'NaN' # Create list of KCs listOfKC = [] for kc_raw in df["kc_id"].unique(): for elt in kc_raw.split('~~'): listOfKC.append(elt) listOfKC = np.unique(listOfKC) dict1_kc = {} dict2_kc = {} for k, v in enumerate(listOfKC): dict1_kc[v] = k dict2_kc[k] = v # Transform ids into numeric df["item_id"] = np.unique(df["item_id"], return_inverse=True)[1] df["user_id"] = np.unique(df["user_id"], return_inverse=True)[1] df.reset_index(inplace=True, drop=True) # Add unique identifier of the row df["inter_id"] = df.index # Build Q-matrix Q_mat = np.zeros((len(df["item_id"].unique()), len(listOfKC))) item_skill = np.array(df[["item_id","kc_id"]]) for i in range(len(item_skill)): splitted_kc = item_skill[i,1].split('~~') for kc in splitted_kc: Q_mat[item_skill[i,0],dict1_kc[kc]] = 1 df = df[['user_id', 'item_id', 'timestamp', 'correct', 'inter_id']] df = df[df.correct.isin([0,1])] # Remove potential continuous outcomes df['correct'] = df['correct'].astype(np.int32) # Cast outcome as int32 # Save data sparse.save_npz(folder_path + "/q_mat.npz", sparse.csr_matrix(Q_mat)) df.to_csv(folder_path + "/preprocessed_data.csv", sep="\t", index=False) return df, Q_mat if __name__ == "__main__": if options.dataset == "assistments12": df, Q_mat = prepare_assistments12(min_interactions_per_user=options.min_interactions, remove_nan_skills=options.remove_nan_skills) elif options.dataset == "bridge_algebra06": df, Q_mat = prepare_kddcup10(data_name="bridge_algebra06", min_interactions_per_user=options.min_interactions, kc_col_name="KC(SubSkills)", remove_nan_skills=options.remove_nan_skills) elif options.dataset == "algebra05": df, Q_mat = prepare_kddcup10(data_name="algebra05", min_interactions_per_user=options.min_interactions, kc_col_name="KC(Default)", remove_nan_skills=options.remove_nan_skills)
Python
UTF-8
812
2.984375
3
[]
no_license
from PIL import Image import os import argparse def rescale_images(directory, size): for img in os.listdir(directory): im = Image.open(directory+img) im = im.rotate(-90, expand=True) im_resized = im.resize(size, Image.ANTIALIAS) im_resized.save(directory+img) if __name__ == '__main__': parser = argparse.ArgumentParser(description="Rescale images") parser.add_argument('-d', '--directory', type=str, required=True, help='Directory containing the images') parser.add_argument('-s', '--size', type=int, nargs=2, required=True, metavar=('width', 'height'), help='Image size') args = parser.parse_args() directories = [x[0] for x in os.walk(args.directory)] for directory in directories[1:]: rescale_images(directory+"/", args.size)
Markdown
UTF-8
238
2.625
3
[]
no_license
# TypeError < StandardError (from ruby core) --- Raised when encountering an object that is not of the expected type. [1, 2, 3].first("two") *raises the exception:* TypeError: no implicit conversion of String into Integer ---
Swift
UTF-8
3,549
3.3125
3
[]
no_license
// // PieChartCarouselAccessibilityElement.swift // Accessibility Chart // // Created by Haryanto Salim on 12/07/21. // import UIKit class PieChartCarouselAccessibilityElement: UIAccessibilityElement { var currentSegment: Segment? { didSet{ if let currSegment = currentSegment{ currentSegment = currSegment } } } init(accessibilityContainer container: Any, segment: Segment) { super.init(accessibilityContainer: container) currentSegment = segment } override var accessibilityLabel: String?{ get{ return "Pie Chart" } set{ super.accessibilityLabel = newValue } } override var accessibilityValue: String?{ get{ if let currSegment = currentSegment { return currSegment.name } return super.accessibilityValue } set{ super.accessibilityValue = newValue } } override var accessibilityTraits: UIAccessibilityTraits{ get{ return .adjustable } set{ super.accessibilityTraits = newValue } } private func moveNextSegment() -> Bool{ guard let container = accessibilityContainer as? PieChartView else{ return false } guard let currSegment = currentSegment else { return false } let firstIdx = 0 let firstSegment = container.segments[0] for idx in firstIdx ..< container.segments.count { if container.segments[idx].name != currSegment.name{ //bole lanjut ke idx berikutnya } else { if idx == container.segments.count - 1 { //idx terakhir container.currentSegment = firstSegment //idx di set ke item pertama } else { container.currentSegment = container.segments[idx + 1] //idx di set item selanjutnya } return true } } return true } private func movePrevSegment() -> Bool{ guard let container = accessibilityContainer as? PieChartView else{ return false } guard let currSegment = currentSegment else { return false } let lastIdx = container.segments.count - 1 let lastSegment = container.segments[lastIdx] for idx in lastIdx...0 { if container.segments[idx].name != currSegment.name { //bole lanjut ke index sebelumnya } else { if idx == 0 { //idx pertama container.currentSegment = lastSegment //idx di set item terakhir } else { container.currentSegment = container.segments[idx - 1] //idx di set ke item sebelumnya } return true } } return true } override func accessibilityIncrement() { _ = moveNextSegment() } override func accessibilityDecrement() { _ = moveNextSegment() } override func accessibilityScroll(_ direction: UIAccessibilityScrollDirection) -> Bool { print("scroll detected") if direction == .left { return moveNextSegment() } else if direction == .right { return movePrevSegment() } return false } }
Java
UTF-8
6,240
1.960938
2
[ "LicenseRef-scancode-unknown-license-reference", "EPL-1.0", "CDDL-1.1", "Classpath-exception-2.0", "BSD-3-Clause", "LicenseRef-scancode-jdom", "GPL-2.0-only", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "MIT", "CC0-1.0", "CC-BY-3.0", "CC-PDDC", "GCC-exception-3.1", "CDDL-1.0", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown" ]
permissive
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.common; import java.lang.management.ManagementFactory; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.MBeanAttributeInfo; import javax.management.MBeanInfo; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import org.apache.commons.logging.Log; import org.apache.commons.logging.impl.Log4JLogger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.metrics2.util.MBeans; import org.apache.log4j.Appender; import org.apache.log4j.AsyncAppender; /** * MetricsLoggerTask can be used as utility to dump metrics to log. */ public class MetricsLoggerTask implements Runnable { public static final Logger LOG = LoggerFactory.getLogger(MetricsLoggerTask.class); private static ObjectName objectName = null; static { try { objectName = new ObjectName("Hadoop:*"); } catch (MalformedObjectNameException m) { // This should not occur in practice since we pass // a valid pattern to the constructor above. } } private Log metricsLog; private String nodeName; private short maxLogLineLength; public MetricsLoggerTask(Log metricsLog, String nodeName, short maxLogLineLength) { this.metricsLog = metricsLog; this.nodeName = nodeName; this.maxLogLineLength = maxLogLineLength; } /** * Write metrics to the metrics appender when invoked. */ @Override public void run() { // Skip querying metrics if there are no known appenders. if (!metricsLog.isInfoEnabled() || !hasAppenders(metricsLog) || objectName == null) { return; } metricsLog.info(" >> Begin " + nodeName + " metrics dump"); final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); // Iterate over each MBean. for (final ObjectName mbeanName : server.queryNames(objectName, null)) { try { MBeanInfo mBeanInfo = server.getMBeanInfo(mbeanName); final String mBeanNameName = MBeans.getMbeanNameName(mbeanName); final Set<String> attributeNames = getFilteredAttributes(mBeanInfo); final AttributeList attributes = server.getAttributes(mbeanName, attributeNames.toArray(new String[attributeNames.size()])); for (Object o : attributes) { final Attribute attribute = (Attribute) o; final Object value = attribute.getValue(); final String valueStr = (value != null) ? value.toString() : "null"; // Truncate the value if it is too long metricsLog.info(mBeanNameName + ":" + attribute.getName() + "=" + trimLine(valueStr)); } } catch (Exception e) { metricsLog.error("Failed to get " + nodeName + " metrics for mbean " + mbeanName.toString(), e); } } metricsLog.info(" << End " + nodeName + " metrics dump"); } private String trimLine(String valueStr) { if (maxLogLineLength <= 0) { return valueStr; } return (valueStr.length() < maxLogLineLength ? valueStr : valueStr .substring(0, maxLogLineLength) + "..."); } private static boolean hasAppenders(Log logger) { if (!(logger instanceof Log4JLogger)) { // Don't bother trying to determine the presence of appenders. return true; } Log4JLogger log4JLogger = ((Log4JLogger) logger); return log4JLogger.getLogger().getAllAppenders().hasMoreElements(); } /** * Get the list of attributes for the MBean, filtering out a few attribute * types. */ private static Set<String> getFilteredAttributes(MBeanInfo mBeanInfo) { Set<String> attributeNames = new HashSet<>(); for (MBeanAttributeInfo attributeInfo : mBeanInfo.getAttributes()) { if (!attributeInfo.getType().equals( "javax.management.openmbean.TabularData") && !attributeInfo.getType().equals( "javax.management.openmbean.CompositeData") && !attributeInfo.getType().equals( "[Ljavax.management.openmbean.CompositeData;")) { attributeNames.add(attributeInfo.getName()); } } return attributeNames; } /** * Make the metrics logger async and add all pre-existing appenders to the * async appender. */ public static void makeMetricsLoggerAsync(Log metricsLog) { if (!(metricsLog instanceof Log4JLogger)) { LOG.warn("Metrics logging will not be async since " + "the logger is not log4j"); return; } org.apache.log4j.Logger logger = ((Log4JLogger) metricsLog).getLogger(); logger.setAdditivity(false); // Don't pollute actual logs with metrics dump @SuppressWarnings("unchecked") List<Appender> appenders = Collections.list(logger.getAllAppenders()); // failsafe against trying to async it more than once if (!appenders.isEmpty() && !(appenders.get(0) instanceof AsyncAppender)) { AsyncAppender asyncAppender = new AsyncAppender(); // change logger to have an async appender containing all the // previously configured appenders for (Appender appender : appenders) { logger.removeAppender(appender); asyncAppender.addAppender(appender); } logger.addAppender(asyncAppender); } } }