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
Python
UTF-8
3,692
2.671875
3
[ "MIT" ]
permissive
class ServiceCentre(object): """ An information store for each service centre in the queueing network. Contains all information that is independent of customer class: - number of servers - queueing capacity - server schedules + preemtion status - class change matrix """ def __init__(self, number_of_servers, queueing_capacity, class_change_matrix=None, schedule=None, schedule_preempt=False, priority_preempt=False, ps_threshold=1, server_priority_function=None): """ Initialises the ServiceCentre object. """ self.number_of_servers = number_of_servers self.queueing_capacity = queueing_capacity self.class_change_matrix = class_change_matrix self.schedule = schedule self.schedule_preempt = schedule_preempt self.priority_preempt = priority_preempt self.ps_threshold = ps_threshold self.server_priority_function = server_priority_function self.class_change_time = False class CustomerClass(object): """ An information store for each customer class in the queueing network. Contains all information that is dependent on customer class: - arrival distributions - service distributions - routing matrices/functions - priority class - baulking functions - batching distributions """ def __init__(self, arrival_distributions, service_distributions, routing, priority_class, baulking_functions, batching_distributions, reneging_time_distributions, reneging_destinations, class_change_time_distributions): """ Initialises the CutomerCass object. """ self.arrival_distributions = arrival_distributions self.service_distributions = service_distributions self.batching_distributions = batching_distributions self.routing = routing self.priority_class = priority_class self.baulking_functions = baulking_functions self.reneging_time_distributions = reneging_time_distributions self.reneging_destinations = reneging_destinations self.class_change_time_distributions = class_change_time_distributions class Network(object): """ An information store the queueing network. Contains a list of ServiceCentre objects for each service centre, and a list of CustomerClass objects for each customer class. """ def __init__(self, service_centres, customer_classes): """ Initialises the Network object """ self.service_centres = service_centres self.customer_classes = customer_classes self.number_of_nodes = len(service_centres) self.number_of_classes = len(customer_classes) self.number_of_priority_classes = len(set([clss.priority_class for clss in customer_classes])) self.priority_class_mapping = {i: clss.priority_class for i, clss in enumerate(customer_classes)} for nd_id, node in enumerate(self.service_centres): if all(clss.reneging_time_distributions[nd_id] == None for clss in self.customer_classes): node.reneging = False else: node.reneging = True if any(dist is not None for clss in customer_classes for dist in clss.class_change_time_distributions): for node in self.service_centres: node.class_change_time = True
Markdown
UTF-8
1,955
3.375
3
[]
no_license
# 控制流 ``` # for for(i in 1:3){ print(i) } # while i <- 1 while(i <= 3){ print(i) i <- i+1 } # if...else if...else x <- 0.1 if(x < -1){ print(-1) } else if(x > 1){ print(1) } else { print(0) } # ifelse ifelse(x>0,"positive","notpositive") # switch switch("2", "1" = "hello", "2" = "hi" ) ``` # 函数 ``` my <- function(name){ re <- paste("hello",name) return(re) } my("test") ``` # 常用函数 ### 数学 ``` # random uniform runif(2) # random normal rnorm(2) # 求余 10%%3 # 整除 10%/%3 abs(-2) sqrt(2) ceiling(2.2) floor(2.2) # 取整数部分 trunc(-2.22222) # 四舍五入到指定位的小数 round(3.14,1) # 四舍五入到指定的有效数字位数 signif(3.14,1) log(2.718282) log(8,base=2) log10(100) exp(1) x=c(1,1,1,1,1,2,2,5,6,7,7) sum(x) length(x) mean(x) median(x) sd(x) var(x) # 绝对中位差 mad(x) min(x) max(x) range(x) quantile(x,c(.25,.5,.75)) # Tukey's five-number summary summary(x) fivenum(x) # 滞后差分 diff(x,lag=2) # 标准正态化 scale(x) # 严格等于,浮点数慎用 3 == 3 3 != 3 # 或 3>2 | 4<= 5 # 与 2 ^ 3 == 8 & 2 ** 3 ==8 ``` ### 日期 ``` # today Sys.Date() # 读取字符串日期为date t <- as.Date("09/22/2019","%m/%d/%y") # 从日期中获取特定值 format(t, format="%B,%d,%A") # 日期计算 difftime(t, as.Date("1989-06-04"), units="weeks") ``` ### 重构 reshape ``` library(reshape2) # 短数据格式,变量作为列名(索引除外)),有多列 mydata <- read.table(header=TRUE, sep=" ", text=" id time X1 X2 1 1 5 6 1 2 3 5 2 1 6 1 2 2 2 4 ") # 重构为长数据格式,变量一列,值一列(索引除外),索引由id指定 mydata <- melt(mydata, id=(c("id","time"))) # 重构为短数据格式,左为索引,右为列名(字符串可以拼接) ## dcast: to data.frame dcast(mydata,id+time~variable) dcast(mydata,id~variable+time) ## acast: to vector/matrix/array acast(mydata,id+time~variable) acast(mydata,id~variable+time) ```
JavaScript
UTF-8
2,297
2.53125
3
[]
no_license
var title = document.createElement("h1"); title.innerHTML = "Making Ice Cream Sandwiches"; document.body.appendChild(title); title.style.color = "orange"; var para1 = document.createElement("p"); para1.innerHTML = "Kids and adults alike will be fighting over these big monster ice cream sandwiches! The best part about these things is that they are no bake. You don't even need to warm up your oven if you purchased cookies. Makes early to use the mini M&Ms or the large ones will fall off. As a volunteer field editor for Taste of Home magazine, I love recipes that can be assembled quickly and still make a quick presentation."; document.body.appendChild(para1); var title1 = document.createElement("div"); title1.style.backgroundColor = "orange"; var title2 = document.createElement("h2"); title2.innerHTML = "Ingredients"; title1.appendChild(title2); document.body.appendChild(title1); title1.style.padding = "20px"; var ul = document.createElement("ul"); var li1 = document.createElement("li"); li1.innerHTML = "Cookies and Cream ice cream"; ul.appendChild(li1); var li2 = document.createElement("li"); li2.innerHTML = "Large chocolate chip cookies"; ul.appendChild(li2); var li3 = document.createElement("li"); li3.innerHTML = "M&M's minis"; ul.appendChild(li3); var li4 = document.createElement("li"); li4.innerHTML = "Reese's mini peanut butter cups"; ul.appendChild(li4); title1.appendChild(ul); document.body.appendChild(title1); var pic1 = document.createElement("img"); pic1.src = "ice-cream.JPG"; document.body.appendChild(pic1); pic1.style.width = "24%"; var pic2 = document.createElement("img"); pic2.src = "cookies.jpg"; document.body.appendChild(pic2); pic2.style.width = "24%"; var pic3 = document.createElement("img"); pic3.src = "mmminis.jpg"; document.body.appendChild(pic3); pic3.style.width = "24%"; var pic4 = document.createElement("img"); pic4.src = "pb.JPG"; document.body.appendChild(pic4); pic4.style.width = "24%"; var para4 = document.createElement("p"); para4.innerHTML = "For more information about this recipe, please visit "; var link = document.createElement("a"); link.href = "https://www.tasteofhome.com/recipes/candy-craze-ice-cream-sandwiches/"; link.innerHTML = "The Taste of Home website"; para4.appendChild(link); document.body.appendChild(para4);
Python
UTF-8
2,819
3.265625
3
[]
no_license
import sys import numpy as np from scipy import spatial def NormalizeFeatureVectors(features): # "features" is a 2-D array with the i'th row containing embedded speakers vector for the i'th superframe. # superframe 0 c0, c1, c2, ...., c259 # superframe 1 c0, c1, c2, ...., c259 # superframe 2 c0, c1, c2, ...., c259 # . # . # . # superframe(N-1) c0, c1, c2, ...., c259 # # Normalize features so that the max sum over a class is 1.0. # Get the sum over 0 to N-1 for each class ci. # Get the max sum. # Normalize all coefs in features array by this value. sumOverRows = np.sum(features, axis=0) maxSum = sumOverRows.max() features = features / maxSum return features def CalculateSpeakerLabels(features, newSpeakerThreshold, sameSpeakerThreshold): """ Using the feature vectors calculated (one feature vector per superframe), detect speaker changes and assign a speaker label (1, 2, ...) to each superframe. """ # R cosine similarity to detect speaker changes. # Record the change as a sequence of speaker labels: # 1 for speaker 1, 2 for speaker 2, ... speakerLabels = [1] # speaker labels sequence over the whole recording. speakerCount = 1 # total number of speakers. currentSpeaker = 1 speakerFeatureDict = {} speakerFeatureDict[currentSpeaker] = features[0] # Dictionary of (speaker label, last feature vector) featureCount = features.shape[0] # Number of features. for i in range(1, featureCount): # Get cosine distance between last feature (i-1) and feature i. dist = spatial.distance.cosine(features[i - 1], features[i]) if dist < newSpeakerThreshold: # no speaker change speakerLabels.append(currentSpeaker) speakerFeatureDict[currentSpeaker] = features[i] else: # Is this a new speaker or a speaker already seen? # Check distance between features[i] and each previously seen speaker. minDist = sys.float_info.max minSpeakerLabel = -1 for kv in speakerFeatureDict.items(): dist = spatial.distance.cosine(features[i], kv[1]) if dist < minDist: minDist = dist minSpeakerLabel = kv[0] if minSpeakerLabel > 0 and minDist < sameSpeakerThreshold: # This is a speaker change to a previously seen speaker currentSpeaker = minSpeakerLabel else: # We have a new speaker: speakerCount += 1 currentSpeaker = speakerCount speakerLabels.append(currentSpeaker) speakerFeatureDict[currentSpeaker] = features[i] return speakerLabels
C
UTF-8
2,220
3.015625
3
[]
no_license
#include <pthread.h> #include <stdio.h> #define NUM_THREADS 2 #define LINHAS 3 #define COLUNAS 3 typedef struct par{ int indiceNzero; double elemento; }Par; Par MatrizEsparsa[4][4]; void *threadCode(void *tid){ int i,j, k; long threadId = (*(long *)tid); for(i=threadId; i < LINHAS; i = i + NUM_THREADS) { if(i >= LINHAS) { return;} for (j=0;j<COLUNAS;j++) { resultado[i][j] = 0; for(k=0;k< COLUNAS;k++) { resultado[i][j] = resultado[i][j] + matriz1[i][k]* matriz2[k][j]; } } } } void preencheMatrizEsparsa(){ MatrizEsparsa[0] = (Par *) malloc(2*sizeof(Par)); // Linha 1 MatrizEsparsa[0][0].indiceNzero = 0; MatrizEsparsa[0][0].elemento = 2.0; MatrizEsparsa[0][1].indiceNzero = 1; MatrizEsparsa[0][1].elemento = -1.0; // Linha 2 MatrizEsparsa[1][0].indiceNzero = 0; MatrizEsparsa[1][0].elemento = -1.0; MatrizEsparsa[1][1].indiceNzero = 1; MatrizEsparsa[1][1].elemento = 2.0; MatrizEsparsa[1][2].indiceNzero = 2; MatrizEsparsa[1][2].elemento = -1.0; // Linha 3 MatrizEsparsa[2][0].indiceNzero = 1; MatrizEsparsa[2][0].elemento = -1.0; MatrizEsparsa[2][1].indiceNzero = 2; MatrizEsparsa[2][1].elemento = 2.0; MatrizEsparsa[2][2].indiceNzero = 3; MatrizEsparsa[2][2].elemento = -1.0; // Linha 4 MatrizEsparsa[3][0].indiceNzero = 2; MatrizEsparsa[3][0].elemento = -1.0; MatrizEsparsa[3][1].indiceNzero = 3; MatrizEsparsa[3][1].elemento = 2.0; } int main (int argc, char *argv[]){ pthread_t threads[NUM_THREADS]; long *taskids[NUM_THREADS]; int i,j,u; long t; for(t=0; t<NUM_THREADS; t++){ printf("No main: criando thread %ld\n", t); taskids[t] = (long *) malloc(sizeof(long)); *taskids[t] = t; pthread_create(&threads[t],NULL,threadCode, (void *)taskids[t]); } for(u=0; u<NUM_THREADS;u++) { long *res; pthread_join(threads[u], NULL); } for(i=0; i < LINHAS; i++) { for (j=0;j<COLUNAS;j++) { printf("%d\t", resultado[i][j]); } printf("\n"); } pthread_exit(NULL); }
Java
UTF-8
2,690
1.960938
2
[]
no_license
package quay.com.ipos.offerdiscount.Model; import java.util.ArrayList; /** * Created by aditi.bhuranda on 16-07-2018. */ public class OfferDiscountModel { String sName; String sDescription; String sDisplayName; String sDisplayImage; String sStartDate; String sEndDate; String sEntity; String sLOB; String sBusinessPlaces; String sState; String sCustomerGroup; String sPolicyDocument; ArrayList<RuleModel > ruleModels = new ArrayList<>(); public String getsName() { return sName; } public void setsName(String sName) { this.sName = sName; } public String getsDescription() { return sDescription; } public void setsDescription(String sDescription) { this.sDescription = sDescription; } public String getsDisplayName() { return sDisplayName; } public void setsDisplayName(String sDisplayName) { this.sDisplayName = sDisplayName; } public String getsDisplayImage() { return sDisplayImage; } public void setsDisplayImage(String sDisplayImage) { this.sDisplayImage = sDisplayImage; } public String getsStartDate() { return sStartDate; } public void setsStartDate(String sStartDate) { this.sStartDate = sStartDate; } public String getsEndDate() { return sEndDate; } public void setsEndDate(String sEndDate) { this.sEndDate = sEndDate; } public String getsEntity() { return sEntity; } public void setsEntity(String sEntity) { this.sEntity = sEntity; } public String getsLOB() { return sLOB; } public void setsLOB(String sLOB) { this.sLOB = sLOB; } public String getsBusinessPlaces() { return sBusinessPlaces; } public void setsBusinessPlaces(String sBusinessPlaces) { this.sBusinessPlaces = sBusinessPlaces; } public String getsState() { return sState; } public void setsState(String sState) { this.sState = sState; } public String getsCustomerGroup() { return sCustomerGroup; } public void setsCustomerGroup(String sCustomerGroup) { this.sCustomerGroup = sCustomerGroup; } public String getsPolicyDocument() { return sPolicyDocument; } public void setsPolicyDocument(String sPolicyDocument) { this.sPolicyDocument = sPolicyDocument; } public ArrayList<RuleModel> getRuleModels() { return ruleModels; } public void setRuleModels(ArrayList<RuleModel> ruleModels) { this.ruleModels = ruleModels; } }
Python
UTF-8
2,394
2.578125
3
[]
no_license
#_*_coding:utf-8_*_ import requests,re,random import time,os import conf class download(object): def __init__(self): #拿到代理iplist iprespon = requests.get('http://haoip.cc/tiqu.htm') pattern = re.compile(r'r/>(.*?)<b',re.S) ipresult = re.findall(pattern, iprespon.text) self.iplist = list(i.strip() for i in ipresult) self.UserAgent = conf.user_agent_list def get(self,url,timeout,proxy=False,num_retries=3): '''url timeout,proxy,num_retries 返回response对象 ''' #伪造UserAgent UA = self.UserAgent[random.randint(0,len(self.UserAgent)-1)] headers = {'User-Agent':UA} if proxy == False: try: return requests.get(url,timeout=timeout,headers=headers) print '2' except Exception as e: print '3',e #判断retries if num_retries>0: print u'爬取网页错误,10s后继续尝试.....' time.sleep(1) return self.get(url, timeout, False, num_retries-1) else:#重试次数用尽,使用代理 time.sleep(1) IP = str(random.choice(self.iplist)) proxy = {'http',IP} return self.get(url, timeout, True,8) else:#使用代理 try: print '开始使用代理' IP = str(random.choice(self.iplist)) proxy = {'http':IP} print proxy['http'] return requests.get(url,headers=headers, timeout=timeout, proxies=proxy) except: if num_retries>0: print u'代理爬取网页错误,10s后继续尝试.....' time.sleep(1) return self.get(url, timeout,True, num_retries-1) else:#代理也不行 time.sleep(30) print u'代理也没用...' return self.get(url, 3) def mkdir(path): if os.path.exists(path) and os.path.isdir(path): #print u'%s 存在'%path pass else: os.makedirs(path) # def test(): # t=download() # tt = t.get('http://www.baidu.com',10,) # print tt.text
C++
UTF-8
1,850
3.109375
3
[]
no_license
/** * camera2D.hpp * * Author : Fatih Erol * Date : 23.03.2010 * * All rights reserved. */ #ifndef GRAPHICSLAB_CAMERA2D_HPP #define GRAPHICSLAB_CAMERA2D_HPP // Base class include #include "camera.hpp" GRAPHICSLAB_NAMESPACE_BEGIN /** Class to simulate a 2D camera with orthogonal viewing volume */ class Camera2D : public Camera { public: /** * Constructor. * * @param[in] scene Owning scene */ Camera2D( Scene &scene ); /** Reset the camera to default values */ void reset(); /** Structure to define an orthogonal view volume */ struct ViewVolume { float left, right, bottom, top, zNear, zFar; /** * Constructor. * * @param[in] left_ Left boundary of the view volume * @param[in] right_ Right boundary of the view volume * @param[in] bottom_ Bottom boundary of the view volume * @param[in] top_ Top boundary of the view volume * @param[in] near_ Near boundary of the view volume * @param[in] far_ Far boundary of the view volume */ ViewVolume( float left_ = -10.0, float right_ = 10.0, float bottom_ = -10, float top_ = 10.0, float zNear_ = 0.0, float zFar_ = 10.0 ) : left( left_ ), right ( right_ ), bottom( bottom_ ), top( top_ ), zNear( zNear_ ), zFar( zFar_ ) { } }; // struct ViewVolume /** * Set the orthogonal view volume. * * @param[in] viewVolume ViewVolume to set to */ void setViewVolume( const ViewVolume &viewVolume ); /** Apply projection transformation */ void applyProjection(); private: ViewVolume _viewVolume; }; // class Camera2D GRAPHICSLAB_NAMESPACE_END #endif // GRAPHICSLAB_CAMERA2D_HPP
JavaScript
UTF-8
201
3.578125
4
[]
no_license
function hi() { var test = "Abdellah"; var result = ""; for (var i = test.length; i>=0; i--) { result+= test.charAt(i); } return result; } console.log(hi());
Python
UTF-8
1,045
3.1875
3
[]
no_license
Characters: Character.objects.count() # Answer: 302 Fighter: Fighter.objects.count() # Answer: 68 Mage: Mage.objects.count() # Answer: 108 Cleric: Cleric.objects.count() # Answer: 75 Thief: Thief.objects.count() # Answer: 51 Necromancer: Necromancer.objects.count() # Answer: 11 Items: Item.objects.count() # Answer: 174 Weapons: Weapon.objects.count() # Answer: 37 Not Weapons: Item.objects.exclude(weapon__isnull=False).count() # Answer: 137 Average Items per Character: characters = (Character.objects.all()) average = 0 for character in characters: average += character.inventory.count() print(average / Character.objects.count()) # Answer: 2.9735099337748343 Average Weapons per Character: characters = Character.objects.all() weapons = 0 for character in characters: weapons = character.inventory.exclude(weapon__isnull=False).count() print(weapons / Character.objects.count()) # Answer: 0.013245033112582781
Python
UTF-8
131
3.28125
3
[]
no_license
strn = "USA usa usa, usa USA?" find = "USA" temp = strn.lower() count = temp.count(find.lower()) print("The USA count is:", count)
C++
UTF-8
390
3.140625
3
[]
no_license
template <class T> void StraightSelectionSort(T* a, int n) { for (int i = 0; i < n - 1; i++) { T min = a[i]; int ixMin = i; for (int k = i + 1; k < n; k++) { if (a[k] < min) { min = a[k]; ixMin = k; } } a[ixMin] = a[i]; a[i] = min; } }
Java
UTF-8
2,005
1.90625
2
[]
no_license
package com.proxair.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.proxair.dto.DtoCreationPrixRef; import com.proxair.dto.DtoCreationTrajet; import com.proxair.dto.DtoGenerate; import com.proxair.dto.DtoTournee; import com.proxair.service.IAdminService; @RestController @RequestMapping(value="/api/admin") public class AdminController { @Autowired IAdminService adminService; @PostMapping(value="/Trajets") @ResponseBody @ResponseStatus(code=HttpStatus.CREATED) public DtoCreationTrajet addTrajet2(@RequestBody DtoCreationTrajet dtotrajet) { return adminService.createtravel(dtotrajet); } @GetMapping(value="/Tournee") @ResponseBody public List<DtoTournee> listTrip(){ return adminService.listTrip(); } @PostMapping(value="/Tournee") @ResponseBody @ResponseStatus(code=HttpStatus.CREATED) public String addTrip(@RequestBody DtoTournee dtoTournee) { return adminService.addTrip(dtoTournee); } @PatchMapping(value="/Tournee") @ResponseBody public String GenerateTripFromNow(@RequestBody DtoGenerate dtoGenerate) { return adminService.GenerateTripFromNow(dtoGenerate); } @PostMapping(value="/Prix") @ResponseBody @ResponseStatus(code=HttpStatus.CREATED) public boolean addPrixRef(@RequestBody DtoCreationPrixRef dtoCreationPrixRef) { return adminService.createPriceRef(dtoCreationPrixRef); } }
C#
UTF-8
2,455
2.53125
3
[ "MIT" ]
permissive
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; namespace dashboard.Controllers { public class KPIController : ApiController { public async Task<JArray> GetKPIs() { var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }); string authInfo = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(String.Format("{0}:{1}", "pischool\\student01", "student"))); //user account and password client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authInfo); try { //this will cause the server call to ingore invailid SSL Cert - should remove for production ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; //example PI Web API call for plot data string uri = @"https://pisrv01.pischool.int/piwebapi/streams/A0EOfPAkD5FdUOZvMMwGLQ7fAieBh7H_k5RGAxwANOjH2Zg7HNRPBjbLVcYCJZMO5tH4AUElTUlYwMVxEQVRVUkFcQU5URVJPU3w1TUlOUFJPRFVDVElPTl9PVVRQVVQ/plot"; HttpResponseMessage response = await client.GetAsync(uri); string content = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) { var responseMessage = "Response status code does not indicate success: " + (int)response.StatusCode + " (" + response.StatusCode + " ). "; throw new HttpRequestException(responseMessage + Environment.NewLine + content); } var data = (JArray)JObject.Parse(content)["Items"]; var result = new JArray(); foreach (var item in data) { if (item["Good"].Value<bool>()) { var dataPair = new JObject(); dataPair.Add("Timestamp", item["Timestamp"].Value<string>()); dataPair.Add("Value", item["Value"].Value<double>()); result.Add(dataPair); } } return result; } catch (Exception e) { throw e; } } } }
Java
ISO-8859-9
191
1.789063
2
[]
no_license
package Odev.GoogleHesap; import Odev.entitites.concretes.User; public class GoogleManager { public void register(String message) { System.out.println("Google ile kayt olundu" ); } }
JavaScript
UTF-8
8,774
2.875
3
[ "MIT" ]
permissive
var tabs = {}; function toggle(tab){ if(!tabs[tab.id]) addTab(tab.id); else removeTab(tab.id); } function addTab(id){ tabs[id] = Object.create(dimensions); tabs[id].activate(id); } function removeTab(id){ tabs[id].deactivate(); for(var tabId in tabs){ if(tabId == id) delete tabs[tabId]; } } chrome.commands.onCommand.addListener(toggle); chrome.browserAction.onClicked.addListener(toggle); chrome.runtime.onConnect.addListener(function(port) { tabs[ port.sender.tab.id ].initialize(port); }); chrome.runtime.onSuspend.addListener(function() { for(var tabId in tabs){ tabs[tabId].deactivate(); } }); var dimensions = { image: new Image(), threshold: 6, takingScreenshot: false, activate: function(id){ this.id = id; this.takeScreenshot(); chrome.tabs.insertCSS(this.id, { file: 'tooltip.css' }); chrome.tabs.executeScript(this.id, { file: 'tooltip.js' }); chrome.browserAction.setIcon({ tabId: this.id, path: { 19: "images/icon_active.png", 38: "images/icon_active@2x.png" } }); }, deactivate: function(){ this.port.postMessage({ type: 'destroy' }); chrome.browserAction.setIcon({ tabId: this.id, path: { 19: "images/icon.png", 38: "images/icon@2x.png" } }); }, initialize: function(port){ this.port = port; port.onMessage.addListener(this.receiveMessage.bind(this)); }, receiveMessage: function(event){ switch(event.type){ case 'position': this.measureDistances(event.data); break; case "area": this.measureArea(event.data); break; case 'newScreenshot': this.takeScreenshot(); break; } }, takeScreenshot: function(){ this.takingScreenshot = true; chrome.tabs.captureVisibleTab({ format: "png" }, this.parseScreenshot.bind(this)); }, parseScreenshot: function(dataUrl){ this.image.onload = this.loadImage.bind(this); this.image.src = dataUrl; // the first time we don't have a port connection yet if(this.port) this.port.postMessage({ type: 'screenshot taken', data: this.image.src }); }, // // measureArea // =========== // // measures the area around pageX and pageY. // // measureArea: function(pos){ if(this.takingScreenshot) return; var x0 = pos.x; var y0 = pos.y; var map = new Int16Array(this.data); var area = { top: y0, right: x0, bottom: y0, left: x0 }; var pixelsInArea = []; var boundaries = { vertical: [], horizontal: [] }; var maxArea = 5000000; var areaFound = true; var i = 0; var startLightness = this.getLightnessAt(map, x0, y0); var stack = [[x0, y0, startLightness]]; while(stack.length){ if(++i > maxArea){ areaFound = false; break; } var xyl = stack.shift(); var x = xyl[0]; var y = xyl[1]; var lastLightness = xyl[2]; currentLightness = this.getLightnessAt(map, x, y); if(currentLightness && Math.abs(currentLightness - lastLightness) < this.threshold){ this.setLightnessAt(map, x, y, 999); pixelsInArea.push([x,y]); if(x < area.left) area.left = x; else if(x > area.right) area.right = x; if(y < area.top) area.top = y; else if(y > area.bottom) area.bottom = y; stack.push([x-1, y , currentLightness]); stack.push([x , y+1, currentLightness]); stack.push([x+1, y , currentLightness]); stack.push([x , y-1, currentLightness]); } } for(var i=0, l=pixelsInArea.length; i<l; i++){ var x = pixelsInArea[i][0]; var y = pixelsInArea[i][1]; if(x === area.left || x === area.right) boundaries.vertical.push(y); if(y === area.top || y === area.bottom) boundaries.horizontal.push(x); } area.x = this.getAverage(boundaries.horizontal); area.y = this.getAverage(boundaries.vertical); area.left = area.x - area.left; area.right = area.right - area.x; area.top = area.y - area.top; area.bottom = area.bottom - area.y; this.port.postMessage({ type: 'distances', data: areaFound ? area : false }); }, getAverage: function(values){ var i = values.length, sum = 0; while (i--) { sum = sum + values[i]; } return Math.floor(sum/values.length); }, // // measureDistances // ================ // // measures the distances to the next boundary // around pageX and pageY. // measureDistances: function(input){ if(this.takingScreenshot) return; var distances = { top: 0, right: 0, bottom: 0, left: 0 }; var directions = { top: { x: 0, y: -1 }, right: { x: 1, y: 0 }, bottom: { x: 0, y: 1 }, left: { x: -1, y: 0 } } var area = 0; var startLightness = this.getLightnessAt(this.data, input.x, input.y); var lastLightness; for(var direction in distances){ var vector = directions[direction]; var boundaryFound = false; var sx = input.x; var sy = input.y; var currentLightness; // reset lightness to start lightness lastLightness = startLightness; while(!boundaryFound){ sx += vector.x; sy += vector.y; currentLightness = this.getLightnessAt(this.data, sx, sy); if(currentLightness && Math.abs(currentLightness - lastLightness) < this.threshold){ distances[direction]++; lastLightness = currentLightness; } else { boundaryFound = true; } } area += distances[direction]; } if(area <= 6){ distances = { top: 0, right: 0, bottom: 0, left: 0 }; var similarColorStreakThreshold = 8; for(var direction in distances){ var vector = directions[direction]; var boundaryFound = false; var sx = input.x; var sy = input.y; var currentLightness; var similarColorStreak = 0; lastLightness = startLightness; while(!boundaryFound){ sx += vector.x; sy += vector.y; currentLightness = this.getLightnessAt(this.data, sx, sy); if(currentLightness){ distances[direction]++; if(Math.abs(currentLightness - lastLightness) < this.threshold){ similarColorStreak++; if(similarColorStreak === similarColorStreakThreshold){ distances[direction] -= (similarColorStreakThreshold+1); boundaryFound = true; } } else { lastLightness = currentLightness; similarColorStreak = 0; } } else { boundaryFound = true; } } } } distances.x = input.x; distances.y = input.y; this.port.postMessage({ type: 'distances', data: distances }); }, getLightnessAt: function(data, x, y){ return this.inBoundaries(x, y) ? data[y * this.width + x] : -1; }, setLightnessAt: function(data, x, y, value){ return this.inBoundaries(x, y) ? data[y * this.width + x] = value : -1; }, // // inBoundaries // ============ // // checks if x and y are in the canvas boundaries // inBoundaries: function(x, y){ if(x >= 0 && x <= this.width && y >= 0 && y <= this.height) return true; else return false; }, // // Grayscale // --------- // // reduces the input image data to an array of gray shades. // grayscale: function(imgData){ var gray = new Int16Array(imgData.length/4); for(var i=0, n=0, l=imgData.length; i<l; i+=4, n++){ var r = imgData[i], g = imgData[i+1], b = imgData[i+2]; // weighted grayscale algorithm gray[n] = Math.round(r * 0.3 + g * 0.59 + b * 0.11); } return gray; }, // // loadImage // --------- // // responsible to load a image and extract the image data // loadImage: function(){ var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); // adjust the canvas size to the image size this.width = canvas.width = this.image.width; this.height = canvas.height = this.image.height; // draw the image to the canvas ctx.drawImage(this.image, 0, 0); // read out the image data from the canvas var imgData = ctx.getImageData(0, 0, this.width, this.height).data; // delete old grayscale data this.data = []; // grayscale the image data this.data = this.grayscale( imgData ); this.takingScreenshot = false; } };
Java
UTF-8
465
1.976563
2
[ "Apache-2.0" ]
permissive
package com.sctt.cinema.api.business.entity.response; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; @Data @AllArgsConstructor @NoArgsConstructor public class SeatStatusDTO implements Serializable { // ma ghe, vd A1...H1... public String seatCode; // loai ghe // 1 - normal // 2 - vip public int seatType; // 0 - empty // 1 - booked public int status; }
Markdown
UTF-8
5,963
3.71875
4
[]
no_license
## 对 PHP 中依赖注入和控制反转的理解 来源:<https://juejin.im/post/5b430952f265da0f66400a28> 时间:2018年07月09日 ## 术语介绍 ### IoC * 控制反转(Inversion of Control) * 依赖关系的转移 * 依赖抽象而非实践 ### DI * 依赖注入(Dependency Injection) * 不必自己在代码中维护对象的依赖 * 容器自动根据配置,将依赖注入指定对象 ### AOP * Aspect-oriented programming ### 面向方面编程 * 无需修改任何一行程序代码,将功能加入至原先的应用程序中,也可以在不修改任何程序的情况下移除 ## 提出需求 某地区有各种不同的商店,每家商店都卖四种水果:苹果十元一个、香蕉二十元一个、橘子三十元一个、西瓜四十元一个,顾客可以在任意商店进行购买,每家商店需要可以随时向税务局提供总销售额。 ### 初步代码实现 ```php class Shop { // 商店的名字 private $name; // 商店的总销售额 private $turnover = 0; public function __construct($name){ $this->name = $name; } // 售卖商品 public function sell($commodity){ switch ($commodity){ case 'apple': $this->turnover += 10; echo "卖出一个苹果<br/>"; break; case 'banana': $this->turnover += 20; echo "卖出一个香蕉<br/>"; break; case 'orange': $this->turnover += 30; echo "卖出一个橘子<br/>"; break; case 'watermelon': $this->turnover += 40; echo "卖出一个西瓜<br/>"; break; } } // 显示商店目前的总销售额 public function getTurnover(){ echo $this->name.'目前为止的销售额为:'.$this->turnover; } } // 顾客类 class Human { //从商店购买商品 public function buy(Shop $shop,$commodity){ $shop->sell($commodity); } } // new一个名为kfc的商店 $kfc = new Shop('kfc'); // new一个名为mike的顾客 $mike = new Human(); // mike从kfc买了一个苹果 $mike->buy($kfc,'apple'); // mike从kfc买了一个香蕉 $mike->buy($kfc,'banana'); // 输出kfc的总营业额 echo $kfc->getTurnover(); ``` 可以看到,虽然代码完成了对目前需求的实现,但是此时的 **`shell()`** 方法依赖于具体的实践并且拥有绝对的控制权。一旦我们需要在商店加入一个新的商品,比如芒果mango,那我们不得不去修改商店类的 **`sell()`** 方法,违反了 **`OCP`** 原则,即 **`对扩展开放,对修改关闭`** 。 此时我们可以修改代码如下 ```php abstract class Fruit { public $name; public $price; } class Shop { //商店的名字 private $name; //商店的总销售额 private $turnover = 0; public function __construct($name){ $this->name = $name; } //售卖商品 public function sell(Fruit $commodity){ $this->turnover += $commodity->price; echo '卖出一个'.$commodity->name.',收入'.$commodity->price."元<br/>"; } //显示商店目前的总销售额 public function getTurnover(){ echo $this->name.'目前为止的销售额为:'.$this->turnover; } } //顾客类 class Human { //从商店购买商品 public function buy(Shop $shop,$commodity){ $shop->sell($commodity); } } class Apple extends Fruit { public $name = 'apple'; public $price = 10; } class Bananae extends Fruit { public $name = 'banana'; public $price = 20; } class Orange extends Fruit { public $name = 'orange'; public $price = 30; } class Watermelon extends Fruit { public $name = 'watermelon'; public $price = 40; } //new一个名为kfc的商店 $kfc = new Shop('kfc'); //new一个名为mike的顾客 $mike = new Human(); //mike从kfc买了一个苹果 $mike->buy($kfc,new Apple()); //mike从kfc买了一个香蕉 $mike->buy($kfc,new Bananae()); //输出kfc的总营业额 echo $kfc->getTurnover(); ``` 上面的代码增加了一个名为 **`Fruit`** 的抽象类,所有的水果都独立成不同的继承了 **`Fruit`** 的类,此时 **`sell()`** 方法不再依赖具体的水果名,而是依赖于抽象的 **`Fruit`** 类,决定卖了多少钱的控制权不再包含在方法内,而是由方法外传入,这就是 **`控制反转`** ,而实现控制反转的过程就是 **`依赖注入`** 。 ### 为什么需要依赖注入? 可以发现,此时,如果我们突然想要给所有的商店加入一样名为芒果的商品,我们无需去修改高层(Shop类)的代码,我们只需要添加如下代码即可 ```php class Lemon extends Fruit { public $name = 'Lemon'; public $price = 50; } ``` 购买柠檬: ```php $mike->buy($kfc,new Lemon()); ``` 同样如果我们需要删除某样商品(功能),我们只需要删除对应类的代码就可以了。这样就实现了 **`OCP`** 原则,使代码的扩展和维护都变得更为简单。 ### 相关文章链接: * [依赖注入那些事][0] * [PHP程序员如何理解IoC/DI][1] [0]: https://link.juejin.im?target=http%3A%2F%2Fwww.cnblogs.com%2Fleoo2sk%2Farchive%2F2009%2F06%2F17%2F1504693.html [1]: https://link.juejin.im?target=https%3A%2F%2Fsegmentfault.com%2Fa%2F1190000002411255
Python
UTF-8
721
2.609375
3
[]
no_license
from typing import Union from .abstract import AbstractAsyncCachingBackend import aioredis class AsyncRedisCachingBackend(AbstractAsyncCachingBackend): def __init__(self, redis_host): self.redis_host = redis_host async def get(self, key: Union[str, int]): redis = await aioredis.create_redis(self.redis_host, encoding="utf-8") value = await redis.get(key, encoding="utf-8") redis.close() return value async def set(self, key: Union[str, int], value: Union[str, int], expire_milliseconds: int = 60): redis = await aioredis.create_redis(self.redis_host, encoding="utf-8") await redis.set(key, value, expire=expire_milliseconds) redis.close()
C++
UTF-8
2,178
3.78125
4
[]
no_license
/* You are given an integer array rolls of length n and an integer k. You roll a k sided dice numbered from 1 to k, n times, where the result of the ith roll is rolls[i]. Return the length of the shortest sequence of rolls that cannot be taken from rolls. A sequence of rolls of length len is the result of rolling a k sided dice len times. Note that the sequence taken does not have to be consecutive as long as it is in order. Example 1: Input: rolls = [4,2,1,2,3,3,2,4,1], k = 4 Output: 3 Explanation: Every sequence of rolls of length 1, [1], [2], [3], [4], can be taken from rolls. Every sequence of rolls of length 2, [1, 1], [1, 2], ..., [4, 4], can be taken from rolls. The sequence [1, 4, 2] cannot be taken from rolls, so we return 3. Note that there are other sequences that cannot be taken from rolls. Example 2: Input: rolls = [1,1,2,2], k = 2 Output: 2 Explanation: Every sequence of rolls of length 1, [1], [2], can be taken from rolls. The sequence [2, 1] cannot be taken from rolls, so we return 2. Note that there are other sequences that cannot be taken from rolls but [2, 1] is the shortest. Example 3: Input: rolls = [1,1,3,2,2,2,3,3], k = 4 Output: 1 Explanation: The sequence [4] cannot be taken from rolls, so we return 1. Note that there are other sequences that cannot be taken from rolls but [4] is the shortest. Constraints: n == rolls.length 1 <= n <= 105 1 <= rolls[i] <= k <= 105 */ #define c11 #include"head.h" class Solution { public: int shortestSequence(vector<int>& rolls, int k) { unordered_set<int> cnt; int res=1; for(int i=0;i<rolls.size();i++) { if(cnt.size()==k) { cnt.clear(); res++; } cnt.insert(rolls[i]); } if(cnt.size()==k) res++; return res; } }; int main() { Solution s; vector<int> v={4,2,1,2,3,3,2,4,1}; cout<<s.shortestSequence(v,4)<<endl; v.clear();v={1,1,2,2}; cout<<s.shortestSequence(v,2)<<endl; v.clear();v={1,1,3,2,2,2,3,3}; cout<<s.shortestSequence(v,4)<<endl; return 0; }
C++
UTF-8
1,529
3.171875
3
[]
no_license
int DIRECTIONA = 4; int MOTORA = 5; int DIRECTIONB = 7; int MOTORB = 6; void setup () { pinMode(MOTORA, OUTPUT); pinMode(DIRECTIONA, OUTPUT); pinMode(MOTORB, OUTPUT); pinMode(DIRECTIONB, OUTPUT); } ​ int phase = 0; int timeToGo; unsigned long startTime; void loop () { ​// Defining speed 120. analogWrite(MOTORA, 120); analogWrite(MOTORB, 120); // Moving to some direction with some speed, which were defined previously, until timeout. startTime = millis(); while (millis() - startTime < timeToGo) { // Check current drain (consumption). // If current is too high - break. if (analogRead(A0) > 325) // > 1.46 amps break; } // Move forwards. if (phase == 0) { digitalWrite(DIRECTIONA, 1); digitalWrite(DIRECTIONB, 1); timeToGo = 1500; phase = 1; } // Move backwards. else if (phase == 1) { digitalWrite(DIRECTIONA, 0); digitalWrite(DIRECTIONB, 0); timeToGo = 1500; phase = 2; } // Move left. else if (phase == 2) { digitalWrite(DIRECTIONA, 1); digitalWrite(DIRECTIONB, 0); timeToGo = 2200; phase = 3; } // Move right. else { digitalWrite(DIRECTIONA, 0); digitalWrite(DIRECTIONB, 1); timeToGo = 2200; phase = 0; } // Defining speed 0. analogWrite(MOTORA, 0); analogWrite(MOTORB, 0); }
Java
UTF-8
3,489
2.34375
2
[]
no_license
package tn.esprit.pidev.services; import com.codename1.io.*; import com.codename1.ui.events.ActionListener; import tn.esprit.pidev.entities.Event; import tn.esprit.pidev.utils.Database; import tn.esprit.pidev.utils.LoginSession; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; public class EventService { public ArrayList<Event> eventArrayList; public Event event = new Event(); public static EventService instance = null; public boolean resultOK; private ConnectionRequest connectionRequest; public EventService() { connectionRequest = new ConnectionRequest(); } public static EventService getInstance() { if (instance == null) { instance = new EventService(); } return instance; } public ArrayList<Event> parseEvent(String jsonText) { try { eventArrayList = new ArrayList<>(); JSONParser j = new JSONParser(); Map<String, Object> eventListJson = j.parseJSON(new CharArrayReader(jsonText.toCharArray())); List<Map<String, Object>> list = (List<Map<String, Object>>) eventListJson.get("root"); for (Map<String, Object> obj : list) { Event event = new Event(); event.setCategory(obj.get("categorie").toString()); event.setPrix(Float.parseFloat(obj.get("prix").toString())); event.setId((int) Float.parseFloat(obj.get("id").toString())); event.setDate(obj.get("date").toString()); event.setDescription(obj.get("description").toString()); event.setPlaces((int) Float.parseFloat(obj.get("nombrePlace").toString())); event.setTitre(obj.get("title").toString()); event.setLocalisation(obj.get("localisation").toString()); eventArrayList.add(event); } } catch (IOException ex) { } return eventArrayList; } public ArrayList<Event> showAll() { String url = Database.BASE_URL + "evenements/showevent"; // Add Symfony URL Here connectionRequest.setUrl(url); connectionRequest.setPost(false); connectionRequest.addResponseListener(new ActionListener<NetworkEvent>() { @Override public void actionPerformed(NetworkEvent evt) { eventArrayList = parseEvent(new String(connectionRequest.getResponseData())); connectionRequest.removeResponseListener(this); } }); NetworkManager.getInstance().addToQueueAndWait(connectionRequest); return eventArrayList; } public ArrayList<Event> showMyEvent() { String url = Database.BASE_URL + "evenements/showMyEvent?idUser=" + LoginSession.loggedUser; // Add Symfony URL Here connectionRequest.setUrl(url); connectionRequest.setPost(false); connectionRequest.addResponseListener(new ActionListener<NetworkEvent>() { @Override public void actionPerformed(NetworkEvent evt) { eventArrayList = parseEvent(new String(connectionRequest.getResponseData())); connectionRequest.removeResponseListener(this); } }); NetworkManager.getInstance().addToQueueAndWait(connectionRequest); return eventArrayList; } public void reserver(Event event) { } public void annuler(Event event) { } }
Markdown
UTF-8
2,268
3.03125
3
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
--- unique-page-id: 1146897 description: Delete People in a Smart List or List - Marketo Docs - Product Documentation title: Delete People in a Smart List or List exl-id: 192e79e6-d816-44e3-84c4-212cd73eb3ce --- # Delete People in a Smart List or List {#delete-people-in-a-smart-list-or-list} You can quickly and easily delete some/all people that are in a list or a smart list. >[!PREREQUISITES] > >[Create a Smart List](/help/marketo/product-docs/core-marketo-concepts/smart-lists-and-static-lists/creating-a-smart-list/create-a-smart-list.md) 1. Go to **Marketing Activities**. ![](assets/ma-1.png) 1. Select the list/smart list that contains all people you want to delete and go to the **People** tab. ![](assets/two-1.png) >[!CAUTION] > >When you delete a person, you are not just removing them from the list - they will be completely removed from the database. 1. Click **Select All**. You can also hand pick a few records by using Ctrl/Cmd and clicking. ![](assets/three-1.png) >[!NOTE] > >If the results span over multiple pages, clicking **Select All** will select all people across all pages. 1. To completely remove the people from Marketo, click **Delete Person**. ![](assets/four-1.png) 1. Set **Remove from CRM** to **true** if you want to delete the records from your CRM as well. ![](assets/five.png) >[!CAUTION] > >Deleting from Marketo and your CRM means you will never be able to recover in either system. The people and their histories will be gone forever. If you add them back later, they will be treated as brand new records. >[!NOTE] > >If your Marketo is not tied to your CRM the option is grayed out like in the screenshot. 1. Click **Run Now**. ![](assets/image2014-9-24-13-3a0-3a3.png) 1. If you are deleting more than 50 people you will see this. Type the number of people you're deleting, check the **Cannot Undo** box, then click **Delete**. ![](assets/seven.png) >[!NOTE] > >To view the results of the mass deletion, click **View Results** in the Single Flow Action pop-up box in the upper-right corner of the screen. Deletion times can vary greatly, depending on multiple factors. This is a great feature, just be really careful when using it!
C
UTF-8
3,665
2.578125
3
[]
no_license
#include <avr/io.h> #include <util/delay.h> #include "usb_gamepad.h" /* #define LED_CONFIG (DDRD |= (1<<6)) #define LED_OFF (PORTD &= ~(1<<6)) #define LED_ON (PORTD |= (1<<6)) */ #define CPU_PRESCALE(n) (CLKPR = 0x80, CLKPR = (n)) #define BTN_CROSS (1 << 0) #define BTN_SQUARE (1 << 1) #define BTN_TRIANGLE (1 << 2) #define BTN_CIRCLE (1 << 3) #define BTN_R1 (1 << 4) #define BTN_R2 (1 << 5) #define BTN_L1 (1 << 6) #define BTN_L2 (1 << 7) #define PORT1 PORTB #define PORT1_PINS (BTN_CROSS | BTN_SQUARE | BTN_TRIANGLE | BTN_CIRCLE | BTN_R1 | BTN_R2 | BTN_L1 | BTN_L2) #define BTN_CROSS_ON (PINB & BTN_CROSS) == 0 #define BTN_SQUARE_ON (PINB & BTN_SQUARE) == 0 #define BTN_TRIANGLE_ON (PINB & BTN_TRIANGLE) == 0 #define BTN_CIRCLE_ON (PINB & BTN_CIRCLE) == 0 #define BTN_R1_ON (PINB & BTN_R1) == 0 #define BTN_R2_ON (PINB & BTN_R2) == 0 #define BTN_L1_ON (PINB & BTN_L1) == 0 #define BTN_L2_ON (PINB & BTN_L2) == 0 #define JOYSTICK_RIGHT (1 << 0) #define JOYSTICK_LEFT (1 << 1) #define JOYSTICK_UP (1 << 2) #define JOYSTICK_DOWN (1 << 3) #define BTN_START (1 << 4) #define BTN_SELECT (1 << 5) #define BTN_PS (1 << 7) #define PORT2 PORTD #define PORT2_PINS (JOYSTICK_LEFT | JOYSTICK_RIGHT | JOYSTICK_UP | JOYSTICK_DOWN | BTN_START | BTN_SELECT | BTN_PS) #define JOYSTICK_RIGHT_ON (PIND & JOYSTICK_RIGHT) == 0 #define JOYSTICK_LEFT_ON (PIND & JOYSTICK_LEFT) == 0 #define JOYSTICK_UP_ON (PIND & JOYSTICK_UP) == 0 #define JOYSTICK_DOWN_ON (PIND & JOYSTICK_DOWN) == 0 #define BTN_START_ON (PIND & BTN_START) == 0 #define BTN_SELECT_ON (PIND & BTN_SELECT) == 0 #define BTN_PS_ON (PIND & BTN_PS) == 0 int main(void) { // set for 16 MHz clock CPU_PRESCALE(0); // enable pull-ups on button & joystick pins PORT1 = PORT1_PINS; PORT2 = PORT2_PINS; /* LED_CONFIG; LED_ON; // power up led on startup for 1 sec */ // Initialize the USB, and then wait for the host to set configuration. // If the Teensy is powered without a PC connected to the USB port, // this will wait forever. usb_init(); while (!usb_configured()) /* wait */ ; // Wait an extra second for the PC's operating system to load drivers // and do whatever it does to actually be ready for input _delay_ms(1000); //LED_OFF; while (1) { usb_gamepad_reset_state(); if (JOYSTICK_UP_ON) { gamepad_state.direction = 0; if (JOYSTICK_LEFT_ON){gamepad_state.direction = 7;} else if (JOYSTICK_RIGHT_ON) {gamepad_state.direction = 1;} } else { if (JOYSTICK_DOWN_ON) { gamepad_state.direction = 4; if (JOYSTICK_LEFT_ON) {gamepad_state.direction = 5;} else if (JOYSTICK_RIGHT_ON) {gamepad_state.direction = 3;} } else { if (JOYSTICK_LEFT_ON) {gamepad_state.direction = 6;} else if (JOYSTICK_RIGHT_ON) {gamepad_state.direction = 2;} } } if (BTN_CROSS_ON) {gamepad_state.cross_btn = 1;gamepad_state.cross_axis = 0xff;} if (BTN_SQUARE_ON) {gamepad_state.square_btn = 1;gamepad_state.square_axis = 0xff;} if (BTN_TRIANGLE_ON) {gamepad_state.triangle_btn = 1;gamepad_state.triangle_axis = 0xff;} if (BTN_CIRCLE_ON) {gamepad_state.circle_btn = 1;gamepad_state.circle_axis = 0xff;} if (BTN_R1_ON) {gamepad_state.r1_btn = 1;gamepad_state.r1_axis = 0xff;} if (BTN_R2_ON) {gamepad_state.r2_btn = 1;gamepad_state.r2_axis = 0xff;} if (BTN_L1_ON) {gamepad_state.l1_btn = 1;gamepad_state.l1_axis = 0xff;} if (BTN_L2_ON) {gamepad_state.l2_btn = 1;gamepad_state.l2_axis = 0xff;} if (BTN_START_ON) {gamepad_state.start_btn = 1;} if (BTN_SELECT_ON) {gamepad_state.select_btn = 1;} if (BTN_PS_ON) {gamepad_state.ps_btn = 1;} usb_gamepad_send(); } }
Java
UTF-8
3,952
2.453125
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* Copyright 2011-2016 Google Inc. 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 com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.DragAndDrop; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; import com.google.common.base.Preconditions; import com.google.security.zynamics.binnavi.CUtilityFunctions; import com.google.security.zynamics.binnavi.Gui.DragAndDrop.IDropHandler; import com.google.security.zynamics.zylib.gui.dndtree.DNDTree; /** * Abstract base class for drag & drop handlers. */ public abstract class CAbstractDropHandler implements IDropHandler { /** * The data flavor supported by this handler. */ private final DataFlavor m_flavor; /** * Creates a new drag & drop handler. * * @param flavor The data flavor supported by this handler. */ protected CAbstractDropHandler(final DataFlavor flavor) { m_flavor = Preconditions.checkNotNull(flavor, "IE01925: Flavor argument can not be null"); } /** * Retrieves the dragged object from a Transferable object. * * @param transferable The transferable object. * * @return The dragged object or null if the dragged object could not be retrieved. */ private Object getData(final Transferable transferable) { try { return transferable.getTransferData(m_flavor); } catch (UnsupportedFlavorException | IOException exception) { CUtilityFunctions.logException(exception); return null; } } /** * Asks the implementing subclasses whether they can handle drag & drop events with the given * parent node and the given dragged object. * * @param parentNode The parent node the object is dragged on. * @param data The object that is dragged onto the node. * * @return True, to signal that the handler can handle the event. False, otherwise. */ protected abstract boolean canHandle(DefaultMutableTreeNode parentNode, Object data); /** * Asks the implementing subclass to execute a drag & drop event. It is guaranteed that this * method is only called if the canHandle method returned true for the given arguments previously. * * @param parentNode The parent node the object is dragged on. * @param data The object that is dragged onto the node. */ protected abstract void drop(DefaultMutableTreeNode parentNode, Object data); @Override public boolean canHandle(final DNDTree target, final Transferable transferable, final DataFlavor flavor, final int x, final int y) { if (!transferable.isDataFlavorSupported(m_flavor)) { return false; } final Object data = getData(transferable); if (data == null) { return false; } final TreePath pathTarget = target.getPathForLocation(x, y); if (pathTarget == null) { target.setSelectionPath(null); return false; } return canHandle((DefaultMutableTreeNode) pathTarget.getLastPathComponent(), data); } @Override public void drop(final Transferable transferable, final DefaultMutableTreeNode parentNode) { if (!transferable.isDataFlavorSupported(m_flavor)) { return; } final Object data = getData(transferable); if (data == null) { return; } drop(parentNode, data); } }
C++
UTF-8
568
2.578125
3
[]
no_license
#include <pix5.h> #include "elfgui5.h" //constructor Anchor::Anchor(bool t,int ty,bool b,int by,bool l,int lx,bool r,int rx) { top=t; bottom=b; left=l; right=r; top_y=ty; bottom_y=by; left_x=lx; right_x=rx; } //SET void Anchor::set(bool t,int ty,bool b,int by,bool l,int lx,bool r,int rx) { top=t; bottom=b; left=l; right=r; top_y=ty; bottom_y=by; left_x=lx; right_x=rx; } //IS NONE bool Anchor::is_none() { return (!top && !bottom && !left && !right); } //IS ALL bool Anchor::is_all() { return (top && bottom && left && right); }
PHP
UTF-8
559
2.546875
3
[]
no_license
<?php /** * Created by PhpStorm. * User: dokuen * Date: 29.09.15 * Time: 11:49 */ namespace Application\Model; class Post { public $id_post; public $idUser; public $comment; public $urlImg; function exchangeArray($data) { $this->id_post = isset($data['id_post']) ? $data['id_post'] : null; $this->idUser = isset($data['idUser']) ? $data['idUser'] : null; $this->comment = isset($data['comment']) ? $data['comment'] : null; $this->urlImg = isset($data['urlImg']) ? $data['urlImg'] : null; } }
Python
UTF-8
11,291
2.828125
3
[]
no_license
import class_Point as cP def intersection(l1, l2): x1, y1 = l1.ipt.x_cor, l1.ipt.y_cor x2, y2 = l1.fpt.x_cor, l1.fpt.y_cor x3, y3 = l2.ipt.x_cor, l2.ipt.y_cor x4, y4 = l2.fpt.x_cor, l2.fpt.y_cor denominator = round(((x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)), 2) x_temp = round(((x1 * y2 - x2 * y1) * (x3 - x4) - (x1 - x2) * (x3 * y4 - x4 * y3)), 2) y_temp = round(((x1 * y2 - x2 * y1) * (y3 - y4) - (y1 - y2) * (x3 * y4 - x4 * y3)), 2) if denominator != 0: x_value = round(((x1 * y2 - x2 * y1) * (x3 - x4) - (x1 - x2) * (x3 * y4 - x4 * y3)) / denominator, 2) y_value = round(((x1 * y2 - x2 * y1) * (y3 - y4) - (y1 - y2) * (x3 * y4 - x4 * y3)) / denominator, 2) if x1 >= x2: c_x_l1 = (x1 >= x_value) and (x_value >= x2) else: c_x_l1 = (x2 >= x_value) and (x_value >= x1) if y1 >= y2: c_y_l1 = (y1 >= y_value) and (y_value >= y2) else: c_y_l1 = (y2 >= y_value) and (y_value >= y1) c_l1 = c_x_l1 and c_y_l1 if x3 >= x4: c_x_l2 = (x3 >= x_value) and (x_value >= x4) else: c_x_l2 = (x4 >= x_value) and (x_value >= x3) if y3 >= y4: c_y_l2 = (y3 >= y_value) and (y_value >= y4) else: c_y_l2 = (y4 >= y_value) and (y_value >= y3) c_l2 = c_x_l2 and c_y_l2 if c_l1 and c_l2: return cP.Point(x_value, y_value), 0 # perfect intersection else: return cP.Point(None, None), 1 # intersection on extension else: # parallel lines if x_temp == 0 and y_temp == 0: c1 = x1 == x2 and y1 == y2 c2 = x3 == x4 and y3 == y4 if c1 or c2: # either of them is point, complete case return cP.Point(None, None), 2 else: cx1 = x1 < x4 and x1 < x3 and x2 < x4 and x2 < x3 # (x1x2)...(x3x4) in any order within same line cx2 = x1 > x4 and x1 > x3 and x2 > x4 and x2 > x3 # x3x4...x1x2, in any order within same line cy1 = y1 < y4 and y1 < y3 and y2 < y4 and y2 < y3 cy2 = y1 > y4 and y1 > y3 and y2 > y4 and y2 > y3 if cx1 or cx2 or cy1 or cy2: # non overlapping lines, same line (complete case) return cP.Point(None, None), 3 else: cx1 = x1 < x3 and x3 < x2 and x1 < x4 and x4 < x2 # x1 (x3/x4) x2 cx2 = x2 < x3 and x3 < x1 and x2 < x4 and x4 < x1 # x2 (x3/x4) x1 cx3 = x3 < x1 and x1 < x4 and x3 < x2 and x2 < x4 # x3 (x1/x2) x4 cx4 = x4 < x1 and x1 < x3 and x4 < x2 and x2 < x3 # x4 (x1/x2) x4 cy1 = y1 < y3 and y3 < y2 and y1 < y4 and y4 < y2 cy2 = y2 < y3 and y3 < y1 and y2 < y4 and y4 < y1 cy3 = y3 < y1 and y1 < y4 and y3 < y2 and y2 < y4 cy4 = y4 < y1 and y1 < y3 and y4 < y2 and y2 < y3 c1 = cx1 or cx2 or cx3 or cx4 c2 = cy1 or cy2 or cy3 or cy4 if c1 or c2: # one line is completely within the other, same line complete case return cP.Point(None, None), 4 else: cx1 = x1 < x3 and x1 < x4 and x3 < x2 and x2 < x4 # x1, x3, x2, x4 cx2 = x1 < x4 and x1 < x3 and x4 < x2 and x2 < x3 # x1, x4, x2, x3 cx3 = x2 < x3 and x2 < x4 and x3 < x1 and x1 < x4 # x2, x3, x1, x4 cx4 = x2 < x4 and x2 < x3 and x4 < x1 and x1 < x3 # x2, x4, x1, x3 cx5 = x3 < x1 and x3 < x2 and x1 < x4 and x4 < x2 # x3, x1, x4, x2 cx6 = x3 < x2 and x3 < x1 and x2 < x4 and x4 < x1 # x3, x2, x4, x1 cx7 = x4 < x1 and x4 < x2 and x1 < x3 and x3 < x2 # x4, x1, x3, x2 cx8 = x4 < x2 and x4 < x1 and x2 < x3 and x3 < x1 # x4, x2, x3, x1 cy1 = y1 < y3 and y1 < y4 and y3 < y2 and y2 < y4 # x1, x3, x2, x4 cy2 = y1 < y4 and y1 < y3 and y4 < y2 and y2 < y3 # x1, x4, x2, x3 cy3 = y2 < y3 and y2 < y4 and y3 < y1 and y1 < y4 # x2, x3, x1, x4 cy4 = y2 < y4 and y2 < y3 and y4 < y1 and y1 < y3 # x2, x4, x1, x3 cy5 = y3 < y1 and y3 < y2 and y1 < y4 and y4 < y2 # x3, x1, x4, x2 cy6 = y3 < y2 and y3 < y1 and y2 < y4 and y4 < y1 # x3, x2, x4, x1 cy7 = y4 < y1 and y4 < y2 and y1 < y3 and y3 < y2 # x4, x1, x3, x2 cy8 = y4 < y2 and y4 < y1 and y2 < y3 and y3 < y1 # x4, x2, x3, x1 c1 = cx1 or cx2 or cx3 or cx4 or cx5 or cx6 or cx7 or cx8 c2 = cy1 or cy2 or cy3 or cy4 or cy5 or cy6 or cy7 or cy8 if c1 or c2: # overlapping at one end , same line, complete case return cP.Point(None, None), 5 else: cx1 = x1 < x3 and x1 < x4 and x3 == x2 and x2 < x4 # x1, x3, x2, x4 cx2 = x1 < x4 and x1 < x3 and x4 == x2 and x2 < x3 # x1, x4, x2, x3 cx3 = x2 < x3 and x2 < x4 and x3 == x1 and x1 < x4 # x2, x3, x1, x4 cx4 = x2 < x4 and x2 < x3 and x4 == x1 and x1 < x3 # x2, x4, x1, x3 cx5 = x3 < x1 and x3 < x2 and x1 == x4 and x4 < x2 # x3, x1, x4, x2 cx6 = x3 < x2 and x3 < x1 and x2 == x4 and x4 < x1 # x3, x2, x4, x1 cx7 = x4 < x1 and x4 < x2 and x1 == x3 and x3 < x2 # x4, x1, x3, x2 cx8 = x4 < x2 and x4 < x1 and x2 == x3 and x3 < x1 # x4, x2, x3, x1 cy1 = y1 < y3 and y1 < y4 and y3 == y2 and y2 < y4 # x1, x3, x2, x4 cy2 = y1 < y4 and y1 < y3 and y4 == y2 and y2 < y3 # x1, x4, x2, x3 cy3 = y2 < y3 and y2 < y4 and y3 == y1 and y1 < y4 # x2, x3, x1, x4 cy4 = y2 < y4 and y2 < y3 and y4 == y1 and y1 < y3 # x2, x4, x1, x3 cy5 = y3 < y1 and y3 < y2 and y1 == y4 and y4 < y2 # x3, x1, x4, x2 cy6 = y3 < y2 and y3 < y1 and y2 == y4 and y4 < y1 # x3, x2, x4, x1 cy7 = y4 < y1 and y4 < y2 and y1 == y3 and y3 < y2 # x4, x1, x3, x2 cy8 = y4 < y2 and y4 < y1 and y2 == y3 and y3 < y1 # x4, x2, x3, x1 c1 = cx1 or cx2 or cx3 or cx4 or cx5 or cx6 or cx7 or cx8 c2 = cy1 or cy2 or cy3 or cy4 or cy5 or cy6 or cy7 or cy8 if c1 or c2: # overlapping at one end , same line, complete case return cP.Point(None, None), 6 else: cx1 = x1 < x3 and x1 < x4 and x3 < x2 and x2 == x4 # x1, x3, x2, x4 cx2 = x1 < x4 and x1 < x3 and x4 < x2 and x2 == x3 # x1, x4, x2, x3 cx3 = x2 < x3 and x2 < x4 and x3 < x1 and x1 == x4 # x2, x3, x1, x4 cx4 = x2 < x4 and x2 < x3 and x4 < x1 and x1 == x3 # x2, x4, x1, x3 cx5 = x3 < x1 and x3 < x2 and x1 < x4 and x4 == x2 # x3, x1, x4, x2 cx6 = x3 < x2 and x3 < x1 and x2 < x4 and x4 == x1 # x3, x2, x4, x1 cx7 = x4 < x1 and x4 < x2 and x1 < x3 and x3 == x2 # x4, x1, x3, x2 cx8 = x4 < x2 and x4 < x1 and x2 < x3 and x3 == x1 # x4, x2, x3, x1 cy1 = y1 < y3 and y1 < y4 and y3 < y2 and y2 == y4 # x1, x3, x2, x4 cy2 = y1 < y4 and y1 < y3 and y4 < y2 and y2 == y3 # x1, x4, x2, x3 cy3 = y2 < y3 and y2 < y4 and y3 < y1 and y1 == y4 # x2, x3, x1, x4 cy4 = y2 < y4 and y2 < y3 and y4 < y1 and y1 == y3 # x2, x4, x1, x3 cy5 = y3 < y1 and y3 < y2 and y1 < y4 and y4 == y2 # x3, x1, x4, x2 cy6 = y3 < y2 and y3 < y1 and y2 < y4 and y4 == y1 # x3, x2, x4, x1 cy7 = y4 < y1 and y4 < y2 and y1 < y3 and y3 == y2 # x4, x1, x3, x2 cy8 = y4 < y2 and y4 < y1 and y2 < y3 and y3 == y1 # x4, x2, x3, x1 c1 = cx1 or cx2 or cx3 or cx4 or cx5 or cx6 or cx7 or cx8 c2 = cy1 or cy2 or cy3 or cy4 or cy5 or cy6 or cy7 or cy8 if c1 or c2: # overlapping at right end , same line, complete case return cP.Point(None, None), 7 else: cx1 = x1 == x3 and x1 < x4 and x3 < x2 and x2 > x4 # x1, x3, x4, x2 cx2 = x1 == x4 and x1 < x3 and x4 < x2 and x2 > x3 # x1, x4, x3, x2 cx3 = x2 == x3 and x2 < x4 and x3 < x1 and x1 > x4 # x2, x3, x4, x1 cx4 = x2 == x4 and x2 < x3 and x4 < x1 and x1 > x3 # x2, x4, x3, x1 cx5 = x3 == x1 and x3 < x2 and x1 < x4 and x4 > x2 # x3, x1, x2, x4 cx6 = x3 == x2 and x3 < x1 and x2 < x4 and x4 > x1 # x3, x2, x1, x4 cx7 = x4 == x1 and x4 < x2 and x1 < x3 and x3 > x2 # x4, x1, x2, x3 cx8 = x4 == x2 and x4 < x1 and x2 < x3 and x3 > x1 # x4, x2, x1, x3 cy1 = y1 == y3 and y1 < y4 and y3 < y2 and y2 > y4 # x1, x3, x2, x4 cy2 = y1 == y4 and y1 < y3 and y4 < y2 and y2 > y3 # x1, x4, x2, x3 cy3 = y2 == y3 and y2 < y4 and y3 < y1 and y1 > y4 # x2, x3, x1, x4 cy4 = y2 == y4 and y2 < y3 and y4 < y1 and y1 > y3 # x2, x4, x1, x3 cy5 = y3 == y1 and y3 < y2 and y1 < y4 and y4 > y2 # x3, x1, x4, x2 cy6 = y3 == y2 and y3 < y1 and y2 < y4 and y4 > y1 # x3, x2, x4, x1 cy7 = y4 == y1 and y4 < y2 and y1 < y3 and y3 > y2 # x4, x1, x3, x2 cy8 = y4 == y2 and y4 < y1 and y2 < y3 and y3 > y1 # x4, x2, x3, x1 c1 = cx1 or cx2 or cx3 or cx4 or cx5 or cx6 or cx7 or cx8 c2 = cy1 or cy2 or cy3 or cy4 or cy5 or cy6 or cy7 or cy8 if c1 or c2: # overlapping at left end , same line, complete case return cP.Point(None, None), 8 else: return cP.Point(None, None), 9 else: return cP.Point(None, None), 10 # parallel lines with distance in between
Java
UTF-8
1,301
2.890625
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain", "CC0-1.0", "BSD-2-Clause" ]
permissive
package com.spacetimecat.java.lang.unexceptional; import java.util.function.Function; import java.util.function.Supplier; public final class Ok<A> extends Risky<A> { private final A value; public Ok (A value) { if (value == null) { throw new NullPointerException("value"); } this.value = value; } @Override public boolean isOk () { return true; } @Override public <B> Risky<B> then (Function<A, Risky<B>> function) { return function.apply(value); } @Override public <B> B fold (Function<Throwable, B> ifFail, Function<A, B> ifOk) { return ifOk.apply(value); } @Override public A getValueOr (A fallback) { return value; } @Override public A getValueOrGetFrom (Supplier<A> supplier) { return value; } @Override public <B> Risky<B> mapValue (Function<A, B> function) { return new Ok<>(function.apply(value)); } @Override public Risky<A> mapThrowable (Function<Throwable, Throwable> function) { return this; } @Override public Risky<A> ifFailRun (Runnable action) { return this; } @Override public A take () throws Throwable { return value; } }
Python
UTF-8
426
2.921875
3
[]
no_license
""" 线上提交结果recall值及正确数计算 """ value = "10.00000000% 0.09942639" preferenceSet = 517 fscore = float(value.split(sep='% ')[0]) precision = float(value.split(sep='% ')[1]) recall = (fscore * precision / 100) / (2 * precision - fscore / 100) tp = round(preferenceSet * recall) predictionSet = round(tp / precision) print("%.8f%% %.8f %.8f %.0f %.0f" % (fscore, precision, recall, tp, predictionSet))
Shell
UTF-8
3,232
4.0625
4
[ "Apache-2.0" ]
permissive
#!/bin/bash # Script that sets up the docker environment to run the tests in and runs the # tests. # Pass --shell to run a shell in the test container. # Failures should cause setup to fail set -v -e -x # Set PS4 so it's easier to differentiate between this script and run_tests.sh # running PS4="+ (test_env.sh): " DC="$(which docker-compose)" ICHNAEA_UID=${ICHNAEA_UID:-"10001"} ICHNAEA_GID=${ICHNAEA_GID:-"10001"} ICHNAEA_DOCKER_DB_ENGINE=${ICHNAEA_DOCKER_DB_ENGINE:-"mysql_5_7"} # Use the same image we use for building docker images because it's cached. # Otherwise this doesn't make any difference. BASEIMAGENAME="python:3.11.3-slim" TESTIMAGE="local/ichnaea_app" # Start services in background (this is idempotent) echo "Starting services needed by tests in the background..." ${DC} up -d db redis # If we're running a shell, then we start up a test container with . mounted # to /app. if [ "$1" == "--shell" ]; then echo "Running shell..." docker run \ --rm \ --user "${ICHNAEA_UID}" \ --volume "$(pwd)":/app \ --workdir /app \ --network ichnaea_default \ --link ichnaea_db_1 \ --link ichnaea_redis_1 \ --env-file ./docker/config/local_dev.env \ --env-file ./docker/config/test.env \ --tty \ --interactive \ --entrypoint="" \ "${TESTIMAGE}" /bin/bash exit $? fi # Create a data container to hold the repo directory contents and copy the # contents into it--reuse if possible if [ "$(docker container ls --all | grep ichnaea-repo)" == "" ]; then echo "Creating ichnaea-repo container..." docker create \ -v /app \ --user "${ICHNAEA_UID}" \ --name ichnaea-repo \ "${BASEIMAGENAME}" /bin/true fi echo "Copying contents..." # Wipe whatever might be in there from past runs and verify files are gone docker run \ --user root \ --volumes-from ichnaea-repo \ --workdir /app \ --entrypoint="" \ "${TESTIMAGE}" sh -c "rm -rf /app/* && ls -l /app/" # Copy the repo root into /app docker cp . ichnaea-repo:/app # Fix file permissions in data container docker run \ --user root \ --volumes-from ichnaea-repo \ --workdir /app \ --entrypoint="" \ "${TESTIMAGE}" chown -R "${ICHNAEA_UID}:${ICHNAEA_GID}" /app # Check that database server is ready for tests docker run \ --rm \ --user "${ICHNAEA_UID}" \ --volumes-from ichnaea-repo \ --workdir /app \ --network ichnaea_default \ --link ichnaea_db_1 \ --link ichnaea_redis_1 \ --env-file ./docker/config/local_dev.env \ --tty \ --interactive \ --entrypoint= \ "${TESTIMAGE}" /app/docker/run_check_db.sh # Run tests in that environment and then remove the container echo "Running tests..." docker run \ --rm \ --user "${ICHNAEA_UID}" \ --volumes-from ichnaea-repo \ --workdir /app \ --network ichnaea_default \ --link ichnaea_db_1 \ --link ichnaea_redis_1 \ --env-file ./docker/config/local_dev.env \ --env-file ./docker/config/test.env \ --tty \ --interactive \ --entrypoint= \ "${TESTIMAGE}" /app/docker/run_tests.sh "$@" echo "Done!"
Java
UTF-8
242
1.617188
2
[]
no_license
package com.projeto.Transportadora.repositories; import org.springframework.data.jpa.repository.JpaRepository; import com.projeto.Transportadora.entities.Empresa; public interface EmpresaRepository extends JpaRepository<Empresa, Long>{ }
Java
UTF-8
2,918
2.328125
2
[]
no_license
package de.tina; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import de.tina.container.NeuronMatrix; import de.tina.controller.Master; import de.tina.controller.Memory; @RunWith(SpringRunner.class) @SpringBootTest public class MasterTest { @Autowired private Master master; @Autowired private Memory memory; @Before public void setUpBeforeClass() throws Exception { memory.deleteAll(); master.learn("Hallo wie geht es dir?", "Begrüßung"); master.learn("Geht es dir gut?", "Begrüßung"); master.learn("Hallo, ich kündige.", "Kündigung"); master.learn("Hallo, ich möchte kündigen.", "Kündigung"); master.persist(); } @Test public void testTrue() { Map<String, Integer> erg = master.ask("Hallo, ich kündige."); assertTrue(erg.containsKey("Kündigung")); } @Test public void testFalse() { Map<String, Integer> erg = master.ask("Hallo, ich heiße Horst."); assertTrue(erg.size() == 0); assertFalse(erg.containsKey("Kündigung")); assertFalse(erg.containsKey("Begrüßung")); } @Test public void testBegruessung() { memory.deleteAll(); master.learn("Hallo wie geht es dir?", "Begrüßung"); master.learn("Geht es dir gut?", "Begrüßung"); master.persist(); Map<String, NeuronMatrix> knowledge = memory.remember(); assertTrue(knowledge.containsKey("Begrüßung")); assertTrue(knowledge.values().size() == 2); } @Test public void testBegruessungAndKuedigung() { memory.deleteAll(); master.learn("Hallo wie geht es dir?", "Begrüßung"); master.learn("Hallo, ich kündige.", "Kündigung"); master.learn("Hallo, ich möchte kündigen.", "Kündigung"); master.persist(); Map<String, NeuronMatrix> knowledge = memory.remember(); assertTrue(knowledge.containsKey("Begrüßung") && knowledge.containsKey("Kündigung")); assertTrue(knowledge.values().size() == 2); } @Test public void testWithoutFinish() { memory.deleteAll(); master.learn("Hallo wie geht es dir?", "Begrüßung"); master.learn("Hallo, ich kündige.", "Kündigung"); Map<String, NeuronMatrix> knowledge = memory.remember(); assertFalse(knowledge.containsKey("Begrüßung")); assertFalse(knowledge.containsKey("Kündigung")); assertTrue(knowledge.values().size() == 0); } }
PHP
UTF-8
1,197
2.71875
3
[ "BSD-3-Clause" ]
permissive
<?php namespace App\Models; class Setting extends BaseModel { public $table = 'settings'; public $incrementing = false; public $fillable = [ 'name', 'key', 'value', 'group', 'type', 'options', 'description', ]; public static $rules = [ 'name' => 'required', 'key' => 'required', 'group' => 'required', ]; /** * @param $key * @return mixed */ public static function formatKey($key) { return str_replace('.', '_', strtolower($key)); } /** * Callbacks */ protected static function boot() { parent::boot(); static::creating(function (Setting $model) { if (!empty($model->id)) { $model->id = Setting::formatKey($model->id); } }); } /** * Override the casting mechanism * @param string $key * @return mixed|string */ /*protected function getCastType($key) { if ($key === 'value' && !empty($this->type)) { return $this->type; } else { return parent::getCastType($key); } }*/ }
Markdown
UTF-8
1,219
2.640625
3
[]
no_license
--- title: Ennemi imaginaire de Rana tags: - Psychologie --- Lorsque Rana parkourt férocement dans mon appartement où elle devrait bien penser à freiner avant d'accélérer, je me demande parfois si elle a un ennemi imaginaire dans sa tête. [<img src="/assets/images/2021/03/rana.jpg" width="800px" />](https://www.instagram.com/ranafattail/){: .align-center} En tout cas, je sais très bien que mon ennemi imaginaire était toujours moi-même et ma relation avec les autres. Un peu comme Shinji de l'Evangelion, on est à la recherche permanente de rassurances de nos existences en suivant des fausses pistes. M'identifier comme asexuel m'a accordé le droit d'exister. Après une courte renaissance de la liberté l'été dernier, j'ai appris à ranger mes jumelles d'observation et remis ma lettre de démission en tant que *Game master* du jeu de la vie. Savoir ne plus masquer mon bégaiement m'a procuré une confiance d'exister. Je bégaie, donc je suis. Il y a autres choses tellement plus importantes dans la vie que le bégaiement. Maintenant, exister ne suffit plus : il est temps de vivre. Bienvenue à toi, la version 2.1.0 de Tianyi[^1]. [^1]: En suivant la convention `MAJOR.MINOR.PATCH`.
Go
UTF-8
440
3.96875
4
[]
no_license
package main import "fmt" func main() { // 구조체 익명 선언 및 활용 // type 구조체명 타입 car1 := struct {name, color string}{"520d", "red"} fmt.Println("[Example 1] : ", car1) fmt.Printf("[Example 1] : %#v\n", car1) // Example 2 cars := []struct{name, color string}{{"520d", "red"}, {"530i", "white"}, {"528i", "blue"}} for _, c := range cars { fmt.Printf("(%s, %s) ----- (%#v)\n", c.name, c.color, c) } }
Python
UTF-8
2,314
3.6875
4
[]
no_license
import numpy as np def compute_error_for_line_given_points(b, w, points): """ compute the loss function of a linear regression :param b: intersection :param w: gradient :param points: array of points [x_, y_] :return: the average loss of the regression model """ total_loss = 0 for i in range(len(points)): x = points[i, 0] # points[i, 0] = points[i][0] y = points[i, 1] # points[i, 1] = points[i][1] loss = (w * x + b - y) ** 2 total_loss += loss return total_loss / float(len(points)) def step_gradient(b_current, w_current, points, learning_rate): b_gradient = 0 w_gradient = 0 N = float(len(points)) for i in range(len(points)): x = points[i, 0] y = points[i, 1] b_gradient += (2/N) * (w_current * x + b_current - y) w_gradient += (2/N) * (w_current * x + b_current - y) * x b_next = b_current - learning_rate * b_gradient w_next = w_current - learning_rate * w_gradient return b_next, w_next def gradient_descent_runner(points, b_starting, w_starting, learning_rate, num_iterations): """ wrap the step_gradient function in a for loop to continuously compute the b and w :param points: an array of x_ and y_ :param b_starting: :param w_starting: :param learning_rate: :param num_iterations: :return: mature b and w """ b = b_starting w = w_starting for i in range(num_iterations): b, w = step_gradient(b, w, points, learning_rate) return b, w def run(): points = np.genfromtxt("data.csv", delimiter=",") learning_rate = 0.0001 initial_b = 0 # initial y_-intercept guess initial_w = 0 # initial slope guess num_iterations = 100000 print("Starting gradient descent at b = {0}, w = {1}, error = {2}" .format(initial_b, initial_w, compute_error_for_line_given_points(initial_b, initial_w, points)) ) print("Running...") [b, w] = gradient_descent_runner(points, initial_b, initial_w, learning_rate, num_iterations) print("After {0} iterations b = {1}, w = {2}, error = {3}". format(num_iterations, b, w, compute_error_for_line_given_points(b, w, points)) ) if __name__ == '__main__': run()
C++
UTF-8
4,440
2.796875
3
[]
no_license
/* * Copyright (c) 2015 Vrije Universiteit Brussel * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "episode.h" #include <algorithm> #include <numeric> #include <assert.h> template<typename T> void extend(std::vector<T> &dest, const std::vector<T> &src) { // Make room in dest for src std::size_t offset = dest.size(); dest.resize(offset + src.size()); // Append src to dest std::copy(src.begin(), src.end(), dest.begin() + offset); } static void extract(const std::vector<float> &vector, unsigned int size, unsigned int t, std::vector<float> &rs) { rs.resize(size); // Compute the positions between which the desired state values are stored unsigned int from = t * size; unsigned int to = from + size; // Copy the desired values into the output std::copy(vector.begin() + from, vector.begin() + to, rs.begin()); } Episode::Episode(unsigned int value_size, unsigned int num_actions, Encoder encoder) : _encoder(encoder), _state_size(0), _value_size(value_size), _num_actions(num_actions), _aborted(false) { } void Episode::addState(const std::vector<float> &state) { // Update the state size, used to split the values stored in _states by state _state_size = state.size(); extend(_states, state); } void Episode::addValues(const std::vector<float> &values) { assert(values.size() == _value_size); extend(_values, values); } void Episode::addReward(float reward) { _rewards.push_back(reward); } void Episode::addAction(int action) { _actions.push_back(action); } void Episode::setAborted(bool aborted) { _aborted = aborted; } void Episode::copyValues(const Episode &other) { _values = other._values; } void Episode::copyActions(const Episode &other) { _actions = other._actions; } void Episode::copyRewards(const Episode &other) { _rewards = other._rewards; } unsigned int Episode::stateSize() const { return _state_size; } unsigned int Episode::encodedStateSize() const { std::vector<float> state; encodedState(0, state); return state.size(); } unsigned int Episode::valueSize() const { return _value_size; } unsigned int Episode::numActions() const { return _num_actions; } unsigned int Episode::length() const { if (_states.size() == 0) { return 0; } else { return _states.size() / _state_size; } } bool Episode::wasAborted() const { return _aborted; } void Episode::state(unsigned int t, std::vector<float> &rs) const { extract(_states, _state_size, t, rs); } void Episode::encodedState(unsigned int t, std::vector<float> &rs) const { state(t, rs); // Encode the state using the encoder if (_encoder) { _encoder(rs); } } void Episode::values(unsigned int t, std::vector<float> &rs) const { extract(_values, _value_size, t, rs); } void Episode::addValue(unsigned int t, unsigned int action, float value) { _values[t * _value_size + action] += value; } void Episode::updateValue(unsigned int t, unsigned int action, float value) { _values[t * _value_size + action] = value; } float Episode::reward(unsigned int t) const { return _rewards[t]; } float Episode::cumulativeReward() const { return std::accumulate(_rewards.begin(), _rewards.end(), 0.0f); } float Episode::action(unsigned int t) const { return _actions[t]; }
Java
UTF-8
3,568
2.515625
3
[]
no_license
package com.study.springboot.oauth2; import java.util.Map; import lombok.Builder; import lombok.Getter; @Getter public class OAuthAttributes { private Map<String, Object> attributes; private String nameAttributeKey; private String name; private String email; private String picture; @Builder public OAuthAttributes(Map<String, Object> attributes, String nameAttributeKey, String name, String email, String picture) { this.attributes = attributes; this.nameAttributeKey = nameAttributeKey; this.name = name; this.email = email; this.picture = picture; } public static OAuthAttributes of(String registrationId, String userNameAttributeName, Map<String, Object> attributes) { // System.out.println(registrationId); // System.out.println(userNameAttributeName); if (registrationId.equals("google")) { return ofGoogle(userNameAttributeName, attributes); } else if (registrationId.equals("facebook")) { return ofFacebook(userNameAttributeName, attributes); } else if (registrationId.equals("kakao")) { return ofKakao(userNameAttributeName, attributes); } else if (registrationId.equals("naver")) { return ofNaver(userNameAttributeName, attributes); } return ofGoogle(userNameAttributeName, attributes); } private static OAuthAttributes ofGoogle(String userNameAttributeName, Map<String, Object> attributes) { System.out.println("google att : "+attributes); return OAuthAttributes.builder() .name((String) attributes.get("name")) .email((String) attributes.get("email")) .picture((String) attributes.get("picture")) .attributes(attributes) .nameAttributeKey(userNameAttributeName) .build(); } private static OAuthAttributes ofFacebook(String userNameAttributeName, Map<String, Object> attributes) { System.out.println("facebook att : "+attributes); String sName = (String) attributes.get("name"); String sEmail = (String) attributes.get("email"); Map<String, Object> pic1 = (Map<String, Object>) attributes.get("picture"); Map<String, Object> pic2 = (Map<String, Object>) pic1.get("data"); String pic3 = (String) pic2.get("url"); return OAuthAttributes.builder() .name(sName) .email(sEmail) .picture(pic3) .attributes(attributes) .nameAttributeKey(userNameAttributeName) .build(); } private static OAuthAttributes ofKakao(String userNameAttributeName, Map<String, Object> attributes) { System.out.println("Kakao att : "+attributes); Map<String, Object> obj1 = (Map<String, Object>) attributes.get("kakao_account"); Map<String, Object> obj2 = (Map<String, Object>) obj1.get("profile"); String sName = (String) obj2.get("nickname"); String sPic = (String) obj2.get("thumbnail_image_url"); String sEmail = (String) obj1.get("email"); return OAuthAttributes.builder() .name(sName) .email(sEmail) .picture(sPic) .attributes(attributes) .nameAttributeKey(userNameAttributeName) .build(); } private static OAuthAttributes ofNaver(String userNameAttributeName, Map<String, Object> attributes) { System.out.println("Naver att : "+attributes); Map<String, Object> obj1 = (Map<String, Object>) attributes.get("response"); String sName = (String) obj1.get("name"); String sPic = (String) obj1.get("profile_image"); String sEmail = (String) obj1.get("email"); return OAuthAttributes.builder() .name(sName) .email(sEmail) .picture(sPic) .attributes(attributes) .nameAttributeKey(userNameAttributeName) .build(); } }
Java
UTF-8
340
1.976563
2
[]
no_license
package additional; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Date; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface TestAnnotation { int value(); // int id(); }
Java
UTF-8
1,147
2.296875
2
[]
no_license
package backTesting; import org.json.*; import java.net.*; import java.util.ArrayList; import java.util.Map; import java.io.*; import java.util.*; public class Algo1 { public static String apiKey = "HA1B7557DRPRIY78"; public static void main(String[] args) { /* * Get input from webpage */ String[] arg = {"V","MSFT","CRON","ATVI","NOC","AMZN","NVDA"}; for(int i = 0 ; i < arg.length; i++) { Basic run = new Basic(arg[i], "1", 0.05); run.runBackTest(); try { Thread.sleep(60000); } catch (InterruptedException e) { e.printStackTrace(); } } //run.runAlgorithmPresent(); /*try { automation.Automated.automatedETrade("MSFT","1", "buy"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ } } /* * JSONObject obj = null; String functionIntra = "TIME_SERIES_INTRADAY"; String symbolIntra = "AMZN"; String intervalIntra = "5min"; String outputsizeIntra = "full"; obj = ApiCall.intraday(functionIntra, symbolIntra, intervalIntra, outputsizeIntra, apiKey); //modify test to accept multiple intervals IntradayParse test = new IntradayParse(obj); */
JavaScript
UTF-8
3,863
2.625
3
[]
no_license
import React, { Component } from 'react'; import { withRouter } from 'react-router-dom' class Edit extends Component { constructor(props) { super(props); this.state = { name: null, startDate: null, endDate: null, date: null, id: this.props.match.params.id } } componentDidMount() { fetch('/events') .then(res => res.json()) .then(events => { const event = events.find((e) => e.id == this.state.id); this.setState({name: event.name, startDate: event.startDate, endDate: event.endDate, date: event.date}) }); } render() { const { name, startDate, endDate } = this.state; return ( <form onSubmit={this.submitHandler} className="form"> <div className="form__title"> Edit event </div> <div className="form__row"> Event name: <input className="form__input" type="text" name="name" value={name || ""} onChange={(e) => this.onNameChange(e)}/> </div> <div className="form__row"> Event start time: <input className="form__input" type="time" name="startTime" value={startDate || ""} onChange={(e) => this.onStartDateChange(e)} /> </div> <div className="form__row"> Event end time: <input className="form__input" type="time" name="endTime" value={endDate || ""} onChange={(e) => this.onEndDateChange(e)} /> </div> <div className="form__row"> <button onClick={(e) => this.deleteHandler(e)} className="form__button"> Delete </button> <button onClick={(e) => this.cancelHandler(e)} className="form__button"> Cancel </button> <button type="submit" className="form__button"> Submit </button> </div> </form> ); } onNameChange = (event) => { this.setState({ name: event.target.value }) } onStartDateChange = (event) => { this.setState({ startDate: event.target.value }); } onEndDateChange = (event) => { this.setState({ endDate: event.target.value }); } cancelHandler = (event) => { event.preventDefault(); this.props.history.push('/'); } submitHandler = (event) => { event.preventDefault(); fetch('http://localhost:4000/events/edit', { method: "POST", body: JSON.stringify(this.state), headers: new Headers({ 'Content-Type': 'application/json' }) }) .then(r => r.json()) .then(console.log); console.log('submit', this.state); this.props.history.push('/'); } deleteHandler = (event) => { event.preventDefault(); fetch('http://localhost:4000/events/delete', { method: "POST", body: JSON.stringify(this.state), headers: new Headers({ 'Content-Type': 'application/json' }) }) .then(r => r.json()) .then(console.log); this.props.history.push('/'); } } export default withRouter(Edit);
C
UTF-8
10,778
3.28125
3
[ "MIT" ]
permissive
#include "parser.h" #include "lexer.h" #include "variable.h" #include <stdio.h> #include <stdlib.h> static Token parse_expression(void); static void parse_variable_decl(void); void parse_tokens(void){ Token *t; Token exp_result; Variable *var; if(show_next_token(&t)){ // this is the first token we get, so there are few possibilities switch (t->type){ case IDENTIFIER: var = get_variable(t->sub.identifier.string); if(var != NULL){ if(var->type == LIT_INTEGER) printf("%s = %d\n", var->name, var->data.int_value); else if(var->type == LIT_FLOAT) printf("%s = %f\n", var->name, var->data.float_value); } else{ printf("ERROR: Undefined identifier %s\n", t->sub.literal.data.string); exit(EXIT_FAILURE); } break; case OPERATOR: printf("Unexpected operator : %c\n", t->sub.operator.symbol); exit(EXIT_FAILURE); case LITERAL: case SEPERATOR: exp_result = parse_expression(); if(exp_result.type == LITERAL){ if(exp_result.subType == LIT_INTEGER) printf("result = %d\n", exp_result.sub.literal.data.int_value); else if(exp_result.subType == LIT_FLOAT) printf("result = %f\n", exp_result.sub.literal.data.float_value); } break; case KEYWORD: // Assuming it is a type keyword parse_variable_decl(); break; default: break; } } } static Token parse_expression(void){ // assuming starting token is literal number int output_count = 0; int op_count = 0; Token output[20]; Token op_stack[20]; Token *n_token; for(;;){ if(get_next_token(&n_token)){ // here running out of tokens if(n_token->type == OPERATOR){ while(op_count > 0 && (op_stack[op_count-1].sub.operator.precedence > n_token->sub.operator.precedence || op_stack[op_count-1].sub.operator.precedence == n_token->sub.operator.precedence) && op_stack[op_count-1].sub.operator.symbol != LEFT_PAR){ // Possible bug on the last comparison (uninitilized memory address could have the same value as LEFT_PAR (40) output[output_count] = op_stack[op_count-1]; op_count -= 1; output_count += 1; } op_stack[op_count] = *n_token; op_count += 1; } else if(n_token->type == LITERAL && (n_token->subType == LIT_INTEGER || n_token->subType == LIT_FLOAT)){ output[output_count] = *n_token; output_count += 1; } else if(n_token->type == IDENTIFIER){ Variable *var = get_variable(n_token->sub.identifier.string); if(var != NULL){ if(var->type == LIT_INTEGER){ // create new literal token Token t; t.type = LITERAL; t.subType = LIT_INTEGER; t.sub.literal.data.int_value = var->data.int_value; output[output_count] = t; output_count += 1; } else if(var->type == LIT_FLOAT){ Token t; t.type = LITERAL; t.subType = LIT_FLOAT; t.sub.literal.data.float_value = var->data.float_value; output[output_count] = t; output_count += 1; } else { printf("ERROR: Identifier '%s' expected to be INTEGER or FLOAT\n", var->name); exit(EXIT_FAILURE); } } else { printf("ERROR: Undefined identifier '%s'\n", var->name); exit(EXIT_FAILURE); } } else if(n_token->type == SEPERATOR){ if(n_token->sub.operator.symbol == LEFT_PAR){ op_stack[op_count] = *n_token; op_count += 1; } else if(n_token->sub.operator.symbol == RIGHT_PAR){ while(op_stack[op_count - 1].sub.operator.symbol != LEFT_PAR){ output[output_count] = op_stack[op_count-1]; op_count -= 1; output_count += 1; } if(op_stack[op_count - 1].sub.operator.symbol == LEFT_PAR) op_count -= 1; } } else{ printf("ERROR: Unexpected token '%s' (Expected : 'OPERATOR' OR 'LITERAL')\n", n_token->sub.literal.data.string); exit(EXIT_FAILURE); } } else break; // For now we only parse math expr, but we probably need to detect if ; token is come up? } while(op_count > 0){ output[output_count] = op_stack[op_count - 1]; op_count -= 1; output_count += 1; } // --------------- calculate post-fix notation --------------- Token result; result.type = LITERAL; // What if there is only literal in output stack // e.g int a = 5 // then we need to return value of that token immediately. if(output_count == 1){ if(output[output_count - 1].subType == LIT_INTEGER){ result.subType = LIT_INTEGER; result.sub.literal.data.int_value = output[output_count - 1].sub.literal.data.int_value; } else if(output[output_count - 1].subType == LIT_FLOAT){ result.subType = LIT_FLOAT; result.sub.literal.data.float_value = output[output_count - 1].sub.literal.data.float_value; } return result; } Token p_stack[20]; int p_counter = 0; int iterator = 0; while(output_count > 0){ if(output[iterator].type == LITERAL){ p_stack[p_counter] = output[iterator]; p_counter += 1; } else if(output[iterator].type == OPERATOR){ Token t2 = p_stack[p_counter-1]; // second operand Token t1 = p_stack[p_counter-2]; // first operand p_counter -= 2; switch(output[iterator].sub.operator.symbol){ // Clean this up (Wrapping switch body to function makes sense) case OPERATOR_PLUS: if(t1.subType == LIT_INTEGER && t2.subType == LIT_INTEGER){ result.sub.literal.data.int_value = t1.sub.literal.data.int_value + t2.sub.literal.data.int_value; result.subType = LIT_INTEGER; } else if(t1.subType == LIT_FLOAT && t2.subType == LIT_INTEGER){ result.sub.literal.data.float_value = t1.sub.literal.data.float_value + t2.sub.literal.data.int_value; result.subType = LIT_FLOAT; } else if(t1.subType == LIT_INTEGER && t2.subType == LIT_FLOAT){ result.sub.literal.data.float_value = t1.sub.literal.data.int_value + t2.sub.literal.data.float_value; result.subType = LIT_FLOAT; } else if(t1.subType == LIT_FLOAT && t2.subType == LIT_FLOAT){ result.sub.literal.data.float_value = t1.sub.literal.data.float_value + t2.sub.literal.data.float_value; result.subType = LIT_FLOAT; } break; case OPERATOR_MINUS: if(t1.subType == LIT_INTEGER && t2.subType == LIT_INTEGER){ result.sub.literal.data.int_value = t1.sub.literal.data.int_value - t2.sub.literal.data.int_value; result.subType = LIT_INTEGER; } else if(t1.subType == LIT_FLOAT && t2.subType == LIT_INTEGER){ result.sub.literal.data.float_value = t1.sub.literal.data.float_value - t2.sub.literal.data.int_value; result.subType = LIT_FLOAT; } else if(t1.subType == LIT_INTEGER && t2.subType == LIT_FLOAT){ result.sub.literal.data.float_value = t1.sub.literal.data.int_value - t2.sub.literal.data.float_value; result.subType = LIT_FLOAT; } else if(t1.subType == LIT_FLOAT && t2.subType == LIT_FLOAT){ result.sub.literal.data.float_value = t1.sub.literal.data.float_value - t2.sub.literal.data.float_value; result.subType = LIT_FLOAT; } break; case OPERATOR_MULTIPLY: if(t1.subType == LIT_INTEGER && t2.subType == LIT_INTEGER){ result.sub.literal.data.int_value = t1.sub.literal.data.int_value * t2.sub.literal.data.int_value; result.subType = LIT_INTEGER; } else if(t1.subType == LIT_FLOAT && t2.subType == LIT_INTEGER){ result.sub.literal.data.float_value = t1.sub.literal.data.float_value * t2.sub.literal.data.int_value; result.subType = LIT_FLOAT; } else if(t1.subType == LIT_INTEGER && t2.subType == LIT_FLOAT){ result.sub.literal.data.float_value = t1.sub.literal.data.int_value * t2.sub.literal.data.float_value; result.subType = LIT_FLOAT; } else if(t1.subType == LIT_FLOAT && t2.subType == LIT_FLOAT){ result.sub.literal.data.float_value = t1.sub.literal.data.float_value * t2.sub.literal.data.float_value; result.subType = LIT_FLOAT; } break; case OPERATOR_DIVIDE: if(t1.subType == LIT_INTEGER && t2.subType == LIT_INTEGER){ result.sub.literal.data.int_value = t1.sub.literal.data.int_value / t2.sub.literal.data.int_value; result.subType = LIT_INTEGER; } else if(t1.subType == LIT_FLOAT && t2.subType == LIT_INTEGER){ result.sub.literal.data.float_value = t1.sub.literal.data.float_value / t2.sub.literal.data.int_value; result.subType = LIT_FLOAT; } else if(t1.subType == LIT_INTEGER && t2.subType == LIT_FLOAT){ result.sub.literal.data.float_value = t1.sub.literal.data.int_value / t2.sub.literal.data.float_value; result.subType = LIT_FLOAT; } else if(t1.subType == LIT_FLOAT && t2.subType == LIT_FLOAT){ result.sub.literal.data.float_value = t1.sub.literal.data.float_value / t2.sub.literal.data.float_value; result.subType = LIT_FLOAT; } break; } p_stack[p_counter] = result; p_counter += 1; } iterator += 1; output_count -= 1; } return result; } static void parse_variable_decl(void){ // <TYPE_KEYWORD> <IDENDTIFIER> <EQUAL_OPERATOR> // then call parse_expression and store return value in memory Token *n_token; if(get_next_token(&n_token)){ // Check if token is keyword if(n_token->type == KEYWORD){ Token *identifier_token; get_next_token(&identifier_token); Token *equal_token; get_next_token(&equal_token); if(equal_token->type == OPERATOR && equal_token->sub.operator.symbol == OPERATOR_EQUAL){ Token result = parse_expression(); if(result.subType == n_token->subType){ create_variable(identifier_token, &result); } else{ printf("ERROR : Variable type is not same with the result\n"); exit(EXIT_FAILURE); } } else{ printf("ERROR: Expected OPERATOR_EQUAL, but got %s\n", equal_token->sub.literal.data.string); exit(EXIT_FAILURE); } } else{ printf("ERROR: Expected KEYWORD\n"); exit(EXIT_FAILURE); } } else{ printf("Uncompleted assignment \n"); exit(EXIT_FAILURE); } } static void parse_function_decl(){ // function def : fdef func_name(){} // Token : fdef Token *def_token; get_next_token(&def_token); if(def_token->type == KEYWORD && def_token->subType == KEY_FUNCDEF){ // This token is fdef Token *function_name; get_next_token(&function_name); if(function_name->type == IDENTIFIER){ Token *parOpen; get_next_token(&parOpen); if(parOpen->type == SEPERATOR && parOpen->sub.operator.symbol == LEFT_PAR){ // openPar present Token *afterParToken; for(;;){ get_next_token(&afterParToken); if(afterParToken->type != SEPERATOR && afterParToken->sub.operator.symbol != RIGHT_PAR) break; // if(afterParToken.type == KEYWORD && ) } } } } }
Java
UTF-8
1,594
3.734375
4
[]
no_license
package Lec49; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; public class Generics_Demo { public static void main(String[] args) { // TODO Auto-generated method stub ArrayList<Integer> list = new ArrayList<>(); //System.out.println(list); Integer [] arr = {12,3,4,5,6,7}; String [] arr1 = {"A","Pooja","Rohit","Shivani","Rahul"}; // Display(arr); // Display(arr1); Cars [] car = new Cars[5]; car[0] = new Cars(1000, 20, "Black"); car[1] = new Cars(200, 10, "White"); car[2] = new Cars(345, 3, "Yellow"); car[3] = new Cars(8907, 6, "Red"); car[4] = new Cars(34, 89, "Grey"); Display(car); //Arrays.sort(car); System.out.println(">>>>>>>>>>>"); Bubble_Sort(car); // Bubble_Sort(car ,new CarPriceComparator()); // Display(car); } public static <T>void Display(T [] arr) { for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]+", "); } } public static <T extends Comparable<T>>void Bubble_Sort(T [] arr) { for (int pass = 1; pass <= arr.length - 1; pass++) { for (int i = 0; i < arr.length - pass; i++) { if(arr[i].compareTo(arr[i+1])>0) { T t = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = t; } } } } // public static <T>void Bubble_Sort(T [] arr, Comparator<T> camp) { // // for (int pass = 1; pass <= arr.length - 1; pass++) { // // for (int i = 0; i < arr.length - pass; i++) { // if(camp.compare(arr[i], arr[i+1])>0) { // T t = arr[i]; // arr[i] = arr[i + 1]; // arr[i + 1] = t; // // } // } // // } // } }
Ruby
UTF-8
5,222
2.6875
3
[]
no_license
require 'active_resource' require 'thor' require 'aeolus_cli/model/base' require 'aeolus_cli/model/provider_type' class AeolusCli::CommonCli < Thor class_option :conductor_url, :type => :string class_option :username, :type => :string class_option :password, :type => :string def initialize(*args) super load_aeolus_config(options) end # abstract-y methods desc "list", "List all" def list(*args) self.shell.say "Implement me." end desc "add", "Add one" def add(*args) self.shell.say "Implement me." end protected class << self def banner(task, namespace = nil, subcommand = false) "#{basename} #{task.formatted_usage(self, false, true)}" # Above line Overrides the line from Thor, below, so the printed usage # line is correct, e.g. for "aeolus provider help list" we get # Usage: # aeolus provider list # instead of # Usage: # aeolus list #"#{basename} #{task.formatted_usage(self, $thor_runner, subcommand)}" end end def load_aeolus_config(options) # set logging defaults ActiveResource::Base.logger = Logger.new(STDOUT) ActiveResource::Base.logger.level = Logger::WARN # locate the config file if one exists config_fname = nil if ENV.has_key?("AEOLUS_CLI_CONF") config_fname = ENV["AEOLUS_CLI_CONF"] if !is_file?(config_fname) raise AeolusCli::ConfigError.new( "environment variable AEOLUS_CLI_CONF with value "+ "'#{ ENV['AEOLUS_CLI_CONF']}' does not point to an existing file") end else ["~/.aeolus-cli","/etc/aeolus-cli"].each do |fname| if is_file?(fname) config_fname = fname break end end end # load the config file if we have one if config_fname != nil @config = YAML::load(File.open(File.expand_path(config_fname))) if @config.has_key?(:conductor) [:url, :password, :username].each do |key| raise AeolusCli::ConfigError.new \ ("Error in configuration file: #{key} is missing" ) unless @config[:conductor].has_key?(key) end AeolusCli::Model::Base.site = @config[:conductor][:url] AeolusCli::Model::Base.user = @config[:conductor][:username] AeolusCli::Model::Base.password = @config[:conductor][:password] else raise AeolusCli::ConfigError.new("Error in configuration file") end if @config.has_key?(:logging) if @config[:logging].has_key?(:logfile) if @config[:logging][:logfile].upcase == "STDOUT" ActiveResource::Base.logger = Logger.new(STDOUT) elsif @config[:logging][:logfile].upcase == "STDERR" ActiveResource::Base.logger = Logger.new(STDERR) else ActiveResource::Base.logger = Logger.new(@config[:logging][:logfile]) end end if @config[:logging].has_key?(:level) log_level = @config[:logging][:level] if ! ['DEBUG','WARN','INFO','ERROR','FATAL'].include?(log_level) raise AeolusCli::ConfigError.new \ ("log level specified in configuration #{log_level}, is not valid."+ ". shoud be one of DEBUG, WARN, INFO, ERROR or FATAL") else ActiveResource::Base.logger.level = eval("Logger::#{log_level}") end end end end # allow overrides from command line if options[:conductor_url] AeolusCli::Model::Base.site = options[:conductor_url] end if options[:username] AeolusCli::Model::Base.user = options[:username] end if options[:password] AeolusCli::Model::Base.password = options[:password] end end # Given a hash of attribute key name to pretty name and an active # resource collection, print the output. def print_table( keys_to_pretty_names, ares_collection) t = Array.new # Add the first row, the column headings t.push keys_to_pretty_names.values # Add the data ares_collection.each do |ares| row = Array.new keys_to_pretty_names.keys.each do |key| row.push ares.attributes[key].to_s end t.push row end # use Thor's shell.print_table() self.shell.print_table(t) end def provider_type(type_s) # we need to hit the API to get the map of provider_type.name => # provider_type.id, so make sure we only do this once. @provider_type_hash ||= provider_type_hash @provider_type_hash[type_s] end def provider_type_hash deltacloud_driver_to_provider_type = Hash.new provider_types = AeolusCli::Model::ProviderType.all if provider_types.size == 0 raise "Retrieved zero provider types from Conductor" end provider_types.each do |pt| deltacloud_driver_to_provider_type[pt.deltacloud_driver] = pt end deltacloud_driver_to_provider_type end # TODO: Consider ripping all this file-related stuff into a module or # class for better encapsulation and testability def is_file?(path) full_path = File.expand_path(path) if File.exist?(full_path) && !File.directory?(full_path) return true end false end end
Java
UTF-8
2,337
2.5625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.utf.grw.utfmaps.modelo.usuario; import com.utf.grw.utfmaps.modelo.usuario.Usuario; import com.utf.grw.utfmaps.util.ConexaoHibernate; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; /** * * @author a1808052 */ public class UsuarioDAOHibernate implements UsuarioDAO { EntityManager manager; public UsuarioDAOHibernate() { manager = ConexaoHibernate.getInstance(); } @Override public void salvar(Usuario usuario) { this.manager.getTransaction().begin(); this.manager.persist(usuario); this.manager.getTransaction().commit(); } @Override public void atualizar(Usuario usuario) { this.manager.getTransaction().begin(); this.manager.merge(usuario); this.manager.getTransaction().commit(); } @Override public void excluir(Usuario usuario) { this.manager.getTransaction().begin(); this.manager.remove(usuario); this.manager.getTransaction().commit(); } @Override public Usuario carregar(Integer codigo) { Usuario usuario = manager.getReference(Usuario.class, codigo); return usuario; } @Override public Usuario buscarPorId(Long codigo) { Usuario usuario = manager.find(Usuario.class, codigo); return usuario; } @Override public List<Usuario> listar() { /*Query q = manager.createQuery("SELECT p FROM Usuario p"); List<Usuario> Usuarioes = q.getResultList();*/ Query query = manager.createNamedQuery("Usuario.findAll"); List<Usuario> usuarios = query.getResultList(); return usuarios; } @Override public Usuario buscarPorLogin(String nome) { String jpql = "SELECT s FROM Usuario s WHERE USU_LOGIN = ?1"; Query query = manager.createQuery(jpql); query.setParameter(1, nome); Usuario usuario = (Usuario)query.getSingleResult(); return usuario; } @Override public Usuario refresh(Usuario usuario){ manager.refresh(usuario); return usuario; } }
Java
UTF-8
1,752
2.28125
2
[]
no_license
package com.xiaoming.dao.impl; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.hibernate.SessionFactory; import org.springframework.stereotype.Repository; import com.xiaoming.base.impl.BaseDaoImpl; import com.xiaoming.dao.FolderDao; import com.xiaoming.domain.Folder; @Repository public class FolderDaoImpl extends BaseDaoImpl<Folder> implements FolderDao { @Resource private SessionFactory sessionFactory; @SuppressWarnings("unchecked") @Override /** * @author zmj * @param id 组织的id * isPublic 是否为公开的文件夹 */ public List<Folder> findList(Long id, Boolean isPublic, Boolean isTop) { String hql = ""; if(isTop){ hql = "FROM Folder as f where f.organization.id=? and f.parent " + "is null" + " and f.isPublic=" + (isPublic ? 1 : 0) + " and f.avariable = 1"; }else{ hql = "FROM Folder as f where " + "f.id = ?" + " and f.isPublic=" + (isPublic ? 1 : 0) + " and f.avariable = 1"; } return (ArrayList<Folder>) sessionFactory.getCurrentSession() .createQuery(hql).setParameter(0, id).list(); } private ArrayList<Long> deleteFolderIds(Folder f,ArrayList<Long> result){ f.setAvariable(false); if(null!=f.getChilders()&&f.getChilders().size()>0){ for(Folder f1:f.getChilders()){ result.addAll(deleteFolderIds(f1,result)); } } result.add(f.getId()); return result; } @Override public void delete(Folder folder) { //获取要删除的id ArrayList<Long> ids = deleteFolderIds(folder,new ArrayList<Long>()); String hql = "Update from Folder as f SET f.avariable = 0 where f.id in (:ids)"; sessionFactory.getCurrentSession().createQuery(hql).setParameterList("ids", ids).isReadOnly(); } }
C++
UTF-8
1,914
2.703125
3
[]
no_license
//Stores an ID3D11Buffer for a constant buffer of any type and its meta-data, automatically rounds the byte width to the 16 byte alignment #pragma once #include <d3d11.h> #include <wrl/client.h> #include "constant_buffer_types.h" #include "../../utils/error_logger.h" namespace hrzn::gfx { template<class T> class ConstantBuffer { private: ConstantBuffer(const ConstantBuffer<T>& rhs); public: ConstantBuffer() : m_buffer(nullptr), m_deviceContext(nullptr) { } ID3D11Buffer* get() const { return m_buffer.Get(); } ID3D11Buffer* const* getAddressOf() const { return m_buffer.GetAddressOf(); } HRESULT initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext) { if (m_buffer.Get() != nullptr) { m_buffer.Reset(); } m_deviceContext = deviceContext; D3D11_BUFFER_DESC constantBufferDesc; ZeroMemory(&constantBufferDesc, sizeof(constantBufferDesc)); constantBufferDesc.Usage = D3D11_USAGE_DYNAMIC; constantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; constantBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; constantBufferDesc.MiscFlags = 0; constantBufferDesc.ByteWidth = static_cast<UINT>(sizeof(T) + (16 - (sizeof(T) % 16))); constantBufferDesc.StructureByteStride = 0; return device->CreateBuffer(&constantBufferDesc, 0, m_buffer.GetAddressOf()); } bool mapToGPU() { D3D11_MAPPED_SUBRESOURCE mappedResource; HRESULT hr = m_deviceContext->Map(m_buffer.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); if (utils::ErrorLogger::logIfFailed(hr, "Failed to map constant buffer.")) { return false; } CopyMemory(mappedResource.pData, &m_data, sizeof(T)); m_deviceContext->Unmap(m_buffer.Get(), 0); return true; } public: T m_data; private: Microsoft::WRL::ComPtr<ID3D11Buffer> m_buffer; ID3D11DeviceContext* m_deviceContext; }; }
Java
UTF-8
7,009
1.757813
2
[]
no_license
/** */ package org.hl7.fhir.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.hl7.fhir.CatalogEntryRelatedEntry; import org.hl7.fhir.CatalogEntryRelationType; import org.hl7.fhir.FhirPackage; import org.hl7.fhir.Reference; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Catalog Entry Related Entry</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.hl7.fhir.impl.CatalogEntryRelatedEntryImpl#getRelationtype <em>Relationtype</em>}</li> * <li>{@link org.hl7.fhir.impl.CatalogEntryRelatedEntryImpl#getItem <em>Item</em>}</li> * </ul> * * @generated */ public class CatalogEntryRelatedEntryImpl extends BackboneElementImpl implements CatalogEntryRelatedEntry { /** * The cached value of the '{@link #getRelationtype() <em>Relationtype</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getRelationtype() * @generated * @ordered */ protected CatalogEntryRelationType relationtype; /** * The cached value of the '{@link #getItem() <em>Item</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getItem() * @generated * @ordered */ protected Reference item; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected CatalogEntryRelatedEntryImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return FhirPackage.eINSTANCE.getCatalogEntryRelatedEntry(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public CatalogEntryRelationType getRelationtype() { return relationtype; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetRelationtype(CatalogEntryRelationType newRelationtype, NotificationChain msgs) { CatalogEntryRelationType oldRelationtype = relationtype; relationtype = newRelationtype; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FhirPackage.CATALOG_ENTRY_RELATED_ENTRY__RELATIONTYPE, oldRelationtype, newRelationtype); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setRelationtype(CatalogEntryRelationType newRelationtype) { if (newRelationtype != relationtype) { NotificationChain msgs = null; if (relationtype != null) msgs = ((InternalEObject)relationtype).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FhirPackage.CATALOG_ENTRY_RELATED_ENTRY__RELATIONTYPE, null, msgs); if (newRelationtype != null) msgs = ((InternalEObject)newRelationtype).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FhirPackage.CATALOG_ENTRY_RELATED_ENTRY__RELATIONTYPE, null, msgs); msgs = basicSetRelationtype(newRelationtype, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, FhirPackage.CATALOG_ENTRY_RELATED_ENTRY__RELATIONTYPE, newRelationtype, newRelationtype)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Reference getItem() { return item; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetItem(Reference newItem, NotificationChain msgs) { Reference oldItem = item; item = newItem; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FhirPackage.CATALOG_ENTRY_RELATED_ENTRY__ITEM, oldItem, newItem); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setItem(Reference newItem) { if (newItem != item) { NotificationChain msgs = null; if (item != null) msgs = ((InternalEObject)item).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FhirPackage.CATALOG_ENTRY_RELATED_ENTRY__ITEM, null, msgs); if (newItem != null) msgs = ((InternalEObject)newItem).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FhirPackage.CATALOG_ENTRY_RELATED_ENTRY__ITEM, null, msgs); msgs = basicSetItem(newItem, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, FhirPackage.CATALOG_ENTRY_RELATED_ENTRY__ITEM, newItem, newItem)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case FhirPackage.CATALOG_ENTRY_RELATED_ENTRY__RELATIONTYPE: return basicSetRelationtype(null, msgs); case FhirPackage.CATALOG_ENTRY_RELATED_ENTRY__ITEM: return basicSetItem(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case FhirPackage.CATALOG_ENTRY_RELATED_ENTRY__RELATIONTYPE: return getRelationtype(); case FhirPackage.CATALOG_ENTRY_RELATED_ENTRY__ITEM: return getItem(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case FhirPackage.CATALOG_ENTRY_RELATED_ENTRY__RELATIONTYPE: setRelationtype((CatalogEntryRelationType)newValue); return; case FhirPackage.CATALOG_ENTRY_RELATED_ENTRY__ITEM: setItem((Reference)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case FhirPackage.CATALOG_ENTRY_RELATED_ENTRY__RELATIONTYPE: setRelationtype((CatalogEntryRelationType)null); return; case FhirPackage.CATALOG_ENTRY_RELATED_ENTRY__ITEM: setItem((Reference)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case FhirPackage.CATALOG_ENTRY_RELATED_ENTRY__RELATIONTYPE: return relationtype != null; case FhirPackage.CATALOG_ENTRY_RELATED_ENTRY__ITEM: return item != null; } return super.eIsSet(featureID); } } //CatalogEntryRelatedEntryImpl
Shell
UTF-8
78
2.609375
3
[]
no_license
filename=$1 touch "$filename" mv "$filename" `echo "$filename"|sed 's/ /_/g'`
Markdown
UTF-8
267
2.671875
3
[]
no_license
Python-2 1. Create the below pattern using nested for loop in Python. * * * * * * * * * * * * * * * * * * * * * * * * * 2. Write a Python program to reverse a word after accepting the input from the user. Sample Output: Input word: ineuron Output: norueni
Java
UTF-8
224
2.203125
2
[]
no_license
package game.boardException; import game.Coord; /** * Called when the user move out a legal position of piece */ public class IllegalMove extends Exception { public IllegalMove(String message){ super (message); }; }
Python
UTF-8
2,342
2.53125
3
[ "MIT" ]
permissive
# -*- encoding: utf-8 -*- from django.db import models from django.conf import settings from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse #Modelo para equipos class Equipo(models.Model): nombre = models.CharField(max_length=50) fechaCreacion = models.DateTimeField(auto_now_add=True) miembros = models.ManyToManyField(User, related_name="equipo_miembros") descripcion = models.TextField(max_length=200) def get_absolute_url(self): return reverse('app:equipo_detalle',args=[self.id]) #Devuelve el nombre en lugar de object def __str__(self): return self.nombre #Modelo para incidencias class Incidencia(models.Model): TIPO_REQUEST = ( ("incidencia", "Incidencia"), ("mejora", "Mejora"), ) GRADO_CHOICES = ( ("P1","Crítico"), ("P2","Alto"), ("P3","Moderado"), ("P4","Bajo"), ("P5","Informativo"), ) ESTADO_CHOICES = ( ("abierto","Abierto"), ("resuelto","Resuelto"), ("cerrado","Cerrado"), ("eliminado","Eliminado"), ) titulo = models.CharField(max_length=200) tipo = models.CharField(choices=TIPO_REQUEST, max_length=20, default = 'incidencia') descripcion = models.TextField(max_length=1000) autor = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sistema_incidencia') fechaCreacion = models.DateTimeField(auto_now_add = timezone.now() ) fechaModificacion = models.DateTimeField(auto_now=True) estado = models.CharField(choices = ESTADO_CHOICES, max_length=20, default = "abierto") responsables = models.ForeignKey(User, on_delete=models.CASCADE, related_name="incidencia_responsables") equipo = models.ForeignKey(Equipo, on_delete=models.CASCADE, related_name='equipo_incidencias', default=None ) grado = models.CharField(max_length=20, choices = GRADO_CHOICES, default='P5') horasEstimadas = models.DecimalField(blank=True, null=True, default=0, decimal_places=2, max_digits=6) #Devuelve el nombre en lugar de object def __str__(self): return self.titulo class Meta: ordering = ('-fechaCreacion',) #Ordenar en orden ascendente class Prueba(models.Model): nombrePrueba = models.TextField(max_length=100)
C#
UTF-8
902
2.78125
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MyCalendar { public partial class TimeTape : Form { public TimeTape() { InitializeComponent(); } private Point point; private void panel1_MouseDown(object sender, MouseEventArgs e) { point = new Point(e.X, e.Y); } private void panel1_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { this.Left += e.X - point.X; this.Top += e.Y - point.Y; } } private void button1_Click(object sender, EventArgs e) { this.Close(); } } }
C
UTF-8
611
2.96875
3
[]
no_license
/* irqreturn.h */ #ifndef _LINUX_IRQRETURN_H #define _LINUX_IRQRETURN_H /* * For 2.4.x compatibility, 2.4.x can use * * typedef void irqreturn_t; * #define IRQ_NONE * #define IRQ_HANDLED * #define IRQ_RETVAL(x) * * To mix old-style and new-style irq handler returns. * * IRQ_NONE means we didn't handle it. * IRQ_HANDLED means that we did have a valid interrupt and handled it. * IRQ_RETVAL(x) selects on the two depending on x being non-zero (for handled) */ typedef int irqreturn_t; #define IRQ_NONE (0) #define IRQ_HANDLED (1) #define IRQ_RETVAL(x) ((x) != 0) #endif
Java
UTF-8
5,265
2.234375
2
[]
no_license
package com.gpdata.wanyou.ds.entity; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import javax.persistence.*; import java.io.Serializable; import java.util.Date; @Entity @Table(name = "datasource_resource") public class DataSourceResource implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer resourceId; /** * 数据资源中文名 */ private String caption; /** * 数据源位置 * 内部数据源:inner * 外部数据源:outer */ private String position; /** * 数据源类型 * 数据库型:DBMS * HDFS型:HDFS */ private String resourceType; /** * 数据类型 * 例如:MySQL、Oracle等 */ private String dataType; /** * 数据量 * 单位:G */ private Long size; /** * 用户表主键 * 暂时采用默认user */ private String creator; /** * 创建时间 */ private Date createDate; /** * 最后一次修改时间 */ private Date reviseDate; /** * 数据源所在主机 */ private String host; /** * 端口号 */ private Integer port; /** * 用户名 */ private String userName; /** * 密码 */ private String passWord; /** * 字符集 * 数据源类型= DBMS 时有效 */ private String encode; /** * 数据库名 * 数据源类型= DBMS 时有效 */ private String dbName; /** * 表个数 * 数据源类型= DBMS 时有效 */ private Integer tablesCount; /** * 连接字符串 * 数据源类型= DBMS 时有效 */ private String connString; /** * HDFS路径 * 数据源类型= HDFS时有效 */ private String hdfsPath; /** * 状态 */ private String status; /** * 备注 */ private String remark; public String getCaption() { return caption; } public void setCaption(String caption) { this.caption = caption; } public String getConnString() { return connString; } public void setConnString(String connString) { this.connString = connString; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public String getDataType() { return dataType; } public void setDataType(String dataType) { this.dataType = dataType; } public String getDbName() { return dbName; } public void setDbName(String dbName) { this.dbName = dbName; } public String getEncode() { return encode; } public void setEncode(String encode) { this.encode = encode; } public String getHdfsPath() { return hdfsPath; } public void setHdfsPath(String hdfsPath) { this.hdfsPath = hdfsPath; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getPassWord() { return passWord; } public void setPassWord(String passWord) { this.passWord = passWord; } public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Integer getResourceId() { return resourceId; } public void setResourceId(Integer resourceId) { this.resourceId = resourceId; } public String getResourceType() { return resourceType; } public void setResourceType(String resourceType) { this.resourceType = resourceType; } public Date getReviseDate() { return reviseDate; } public void setReviseDate(Date reviseDate) { this.reviseDate = reviseDate; } public Long getSize() { return size; } public void setSize(Long size) { this.size = size; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Integer getTablesCount() { return tablesCount; } public void setTablesCount(Integer tablesCount) { this.tablesCount = tablesCount; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } @Override public String toString() { return new ReflectionToStringBuilder(this) .toString(); } }
Java
UTF-8
794
2.140625
2
[]
no_license
package abcd.spc.sstreams.sg; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.stereotype.Component; @Component public class RunClient { @Autowired private KafkaTemplate<String, String> kafkaTemplate; @Autowired private ObjectMapper objectMapper; public void sendRun(String key, Run run) { String data = ""; try { data = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(run); } catch (JsonProcessingException e) { e.printStackTrace(); } kafkaTemplate.send("runs", key, data); } }
Python
UTF-8
2,273
3.34375
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env python # # Matrix-matrix multiplication in MATLAB. # Both matrices here are square ( size x size ). # # Intended to demonstrate Automatic Offload to Xeon Phi MIC using # Intel Math Kernel Library (MKL) # # djames (at) tacc.utexas.edu # cproctor (at) tacc.utexas.edu # 18 Aug 2014 # # --------------------------------------------------------------------- import numpy as np import time size = 8000 # number of rows and columns in each matrix totalruns = 3 # total number of runs in this experiment times = np.zeros( totalruns ) # times(i) is the time in seconds for run i print "" print " code: Python" print " size: %g" % (size) for run in xrange( totalruns ): print "" print "\t------------------------" print "\t ...executing run %g... " % ( run ) print "\t------------------------" print "" # Initialize matrices for new run. Remember that a NumPy matrix, a NumPy array, # and a Python array are all different things. Here we're using NumPy matrices; # for NumPy matrices, the "*" operator does matrix multiplication by calling # BLAS. (With arrays, the "*" operator generally gives you element-by-element # multiplication, and does not use BLAS.) A = np.matrix( np.random.random( (size, size) ) ) # CAUTION: SEE COMMENTS ABOVE B = np.matrix( np.random.random( (size, size) ) ) # CAUTION: SEE COMMENTS ABOVE # Multiply... start_time = time.time() # alternative: time.clock() C = A*B # CAUTION: SEE COMMENTS ABOVE end_time = time.time() times[ run ] = end_time - start_time # Clear matrices... del A del B del C # end run loop # Report times for each run... print "" print " code: Python" print " size: %g" % (size) print "" for run in xrange( totalruns ): print " run %g time: %.2f sec" % ( run, times[run] ) # Compute and display overall average time... avgtime = np.average( times ) print "" print " average time (all runs): %.2f sec" % ( avgtime ) # Compute and display overall average time excluding first run... avgtime = np.average( times[1:len(times)] ) print " average time (skip 1st run): %.2f sec" % ( avgtime ) print ""
JavaScript
UTF-8
12,648
3.65625
4
[ "MIT" ]
permissive
let mathEnforcer = { addFive: function (num) { if (typeof(num) !== 'number') { return undefined; } return num + 5; }, subtractTen: function (num) { if (typeof(num) !== 'number') { return undefined; } return num - 10; }, sum: function (num1, num2) { if (typeof(num1) !== 'number' || typeof(num2) !== 'number') { return undefined; } return num1 + num2; } }; const assert = require('chai').assert; describe("Math enforcer test", function () { let range = 0.01; // function numberInRange(actualNumber, expectedResult){ // let currentNumber = Number(actualNumber); // // let upperTolerance = Number((currentNumber + range).toFixed(2)); // let lowerTolerance = Number((currentNumber - range).toFixed(2)); // // if (currentNumber === expectedResult){ // return true; // } else if(upperTolerance === expectedResult ) { // return true; // } else if (lowerTolerance === expectedResult) { // return true; // } else { // return false; // } // } //• addFive(num) - A function that accepts a single parameter: // o If the parameter is not a number, the function should return undefined. // o If the parameter is a number, add 5 to it, and return the result. describe('addFive tests', function () { it('should correctly handle negative argument', function () { let input = -4; let input1 = -5.472398; let expectedResult = 1; let expected1Result = -0.47; // .toFixed(2); // .toFixed(2); let result = mathEnforcer.addFive(input); let result1 = mathEnforcer.addFive(input1); // let actual = numberInRange(result, expectedResult); // let actual1 = numberInRange(result1, expected1Result); // let expected = true; assert.closeTo(result, expectedResult, range); assert.closeTo(result1, expected1Result, range); // assert.equal(actual, expected); // assert.equal(actual1, expected); }); it('should add correct value and return result', function () { let input = 0; let input1 = 0.43945684; let input2 = 5.329457; let input3 = 453684.329457; let expectedResult = 5; let expected1Result = 5.44; let expected2Result = 10.33; let expected3Result = 453689.33; // .toFixed(2); // .toFixed(2); // .toFixed(2); // .toFixed(2); let result = mathEnforcer.addFive(input); let result1 = mathEnforcer.addFive(input1); let result2 = mathEnforcer.addFive(input2); let result3 = mathEnforcer.addFive(input3); // let actual = numberInRange(result, expectedResult); // let actual1 = numberInRange(result1, expected1Result); // let actual2 = numberInRange(result2, expected2Result); // let actual3 = numberInRange(result3, expected3Result); // let expected = true; assert.closeTo(result, expectedResult, range); assert.closeTo(result1, expected1Result, range); assert.closeTo(result2, expected2Result, range); assert.closeTo(result3, expected3Result, range); // assert.equal(actual, expected); // assert.equal(actual1, expected); // assert.equal(actual2, expected); // assert.equal(actual3, expected); }); it('should return undefined if arg is not a number', function () { let input = []; let input1 = {}; let input2 = function () { }; let input3 = ""; let input4 = "123"; let input5 = "123.456"; let input6 = "pesho"; let input7 = null; let input8 = undefined; let expected = undefined; let actual = mathEnforcer.addFive(input); let actual1 = mathEnforcer.addFive(input1); let actual2 = mathEnforcer.addFive(input2); let actual3 = mathEnforcer.addFive(input3); let actual4 = mathEnforcer.addFive(input4); let actual5 = mathEnforcer.addFive(input5); let actual6 = mathEnforcer.addFive(input6); let actual7 = mathEnforcer.addFive(input7); let actual8 = mathEnforcer.addFive(input8); assert.equal(actual, expected); assert.equal(actual1, expected); assert.equal(actual2, expected); assert.equal(actual3, expected); assert.equal(actual4, expected); assert.equal(actual5, expected); assert.equal(actual6, expected); assert.equal(actual7, expected); assert.equal(actual8, expected); }); }); //• subtractTen(num) - A function that accepts a single parameter: // o If the parameter is not a number, the function should return undefined. // o If the parameter is a number, subtract 10 from it, and return the result. describe('subtractTen tests', function () { it('should correctly handle negative argument', function () { let input = -4; let input1 = -5.472398; let expectedResult = -14; let expected1Result = -15.47; // .toFixed(2); // .toFixed(2); let result = mathEnforcer.subtractTen(input); let result1 = mathEnforcer.subtractTen(input1); // let actual = numberInRange(result, expectedResult); // let actual1 = numberInRange(result1, expected1Result); // let expected = true; assert.closeTo(result, expectedResult, range); assert.closeTo(result1, expected1Result, range); }); it('should subtract correct value and return result', function () { let input = 10; let input1 = 10.43; let input2 = 15.32; let expectedResult = 0; let expected1Result = 0.43; let expected2Result = 5.32; // .toFixed(2); // .toFixed(2); // .toFixed(2); let result = mathEnforcer.subtractTen(input); let result1 = mathEnforcer.subtractTen(input1); let result2 = mathEnforcer.subtractTen(input2); // let actual = numberInRange(result, expectedResult); // let actual1 = numberInRange(result1, expected1Result); // let actual2 = numberInRange(result2, expected2Result); // let expected = true; assert.closeTo(result, expectedResult, range); assert.closeTo(result1, expected1Result, range); assert.closeTo(result2, expected2Result, range); }); it('should return undefined if arg is not a number', function () { let input = []; let input1 = {}; let input2 = function () { }; let input3 = ""; let input4 = "123"; let input5 = "123.456"; let input6 = "pesho"; let expected = undefined; let actual = mathEnforcer.subtractTen(input); let actual1 = mathEnforcer.subtractTen(input1); let actual2 = mathEnforcer.subtractTen(input2); let actual3 = mathEnforcer.subtractTen(input3); let actual4 = mathEnforcer.subtractTen(input4); let actual5 = mathEnforcer.subtractTen(input5); let actual6 = mathEnforcer.subtractTen(input6); assert.equal(actual, expected); assert.equal(actual1, expected); assert.equal(actual2, expected); assert.equal(actual3, expected); assert.equal(actual4, expected); assert.equal(actual5, expected); assert.equal(actual6, expected); }); }); //• sum(num1, num2) - A function that should accepts two parameters: // o If any of the 2 parameters is not a number, the function should return undefined. // o If both parameters are numbers, the function should return their sum. describe('sum tests', function () { it('should return correct value for sum of firstArg/secondArg and secondArg/firstArg', function () { let input = 10; let input1 = 14.537345734; let input2 = -25; let input3 = -345.3215; let expectedResult1 = 24.54; let expectedResult2 = -370.32; // .toFixed(2); // .toFixed(2); // .toFixed(2); // .toFixed(2); let result = mathEnforcer.sum(input, input1); let result1 = mathEnforcer.sum(input1, input); let result2 = mathEnforcer.sum(input2, input3); let result3 = mathEnforcer.sum(input3, input2); // let actual = numberInRange(result, expectedResult1); // let actual1 = numberInRange(result1, expectedResult1); // // let actual2 = numberInRange(result2, expectedResult2); // let actual3 = numberInRange(result3, expectedResult2); // let expected = true; assert.closeTo(result, expectedResult1, range); assert.closeTo(result1, expectedResult1, range); assert.closeTo(result2, expectedResult2, range); assert.closeTo(result3, expectedResult2, range); }); it('should return undefined if second arg is not a number', function () { let validFirstNum = 2; let input = []; let input1 = {}; let input2 = function () { }; let input3 = ""; let input4 = "123"; let input5 = "123.456"; let input6 = "pesho"; let input7 = null; let input8 = undefined; let expected = undefined; let actual = mathEnforcer.sum(validFirstNum, input); let actual1 = mathEnforcer.sum(validFirstNum, input1); let actual2 = mathEnforcer.sum(validFirstNum, input2); let actual3 = mathEnforcer.sum(validFirstNum, input3); let actual4 = mathEnforcer.sum(validFirstNum, input4); let actual5 = mathEnforcer.sum(validFirstNum, input5); let actual6 = mathEnforcer.sum(validFirstNum, input6); let actual7 = mathEnforcer.sum(validFirstNum, input7); let actual8 = mathEnforcer.sum(validFirstNum, input8); assert.equal(actual, expected); assert.equal(actual1, expected); assert.equal(actual2, expected); assert.equal(actual3, expected); assert.equal(actual4, expected); assert.equal(actual5, expected); assert.equal(actual6, expected); assert.equal(actual7, expected); assert.equal(actual8, expected); }); it('should return undefined if first arg is not a number', function () { let validSecondNum = 2; let input = []; let input1 = {}; let input2 = function () { }; let input3 = ""; let input4 = "123"; let input5 = "123.456"; let input6 = "pesho"; let input7 = null; let input8 = undefined; let expected = undefined; let actual = mathEnforcer.sum(input, validSecondNum); let actual1 = mathEnforcer.sum(input1, validSecondNum); let actual2 = mathEnforcer.sum(input2, validSecondNum); let actual3 = mathEnforcer.sum(input3, validSecondNum); let actual4 = mathEnforcer.sum(input4, validSecondNum); let actual5 = mathEnforcer.sum(input5, validSecondNum); let actual6 = mathEnforcer.sum(input6, validSecondNum); let actual7 = mathEnforcer.sum(input7, validSecondNum); let actual8 = mathEnforcer.sum(input8, validSecondNum); assert.equal(actual, expected); assert.equal(actual1, expected); assert.equal(actual2, expected); assert.equal(actual3, expected); assert.equal(actual4, expected); assert.equal(actual5, expected); assert.equal(actual6, expected); assert.equal(actual7, expected); assert.equal(actual8, expected); }); }); });
Java
UTF-8
1,991
2.125
2
[]
no_license
package com.echeng.resumeparser.server; import java.util.Arrays; import java.util.List; import org.apache.log4j.PropertyConfigurator; import com.echeng.resumeparser.common.Constant; import com.echeng.resumeparser.common.utils.config.GlobalConfig; import com.echeng.resumeparser.common.utils.config.ALConfig; public abstract class BaseWorker implements Server { static { PropertyConfigurator.configure(Constant.LOG_FILE); } public static final ALConfig SEVER_CONFIG = GlobalConfig.getInstanceFromFile(Constant.SERVER_FILE); public static final String FUNCTION_NAME = SEVER_CONFIG.getString("worker_name"); public static final String SERVER_HOST = SEVER_CONFIG.getString("server_host"); public static final Integer SERVER_PORT = SEVER_CONFIG.getInt("server_port"); public static final Integer WORKER_COUNT = SEVER_CONFIG.getInt("worker_count"); public static final List<String> M_LIST = Arrays.asList(SEVER_CONFIG.getString("worker_mList").split(",")); public static final ERROR ERROR_0 = ERROR.ERROR_0; public static final ERROR ERROR_1 = ERROR.ERROR_1; public static final ERROR ERROR_2 = ERROR.ERROR_2; public static final ERROR ERROR_3 = ERROR.ERROR_3; public static final ERROR ERROR_4 = ERROR.ERROR_4; public static final ERROR ERROR_5 = ERROR.ERROR_5; public abstract void init(); public abstract void reload(); public abstract void run(); public abstract void destory(); public enum ERROR{ ERROR_0(0,""), ERROR_1(1,"header is invalid!"), ERROR_2(2,"request is not satisfied"), ERROR_3(3,"the work returned none"), ERROR_4(4,"work raise some exceptions"), ERROR_5(5,"have no idea yet"), ; private int id; private String info; private ERROR(int id, String info){ this.id = id; this.info = info; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } }; }
C++
UTF-8
10,420
3.015625
3
[]
no_license
/* * Antoine Carpentier * 000324440 * BA2 informatique ULB 2013-2014 * Langages de programmation 2 - INFO-F-202 * Project C++ * * main.cpp: * Contient les tests */ #include <iostream> #include <cstdlib> #include <cassert> #include <string> #include "Vector.hpp" #include "VectorString.hpp" #include "VectorNum.hpp" using namespace std; void constructors() { // int, false Vector<int, false> intFalse1(10); intFalse1[0] = 1; intFalse1[5] = 6; assert(intFalse1.len() == 10); assert(intFalse1[0] == 1); assert(intFalse1[5] == 6); // int, false -> int, true Vector<int, true> intTrue1(intFalse1); assert(intTrue1.len() == 10); assert(intTrue1[0] == 1); assert(intTrue1[5] == 6); intTrue1[0] = 5; // int, true -> int, false Vector<int, false> intFalse2(intTrue1); assert(intFalse2.len() == 10); assert(intFalse2[0] == 5); assert(intFalse2[5] == 6); // int*, false Vector<int*, false> intStar1(10); intStar1[0] = new int(1); intStar1[1] = new int(2); assert(intStar1[5] == nullptr); assert(*(intStar1[0]) == 1); assert(*(intStar1[1]) == 2); // int, true -> int*, false Vector<int*, false> intStar2(intTrue1); assert(*(intStar2[0]) == 5); assert(*(intStar2[5]) == 6); assert(intStar2[0] != &(intFalse2[0])); assert(intStar2[5] != &(intFalse2[5])); // int*, false -> int, false Vector<int, false> intFalse3(intStar2); assert(intFalse3[0] == 5); assert(intFalse3[5] == 6); // int, false -> int*, false Vector<int*, false> intStar3(intFalse3); assert(*(intStar3[0]) == 5); assert(*(intStar3[5]) == 6); // int*, false -> int, true Vector<int, true> intTrue2(intStar3); assert(intTrue2[0] == 5); assert(intTrue2[5] == 6); assert(&(intTrue2[0]) != intStar3[0]); assert(&(intTrue2[5]) != intStar3[5]); // int*, false -> int*, false Vector<int*, false> intStar4(intStar3); assert(*(intStar4[0]) == 5); assert(*(intStar4[5]) == 6); assert(intStar4[0] != intStar3[0]); assert(intStar4[5] != intStar3[5]); // int, true -> int, true Vector<int, true> intTrue3(intTrue2); assert(intTrue3[0] == 5); assert(intTrue3[5] == 6); assert(&(intTrue3[0]) != &(intTrue2[0])); assert(&(intTrue3[5]) != &(intTrue2[5])); // int*, false -> int*, true Vector<int*, true> intStar5(intStar4); assert(*(intStar5[0]) == 5); assert(*(intStar5[5]) == 6); assert(intStar5[0] != intStar4[0]); assert(intStar5[5] != intStar4[5]); // intFalse1.caca(); } void operators() { // int, false -> int, true Vector<int, false> intFalse1(10); intFalse1[0] = 5; intFalse1[5] = 6; Vector<int, true> intTrue1(10); intTrue1 = intFalse1; assert(intTrue1[0] == 5); assert(intTrue1[5] == 6); assert(&(intTrue1[1]) != nullptr); // int, true -> int, false intTrue1[1] = 1; intTrue1[2] = 2; intFalse1 = intTrue1; assert(intFalse1[1] == 1); assert(intFalse1[2] == 2); // int, false -> int*, false Vector<int*, false> intStar1(10); intStar1 = intFalse1; assert(*(intStar1[0]) == 5); assert(*(intStar1[1]) == 1); assert(*(intStar1[2]) == 2); assert(*(intStar1[5]) == 6); // int*, false -> int, false *(intStar1[1]) = 10; intFalse1 = intStar1; assert(intFalse1[1] == 10); // int, true -> int*,false Vector<int*, false> intStar2(10); intStar2 = intTrue1; assert(*(intStar2[0]) == 5); assert(*(intStar2[1]) == 1); assert(*(intStar2[2]) == 2); assert(*(intStar2[5]) == 6); assert(intStar2[0] != &(intTrue1[0])); assert(intStar2[1] != &(intTrue1[1])); assert(intStar2[2] != &(intTrue1[2])); assert(intStar2[5] != &(intTrue1[5])); // int*, false -> int, true Vector<int, true> intTrue2(10); intTrue2 = intStar2; assert(intTrue2[0] == 5); assert(intTrue2[1] == 1); assert(intTrue2[2] == 2); assert(intTrue2[5] == 6); assert(intStar2[0] != &(intTrue2[0])); assert(intStar2[1] != &(intTrue2[1])); assert(intStar2[2] != &(intTrue2[2])); assert(intStar2[5] != &(intTrue2[5])); // int, true -> int, true Vector<int, true> intTrue3(10); intTrue3 = intTrue2; assert(intTrue3[0] == 5); assert(intTrue3[1] == 1); assert(intTrue3[2] == 2); assert(intTrue3[5] == 6); assert(&(intTrue3[0]) != &(intTrue2[0])); assert(&(intTrue3[1]) != &(intTrue2[1])); assert(&(intTrue3[2]) != &(intTrue2[2])); assert(&(intTrue3[5]) != &(intTrue2[5])); // int*, false -> int*, false Vector<int*, false> intStar3(10); delete intStar2[3]; intStar2[3] = nullptr; intStar3 = intStar2; assert(*(intStar3[0]) == 5); assert(*(intStar3[1]) == 1); assert(*(intStar3[2]) == 2); assert(*(intStar3[5]) == 6); assert(intStar2[0] != intStar3[0]); assert(intStar2[1] != intStar3[1]); assert(intStar2[2] != intStar3[2]); assert(intStar2[5] != intStar3[5]); assert(intStar3[3] == nullptr); // char, true -> int, true Vector<char, true> charTrue1(10); charTrue1[3] = 65; charTrue1[4] = 90; intTrue2 = charTrue1; assert(intTrue2[3] == 65); assert(intTrue2[4] == 90); assert(&(intTrue2[3]) != (int*)&(charTrue1[3])); assert(&(intTrue2[4]) != (int*)&(charTrue1[4])); } void conversions() { Vector<char, false> vectorInt(10); vectorInt[0] = 90; vectorInt[5] = 65; Vector<int, false> vectorChar(vectorInt); assert(vectorChar[0] == 90); assert(vectorChar[0] == 'Z'); assert(vectorChar[5] == 'A'); Vector<int, true> vectorCharTrue(vectorInt); assert(vectorCharTrue[0] == 'Z'); assert(vectorCharTrue[5] == 'A'); Vector<int*, false> vectorCharStar(vectorInt); assert(*(vectorCharStar[0]) == 'Z'); assert(*(vectorCharStar[5]) == 'A'); Vector<char*, false> vectorIntStar(10); vectorIntStar[0] = new char('Z'); vectorIntStar[5] = new char('A'); Vector<int*, false> vectorCharStar2(vectorIntStar); assert(*(vectorCharStar2[0]) == 'Z'); assert(*(vectorCharStar2[5]) == 'A'); Vector<int, true> vectorCharTrue2(vectorIntStar); assert(vectorCharTrue[0] == 'Z'); assert(vectorCharTrue[5] == 'A'); Vector<int, false> vectorChar2(vectorIntStar); assert(vectorChar2[0] == 'Z'); assert(vectorChar2[5] == 'A'); Vector<char, true> vectorIntTrue(10); vectorIntTrue[0] = 90; vectorIntTrue[5] = 65; Vector<int*, false> vectorCharStar3(vectorIntTrue); assert(*(vectorCharStar2[0]) == 'Z'); assert(*(vectorCharStar2[5]) == 'A'); Vector<int, true> vectorCharTrue3(vectorIntTrue); assert(vectorCharTrue[0] == 'Z'); assert(vectorCharTrue[5] == 'A'); Vector<int, false> vectorChar3(vectorIntTrue); assert(vectorChar2[0] == 'Z'); assert(vectorChar2[5] == 'A'); } void vStatic() { Vector<int, false> vector(10); vector[0] = 5; vector[5] = 6; VectorStatic<int, false, 10> vectorStatic1(vector); vectorStatic1[1] = 11; assert(vectorStatic1[0] == 5); assert(vectorStatic1[5] == 6); assert(vectorStatic1[1] == 11); } void sizeDifference() { Vector<int, false> vector1(10); vector1[0] = 5; Vector<int, true> vector2(9); vector2 = vector1; assert(vector2[0] != 5); Vector<int*, true> vector3(9); vector2[1] = 6; vector3 = vector2 = vector1; assert(vector2[0] != 5); assert(*(vector3[0]) != 5); assert(vector2[1] == 6); assert(*(vector3[1]) == 6); } void strings() { Vector<char, false> charFalse(7); charFalse[0] = 'W'; charFalse[1] = 'o'; charFalse[2] = 'r'; charFalse[3] = 'k'; charFalse[4] = 'i'; charFalse[5] = 'n'; charFalse[6] = 'g'; cout << charFalse << endl; Vector<char*, false> charStar(10); charStar[0] = new char[5]; charStar[0][0] = 'W'; charStar[0][1] = 'o'; charStar[0][2] = 'r'; charStar[0][3] = 'k'; charStar[0][4] = '\0'; charStar[1] = new char[5]; charStar[1][0] = 'i'; charStar[1][1] = 'n'; charStar[1][2] = 'g'; charStar[1][3] = '!'; charStar[1][4] = '\0'; cout << charStar << endl; Vector<string, false> stringFalse(10); stringFalse[0] = "Wor"; stringFalse[1] = "ki"; stringFalse[2] = "ng!"; cout << stringFalse << endl; } void iterators() { cout << endl << "iterator <int, false>" << endl; Vector<int, false> vector1(10); vector1[0] = 1; vector1[1] = 2; vector1[2] = 4; vector1[3] = 8; for (Vector<int, false>::iterator it = vector1.begin(); it != vector1.end(); it++) { cout << *it << " "; } cout << endl << "iterator <int*, ...>" << endl; Vector<int*, true> vector3(10); vector3[0] = new int(1); vector3[1] = new int(2); vector3[2] = new int(4); vector3[3] = new int(8); for (Vector<int*, true>::iterator it = vector3.begin(); it != vector3.end(); it++) { if (*it != nullptr) cout << **it << " "; else cout << "nullptr" << " "; } Vector<int, false> intFalse1(vector3.begin(), vector3.end()); assert(intFalse1[0] == 1); assert(intFalse1[1] == 2); assert(intFalse1[2] == 4); assert(intFalse1[3] == 8); Vector<int, false> intFalse2(intFalse1.begin(), intFalse1.end()); assert(intFalse2[0] == 1); assert(intFalse2[1] == 2); assert(intFalse2[2] == 4); assert(intFalse2[3] == 8); Vector<int, true> intTrue1(intFalse1.begin(), intFalse1.end()); assert(intTrue1[0] == 1); assert(intTrue1[1] == 2); assert(intTrue1[2] == 4); assert(intTrue1[3] == 8); Vector<int*, false> intStar1(intFalse1.begin(), intFalse1.end()); assert(*(intStar1[0]) == 1); assert(*(intStar1[1]) == 2); assert(*(intStar1[2]) == 4); assert(*(intStar1[3]) == 8); Vector<int, true> intTrue2(intStar1.begin(), intStar1.end()); assert(intTrue2[0] == 1); assert(intTrue2[1] == 2); assert(intTrue2[2] == 4); assert(intTrue2[3] == 8); } void integers() { Vector<int, false> intFalse1(10); intFalse1[0] = 1; intFalse1[1] = 2; Vector<int*, false> intStar1(10); intStar1[0] = new int(1); intStar1[1] = new int(2); Vector<int, true> intTrue1(10); intTrue1 = intFalse1 + intStar1; assert(intTrue1[0] == 2); assert(intTrue1[1] == 4); Vector<int, false> intFalse2(10); intFalse2 = intStar1 + intTrue1; assert(intFalse2[0] == 3); assert(intFalse2[1] == 6); Vector<int, true> intTrue2(10); intTrue2 = intFalse1 - intFalse2; assert(intTrue2[0] == -2); assert(intTrue2[1] == -4); assert(-intTrue2[0] == 2); assert(-intTrue2[1] == 4); assert(+intTrue2[0] == -2); assert(+intTrue2[1] == -4); double produit = intStar1 * intTrue1; assert(produit == 10); produit = intFalse1 * intFalse2; assert(produit == 15); produit = intFalse1 * intTrue1; assert(produit == 10); Vector<int, false> intFalse3(10); intFalse3[0] = 9; intFalse3[1] = 12; assert(intFalse3.norm() == 15); Vector<int*, false> intStar2(10); intStar2 = 7*intFalse3; assert(*(intStar2[0]) == 63); assert(*(intStar2[1]) == 84); } int main() { constructors(); // Ok operators(); // Ok conversions(); // Ok vStatic(); // Ok sizeDifference(); // Ok strings(); // Ok iterators(); integers(); return EXIT_SUCCESS; }
Java
UTF-8
1,387
2.375
2
[]
no_license
package model.objects; import java.util.ArrayList; public class Usuario { private Nivel nivel; private String nome; private String login; private String senha; private ArrayList<Sala> salas; private ArrayList<Demonstrativo> demonstrativos; public ArrayList<Sala> getSalas() { return salas; } public void setSalas(ArrayList<Sala> salas) { this.salas = salas; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } public ArrayList<Demonstrativo> getDemonstrativos() { return demonstrativos; } public void setDemonstrativos(ArrayList<Demonstrativo> demonstrativos) { this.demonstrativos = demonstrativos; } private Usuario usuario; public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public Usuario() { } public String getNivel() { return nivel.toString(); } public void setNivel(Nivel nivel) { this.nivel = nivel; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getEmail() { return login; } public void setEmail(String email) { this.login = email; } }
C++
GB18030
879
2.9375
3
[]
no_license
#include<iostream> #include<cstring> #include<cstdlib> using namespace std; int total = 0; void dfs(int n, int num, int j, int a[]){ //j if(num != n){ int i=1; while(i<=n){ bool flag = true; if(a[i]){ // flag = false; } if(flag){ int ii=i,jj=j; while(ii-1>=1&&jj-1>=1){ // ii--; jj--; if(a[ii]==jj){ flag = false; break; } } if(flag){ ii=i; jj=j; while(ii+1<=n&&jj-1>=1){ // ii++; jj--; if(a[ii]==jj){ flag = false; break; } } } } if(flag){ a[i] = j; dfs(n,num+1,j+1,a); a[i] = 0; i++; } else{ i++; } }; } else{ total++; } } int main(){ int n; cin >> n; int *a = new int[n+1]; //м¼ memset(a,0,sizeof(int)*(n+1)); dfs(n,0,1,a); cout << total; return 0; }
Markdown
UTF-8
3,533
3.515625
4
[]
no_license
# Money Shuffle ## *work in progress* <br> ## Description The Money Shuffle app is created for users who would like to keep better track of the money they spend. The app offers insight into how much budget is used for specific categories of expenses. The aim is to offer a straightforward and practical solution to keep an eye on where the money goes. To increase ease of use, the app uses rounded numbers (no decimals). One of the definitions of *shuffle* is to rearrange, to move from one place to another. The idea behind the app is that users set a budget for specific expenses, and keep track of their expenditures. The users are presented with an overview of expenditures versus budget at the end of the day or week. This makes it easy for users to rearrange the budget in case of unexpected expenses or changes in priorities. It also helps users to be more aware of where the money is going. The central component of the app is the overview page with the current budgets. Some standard expenditure categories are provided as a starting point (these can be changed or deleted). The user can: - create categories of expenses, or change/delete an existing category - keep an overview of the total amount of expenditure for each category - generate a weekly or monthly overview of expenditure per category - set alerts in case a certain percentage of a budget is reached The homepage has the categories of expenses and the user can click and go to the page of a category. On the category page, the user can: - set a budget for the current category of expenses - check the budget and add, edit and delete expenses <br> ## User Stories - **sign up** - As a user I want to be able to sign up to have access to the app and use it. - **login** - As a user I want to be able to log in so that I can access my account and use the app. - **logout** - As a user I want to be able to log out from the app so that I can make sure no one will access my account. - **error**- As a user I want to see when there is an error, and get a clear message of what I have to do next. - **homepage** - As a user I want to see a home page that is easy to navigate so that I can use the app right away. - **create budgets** - As a user, I want to be able to create budgets for expenditure categories of different types. - **edit/delete budgets** - As a user in the role of host, I want to be able to edit or delete budgets. - **budget details** - As a user, I want to be able to see the details of the budgets I have created. - **budget overviews** - As a user, I want to be able to generate daily and weekly overviews - **budget alerts** - As a user, I want to receive alerts regarding expenditure limits I have set for categories of expenses. <br> ## Minimal Viable Product (MVP) 1. Home page with overview of standard budget categories 2. Home page navbar with option to create a new category 3. A View/Edit button for each expenditure category 4. Functionality to create, edit and delete a budget category 5. Functionality to manage expenses (add, edit and delete expenses) 6. Page with credits for pictures and font used for the app <br> *Backlog* - *Page for sign up* - *Page for log in* - *Option to log out* - *Option to generate daily and weekly overviews per category of expenses* - *Option on home page to set alerts to be activated when a specific percentage of the budget has been spent* <br> ## Technology • JavaScript • React & React Router • Local storage • HTML • CSS • GitHub Pages for deployment
C++
UTF-8
10,536
2.53125
3
[]
no_license
#define BOOST_TEST_MODULE Remora_MatrixProxy #include <boost/test/unit_test.hpp> #include <boost/test/floating_point_comparison.hpp> #include <remora/proxy_expressions.hpp> #include <remora/dense.hpp> using namespace remora; template<class M1> double get(M1 const& m, std::size_t i, std::size_t j, row_major){ return m(i,j); } template<class M1> double get(M1 const& m, std::size_t i, std::size_t j, column_major){ return m(j,i); } template<class M1, class M2> void checkDenseMatrixEqual(M1 const& m1, M2 const& m2){ BOOST_REQUIRE_EQUAL(m1.size1(),m2.size1()); BOOST_REQUIRE_EQUAL(m1.size2(),m2.size2()); //indexed access for(std::size_t i = 0; i != m2.size1(); ++i){ for(std::size_t j = 0; j != m2.size2(); ++j){ BOOST_CHECK_EQUAL(m1(i,j),m2(i,j)); } } //iterator access rows for(std::size_t i = 0; i != m2.size1(); ++i){ typedef typename M1::const_major_iterator Iter; BOOST_REQUIRE_EQUAL(m1.major_end(i)-m1.major_begin(i), m1.size2()); std::size_t k = 0; for(Iter it = m1.major_begin(i); it != m1.major_end(i); ++it,++k){ BOOST_CHECK_EQUAL(k,it.index()); BOOST_CHECK_EQUAL(*it,get(m2,i,k, typename M1::orientation())); } //test that the actual iterated length equals the number of elements BOOST_CHECK_EQUAL(k, m1.size2()); } } template<class M1, class M2> void checkDenseMatrixAssignment(M1& m1, M2 const& m2){ BOOST_REQUIRE_EQUAL(m1.size1(),m2.size1()); BOOST_REQUIRE_EQUAL(m1.size2(),m2.size2()); //indexed access for(std::size_t i = 0; i != m2.size1(); ++i){ for(std::size_t j = 0; j != m2.size2(); ++j){ m1(i,j) = 0; BOOST_CHECK_EQUAL(m1(i,j),0); m1(i,j) = m2(i,j); BOOST_CHECK_EQUAL(m1(i,j),m2(i,j)); m1(i,j) = 0; BOOST_CHECK_EQUAL(m1(i,j),0); } } //iterator access rows for(std::size_t i = 0; i != major_size(m1); ++i){ typedef typename M1::major_iterator Iter; BOOST_REQUIRE_EQUAL(m1.major_end(i)-m1.major_begin(i), minor_size(m1)); std::size_t k = 0; for(Iter it = m1.major_begin(i); it != m1.major_end(i); ++it,++k){ BOOST_CHECK_EQUAL(k,it.index()); *it=0; BOOST_CHECK_EQUAL(*it,0); BOOST_CHECK_EQUAL(get(m1,i,k, typename M1::orientation()),0); *it = get(m2,i,k, typename M1::orientation()); BOOST_CHECK_EQUAL(*it,get(m2,i,k, typename M1::orientation())); BOOST_CHECK_EQUAL(get(m1,i,k, typename M1::orientation()),get(m2,i,k, typename M1::orientation())); } //test that the actual iterated length equals the number of elements BOOST_CHECK_EQUAL(k, minor_size(m1)); } } template<class V1, class V2> void checkDenseVectorEqual(V1 const& v1, V2 const& v2){ BOOST_REQUIRE_EQUAL(v1.size(),v2.size()); //indexed access for(std::size_t i = 0; i != v2.size(); ++i){ BOOST_CHECK_EQUAL(v1(i),v2(i)); } //iterator access rows typedef typename V1::const_iterator Iter; BOOST_REQUIRE_EQUAL(v1.end()-v1.begin(), v1.size()); std::size_t k = 0; for(Iter it = v1.begin(); it != v1.end(); ++it,++k){ BOOST_CHECK_EQUAL(k,it.index()); BOOST_CHECK_EQUAL(*it,v2(k)); } //test that the actual iterated length equals the number of elements BOOST_CHECK_EQUAL(k, v2.size()); } template<class V1, class V2> void checkDenseVectorAssignment(V1& v1, V2 const& v2){ BOOST_REQUIRE_EQUAL(v1.size(),v2.size()); //indexed access for(std::size_t i = 0; i != v2.size(); ++i){ v1(i) = 0; BOOST_CHECK_EQUAL(v1(i),0); v1(i) = v2(i); BOOST_CHECK_EQUAL(v1(i),v2(i)); v1(i) = 0; BOOST_CHECK_EQUAL(v1(i),0); } //iterator access rows typedef typename V1::iterator Iter; BOOST_REQUIRE_EQUAL(v1.end()-v1.begin(), v1.size()); std::size_t k = 0; for(Iter it = v1.begin(); it != v1.end(); ++it,++k){ BOOST_CHECK_EQUAL(k,it.index()); *it = 0; BOOST_CHECK_EQUAL(v1(k),0); *it = v2(k); BOOST_CHECK_EQUAL(v1(k),v2(k)); *it = 0; BOOST_CHECK_EQUAL(v1(k),0); } //test that the actual iterated length equals the number of elements BOOST_CHECK_EQUAL(k, v2.size()); } std::size_t Dimensions1 = 4; std::size_t Dimensions2 = 5; struct MatrixProxyFixture { matrix<double,row_major> denseData; matrix<double,column_major> denseDataColMajor; MatrixProxyFixture():denseData(Dimensions1,Dimensions2),denseDataColMajor(Dimensions1,Dimensions2){ for(std::size_t row=0;row!= Dimensions1;++row){ for(std::size_t col=0;col!=Dimensions2;++col){ denseData(row,col) = row*Dimensions2+col+5.0; denseDataColMajor(row,col) = row*Dimensions2+col+5.0; } } } }; BOOST_FIXTURE_TEST_SUITE (Remora_matrix_proxy, MatrixProxyFixture); BOOST_AUTO_TEST_CASE( Remora_Dense_Subrange ){ //all possible combinations of ranges on the data matrix for(std::size_t rowEnd=0;rowEnd!= Dimensions1;++rowEnd){ for(std::size_t rowBegin =0;rowBegin <= rowEnd;++rowBegin){//<= for 0 range for(std::size_t colEnd=0;colEnd!=Dimensions2;++colEnd){ for(std::size_t colBegin=0;colBegin != colEnd;++colBegin){ std::size_t size1= rowEnd-rowBegin; std::size_t size2= colEnd-colBegin; matrix<double> mTest(size1,size2); for(std::size_t i = 0; i != size1; ++i){ for(std::size_t j = 0; j != size2; ++j){ mTest(i,j) = denseData(i+rowBegin,j+colBegin); } } checkDenseMatrixEqual( subrange(denseData,rowBegin,rowEnd,colBegin,colEnd), mTest ); matrix<double> newData(Dimensions1,Dimensions2,0); matrix<double,column_major> newDataColMaj(Dimensions1,Dimensions2,0); auto rangeTest = subrange(newData,rowBegin,rowEnd,colBegin,colEnd); auto rangeTestColMaj = subrange(newDataColMaj,rowBegin,rowEnd,colBegin,colEnd); checkDenseMatrixAssignment(rangeTest,mTest); checkDenseMatrixAssignment(rangeTestColMaj,mTest); //check assignment { rangeTest=mTest; matrix<double> newData2(Dimensions1,Dimensions2,0); auto rangeTest2 = subrange(newData2,rowBegin,rowEnd,colBegin,colEnd); rangeTest2=rangeTest; for(std::size_t i = 0; i != size1; ++i){ for(std::size_t j = 0; j != size2; ++j){ BOOST_CHECK_EQUAL(newData(i+rowBegin,j+colBegin),mTest(i,j)); BOOST_CHECK_EQUAL(newData2(i+rowBegin,j+colBegin),mTest(i,j)); } } } //check clear for(std::size_t i = 0; i != size1; ++i){ for(std::size_t j = 0; j != size2; ++j){ rangeTest(i,j) = denseData(i+rowBegin,j+colBegin); rangeTestColMaj(i,j) = denseData(i+rowBegin,j+colBegin); } } rangeTest.clear(); rangeTestColMaj.clear(); for(std::size_t i = 0; i != size1; ++i){ for(std::size_t j = 0; j != size2; ++j){ BOOST_CHECK_EQUAL(rangeTest(i,j),0); BOOST_CHECK_EQUAL(rangeTestColMaj(i,j),0); } } } } } } } BOOST_AUTO_TEST_CASE( Remora_Dense_row){ for(std::size_t r = 0;r != Dimensions1;++r){ vector<double> vecTest(Dimensions2); for(std::size_t i = 0; i != Dimensions2; ++i) vecTest(i) = denseData(r,i); checkDenseVectorEqual(row(denseData,r),vecTest); checkDenseVectorEqual(row(denseDataColMajor,r),vecTest); matrix<double> newData(Dimensions1,Dimensions2,0); matrix<double,column_major> newDataColMajor(Dimensions1,Dimensions2,0); auto rowTest = row(newData,r); auto rowTestColMajor = row(newDataColMajor,r); checkDenseVectorAssignment(rowTest,vecTest); checkDenseVectorAssignment(rowTestColMajor,vecTest); //check assignment { rowTest=vecTest; matrix<double> newData2(Dimensions1,Dimensions2,0); auto rowTest2 = row(newData2,r); rowTest2=rowTest; for(std::size_t i = 0; i != Dimensions2; ++i){ BOOST_CHECK_EQUAL(newData(r,i),vecTest(i)); BOOST_CHECK_EQUAL(newData2(r,i),vecTest(i)); } } //check clear for(std::size_t i = 0; i != Dimensions2; ++i){ rowTest(i) = double(i); rowTestColMajor(i) = double(i); } rowTest.clear(); rowTestColMajor.clear(); for(std::size_t i = 0; i != Dimensions2; ++i){ BOOST_CHECK_EQUAL(rowTest(i),0.0); BOOST_CHECK_EQUAL(rowTestColMajor(i),0.0); } } } BOOST_AUTO_TEST_CASE( Remora_Dense_column){ for(std::size_t c = 0;c != Dimensions2;++c){ vector<double> vecTest(Dimensions1); for(std::size_t i = 0; i != Dimensions1; ++i) vecTest(i) = denseData(i,c); checkDenseVectorEqual(column(denseData,c),vecTest); matrix<double> newData(Dimensions1,Dimensions2,0); matrix<double,column_major> newDataColMajor(Dimensions1,Dimensions2,0); auto columnTest = column(newData,c); auto columnTestColMajor = column(newDataColMajor,c); checkDenseVectorAssignment(columnTest,vecTest); checkDenseVectorAssignment(columnTestColMajor,vecTest); { columnTest=vecTest; matrix<double> newData2(Dimensions1,Dimensions2,0); auto columnTest2 = column(newData2,c); columnTest2=columnTest; for(std::size_t i = 0; i != Dimensions1; ++i){ BOOST_CHECK_EQUAL(newData(i,c),vecTest(i)); BOOST_CHECK_EQUAL(newData2(i,c),vecTest(i)); } } //check clear for(std::size_t i = 0; i != Dimensions1; ++i){ columnTest(i) = double(i); columnTestColMajor(i) = double(i); } columnTest.clear(); columnTestColMajor.clear(); for(std::size_t i = 0; i != Dimensions1; ++i){ BOOST_CHECK_EQUAL(columnTest(i),0.0); BOOST_CHECK_EQUAL(columnTestColMajor(i),0.0); } } } BOOST_AUTO_TEST_CASE( Remora_To_Vector){ { vector<double> vecTest(Dimensions1 * Dimensions2); for(std::size_t i = 0; i != Dimensions1; ++i) for(std::size_t j = 0;j != Dimensions2;++j) vecTest(i * Dimensions2 + j) = denseData(i,j); checkDenseVectorEqual(to_vector(denseData),vecTest); matrix<double,row_major> m(Dimensions1,Dimensions2,0); auto test = to_vector(m); checkDenseVectorAssignment(test,vecTest); } { vector<double> vecTest(Dimensions1 * Dimensions2); for(std::size_t i = 0; i != Dimensions1; ++i) for(std::size_t j = 0;j != Dimensions2;++j) vecTest(j * Dimensions1 + i) = denseData(i,j); checkDenseVectorEqual(to_vector(denseDataColMajor),vecTest); matrix<double,column_major> m(Dimensions1,Dimensions2,0); auto test = to_vector(m); checkDenseVectorAssignment(test,vecTest); } } BOOST_AUTO_TEST_CASE( Remora_To_Matrix){ vector<double> vecData(Dimensions1 * Dimensions2); for(std::size_t i = 0; i != Dimensions1; ++i) for(std::size_t j = 0;j != Dimensions2;++j) vecData(i * Dimensions2 + j) = denseData(i,j); checkDenseMatrixEqual(to_matrix(vecData,Dimensions1,Dimensions2),denseData); vector<double> newData(Dimensions1 * Dimensions2,1.0); auto test = to_matrix(newData,Dimensions1,Dimensions2); checkDenseMatrixAssignment(test,denseData); test = denseData; checkDenseVectorEqual(newData, vecData); } BOOST_AUTO_TEST_SUITE_END();
PHP
UTF-8
889
2.640625
3
[]
no_license
<?php function insereProduto($conexao, $nome, $valor){ $comando = "insert into produtos(nome, valor) values ('{$nome}', {$valor})"; $resultado = mysqli_query($conexao, $comando); return $resultado; } function listaProdutos($conexao){ return mysqli_query($conexao, "select * from produtos"); } function buscaProduto($conexao, $id){ $comando = "select * from produtos where id={$id}"; $resultado = mysqli_query($conexao, $comando); return mysqli_fetch_assoc($resultado); } function alteraProduto($conexao, $id, $nome, $valor){ $comando = "update produtos set nome='{$nome}', valor={$valor} where id={$id}"; $resultado = mysqli_query($conexao, $comando); return $resultado; } function removeProduto($conexao, $id){ $comando = "delete from produtos where id={$id}"; $resultado = mysqli_query($conexao, $comando); return $resultado; } ?>
Java
UTF-8
11,165
2.34375
2
[]
no_license
import java.io.*; import java.math.*; import java.util.*; import static java.util.Arrays.*; public class Main { private static final int mod = (int)1e9+7; final Random random = new Random(0); final IOFast io = new IOFast(); /// MAIN CODE public void run() throws IOException { long[][] comb = new long[401][401]; long[] fact = new long[401]; fact[0] = 1; for(int i = 0; i < comb.length; i++) { if(i > 0) fact[i] = fact[i-1] * i; comb[i][0] = comb[i][i] = 1; for(int j = 1; j < i; j++) { comb[i][j] = comb[i-1][j-1] + comb[i-1][j]; } } // dump(comb[400][6]); // int TEST_CASE = Integer.parseInt(new String(io.nextLine()).trim()); int TEST_CASE = 1; while(TEST_CASE-- != 0) { int n = io.nextInt(); int[][] C = io.nextIntArray2D(n, 4); long ans = 0; // int[] p1 = new int[]{0, 1, 2, 3,}; int[] p2 = new int[]{1, 0, 3, 2,}; RollingHashMod[] rh = new RollingHashMod[n]; for(int i = 0; i < n; i++) rh[i] = new RollingHashMod(C[i]); final TreeMap<Long, Integer> mp = new TreeMap<>(); // dump(3, rh[3].str, rh[3].minRotateIndex()); // if(true) throw new RuntimeException(); for(int i = 0; i < n; i++) { long h = rh[i].minRotateHash(); mp.put(h, mp.getOrDefault(h, 0) + 1); // dump(i, rh[i].str, rh[i].minRotateIndex(), h); } // if(true) throw new RuntimeException(); int[] dup = new int[4]; /* * 1 2 * 3 4 * * 1 2 * 3 4 */ for(int i = 0; i < n; i++) { mp.put(rh[i].minRotateHash(), mp.get(rh[i].minRotateHash()) - 1); for(int j = i + 1; j < n; j++) for(int d = 0; d < 4; d++) { Arrays.fill(dup, 1); RollingHashMod[] hs = new RollingHashMod[4]; for(int s = 0; s < 4; s++) { hs[s] = new RollingHashMod(C[i][(s+1)&3], C[i][(s+0)&3], C[j][p2[(s+d+0)&3]], C[j][p2[(s+d+1)&3]]); } long val = 1; for(int s = 0; s < 4; s++) if(dup[s] == 1) { for(int k = s + 1; k < 4; k++) { if(hs[s].minRotateHash() == hs[k].minRotateHash()) { dup[k] = -1; dup[s]++; } } // int cnt = mp.getOrDefault(hs[s].minRotateHash(), 0); if(rh[j].minRotateHash() == hs[s].minRotateHash()) { cnt--; } int hi = hs[s].minRotateIndex(); int sym = 1; if(hs[s].minRotateHash() == hs[s].hash((hi + 1) % 4, (hi + 1) % 4)) { sym = 4; } else if(hs[s].minRotateHash() == hs[s].hash((hi + 2) % 4, (hi + 2) % 4)) { sym = 2; } long pow = 1; long comb_fact = 1; for(int k = 0; k < dup[s]; k++) { pow *= sym; comb_fact *= cnt - k; } val *= pow * comb_fact; // if(i == 1 && j == 3 && d == 3) { // dump(i, j, s, dup[s], sym, cnt, hs[s].str, hs[s].minRotateHash(), hs[s].minRotateIndex(), val); // } } // dump(i, j, d, dup, val); ans += val; } } io.out.println(ans); } } static class RollingHashMod { private static final int[] LARGE_PRIMES = new int[]{ 1000000007, 1000000009, 1000000021, 1000000033, 1000000087, 1000000093, 1000000097, 1000000103, 1000000123, 1000000181, 1000000207, 1000000223, 1000000241, 1000000271, 1000000289, 1000000297, 1000000321, 1000000349, 1000000363, 1000000403, }; private static final Random random = new Random(0); private static final int HASH_NUM = 2; // private static final long RADIX = 1000000409; private static final long RADIX = 1000000003; private static final long XOR = random.nextLong(); private int n; private static int[] primes; private int[] str; private int[][] pow; private int[][] table; public RollingHashMod(int... str) { if(primes == null) { // final Random random = new Random(System.currentTimeMillis()); primes = new int[HASH_NUM]; for(int i = 0; i < HASH_NUM; i++) { final int idx = random.nextInt(LARGE_PRIMES.length - i); primes[i] = LARGE_PRIMES[idx]; LARGE_PRIMES[idx] = LARGE_PRIMES[LARGE_PRIMES.length - i - 1]; LARGE_PRIMES[LARGE_PRIMES.length - i - 1] = primes[i]; } } n = str.length; this.str = str.clone(); table = new int[HASH_NUM][n + 1]; pow = new int[HASH_NUM][n + 1]; for(int j = 0; j < HASH_NUM; j++) { final int p = primes[j]; pow[j][0] = 1; for (int i = 0; i < n; i++) { table[j][i + 1] = (int)(((long)table[j][i] * RADIX + (this.str[i]^XOR)%p + p) % p); pow[j][i + 1] = (int)((long)pow[j][i] * RADIX % p); } } } public long hash(int i, int j) { if(j >= n) { j -= n; } if(i >= j) { return hashRotate(i, j); } else { return hash(0, i, j) << 32 | hash(1, i, j); } } public long hashRotate(int i, int j) { assert(i >= j); long h0 = hash(0, i, n) * pow[0][j] % primes[0] + table[0][j]; long h1 = hash(1, i, n) * pow[1][j] % primes[1] + table[1][j]; if(h0 >= primes[0]) h0 -= primes[0]; if(h1 >= primes[1]) h1 -= primes[1]; // dump(str, i, j, h0, h1, hash(0, i, n), table[0]); return h0 << 32 | h1; } private long hash(int idx, int i, int j) { assert(i <= j); long h0 = table[idx][j] - (long)table[idx][i] * pow[idx][j - i] % primes[idx]; if(h0 < 0) h0 += primes[idx]; return h0; } public long minRotateHash() { int s = minRotateIndex(); return hash(s, s); } private int minRotateCache = -1; public int minRotateIndex() { if(minRotateCache != -1) return minRotateCache; int s = n - 1; for(int i = n - 2; i >= 0; i--) { int low = 0, high = n; while(high - low > 1) { int mid = (low + high) / 2; if(hash(i, i + mid) == hash(s, s + mid)) { low = mid; } else { high = mid; } } // dump(i, s, str, low, high); if(str[(i + low) % n] <= str[(s + low) % n]) { s = i; } } return minRotateCache = s; } } /// TEMPLATE static int gcd(int n, int r) { return r == 0 ? n : gcd(r, n%r); } static long gcd(long n, long r) { return r == 0 ? n : gcd(r, n%r); } static <T> void swap(T[] x, int i, int j) { T t = x[i]; x[i] = x[j]; x[j] = t; } static void swap(int[] x, int i, int j) { int t = x[i]; x[i] = x[j]; x[j] = t; } void printArrayLn(int[] xs) { for(int i = 0; i < xs.length; i++) io.out.print(xs[i] + (i==xs.length-1?"\n":" ")); } void printArrayLn(long[] xs) { for(int i = 0; i < xs.length; i++) io.out.print(xs[i] + (i==xs.length-1?"\n":" ")); } static void dump(Object... o) { System.err.println(Arrays.deepToString(o)); } void main() throws IOException { // IOFast.setFileIO("rle-size.in", "rle-size.out"); try { run(); } catch (EndOfFileRuntimeException e) { } io.out.flush(); } public static void main(String[] args) throws IOException { new Main().main(); } static class EndOfFileRuntimeException extends RuntimeException { private static final long serialVersionUID = -8565341110209207657L; } static public class IOFast { private BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); private PrintWriter out = new PrintWriter(System.out); void setFileIn(String ins) throws IOException { in.close(); in = new BufferedReader(new FileReader(ins)); } void setFileOut(String outs) throws IOException { out.flush(); out.close(); out = new PrintWriter(new FileWriter(outs)); } void setFileIO(String ins, String outs) throws IOException { setFileIn(ins); setFileOut(outs); } private static int pos, readLen; private static final char[] buffer = new char[1024 * 8]; private static char[] str = new char[500*8*2]; private static boolean[] isDigit = new boolean[256]; private static boolean[] isSpace = new boolean[256]; private static boolean[] isLineSep = new boolean[256]; static { for(int i = 0; i < 10; i++) { isDigit['0' + i] = true; } isDigit['-'] = true; isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true; isLineSep['\r'] = isLineSep['\n'] = true; } public int read() throws IOException { if(pos >= readLen) { pos = 0; readLen = in.read(buffer); if(readLen <= 0) { throw new EndOfFileRuntimeException(); } } return buffer[pos++]; } public int nextInt() throws IOException { int len = 0; str[len++] = nextChar(); len = reads(len, isSpace); int i = 0; int ret = 0; if(str[0] == '-') { i = 1; } for(; i < len; i++) ret = ret * 10 + str[i] - '0'; if(str[0] == '-') { ret = -ret; } return ret; } public long nextLong() throws IOException { int len = 0; str[len++] = nextChar(); len = reads(len, isSpace); int i = 0; long ret = 0; if(str[0] == '-') { i = 1; } for(; i < len; i++) ret = ret * 10 + str[i] - '0'; if(str[0] == '-') { ret = -ret; } return ret; } public char nextChar() throws IOException { while(true) { final int c = read(); if(!isSpace[c]) { return (char)c; } } } int reads(int len, boolean[] accept) throws IOException { try { while(true) { final int c = read(); if(accept[c]) { break; } if(str.length == len) { char[] rep = new char[str.length * 3 / 2]; System.arraycopy(str, 0, rep, 0, str.length); str = rep; } str[len++] = (char)c; } } catch(EndOfFileRuntimeException e) { ; } return len; } int reads(char[] cs, int len, boolean[] accept) throws IOException { try { while(true) { final int c = read(); if(accept[c]) { break; } cs[len++] = (char)c; } } catch(EndOfFileRuntimeException e) { ; } return len; } public char[] nextLine() throws IOException { int len = 0; str[len++] = nextChar(); len = reads(len, isLineSep); try { if(str[len-1] == '\r') { len--; read(); } } catch(EndOfFileRuntimeException e) { ; } return Arrays.copyOf(str, len); } public String nextString() throws IOException { return new String(next()); } public char[] next() throws IOException { int len = 0; str[len++] = nextChar(); len = reads(len, isSpace); return Arrays.copyOf(str, len); } // public int next(char[] cs) throws IOException { int len = 0; cs[len++] = nextChar(); len = reads(cs, len, isSpace); return len; } public double nextDouble() throws IOException { return Double.parseDouble(nextString()); } public long[] nextLongArray(final int n) throws IOException { final long[] res = new long[n]; for(int i = 0; i < n; i++) { res[i] = nextLong(); } return res; } public int[] nextIntArray(final int n) throws IOException { final int[] res = new int[n]; for(int i = 0; i < n; i++) { res[i] = nextInt(); } return res; } public int[][] nextIntArray2D(final int n, final int k) throws IOException { final int[][] res = new int[n][]; for(int i = 0; i < n; i++) { res[i] = nextIntArray(k); } return res; } public int[][] nextIntArray2DWithIndex(final int n, final int k) throws IOException { final int[][] res = new int[n][k+1]; for(int i = 0; i < n; i++) { for(int j = 0; j < k; j++) { res[i][j] = nextInt(); } res[i][k] = i; } return res; } public double[] nextDoubleArray(final int n) throws IOException { final double[] res = new double[n]; for(int i = 0; i < n; i++) { res[i] = nextDouble(); } return res; } } }
Python
UTF-8
2,614
2.65625
3
[]
no_license
#-*- coding:utf-8 -*- # AUTHOR: yaolili # FILE: twoLayers.py # ROLE: get properties of specific freebaseId # CREATED: 2015-11-28 14:45:23 # MODIFIED: 2015-11-28 20:20:52 import sys import os import re import MySQLdb def connectDB(freebaseIdList): result = {} if not freebaseIdList: return result try: db = MySQLdb.connect(host="localhost", user="root", passwd="q1w2e3r4", db="wikiLink") cursor = db.cursor() for freebaseId in freebaseIdList: sql = "SELECT wikiId FROM wikiFreebaseId WHERE freebaseId = \"%s\"" % (freebaseId) cursor.execute(sql) wikiId = cursor.fetchone() if wikiId: wikiId = int(wikiId[0]) getStringSql = "SELECT property FROM wikiPro WHERE wikiId = %d" % (wikiId) cursor.execute(getStringSql) string = cursor.fetchone() if string: #print "string match!" result[freebaseId] = string return result except MySQLdb.Error, e: print e db.close() def isFreebaseEntity(obj): reStr = "^m\..+" result = re.match(reStr, obj) if result: return True else: return False def twoLayers(inputFile, outputFile): result = open(outputFile, "w+") try: with open(inputFile, "r") as fin: for lineNum, line in enumerate(fin): freebase, string = line.strip().split("\t") pattern = r"(\[.*?\])"; reResult = re.findall(pattern, string, re.M) if(reResult): freebaseIdList = [] for i in range(0, len(reResult)): reResult[i] = reResult[i].replace('[','').replace(']','') predicate, obj = reResult[i].strip().split(", ") obj = obj.strip().split("'") if(isFreebaseEntity(obj[1])): freebaseIdList.append(obj[1]) secondInfo = connectDB(freebaseIdList) if secondInfo: for key in secondInfo: result.write(str(lineNum) + ":" + key + "\t" + str(secondInfo[key]) + "\n") print "file done!" result.close() except IOError, e: print 'Could not open file:', e exit() if __name__ == '__main__': if len(sys.argv) < 3: print "sys.argv[1]: input entity.txt file" print "sys.argv[2]: output file" exit() twoLayers(sys.argv[1], sys.argv[2])
Java
UTF-8
241
2.578125
3
[]
no_license
package com.github.lette1394.calculator; public class PartialOperand implements Operand { @Override public Operand apply(Operator operator, Operand other) { return null; } @Override public long asLong() { return 0; } }
Shell
UTF-8
1,027
3.359375
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env bash NAME=calibre CONTENT_SERVER_PORT=7777 PORT=10002 WAIT=4 if [ ! "$(docker ps -q -f name=$NAME)" ]; then if [ "$(docker ps -aq -f status=exited -f name=$NAME)" ]; then echo "Starting existing $NAME container..." docker start $NAME sleep $WAIT open http://localhost:$PORT else echo "Starting new $NAME container..." docker run \ -d \ --name $NAME \ -v "${HOME}/calibre-library:/calibre-library" \ -v "${HOME}/calibre-autoscan:/calibre-autoscan" \ -v "${HOME}/calibre-inbox:/nobody/inbox" \ -p ${CONTENT_SERVER_PORT}:7777 \ -p ${PORT}:32000 \ ivonet/$NAME sleep $WAIT open http://localhost:$PORT fi else echo "Stopping $NAME..." docker stop $NAME fi
C#
UTF-8
866
2.71875
3
[]
no_license
public void InlineQueryWrite(Dictionary<Int32, PhaseMag> data) { using (var conn = new SqlConnection("conneciton string")) { conn.Open(); foreach (var bulk in data.Select((d, i) => new {d, i}).GroupBy(x => x.i % 10)) { var sb = new StringBuilder(); foreach (var x in bulk) { sb.AppendFormat("Insert Into Your_Table (Key, Magnitude, Phase) Values ({0},{1},{2});", x.d.Key, x.d.Value.Magnitude, x.d.Value.Phase); } using (var command = conn.CreateCommand()) { command.CommandText = sb.ToString(); command.ExecuteNonQuery(); } } } }
Python
UTF-8
12,508
3.09375
3
[]
no_license
# hardware control protocol imports: import minimalmodbus import serial import visa # --- abstract class which we want all innstrument classes to inherite --- class Instrument(): """Every instrument must inherite from the Instrument class and therefore must implement: -> the measure method -> the open method -> the close method -> the get_y_label method ...or a NotImplementedError is raised if the app will call one of those methods! The following is optional: -> the has_port_settings method ...override it only if the Instrument is connected to some sort of a port that is named and it will make sense for the user to change this name e.g. a serial port of an Instrument could be named COM6 on one PC and COM7 on another """ # of cause we want the Instrument to measure something! def measure(self) -> float: raise NotImplementedError("No method: measure() implemented on", self.__class__.__name__) # every Instrument must have some sort of connection to the PC so we # need a method for opening and closing this connection! def open(self): raise NotImplementedError("No method: open() implemented on", self.__class__.__name__) def close(self): raise NotImplementedError("No method: close() implemented on", self.__class__.__name__) # a class method that tells the MeasurementPage # whether we can set the port settings in the GUI or not! # override this method so that it returns True if port settings make sense # for the Instrument def has_port_settings(): return False # this is used for labeling the axis(and legend) when plotting the data measured with measure! # note: this is a class function! def get_labels() -> str: raise NotImplementedError("No method: get_labels() implemented!") # --- custom instruments --- class LightSwitch(Instrument): """ The light switch is conncted to a Arduino. The command "R\n" sent will lead to the Arduino responding with 1 or 0 (ON or OFF). """ def __init__(self, port=None, baudrate=9600, timeout=0.5): if port == None: port = "COM7" self.serial = serial.Serial(port=port, baudrate=baudrate, timeout=timeout, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE) print(f"{self.__class__.__name__} has been successfully initialized!\n{self.serial}") def has_port_settings(): return True def open(self): print("Opening connection of:", self.__class__.__name__, "again...") self.serial.open() if self.serial.is_open: print("Connection of instrument:", self.__class__.__name__, " has been opened!") else: raise IOError("Failed to open connection of instrument:", self.__class__.__name__) def close(self): print("Closing connection of:", self.__class__.__name__) self.serial.close() if not self.serial.is_open: print("Connection of instrument:", self.__class__.__name__, " has been closed!") else: raise IOError("Failed to close connection of instrument:", self.__class__.__name__) def measure(self): self.serial.write(("R\n").encode("ascii")) # wait till all data is written: self.serial.flush() msg = self.serial.readline().decode("ascii") print(f"{self.__class__.__name__}: {msg}") return float(msg) def get_labels() -> str: # the first is for the axis label, the second for the legend label: return ("Sensor ON/OFF (1/0)", "Light Sensor") class Eurotherm2416(minimalmodbus.Instrument, Instrument): def __init__(self, port=None, baudrate=9600): # if no port specified use the default port: if port == None: port = "COM7" # we will open a serial port inside the minimalmodbus.Instrument __init__ # with the baudrate constant of the module so we need to set this: minimalmodbus.BAUDRATE = baudrate print("Starting", self.__class__.__name__, "initialization...") # 1 is the slaveadress (1 to 247) minimalmodbus.Instrument.__init__(self, port, 1) # check the instrument properties, this will # call __repr__ of minimalmodbus.Instrument: print(self) print("Finished", self.__class__.__name__, "initialization...") def has_port_settings(): return True def open(self): print("Opening connection of:", self.__class__.__name__, "again...") # in minimalmodbus.Instrument.__init__(self, port, 1) we create a Serial object: # self.serial = serial.Serial(port=port, baudrate=BAUDRATE, parity=PARITY, # bytesize=BYTESIZE, stopbits=STOPBITS, timeout=TIMEOUT) # so let's open this connection here again: self.serial.open() if self.serial.is_open: print("Connection of instrument:", self.__class__.__name__, " has been opened!") else: raise IOError("Failed to open connection of instrument:", self.__class__.__name__) def close(self): print("Closing connection of:", self.__class__.__name__) self.serial.close() if not self.serial.is_open: print("Connection of instrument:", self.__class__.__name__, " has been closed!") else: raise IOError("Failed to close connection of instrument:", self.__class__.__name__) def measure(self) -> float: # arguments of read_register() method: # > register address we want to read from # > number of decimals # --> see docs: # If a value of 77.0 is stored internally in the slave register as 770, # then use numberOfDecimals=1 which will divide the received data # by 10 before returning the value temp = self.read_register(289, 1) print(self.__class__.__name__, "response:", temp) return temp def get_labels() -> str: # the first is for the axis label, the second for the legend label: return ("Temperature in °C", "Temperature") class FMI220(Instrument): """ Most common commands: AD ... actual value mode AG ... units in N AA ... set current force value to null point BA ... one shot force measurement """ def __init__(self, port=None, baudrate=9600, timeout=0.5): # if no port specified use the default port: if port == None: port = "COM6" self.serial = serial.Serial(port=port, baudrate=baudrate, timeout=timeout, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE) print("Starting FMI220 initialization...") # check instrument properties by calling __repr__ implicitly: print(self) # for further information see most command command list above self.query("AD") self.query("AG") self.query("AA") print("Finished FMI220 initialization...") def has_port_settings(): return True def open(self): print("Opening connection of:", self.__class__.__name__, "again...") self.serial.open() if self.serial.is_open: print("Connection of instrument:", self.__class__.__name__, " has been opened!") else: raise IOError("Failed to open connection of instrument:", self.__class__.__name__) def close(self): print("Closing connection of:", self.__class__.__name__) self.serial.close() if not self.serial.is_open: print("Connection of instrument:", self.__class__.__name__, " has been closed!") else: raise IOError("Failed to close connection of instrument:", self.__class__.__name__) def __repr__(self): # string representaion of FMI220 object: return "{}.{}<id=0x{:x}, serial={}>".format(self.__module__, self.__class__.__name__, id(self), self.serial) def query(self, command) -> str: # clear buffer of eventual remaining content: self.serial.reset_input_buffer() # write command to instrument: bytes_writen = self.serial.write((command+"\r").encode("ascii")) # wait till all data is written: self.serial.flush() if command=="BA": # one shot measurement: msg = self.serial.read(size=12).decode("ascii").replace("\r","")[4:] else: # change settings: msg = self.serial.read(size=3).decode("ascii") print("FMI220 query response:", msg) return msg def measure(self) -> float: force = float(self.query("BA")) print("FMI220 response:", force) return force def get_labels() -> str: return ("Force in N", "Force") class Keithley2000(Instrument): # TODO: implement voltage measurement RESISTANCE = 0 VOLTAGE = 1 # choose what you want to measure by the corresponding function code: # (note: the function code has to match the function code in the get_labels method!) def __init__(self, function=0): # self.gpib will be a obect of: pyvisa.resources.Resource # with the open and close method of that resource we can open and close # a session! self.gpib = None self.function = function print("Starting Keithley2000 initialization...") self.open_gpib_connection() if self.function == Keithley2000.RESISTANCE: init_code = ["*rst; status:preset; *cls;", "configure:fresistance", "fresistance:range:auto ON", "sense:fresistance:nplcycles 0.01"] elif self.function == Keithley2000.VOLTAGE: init_code = [] raise NotImplementedError("Voltage measurement not implemented yet!") else: raise ValueError("Function number not supported!") print("Keithley2000 info:", self.gpib.query('*IDN?')) print("Initialize Keithley2000 with code:") print(init_code) for command in init_code: self.gpib.write(command) print("Check measurement properties on Keithley2000:") if self.function == Keithley2000.RESISTANCE: print("Range auto:", self.gpib.query("fresistance:range:auto?")) print("Cycles:", self.gpib.query("fresistance:nplcycles?")) elif self.function == Keithley2000.VOLTAGE: pass print("Finished Keithley2000 initialization...") def open_gpib_connection(self): rm = visa.ResourceManager() resource_list = rm.list_resources() for resource in resource_list: if "GPIB" in resource: print("Trying to open gpib connection...", resource) self.gpib = rm.open_resource(resource) if self.gpib == None: raise RuntimeError("No gpib connection found!") def open(self): print("Opening connection of:", self.__class__.__name__, "again...") self.gpib.open() print("Connection of instrument:", self.__class__.__name__, " has been opened!") print(self.gpib.resource_info) def close(self): print("Closing connection of:", self.__class__.__name__) self.gpib.close() print("Connection of instrument:", self.__class__.__name__, " has been closed!") def measure(self) -> float: if self.function == Keithley2000.RESISTANCE: response = float(self.gpib.query("read?")[:-1]) elif self.function == Keithley2000.VOLTAGE: pass print("Keithley2000 response:", response) return response # a function to get the string label which should be used for plotting data # measured from this instrument: # (note: the function code has to match the function code in the init method!) def get_labels(function=0) -> str: if function == Keithley2000.RESISTANCE: return ("Resistance in OHM", "Resistance") elif function == Keithley2000.VOLTAGE: return ("Voltage in V", "Voltage")
Java
UTF-8
7,573
1.8125
2
[]
no_license
package com.example.sofra.ui.activity; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import com.example.sofra.R; import com.example.sofra.data.local.room.OrderItem; import com.example.sofra.data.local.room.RoomDao; import com.example.sofra.ui.fragment.homeCycle.CartFragment; import com.example.sofra.ui.fragment.homeCycle.ClientMoreFragment; import com.example.sofra.ui.fragment.homeCycle.ClientOrderContainerFragment; import com.example.sofra.ui.fragment.homeCycle.EditClientProfileFragment; import com.example.sofra.ui.fragment.homeCycle.NotificationFragment; import com.example.sofra.ui.fragment.homeCycle.RestaurantListFragment; import com.example.sofra.ui.fragment.homeCycle.EditRestaurantProfileFragment; import com.example.sofra.ui.fragment.homeCycle.CommissionFragment; import com.example.sofra.ui.fragment.homeCycle.RestaurantCategoriesFragment; import com.example.sofra.ui.fragment.homeCycle.RestaurantMoreFragment; import com.example.sofra.ui.fragment.homeCycle.RestaurantOrderContainerFragment; import com.google.android.material.bottomnavigation.BottomNavigationView; import java.util.List; import java.util.concurrent.Executors; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import static com.example.sofra.data.local.SharedPreferencesManger.LoadData; import static com.example.sofra.data.local.SofraConstans.USER_TYPE; import static com.example.sofra.data.local.room.RoomManger.getInstance; import static com.example.sofra.helper.HelperMethod.customToast; import static com.example.sofra.helper.HelperMethod.replace; public class HomeActivity extends BaseActivity implements BottomNavigationView.OnNavigationItemSelectedListener { @BindView(R.id.activity_home_bottom_navigation) public BottomNavigationView bottomNavigationView; @BindView(R.id.activity_home_tv_title) public TextView activityHomeTvTitle; @BindView(R.id.activity_home_iv_cart) ImageView activityHomeIvCart; String userType; RestaurantListFragment restaurantListFragment; ClientOrderContainerFragment clientOrderContainerFragment; EditClientProfileFragment editClientProfileFragment; ClientMoreFragment clientMoreFragment; RestaurantCategoriesFragment restaurantCategoriesFragment; RestaurantMoreFragment restaurantMoreFragment; RestaurantOrderContainerFragment restaurantOrderContainerFragment; EditRestaurantProfileFragment editRestaurantProfileFragment; CartFragment cartFragment; RoomDao roomDao; List<OrderItem> ordersList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); ButterKnife.bind(this); roomDao = getInstance(HomeActivity.this).roomDao(); userType = LoadData(this, USER_TYPE); restaurantListFragment = new RestaurantListFragment(); clientOrderContainerFragment = new ClientOrderContainerFragment(); editClientProfileFragment = new EditClientProfileFragment(); clientMoreFragment = new ClientMoreFragment(); cartFragment = new CartFragment(); restaurantCategoriesFragment = new RestaurantCategoriesFragment(); restaurantMoreFragment = new RestaurantMoreFragment(); restaurantOrderContainerFragment = new RestaurantOrderContainerFragment(); editRestaurantProfileFragment = new EditRestaurantProfileFragment(); if (userType.equals("client")) { activityHomeIvCart.setImageResource(R.drawable.ic_shopping); replace(restaurantListFragment, getSupportFragmentManager(), R.id.activity_home_fl_frame, null, null); } else if (userType.equals("restaurant")) { activityHomeIvCart.setImageResource(R.drawable.ic_calculator); replace(restaurantCategoriesFragment, getSupportFragmentManager(), R.id.activity_home_fl_frame, null, null); } bottomNavigationView.setOnNavigationItemSelectedListener(this); } @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.home: if (userType.equals("client")) { replace(restaurantListFragment, getSupportFragmentManager(), R.id.activity_home_fl_frame, null, null); } else if (userType.equals("restaurant")) { replace(restaurantCategoriesFragment, getSupportFragmentManager(), R.id.activity_home_fl_frame, null, null); } break; case R.id.check_list: if (userType.equals("client")) { replace(clientOrderContainerFragment, getSupportFragmentManager(), R.id.activity_home_fl_frame, null, null); } else if (userType.equals("restaurant")) { replace(restaurantOrderContainerFragment, getSupportFragmentManager(), R.id.activity_home_fl_frame, null, null); } break; case R.id.profile: if (userType.equals("client")) { replace(editClientProfileFragment, getSupportFragmentManager(), R.id.activity_home_fl_frame, null, null); } else if (userType.equals("restaurant")) { replace(editRestaurantProfileFragment, getSupportFragmentManager(), R.id.activity_home_fl_frame, null, null); } break; case R.id.more: if (userType.equals("client")) { replace(clientMoreFragment, getSupportFragmentManager(), R.id.activity_home_fl_frame, null, null); } else if (userType.equals("restaurant")) { replace(restaurantMoreFragment, getSupportFragmentManager(), R.id.activity_home_fl_frame, null, null); } break; } return true; } @OnClick({R.id.activity_home_iv_notification, R.id.activity_home_iv_cart}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.activity_home_iv_notification: NotificationFragment notificationFragment = new NotificationFragment(); replace(notificationFragment, getSupportFragmentManager(), R.id.activity_home_fl_frame, null, null); break; case R.id.activity_home_iv_cart: if (userType.equals("client")) { Executors.newSingleThreadExecutor().execute(new Runnable() { @Override public void run() { ordersList = roomDao.getAll(); cartFragment.ordersList = ordersList; runOnUiThread(new Runnable() { @Override public void run() { replace(cartFragment, getSupportFragmentManager(), R.id.activity_home_fl_frame, null, null); } }); } }); } else if (userType.equals("restaurant")) { CommissionFragment commissionFragment = new CommissionFragment(); replace(commissionFragment, getSupportFragmentManager(), R.id.activity_home_fl_frame, null, null); } break; } } }
JavaScript
UTF-8
5,926
2.53125
3
[ "ISC" ]
permissive
import { getSuite } from '../node_modules/just-test/dist/just-test.min.js'; import * as DataTier from '../dist/data-tier.js'; const suite = getSuite({ name: 'Testing model changes' }), user = { name: 'some', age: 7, address: { street: 'str', apt: 9 } }; suite.runTest({ name: 'new model bound' }, async test => { DataTier.ties.create('modelA', user); const s1 = document.createElement('input'), s2 = document.createElement('div'), s3 = document.createElement('div'), s4 = document.createElement('div'); s1.dataset.tie = 'modelA:name => value'; document.body.appendChild(s1); s2.dataset.tie = 'modelA:age => textContent'; document.body.appendChild(s2); s3.dataset.tie = 'modelA:address.street => textContent'; document.body.appendChild(s3); s4.dataset.tie = 'modelA:address.apt => textContent'; document.body.appendChild(s4); await test.waitNextMicrotask(); test.assertEqual(s1.value, user.name); test.assertEqual(s2.textContent, user.age.toString()); test.assertEqual(s3.textContent, user.address.street); test.assertEqual(s4.textContent, user.address.apt.toString()); }); suite.runTest({ name: 'primitive model changes' }, async test => { DataTier.ties.create('modelB', user); const s1 = document.createElement('input'); s1.dataset.tie = 'modelB:name => value'; document.body.appendChild(s1); await test.waitNextMicrotask(); test.assertEqual(s1.value, user.name); DataTier.ties.get('modelB').name = 'other'; test.assertEqual(s1.value, 'other'); }); suite.runTest({ name: 'deep model changes (graph replace)' }, async test => { DataTier.ties.create('modelC', user); const s3 = document.createElement('div'); s3.dataset.tie = 'modelC:address.street => textContent'; document.body.appendChild(s3); await test.waitNextMicrotask(); test.assertEqual(s3.textContent, 'str'); DataTier.ties.get('modelC').address.street = 'Street'; test.assertEqual(s3.textContent, DataTier.ties.get('modelC').address.street); }); suite.runTest({ name: 'binding view to object' }, async test => { const s1 = document.createElement('input'), s2 = document.createElement('div'), s3 = document.createElement('div'), s4 = document.createElement('div') s1.dataset.tie = 'modelF:name => value'; document.body.appendChild(s1); s2.dataset.tie = 'modelF:age => textContent'; document.body.appendChild(s2); s3.dataset.tie = 'modelF:address.street => textContent'; document.body.appendChild(s3); s4.dataset.tie = 'modelF:address.apt => textContent'; document.body.appendChild(s4); const t = DataTier.ties.create('modelF', user); s3.dataset.tie = 'modelF:address'; test.assertEqual(s3.textContent, ''); t.address = { street: 'street name', apt: 17 }; t.address.toString = function () { return 'Street: ' + this.street + '; Apt: ' + this.apt }; await test.waitNextMicrotask(); test.assertEqual(s4.textContent, '17'); test.assertEqual(s3.textContent, t.address.toString()); }); suite.runTest({ name: 'deep model, NULL base' }, async test => { DataTier.ties.create('testNullBase', { address: null }); const d1 = document.createElement('div'), d2 = document.createElement('div'), d3 = document.createElement('div'); d1.dataset.tie = 'testNullBase'; d2.dataset.tie = 'testNullBase:address'; d3.dataset.tie = 'testNullBase:address.city'; document.body.appendChild(d1); document.body.appendChild(d2); document.body.appendChild(d3); await test.waitNextMicrotask(); test.assertEqual('[object Object]', d1.textContent); test.assertEqual('', d2.textContent); test.assertEqual('', d3.textContent); }); suite.runTest({ name: 'deep model, NULL IN path' }, async test => { DataTier.ties.create('testNullIn', { user: { address: null } }); const d1 = document.createElement('div'), d2 = document.createElement('div'), d3 = document.createElement('div'); d1.dataset.tie = 'testNullIn'; d2.dataset.tie = 'testNullIn:user.address'; d3.dataset.tie = 'testNullIn:user.address.city'; document.body.appendChild(d1); document.body.appendChild(d2); document.body.appendChild(d3); await test.waitNextMicrotask(); test.assertEqual('[object Object]', d1.textContent); test.assertEqual('', d2.textContent); test.assertEqual('', d3.textContent); }); // nullish values should turn to empty string for // * textContent target // * value target of INPUT, SELECT, TEXTAREA for (const nullish of [undefined, null]) { suite.runTest({ name: `'${nullish}' to empty string - textContent` }, async test => { const tn = test.getRandom(8); DataTier.ties.create(tn, { p: nullish }); const e1 = document.createElement('span'); e1.dataset.tie = `${tn}:p`; document.body.appendChild(e1); await test.waitNextMicrotask(); test.assertEqual('', e1.textContent); const e2 = document.createElement('div'); e2.dataset.tie = `${tn}:p => textContent`; document.body.appendChild(e2); await test.waitNextMicrotask(); test.assertEqual('', e2.textContent); }); for (const inputish of ['input', 'select', 'textarea']) { suite.runTest({ name: `'${nullish}' to empty string - value - ${inputish}` }, async test => { const tn = test.getRandom(8); DataTier.ties.create(tn, { v: nullish }); const e1 = document.createElement(inputish); e1.dataset.tie = `${tn}:v`; document.body.appendChild(e1); await test.waitNextMicrotask(); test.assertEqual('', e1.textContent); const e2 = document.createElement(inputish); e2.dataset.tie = `${tn}:v => value`; document.body.appendChild(e2); await test.waitNextMicrotask(); test.assertEqual('', e2.textContent); }); } suite.runTest({ name: `'${nullish}' preserved - value - non-input-like` }, async test => { const tn = test.getRandom(8); DataTier.ties.create(tn, { p: nullish }); const e = document.createElement('div'); e.dataset.tie = `${tn}:p => value`; document.body.appendChild(e); await test.waitNextMicrotask(); test.assertEqual(nullish, e.value); }); }
Python
UTF-8
3,204
2.515625
3
[]
no_license
import requests import json from helpers import * from datetime import date, datetime from datetime import timedelta from dateutil import parser config = load_config() today = date.today() maximum_time = date.today() + timedelta(config['maximum_time_delta']) def get_5days_3hours_forcast_data(city_code='HaNoi', country_code='vn', units='metric'): url = config["fivedays_3hours_forcast_api"] url += 'q={},{}&units={}&APPID={}&lang={}'.format(city_code, country_code, units, config["api_key"], config['lang']) print (url) response = requests.get(url) data = response.text parsed = json.loads(data) return parsed def get_data_from_file(city_code='hanoi'): with open(config["data_file_path"], "r") as read_file: data = json.load(read_file) try: return data[city_code] except: return False pass def remove_unused_attributes(data): re = [] for el in data: tmp = {} tmp['dt_txt'] = el['dt_txt'] tmp['temp_min'] = el['main']['temp_min'] tmp['temp_max'] = el['main']['temp_max'] tmp['feels_like'] = (el['main']['temp_min'] + el['main']['temp_max'])/ 2 tmp['weather'] = el['weather'][0]['main'] tmp['description'] = el['weather'][0]['description'] tmp['icon'] = el['weather'][0]['icon'] r = handle_data_with_temp_condition(float(el['main']['temp_min']), float(el['main']['temp_max']), config) tmp['recommend'] = r['recommend'] tmp['time'] = add_time(config, el) condition = add_condition(config, tmp['weather']) tmp['type'] = condition['japanese'] tmp['images'] = condition['images'] re.append(tmp) return re def handle_data_with_temp_condition(min_temp=26, max_temp=30, config=None): recommends = config["closet_recommend"] average_temp = (min_temp + max_temp) / 2 for key, r in recommends.items(): if average_temp >= r['min'] and average_temp < r['max']: return r pass def handle_data_with_date_condition(data, start_date=today, end_date=maximum_time): filter_data = [v for v in data if get_date(v['dt_txt']) >= start_date and get_date(v['dt_txt']) <= end_date] return filter_data def handle_data_with_time_condition(data): #get morning, afternoon, night forcast filter_data = [v for v in data if is_in_config_time(config, get_time(v['dt_txt']))] return filter_data def add_recommend_msg(data): for el in data: r = handle_data_with_temp_condition(float(el['main']['temp_min']), float(el['main']['temp_max']), config) el['recommend'] = r['recommend'] return data def handle_data(data, start_date=today, end_date=maximum_time): filter_data = handle_data_with_date_condition(data['list']) filter_data = handle_data_with_time_condition(filter_data) filter_data = add_recommend_msg(filter_data) # group by date list_dates = {} start = start_date # values = set(map(lambda x:(x['dt_txt']), filter_data)) # results = [[y for y in filter_data if (y['dt_txt'])==x] for x in values] results = remove_unused_attributes(filter_data) return results if __name__ == '__main__': print ()
JavaScript
UTF-8
561
3.015625
3
[]
no_license
class Player { constructor() { this.height = 190; this.width = 170; this.x = 0; this.y = height - this.height; this.gravity = 0.2; this.velocity = 0; this.image; } drawPlayer() { this.velocity += this.gravity; this.y += this.velocity; if (this.y >= height - this.height) { this.y = height - this.height; } image(this.image, this.x, this.y, this.height, this.width); } jump() { console.log("this will be the jump"); if (this.y === height - this.height) { this.velocity = -10; } } }
C++
UTF-8
377
3.46875
3
[ "Apache-2.0" ]
permissive
#include <iostream> int main() { int lower,upper; int v1, v2; std::cout << "Input two numbers:" << std::endl; std::cin >> v1 >> v2; if(v1 <= v2) { lower = v1; upper = v2; } else { lower = v2; upper = v1; } for(int i = lower; i <= upper; i++) { std::cout << i << " "; } return 0; }
Java
UTF-8
486
2.359375
2
[]
no_license
package org.nutz.mvc.param; import org.nutz.mvc.annotation.Param; import org.nutz.mvc.param.injector.NameInjector; import org.nutz.mvc.param.injector.ObjectPairInjector; public class PairAdaptor extends AbstractAdaptor { @Override protected ParamInjector evalInjector(Class<?> type, Param param) { if (null == param) return null; if ("..".equals(param.value())) return new ObjectPairInjector(type); return new NameInjector(param.value(), type); } }
Python
UTF-8
4,618
4.46875
4
[]
no_license
string1 = "this is a example string for learning python inbuilt string capability for" print(35*'#') print("Demonstrating Capatilize() Method ---> It capitalizes the first character of the String") print(35*'#') print("'{}' is the string before calling capatilize() Method".format(string1)) print("'{}' is the string before calling capatilize() Method".format(string1.capitalize())) print(150*'*') print(35*'#') print("Demonstrating Count() Method ----> It Counts number of times substring occurs in a String between begin and end index.") print(35*'#') print("'{}' is the count ".format(string1.count('for'))) print(150*'*') print(35*'#') print("Demonstrating endswith(suffix ,begin=0,end=n) ----> It returns a Boolean value if the string terminates with given suffix between begin and end.") print(35*'#') print("'{}' is the count ".format(string1.endswith('for'))) print(150*'*') print(35*'#') print("Demonstrating find(substring ,beginIndex, endIndex) It returns the index value of the string where substring is found between begin index and end index.") print(35*'#') print("'{}' is the place where substring is present ".format(string1.find('python'))) print(150*'*') print(35*'#') print("Demonstrating index(subsring, beginIndex, endIndex) It throws an exception if string is not found and works same as find() method.") print(35*'#') print("'{}' is the index ".format(string1.index('python'))) print(150*'*') print(35*'#') print("Demonstrating isalnum() It returns True if characters in the string are alphanumeric i.e., alphabets or numbers and there is at least 1 character. Otherwise it returns False.") print(35*'#') print("'{}' ".format(string1.isalnum())) print(150*'*') print(35*'#') print("Demonstrating isalpha() It returns True when all the characters are alphabets and there is at least one character, otherwise False.") print("'{}' ".format(string1.isalpha())) print(35*'#') print("Demonstrating isdigit() It returns True if all the characters are digit and there is at least one character, otherwise False..") print("'{}' ".format(string1.isdigit())) print(35*'#') print("Demonstrating islower() It returns True if the characters of a string are in lower case, otherwise False.") print("'{}' ".format(string1.islower())) print(35*'#') print("Demonstrating isupper() It returns False if characters of a string are in Upper case, otherwise False.") print("'{}' ".format(string1.isupper())) print(35*'#') print("Demonstrating isspace() It returns True if the characters of a string are whitespace, otherwise false.") print("'{}' ".format(string1.isupper())) print(150*'*') print(35*'#') print("Demonstrating lower() It converts all the characters of a string to Lower case.") print(35*'#') print("'{}' is the string before calling lower() Method".format(string1)) print("'{}' is the string before calling lower() Method".format(string1.lower())) print(150*'*') print(35*'#') print("Demonstrating upper() It converts all the characters of a string to Upper Case..") print(35*'#') print("'{}' is the string before calling upper() Method".format(string1)) print("'{}' is the string before calling upper() Method".format(string1.upper())) print(150*'*') print(35*'#') print("Demonstrating startswith(str ,begin=0,end=n) It returns a Boolean value if the string starts with given str between begin and end.") print(35*'#') print("'{}' is the count ".format(string1.startswith('for'))) print(150*'*') print(35*'#') print("Demonstrating swapcase() It inverts case of all characters in a string.") print(35*'#') print("'{}' is the string before calling swapcase() Method".format(string1)) print("'{}' is the string before calling swapcase() Method".format(string1.swapcase())) print(150*'*') print(35*'#') print("Demonstrating lstrip() It removes all leading whitespace of a string and can also be used to remove particular character from leading.") print("Demonstrating rstrip() It removes all trailing whitespace of a string and can also be used to remove particular character from trailing.") print(35*'#') print("'{}' is the string before lstrip('this') ".format(string1)) print("'{}' is the string after lstrip('this') ".format(string1.lstrip('this'))) print("'{}' is the string before rstrip('for') ".format(string1)) print("'{}' is the string after rstrip('for')".format(string1.rsplit('for'))) print(150*'*')
Python
UTF-8
4,280
2.59375
3
[ "MIT" ]
permissive
#!/usr/bin/evn python3 # coding=utf-8 import math from datetime import datetime from dao.publish import PublishDAO from dao.setting import SettingDAO from service.base import BaseSrv class PublishSrv(BaseSrv): """ # 对简历发布表增删改查 """ @classmethod def add_publish( cls, resume_id: int, receiver: str, access_code: str, exp_time: datetime ) -> None: """ # 新增一个简历发布 :param resume_id: 简历ID :param receiver: 简历接收者 :param access_code: 前台简历访问吗 :param exp_time: 过期时间 """ PublishDAO.insert_one( resume_id=resume_id, receiver=receiver, access_code=access_code, exp_time=exp_time ) @classmethod def del_publish(cls, publish_id: int) -> None: """ # 删除一个简历发布 :param publish_id: 发布ID """ PublishDAO.delete_one(publish_id) @classmethod def put_publish(cls, publish_id: int, **kwargs) -> None: """ # 更新一个简历发布 :param publish_id: 发布ID :param kwargs: 更新字段 resume_id=resume_id, receiver=receiver, access_code=access_code, exp_time=exp_time """ PublishDAO.update_one(publish_id, **kwargs) @classmethod def get_publish(cls, publish_id: int) -> dict: """ # 获取一个简历发布 :param publish_id: 发布ID,数据库中的主键 """ publish = PublishDAO.select_one(publish_id) if publish: publish_data = { "id": publish.id, "access_code": publish.access_code, "resume_id": publish.resume_id, "resume_title": publish.resume.title, "receiver": publish.receiver, "exp_time": publish.exp_time, "read_count": publish.read_count, "read_time": publish.read_time, "read_duration": publish.read_duration, "create_time": publish.create_time, "update_time": publish.update_time } return publish_data @classmethod def get_published_resume(cls, access_code: str) -> dict: """ # 前台通过访问码查看简历 :param access_code: :return: 返回是简历的数据,字典类型 """ resume = PublishDAO.select_publish(access_code) if resume: return resume[0] return {} @classmethod def get_access_code_exists(cls, access_code: str) -> bool: """ # 查询访问码是否存在AJAX请求使用 :param access_code: 访问码 """ return PublishDAO.select_access_code_exists(access_code) @classmethod def get_publish_list(cls, page=1, receiver_like: str = "") -> tuple: """ # 获取简历发布列表 :param page: 页码 :param receiver_like: 简历接收者 """ page_size = SettingDAO.select_setting()["admin_publish_pz"] all_publish: list = PublishDAO.select_all(receiver_like) max_page = math.ceil(len(all_publish) / page_size) page = max_page if page > max_page else page page = 1 if page == 0 else page if page == 1: start = 0 end = page_size else: start = (page-1) * page_size end = start + page_size publish_list = [ { "id": item["id"], "access_code": item["access_code"], "resume_id": item["resume_id"], "resume_title":item["title"], "receiver": item["receiver"], "exp_time": item["exp_time"], "read_count": item["read_count"], "read_duration":item["read_duration"], "read_time":item["read_time"], "create_time":item["create_time"], "update_time":item["update_time"] } for item in all_publish[start:end] ] return max_page, publish_list
Python
UTF-8
290
3.078125
3
[]
no_license
class Solution: # @param A : list of integers # @return a list of list of integers def permute(self, A): x = [[]] for n in A: x = [l[:i]+[n]+l[i:] for l in x for i in xrange((l+[n]).index(n)+1)] return x
Java
UTF-8
3,883
2.46875
2
[]
no_license
package com.excilys.wrapper; import java.util.List; import com.excilys.om.Computer; public class PageWrapper { private int entitiesPerPage; private int currentPagenumber; private long numberOfComputer; private long numberTotalOfComputer; private int pageMax; private String criteria; private String order; private String filter; private String add; private String edit; private String delete; private List<Computer> computerPageList; /** * @return the entitiesPerPage */ public int getEntitiesPerPage() { return entitiesPerPage; } /** * @param entitiesPerPage the entitiesPerPage to set */ public void setEntitiesPerPage(int entitiesPerPage) { this.entitiesPerPage = entitiesPerPage; } /** * @return the currentPagenumber */ public int getCurrentPagenumber() { return currentPagenumber; } /** * @param currentPagenumber the currentPagenumber to set */ public void setCurrentPagenumber(int currentPagenumber) { this.currentPagenumber = currentPagenumber; } /** * @return the numberOfComputer */ public long getNumberOfComputer() { return numberOfComputer; } /** * @param l the numberOfComputer to set */ public void setNumberOfComputer(long l) { this.numberOfComputer = l; } /** * @return the numberTotalOfComputer */ public long getNumberTotalOfComputer() { return numberTotalOfComputer; } /** * @param l the numberTotalOfComputer to set */ public void setNumberTotalOfComputer(long l) { this.numberTotalOfComputer = l; } /** * @return the pageMax */ public int getPageMax() { return pageMax; } /** * @param pageMax the pageMax to set */ public void setPageMax(int pageMax) { this.pageMax = pageMax; } /** * @return the criteria */ public String getCriteria() { return criteria; } /** * @param criteria the criteria to set */ public void setCriteria(String criteria) { this.criteria = criteria; } /** * @return the order */ public String getOrder() { return order; } /** * @param order the order to set */ public void setOrder(String order) { this.order = order; } /** * @return the filter */ public String getFilter() { return filter; } /** * @param filter the filter to set */ public void setFilter(String filter) { this.filter = filter; } /** * @return the computerPageList */ public List<Computer> getComputerPageList() { return computerPageList; } /** * @return the add */ public String getAdd() { return add; } /** * @param add the add to set */ public void setAdd(String add) { this.add = add; } /** * @return the edit */ public String getEdit() { return edit; } /** * @param edit the edit to set */ public void setEdit(String edit) { this.edit = edit; } /** * @return the delete */ public String getDelete() { return delete; } /** * @param delete the delete to set */ public void setDelete(String delete) { this.delete = delete; } /** * @param computerPageList the computerPageList to set */ public void setComputerPageList(List<Computer> computerPageList) { this.computerPageList = computerPageList; } public PageWrapper() { super(); } public PageWrapper(int entitiesPerPage, int currentPagenumber, int numberOfComputer, int numberTotalOfComputer, int pageMax, String criteria, String order, String filter, String add, String edit, String delete, List<Computer> computerPageList) { super(); this.entitiesPerPage = entitiesPerPage; this.currentPagenumber = currentPagenumber; this.numberOfComputer = numberOfComputer; this.numberTotalOfComputer = numberTotalOfComputer; this.pageMax = pageMax; this.add = add; this.edit = edit; this.delete = delete; this.criteria = criteria; this.order = order; this.filter = filter; this.computerPageList = computerPageList; } }
Python
UTF-8
679
3.75
4
[]
no_license
# Recursive def findClosestValueInBst(tree, target): return work(tree, target, tree.value) def work (tree, target, closest): # if at the end of the tree, return last closest value print(closest) if tree is None: return closest # check if the distance between the current closest and the target is more than the new node value if abs(tree.value - target) < abs(closest - target): closest = tree.value # recurse through sub tree and return the closest value if tree.value > target: return work(tree.left, target, closest) # make sure not to forget return with recursion elif tree.value < target: return work(tree.right, target, closest) else: return closest
C#
UTF-8
1,032
3.140625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RSSClient.Exceptions { /// <summary> /// Represent an invalid URL Source Exception /// </summary> public class DuplicatedSourceException : ApplicationException { /// <summary> /// Message Source /// </summary> private int source; /// <summary> /// Invalid URL Exception Constructor /// </summary> /// <param name="sourceId">SourceId</param> public DuplicatedSourceException(int sourceId) : base("There are duplicated sources in the provided parameters") { source = sourceId; } /// <summary> /// Returns the message of the exceptions /// </summary> public override string Message { get { return string.Format("Source {0} - {1}", source.ToString(), base.Message); } } } }
Markdown
UTF-8
1,016
2.703125
3
[]
no_license
**BIOS MBR DOS** *-Antiguo* -> **BIOS MBR DOS** -> Admite hasta un máximo de 2 TB por cada partición existente. *-Actual* -> **UEFI GPT** -> Admite hasta un máximo de 18 exabytes, que este es equivalente a 18,8 millones de TB **Reglas MBR** -Tiene un máximo de **4 particiones primarias**. ---> Una de estas puede ser extended. -Una **extended** puede tener "n lógicas" -Una de ellas obligatoriamente debe ser **"Activa"**---> Una Activa no puede ser extended y al revés. *UEFI/GPT*->Ni primarias ni activas tiene.<-|---> En *Linux* esta no es obligatoria como en Windows, no es del todo necesaria. |---> En *Windows* si no es "Activa" el PC no arrancará **Boot Manager** --> Gestor de arranque de Windows. **GRUB** --> Gestor de arranque de Linux Para cambiar a *MBR* se debe entra en la *BIOS* y poner el *Modo Legacy*, y si queremos ponerlo al revés, de *GPT* cambiamos al modo a *UEFI*.
JavaScript
UTF-8
543
2.671875
3
[]
no_license
import {AUTH, LOGOUT} from '../constants/actionContants'; const authReducer = (state={authData: null}, action) => { switch(action.type) { case AUTH: const user = {profile: action.data.user, token: action.data.token}; localStorage.setItem("profile", JSON.stringify(user)); return ({...state, authData: user}); case LOGOUT: localStorage.clear(); return ({...state, authData: null}); default: return state; } } export default authReducer;
JavaScript
UTF-8
1,023
2.625
3
[]
no_license
import React, { useEffect, useState } from 'react' import { Link } from 'react-router-dom' import './movieList.css' export const MovieList = () => { const MovieURL = ('https://api.themoviedb.org/3/movie/popular?api_key=3bb2ad59c76c83daa1fd97f0b4effa78&language=en-US&page=1') const [movieList, setMovieList] = useState([]) useEffect (() => { fetch (MovieURL) .then ((res) => res.json()) .then ((json) => { setMovieList(json.results) }) }, []) return ( <article> {movieList.map((title) => ( <div key={title.id} className="mainSection"> <div className="imageSection"> <Link to={`/details/${title.id}`}> <img className="imgPosterSize" src= {`https://image.tmdb.org/t/p/w342${title.poster_path}`} alt={title.title}/> <div className="overlay"> <h2>{title.title}</h2> <p>{title.vote_average}</p> </div> </Link> </div> </div> ))} </article> ) }
C++
UHC
280
3.0625
3
[]
no_license
#include "pch.h" #include <iostream> #include <string> using namespace std; int main() { int a = 20000; char c = a; // ٸ ٲ. int b = c; if (a != b) { cout << "̷: " << a << "!=" << b << '\n'; } else { "Ϳ ڰ û ũ׿.\n"; } }
Python
UTF-8
613
2.96875
3
[]
no_license
def unescaped_length(line): line = line[1:len(line)-1] length = 0 skip = 0 for i in range(0, len(line)): if skip > 0: skip -= 1 continue c = line[i] length += 1 if c == "\\": d = line[i+1] if d == '"': skip = 1 elif d == "\\": skip = 1 elif d == "x": skip = 3 # print("'{}' ({})".format(line, length)) return length def encode(line): output = "" for char in line: if char == '\"': output += '\\\"' elif char == '\\': output += '\\\\' else: output += char output = '\"{}\"'.format(output) print("{} -> {}".format(line, output)) return output
Java
UTF-8
1,640
2.890625
3
[]
no_license
package test; import static org.junit.Assert.*; import java.util.NoSuchElementException; import org.junit.After; import org.junit.Before; import org.junit.Test; import set.ArraySet; import set.RemoveDuplicates; public class RemoveDuplicatesTest { private RemoveDuplicates rd; @Before public void setUp() throws Exception { rd = null; } @After public void tearDown() throws Exception { rd = null; } @Test public final void testNullPointer() { try { int[] i = rd.uniqueElements(null); fail("uniqueElements should catch NullPointerException"); } catch (NullPointerException e) { } } @Test public final void testEmptySet() { int[] ints = new int[5]; int[] sortedInts = rd.uniqueElements(ints); assertEquals("uniqeElements should return 1", 1, sortedInts.length); } @Test public final void testSingleElements() { int[] ints = new int[1]; ints[0] = 1; int[] sortedInts = rd.uniqueElements(ints); assertEquals("uniqueElements should return one element", 1, sortedInts[0]); } @Test public final void testDuplicateElements() { int[] ints = new int[20]; for (int i = 0; i < ints.length; i++) { ints[i] = 1; } int[] sortedInts = rd.uniqueElements(ints); assertEquals("uniqueElements should return one element", 1, sortedInts[0]); } @Test public final void testDifferentElements() { int[] ints = new int[10]; for (int i = 0; i < ints.length; i++) { ints[i] = i + 1; } int[] sortedInts = rd.uniqueElements(ints); assertEquals("uniqueElements should return a sorted list", ints, sortedInts); } }
C#
UTF-8
4,064
2.796875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Markup; using System.Xml; using System.IO; namespace Library.Client.Wpf { public static class WpfExtensions { /// <summary> /// find the specifical type child from visual tree /// </summary> /// <typeparam name="T">the child type</typeparam> /// <param name="dependencyObject">the root object</param> /// <returns></returns> public static T FindFirstVisualChild<T>(this DependencyObject dependencyObject) where T:DependencyObject { var targetType = typeof(T); int childCount = VisualTreeHelper.GetChildrenCount(dependencyObject); if (childCount == 0) return null; for (int i = 0; i < childCount; i++) { var child = VisualTreeHelper.GetChild(dependencyObject, i); if (child.DependencyObjectType.SystemType == targetType) return child as T; var final = WpfExtensions.FindFirstVisualChild<T>(child); if (final != null) return final; } return null; } /// <summary> /// find the specifical type child from logical tree /// </summary> /// <typeparam name="T">the child type</typeparam> /// <param name="dependencyObject">the root object</param> /// <returns></returns> public static T FindFirstLogicalChild<T>(this DependencyObject dependencyObject) where T:DependencyObject { var targetType = typeof(T); var children = LogicalTreeHelper.GetChildren(dependencyObject); foreach (var child in children) { DependencyObject obj = child as DependencyObject; if (obj == null) return null; if (obj.DependencyObjectType.SystemType == targetType) return obj as T; var final = FindFirstLogicalChild<T>(obj); if (final != null) return final; } return null; } /// <summary> /// find the specifical type parent from logic tree /// </summary> /// <typeparam name="T">the parent type</typeparam> /// <param name="dependencyObject">the root object</param> /// <returns></returns> public static T FindLogicParent<T>(this DependencyObject dependencyObject) where T:DependencyObject { var parent = LogicalTreeHelper.GetParent(dependencyObject); if (parent == null) return null; T tp = parent as T; if (tp == null) return FindLogicParent<T>(parent); return tp; } /// <summary> /// find the first specific type visual parent /// </summary> /// <typeparam name="T">the sepcific type</typeparam> /// <param name="dependencyObject"></param> /// <returns></returns> public static T FindVisualParent<T>(this DependencyObject dependencyObject) where T:DependencyObject { var parent = VisualTreeHelper.GetParent(dependencyObject); if (parent == null) return null; if (parent is T) return parent as T; return FindVisualParent<T>(parent); } /// <summary> /// clone the element /// </summary> /// <param name="dependencyObject"></param> /// <returns></returns> public static T CloneElement<T>(this T dependencyObject) { string xaml = XamlWriter.Save(dependencyObject); var obj = XamlReader.Load(new XmlTextReader(new StringReader(xaml))); return (T)obj; } } }
Markdown
UTF-8
2,298
3.03125
3
[ "MIT", "Apache-2.0" ]
permissive
--- layout: post title: "Apache Spark RDD operation examples" date: 2014-10-23 16:00:00 +0200 comments: true categories: [Spark, YARN] author: Oliver Szabo published: true --- Recently we blogged about how you can write simple Apache Spark jobs and how to test them. Now we'd like to introduce all basic RDD operations with easy examples (our goal is to come up with examples as simply as possible). The Spark [documentation](http://spark.apache.org/docs/latest/programming-guide.html#rdd-operations) explains well what each operations is doing in detail. We made tests for most of the RDD operations with good ol' `TestNG`. e.g.: ```scala @Test def testRightOuterJoin() { val input1 = sc.makeRDD(Seq((1, 4))) val input2 = sc.makeRDD(Seq((1, '1'), (2, '2'))) val expectedOutput = Array((1, (Some(4), '1')), (2, (None, '2'))) val output = input1.rightOuterJoin(input2) Assert.assertEquals(output.collect(), expectedOutput) } ``` <!-- more --> ##Sample Get the code from our GitHub repository [GitHub examples](https://github.com/sequenceiq/sequenceiq-samples) and build the project inside the `spark-samples` directory. For running the examples, you do not need any pre-installed Hadoop/Spark clusters or anything else. ```bash git clone https://github.com/sequenceiq/sequenceiq-samples.git cd sequenceiq-samples/spark-samples/ ./gradlew clean build ``` All the other RDD operations are covered in the example (makes no sense listing them here). ##Spark on YARN Should you want to run your Spark code on a YARN cluster you have several options. * Use our Spark Docker [container](https://github.com/sequenceiq/docker-spark) * Use our multi-node Hadoop [cluster](http://blog.sequenceiq.com/blog/2014/06/19/multinode-hadoop-cluster-on-docker/) * Use [Cloudbreak](http://sequenceiq.com/cloudbreak/) to provision a YARN cluster on your favorite cloud provider In order to help you get on going with Spark on YARN read our previous blog post about how to [submit a Spark](http://blog.sequenceiq.com/blog/2014/08/22/spark-submit-in-java/) job into a cluster. If you have any questions or suggestions you can reach us on [LinkedIn](https://www.linkedin.com/company/sequenceiq/), [Twitter](https://twitter.com/sequenceiq) or [Facebook](https://www.facebook.com/sequenceiq).
C#
UTF-8
1,844
2.515625
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CandleControl : MonoBehaviour { public Transform[] candleFires = null; private float fev1; private float fvc; private float smallerNumber; private float sizeBorder = 0.01f; private int offNum = 0; private int offTurn = 0; public void fev1Reaction() { fev1 = float.Parse(CandleGameManager1.instance.fev1Input.text); for(int i=0;i<10;i++) candleFires[i].gameObject.SendMessage("BlowStart", i); StartCoroutine("fireSmaller"); } IEnumerator fireSmaller() { candleFires[(int)(fev1 / 100f)].gameObject.SendMessage("FireSmaller", fev1); yield return null; StopCoroutine("fireSmaller"); } /// <summary> /// 1초 이후 fvc에 따라 줄어들었던 불이 정해진 갯수만큼 꺼지게 하는 것 /// offTurn은 이번에 꺼질 차례인 촛불을 의미. /// 꺼칠 차례의 촛불의 FireReaction 스크립트에 꺼지라는 메시지 전달. /// </summary> public void fvcReaction() { fvc = float.Parse(CandleGameManager1.instance.fvcInput.text); float offRatio = (fvc / CandleGameManager1.instance.maxFvc); offNum = (int)(offRatio * (int)(fev1 / 100f)); if(offNum>offTurn && offRatio<=1.01f) { candleFires[offTurn].gameObject.SendMessage("fireOff", fvc); offTurn++; } } /// <summary> /// 호기 종료 이후에 각 촛불의 기울기를 원래대로 되돌림. 게임컨트롤에서 불러옴 /// </summary> public void blowEnd() { for (int i = (int)smallerNumber; i < 10; i++) { candleFires[i].gameObject.SendMessage("blowFinished", i); } } }
Python
UTF-8
1,488
2.546875
3
[ "MIT" ]
permissive
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import pendulum from flask import Flask, Response from flask_dataview import RangeTimeSeries, FlaskDataViews class MyTestSeries(RangeTimeSeries): def get_range(self): d1 = pendulum.datetime(2000, 1, 1, 12, 0) d2 = pendulum.datetime(2000, 1, 31, 12, 0) return (d1, d2) def get_data_range(self, dt_from, dt_to): out = [] cur = dt_from.replace(microsecond=0) while cur < dt_to: val = ((cur.int_timestamp / 3600) % 24) out.append((cur.isoformat(), val)) cur = cur.add(minutes=10) return out class BaseTests(unittest.TestCase): def setUp(self): pass def tearDown(self): pass @classmethod def tearDownClass(cls): pass @classmethod def setUpClass(cls): pass def test_base(self): e = FlaskDataViews() app = Flask("test_flask_app", template_folder=".") test_client = app.test_client() e.init_app(app) with app.app_context() as ctx: data = [MyTestSeries("temp"), MyTestSeries("hum")] chart = e.basechart("myid1", "My Chart", series=data) with app.test_request_context(): self.assertIn("some_div_id", chart.render("some_div_id")) r = chart.data() self.assertTrue(isinstance(r, Response)) self.assertEqual(r.status_code, 200)
Java
UTF-8
4,979
3.375
3
[]
no_license
import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; public class Day11 { public static void main(String[] args) throws Exception { final char[][] seats = Files .readAllLines(Paths.get("java-solutions", "input", "day11")).stream() .map(String::trim) .map(String::toCharArray) .toArray(char[][]::new); final int part_one_result = part_one(cloneArray(seats)); System.out.printf("Part one result = %d\n", part_one_result); final int part_two_result = part_two(cloneArray(seats)); System.out.printf("Part two result = %d\n", part_two_result); } private static int part_one(char[][] seats) { final char[][] seats_copy = cloneArray(seats); final int n = seats.length; final int m = seats[0].length; boolean changed = true; while (changed) { changed = false; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { final int occupied_neighbours = count_occupied_neighbours(seats, i, j); if (seats[i][j] == 'L' && occupied_neighbours == 0) { seats_copy[i][j] = '#'; changed = true; } else if (seats[i][j] == '#' && occupied_neighbours >= 4) { seats_copy[i][j] = 'L'; changed = true; } else { seats_copy[i][j] = seats[i][j]; } } } copyArray(seats_copy, seats); } return count_occupied(seats); } private static int count_occupied_neighbours(char[][] seats, int x, int y) { final int[] dx = {-1, -1, -1, 0, 1, 1, 1, 0}; final int[] dy = {-1, 0, 1, 1, 1, 0, -1, -1}; final int n = seats.length; final int m = seats[0].length; int occupied_neighbours = 0; for (int k = 0; k < 8; ++k) { final int x2 = x + dx[k]; final int y2 = y + dy[k]; if (0 <= x2 && x2 < n && 0 <= y2 && y2 < m && seats[x2][y2] == '#') { occupied_neighbours += 1; } } return occupied_neighbours; } private static int part_two(char[][] seats) { final char[][] seats_copy = cloneArray(seats); final int n = seats.length; final int m = seats[0].length; boolean changed = true; while (changed) { changed = false; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { final int occupied_neighbours = count_occupied_neighbours_fov(seats, i, j); if (seats[i][j] == 'L' && occupied_neighbours == 0) { seats_copy[i][j] = '#'; changed = true; } else if (seats[i][j] == '#' && occupied_neighbours >= 5) { seats_copy[i][j] = 'L'; changed = true; } else { seats_copy[i][j] = seats[i][j]; } } } copyArray(seats_copy, seats); } return count_occupied(seats); } private static int count_occupied_neighbours_fov(char[][] seats, int x, int y) { final int[] dx = {-1, -1, -1, 0, 1, 1, 1, 0}; final int[] dy = {-1, 0, 1, 1, 1, 0, -1, -1}; final int n = seats.length; final int m = seats[0].length; int occupied_neighbours = 0; for (int k = 0; k < 8; ++k) { int x2 = x + dx[k]; int y2 = y + dy[k]; while (0 <= x2 && x2 < n && 0 <= y2 && y2 < m) { if (seats[x2][y2] == '.') { x2 = x2 + dx[k]; y2 = y2 + dy[k]; } else if (seats[x2][y2] == '#') { ++occupied_neighbours; break; } else { break; } } } return occupied_neighbours; } private static int count_occupied(char[][] seats) { int empty_seats = 0; for (char[] seat : seats) for (char chr : seat) if (chr == '#') ++empty_seats; return empty_seats; } private static void print(char[][] seats) { for (char[] seat : seats) { System.out.printf("%s\n", String.valueOf(seat)); } } private static char[][] cloneArray(char[][] array) { return Arrays.stream(array) .map(char[]::clone) .toArray(char[][]::new); } private static void copyArray(char[][] src, char[][] dest) { for (int i = 0; i < src.length; ++i) { System.arraycopy(src[i], 0, dest[i], 0, src[i].length); } } }
C++
UTF-8
3,110
3.265625
3
[ "MIT" ]
permissive
#ifndef AABB_HPP #define AABB_HPP #include <VBE/math.hpp> #include <VBE/system/Log.hpp> /// /// \brief Represents an Axis-Aliged Bounding Box /// class AABB { public: /// /// \brief Default constructor /// /// This AABB will be init with the maximum value /// in all three edges for the minimum point /// and vice-versa. This leaves the AABB in an /// invalid state untill extended at least once. /// AABB(); /// /// \brief Copy constructor /// /// The minimum and maximum will be copied /// AABB(const AABB& aabb); /// /// \brief Explicit constructor /// AABB(const vec3f& pmin, const vec3f& pmax); /// /// \brief Destructor /// ~AABB(); /// /// \brief Extend this AABB to contain a point /// void extend(const vec3f& p); /// /// \brief Extend this AABB to contain another AABB /// void extend(const AABB& aabb); /// /// \brief Test a point against this AABB /// /// Points on the edge are considered inside /// /// \return Wether the point lies inside or not /// bool inside(const vec3f& p) const; //p inside this box /// /// \brief Test another AABB against this AABB /// /// Merely overlapping will not pass this test /// /// \return Wether the AABB lies inside or not /// bool inside(const AABB& aabb) const; //aabb inside this boxs /// /// \brief Get the current minimum /// /// \return Minimum point /// vec3f getMin() const; /// /// \brief Get the current maximum /// /// \return Maximum point /// vec3f getMax() const; /// /// \brief Get the current center /// /// \return Center /// vec3f getCenter() const; /// /// \brief Get the current dimensions /// /// \return Dimensions /// vec3f getDimensions() const; /// /// \brief Get the current radius /// /// \return Radius /// float getRadius() const; private: friend class Collision; vec3f pmin = vec3f(std::numeric_limits<float>::max()); vec3f pmax = vec3f(std::numeric_limits<float>::lowest()); }; /// /// \class AABB AABB.hpp <VBE/geometry/AABB.hpp> /// \ingroup Geometry /// /// This class can be used to test against other geometry objects. /// /// \see Collision /// inline vec3f AABB::getMin() const { return pmin; } inline vec3f AABB::getMax() const { return pmax; } inline vec3f AABB::getCenter() const { return 0.5f*(pmin + pmax); } inline vec3f AABB::getDimensions() const { return pmax - pmin; } inline float AABB::getRadius() const { return 0.5f*glm::length(pmax - pmin); } const Log&operator << (const Log& log, const AABB& aabb); #endif // AABB_HPP
JavaScript
UTF-8
1,243
2.78125
3
[]
no_license
import React, {useState} from 'react'; import MovieCard from './MovieCard' export default function SearchMovies() { const [query, setQuery] = useState(''); const [movies, setMovies] = useState([]); const searchMovies = async (event) => { event.preventDefault(); const url = `https://api.themoviedb.org/3/search/movie?api_key=5dcf7f28a88be0edc01bbbde06f024ab&language=en-US&query=${query}&page=1&include_adult=false`; try { const res = await fetch(url); const data = await res.json(); setMovies(data.results); } catch(err) { console.log(err); } } return ( <section className="movie-search"> <form className="form" onSubmit={searchMovies}> <label htmlFor="query" className="label">Movie Name</label> <input type="text" name="query" id="query" placeholder="i.e. Jurassic Park" value={query} onChange={(event) => setQuery(event.target.value)} /> <button type="submit" className="button">Search</button> </form> <section className="card-list"> {movies.filter(movie => movie.poster_path).map(movie => ( <MovieCard key={movie.id} movie={movie} /> ))} </section> </section> ) }
Swift
UTF-8
3,610
2.5625
3
[]
no_license
// // MarqueeView.swift // betlead // // Created by Victor on 2019/8/20. // Copyright © 2019 vanness wu. All rights reserved. // import UIKit import RxSwift class MarqueeView: UIView { private lazy var label1: UILabel = { let lb = UILabel() lb.tag = 1 lb.textColor = Themes.darkGrey lb.font = Fonts.pingFangTCRegular(12) return lb }() private lazy var label2: UILabel = { let lb = UILabel() lb.tag = 2 lb.textColor = Themes.darkGrey lb.font = Fonts.pingFangTCRegular(12) return lb }() private var currentLabel = UILabel() private var nextLabel = UILabel() private var duration: Double = 0.75 fileprivate let viewModel = MarqueeViewModel() let takeOutMarqueeView = PublishSubject<Void>() private var defaultMarqueeCount : Int = 0 private let dpg = DisposeBag() override init(frame: CGRect) { super.init(frame: frame) bindViewModel() bindStyle() } func bindStyle() { Themes.thaiBrownAndBrown.bind(to: label1.rx.textColor).disposed(by: dpg) Themes.thaiBrownAndBrown.bind(to: label2.rx.textColor).disposed(by: dpg) } func bindViewModel() { viewModel.selectedMarquee .subscribeSuccess { [weak self] (dto) in if dto.NewsName != "暂无公告资料" { self?.nextNews(title: dto.NewsName) }else { if self!.defaultMarqueeCount < 2 { self?.takeOutMarqueeView.onNext(()) self?.nextNews(title: dto.NewsName) self!.defaultMarqueeCount += 1 } } }.disposed(by: dpg) } func nextNews(title: String) { if currentLabel.text == nil { currentLabel.text = title return } nextLabel.text = title moveLabel() } func moveLabel() { let viewWidth = frame.width UIView.animate(withDuration: duration, animations: { [weak self] in guard let strongSelf = self else { return } strongSelf.currentLabel.frame.origin = CGPoint(x: -viewWidth, y: 0) strongSelf.nextLabel.frame.origin = .zero }){ [weak self] (status) in guard let strongSelf = self else { return } let tmpCurrentLabel = strongSelf.nextLabel strongSelf.nextLabel = strongSelf.currentLabel strongSelf.nextLabel.frame.origin.x = viewWidth strongSelf.currentLabel = tmpCurrentLabel } } override func draw(_ rect: CGRect) { super.draw(rect) if label1.frame.width > 0 { return } label1.frame = CGRect(origin: .zero, size: frame.size) label2.frame = CGRect(origin: CGPoint(x: frame.width, y: 0), size: frame.size) clipsToBounds = true addSubview(label1) addSubview(label2) var tempOneString = "" var tempTwoString = "" tempOneString = currentLabel.text ?? "" tempTwoString = nextLabel.text ?? "" currentLabel = label1 nextLabel = label2 label1.text = tempOneString label2.text = tempTwoString } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } extension Reactive where Base: MarqueeView { var selectedMarquee: Observable<News> { return base.rx.click.withLatestFrom(self.base.viewModel.selectedMarquee) } }
JavaScript
UTF-8
864
2.625
3
[]
no_license
const fs = require('fs') const data = fs.readFileSync('linux_env', 'utf8') const lines = data.split(/\r?\n/) // console.log(lines.length) const envVars = [] lines.map((line, i) => { const separator = line.indexOf('=') // console.log(i, separator) envVars[i] = { title: line .slice(0, separator) .toString() .toLowerCase() .split('_').join (' '), vars: line.slice(separator + 1, line.length) } // envVars = [...envVars, ] }) // console.log('lines:', typeof lines) // lines.map(line => { // // console.log(line) // console.log(line.split(':').join('\n\t')) // }) // lines.map(line => console.log(line)) console.log() envVars.pop() envVars.pop() envVars.pop() envVars.pop() envVars.pop() envVars.pop() const noBashTitle = envVars.filter(line => !line.title.indexOf("bash") ) module.exports = envVars, noBashTitle
Java
UTF-8
864
2.0625
2
[]
no_license
package com.eloisapaz.cloud.microservice; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.ws.rs.core.MediaType; import javax.ws.rs.Produces; @RestController public class Controller { @RequestMapping(value = "/github/{gitUser}/twitter/{ttUser}", method = RequestMethod.GET) @Produces(MediaType.APPLICATION_JSON) public ResponseEntity<String> getUser(@PathVariable("gitUser") String gitUser, @PathVariable("ttUser") String ttUser){ return new ResponseEntity(TwitterAndGitService.getTwitterAndGit(ttUser, gitUser), HttpStatus.OK); } }