code
stringlengths
0
29.6k
language
stringclasses
9 values
AST_depth
int64
3
30
alphanumeric_fraction
float64
0.2
0.86
max_line_length
int64
13
399
avg_line_length
float64
5.02
139
num_lines
int64
7
299
source
stringclasses
4 values
var main = function(){ let wordView = new WordView() wordView.start('mynetwork') window.ww = wordView } var colormap = { 'relatedto': '#dcdcdc' , 'isa': 'lightblue' // similat , 'synonym': '#57f09d' // opposite , 'antonym': 'purple' , '>>': 'red' , 'derived': 'pink' } class WordView { create(nodeId) { /* create the network view on the given element id*/ var options = {}; let data = this.getData() var container = document.getElementById(nodeId); var network = new vis.Network(container, data, options); return network; } start(name){ this.network = this.create(name); bus.$on('message', this.wsMessage.bind(this)) } wsMessage(data) { let sent = [] let tokens = data.data.tokens || []; for(let l of tokens) { sent.push(l[0]) } this.addWords(sent); if(data.data.ident) { //this.presentConceptNetResult(data) } if(data.data.word) { this.presentWord(data) } } presentWord(data) { let word = data.data.word; //this.addWord(word) //this.addWords() window.word = word let value = word.value; if(value == undefined) { console.warn(`Old data cache does not contain "value" attribte. Please delete dictionary file and update the cache.`) return } let iters = ['synonym', 'antonym'] for (var j = 0; j < iters.length; j++) { if(word[iters[j]] == undefined) { console.log(`Word "${value}" does not have "${iters[j]}"`) continue } for (var i = 0; i < word[iters[j]].length; i++) { this.addRelate(value, word[iters[j]][i], iters[j]) }; } window.vpr = this } presentConceptNetResult(data){ let metas = data.data.ident.meta; for(let meta of metas) { let end = meta.end.label.toLowerCase(); let label = meta.rel.label.toLowerCase(); let start = meta.start.label.toLowerCase(); if( meta.end.language != 'en' || meta.start.language != 'en' ) { continue; } if(meta.weight < 1.4) { continue; } this.addRelate(start, end, label) this.addEdge(start, end, label) } console.log(data.data.type, Object.keys(data.data)) console.log(data.data) } addWords(words, edgeLabel) { let last; for(let token of words) { let c = this.addWord(token.toLowerCase()) if(last) { this.addEdge(last.toLowerCase(), token.toLowerCase(), edgeLabel) } last = token } } nodes(){ if(this._nodes == undefined ) { this._nodes = new vis.DataSet([]) }; return this._nodes; } edges(){ if(this._edges == undefined ) { this._edges = new vis.DataSet([]) }; return this._edges; } addWord(word){ word = word.toLowerCase() if(word[0] == 'a') { let _word = word.split(' ').slice(1).join(' ') if(_word != '') { word = _word; } } if(word.split(' ').length > 1) { return this.addWords(word.split(' '), 'derived') } let nodes = this.nodes(); let enode = nodes.get(word); if(enode != null) return enode; return nodes.add({ id: word , label: word , color: '#EEE' , shape: 'box' }) } addEdge(a, b, related='>>') { let edges = this.edges(); related = related.toLowerCase() let eedge = edges.get(`${a}${b}`); if(eedge != null) return eedge; let cmap = colormap[related]; let cl = cmap; if(typeof(cmap) == 'string') { cmap = {} } else { cl = cmap.color; } this.edges().add(Object.assign({ id:`${a}${b}` , from:a , to: b , color: cl || '#DDD' // , value: .1 , arrows: { to: { scaleFactor: .4 } } , label: colormap[related] == undefined? related: undefined , related: related }, cmap)) } addRelate(word, relate, label='relatedTo') { /* Add a word related to another word, connecting an edge with an arrow pointing to relate (B) */ /* append a 'relateTo', a related to b */ this.addWord(word.toLowerCase()) this.addWord(relate.toLowerCase()) this.addEdge(word.toLowerCase(), relate.toLowerCase(), label) } getData(){ // create a network var data = { nodes: this.nodes() , edges: this.edges() }; return data; } } ;main();
javascript
14
0.455673
91
23.267281
217
starcoderdata
def getCArr(path="scripts\\script.txt"): #returns Command Array carr = [] f = open(path, "r") f1 = f.readlines() for statement in f1: carr.append(statement.rstrip("\n")) return carr
python
12
0.577273
43
25.75
8
inline
def metrics_update(self, name, S, T=None): target_csr = df_to_coo(self.D.target_df) score_mat = self.D.transform(S).values if self.online: # reindex by valid users and test items to keep dimensions consistent valid_mat = self.D.transform(T, self.V.user_in_test.index, 0).values elif self.cvx: valid_mat = score_mat else: valid_mat = None self.item_rec[name] = evaluate_item_rec( target_csr, score_mat, self._k1, device=self.device) self.user_rec[name] = evaluate_user_rec( target_csr, score_mat, self._c1, device=self.device) print(pd.DataFrame({ 'item_rec': self.item_rec[name], 'user_rec': self.user_rec[name], }).T) if len(self.mult): self.mtch_[name] = self._mtch_update(target_csr, score_mat, valid_mat, name)
python
13
0.568132
88
36.958333
24
inline
void laserdisc_data_w(laserdisc_info *info, UINT8 data) { UINT8 prev = info->datain; info->datain = data; /* call through to the player-specific write handler */ if (info->writedata != NULL) (*info->writedata)(info, prev, data); }
c
9
0.687764
56
25.444444
9
inline
from IGParameter import * from IGNode import * from PIL import ImageOps from IGParameterRectangle import * from IGParameterCoords import * class IGGetRelativeCoords(IGNode): def __init__(self): super().__init__("Relative Coords") self.add_input_parameter("rectangle", IGParameterRectangle.IGParameterRectangle()) self.add_input_parameter("relative coords", IGParameterCoords.IGParameterCoords()) self.add_output_parameter("coords", IGParameterCoords.IGParameterCoords()) # default is middle self.inputs["relative coords"].x = 0.5 self.inputs["relative coords"].y = 0.5 def process(self): left = self.inputs["rectangle"].left top = self.inputs["rectangle"].top right = self.inputs["rectangle"].right bottom = self.inputs["rectangle"].bottom relative_coord_x = self.inputs["relative coords"].x relative_coord_y = self.inputs["relative coords"].y self.outputs["coords"].x = ((right-left)*relative_coord_x) + left self.outputs["coords"].y = ((bottom-top)*relative_coord_y) + top self.set_all_outputs_ready()
python
12
0.668416
91
42.961538
26
starcoderdata
function randomizeMap(map) { map.randomize(); store.dispatch(UPDATE_MAP, {map}); } function increaseTurn () { store.dispatch(INCREASE_TURN); } function updateMapWithRule(map) { map.updateWithRule(); store.dispatch(UPDATE_MAP, {map}); }
javascript
7
0.670498
36
18.076923
13
starcoderdata
<?php require("../../global/session_start.php"); ft_check_permission("admin"); $request = array_merge($_POST, $_GET); $form_id = ft_load_field("form_id", "form_id", ""); if (!ft_check_form_exists($form_id)) { header("location: index.php"); exit; } // store the current selected tab in memory - except for pages which require additional // query string info. For those, use the parent page if (isset($request["page"]) && !empty($request["page"])) { $remember_page = $request["page"]; switch ($remember_page) { case "field_options": case "files": $remember_page = "fields"; break; case "edit_email": $remember_page = "emails"; break; } $_SESSION["ft"]["form_{$form_id}_tab"] = $remember_page; $page = $request["page"]; } else { $page = ft_load_field("page", "form_{$form_id}_tab", "edit_form_main"); } if (isset($request['edit_email_user_settings'])) { header("Location: edit.php?page=email_settings"); exit; } $view_submissions_link = "submissions.php?form_id={$form_id}"; if (isset($_SESSION["ft"]["last_link_page_{$form_id}"]) && isset($_SESSION["ft"]["last_submission_id_{$form_id}"]) && $_SESSION["ft"]["last_link_page_{$form_id}"] == "edit") { $view_submissions_link = "edit_submission.php?form_id={$form_id}&submission_id={$_SESSION["ft"]["last_submission_id_{$form_id}"]}"; } $same_page = ft_get_clean_php_self(); $tabs = array( "main" => array( "tab_label" => $LANG["word_main"], "tab_link" => "{$same_page}?form_id=$form_id&page=main", "pages" => array("main", "public_form_omit_list") ), "fields" => array( "tab_label" => $LANG["word_fields"], "tab_link" => "{$same_page}?form_id=$form_id&page=fields", "pages" => array("fields") ), "views" => array( "tab_label" => $LANG["word_views"], "tab_link" => "{$same_page}?form_id=$form_id&page=views", "pages" => array("edit_view", "view_tabs", "public_view_omit_list") ), "emails" => array( "tab_label" => $LANG["word_emails"], "tab_link" => "{$same_page}?form_id=$form_id&page=emails", "pages" => array("email_settings", "edit_email") ) ); $tabs = ft_module_override_data("admin_edit_form_tabs", $tabs); $order = ft_load_field("order", "form_sort_order", "form_name-ASC"); $keyword = ft_load_field("keyword", "form_search_keyword", ""); $status = ft_load_field("status", "form_search_status", ""); $client_id = ft_load_field("client_id", "form_search_client_id", ""); $search_criteria = array( "order" => $order, "keyword" => $keyword, "status" => $status, "client_id" => $client_id, // this is a bit weird, but it's used so that ft_get_form_prev_next_links() doesn't return incomplete forms: // they're not fully set up, so the Edit pages wouldn't work for them yet "is_admin" => false ); $links = ft_get_form_prev_next_links($form_id, $search_criteria); $prev_tabset_link = (!empty($links["prev_form_id"])) ? "edit.php?page=$page&form_id={$links["prev_form_id"]}" : ""; $next_tabset_link = (!empty($links["next_form_id"])) ? "edit.php?page=$page&form_id={$links["next_form_id"]}" : ""; // start compiling the page vars here, so we don't have to duplicate the shared stuff for each included code file below $page_vars = array(); $page_vars["tabs"] = $tabs; $page_vars["form_id"] = $form_id; $page_vars["view_submissions_link"] = $view_submissions_link; $page_vars["show_tabset_nav_links"] = true; $page_vars["prev_tabset_link"] = $prev_tabset_link; $page_vars["next_tabset_link"] = $next_tabset_link; $page_vars["prev_tabset_link_label"] = $LANG["phrase_prev_form"]; $page_vars["next_tabset_link_label"] = $LANG["phrase_next_form"]; // load the appropriate code page switch ($page) { case "main": require("page_main.php"); break; case "public_form_omit_list": require("page_public_form_omit_list.php"); break; case "fields": require("page_fields.php"); break; case "files": require("page_files.php"); break; case "views": require("page_views.php"); break; case "edit_view": require("page_edit_view.php"); break; case "public_view_omit_list": require("page_public_view_omit_list.php"); break; case "emails": require("page_emails.php"); break; case "email_settings": require("page_email_settings.php"); break; case "edit_email": require("page_edit_email.php"); break; default: $vals = ft_module_override_data("admin_edit_form_page_name_include", array("page_name" => "page_main.php")); require($vals["page_name"]); break; }
php
12
0.617448
133
29.771812
149
starcoderdata
public static void visitEntries(STXRefSection section, IXRefEntryVisitor visitor) throws IOException { Iterator i = section.subsectionIterator(); while (i.hasNext()) { STXRefSubsection subsection = (STXRefSubsection) i.next(); for (Iterator ie = subsection.getEntries().iterator(); ie.hasNext(); ) { try { ((STXRefEntry) ie.next()).accept(visitor); } catch (XRefEntryVisitorException e) { // in this context the exception type is always an // IOException throw (IOException) e.getCause(); } } } }
java
15
0.540698
102
44.933333
15
inline
//****************************************************************** // // utilidades.h // // Define una serie de MACROS que se van a utilizar a lo largo // de todo el programa.Son en particular los nombres de las // componentes en los distintos tipos de vectores. // // fecha: 04/03/99 // // Modifications-----> // Date By Commets // //****************************************************************** #ifndef UTILIDADES_H #define UTILIDADES_H #include #include #include #include #include #define X 1 #define Y 2 #define Z 3 #define I 1 #define J 2 #define K 3 #define L 4 #define XI 1 #define ETA 2 #define ZETA 3 //////////////////////////////////////////////////////////// // // Funciones globales // //////////////////////////////////////////////////////////// int factorial (int n); int combinacion (int n, int p); double maximo (double a, double b); #endif UTILIDADES_H
c
6
0.468405
68
18.387755
49
starcoderdata
void floyd_warshall(int** arr, int n) { rep(k,0,n) rep(i,0,n) rep(j,0,n) if (arr[i][k] != INF && arr[k][j] != INF) arr[i][j] = min(arr[i][j], arr[i][k] + arr[k][j]); // Check negative cycles rep(i,0,n) rep(j,0,n) rep(k,0,n) if (arr[i][k] != INF && arr[k][k] < 0 && arr[k][j]!=INF) arr[i][j] = -INF; } // vim: cc=60 ts=2 sts=2 sw=2:
c++
11
0.493369
60
36.7
10
starcoderdata
package io.graversen.trunk.mapper; import org.modelmapper.config.Configuration; /** * @author Martin */ public class ObjectMapperFactory { /** * ModelMapper with: * * ignored * matching enabled * access level: private * */ public static ObjectMapper defaultObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.getConfiguration() .setAmbiguityIgnored(true) .setFieldMatchingEnabled(true) .setFieldAccessLevel(Configuration.AccessLevel.PRIVATE); return objectMapper; } }
java
11
0.625509
72
24.413793
29
starcoderdata
<?php namespace Dokobit\Gateway; use Dokobit\Gateway\Result\ResultInterface; /** * Response mapper interface for building response mappers. */ interface ResponseMapperInterface { /** * Map response to result objects * @param array $response * @param ResultInterface $result * @return ResultInterface */ public function map(array $response, ResultInterface $result): ResultInterface; }
php
8
0.730603
83
23.421053
19
starcoderdata
""" (c) April 2017 by Code for plotting behavioral cloning. No need to use command line arguments, just run `python plot_bc.py`. Easy! Right now it generates two figures per environment, one with validation set losses and the other with returns. The latter is probably more interesting. """ import argparse import gym import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import os import pickle import sys np.set_printoptions(edgeitems=100, linewidth=100, suppress=True) # Some matplotlib settings. plt.style.use('seaborn-darkgrid') error_region_alpha = 0.25 LOGDIR = 'logs/' FIGDIR = 'figures/' title_size = 22 tick_size = 17 legend_size = 17 ysize = 18 xsize = 18 lw = 3 ms = 8 colors = ['red', 'blue', 'yellow', 'black'] def plot_bc_modern(edir): """ Plot the results for this particular environment. """ subdirs = os.listdir(LOGDIR+edir) print("plotting subdirs {}".format(subdirs)) # Make it easy to count how many of each numrollouts we have. R_TO_COUNT = {'4':0, '11':0, '18':0, '25':0} R_TO_IJ = {'4':(0,2), '11':(1,0), '18':(1,1), '25':(1,2)} fig,axarr = plt.subplots(2, 3, figsize=(24,15)) axarr[0,2].set_title(edir+", Returns, 4 Rollouts", fontsize=title_size) axarr[1,0].set_title(edir+", Returns, 11 Rollouts", fontsize=title_size) axarr[1,1].set_title(edir+", Returns, 18 Rollouts", fontsize=title_size) axarr[1,2].set_title(edir+", Returns, 25 Rollouts", fontsize=title_size) # Don't forget to plot the expert performance! exp04 = np.mean(np.load("expert_data/"+edir+"_004.npy")[()]['returns']) exp11 = np.mean(np.load("expert_data/"+edir+"_011.npy")[()]['returns']) exp18 = np.mean(np.load("expert_data/"+edir+"_018.npy")[()]['returns']) axarr[0,2].axhline(y=exp04, color='brown', lw=lw, linestyle='--', label='expert') axarr[1,0].axhline(y=exp11, color='brown', lw=lw, linestyle='--', label='expert') axarr[1,1].axhline(y=exp18, color='brown', lw=lw, linestyle='--', label='expert') if 'Reacher' not in edir: exp25 = np.mean(np.load("expert_data/"+edir+"_025.npy")[()]['returns']) axarr[1,2].axhline(y=exp25, color='brown', lw=lw, linestyle='--', label='expert') for dd in subdirs: ddsplit = dd.split("_") # `dd` is of the form `numroll_X_seed_Y` numroll, seed = ddsplit[1], ddsplit[3] xcoord = np.load(LOGDIR+edir+"/"+dd+"/iters.npy") tr_loss = np.load(LOGDIR+edir+"/"+dd+"/tr_loss.npy") val_loss = np.load(LOGDIR+edir+"/"+dd+"/val_loss.npy") returns = np.load(LOGDIR+edir+"/"+dd+"/returns.npy") mean_ret = np.mean(returns, axis=1) std_ret = np.std(returns, axis=1) # Playing with dictionaries ijcoord = R_TO_IJ[numroll] cc = colors[ R_TO_COUNT[numroll] ] R_TO_COUNT[numroll] += 1 axarr[ijcoord].plot(xcoord, mean_ret, lw=lw, color=cc, label=dd) axarr[ijcoord].fill_between(xcoord, mean_ret-std_ret, mean_ret+std_ret, alpha=error_region_alpha, facecolor=cc) # Cram the training and validation losses on these subplots. axarr[0,0].plot(xcoord, tr_loss, lw=lw, label=dd) axarr[0,1].plot(xcoord, val_loss, lw=lw, label=dd) boring_stuff(axarr, edir) plt.tight_layout() plt.savefig(FIGDIR+edir+".png") def plot_bc_humanoid(edir): """ Plots humanoid. The argument here is kind of redundant... also, I guess we'll have to ignore one of the plots here since Humanoid will have 5 subplots. Yeah, it's a bit awkward. """ assert edir == "Humanoid-v1" subdirs = os.listdir(LOGDIR+edir) print("plotting subdirs {}".format(subdirs)) # Make it easy to count how many of each numrollouts we have. R_TO_COUNT = {'80':0, '160':0, '240':0} R_TO_IJ = {'80':(1,0), '160':(1,1), '240':(1,2)} fig,axarr = plt.subplots(2, 3, figsize=(24,15)) axarr[0,2].set_title("Empty Plot", fontsize=title_size) axarr[1,0].set_title(edir+", Returns, 80 Rollouts", fontsize=title_size) axarr[1,1].set_title(edir+", Returns, 160 Rollouts", fontsize=title_size) axarr[1,2].set_title(edir+", Returns, 240 Rollouts", fontsize=title_size) # Plot expert performance (um, this takes a while...). exp080 = np.mean(np.load("expert_data/"+edir+"_080.npy")[()]['returns']) exp160 = np.mean(np.load("expert_data/"+edir+"_160.npy")[()]['returns']) exp240 = np.mean(np.load("expert_data/"+edir+"_240.npy")[()]['returns']) axarr[1,0].axhline(y=exp080, color='brown', lw=lw, linestyle='--', label='expert') axarr[1,1].axhline(y=exp160, color='brown', lw=lw, linestyle='--', label='expert') axarr[1,2].axhline(y=exp240, color='brown', lw=lw, linestyle='--', label='expert') for dd in subdirs: ddsplit = dd.split("_") # `dd` is of the form `numroll_X_seed_Y` numroll, seed = ddsplit[1], ddsplit[3] xcoord = np.load(LOGDIR+edir+"/"+dd+"/iters.npy") tr_loss = np.load(LOGDIR+edir+"/"+dd+"/tr_loss.npy") val_loss = np.load(LOGDIR+edir+"/"+dd+"/val_loss.npy") returns = np.load(LOGDIR+edir+"/"+dd+"/returns.npy") mean_ret = np.mean(returns, axis=1) std_ret = np.std(returns, axis=1) # Playing with dictionaries ijcoord = R_TO_IJ[numroll] cc = colors[ R_TO_COUNT[numroll] ] R_TO_COUNT[numroll] += 1 axarr[ijcoord].plot(xcoord, mean_ret, lw=lw, color=cc, label=dd) axarr[ijcoord].fill_between(xcoord, mean_ret-std_ret, mean_ret+std_ret, alpha=error_region_alpha, facecolor=cc) # Cram the training and validation losses on these subplots. axarr[0,0].plot(xcoord, tr_loss, lw=lw, label=dd) axarr[0,1].plot(xcoord, val_loss, lw=lw, label=dd) boring_stuff(axarr, edir) plt.tight_layout() plt.savefig(FIGDIR+edir+".png") def boring_stuff(axarr, edir): """ Axes, titles, legends, etc. Yeah yeah ... """ for i in range(2): for j in range(3): if i == 0 and j == 0: axarr[i,j].set_ylabel("Loss Training MBs", fontsize=ysize) if i == 0 and j == 1: axarr[i,j].set_ylabel("Loss Validation Set", fontsize=ysize) else: axarr[i,j].set_ylabel("Average Return", fontsize=ysize) axarr[i,j].set_xlabel("Training Minibatches", fontsize=xsize) axarr[i,j].tick_params(axis='x', labelsize=tick_size) axarr[i,j].tick_params(axis='y', labelsize=tick_size) axarr[i,j].legend(loc="best", prop={'size':legend_size}) axarr[i,j].legend(loc="best", prop={'size':legend_size}) axarr[0,0].set_title(edir+", Training Losses", fontsize=title_size) axarr[0,1].set_title(edir+", Validation Losses", fontsize=title_size) axarr[0,0].set_yscale('log') axarr[0,1].set_yscale('log') def plot_bc(e): """ Split into cases. It makes things easier for me. """ env_to_method = {'Ant-v1': plot_bc_modern, 'HalfCheetah-v1': plot_bc_modern, 'Hopper-v1': plot_bc_modern, 'Walker2d-v1': plot_bc_modern, 'Reacher-v1': plot_bc_modern, 'Humanoid-v1': plot_bc_humanoid} env_to_method[e](e) if __name__ == "__main__": env_dirs = [e for e in os.listdir(LOGDIR) if "text" not in e] print("Plotting with one figure per env_dirs = {}".format(env_dirs)) for e in env_dirs: plot_bc(e)
python
16
0.601107
89
39.593583
187
starcoderdata
/* * Dicas: * -> CTRL + SHIFT + S para criar todos os tipos de métodos (hashcode, * getters and setters e até mesmo outros tipos de funcionalidades... * -> CTRL + D deleta uma linha inteira * -> CTRL + SHIFT + O arruma as importações * -> CTRL + SHIFT + F para arrumar automaticamente o código * */ package com.thiago.bookstore.domain; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Objects; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; /* * Sobre o @Entity: * Ele irá basicamente dizer para o JPA e o Hibernate que esta classe * é uma entidade, que pode criar uma tabela para nossa base de dados, tanto que você pode * até mesmo instanciar ao lado dela o nome da tabela, se for de seu desejo. * * Mas caso isso não seja feito, a tabela será criada com o próprio nome da classe. */ @Entity public class Categoria implements Serializable{ //1L é o valor padrão gerado para a serialVersion private static final long serialVersionUID = 1L; //Variáveis @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String nome; private String descricao; @OneToMany(mappedBy = "categoria") //Declaração do array de Livro -- private List livros = new ArrayList<>(); public Categoria() { super(); } /* Sobre este construtor: * Não selecionamos livros por que quando formos instanciar uma categoria não * precisamos passar um array de livros */ public Categoria(Integer id, String nome, String descricao) { super(); this.id = id; this.nome = nome; this.descricao = descricao; } // Getters and Setters -> Acessores e modificadores de uma forma mais simples public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public List getLivros() { return livros; } public void setLivros(List livros) { this.livros = livros; } /* Sobre o Hash e o equals: * O hashcode e o equals vão ser usados para fazer a comparação dos dados da * variável em memória (Comparar os ids) */ @Override public int hashCode() { return Objects.hash(id); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Categoria other = (Categoria) obj; return Objects.equals(id, other.id); } }
java
10
0.709235
91
22.896552
116
starcoderdata
import produce, { enableMapSet } from 'immer' enableMapSet() /** * createReducer - Creates immer compatible reducer. * * @param {object} initialState initial redux state * @param {object} actionHandlers <action_name, reducer> map * @returns {Function} immer compatible reducer function */ const createReducer = (initialState, actionHandlers = {}) => (state = initialState, action) => { return produce(state, draft => { const handler = actionHandlers[action.type] return handler && handler(draft, action) }) } export default createReducer
javascript
11
0.723684
96
29.4
20
starcoderdata
from imageai.Detection import ObjectDetection import os import cv2 import sys model_path = str(sys.argv[1]) dataset_path = model_path + '/Dataset' inpath = model_path + "/MinuteMask/" outpath = model_path + "/BGDetections/" execution_path = os.getcwd() video_amount = len(next(os.walk(dataset_path))[2]) + 1 detector = ObjectDetection() detector.setModelTypeAsYOLOv3() detector.setModelPath( os.path.join(execution_path , "./yolo.h5")) detector.loadModel() custom = detector.CustomObjects(car=True, bus=True,truck=True) for i in range(1,video_amount): Len = len(os.listdir(os.path.join(inpath,str(i)))) if(not os.path.exists(outpath+str(i))): os.mkdir(outpath+str(i)) texfile=open(outpath+str(i)+"/out.txt","w") for q in range(Len): detections = detector.detectCustomObjectsFromImage( custom_objects=custom,input_image=os.path.join(execution_path , inpath+str(i)+"/"+str(q+1)+'.png'), output_image_path=os.path.join(execution_path , outpath+str(i)+"/"+str(q+1)+'.png'), minimum_percentage_probability=10) for eachObject in detections: if eachObject["percentage_probability"]>10.0: texfile.write(str(i)+"," +str(q)+", "+str(eachObject["percentage_probability"])+","+str(eachObject["box_points"])+","+str(eachObject["name"] )+ "\n")
python
23
0.679031
279
44.551724
29
starcoderdata
<?php declare(strict_types=1); namespace Symplify\PhpConfigPrinter\ExprResolver; use PhpParser\Node\Arg; use PhpParser\Node\Expr; use PhpParser\Node\Expr\FuncCall; use PhpParser\Node\Name\FullyQualified; final class ServiceReferenceExprResolver { public function __construct( private StringExprResolver $stringExprResolver ) { } public function resolveServiceReferenceExpr( string $value, bool $skipServiceReference, string $functionName ): Expr { $value = ltrim($value, '@'); $expr = $this->stringExprResolver->resolve($value, $skipServiceReference, false); if ($skipServiceReference) { return $expr; } $args = [new Arg($expr)]; return new FuncCall(new FullyQualified($functionName), $args); } }
php
13
0.663415
89
23.117647
34
starcoderdata
// Fill out your copyright notice in the Description page of Project Settings. #include "AbilitySystem/Items/FPGABaseItem.h" #include "AbilitySystemComponent.h" FString UFPGABaseItem::GetIdentifierString() const { return GetPrimaryAssetId().ToString(); } FPrimaryAssetId UFPGABaseItem::GetPrimaryAssetId() const { // This is a DataAsset and not a blueprint so we can just use the raw FName // For blueprints you need to handle stripping the _C suffix return FPrimaryAssetId(ItemType, GetFName()); } void UFPGABaseItem::ApplyItem(UAbilitySystemComponent* AbilitySystem) { if (!AbilitySystem) return; for (TSubclassOf Ability : GrantedAbilities) { //UE_LOG(LogTemp, Warning, TEXT("Granted ability %s"), *Ability->GetName()); FGameplayAbilitySpecHandle AbilitySpecHandle = AbilitySystem->GiveAbility(FGameplayAbilitySpec(Ability.GetDefaultObject())); AbilitySpecHandles.Add(AbilitySpecHandle); } for (TSubclassOf Effect : GrantedEffects) { AbilitySystem->BP_ApplyGameplayEffectToSelf(Effect, 0.f, FGameplayEffectContextHandle()); } } void UFPGABaseItem::RemoveItem(UAbilitySystemComponent* AbilitySystem) { if (!AbilitySystem) return; for (FGameplayAbilitySpecHandle Ability : AbilitySpecHandles) { AbilitySystem->ClearAbility(Ability); } for (TSubclassOf Effect : GrantedEffects) { AbilitySystem->RemoveActiveGameplayEffectBySourceEffect(Effect, nullptr, 1); } }
c++
13
0.788346
126
28.27451
51
starcoderdata
#import #import @interface AppSwitcherPrivacy : CDVPlugin - (void)unblock:(CDVInvokedUrlCommand*)command; - (void)block:(CDVInvokedUrlCommand*)command; @end
c
5
0.78481
47
22.7
10
starcoderdata
/* * Carbon framework * Timers base class * * Copyright (c) 2013-2015 Softland. All rights reserved. * Licensed under the Apache License, Version 2.0 */ /* * Revision history: * * Revision 1.0, 27.03.2013 16:24:13 * Initial revision. * * Revision 2.0, 18.07.2015 22:44:51 * Completely rewrite to use non-static callbacks. */ #ifndef __CARBON_EVENT_TIMER_H_INCLUDED__ #define __CARBON_EVENT_TIMER_H_INCLUDED__ #include #include "shell/config.h" #include "shell/types.h" #include "shell/hr_time.h" #include "shell/object.h" #include "shell/lockedlist.h" #if CARBON_DEBUG_TRACK_OBJECT #include "shell/track_object.h" #endif /* CARBON_DEBUG_TRACK_OBJECT */ typedef std::function timer_cb_t; #if CARBON_DEBUG_TRACK_OBJECT #define __CTimer_PARENT ,public CTrackObject #else /* CARBON_DEBUG_TRACK_OBJECT */ #define __CTimer_PARENT #endif /* CARBON_DEBUG_TRACK_OBJECT */ class CTimer : public CObject, public CListItem __CTimer_PARENT { public: enum { timerPeriodic = 0x1 }; protected: hr_time_t m_hrTime; /* Next fire time */ hr_time_t m_hrPeriod; /* Timer period */ timer_cb_t m_callback; /* Timer function */ int m_options; /* Timer options, timerXXX */ void* m_pParam; /* Timer parameter */ public: CTimer(hr_time_t hrPeriod, timer_cb_t callback, int options, void* pParam, const char* strName); CTimer(hr_time_t hrPeriod, timer_cb_t callback, int options, const char* strName); CTimer(hr_time_t hrPeriod, timer_cb_t callback, void* pParam, const char* strName); CTimer(hr_time_t hrPeriod, timer_cb_t callback, const char* strName); virtual ~CTimer(); void* operator new(size_t size) throw(); void* operator new[](size_t size) throw(); void operator delete(void* pData); void operator delete[](void* pData); public: boolean_t isPeriodic() const { return (m_options&timerPeriodic) != 0; } hr_time_t getTime() const { return m_hrTime; } virtual void restart(hr_time_t hrNewPeriod = HR_0) { if ( hrNewPeriod != HR_0 ) { m_hrPeriod = hrNewPeriod; } m_hrTime = hr_time_now() + m_hrPeriod; } virtual void pause() { m_hrTime = hr_time_now() + HR_FOREVER; } virtual void execute() { if ( m_callback ) { m_callback(m_pParam); } } public: #if CARBON_DEBUG_DUMP virtual void dump(const char* strPref = "") const; #else /* CARBON_DEBUG_DUMP */ virtual void dump(const char* strPref = "") const { UNUSED(strPref); } #endif /* CARBON_DEBUG_DUMP */ }; #define SAFE_DELETE_TIMER(__pTimer, __pEventLoop) \ do { \ if ( (__pTimer) != 0 ) { \ (__pEventLoop)->deleteTimer(__pTimer); \ (__pTimer) = 0; \ } \ } while(0) #define TIMER_CALLBACK(__class_member, __object) \ std::bind(&__class_member, __object, std::placeholders::_1) /* * WatchDog API */ typedef CTimer* wd_handle_t; class CEventLoop; extern wd_handle_t wdCreate(hr_time_t hrTimeout, timer_cb_t cb, CEventLoop* pEventLoop = 0, void* p = 0, const char* strName = 0); extern void wdCancel(wd_handle_t wdHandle, CEventLoop* pEventLoop = 0); #define SAFE_CANCEL_WD_WITH_EVENTLOOP(__handle, __pEventLoop) \ do { \ if ( (__handle) != 0 ) { \ wdCancel(__handle, __pEventLoop); \ (__handle) = 0; \ } \ } while(0) #define SAFE_CANCEL_WD(__handle) \ do { \ if ( (__handle) != 0 ) { \ wdCancel(__handle); \ (__handle) = 0; \ } \ } while(0) #endif /* __CARBON_EVENT_TIMER_H_INCLUDED__ */
c
12
0.593545
104
27.440299
134
starcoderdata
<?php class Template_model extends CI_Model { public function get_fields($parms) { $this->db->select('tf.*,tfd.Field_Data_Value'); $this->db->from('template_fields as tf'); $this->db->join('template_fields_data as tfd','tf.Template_Field_Id = tfd.Template_Field_Id','left'); $this->db->where(array('tf.Template_Id' => $parms['Template_Id'],'tfd.Template_Data_Id' => $parms['Template_Data_Id'])); return $this->db->get()->result_array(); } public function get_lcp_list($parms) { $this->db->select('td.*,t.Template_Type'); $this->db->from('template_data as td'); $this->db->join('templates as t','t.Template_Id = td.Template_Id','left'); $this->db->where(array('td.Is_Deleted' => '0', 'td.Is_Blocked' => '0','td.Program_Id'=>$parms['Program_Id'], 't.Template_Type' => $parms['Template_Type'])); if(isset($parms['search']) && !empty($parms['search'])){ $this->db->where($parms['search']); } $this->db->limit(DEFAULT_NO_PER_PAGE, $parms['start']); $this->db->order_by('Created_On','desc'); return $this->db->get()->result_array(); } public function get_vsl_list($parms) { $this->db->select('td.*,t.Template_Type'); $this->db->from('template_data as td'); $this->db->join('templates as t','t.Template_Id = td.Template_Id','left'); $this->db->where(array('td.Is_Deleted' => '0', 'td.Is_Blocked' => '0','td.Program_Id'=>$parms['Program_Id'], 't.Template_Type' => $parms['Template_Type'])); if(isset($parms['search']) && !empty($parms['search'])){ $this->db->where($parms['search']); } $this->db->limit(DEFAULT_NO_PER_PAGE, $parms['start']); $this->db->order_by('Created_On','desc'); return $this->db->get()->result_array(); } }
php
14
0.577683
164
44.682927
41
starcoderdata
package org.codehaus.prometheus.processors.standardprocessor; import org.codehaus.prometheus.processors.IntegerProcess; import org.codehaus.prometheus.processors.NoArgProcess; import org.codehaus.prometheus.processors.TestProcess; import org.codehaus.prometheus.processors.VoidValue; import java.util.List; /** * Unittests the {@link StandardProcessor}. * * @author */ public class StandardProcessor_OnceTest extends StandardProcessor_AbstractTest { public void testNoMatchingReceive() { String arg = "foo"; TestProcess process = new IntegerProcess(); newPipedProcessor(process); spawned_assertPut(arg); spawned_assertOnceAndReturnTrue(); spawned_assertTake(arg); process.assertNotCalled(); spawned_assertTakeNotPossible(); } public void testSingleProcessReturnsVoid() { Integer arg = 10; IntegerProcess process = new IntegerProcess(arg, VoidValue.INSTANCE); newPipedProcessor(process); spawned_assertPut(arg); spawned_assertOnceAndReturnTrue(); spawned_assertTake(arg); process.assertCalledOnce(); spawned_assertTakeNotPossible(); } public void testFirstOfMultipleProcessesReturnsVoid() { Integer arg1 = 10; Integer arg2 = 20; IntegerProcess process1 = new IntegerProcess(arg1, VoidValue.INSTANCE); IntegerProcess process2 = new IntegerProcess(arg1,arg2); newPipedProcessor(process1,process2); spawned_assertPut(arg1); spawned_assertOnceAndReturnTrue(); spawned_assertTake(arg2); process1.assertCalledOnce(); process2.assertCalledOnce(); spawned_assertTakeNotPossible(); } public void testInputReturnsVoid() { TestProcess process = new NoArgProcess(); newPipedProcessor(process); spawned_assertPut(VoidValue.INSTANCE); spawned_assertOnceAndReturnTrue(); spawned_assertTakeNotPossible(); process.assertCalledOnce(); spawned_assertTakeNotPossible(); } public void testNoArgProcessReturnsValue() { Integer returned = 10; TestProcess process = new NoArgProcess(returned); newSourceProcessor(process); spawned_assertOnceAndReturnTrue(); spawned_assertTake(returned); process.assertCalledOnce(); spawned_assertTakeNotPossible(); } public void testSingleProcessReturnsNull() { Integer arg = 10; TestProcess process = new IntegerProcess(arg, null); newPipedProcessor(process); spawned_assertPut(arg); spawned_assertOnceAndReturnTrue(); spawned_assertTakeNotPossible(); process.assertCalledOnce(); } public void testFirstOfMultipleProcessesReturnsNull() { Integer arg1 = 1; TestProcess process1 = new IntegerProcess(arg1, null); TestProcess process2 = new IntegerProcess(); newPipedProcessor(process1, process2); spawned_assertPut(arg1); spawned_assertOnceAndReturnTrue(); process1.assertCalledOnce(); process2.assertNotCalled(); spawned_assertTakeNotPossible(); } public void testProcessReturnsIterator() { Integer arg = 10; List itemList = generateRandomNumberList(10); TestProcess process = new IntegerProcess(arg, itemList.iterator()); newPipedProcessor(process); spawned_assertPut(arg); for (Integer item : itemList) { spawned_assertOnceAndReturnTrue(); spawned_assertTake(item); spawned_assertTakeNotPossible(); } } public void testInputReturnsIterator() { List itemList = generateRandomNumberList(10); newPipedProcessor(); spawned_assertPut(itemList.iterator()); for (Integer item : itemList) { spawned_assertOnceAndReturnTrue(); spawned_assertTake(item); spawned_assertTakeNotPossible(); } } /* public void testChainedProcessesThatReturnIterators() { TestProcess process1; TestProcess process2; newProcessor(new Object[]{process1, process2}); } */ public void test_noInput_noOutput_noProcess() { newPipedProcessor(-1, -1, new Object[]{}); spawned_assertOnceAndReturnTrue(); } public void test_noProcess() { Integer arg = 1; newPipedProcessor(); spawned_assertPut(arg); spawned_assertOnceAndReturnTrue(); spawned_assertTake(arg); spawned_assertTakeNotPossible(); } public void test_onlyProcess() { Integer arg1 = 1; Integer arg2 = 2; TestProcess process = new IntegerProcess(arg1, arg2); newPipedProcessor(new Object[]{process}); spawned_assertPut(arg1); spawned_assertOnceAndReturnTrue(); spawned_assertTake(arg2); process.assertCalledOnce(); spawned_assertTakeNotPossible(); } public void test_noArgVoidProcess(){ TestProcess process = new VoidNoArgProcess(); newSourceProcessor(process); spawned_assertOnceAndReturnTrue(); process.assertCalledOnce(); spawned_assertTakeNotPossible(); } public static class VoidNoArgProcess extends TestProcess{ public void receive(){ signalCalled(); } } public void test_chainedProcesses() { Integer arg1 = 1; Integer arg2 = 2; Integer arg3 = 3; Integer arg4 = 4; TestProcess process1 = new IntegerProcess(arg1, arg2); TestProcess process2 = new IntegerProcess(arg2, arg3); TestProcess process3 = new IntegerProcess(arg3, arg4); newPipedProcessor(new Object[]{process1, process2, process3}); spawned_assertPut(arg1); spawned_assertOnceAndReturnTrue(); spawned_assertTake(arg4); process1.assertCalledOnce(); process2.assertCalledOnce(); process3.assertCalledOnce(); spawned_assertTakeNotPossible(); } }
java
11
0.649782
113
28.564593
209
starcoderdata
bool CircularQueue::push(const timespec &ts, const JVMPI_CallTrace &item, ThreadBucketPtr info) { size_t currentInput; size_t nextInput; do { currentInput = input.load(std::memory_order_relaxed); nextInput = advance(currentInput); if (output.load(std::memory_order_relaxed) == nextInput) { return false; } // TODO: have someone review the memory ordering constraints } while (!input.compare_exchange_strong(currentInput, nextInput, std::memory_order_relaxed)); write(item, currentInput); buffer[currentInput].tspec.tv_sec = ts.tv_sec; buffer[currentInput].tspec.tv_nsec = ts.tv_nsec; buffer[currentInput].info = std::move(info); buffer[currentInput].is_committed.store(COMMITTED, std::memory_order_release); return true; }
c++
11
0.682209
97
41.947368
19
inline
// Copyright 2016-2019 the Bayou Authors ( et alia). // Licensed AS IS and WITHOUT WARRANTY under the Apache License, // Version 2.0. Details: import { BaseConnection } from './BaseConnection'; import { BaseTokenAuthorizer } from './BaseTokenAuthorizer'; import { Context } from './Context'; import { ContextInfo } from './ContextInfo'; import { PostConnection } from './PostConnection'; import { ProxiedObject } from './ProxiedObject'; import { Schema } from './Schema'; import { Target } from './Target'; import { TokenMint } from './TokenMint'; import { WsConnection } from './WsConnection'; export { BaseConnection, BaseTokenAuthorizer, Context, ContextInfo, PostConnection, ProxiedObject, Schema, Target, TokenMint, WsConnection };
javascript
12
0.71705
69
28.535714
28
starcoderdata
package leetcode_go import ( "fmt" "testing" ) func TestFindMin(t *testing.T) { fmt.Println(findMin([]int{193, 194, 198, 199, 200, 204, 207, 212, 214, 217, 221, 225, 227, 230, 231, 232, 233, 235, 237, 245, 247, 252, 260, 262, 263, 264, 265, 271, 276, 284, 285, 287, 296, 297, 4, 9, 21, 24, 25, 27, 28, 29, 30, 36, 40, 45, 50, 55, 63, 64, 65, 77, 79, 100, 102, 103, 107, 111, 114, 118, 120, 123, 126, 130, 132, 134, 135, 139, 142, 143, 146, 147, 149, 150, 151, 152, 153, 157, 162, 167, 170, 173, 174, 176, 179, 182, 183, 184, 187, 189})) }
go
11
0.606112
103
35.8125
16
starcoderdata
#include "mouse3d.h" #include Mouse3D::Mouse3D() { motion_x = 0; motion_y = 0; motion_z = 0; motion_rx = 0; motion_ry = 0; motion_rz = 0; bnum = 0; bpress = 0; stop_flag = 0; } void Mouse3D::stop() { stop_flag = 1; } void Mouse3D::run() { spnav_event sev; if(spnav_open()==-1) { fprintf(stderr, "Failed to connect to the space navigator daemon.\n"); return; } while(stop_flag==0){ if(spnav_poll_event(&sev)){ if(sev.type == SPNAV_EVENT_MOTION) { // if(sev.motion.x != motion_x || sev.motion.y != motion_y || sev.motion.z != motion_z){ motion_x=sev.motion.x; motion_y=sev.motion.y; motion_z=sev.motion.z; emit motion(motion_x,motion_y,motion_z); // } // if(sev.motion.rx != motion_rx || sev.motion.ry != motion_ry || sev.motion.rz != motion_rz){ motion_rx=sev.motion.rx; motion_ry=sev.motion.ry; motion_rz=sev.motion.rz; emit motionR(motion_rx,motion_ry,motion_rz); // } } else{ /* SPNAV_EVENT_BUTTON */ if(sev.button.bnum != bnum || sev.button.press != bpress) { bnum = sev.button.bnum; bpress = sev.button.press; emit button(bnum,bpress); } } } } spnav_close(); }
c++
16
0.457902
109
26.087719
57
starcoderdata
"""Process a donation & issue a thank you letter or generate a report.""" DONORS_AMT = {'example': 100, 'other': 20, 'more': 200} DONORS_CT = {'example': 1, 'other': 2, 'more': 3} def main(): # pragma: no cover """Menu Interface. Input required.""" reply = None while reply is not quit: print("Message") print("1: Process a Donation & Send a Thank You") print("2: Create a Report") print("3. Quit this program") print("(Enter 'q' at any time to return to this menu.)") reply = int(input("1, 2, or 3?")) # Input if reply == 1: name, amount = receive_donation() add_amount(name, amount) print(write_letter(name, amount)) if reply == 2: print_report() if reply == 3: reply = quit def receive_donation(): # pragma: no cover """Receive new donation. Input required.""" amount = "" name = input("Enter the donor's name: ") # Input if name == "q": return while not amount.isdigit(): amount = input("Enter their donation: ") # Input if amount == "q": return return name, amount def add_amount(donor, donation): """Add the [amount] to the [donor]'s total.""" if donor in DONORS_AMT: DONORS_AMT[donor] += int(donation) DONORS_CT[donor] += 1 else: DONORS_AMT[donor] = int(donation) DONORS_CT[donor] = 1 def sort_report(): """Sort the DONORS_LIST by the DONORS_AMT.""" print("\tName\t\tDonation\tTotal Amt\tAverage") sorted_list = sorted(DONORS_AMT, key=DONORS_AMT.get) return sorted_list def print_report(): """Print the sorted donor list.""" x = sort_report() for donor in x: print("\t{}\t\t{}\t\t${}\t\t${}".format( donor, DONORS_CT[donor], DONORS_AMT[donor], DONORS_AMT[donor] / DONORS_CT[donor])) def write_letter(letter_to, contribution): """Print the thank you letter to the donor.""" letter = """Dear Mr. or Mrs. {}, \n\tThank you very much for your generous donation of ${}. It's thanks to people like you that we are able to continue our noble cause of shaving the homeless. Without your generous contribution even more homeless people would be living on the streets with a full set of whiskers.\n""".format( letter_to, contribution) return letter if __name__ == '__main__': main()
python
12
0.575271
73
30.1375
80
starcoderdata
package com.shawndfox.javafxconcurrency; import com.shawndfox.javafxconcurrency.model.FileProperties; import com.shawndfox.javafxconcurrency.model.WordCounterTask; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.stage.FileChooser; import javafx.stage.FileChooser.ExtensionFilter; /** * * @author */ public class WordCounterController implements Initializable { @FXML private TableView fileTable; private final ObservableList fileTableEntries = FXCollections.observableArrayList(); ExecutorService threads = Executors.newCachedThreadPool(); private String initialDirectory; /** * This is the event handler method for the AddFile button. Displays a file chooser * dialog so that the user can select files. * @param event * @throws IOException */ @FXML void addFileToTable(ActionEvent event) throws IOException { FileChooser dlg = new FileChooser(); dlg.setTitle("Pick a text file to analyze!"); dlg.setInitialDirectory(new File(initialDirectory)); dlg.getExtensionFilters().addAll( new ExtensionFilter("Text Files", "*.md", "*.txt", "*.xml", "*.html", "*.conf"), new ExtensionFilter("Java Files", "*.java")); File chosen = dlg.showOpenDialog(null); if(chosen != null) { FileProperties fp = new FileProperties(); fp.setTheFile(chosen); fp.setWordCount(""); fileTableEntries.add(fp); initialDirectory = chosen.getParent(); } } /** * For each entry in the file table, start a background thread to determine the word count of the file. * * @param event */ @FXML void startCounting(ActionEvent event) { Integer wordCount = 100; for(FileProperties entry : fileTableEntries) { //construct a task, and register an event so that Task task = new WordCounterTask(entry.getTheFile()); entry.bindWordCount(task.valueProperty()); threads.submit(task); } } /** * Perform initialization of the JavaFx application. Setup the table view and the initialDirectory * properties that will be eventually used in other methods. * @param url * @param rb */ @Override public void initialize(URL url, ResourceBundle rb) { fileTable.setItems(fileTableEntries); TableColumn<FileProperties, String> nameColumn = new TableColumn<>("File Name"); nameColumn.setCellValueFactory(new PropertyValueFactory("fileName")); TableColumn<FileProperties, String> wordCountColumn = new TableColumn<>("Word Count"); wordCountColumn.setCellValueFactory(new PropertyValueFactory("wordCount")); fileTable.getColumns().setAll(nameColumn, wordCountColumn); initialDirectory = System.getProperty("user.dir"); } }
java
11
0.697029
114
34.68
100
starcoderdata
def are_overlapped(gstart,gend,tstart,tend): return ( (( gstart <= tend ) and (gstart >= tstart)) or ((gend <= tend) and (gend >= tstart)) or ((tstart <= gend) and (tstart >= gstart))or ((tend <= gend) and (tend >= gstart)) ) # Runs through deid'ed (gs) file line by line # Enters PHI locations in a HASH phi with KEY = (patient_number appended, note_number) and VALUE = (ARRAY of PHI locations in that note) import re,sys from collections import defaultdict def run_stats(gold_path = 'id.deid', gold_cats_path= 'id-phi.phrase', test_path='phone.phi'): """ Inputs: gold_path: path to the gold standard file that does not include categories. gold_cats_path: path to the gold standard file that includes category information test_path: path to the test file that we want to run the stats on Outputs: Displays: - All categories present in gold standard file - Cumulative accuracy for all categories - Accuracy for each category """ patient_note_pattern = '^patient\s+(\d+)\s+note\s+(\d+)$' three_numbers_pattern = '^(\d+)\s+(\d+)\s+(\d+)$' test_phi = defaultdict(list) gold_phi = defaultdict(list) total_test_phi = 0 with open(test_path) as test: for line in test: results = re.findall(patient_note_pattern,line,flags=re.IGNORECASE) if len(results) ==1: #print(results) patient, note = results[0] continue elif len(results)>1: print(results) raise Exception("Debug here!") three_numbers = re.findall(three_numbers_pattern, line, flags=re.IGNORECASE) if len(three_numbers) ==1: (_,start,end) = three_numbers[0] #TODO: strings! #print('three',start,end) position = (start,end) test_phi[(patient,note)].append(position) total_test_phi +=1 #print(total_test_phi) total_events_gold = 0 with open(gold_path) as gold: for line in gold: results = re.findall(patient_note_pattern,line,flags=re.IGNORECASE) if len(results) ==1: patient, note = results[0] continue elif len(results)>1: print(results) raise Exception("Debug here!") three_numbers = re.findall(three_numbers_pattern, line, flags=re.IGNORECASE) if len(three_numbers) ==1: (_,start,end) = three_numbers[0] #TODO: strings! #print('three',start,end) position = (start,end) gold_phi[(patient,note)].append(position) total_events_gold += 1 # Runs through each patient_note combination in Gold Standard hash # Then in each note, runs through each PHI location # For each PHI location, checks if the same location exists in the same patient_note in the deid'ed hash # If there is a match, true positives is incremented # If there is no match, false negatives is incremented tp = 0; # true positives fn = 0; # false negatives n_checked_in_gold = 0 for (patient,note) in gold_phi: for (g_start,g_end) in gold_phi[patient,note]: found = False n_checked_in_gold += 1 if (patient,note) in test_phi: for t_start,t_end in test_phi[patient,note]: if are_overlapped(g_start,g_end, t_start,t_end): tp += 1 # true positive found = True break if not found: fn += 1 # Runs through each patient_note combination in deid'ed hash # Then in each note, runs through each PHI location # For each PHI location, checks if the same location exists in the same patient_note in the Gold Standard hash # If there is a match, true positives is incremented # If there is no match, false positives is incremented fp = 0 tp_test = 0 said_negative_test = 0 for (patient, note) in test_phi: for (t_start,t_end) in test_phi[patient,note]: found = False if (patient,note) in gold_phi: for g_start,g_end in gold_phi[patient,note]: if are_overlapped(g_start,g_end, t_start,t_end): found = True tp_test +=1 break else: said_negative_test +=1 if not found: fp += 1 # Calculates sensitivity and positive predictive value (PPV) sens = round((tp/(tp+fn))*1000)/1000.0; ppv = round(( (total_test_phi-fp)/total_test_phi)*1000)/1000; # Prints code performance statistics on the screen print("\n\n==========================") print("\nNum of true positives = {}".format(tp)) print("\nNum of false positives = {}".format(fp)) print("\nNum of false negatives = {}".format(fn)) print("\nSensitivity/Recall = {}".format(sens)) print("\nPPV/Specificity = {}".format(ppv)) print("\n==========================\n\n") """ Per category experiments!""" gold_cats_map = defaultdict(dict) gold_cats_pattern = '^(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s(\w+)*' total_events_gold_cats = 0 with open(gold_cats_path) as gold_cats: for line in gold_cats: results = re.findall(gold_cats_pattern,line,flags=re.IGNORECASE) if len(results) ==1: #print(results) patient,note,start,end,category = results[0] total_events_gold_cats += 1 if (patient,note) in gold_cats_map[category]: gold_cats_map[category][patient,note].append((start,end)) else: gold_cats_map[category][patient,note] = [(start,end)] elif len(results)>1: print(results) raise Exception("Debug here!") print('Total events in \'{}\': {}'.format(gold_cats_path,total_events_gold_cats)) categories = list(gold_cats_map.keys()) print('='*40) print('Categories Present:') for cat in categories: print(cat) print('='*40) print('\n'*5) for current_cat in categories: print("Examining \"{}\" category.".format(current_cat)) gold_phi = gold_cats_map[current_cat] # Runs through each patient_note combination in Gold Standard hash # Then in each note, runs through each PHI location # For each PHI location, checks if the same location exists in the same patient_note in the deid'ed hash # If there is a match, true positives is incremented # If there is no match, false negatives is incremented tp = 0; # true positives fn = 0; # false negatives n_checked_in_gold = 0 for (patient,note) in gold_phi: for (g_start,g_end) in gold_phi[patient,note]: found = False n_checked_in_gold += 1 if (patient,note) in test_phi: for t_start,t_end in test_phi[patient,note]: if are_overlapped(g_start,g_end, t_start,t_end): tp += 1 # true positive found = True break if not found: fn += 1 # Runs through each patient_note combination in deid'ed hash # Then in each note, runs through each PHI location # For each PHI location, checks if the same location exists in the same patient_note in the Gold Standard hash # If there is a match, true positives is incremented # If there is no match, false positives is incremented fp = 0 tp_test = 0 said_negative_test = 0 for (patient, note) in test_phi: for (t_start,t_end) in test_phi[patient,note]: found = False if (patient,note) in gold_phi: for g_start,g_end in gold_phi[patient,note]: if are_overlapped(g_start,g_end, t_start,t_end): found = True tp_test +=1 break else: said_negative_test +=1 if not found: fp += 1 # Calculates sensitivity and positive predictive value (PPV) sens = round((tp/(tp+fn))*1000)/1000.0; ppv = round(( (total_test_phi-fp)/total_test_phi)*1000)/1000; # Prints code performance statistics on the screen print("\n\n==========================") print("\nNum of true positives = {}".format(tp)) print("\nNum of false positives = {}".format(fp)) print("\nNum of false negatives = {}".format(fn)) print("\nSensitivity/Recall = {}".format(sens)) print("\nPPV/Specificity = {}".format(ppv)) print("\n==========================\n\n") if __name__== "__main__": run_stats(sys.argv[1], sys.argv[2], sys.argv[3])
python
18
0.53544
136
35.451362
257
starcoderdata
package com.electribesx.model; public class ESXGlobalParameters extends BufferManager { public ESXGlobalParameters (byte[] inBuffer, int inOffset) { super (inBuffer, inOffset); } }
java
8
0.751295
53
12.785714
14
starcoderdata
package com.mcplusa.coveo.connector.aem.indexing.config; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Service; import org.apache.jackrabbit.JcrConstants; import org.apache.sling.commons.osgi.PropertiesUtil; import org.osgi.service.component.ComponentContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Component( metatype = true, immediate = true, configurationFactory = true, label = CoveoIndexConfiguration.SERVICE_NAME, description = CoveoIndexConfiguration.SERVICE_DESCRIPTION) @Service(CoveoIndexConfiguration.class) @Properties({ @Property( name = "webconsole.configurationFactory.nameHint", value = "Primary Type: {primaryType}") }) public class CoveoIndexConfiguration { private static final Logger LOG = LoggerFactory.getLogger(CoveoIndexConfiguration.class); /** Filter Property for jcr:primary Type. */ public static final String PRIMARY_TYPE = JcrConstants.JCR_PRIMARYTYPE; public static final String SERVICE_NAME = "Coveo Index Configuration"; public static final String SERVICE_DESCRIPTION = "Service to configure the Coveo Index"; @Property( name = "primaryType", label = "Primary Type", description = "Primary Type for which this configuration is responsible. E.g. cq:Page or dam:Asset") public static final String PROPERTY_BASE_PATH = "primaryType"; @Property( name = "indexRules", cardinality = Integer.MAX_VALUE, label = "Index Rules", description = "List with the names of all properties that should be indexed.") public static final String PROPERTY_INDEX_RULES = "indexRules"; protected String[] indexRules; protected ComponentContext context; @Activate public void activate(ComponentContext context) { this.context = context; this.indexRules = PropertiesUtil.toStringArray( context.getProperties().get(CoveoIndexConfiguration.PROPERTY_INDEX_RULES)); } /** * Get method that returns all index rules. * * @return array of index rules */ public String[] getIndexRules() { return indexRules; } }
java
9
0.741247
96
31.985915
71
starcoderdata
package it.polito.oop.elective; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeMap; import java.util.stream.Collectors; /** * Manages elective courses enrollment. * * */ public class ElectiveManager { private Map students = new HashMap<>(); private TreeMap coursesR = new TreeMap<>(); private List notifications = new ArrayList<>(); /** * Define a new course offer. * A course is characterized by a name and a number of available positions. * * @param name : the label for the request type * @param availablePositions : the number of available positions */ public void addCourse(String name, int availablePositions) { Course element = new Course(name, availablePositions); coursesR.put(name, element); } /** * Returns a list of all defined courses * @return */ public SortedSet getCourses(){ return coursesR.navigableKeySet(); } /** * Adds a new student info. * * @param id : the id of the student * @param gradeAverage : the grade average */ public void loadStudent(String id, double gradeAverage){ if(!students.containsKey(id)) { Student element = new Student (id, gradeAverage); students.put(id, element); }else { students.get(id).setGradeAverage(gradeAverage); } } /** * Lists all the students. * * @return : list of students ids. */ public Collection getStudents(){ return students.keySet(); } /** * Lists all the students with grade average in the interval. * * @param inf : lower bound of the interval (inclusive) * @param sup : upper bound of the interval (inclusive) * @return : list of students ids. */ public Collection getStudents(double inf, double sup){ return students.values().stream().filter(x->(x.getGradeAverage()>= inf && x.getGradeAverage()<= sup)).map(x->x.getId()). collect(Collectors.toList()); } /** * Adds a new enrollment request of a student for a set of courses. * * The request accepts a list of course names listed in order of priority. * The first in the list is the preferred one, i.e. the student's first choice. * * @param id : the id of the student * @param selectedCourses : a list of of requested courses, in order of decreasing priority * * @return : number of courses the user expressed a preference for * * @throws ElectiveException : if the number of selected course is not in [1,3] or the id has not been defined. */ public int requestEnroll(String id, List courses) throws ElectiveException { if(!students.containsKey(id)) throw new ElectiveException(); for(Notifier tmp: this.notifications) { tmp.requestReceived(id); } List preferences = new LinkedList<>(); for(String tmp: courses) { if(!courses.contains(tmp)) throw new ElectiveException(); else { preferences.add(coursesR.get(tmp)); } } if(preferences.size()<1 || preferences.size()>3) throw new ElectiveException(); students.get(id).setPreferences(preferences); for(int i = 0; i<preferences.size(); ++i ) { preferences.get(i). getPreferences(). replace(i+1, preferences.get(i).getPreferences().get(i+1)+1); } return preferences.size(); } /** * Returns the number of students that selected each course. * * Since each course can be selected as 1st, 2nd, or 3rd choice, * the method reports three numbers corresponding to the * number of students that selected the course as i-th choice. * * In case of a course with no requests at all * the method reports three zeros. * * * @return the map of list of number of requests per course */ public Map numberRequests(){ return coursesR.values().stream().collect( Collectors.toMap(Course::getName, x->x.getPreferences().values().stream().collect(Collectors.toList()) )); } /** * Make the definitive class assignments based on the grade averages and preferences. * * Student with higher grade averages are assigned to first option courses while they fit * otherwise they are assigned to second and then third option courses. * * * @return the number of students that could not be assigned to one of the selected courses. */ public long makeClasses() { List studentsOrd = students.values().stream(). sorted(Comparator.comparing(Student::getGradeAverage).reversed()).collect(Collectors.toList()); for(Student tmp: studentsOrd ) { for(int i = 0; i< tmp.getPreferences().size(); ++i) { if(tmp.getPreferences().get(i).getAvailablePositions() != tmp.getPreferences().get(i).getSub().size()) { tmp.setAssigned(true); tmp.setChoose(i+1); tmp.getPreferences().get(i).getSub().add(tmp); tmp.setAttending(tmp.getPreferences().get(i)); for(Notifier tmpN: this.notifications) { tmpN.assignedToCourse(tmp.getId(), tmp.getPreferences().get(i).getName()); } break; } } } return students.values().stream().filter(x->x.getAssigned()== false).count(); } /** * Returns the students assigned to each course. * * @return the map course name vs. student id list. */ public Map getAssignments(){ return coursesR.values().stream().collect(Collectors.toMap( Course::getName , Course::getsubString )); } /** * Adds a new notification listener for the announcements * issues by this course manager. * * @param listener : the new notification listener */ public void addNotifier(Notifier listener) { this.notifications.add(listener); } /** * Computes the success rate w.r.t. to first * (second, third) choice. * * @param choice : the number of choice to consider. * @return the success rate (number between 0.0 and 1.0) */ public double successRate(int choice){ long numerator =students.values().stream().filter(x->x.getAssigned()== true).filter(x->(x.getChoose()) == choice).count(); long denominator = students.values().stream().count(); double result = (double) numerator/denominator; return result; } /** * Returns the students not assigned to any course. * * @return the student id list. */ public List getNotAssigned(){ return students.values().stream().filter(x->x.getAssigned()== false).map(x->x.getId()).collect(Collectors.toList()); } }
java
20
0.607432
127
27.90625
256
starcoderdata
protected IValueControl createEditorForType(Class toValueType, String tcProperty) { if (toValueType == null) { return null; } Class loPrimitive = Java.getPrimitiveClass(toValueType); // If we are setting the value to null, we don't know what the type is so just clear if (loPrimitive != null) { if (loPrimitive.equals(boolean.class)) { return new Checkbox(); } else if (toValueType.equals(String.class)) { return new Textbox(); } else { return new Textbox(); } } else if (loPrimitive == null) { // This was not a primitive type, so we need to create a full editor if (Java.isEqualOrAssignable(java.util.List.class, toValueType)) { return new ListEditor(toValueType, false, getPropertyName(tcProperty) + " List"); } else if (Java.isEqualOrAssignable(java.io.File.class, toValueType)) { return new FileTextbox(); } else if (Java.isEqualOrAssignable(DynamicEnum.class, toValueType)) { Combobox<? extends DynamicEnum> loCombobox = new Combobox(DynamicEnum.getEnumerations(toValueType)); return loCombobox; } else if (Java.isEqualOrAssignable(Dimension.class, toValueType)) { return new DimensionTextbox(); } else if (Java.isEqualOrAssignable(Point.class, toValueType)) { return new PointTextbox(); } else if (Java.isEqualOrAssignable(Color.class, toValueType)) { return new ColorChooser(); } } // If all else fails return new Textbox(); }
java
16
0.517312
116
33.473684
57
inline
def __add__(self,other_roipack): """Combine layers from two roipacks. Layers / svg file from first is maintained.""" comb = copy.deepcopy(self) if hasattr(comb,'layers'): lay1 = self.layer_names else: # Convert single-layer to multi-layer ROI comb.layers = {self.layer:self} comb.layer = 'multi_layer' lay1 = [self.layer] svg_fin = copy.copy(comb.svg) if hasattr(other_roipack,'layers'): lay2 = other_roipack.layer_names for k,L in other_roipack.layers.items(): comb.layers[k] = L comb.rois.update(L.rois) to_add = _find_layer(L.svg, k) svg_fin.getroot().insert(0, to_add) else: comb.layers[other_roipack.layer] = other_roipack to_add = _find_layer(other_roipack.svg, other_roipack.layer) svg_fin.getroot().insert(0, to_add) lay2 = [other_roipack.layer] # Maintain order of layers according to order of addition comb.layer_names = lay1+lay2 comb.svg = svg_fin comb.kdt = cKDTree(self.kdt.data) # necessary? for L in comb.layer_names: comb.layers[L].kdt = comb.kdt # Why the hell do I have to do this? #for r in comb.rois: # r.parent = comb # necessary? return comb
python
12
0.552143
91
42.78125
32
inline
@Test @EnabledOnCommand("ACL") void authWithUsername() { WithPassword.run(client, () -> { client.setOptions( ClientOptions.builder().pingBeforeActivateConnection(false).protocolVersion(ProtocolVersion.RESP2).build()); RedisCommands<String, String> connection = client.connect().sync(); assertThatThrownBy(connection::ping).isInstanceOf(RedisException.class) .hasMessageContaining("NOAUTH Authentication required"); assertThat(connection.auth(passwd)).isEqualTo("OK"); assertThat(connection.set(key, value)).isEqualTo("OK"); // Aut with the same user & password (default) assertThat(connection.auth(username, passwd)).isEqualTo("OK"); assertThat(connection.set(key, value)).isEqualTo("OK"); // Switch to another user assertThat(connection.auth(aclUsername, aclPasswd)).isEqualTo("OK"); assertThat(connection.set("cached:demo", value)).isEqualTo("OK"); assertThatThrownBy(() -> connection.get(key)).isInstanceOf(RedisCommandExecutionException.class); assertThat(connection.del("cached:demo")).isEqualTo(1); RedisURI redisURI = RedisURI.Builder.redis(host, port).withDatabase(2).withPassword(passwd).build(); RedisCommands<String, String> authConnection = client.connect(redisURI).sync(); authConnection.ping(); authConnection.getStatefulConnection().close(); }); }
java
16
0.644156
128
48.709677
31
inline
import datetime import unittest from datetime import timedelta from parides.converter import data_to_csv, data_from_prom, data_from_csv from unittest.mock import patch PROMETHEUS_URL = "http://192.168.42.60:9090/graph" TEST_TIME = datetime.datetime.utcnow() class ApiIntegration(unittest.TestCase): @patch('parides.prom_service.requests.get') def test_save_data_to_csv(self, mock_get): directory = 'container_metrics' dataset_id = "incident_1" f = data_to_csv(url=PROMETHEUS_URL, metrics_query="up", dataset_id=dataset_id, directory=directory, start_time=TEST_TIME - timedelta(minutes=5), end_time=TEST_TIME, resolution="15s") with open(f, 'r') as X_data: self.assertTrue('time,id,up' in X_data.read()) @patch('parides.prom_service.requests.get') def test_load_data_from_csv(self, mock_get): X = data_from_csv( directory="data", dataset_id="incident_1", ) print(X) @patch('parides.prom_service.requests.get') def test_query_resolution_can_be_changed(self, mock_get): metrics_data_high_res = \ data_from_prom(url=PROMETHEUS_URL, query="up", start_time=TEST_TIME - timedelta(minutes=5), end_time=TEST_TIME, resolution="15s") metrics_data_low_res = \ data_from_prom(url=PROMETHEUS_URL, query="up", start_time=TEST_TIME - timedelta(minutes=5), end_time=TEST_TIME, resolution="30s") self.assertLess(metrics_data_low_res['up'].sum(), metrics_data_high_res['up'].sum()) if __name__ == '__main__': unittest.main()
python
15
0.630435
107
35.212766
47
starcoderdata
/* eslint jsx-a11y/anchor-is-valid: 0 */ // --> OFF import { Modal } from "antd"; import React from "react"; import { connect } from "react-redux"; import { Link } from "react-router-dom"; import { deletePhoto, favouritePhotoAction } from "../../Redux-actions/Images"; import Loading from "../common/Loading"; import SuccessNotification from "../notification/SuccessNotification"; const confirm = Modal.confirm; function onClickFavourite(e, id, favouritePhotoAction) { e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); favouritePhotoAction({ id }); } function onClickDelete(e, id, deletePhoto) { e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); confirm({ title: "Do you Want to delete this image?", centered: true, okText: "Yes", okType: "danger", cancelText: "No", onOk() { deletePhoto({ id }).then(() => { SuccessNotification({ message: "Image deleted Successfully" }); }); }, onCancel() { return; } }); } function RenderGallery({ images, openLightbox, deletePhoto, favouritePhotoAction }) { if (!images) return <Loading />; if (images.length === 0 && !images) { return ( <div className="wrapper-withNoimages"> <div className="withNoimages"> <h1 style={{ color: "#447efd" }}>No images Uploaded <h4 className="Custom-style-no-upload"> <Link to="/upload">upload new images ); } const gallery = images.map((obj, i) => { return ( <div className="hovereffect" key={i}> <img src={obj.thumbnail} alt={obj.caption} /> <div className="overlay" onClick={e => openLightbox(i, e)}> <a className="info" onClick={e => onClickDelete(e, obj.id, deletePhoto)} style={{ marginRight: "40px" }}> <span className="fa fa-trash" /> <a className="info" style={obj.favouritePhoto ? yellowColor : whiteColor} onClick={e => onClickFavourite(e, obj.id, favouritePhotoAction)} > <span className="fa fa-star" /> ); }); return <div className="images-wrapper">{gallery} } const yellowColor = { color: "yellow" }; const whiteColor = { color: "white" }; export default connect( null, { deletePhoto, favouritePhotoAction } )(RenderGallery);
javascript
20
0.591444
117
27.629213
89
starcoderdata
public bool Equals(T[] x, T[] y) { // Null equals null, and nothing else if (x == null && y == null) return true; if (x == null || y == null) return false; // Compare arrays' lengths if (x.Length != y.Length) return false; // Compare arrays' contents for (int i = 0; i < x.Length; i++) { if ((x[i] == null && y[i] != null) || (!x[i].Equals(y[i]))) { return false; } } return true; }
c#
16
0.497768
63
21.45
20
inline
from servicelocator.lookup import service_provider from tests.integration.FileOpeners.FileOpenerService import FileOpenerService from tests.integration.MIMERecognizers.MIMERecognizerService import MIMERecognizerService #some classes can be multiple service providers @service_provider(FileOpenerService, MIMERecognizerService) class WavOpener(FileOpenerService, MIMERecognizerService): def can_open_mime_type(self, mime): return mime == "audio/wav" def open(self, file): print("opening with audio wav editor") def recognizes_extension(self, extension): return extension == ".wav" def get_MIME_type(self): return "audio/wav"
python
10
0.767407
89
36.555556
18
starcoderdata
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs { public class Pkcs12PbeParams : Asn1Encodable { private readonly DerInteger iterations; private readonly Asn1OctetString iv; public Pkcs12PbeParams( byte[] salt, int iterations) { this.iv = new DerOctetString(salt); this.iterations = new DerInteger(iterations); } private Pkcs12PbeParams( Asn1Sequence seq) { if (seq.Count != 2) throw new ArgumentException("Wrong number of elements in sequence", "seq"); iv = Asn1OctetString.GetInstance(seq[0]); iterations = DerInteger.GetInstance(seq[1]); } public static Pkcs12PbeParams GetInstance( object obj) { if (obj is Pkcs12PbeParams) { return (Pkcs12PbeParams) obj; } if (obj is Asn1Sequence) { return new Pkcs12PbeParams((Asn1Sequence) obj); } throw new ArgumentException("Unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public BigInteger Iterations { get { return iterations.Value; } } public byte[] GetIV() { return iv.GetOctets(); } public override Asn1Object ToAsn1Object() { return new DerSequence(iv, iterations); } } } #pragma warning restore #endif
c#
19
0.6
148
24.41791
67
starcoderdata
void WriteWideString(CTextBufferA &buf, va_list &param, char *&pFormat) { WriteWideStringCommon(buf, va_arg(param, const WCHAR *)); // Advance format pointer if(*(pFormat+1) == 's') { pFormat+=2; } else { pFormat++; } }
c++
11
0.533808
71
18.214286
14
inline
import { setOwner } from '@ember/application'; import { assert } from '@ember/debug'; import { toString } from './util/to-string'; import { isFunction } from './util/types'; export const setProperties = (object, hash, diff=true) => { for(let key in hash) { let value = hash[key]; if(diff && object[key] === value) { continue; } object[key] = value; } }; export default class ZugletObject { constructor(owner) { assert(`owner must be owner object`, owner && isFunction(owner.lookup)); setOwner(this, owner); } toString() { let extension; if(isFunction(this.toStringExtension)) { extension = this.toStringExtension(); } return toString(this, extension); } }
javascript
13
0.634483
76
22.387097
31
starcoderdata
package contagionJVM.Entities; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import javax.persistence.*; import java.util.List; @Entity @Table(name = "PCTerritoryFlags") public class PCTerritoryFlagEntity { @Id @Column(name = "PCTerritoryFlagID") @GeneratedValue(strategy = GenerationType.AUTO) private int pcTerritoryFlagID; @Column(name = "PlayerID") private String playerID; @Column(name = "LocationAreaTag") private String locationAreaTag; @Column(name = "LocationX") private double locationX; @Column(name = "LocationY") private double locationY; @Column(name = "LocationZ") private double locationZ; @Column(name = "LocationOrientation") private double locationOrientation; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "BuildPrivacySettingID", insertable = false) private BuildPrivacyEntity buildPrivacy; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "StructureBlueprintID") private StructureBlueprintEntity blueprint; @OneToMany(cascade = CascadeType.ALL, mappedBy = "pcTerritoryFlag", fetch = FetchType.EAGER, orphanRemoval = true) private List structures; @OneToMany(cascade = CascadeType.ALL, mappedBy = "pcTerritoryFlag", fetch = FetchType.EAGER, orphanRemoval = true) @Fetch(value = FetchMode.SUBSELECT) private List permissions; @OneToMany(cascade = CascadeType.ALL, mappedBy = "pcTerritoryFlag", fetch = FetchType.EAGER, orphanRemoval = true) @Fetch(value = FetchMode.SUBSELECT) private List constructionSites; public int getPcTerritoryFlagID() { return pcTerritoryFlagID; } public void setPcTerritoryFlagID(int pcTerritoryFlagID) { this.pcTerritoryFlagID = pcTerritoryFlagID; } public String getPlayerID() { return playerID; } public void setPlayerID(String playerID) { this.playerID = playerID; } public String getLocationAreaTag() { return locationAreaTag; } public void setLocationAreaTag(String locationAreaTag) { this.locationAreaTag = locationAreaTag; } public double getLocationX() { return locationX; } public void setLocationX(double locationX) { this.locationX = locationX; } public double getLocationY() { return locationY; } public void setLocationY(double locationY) { this.locationY = locationY; } public double getLocationZ() { return locationZ; } public void setLocationZ(double locationZ) { this.locationZ = locationZ; } public double getLocationOrientation() { return locationOrientation; } public void setLocationOrientation(double locationOrientation) { this.locationOrientation = locationOrientation; } public List getStructures() { return structures; } public void setStructures(List structures) { this.structures = structures; } public List getPermissions() { return permissions; } public void setPermissions(List permissions) { this.permissions = permissions; } public StructureBlueprintEntity getBlueprint() { return blueprint; } public void setBlueprint(StructureBlueprintEntity blueprint) { this.blueprint = blueprint; } public BuildPrivacyEntity getBuildPrivacy() { return buildPrivacy; } public void setBuildPrivacy(BuildPrivacyEntity buildPrivacy) { this.buildPrivacy = buildPrivacy; } public List getConstructionSites() { return constructionSites; } public void setConstructionSites(List constructionSites) { this.constructionSites = constructionSites; } }
java
7
0.707169
118
26.251656
151
starcoderdata
int main() { S_Trivial inVal, outVal; outVal = takeTrivial(inVal); S_NotTrivial inNotVal, outNotVal; outNotVal = takeNotTrivial(inNotVal); return 0; // Set another for return value }
c++
7
0.71134
43
16.727273
11
inline
package com.pic.lib.task; abstract public class CallBackTask extends Task { public CallBackTask(String strTaskName) { super(strTaskName); } }
java
7
0.701863
49
16.888889
9
starcoderdata
def predict(test, model, save=False): """ Make predictions on the test set with the inputted data. :param test: testing set :param model: model to make predictions :param save: save predictions to new csv :return: testing set with predictions made """ predictions = model.predict(test) preds = test.assign(Predictions=predictions) if save: preds.to_csv("preds.csv") return preds
python
9
0.675174
60
29.857143
14
inline
package repoprovider import ( "github.com/kluctl/kluctl/v2/pkg/git" git_url "github.com/kluctl/kluctl/v2/pkg/git/git-url" ) type RepoInfo struct { Url git_url.GitUrl `yaml:"url"` RemoteRefs map[string]string `yaml:"remoteRefs"` DefaultRef string `yaml:"defaultRef"` } type RepoProvider interface { GetRepoInfo(url git_url.GitUrl) (RepoInfo, error) GetClonedDir(url git_url.GitUrl, ref string) (string, git.CheckoutInfo, error) Clear() }
go
8
0.714286
79
25.055556
18
starcoderdata
public static void sumupProblems(MessageLogger logger) { if (logger.getProblems().isEmpty()) { return; } final List<String> warns = new ArrayList<>(logger.getWarns()); final List<String> errors = new ArrayList<>(logger.getErrors()); logger.info(""); // new line on info to isolate error summary if (!errors.isEmpty()) { logger.log(":: problems summary ::", Message.MSG_ERR); } else { logger.log(":: problems summary ::", Message.MSG_WARN); } if (warns.size() > 0) { logger.log(":::: WARNINGS", Message.MSG_WARN); for (String msg : warns) { logger.log("\t" + msg + "\n", Message.MSG_WARN); } } if (errors.size() > 0) { logger.log(":::: ERRORS", Message.MSG_ERR); for (String msg : errors) { logger.log("\t" + msg + "\n", Message.MSG_ERR); } } logger.info("\n:: USE VERBOSE OR DEBUG MESSAGE LEVEL FOR MORE DETAILS"); }
java
13
0.507519
80
39.961538
26
inline
def __init__(self, n_ins, hidden_layers_sizes, np_rs=None, theano_rs=None, field_importance=None, input_data=None): # set theano random state if not given if np_rs is None: np_rs = np.random.RandomState(numpy_random_seed) if theano_rs is None: theano_rs = RandomStreams(np_rs.randint(theano_random_seed)) self.theano_rs = theano_rs self.dA_layers = [] self.params = [] self.n_layers = len(hidden_layers_sizes) assert self.n_layers > 0 if input_data is None: input_data = T.matrix(name='input_data') self.x = input_data outputs = [] for i in range(self.n_layers): if i == 0: layer_input = self.x dA_layer = dA( n_visible=n_ins, n_hidden=hidden_layers_sizes[i], np_rs=np_rs, theano_rs=theano_rs, field_importance=field_importance, input_data=layer_input, ) else: layer_input = outputs[-1] dA_layer = dA( n_visible=hidden_layers_sizes[i - 1], n_hidden=hidden_layers_sizes[i], np_rs=np_rs, theano_rs=theano_rs, input_data=layer_input ) # ipdb.set_trace() outputs.append(dA_layer.get_hidden_values(layer_input)) self.dA_layers.append(dA_layer) self.params.extend(dA_layer.params)
python
15
0.480958
72
38.731707
41
inline
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading.Tasks; using NuGet.Services.Metadata.Catalog.Monitoring; using Xunit; namespace NgTests { public class ValidatorTests { [Fact] public async Task Run_ReturnsPass() { // Arrange Func shouldRun = () => true; Action runInternal = () => { }; var validator = new TestableValidator(shouldRun, runInternal); var context = new ValidationContext(); // Act var result = await validator.ValidateAsync(context); // Assert Assert.Same(validator, result.Validator); Assert.Equal(TestResult.Pass, result.Result); Assert.Null(result.Exception); } [Fact] public async Task Run_ReturnsSkip() { // Arrange Func shouldRun = () => false; Action runInternal = () => { }; var validator = new TestableValidator(shouldRun, runInternal); var context = new ValidationContext(); // Act var result = await validator.ValidateAsync(context); // Assert Assert.Same(validator, result.Validator); Assert.Equal(TestResult.Skip, result.Result); Assert.Null(result.Exception); } [Fact] public async Task Run_ReturnsFail() { // Arrange var exception = new Exception(); Func shouldRun = () => true; Action runInternal = () => { throw exception; }; var validator = new TestableValidator(shouldRun, runInternal); var context = new ValidationContext(); // Act var result = await validator.ValidateAsync(context); // Assert Assert.Same(validator, result.Validator); Assert.Equal(TestResult.Fail, result.Result); Assert.Same(exception, result.Exception); } } public class TestableValidator : Validator { public TestableValidator(Func shouldRun, Action runInternal) { _shouldRun = shouldRun; _runInternal = runInternal; } protected override Task ShouldRunAsync(ValidationContext context) { return Task.FromResult(_shouldRun()); } protected override Task RunInternalAsync(ValidationContext context) { _runInternal(); return Task.FromResult(0); } private Func _shouldRun; private Action _runInternal; } }
c#
15
0.571377
111
27.242424
99
starcoderdata
#pragma once #include #include #include namespace sviper { /*! Assigns a variant the average of identity and fuzzyness score. * Based on the polsihed sequence alignment given in record * @param record The alignment record containing the alignment of the polished * sequence to the reference. * @param variant The variant to be scored (Quality member will be replaced). */ void assign_quality(seqan::BamAlignmentRecord & record, Variant & variant, SViperConfig const & config) { // Score computation // ----------------- double error_rate = ((double)length(record.cigar) - 1.0)/ (config.flanking_region * 2.0); double fuzzyness = (1.0 - error_rate/0.15) * 100.0; variant.quality = std::max(fuzzyness, 0.0); record.mapQ = variant.quality; } } // namespace sviper
c
14
0.665608
93
30.5
30
starcoderdata
package patrick.array.duplicates; /** EASY */ /* Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Example 1: Given nums = [1,1,2], Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the returned length. 题意: 1. 统计给定有序数组的唯一值的长度,相同值只能存在一个 前提: 1. 给定数组是有顺序的 2. 不能使用额外的空间,也就是不能借助新的数组 3. 只能迭代一次 2. 统计不重复的数组length 思路: 1. 因为数组是有序的 2. 2个指针思路 -> 指针j用来迭代数组,从1开始 指针i用来记录前一个数组位置,从0开始 (也用来记录值不重复的数组长度) 3. 迭代开始 当j val != i val, i++, 同时nums[i]=nums[j] -> 目的:当i和j中间差>=2时,下一轮j+1不需要和原来的i比较,应与前面一个值(也就是j)比较 改进: 1。下题算法也可以适用本题 */ public class ARemoveDuplicate { public static void main(String[] args) { ARemoveDuplicate removeDuplicate = new ARemoveDuplicate(); System.out.println("new length="+removeDuplicate.removeDuplicates(new int[]{1, 1, 1, 2, 3, 5, 5, 5})); System.out.println("new length="+removeDuplicate.removeDupliates02(new int[]{1, 1, 1, 2, 3, 5,5},1)); } //就是下一题(BRemoveDuplicate2.java) 的解法 public int removeDupliates02(int[] nums, int allow_dup){ int j=1; int count=1; for(int i =1;i<nums.length;i++){ if(nums[i]==nums[i-1]){ count++; }else{ count = 1; } if(count<=allow_dup){ //1;可设置,指可允许相同数字在数组中出现的次数 j++; } } return j; } public int removeDuplicates(int[] nums) { if (nums.length == 0) return 0; int i = 0; //用于统计个数 for (int j = 1; j < nums.length; j++) { if (nums[j] != nums[i]) { i++; //下面这行代码,用于解决当前面N个数字都是一样的情况,即如:1,1,1, 2,3,5,5 //如果没有下面这行,结果是5,而不是4 nums[i] = nums[j]; //目的:当i和j中间差>=2时,下一轮j+1不需要和原来的i比较,应与前面一个值(也就是j)比较 } } //Arrays.stream(nums).forEach(System.out::println); return i + 1; } }
java
13
0.582238
110
27.294872
78
starcoderdata
package com.xdidian.keryhu.personal_menu.service; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.xdidian.keryhu.personal_menu.client.UserClient; import com.xdidian.keryhu.personal_menu.domain.MenuDto; import com.xdidian.keryhu.personal_menu.domain.MenuType; import com.xdidian.keryhu.personal_menu.repository.MenuRepository; import com.xdidian.keryhu.util.SecurityUtils; import lombok.RequiredArgsConstructor; @Component("menuService") @RequiredArgsConstructor(onConstructor = @__(@Autowired)) public class MenuServiceImpl implements MenuService { private final UserClient userClient; private final MenuRepository repository; @Override public List getMenu(String userId) { // TODO Auto-generated method stub // 当前用户的权限。 Collection authorities = SecurityUtils.getAuthorities(); boolean isInCompany = userClient.isInComopany(userId); boolean defaultMenu = repository.findByUserId(userId).map(e -> e.isDefaultMenus()).orElse(true); List dto = new ArrayList // 如果未加入任何公司,那么就返回这3个。 if (!isInCompany) { dto.add(new MenuDto(MenuType.NEW_COMPANY.getName(), MenuType.NEW_COMPANY.getUrl())); dto.add(new MenuDto(MenuType.JOIN_COMPANY.getName(), MenuType.JOIN_COMPANY.getUrl())); dto.add(new MenuDto(MenuType.PERSONAL_INFO.getName(), MenuType.PERSONAL_INFO.getUrl())); return dto; } // 如果用户的权限 是 公司的 管理员,则含有所有的 默认菜单,,不是 else if (authorities.contains("ROLE_COMPANY_ADMIN")) { for (MenuType m : MenuType.values()) { dto.add(new MenuDto(m.getName(), m.getUrl())); } return dto; // 当用户的菜单是默认菜单, } else if (defaultMenu) { dto.add(new MenuDto(MenuType.HOME.getName(), MenuType.HOME.getUrl())); dto.add(new MenuDto(MenuType.COMPANY_INFO.getName(), MenuType.COMPANY_INFO.getUrl())); dto.add(new MenuDto(MenuType.CAREER_PLANNING.getName(), MenuType.CAREER_PLANNING.getUrl())); dto.add(new MenuDto(MenuType.PERFORMANCE_APPRAISAL.getName(), MenuType.PERFORMANCE_APPRAISAL.getUrl())); dto.add( new MenuDto(MenuType.ATTENDANCE_SALARY.getName(), MenuType.ATTENDANCE_SALARY.getUrl())); dto.add( new MenuDto(MenuType.RELEASE_MANAGEMENT.getName(), MenuType.RELEASE_MANAGEMENT.getUrl())); dto.add(new MenuDto(MenuType.REPORT_TRAINING.getName(), MenuType.REPORT_TRAINING.getUrl())); dto.add(new MenuDto(MenuType.INNOVATION_SUGGESTIONS.getName(), MenuType.INNOVATION_SUGGESTIONS.getUrl())); dto.add(new MenuDto(MenuType.PERSONAL_INFO.getName(), MenuType.PERSONAL_INFO.getUrl())); return dto; } // 自定义菜单。 else if (!defaultMenu) { List t = repository.findByUserId(userId).map(e -> e.getMenuTypes()).get(); return t.stream().map(e->new MenuDto(e.getName(),e.getUrl())) .collect(Collectors.toList()); } return null; } }
java
19
0.717134
110
38.62963
81
starcoderdata
void dynamicTW_setup(void){ /*class_new(t_symbol *name, t_newmethod newmethod, t_method freemethod, size_t size, int flags, t_atomtype arg1, ...); */ dynamicTW_class = class_new(gensym("dynamicTW"), //defines the symbol in puredata (t_newmethod)dynamicTW_new, //inializing method 0, sizeof(t_dynamicTW), CLASS_DEFAULT,//makes the box A_DEFFLOAT, A_DEFFLOAT, 0); class_addbang(dynamicTW_class, (t_method)dtw_onBangMsg); class_addmethod(dynamicTW_class, (t_method)dtw_onSet_A, gensym("ratio_A"), A_DEFFLOAT, 0); class_addmethod(dynamicTW_class, (t_method)dtw_onSet_B, gensym("ratio_B"), A_DEFFLOAT, 0); }
c++
10
0.466387
85
40.434783
23
inline
private static CallableDefinition makeOliveDefinition(ObjectNode node) { return new CallableDefinition() { final boolean isRoot = node.get("isRoot").asBoolean(); final String name = node.get("name").asText(); final String format = node.get("format").asText(); final List<Imyhat> parameters = Utils.stream(node.get("parameters").elements()) .map(parameter -> Imyhat.parse(parameter.asText())) .collect(Collectors.toList()); final List<Target> output = Utils.stream(node.get("output").fields()) .map( output -> new Target() { private final String name = output.getKey(); private final Imyhat type = Imyhat.parse(output.getValue().asText()); @Override public Flavour flavour() { return Flavour.STREAM; } @Override public String name() { return name; } @Override public void read() { // Don't care. } @Override public Imyhat type() { return type; } }) .collect(Collectors.toList()); @Override public void collectSignables( Set<String> signableNames, Consumer<SignableVariableCheck> addSignableCheck) { // Pretend like there's none, since we can't know. } @Override public Stream<OliveClauseRow> dashboardInner(Optional<String> label, int line, int column) { return Stream.empty(); } @Override public Path filename() { return null; } @Override public String format() { return format; } @Override public boolean isRoot() { return isRoot; } @Override public String name() { return name; } @Override public Optional<Stream<Target>> outputStreamVariables( OliveCompilerServices oliveCompilerServices, Consumer<String> errorHandler) { return Optional.of(output.stream()); } @Override public int parameterCount() { return parameters.size(); } @Override public Imyhat parameterType(int index) { return parameters.get(index); } }; }
java
21
0.497696
98
28.942529
87
inline
import sys N = int(sys.stdin.readline().rstrip()) S = 0 for num in range(1, N+1): f = num%5 == 0 or num%3==0 or num%15==0 if not f: S+=num print(S)
python
10
0.520231
43
16.4
10
codenet
using Android.OS; using Android.Support.V7.Widget; using Android.Views; using System; using System.IO; namespace TSGPDic { public class Main_DicFragment : Android.Support.V4.App.Fragment { private View v; private CardView MusicDBView; private CardView CharacterDBView; public override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your fragment here } public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Use this to return your custom view for this Fragment // return inflater.Inflate(Resource.Layout.YourFragment, container, false); v = inflater.Inflate(Resource.Layout.Main_DicLayout, container, false); MusicDBView = v.FindViewById MusicDBView.Click += CardView_Click; CharacterDBView = v.FindViewById CharacterDBView.Click += CardView_Click; return v; } private void CardView_Click(object sender, EventArgs e) { CardView cv = sender as CardView; try { switch (cv.Id) { case Resource.Id.Main_Dic_MusicDBCardView: ETC.LoadDBSync(ETC.MusicList, Path.Combine(ETC.DBPath, "Song.tsgp"), true); Activity.StartActivity(typeof(Dic_MusicMain)); Activity.OverridePendingTransition(Android.Resource.Animation.FadeIn, Android.Resource.Animation.FadeOut); break; case Resource.Id.Main_Dic_CharacterDBCardView: ETC.LoadDBSync(ETC.CharacterList, Path.Combine(ETC.DBPath, "Character.tsgp"), true); Activity.StartActivity(typeof(Dic_StarMain)); Activity.OverridePendingTransition(Android.Resource.Animation.FadeIn, Android.Resource.Animation.FadeOut); break; } } catch (Exception ex) { ETC.LogError(Activity, ex.ToString()); } } } }
c#
20
0.592055
130
35.59375
64
starcoderdata
<?php namespace common\tests; use Yii; use Swift_Message; use common\models\User; use common\models\MailQueue; use common\components\helpers\EmailHelper; /** * Inherited Methods * @method void wantToTest($text) * @method void wantTo($text) * @method void execute($callable) * @method void expectTo($prediction) * @method void expect($prediction) * @method void amGoingTo($argumentation) * @method void am($role) * @method void lookForwardTo($achieveValue) * @method void comment($description) * @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL) * * @SuppressWarnings(PHPMD) */ class UnitTester extends \Codeception\Actor { use _generated\UnitTesterActions; use \Codeception\Specify; /** * Checks mention result items schema. * @see `Project::findAllCommenters()` * @param array $result */ public function checkMentionResultItems(array $result) { // check result item fields foreach ($result as $item) { verify('Each result item should have an email key', $item)->hasKey('email'); verify('Each result item should have a firstName key', $item)->hasKey('firstName'); verify('Each result item should have a lastName key', $item)->hasKey('lastName'); verify('Each result item should have a userId key', $item)->hasKey('userId'); // if the user is guest $user = User::findOne(['email' => $item['email']]); if (!$user) { verify('userId should not be set for guests', $item['userId'])->null(); } else { verify('userId should match with the user one', $item['userId'])->equals($user['id']); verify('firstName should match with the user one', $item['firstName'])->equals($user['firstName']); verify('lastName should match with the user one', $item['lastName'])->equals($user['lastName']); } } } /** * Checks whether an email message has valid mail queue data. * @param MailQueue $model MailQueue model to check * @param Swift_Message $message Message instance */ public function checkMailQueueMessage(MailQueue $model, Swift_Message $message) { $to = EmailHelper::stringToArray($model->to); $from = EmailHelper::stringToArray($model->from); $cc = EmailHelper::stringToArray($model->cc); $bcc = EmailHelper::stringToArray($model->bcc); foreach ($to as $email => $name) { verify('Mail sender should match', $message->getTo())->hasKey($email); verify('Mail sender name should match', $message->getTo()[$email])->equals($name); } if (!$from) { verify('Mail sender should match', $message->getFrom())->hasKey(Yii::$app->params['noreplyEmail']); verify('Mail sender name should match', $message->getFrom()[Yii::$app->params['noreplyEmail']])->equals('Presentator'); } else { foreach ($from as $email => $name) { verify('Mail sender should match', $message->getFrom())->hasKey($email); verify('Mail sender name should match', $message->getFrom()[$email])->equals($name); } } if (!$cc) { verify('Mail cc should not be set', $message->getCc())->isEmpty(); } else { foreach ($cc as $email => $name) { verify('Mail cc should match', $message->getCc())->hasKey($email); verify('Mail cc name should match', $message->getCc()[$email])->equals($name); } } if (!$bcc) { verify('Mail bcc should not be set', $message->getBcc())->isEmpty(); } else { foreach ($bcc as $email => $name) { verify('Mail bcc should match', $message->getBcc())->hasKey($email); verify('Mail bcc name should match', $message->getBcc()[$email])->equals($name); } } verify('Mail subject should match', $message->getSubject())->equals($model->subject); $body = $message->getBody(); $bodyChildren = $message->getChildren(); if (empty($body) && !empty($bodyChildren)) { $parts = []; foreach ($bodyChildren as $child) { $parts[$child->getContentType()] = $child->getBody(); } if (!empty($parts['text/html'])) { $body = $parts['text/html']; } elseif (!empty($parts['text/plain'])) { $body = $parts['text/plain']; } } verify('Mail body should match', $body)->equals($model->body); } }
php
18
0.573083
131
37.918033
122
starcoderdata
#include #include #include "voxcgeomConfig.h" #include "voxcgeom/math/Vec3D.h" #include "voxcgeom/math/Matrix4.h" #include "voxcgeom/base/AABB.h" #include "voxcgeom/base/Sphere.h" #include "voxcgeom/base/StraightLine.h" #include "voxcgeom/base/RadialLine.h" #include "voxcgeom/base/LineSegment.h" #include "voxcgeom/base/Plane.h" #include "voxcgeom/base/Cone.h" #include "voxcgeom/calc/PlaneCalc.h" ////////////////////////////////////////////////////////////// /// /// demo /// /// ///////////////////////////////////////////////////////// #include "../demo/math/MatrixComputer.h" void testCone() { Vec3D outPv; Cone pcone; pcone.position.setXYZ(0.0f, 200.0f, 0.0f); pcone.tv.setXYZ(0.0f, -1.0f, 0.0f); pcone.height = 210.0f; pcone.radius = 100.0f; Vec3D innerPv(-7.5f, 187.0f, -25.98f); pcone.tv.copyFrom(innerPv); pcone.tv.subtractBy(pcone.position); pcone.update(); pcone.tv.coutThis(); std::cout << "pcone.getHalfAngleCos: " << pcone.getHalfAngleCos() << std::endl; bool boo0 = pcone.containsPosition(outPv); std::cout << "pcone.containsPosition(): " << boo0 << std::endl; Vec3D pa, nearV0, nearV1; pa.copyFrom(pcone.position); Vec3D pb(100.0f, -30.0f, -340.0f); Vec3D dv(-50.0f, 41.072f, -50.0f); pa.addBy(dv); pb.addBy(dv); Vec3D tv; tv.copyFrom(pb); tv.subtractBy(pa); tv.normalize(); pb.x = pa.x + tv.x * 700.0f; pb.y = pa.y + tv.y * 700.0f; pb.z = pa.z + tv.z * 700.0f; pa.x += tv.x * -300.0f; pa.y += tv.y * -300.0f; pa.z += tv.z * -300.0f; bool boo1 = pcone.intersectionSL(pa, tv, nearV0, nearV1); std::cout << "pcone.intersectionSL(): " << boo1 << std::endl; } void testSimple() { Vec3D va{ 1.1f,2.1f,3.3f,4.5f }; va.coutThis(); AABB ab0{ Vec3D{10.0f,10.0f,10.0f}, Vec3D{110.0f,110.0f,110.0f} }; AABB ab1{ Vec3D{-30.0f,-30.0f,-30.0f}, Vec3D{-110.0f,-110.0f,-110.0f} }; bool boo = ab0.intersect(ab1); std::cout << "boo: " << boo << std::endl; std::cout << std::setiosflags(std::ios::fixed); std::cout << std::setprecision(10) << VCG_MATH_PI << std::endl; VCG_Number degree = Vec3D::DegreeBetween(Vec3D::X_AXIS, Vec3D::Y_AXIS); std::cout << "degree: " << degree << std::endl; Sphere sph; std::cout << "Sphere::uid: " << sph.uid << std::endl; } void testMatrix4() { int setprecisionSize = 6; std::cout << std::setiosflags(std::ios::fixed); std::cout << std::setprecision(setprecisionSize) << "testMatrix4" << std::endl; Matrix4 mat4A; mat4A.identity(); mat4A.setScaleXYZ(10.0f,4.5f,2.1f); mat4A.setRotationEulerAngle(30.0f,20.0f,80.0f); mat4A.setTranslationXYZ(30.0f,20.0f,80.0f); mat4A.coutThis(); mat4A.pointAt(Vec3D(), Vec3D(0.0f,0.0f,100.0f), Vec3D(0.0f,1.0f,0.0f)); std::cout << "mat4A.pointAt: " << std::endl; mat4A.coutThis(); } void testMathDemo() { Matrix4 mat4A; mat4A.identity(); mat4A.setScaleXYZ(10.0f, 4.5f, 2.1f); mat4A.setRotationEulerAngle(30.0f, 20.0f, 80.0f); mat4A.setTranslationXYZ(30.0f, 20.0f, 80.0f); mat4A.coutThis(); unsigned int index = 0; ///* MatrixComputer matCompter; matCompter.allocate(16); matCompter.setScaleXYZParamAt(10.0f, 4.5f, 2.1f, index); matCompter.setRotationEulerAngleParamAt(30.0f, 20.0f, 80.0f, index); matCompter.setTranslationXYZParamAt(30.0f, 20.0f, 80.0f, index); index++; matCompter.setScaleXYZParamAt(10.0f, 4.5f, 2.1f, index); matCompter.setRotationEulerAngleParamAt(30.0f, 20.0f, 80.0f, index); matCompter.setTranslationXYZParamAt(30.0f, 20.0f, 80.0f, index); matCompter.calc(2); //matCompter.identityAt(0); std::cout << "----------- ------ ----------------- ----" << std::endl; matCompter.coutThisMatAt(0); matCompter.coutThisMatAt(1); matCompter.coutThis(); //*/ } int main (int argc, char *argv[]) { // testSimple(); // testCone(); // testMatrix4(); testMathDemo(); // std::cout<< std::setiosflags(std::ios::fixed); // std::cout<< std::setprecision(20) << VCG_MATH_PI << std::endl; // std::cout<<"boxcgeom init...\n"; // std::cout<< VCG_MATH_PI<<std::endl; // std::cout<<"180.0f/VCG_MATH_PI: "<< 180.0f/VCG_MATH_PI<<std::endl; // std::cout<<"VCG_MATH_PI/180.0f: "<< VCG_MATH_PI/180.0f<<std::endl; return 0; }
c++
9
0.597052
83
30.733813
139
starcoderdata
func Get() *Config { configLock.Lock() defer configLock.Unlock() if config == nil { var path = "" if *disableConfig { // don't set config path } else if *configPath != "" { // set custom config path path = *configPath } else { // use default config path u, err := user.Current() handle(err, "could not get current user") path = filepath.Join(u.HomeDir, CONFIG_FILENAME) err = os.MkdirAll(filepath.Dir(path), 0777) handle(err, "could not create parent directories of config file") } config = newConfig(path) } return config }
go
14
0.642361
68
18.233333
30
inline
<?php date_default_timezone_set('Asia/Ho_Chi_Minh'); return [ 'appName' => 'Funny Bet', 'startingMoney' => 500, 'adminEmail' => ' ];
php
6
0.584416
46
21
7
starcoderdata
from django.db import models from django.utils.text import slugify from taggit.managers import TaggableManager from authors.apps.authentication.models import User from authors.apps.core.models import TimestampMixin from cloudinary.models import CloudinaryField from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import (GenericForeignKey, GenericRelation) from django.db.models import Sum class ReactionManager(models.Manager): """ The class enables article likes and dislikes set to be managed separately. """ use_related_fields = True def likes(self): """fetches reactions with a value greater than zero""" return self.get_queryset().filter(reaction__gt=0) def dislikes(self): """fetches reactions with a value less than zero""" return self.get_queryset().filter(reaction__lt=0) def sum_rating(self): """returns the sum of reaction items""" return self.get_queryset().aggregate( Sum('reaction')).get('reaction__sum') or 0 class Reaction(models.Model): LIKE = 1 DISLIKE = -1 """ reactions set contains either a like a dislike """ REACTIONS = ( (LIKE, 'like'), (DISLIKE, 'dislike') ) """ reaction field can be set to a like or dislike """ reaction = models.SmallIntegerField(choices=REACTIONS) user = models.ForeignKey(User, on_delete=models.CASCADE) """ defines the type of related object """ content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) """ defines the object id for the related object """ object_id = models.PositiveSmallIntegerField() """ provides generic foreign key using content_type and object_id """ content_object = GenericForeignKey() objects = ReactionManager() class Article(TimestampMixin, models.Model): """ Model representation of an article """ slug = models.SlugField( db_index=True, max_length=1000, unique=True, blank=True) title = models.CharField(max_length=500, blank=False) description = models.CharField(max_length=1000, blank=False) body = models.TextField(blank=False) image = CloudinaryField(blank=True, null=True) tagList = TaggableManager() author = models.ForeignKey(User, related_name='article', on_delete=models.CASCADE) reaction = GenericRelation(Reaction, related_query_name='article') def __str__(self): return self.title def generate_slug(self): """ Generates a slug for article title Example: "Me is a me" is converted to "me-is-a-me" """ slug = slugify(self.title) new_slug = slug n = 1 while Article.objects.filter(slug=new_slug).exists(): """increment slug value by one if already exists""" new_slug = '{}-{}'.format(slug, n) n += 1 return new_slug def save(self, *args, **kwargs): """ Create article and save to db """ if not self.slug: self.slug = self.generate_slug() super().save(*args, **kwargs)
python
14
0.636364
78
32.22449
98
starcoderdata
<?php namespace App\Http\Controllers; use Exception; use Illuminate\Http\Request; use App\Http\Requests; use Illuminate\Support\Facades\Response; class SubdivisionController extends Controller { /** * Get subdivisions for a country * @param $country * @return mixed */ public function show($country) { try { $subdivisions = subdivisions($country); } catch (Exception $e) { return Response::json([ 'error' => $e->getMessage(), ], 422); } return Response::json([ 'subdivisions' => $subdivisions, ], 200); } }
php
16
0.562883
51
19.375
32
starcoderdata
public void addExp(int add) { float calc = 0; Exp = Exp + add; System.out.println(add + " Exp gained!"); System.out.println("======================="); //lvl array holds current exp path to next level if(Exp > reachExp) { System.out.println("Level up!"); lvlUp(); reachExp = (int) (reachExp * 1.54321); calc = ((float)Exp/reachExp)*100; System.out.println("Progress: " + Exp + " / " +reachExp + " = " + (int)calc + "%" + " Complete! "); System.out.println(""); while(Exp > reachExp) { System.out.println("Level up!"); lvlUp(); reachExp = (int) (reachExp * 1.54321); System.out.println("Progress: " + Exp + " / " + reachExp + " = " + (int)calc + "%" + " Complete! "); System.out.println(""); } } else{ calc = ((float)Exp/reachExp)*100; System.out.println("Progress: " + Exp + " / " + reachExp + " = " + (int)calc + "%" + " Complete! "); } }
java
18
0.515789
104
24.702703
37
inline
from grobid_superconductors.material_parser.material2class import Material2Tags class TestMaterial2Tags: def test_material2Tags_Oxide(self): target = Material2Tags() taxonomy = target.get_classes("LaFeO2") assert len(taxonomy.keys()) == 1 assert list(taxonomy.keys())[0] == 'Oxides' assert len(taxonomy['Oxides']) == 1 assert taxonomy['Oxides'][0] == 'Transition Metal-Oxides' def test_material2Tags_Alloys(self): target = Material2Tags() taxonomy = target.get_classes("SrFeCu0.2") assert len(taxonomy.keys()) == 1 assert list(taxonomy.keys())[0] == 'Alloys' assert len(taxonomy['Alloys']) == 0 def test_material2Tags_mixedCombinations_0(self): target = Material2Tags() taxonomy = target.get_classes("CuFrO2") assert len(taxonomy.keys()) == 2 first_level = sorted(list(taxonomy.keys())) assert first_level[0] == 'Cuprates' assert first_level[1] == 'Oxides' assert len(taxonomy['Oxides']) == 1 assert len(taxonomy['Cuprates']) == 0 def test_material2Tags_mixedCombinations_1(self): target = Material2Tags() taxonomy = target.get_classes("CuFrO2C") assert len(taxonomy.keys()) == 3 first_level = sorted(list(taxonomy.keys())) assert first_level[0] == 'Carbides' assert first_level[1] == 'Cuprates' assert first_level[2] == 'Oxides' assert len(taxonomy['Carbides']) == 1 assert len(taxonomy['Cuprates']) == 0 assert len(taxonomy['Oxides']) == 1 def test_material2Tags_mixedCombinations_2(self): target = Material2Tags() taxonomy = target.get_classes("CuFrO2H") assert len(taxonomy.keys()) == 3 first_level = sorted(list(taxonomy.keys())) assert first_level[0] == 'Cuprates' assert first_level[1] == 'Hydrides' assert first_level[2] == 'Oxides' assert len(taxonomy['Cuprates']) == 0 assert len(taxonomy['Hydrides']) == 0 assert len(taxonomy['Oxides']) == 1 def test_material2Tags_mixedCombinations_3(self): target = Material2Tags() taxonomy = target.get_classes("CuFrO2CH") assert len(taxonomy.keys()) == 4 first_level = sorted(list(taxonomy.keys())) assert first_level[0] == 'Carbides' assert first_level[1] == 'Cuprates' assert first_level[2] == 'Hydrides' assert first_level[3] == 'Oxides' assert len(taxonomy['Cuprates']) == 0 assert len(taxonomy['Carbides']) == 1 assert len(taxonomy['Hydrides']) == 0 assert len(taxonomy['Oxides']) == 1 def test_material2Tags_mixedCombinations(self): target = Material2Tags() taxonomy = target.get_classes("CsFe2As2") assert len(taxonomy.keys()) == 2 first_level = sorted(list(taxonomy.keys())) assert first_level[0] == 'Iron-pnictides' assert first_level[1] == 'Pnictides' assert len(taxonomy['Iron-pnictides']) == 0 assert len(taxonomy['Pnictides']) == 0
python
13
0.609934
80
35.333333
87
starcoderdata
/** * @class Ext.chart.series.sprite.Pie3DPart * @extend Ext.draw.sprite.Path * @alias sprite.pie3dpart * Pie3D series sprite. */ /** * @cfg {Number} [centerX=0] * The central point of the series on the x-axis. */ /** * @cfg {Number} [centerY=0] * The central point of the series on the x-axis. */ /** * @cfg {Number} [startAngle=0] * The starting angle of the polar series. */ /** * @cfg {Number} [endAngle=Math.PI] * The ending angle of the polar series. */ /** * @cfg {Number} [startRho=0] * The starting radius of the polar series. */ /** * @cfg {Number} [endRho=150] * The ending radius of the polar series. */ /** * @cfg {Number} [margin=0] * Margin from the center of the pie. Used for donut. */ /** * @cfg {Number} [thickness=0] * The thickness of the 3D pie part. */ /** * @cfg {Number} [bevelWidth=5] * The size of the 3D pie bevel. */ /** * @cfg {Number} [distortion=0] * The distortion of the 3D pie part. */ /** * @cfg {Object} [baseColor='white'] * The color of the 3D pie part before adding the 3D effect. */ /** * @cfg {Number} [colorSpread=1] * An attribute used to control how flat the gradient of the sprite looks. * A value of 0 essentially means no gradient (flat color). */ /** * @cfg {Number} [baseRotation=0] * The starting rotation of the polar series. */ /** * @cfg {String} [part='top'] * The part of the 3D Pie represented by the sprite. */ /** * @cfg {String} [label=''] * The label associated with the 'top' part of the sprite. */
javascript
3
0.62701
74
17.73494
83
starcoderdata
/** * Copyright 2019 The JoyQueue Authors. * * 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 io.chubao.joyqueue.client.internal.cluster; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import io.chubao.joyqueue.client.internal.cluster.domain.TopicMetadataHolder; import io.chubao.joyqueue.client.internal.metadata.MetadataManager; import io.chubao.joyqueue.client.internal.metadata.domain.TopicMetadata; import io.chubao.joyqueue.client.internal.nameserver.NameServerConfig; import io.chubao.joyqueue.client.internal.nameserver.NameServerConfigChecker; import com.google.common.base.Preconditions; import io.chubao.joyqueue.toolkit.service.Service; import org.apache.commons.collections.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.Map; /** * ClusterManager * * author: gaohaoxiang * date: 2018/11/28 */ public class ClusterManager extends Service { protected static final Logger logger = LoggerFactory.getLogger(ClusterManager.class); private NameServerConfig config; private ClusterClientManager clusterClientManager; private MetadataManager metadataManager; private MetadataCacheManager metadataCacheManager; private MetadataUpdater metadataUpdater; public ClusterManager(NameServerConfig config, ClusterClientManager clusterClientManager) { NameServerConfigChecker.check(config); Preconditions.checkArgument(clusterClientManager != null, "clusterClientManager can not be null"); this.config = config; this.clusterClientManager = clusterClientManager; } public List fetchTopicMetadataList(List topics, String app) { Map<String, TopicMetadata> topicMetadataMap = fetchTopicMetadata(topics, app); List result = Lists.newArrayListWithCapacity(topicMetadataMap.size()); for (Map.Entry<String, TopicMetadata> entry : topicMetadataMap.entrySet()) { TopicMetadata topicMetadata = entry.getValue(); if (topicMetadata != null) { result.add(topicMetadata); } } return result; } public Map<String, TopicMetadata> fetchTopicMetadata(List topics, String app) { Map<String, TopicMetadata> result = Maps.newLinkedHashMap(); List needUpdateTopics = null; for (String topic : topics) { TopicMetadataHolder topicMetadataHolder = metadataCacheManager.getTopicMetadata(topic, app); if (topicMetadataHolder != null) { if (topicMetadataHolder.isExpired()) { metadataUpdater.tryUpdateTopicMetadata(topic, app); } result.put(topic, topicMetadataHolder.getTopicMetadata()); } else { if (needUpdateTopics == null) { needUpdateTopics = Lists.newLinkedList(); } needUpdateTopics.add(topic); } } if (CollectionUtils.isNotEmpty(needUpdateTopics)) { Map<String, TopicMetadata> topicMetadataMap = metadataUpdater.updateTopicMetadata(topics, app); result.putAll(topicMetadataMap); } return result; } public TopicMetadata fetchTopicMetadata(String topic, String app) { TopicMetadataHolder topicMetadataHolder = metadataCacheManager.getTopicMetadata(topic, app); if (topicMetadataHolder == null) { return metadataUpdater.updateTopicMetadata(topic, app); } if (topicMetadataHolder.isExpired()) { metadataUpdater.tryUpdateTopicMetadata(topic, app); } return topicMetadataHolder.getTopicMetadata(); } public boolean tryUpdateTopicMetadata(String topic, String app) { TopicMetadataHolder topicMetadataHolder = metadataCacheManager.getTopicMetadata(topic, app); if (topicMetadataHolder != null && !topicMetadataHolder.isExpired(config.getTempMetadataInterval())) { return false; } return metadataUpdater.tryUpdateTopicMetadata(topic, app); } public TopicMetadata updateTopicMetadata(String topic, String app) { TopicMetadataHolder topicMetadataHolder = metadataCacheManager.getTopicMetadata(topic, app); if (topicMetadataHolder != null && !topicMetadataHolder.isExpired(config.getTempMetadataInterval())) { return topicMetadataHolder.getTopicMetadata(); } return metadataUpdater.updateTopicMetadata(topic, app); } public TopicMetadata forceUpdateTopicMetadata(String topic, String app) { return metadataUpdater.updateTopicMetadata(topic, app); } public Map<String, TopicMetadata> forceUpdateTopicMetadata(List topics, String app) { return metadataUpdater.updateTopicMetadata(topics, app); } @Override protected void validate() throws Exception { metadataCacheManager = new MetadataCacheManager(config); metadataManager = new MetadataManager(clusterClientManager); metadataUpdater = new MetadataUpdater(config, metadataManager, metadataCacheManager); } @Override protected void doStart() throws Exception { metadataUpdater.start(); // logger.info("clusterManager is started"); } @Override protected void doStop() { if (metadataUpdater != null) { metadataUpdater.stop(); } // logger.info("clusterManager is stopped"); } }
java
15
0.70937
134
38.685897
156
starcoderdata
ConvexVsMeshOverlapCallback( const ConvexMesh& cm, const PxMeshScale& convexScale, const FastVertex2ShapeScaling& meshScale, const PxTransform& tr0, const PxTransform& tr1, bool identityScale, const Box& meshSpaceOBB) : MeshHitCallback<PxRaycastHit>(CallbackMode::eMULTIPLE), mAnyHit (false), mIdentityScale (identityScale) { if (!mIdentityScale) // not done in initializer list for performance mMeshScale = Ps::aos::Mat33V( V3LoadU(meshScale.getVertex2ShapeSkew().column0), V3LoadU(meshScale.getVertex2ShapeSkew().column1), V3LoadU(meshScale.getVertex2ShapeSkew().column2) ); using namespace Ps::aos; const ConvexHullData* hullData = &cm.getHull(); const Vec3V vScale0 = V3LoadU_SafeReadW(convexScale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale const QuatV vQuat0 = QuatVLoadU(&convexScale.rotation.x); mConvex = ConvexHullV(hullData, V3Zero(), vScale0, vQuat0, convexScale.isIdentity()); aToB = PsMatTransformV(tr0.transformInv(tr1)); mIdentityScale = identityScale; { // Move to AABB space Matrix34 MeshToBox; computeWorldToBoxMatrix(MeshToBox, meshSpaceOBB); const Vec3V base0 = V3LoadU(MeshToBox.m.column0); const Vec3V base1 = V3LoadU(MeshToBox.m.column1); const Vec3V base2 = V3LoadU(MeshToBox.m.column2); const Mat33V matV(base0, base1, base2); const Vec3V p = V3LoadU(MeshToBox.p); MeshToBoxV = PsMatTransformV(p, matV); boxExtents = V3LoadU(meshSpaceOBB.extents+PxVec3(0.001f)); } }
c++
13
0.744048
123
37.794872
39
inline
<?php namespace App\Http\Controllers; use Carbon\Carbon; use Cache, Exception; use App\{Resource, ResourceRecord}; use App\Http\Requests\{ ResourceUpdateRequest as UpdateRequest, ResourceCreateRequest as CreateRequest, ResourceRecordsShowRequest as ShowRequest, ResourceStatusUpdateRequest as RecordUpdateRequest }; class ResourceController extends Controller { /** * Class constructor. */ public function __construct() { $this->middleware('auth')->except('generate', 'updateStatus'); } /** * Generate records for the beacon to validate. * * @param Resource $resource * @return array */ public function generate(Resource $resource) : array { $resource->get()->each->generateNewRecord(); return ['status' => 'success', 'message' => 'Records generated!']; } /** * Generates a new record for the resource. * * @param ResourceRecord $record * @param RecordUpdateRequest $request * @return array */ public function updateStatus(ResourceRecord $record, RecordUpdateRequest $request) : array { $updated = $record->updateAvailability($request); return [ 'status' => ($updated ? 'success' : 'error'), 'message' => ($updated ? 'Record updated.' : 'Record update failed.'), ]; } /** * Display a listing of the resource. * * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory */ public function index(Resource $resources) { $resources = $resources->ordered()->get(); return view('resources.index', compact('resources')); } /** * Show the resource and the records (filterable by date range) * * @param ShowRequest $request * @param Resource $resource * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory */ public function show(ShowRequest $request, Resource $resource) { $lastRecord = $resource->records()->orderBy('created_at','DESC')->first(); $lastRecord = $lastRecord ? $lastRecord->created_at->diffForHumans() : 'Nothing recorded'; $cacheKey = "records.{$resource->id}.".$request->startDate()."-".$request->endDate(); $resource = Cache::remember($cacheKey, config('records.cache_time'), function () use ($request, $resource) { return $resource->withRecordsWithinDateRange($request->startDate(), $request->endDate()); }); $stats = generate_stats_from_records($resource->records); return view('resources.show', compact('resource', 'stats', 'lastRecord')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('resources.create'); } /** * Store a newly created resource in storage. * * @param CreateRequest $request * @return \Illuminate\Http\Response */ public function store(CreateRequest $request) { Resource::create($request->only(['name', 'type','resource_starts','resource_ends','exclude_weekends'])); return redirect(route('resources.index'))->withSuccess('Resource created!'); } /** * Show the form for editing the specified resource. * * @param \App\Resource $resource * @return \Illuminate\Http\Response */ public function edit(Resource $resource) { return view('resources.edit', compact('resource')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Resource $resource * @return \Illuminate\Http\Response */ public function update(UpdateRequest $request, Resource $resource) { $resource->update($request->only('name', 'type','resource_starts','resource_ends','exclude_weekends')); return redirect(route('resources.show', $resource->id))->withSuccess('Updated successfully!'); } /** * Remove the specified resource from storage. * * @param \App\Resource $resource * @return \Illuminate\Http\Response */ public function destroy(Resource $resource) { $resource->delete(); return redirect(route('resources.index'))->withSuccess('Resource deleted!'); } }
php
18
0.619166
117
28.039474
152
starcoderdata
$(document).ready(function(){ // Select $('select').select2({width: 'resolve'}) var quizCount = 1; var maxQuizCount = $('.quiz-item').length var maxQuizToForm = maxQuizCount - 1; $('#quiz-next').on('click',function(){ if(quizCount >= maxQuizToForm){ var lastClass = 'quiz-process-' + quizCount; $('#quiz').removeClass() quizCount = quizCount + 1; var itemCount = quizCount - 1; $('#quiz').addClass('quiz-process-' + quizCount) $('.quiz-line__inner h6 span').removeClass('active') $('.quiz-line__inner h6 span').eq(itemCount).addClass('active') $('.quiz-item').removeClass('active') $('.quiz-item').eq(itemCount).addClass('active') $('.quiz').addClass('showform') $('.quiz-title, .quiz-line, .quiz-steps, .quiz-controller').fadeOut() } else{ var lastClass = 'quiz-process-' + quizCount; $('#quiz').removeClass() quizCount = quizCount + 1; var itemCount = quizCount - 1; $('#quiz').addClass('quiz-process-' + quizCount) $('.quiz-line__inner h6 span').removeClass('active') $('.quiz-line__inner h6 span').eq(itemCount).addClass('active') $('.quiz-item').removeClass('active') $('.quiz-item').eq(itemCount).addClass('active') } }) $('#quiz-back').on('click',function(){ var lastClass = 'quiz-process-' + quizCount; $('#quiz').removeClass() quizCount = quizCount - 1; var itemCount = quizCount - 1; $('#quiz').addClass('quiz-process-' + quizCount) $('.quiz-line__inner h6 span').removeClass('active') $('.quiz-line__inner h6 span').eq(itemCount).addClass('active') $('.quiz-item').removeClass('active') $('.quiz-item').eq(itemCount).addClass('active') }) })
javascript
24
0.581118
75
25.724638
69
starcoderdata
bool mutation::add_client_request(dsn_task_code_t code, dsn_message_t request) { client_info ci; ci.code = code; ci.req = request; client_requests.push_back(ci); if (request != nullptr) { dsn_msg_add_ref(request); // released on dctor void* ptr; size_t size; bool r = dsn_msg_read_next(request, &ptr, &size); dassert(r, "payload is not present"); dsn_msg_read_commit(request, size); blob buffer((char*)ptr, 0, (int)size); data.updates.push_back(buffer); _appro_data_bytes += (int)size + sizeof(int); } else { blob bb; data.updates.push_back(bb); _appro_data_bytes += sizeof(int); } dbg_dassert(client_requests.size() == data.updates.size(), "size must be equal"); return true; }
c++
11
0.564804
78
23.057143
35
inline
Create a class CheckMultipleOf with a public method checkMultipleOf that takes two parameters first and second are of type int and returns true if first is multiple of second. The return type of checkMultipleOf is boolean. Here is an example: Cmd Args : 18 9 true Hint: Use the % (modulus) operator. It can be used to find the remainder after division by a number. For example, to check if a given number is even we write if (number % 2 == 0) {// when divided by 2, if the reminder is zero, it is a even number System.out.println("number is even"); } Note: Please don't change the package name. ' package q10925; public class CheckMultipleOf{ public boolean checkMultipleOf(int f ,int s){ if(f%s==0){ return true; } else{ return false; } } }
java
9
0.714953
222
21.552632
38
starcoderdata
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Covid; use PhpParser\Node\Stmt\Echo_; class CovidController extends Controller { public function index() { $user_get = Covid::all(); if ($user_get) { $resource = [ 'messagge' => 'Get All Data', 'resource' => $user_get ]; #mengubah data yang ada menjadi format json return response()->json($resource, 200); } else { $resource = [ 'messagge' => 'Data Not Found', 'resource' => $user_get ]; #mengubah data yang ada menjadi format json return response()->json($resource, 404); } } public function show($id) { $user_get = Covid::find($id); if ($user_get) { $resource = [ 'messagge' => 'Get Detail Data', 'resource' => $user_get ]; #mengubah data yang ada menjadi format json return response()->json($resource, 200); } else { $resource = [ 'messagge' => 'Data Not Found', 'resource' => $user_get ]; #mengubah data yang ada menjadi format json return response()->json($resource, 404); } } public function search($nama) { $user_get = Covid::where('name', $nama)->get(); if ($user_get) { $resource = [ 'messagge' => 'Get Data Detail By Name', 'resource' => $user_get ]; return response()->json($resource, 200); } else { $resource = [ 'messagge' => 'Data Not Found', 'resource' => $user_get ]; return response()->json($resource, 404); } } public function positive() { $user_get = Covid::where('status', 'positive')->get(); if ($user_get) { $resource = [ 'messagge' => 'Get Data Positive', 'resource' => $user_get ]; return response()->json($resource, 200); } else { $resource = [ 'messagge' => 'Data Not Found', 'resource' => $user_get ]; return response()->json($resource, 404); } } public function recovered() { $user_get = Covid::where('status', 'recovered')->get(); if ($user_get) { $resource = [ 'messagge' => 'Get Data Recovered', 'resource' => $user_get ]; return response()->json($resource, 200); } else { $resource = [ 'messagge' => 'Data Not Found', 'resource' => $user_get ]; return response()->json($resource, 404); } } public function dead() { $user_get = Covid::where('status', 'dead')->get(); if ($user_get) { $resource = [ 'messagge' => 'Get Data Dead', 'resource' => $user_get ]; return response()->json($resource, 200); } else { $resource = [ 'messagge' => 'Data Not Found', 'resource' => $user_get ]; return response()->json($resource, 404); } } public function store(Request $request) { $input = $request->validate([ 'name' => 'required', 'phone' => 'required', 'address' => 'required', 'status' => 'required', 'in_date_at' => 'required', 'out_date_at' => 'nullable' ]); //memasukan input pada varible sementara untuk direturn //memasukan input ke database $user_input = Covid::create($input); $resource = [ 'message' => 'New Patient Has Been Added Successfully', 'resource' => $user_input ]; return response()->json($resource, 201); } public function update(Request $request, $id) { $user_response = Covid::find($id); if ($user_response) { $user_response->update([ 'name' => $request->name ?? $user_response->name, // ?? merupakan statement ketika response update tidak diisi maka akan memakai data yang lama 'phone' => $request->phone ?? $user_response->phone, 'address' => $request->address ?? $user_response->address, 'status' => $request->status ?? $user_response->status, 'in_date_at' => $request->in_date_at ?? $user_response->in_date_at, 'out_date_at' => $request->out_date_at ?? $user_response->out_date_at ]); $resource = [ 'messagge' => 'Update Successfully', 'resource' => $user_response ]; return response()->json($resource, 201); } else { $resource = [ 'messagge' => 'Data Not Found', 'resource' => $user_response ]; return response()->json($resource, 404); } } public function destroy($id) { $user_get = Covid::find($id); if ($user_get) { $user_get->delete(); $resource = [ 'messagge' => 'Data Successfully Deleted', 'resource' => $user_get ]; return response()->json($resource, 204); } else { $resource = [ 'messagge' => 'Data Not Found', 'resource' => $user_get ]; return response()->json($resource, 404); } } }
php
16
0.450265
159
27.773399
203
starcoderdata
package net.mollywhite.mbta.resources; import com.codahale.metrics.annotation.Timed; import net.mollywhite.mbta.api.Branch; import net.mollywhite.mbta.client.TweetDetails; import net.mollywhite.mbta.dao.TweetDAO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import java.util.Arrays; import java.util.List; @Path("/branch") @Produces(MediaType.APPLICATION_JSON) public class BranchResource { private final TweetDAO tweetDAO; final Logger logger = LoggerFactory.getLogger(BranchResource.class); public BranchResource(TweetDAO tweetDAO) { this.tweetDAO = tweetDAO; } @GET @Path("/{branch}") @Timed public Response getTweetsByBranch(@PathParam("branch") String branchStr) { try { Branch branch = Branch.valueOf(branchStr.toUpperCase()); List tweets = tweetDAO.getTweetsByBranch(branch); return Response.ok(tweets).build(); } catch (IllegalArgumentException e) { return Response.status(Status.NOT_FOUND) .entity("Line " + branchStr + " not found. Use one of " + Arrays.toString(Branch.values()) + ".") .build(); } } }
java
16
0.733965
107
29.488889
45
starcoderdata
/* global angular */ (function(angular) { angular.module('angularScreenfull') .directive('showIfFullscreenEnabled', showIfFullscreenEnabledDirective); showIfFullscreenEnabledDirective.$inject = ['$animate']; function showIfFullscreenEnabledDirective ($animate) { return { restrict: 'A', require: '^ngsfFullscreen', link: function(scope, elm, attrs,fullScreenCtrl) { if (fullScreenCtrl.fullscreenEnabled()) { $animate.removeClass(elm, 'ng-hide'); } else { $animate.addClass(elm, 'ng-hide'); } } }; } })(angular);
javascript
20
0.55814
76
28.913043
23
starcoderdata
#include using namespace std; class demo { int num; public: demo(int x) { try { if (x == 0) throw "Zero not allowed "; num = x; show(); } catch (const char* exp) { cout << "Exception caught \n "; cout << exp << endl; } } void show() { cout << "Num = " << num << endl; } }; int main() { // constructor will be called demo(0); cout << "Again creating object \n"; demo(1); return 0; }
c++
11
0.393333
43
14.216216
37
starcoderdata
import pytest from web_error import error class A404Error(error.NotFoundException): code = "E404" message = "a 404 message" class A401Error(error.UnauthorisedException): code = "E401" message = "a 401 message" class A400Error(error.BadRequestException): code = "E400" message = "a 400 message" class A500Error(error.ServerException): code = "E500" message = "a 500 message" @pytest.mark.parametrize("exc", [ A404Error, A401Error, A400Error, A500Error, ]) def test_marshal(exc): e = exc("debug_message") assert e.marshal() == { "code": "E{}".format(e.status), "message": e.message, "debug_message": "debug_message", } @pytest.mark.parametrize("exc", [ A404Error, A401Error, A400Error, A500Error, ]) def test_reraise(exc): e = exc("debug_message") d = e.marshal() try: error.HttpException.reraise(status=e.status, **d) except error.HttpException as exc: assert exc.status == e.status assert exc.marshal() == { "code": "E{}".format(e.status), "message": e.message, "debug_message": "debug_message", }
python
14
0.600826
57
18.516129
62
starcoderdata
/* eslint-disable no-param-reassign */ const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = function rewireSilentRenew(config, env) { if (typeof config.entry === 'string') { config.entry = { main: config.entry, }; } config.entry.silentRenew = ['./src/silent_renew.js']; // exclude silentRenew chunk from main html plugin const mainHtmlPlugin = config.plugins.find(x => x.constructor.name === 'HtmlWebpackPlugin'); mainHtmlPlugin.options.excludeChunks.push('silentRenew'); // add new html plugin for silent renew config.plugins.push(new HtmlWebpackPlugin({ template: './public/silent_renew.html', excludeChunks: ['main'], filename: 'silent_renew.html' }) ); return config; };
javascript
14
0.683377
94
28.153846
26
starcoderdata
func socket(ws *websocket.Conn) { for { // allocate our container struct var m message // si il recoit un message if err := websocket.JSON.Receive(ws, &m); err != nil { log.Println(err) break } log.Println("Received message:", m.Message) // alors envoi une réponse à celui qui a envoyé le message //envoi la structure contenant les données de la stib m2 := cD; if err := websocket.JSON.Send(ws, m2); err != nil { log.Println(err) break } } }
go
11
0.628283
61
21.545455
22
inline
package racingcar.domain; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import java.util.stream.Collectors; import camp.nextstep.edu.missionutils.Randoms; import racingcar.view.OutputView; public class Race { ArrayList cars = new ArrayList<>(); public void participate(Car car) { if (cars.contains(car)) { throw new IllegalArgumentException("자동차의 이름은 중복될 수 없습니다."); } cars.add(car); } public ArrayList showAllCarName() { ArrayList allCarsName = new ArrayList<>(); cars.stream().forEach(car -> allCarsName.add(car.getName())); return allCarsName; } public void repeatGamePhase(Round round) { OutputView.showSentenceBeforeGame(); for (int i = 0; i < round.getRepeatCnt(); i++) { cars.stream().forEach(car -> car.move(Randoms.pickNumberInRange(0, 9))); OutputView.showThisPhaseResult(cars); } } public void showWinners() { List winners = findWinner(); OutputView.showWinners(winners); } private List findWinner() { int maxDistance = cars.stream().mapToInt(car -> car.getMovingDistance()).max().orElseThrow(NoSuchElementException::new); return cars.stream() .filter(car -> car.getMovingDistance() == maxDistance) .collect(Collectors.toList()); } public void clearIncorrectValues() { cars.clear(); } //최종 우승자를 보여주는 메서드. }
java
15
0.71553
107
23.607143
56
starcoderdata
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using Spelprojekt.Engine; using System; namespace Spelprojekt.Control { class Mouse { static MouseState currentMouseState; static MouseState previousMouseState; public static Vector2 mousePos() { Vector2 pos; pos.X = currentMouseState.X; pos.Y = currentMouseState.Y; return pos; } public static MouseState GetStateLocal() { previousMouseState = currentMouseState; currentMouseState = Microsoft.Xna.Framework.Input.Mouse.GetState(); return currentMouseState; } public static bool IsPressed(MouseKey key) { switch(key) { case MouseKey.LeftButton: return currentMouseState.LeftButton == ButtonState.Pressed; case MouseKey.MiddleButton: return currentMouseState.MiddleButton == ButtonState.Pressed; case MouseKey.RightButton: return currentMouseState.RightButton == ButtonState.Pressed; default: return false; } } public static bool HasBeenPressed(MouseKey key) { previousMouseState = currentMouseState; currentMouseState = Microsoft.Xna.Framework.Input.Mouse.GetState(); switch (key) { case MouseKey.LeftButton: return (currentMouseState.LeftButton == ButtonState.Pressed) && !(previousMouseState.LeftButton == ButtonState.Pressed); case MouseKey.MiddleButton: return (currentMouseState.MiddleButton == ButtonState.Pressed) && !(previousMouseState.MiddleButton == ButtonState.Pressed); case MouseKey.RightButton: return (currentMouseState.RightButton == ButtonState.Pressed) && !(previousMouseState.RightButton == ButtonState.Pressed); default: return false; } } // Rotation och postitionshantering public static float RelativeRotation(Camera camera, float X, float Y) { return (float) Math.Atan2(DeltaY(camera, Y), DeltaX(camera, X)); } public static float DeltaX(Camera camera, float X) { return GamePosX(camera) - X; } public static float DeltaY(Camera camera, float Y) { return GamePosY(camera) - Y; } public static float GamePosX(Camera camera) { return (GetStateLocal().X / camera.Scaling + -camera.X); } public static float GamePosY(Camera camera) { return (GetStateLocal().Y / camera.Scaling + -camera.Y); } ///////////////////////////////////////////////// } enum MouseKey { LeftButton, MiddleButton, RightButton } }
c#
16
0.596565
168
32.174419
86
starcoderdata
void Domain::finalisePositionAndVelocityUpdate(std::set<BaseParticle*>& ghostParticlesToBeDeleted) { //For all active boundaries for (int localIndex : boundaryList_) { updateParticlePosition(localIndex); updateParticleVelocity(localIndex); } //Based on the new position, update the particle lists. //Remove particles that left the communication zone, they will be re-communicated in a later step updateParticles(ghostParticlesToBeDeleted); //For all active boundaries clear the data lists for (int localIndex : boundaryList_) { updatePositionDataSend_[localIndex].clear(); updateVelocityDataSend_[localIndex].clear(); updatePositionDataReceive_[localIndex].clear(); updateVelocityDataReceive_[localIndex].clear(); } }
c++
10
0.70241
101
33.625
24
inline
<?php function nbvalue($assetAmount, $assetDate,$useMonth, $monthlyAmount) { $dat= date('Y-m-d', strtotime($assetDate. '+'. $useMonth.' months')); $today=date('Y-m-d'); $dateTo=strtotime($dat); $dateFrom=strtotime($assetDate); $dateDiff= $dateTo-$dateFrom; $date= floor($dateDiff/(60*60*24)); $m = $date/30; $m= (int)$m; $dateToday=strtotime($today); $dateDiffs= $dateToday-$dateFrom; $dates= floor($dateDiffs/(60*60*24)); $ms = $dates/30; $ms= (int)$ms; if($ms==0): return 0; elseif($ms < $m): $used= round(abs($ms *$monthlyAmount),2); return $nbv=$assetAmount-$used; elseif($ms >= $m): return $assetAmount; endif; } ?>
php
16
0.599727
71
19
35
starcoderdata
package kustomize import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestMixin_Build(t *testing.T) { m := NewTestMixin(t) err := m.Build() require.NoError(t, err) wantOutput := `RUN apt-get update && \ apt-get install -y curl git && \ curl -L -O https://github.com/kubernetes-sigs/kustomize/releases/download/v3.1.0/kustomize_3.1.0_linux_amd64 && \ mv ./kustomize_3.1.0_linux_amd64 /usr/local/bin/kustomize && \ chmod a+x /usr/local/bin/kustomize ` gotOutput := m.TestContext.GetOutput() assert.Equal(t, wantOutput, gotOutput) }
go
8
0.704013
114
22.92
25
starcoderdata
// Copyright 2014 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #ifndef _FX_CODEC_PROGRESS_H_ #define _FX_CODEC_PROGRESS_H_ #define FXCODEC_BLOCK_SIZE 4096 #define FXCODEC_PNG_GAMMA 2.2 #if _FX_OS_ == _FX_MACOSX_ || _FX_OS_ == _FX_IOS_ #undef FXCODEC_PNG_GAMMA #define FXCODEC_PNG_GAMMA 1.7 #endif struct PixelWeight { int m_SrcStart; int m_SrcEnd; int m_Weights[1]; }; class CFXCODEC_WeightTable { public: CFXCODEC_WeightTable() { m_pWeightTables = NULL; } ~CFXCODEC_WeightTable() { if (m_pWeightTables != NULL) { FX_Free(m_pWeightTables); } } void Calc(int dest_len, int dest_min, int dest_max, int src_len, int src_min, int src_max, FX_BOOL bInterpol); PixelWeight* GetPixelWeight(int pixel) { return (PixelWeight*)(m_pWeightTables + (pixel - m_DestMin) * m_ItemSize); } int m_DestMin, m_ItemSize; uint8_t* m_pWeightTables; }; class CFXCODEC_HorzTable { public: CFXCODEC_HorzTable() { m_pWeightTables = NULL; } ~CFXCODEC_HorzTable() { if (m_pWeightTables != NULL) { FX_Free(m_pWeightTables); } } void Calc(int dest_len, int src_len, FX_BOOL bInterpol); PixelWeight* GetPixelWeight(int pixel) { return (PixelWeight*)(m_pWeightTables + pixel * m_ItemSize); } int m_ItemSize; uint8_t* m_pWeightTables; }; class CFXCODEC_VertTable { public: CFXCODEC_VertTable() { m_pWeightTables = NULL; } ~CFXCODEC_VertTable() { if (m_pWeightTables != NULL) { FX_Free(m_pWeightTables); } } void Calc(int dest_len, int src_len); PixelWeight* GetPixelWeight(int pixel) { return (PixelWeight*)(m_pWeightTables + pixel * m_ItemSize); } int m_ItemSize; uint8_t* m_pWeightTables; }; enum FXCodec_Format { FXCodec_Invalid = 0, FXCodec_1bppGray = 0x101, FXCodec_1bppRgb = 0x001, FXCodec_8bppGray = 0x108, FXCodec_8bppRgb = 0x008, FXCodec_Rgb = 0x018, FXCodec_Rgb32 = 0x020, FXCodec_Argb = 0x220, FXCodec_Cmyk = 0x120 }; class CCodec_ProgressiveDecoder : public ICodec_ProgressiveDecoder { public: CCodec_ProgressiveDecoder(CCodec_ModuleMgr* pCodecMgr); ~CCodec_ProgressiveDecoder() override; FXCODEC_STATUS LoadImageInfo(IFX_FileRead* pFile, FXCODEC_IMAGE_TYPE imageType, CFX_DIBAttribute* pAttribute) override; FXCODEC_IMAGE_TYPE GetType() const override { return m_imagType; } int32_t GetWidth() const override { return m_SrcWidth; } int32_t GetHeight() const override { return m_SrcHeight; } int32_t GetNumComponents() const override { return m_SrcComponents; } int32_t GetBPC() const override { return m_SrcBPC; } void SetClipBox(FX_RECT* clip) override; FXCODEC_STATUS GetFrames(int32_t& frames, IFX_Pause* pPause) override; FXCODEC_STATUS StartDecode(CFX_DIBitmap* pDIBitmap, int start_x, int start_y, int size_x, int size_y, int32_t frames, FX_BOOL bInterpol) override; FXCODEC_STATUS ContinueDecode(IFX_Pause* pPause) override; protected: static FX_BOOL PngReadHeaderFunc(void* pModule, int width, int height, int bpc, int pass, int* color_type, double* gamma); static FX_BOOL PngAskScanlineBufFunc(void* pModule, int line, uint8_t*& src_buf); static void PngFillScanlineBufCompletedFunc(void* pModule, int pass, int line); static void GifRecordCurrentPositionCallback(void* pModule, FX_DWORD& cur_pos); static uint8_t* GifAskLocalPaletteBufCallback(void* pModule, int32_t frame_num, int32_t pal_size); static FX_BOOL GifInputRecordPositionBufCallback(void* pModule, FX_DWORD rcd_pos, const FX_RECT& img_rc, int32_t pal_num, void* pal_ptr, int32_t delay_time, FX_BOOL user_input, int32_t trans_index, int32_t disposal_method, FX_BOOL interlace); static void GifReadScanlineCallback(void* pModule, int32_t row_num, uint8_t* row_buf); static FX_BOOL BmpInputImagePositionBufCallback(void* pModule, FX_DWORD rcd_pos); static void BmpReadScanlineCallback(void* pModule, int32_t row_num, uint8_t* row_buf); FX_BOOL DetectImageType(FXCODEC_IMAGE_TYPE imageType, CFX_DIBAttribute* pAttribute); void GetDownScale(int& down_scale); void GetTransMethod(FXDIB_Format des_format, FXCodec_Format src_format); void ReSampleScanline(CFX_DIBitmap* pDeviceBitmap, int32_t des_line, uint8_t* src_scan, FXCodec_Format src_format); void Resample(CFX_DIBitmap* pDeviceBitmap, int32_t src_line, uint8_t* src_scan, FXCodec_Format src_format); void ResampleVert(CFX_DIBitmap* pDeviceBitmap, double scale_y, int des_row); FX_BOOL JpegReadMoreData(ICodec_JpegModule* pJpegModule, FXCODEC_STATUS& err_status); void PngOneOneMapResampleHorz(CFX_DIBitmap* pDeviceBitmap, int32_t des_line, uint8_t* src_scan, FXCodec_Format src_format); FX_BOOL GifReadMoreData(ICodec_GifModule* pGifModule, FXCODEC_STATUS& err_status); void GifDoubleLineResampleVert(CFX_DIBitmap* pDeviceBitmap, double scale_y, int des_row); FX_BOOL BmpReadMoreData(ICodec_BmpModule* pBmpModule, FXCODEC_STATUS& err_status); void ResampleVertBT(CFX_DIBitmap* pDeviceBitmap, double scale_y, int des_row); public: IFX_FileRead* m_pFile; CCodec_ModuleMgr* m_pCodecMgr; void* m_pJpegContext; void* m_pPngContext; void* m_pGifContext; void* m_pBmpContext; void* m_pTiffContext; FXCODEC_IMAGE_TYPE m_imagType; FX_DWORD m_offSet; uint8_t* m_pSrcBuf; FX_DWORD m_SrcSize; uint8_t* m_pDecodeBuf; int m_ScanlineSize; CFX_DIBitmap* m_pDeviceBitmap; FX_BOOL m_bInterpol; CFXCODEC_WeightTable m_WeightHorz; CFXCODEC_VertTable m_WeightVert; CFXCODEC_HorzTable m_WeightHorzOO; int m_SrcWidth; int m_SrcHeight; int m_SrcComponents; int m_SrcBPC; FX_RECT m_clipBox; int m_startX; int m_startY; int m_sizeX; int m_sizeY; int m_TransMethod; FX_ARGB* m_pSrcPalette; int m_SrcPaletteNumber; int m_SrcRow; FXCodec_Format m_SrcFormat; int m_SrcPassNumber; int m_FrameNumber; int m_FrameCur; int m_GifBgIndex; uint8_t* m_pGifPalette; int32_t m_GifPltNumber; int m_GifTransIndex; FX_RECT m_GifFrameRect; FX_BOOL m_BmpIsTopBottom; FXCODEC_STATUS m_status; }; #endif
c
13
0.547765
80
35.0625
224
starcoderdata
using Newtonsoft.Json; using System.Collections.Generic; namespace Pexip.Lib { /// /// Models the Pexip API reponse for /api/admin/history/v1/participant/. /// public class ParticipantHistoryResponse { [JsonProperty(PropertyName = "meta")] public MetaObject MetaObject { get; set; } [JsonProperty(PropertyName = "objects")] public List ParticipantHistoryObject { get; set; } } }
c#
11
0.692022
84
28.944444
18
starcoderdata
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.model.parser; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import org.eclipse.birt.report.model.api.Expression; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.birt.report.model.api.util.StringUtil; import org.eclipse.birt.report.model.api.util.URIUtil; import org.eclipse.birt.report.model.api.validators.ImageDataValidator; import org.eclipse.birt.report.model.core.DesignElement; import org.eclipse.birt.report.model.core.Module; import org.eclipse.birt.report.model.elements.ImageItem; import org.eclipse.birt.report.model.elements.interfaces.IImageItemModel; import org.eclipse.birt.report.model.metadata.StructRefValue; import org.eclipse.birt.report.model.util.SecurityUtil; import org.eclipse.birt.report.model.util.VersionUtil; import org.eclipse.birt.report.model.util.XMLParserException; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * This class parses an image item in the design file. * */ public class ImageState extends ReportItemState { /** * The image item being created. */ protected ImageItem image; /** * Constructs the image item state with the design parser handler, the * container element and the container slot of the image item. * * @param handler * the design file parser handler * @param theContainer * the element that contains this one * @param slot * the slot in which this element appears */ public ImageState( ModuleParserHandler handler, DesignElement theContainer, int slot ) { super( handler, theContainer, slot ); } /** * Constructs image state with the design parser handler, the container * element and the container property name of the report element. * * @param handler * the design file parser handler * @param theContainer * the element that contains this one * @param prop * the slot in which this element appears */ public ImageState( ModuleParserHandler handler, DesignElement theContainer, String prop ) { super( handler, theContainer, prop ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.model.parser.DesignParseState#getElement() */ public DesignElement getElement( ) { return image; } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.util.AbstractParseState#parseAttrs(org. * xml.sax.Attributes) */ public void parseAttrs( Attributes attrs ) throws XMLParserException { image = new ImageItem( ); initElement( attrs ); } /** * Check whether the source type conflicts, and set the proper source type. */ private void checkImageType( ) { int type = 0; Module module = handler.getModule( ); String uri = getLocalStringExpression( image, IImageItemModel.URI_PROP, module ); if ( !StringUtil.isEmpty( uri ) ) { uri = StringUtil.trimQuotes( uri ); try { new URL( uri ); setProperty( IImageItemModel.SOURCE_PROP, DesignChoiceConstants.IMAGE_REF_TYPE_URL ); } catch ( MalformedURLException e ) { if ( isFileProtocol( uri ) ) setProperty( IImageItemModel.SOURCE_PROP, DesignChoiceConstants.IMAGE_REF_TYPE_FILE ); else setProperty( IImageItemModel.SOURCE_PROP, DesignChoiceConstants.IMAGE_REF_TYPE_EXPR ); } type++; } StructRefValue imageName = (StructRefValue) image.getLocalProperty( module, IImageItemModel.IMAGE_NAME_PROP ); if ( imageName != null ) { setProperty( IImageItemModel.SOURCE_PROP, DesignChoiceConstants.IMAGE_REF_TYPE_EMBED ); type++; } String typeExpr = getLocalStringExpression( image, IImageItemModel.TYPE_EXPR_PROP, module ); String valueExpr = getLocalStringExpression( image, IImageItemModel.VALUE_EXPR_PROP, module ); if ( !StringUtil.isEmpty( typeExpr ) || !StringUtil.isEmpty( valueExpr ) ) { setProperty( IImageItemModel.SOURCE_PROP, DesignChoiceConstants.IMAGE_REF_TYPE_EXPR ); type++; } if ( type > 1 ) handler .getErrorHandler( ) .semanticError( new DesignParserException( DesignParserException.DESIGN_EXCEPTION_IMAGE_REF_CONFLICT ) ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.model.util.AbstractParseState#end() */ public void end( ) throws SAXException { Module module = handler.getModule( ); if ( image.getLocalProperty( module, IImageItemModel.SOURCE_PROP ) == null && handler.versionNumber <= VersionUtil.VERSION_3_2_3 ) checkImageType( ); // check the validation of the image data. List tmpList = ImageDataValidator.getInstance( ) .validate( handler.module, image ); for ( int i = 0; i < tmpList.size( ); i++ ) { handler.getErrorHandler( ).semanticWarning( tmpList.get( i ) ); } super.end( ); } /** * Checks whether is a valid file on the disk. * can follow these scheme. * * * * * * * @param filePath * the input filePath * @return true if filePath exists on the disk. Otherwise false. */ private static boolean isFileProtocol( String filePath ) { try { URL fileUrl = new URL( filePath ); if ( URIUtil.FILE_SCHEMA.equalsIgnoreCase( fileUrl.getProtocol( ) ) ) return true; return false; } catch ( MalformedURLException e ) { // ignore the error since this string is not in URL format } File file = new File( filePath ); String scheme = SecurityUtil.getFiletoURISchemaPart( file ); if ( scheme == null ) return false; if ( scheme.equalsIgnoreCase( URIUtil.FILE_SCHEMA ) ) { return true; } return false; } /** * @param element * @param propName * @return */ private static String getLocalStringExpression( DesignElement element, String propName, Module root ) { Object value = element.getLocalProperty( root, propName ); if ( !( value instanceof Expression ) ) return null; return ( (Expression) value ).getStringExpression( ); } }
java
15
0.681791
81
25.228682
258
starcoderdata
def launch_epidemic(self, source, max_time=np.inf): """ Run the epidemic, starting from node 'source', for at most `max_time` units of time """ self._init_run(source, max_time) # Init epidemic time to 0 time = 0 last_print = 0 while self.processing: # Get the next event to process (node, event_type), time = self.processing.pop(0) if time > self.max_time: break # Stop at then end of the observation window # Process the event if event_type == 'inf': self._process_infection_event(node, time) elif event_type == 'rec': self._process_recovery_event(node, time) else: raise ValueError("Invalid event type") self._printer.print(self, time) self._printer.println(self, time) self.max_time = time # Free memory del self.processing
python
12
0.53629
78
37.192308
26
inline
import React from 'react'; export default class HCardPreview extends React.Component { constructor(props) { super(props); this.state = { hCard: props.hCard }; } render() { return (<div className="hCard"> PREVIEW <div className="hCard-wrapper"> <div className="hCard-header"> {this.state.hCard.surname} <img src={this.state.hCard.avatar} id="imagePreview" /> <div className="hCard-body"> <div className="row"> <div className="three columns hCard-body-label"> Email <div className="nine columns hCard-body-value no-transform"> {this.state.hCard.email} <div className="row"> <div className="three columns hCard-body-label"> Phone <div className="nine columns hCard-body-value"> {this.state.hCard.phone} <div className="row"> <div className="three columns hCard-body-label"> Address <div className="nine columns hCard-body-value"> {this.state.hCard.houseno} {this.state.hCard.street} <div className="row"> <div className="three columns hCard-body-label"> <div className="nine columns hCard-body-value"> {this.state.hCard.suburb}{(this.state.hCard.state!=='') ? ', ' : ''} {this.state.hCard.state} <div className="row"> <div className="two columns hCard-body-label">Postcode <div className="four columns hCard-body-value">{this.state.hCard.postcode} <div className="two columns hCard-body-label">Country <div className="four columns hCard-body-value">{this.state.hCard.country} } }
javascript
20
0.444138
115
40.672131
61
starcoderdata
package uk.co.gencoreoperative.btw.ui; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeNode; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class ZipTreeViewer { final String DECO_CLIENT = "minecraft"; final String JORGE_CLIENT = "JAR - CLIENT"; JFrame frame = new JFrame(); JDialog dialog = new JDialog(frame, true); private String pathString = Strings.NOT_RECOGNISED.getText(); public void view(ZipFile zipFile) throws IOException { DefaultMutableTreeNode root = new DefaultMutableTreeNode("/"); constructTree(zipFile, root); boolean visible = false; // "Smart" auto selection, only asks user to specify what folder in the zip files if none of these match. if (doesChildHaveSubstring(root, ".class")) { pathString = ""; } else if (doesChildHaveString(root, DECO_CLIENT)) { pathString = DECO_CLIENT + "/"; } else if (doesChildHaveString(root, JORGE_CLIENT)) { pathString = JORGE_CLIENT + "/"; } else { visible = true; } JTree tree = new JTree(root); tree.setShowsRootHandles(true); dialog.add(new JScrollPane(tree)); JPanel panel = new JPanel(); // Select button. JButton selectZIPFolder = new JButton(Strings.BUTTON_DIALOG_SELECT.getText()); selectZIPFolder.setToolTipText(Strings.TOOLTIP_SELECT_ZIP.getText()); selectZIPFolder.setIcon(Icons.ACCEPT.getIcon()); selectZIPFolder.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dialog.setVisible(false); } }); selectZIPFolder.setEnabled(false); panel.add(selectZIPFolder); // Cancel button. JButton cancelButton = new JButton(Strings.BUTTON_CANCEL.getText()); cancelButton.setToolTipText(Strings.TOOLTIP_CANCEL.getText()); cancelButton.setIcon(Icons.DELETE.getIcon()); cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dialog.setVisible(false); pathString = Strings.NOT_RECOGNISED.getText(); } }); panel.add(cancelButton); // Selection changed. tree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); pathString = constructPath(selectedNode); selectZIPFolder.setEnabled(!pathString.equals(Strings.NOT_RECOGNISED.getText())); } }); dialog.add(panel, BorderLayout.SOUTH); dialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); dialog.setTitle("Select the folder to import"); dialog.setSize(512, 420); dialog.setLocationRelativeTo(null); dialog.setVisible(visible); } public String getPathString() { return pathString; } private void constructTree(ZipFile zipFile, DefaultMutableTreeNode root) throws IOException { Enumeration<? extends ZipEntry> entries = zipFile.entries(); while(entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String[] path = entry.getName().split("/"); DefaultMutableTreeNode prevRoot = root; for (String filename : path) { DefaultMutableTreeNode newNode = getChild(prevRoot, filename); prevRoot.add(newNode); prevRoot = newNode; } } zipFile.close(); } private DefaultMutableTreeNode getChild(DefaultMutableTreeNode root, String name) { Enumeration e = root.children(); while (e.hasMoreElements()) { DefaultMutableTreeNode child = (DefaultMutableTreeNode) e.nextElement(); if (name.contentEquals(child.toString())) { return child; } } return new DefaultMutableTreeNode(name); } private String constructPath(DefaultMutableTreeNode node) { if (node.toString().contains(".")) { return Strings.NOT_RECOGNISED.getText(); } StringBuilder nodePath = new StringBuilder(); for (TreeNode o : node.getPath()) { nodePath.append(o.toString()).append("/"); } return nodePath.substring(2); } private boolean doesChildHaveString(DefaultMutableTreeNode root, String s) { for (int i = 0; i < root.getChildCount(); i++) { if (root.getChildAt(i).toString().matches(s)) { return true; } } return false; } private boolean doesChildHaveSubstring(DefaultMutableTreeNode root, CharSequence s) { for (int i = 0; i < root.getChildCount(); i++) { if (root.getChildAt(i).toString().contains(s)) { return true; } } return false; } }
java
20
0.625544
115
34.56129
155
starcoderdata
package pl.uniq.utils; import org.junit.jupiter.api.Test; import org.springframework.security.core.userdetails.UserDetails; import pl.uniq.model.CustomUserDetails; import pl.uniq.model.User; import pl.uniq.utils.JwtUtil; import static org.junit.jupiter.api.Assertions.assertEquals; class JwtUtilTest { @Test void test1() { User user = User.builder() .username("johny") .build(); UserDetails userDetails = new CustomUserDetails(user); JwtUtil jwtUtil = new JwtUtil(); String jwt = jwtUtil.generateToken(userDetails); System.out.println(jwt); assertEquals(user.getUsername(), jwtUtil.extractUsername(jwt)); } }
java
11
0.756173
65
24.92
25
starcoderdata
import sys import os.path sys.path.append(os.path.join(os.path.dirname(__file__), "vendor")) from Qt import QtWidgets, QtGui, QtCore from app import *
python
9
0.746032
66
20
9
starcoderdata
package iou.model; import iou.enums.TransactionType; import org.apache.commons.lang.builder.HashCodeBuilder; import java.util.Date; public abstract class Transaction { private TransactionType type; private String description; private Date date = new Date(); private long id; private float annPaid; private float bobPaid; public Transaction(TransactionType type) { this.type = type; } public void setAnnPaid(float amount) { this.annPaid = amount; } public void setBobPaid(float amount) { this.bobPaid = amount; } public float getBobPaid() { return bobPaid; } public float getAnnPaid() { return annPaid; } public long getId() { return id; } public void setId(long id) { this.id = id; } public TransactionType getTransactionType() { return type; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } @Override public String toString() { return String.format("id=%s, description=%s, date=%s, ann paid=%s, bob paid=%s", id, description, date, annPaid, bobPaid); } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Transaction)) { return false; } return this.id == ((Transaction) obj).id; } @Override public int hashCode() { return new HashCodeBuilder(17, 37).append(id).toHashCode(); } }
java
9
0.61059
88
19.602273
88
starcoderdata
package homomorphic_authentication_library_Java.crypto.pairing; import homomorphic_authentication_library_Java.crypto.PairingFactory; import homomorphic_authentication_library_Java.io.ElementConversionTool; import it.unisa.dia.gas.crypto.jpbc.signature.bls01.params.BLS01Parameters; import it.unisa.dia.gas.jpbc.Element; import it.unisa.dia.gas.jpbc.Pairing; import it.unisa.dia.gas.jpbc.PairingParameters; import it.unisa.dia.gas.plaf.jpbc.pairing.a.TypeACurveGenerator; public abstract class PairingGenerator { protected PairingParameters params = null; protected Pairing pairing = null; protected Element g = null; protected Element w = null; public abstract void generate(); public void generate(PairingParameters params, Element g) { this.params = params; this.pairing = PairingFactory.getPairing(params); this.g = g.getImmutable(); } public void generate(String params, byte[] g) { this.params = PairingFactory.getPairingParameters(params); this.pairing = PairingFactory.getPairing(params); this.g = parseG(g); } public void generate(String params, Element g) { this.params = PairingFactory.getPairingParameters(params); this.pairing = PairingFactory.getPairing(params); this.g = g; } public abstract Element generateW(); public PairingParameters parsePairingParameters(String params) { return PairingFactory.getPairingParameters(params); } /** * @return the params */ public PairingParameters getPairingParameters() { return params; } /** * @return the pairing */ public Pairing getPairing() { return pairing; } /** * @return the g */ public Element getG() { return g; } public abstract Element parseG(byte[] g); }
java
11
0.687901
75
26.072464
69
starcoderdata
// Copyright 2020 #include #include #include #include #include "./radix_sort.h" TEST(Odd_Even_Merge_Radix, Test_Sequential_Radix_Sort_Size_1) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 0) { std::vector vec1(1); vec1[0] = 0.0; std::vector vec2 = radixSort(vec1); EXPECT_EQ(vec1, vec2); } } TEST(Odd_Even_Merge_Radix, Test_Sequential_Radix_Sort_Size_1000) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 0) { int sizeVec = 1000; std::vector vec1 = getRandVec(sizeVec); std::vector vec2 = vec1; vec1 = radixSort(vec1); std::sort(vec2.begin(), vec2.end()); EXPECT_EQ(vec1, vec2); } } TEST(Odd_Even_Merge_Radix, Test_Sequential_Radix_Sort_Size_1005) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 0) { int sizeVec = 1005; std::vector vec1 = getRandVec(sizeVec); std::vector vec2 = vec1; vec1 = radixSort(vec1); std::sort(vec2.begin(), vec2.end()); EXPECT_EQ(vec1, vec2); } } TEST(Odd_Even_Sort, Test_Parallel_Odd_Even_Merge_Size_4) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int sizeVec = 4; std::vector vec1 = getRandVec(sizeVec); std::vector vec2 = vec1; vec1 = parOddEvenMerge(vec1); if (rank == 0) { vec2 = radixSort(vec2); EXPECT_EQ(vec1, vec2); } } TEST(Odd_Even_Sort, Test_Parallel_Odd_Even_Merge_Size_5) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int sizeVec = 5; std::vector vec1 = getRandVec(sizeVec); std::vector vec2 = vec1; vec1 = parOddEvenMerge(vec1); if (rank == 0) { vec2 = radixSort(vec2); EXPECT_EQ(vec1, vec2); } } TEST(Odd_Even_Sort, Test_Parallel_Odd_Even_Merge_Size_100) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int sizeVec = 100; std::vector vec1 = getRandVec(sizeVec); std::vector vec2 = vec1; vec1 = parOddEvenMerge(vec1); if (rank == 0) { vec2 = radixSort(vec2); EXPECT_EQ(vec1, vec2); } } TEST(Odd_Even_Sort, Test_Parallel_Odd_Even_Merge_Size_105) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int sizeVec = 105; std::vector vec1 = getRandVec(sizeVec); std::vector vec2 = vec1; vec1 = parOddEvenMerge(vec1); if (rank == 0) { vec2 = radixSort(vec2); EXPECT_EQ(vec1, vec2); } } TEST(Odd_Even_Sort, Test_Parallel_Odd_Even_Merge_Size_1000) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int sizeVec = 1000; std::vector vec1 = getRandVec(sizeVec); std::vector vec2 = vec1; vec1 = parOddEvenMerge(vec1); if (rank == 0) { vec2 = radixSort(vec2); EXPECT_EQ(vec1, vec2); } } TEST(Odd_Even_Sort, Test_Parallel_Odd_Even_Merge_Size_1005) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int sizeVec = 1005; std::vector vec1 = getRandVec(sizeVec); std::vector vec2 = vec1; vec1 = parOddEvenMerge(vec1); if (rank == 0) { vec2 = radixSort(vec2); EXPECT_EQ(vec1, vec2); } } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); MPI_Init(&argc, &argv); ::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment); ::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners(); listeners.Release(listeners.default_result_printer()); listeners.Release(listeners.default_xml_generator()); listeners.Append(new GTestMPIListener::MPIMinimalistPrinter); return RUN_ALL_TESTS(); }
c++
11
0.612451
78
26.733813
139
starcoderdata
package org.clever.graaljs.data.jdbc.builtin.wrap; import lombok.SneakyThrows; import org.clever.graaljs.core.internal.utils.InteropScriptToJavaUtils; import org.clever.graaljs.data.jdbc.builtin.wrap.support.AbstractJdbcDatabase; import org.clever.graaljs.data.jdbc.builtin.wrap.support.JdbcConfig; import org.clever.graaljs.data.jdbc.support.JdbcDataSourceStatus; import org.clever.graaljs.data.jdbc.support.JdbcInfo; import org.springframework.util.Assert; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * 作者:lizw * 创建时间:2020/07/29 12:50 */ public class JdbcDatabase extends AbstractJdbcDatabase { public static final JdbcDatabase Instance = new JdbcDatabase(); private static final ConcurrentMap<String, JdbcDataSource> DATASOURCE_MAP = new ConcurrentHashMap<>(); private String defaultName; protected JdbcDatabase() { } /** * 设置默认数据源 * * @param defaultName 默认数据源名称 * @return 默认数据源对象 */ public JdbcDataSource setDefault(String defaultName) { Assert.hasText(defaultName, "参数defaultName不能为空"); Assert.isTrue(DATASOURCE_MAP.containsKey(defaultName) && !DATASOURCE_MAP.get(defaultName).isClosed(), "默认数据源已经关闭(isClosed)"); this.defaultName = defaultName; return getDefault(); } /** * 设置默认数据源 * * @param defaultName 默认数据源名称 * @param jdbcDataSource 默认数据源对象 */ public void setDefault(String defaultName, org.clever.graaljs.data.jdbc.builtin.adapter.JdbcDataSource jdbcDataSource) { Assert.hasText(defaultName, "参数defaultName不能为空"); Assert.isTrue(!jdbcDataSource.isClosed(), "默认数据源已经关闭(isClosed)"); this.defaultName = defaultName; add(defaultName, jdbcDataSource); } /** * 获取默认数据源 */ public JdbcDataSource getDefault() { return getDataSource(defaultName); } /** * 获取默认数据源名称 */ public String getDefaultName() { return defaultName; } /** * 根据名称获取数据源 * * @param name 数据源名称 */ public JdbcDataSource getDataSource(String name) { return DATASOURCE_MAP.get(name); } /** * 判断数据源是否存在 * * @param name 数据源名称 */ public boolean hasDataSource(String name) { return DATASOURCE_MAP.containsKey(name); } /** * 添加数据源 * * @param name 数据源名称 * @param jdbcDataSource 数据源 */ public void add(String name, org.clever.graaljs.data.jdbc.builtin.adapter.JdbcDataSource jdbcDataSource) { Assert.notNull(jdbcDataSource, "参数jdbcDataSource不能为空"); Assert.isTrue(!DATASOURCE_MAP.containsKey(name), "数据源已经存在"); DATASOURCE_MAP.put(name, new JdbcDataSource(jdbcDataSource)); } /** * 添加数据源 * * @param name 数据源名称 * @param config 数据源配置 */ @SuppressWarnings("DuplicatedCode") public JdbcDataSource add(String name, Map<String, Object> config) { Assert.isTrue(!DATASOURCE_MAP.containsKey(name), "数据源已经存在"); config = InteropScriptToJavaUtils.Instance.convertMap(config); JdbcConfig jdbcConfig = getJdbcConfig(config); org.clever.graaljs.data.jdbc.builtin.adapter.JdbcDataSource jdbcDataSource = new org.clever.graaljs.data.jdbc.builtin.adapter.JdbcDataSource(jdbcConfig.getHikariConfig()); add(name, jdbcDataSource); return DATASOURCE_MAP.get(name); } /** * 删除数据源 * * @param name 数据源名称 */ @SneakyThrows public boolean del(String name) { Assert.isTrue(!Objects.equals(name, defaultName), "不能删除默认数据源"); JdbcDataSource jdbcDataSource = DATASOURCE_MAP.get(name); if (jdbcDataSource != null) { jdbcDataSource.close(); DATASOURCE_MAP.remove(name); } return jdbcDataSource != null; } /** * 删除所有数据源 */ @SneakyThrows public void delAll() { Iterator<Map.Entry<String, JdbcDataSource>> iterator = DATASOURCE_MAP.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, JdbcDataSource> entry = iterator.next(); entry.getValue().close(); iterator.remove(); } defaultName = null; } /** * 获取所有数据源名称 */ public Set allNames() { return DATASOURCE_MAP.keySet(); } /** * 获取数据源信息 * * @param name 数据源名称 */ public JdbcInfo getInfo(String name) { JdbcDataSource jdbcDataSource = getDataSource(name); return jdbcDataSource == null ? null : jdbcDataSource.getInfo(); } /** * 获取所有数据源信息 */ public Map<String, JdbcInfo> allInfos() { Map<String, JdbcInfo> map = new HashMap<>(DATASOURCE_MAP.size()); for (Map.Entry<String, JdbcDataSource> entry : DATASOURCE_MAP.entrySet()) { String name = entry.getKey(); map.put(name, getInfo(name)); } return map; } /** * 获取数据源状态 * * @param name 数据源名称 */ public JdbcDataSourceStatus getStatus(String name) { JdbcDataSource jdbcDataSource = getDataSource(name); return jdbcDataSource == null ? null : jdbcDataSource.getStatus(); } /** * 获取数据源状态 */ public Map<String, JdbcDataSourceStatus> allStatus() { Map<String, JdbcDataSourceStatus> map = new HashMap<>(DATASOURCE_MAP.size()); for (Map.Entry<String, JdbcDataSource> entry : DATASOURCE_MAP.entrySet()) { String name = entry.getKey(); map.put(name, getStatus(name)); } return map; } }
java
13
0.635501
179
27.883249
197
starcoderdata
<?php namespace MiniSkirt\Sugar\DS; class NA { public function __toString() { return 'NA'; } }
php
7
0.565217
32
10.6
10
starcoderdata
<?php namespace App\Repositories; /** * Class Repository * @package App\Repositories */ abstract class Repository implements RepositoryInterface { /** * @var */ protected $_model; /** * Repository constructor. */ public function __construct() { $this->setModel(); } /** * @return mixed */ abstract public function getModel(); /** * */ public function setModel(){ $this->_model = app()->make($this->getModel()); } /** * @return mixed */ public function all(){ return $this->_model->all(); } /** * @param $id * @return mixed */ public function find($id){ return $this->_model->find($id); } /** * @param $id * @return mixed */ public function findOrFail($id) { return $this->_model->findOrFail($id); } /** * @param $id * @return mixed */ public function destroy($id) { return $this->_model->destroy($id); } /** * @param array $attrs * @return mixed */ public function create($attrs = []) { return $this->_model->create($attrs); } }
php
12
0.487765
56
14.518987
79
starcoderdata
import { indicatormixin } from './indicatormixin'; import { accessors } from '../accessor'; import { ema_init } from './ema'; import { sma_init } from './sma'; import { atr_init } from './atr'; import { util } from '../util'; import { sroc_init } from './sroc'; import { vwap } from './vwap'; import { atrtrailingstop } from './atrtrailingstop'; import { heikinashi } from './heikinashi'; import { ichimoku } from './ichimoku'; import { macd } from './macd'; import { rsi } from './rsi'; import { adx } from './adx'; import { aroon } from './aroon'; import { stochastic } from './stochastic'; import { williams } from './williams'; import { bollinger } from './bollinger'; export const indicators = function(d3) { var indicatorMixin = indicatormixin(), accessor = accessors(), ema = ema_init(indicatorMixin, accessor.ohlc, ema_alpha_init), sma = sma_init(indicatorMixin, accessor.ohlc), atr = atr_init(indicatorMixin, accessor.ohlc, sma), circularbuffer = util().circularbuffer; return { atr: atr, atrtrailingstop: atrtrailingstop(indicatorMixin, accessor.ohlc, atr), ema: ema, heikinashi: heikinashi(indicatorMixin, accessor.ohlc, d3.min, d3.max), ichimoku: ichimoku(indicatorMixin, accessor.ohlc), macd: macd(indicatorMixin, accessor.ohlc, ema), rsi: rsi(indicatorMixin, accessor.ohlc, ema), sma: sma, wilderma: ema_init(indicatorMixin, accessor.ohlc, wilder_alpha_init), aroon: aroon(indicatorMixin, accessor.ohlc), roc: sroc_init(circularbuffer, indicatorMixin, accessor.ohlc, ema, 1), sroc: sroc_init(circularbuffer, indicatorMixin, accessor.ohlc, ema, 13), stochastic: stochastic(indicatorMixin, accessor.ohlc, ema), williams: williams(indicatorMixin, accessor.ohlc, ema), adx: adx(d3.max, indicatorMixin, accessor.ohlc, ema), bollinger: bollinger(indicatorMixin, accessor.ohlc, sma), vwap: vwap(indicatorMixin, accessor.ohlc) }; }; function ema_alpha_init(period) { return 2/(period+1); } function wilder_alpha_init(period) { return 1/period; }
javascript
14
0.683341
76
34.915254
59
starcoderdata
#include #include #include #include "LevelView.h" LevelView::LevelView() { } LevelView::LevelView(std::map<char, sf::Texture*> viewTextures) { loadTextures(); createTextures(viewTextures); } LevelView::~LevelView() { } void LevelView::loadTextures() { std::ifstream file("textures.txt"); std::string charLine; std::vector textureLine; if (file.is_open()) { while (file.good()) { getline(file, charLine); for (int i = 0; i < charLine.length(); i++) { textureLine.push_back(charLine[i]); } ArrangementView.push_back(textureLine); textureLine.clear(); charLine.clear(); } } } void LevelView::createTextures(std::map<char, sf::Texture*> viewTextures) { std::vector spritesLine; sf::Sprite chunk; for (int i = 0; i < ArrangementView.size(); i++) { for (int j = 0; j < ArrangementView[i].size(); j++) { if (ArrangementView[i][j] != '0') { //chunk.setRepeated(true); chunk.setTexture(*viewTextures[ArrangementView[i][j]]); chunk.setScale(1.0f, 1.0f); chunk.setPosition(float(j * 128), float(i * 128)); spritesLine.push_back(chunk); } } MatrixView.push_back(spritesLine); spritesLine.clear(); } }
c++
18
0.649552
73
18.47619
63
starcoderdata