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
package router import ( "strconv" "sync" "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/binding" "XustAutoSignIn/config" "XustAutoSignIn/utils" "XustAutoSignIn/variable" ) var runServer sync.Once const ( afternoonSignInCronString = "0 30 11 * * ?" nightSignInCronString = "0 30 17 * * ?" ) func Run() { runServer.Do(func() { cfg := config.GetConfig() // init server binding.Validator = new(ginValidator) // update validator gin.SetMode(gin.ReleaseMode) variable.Engine = gin.Default() // middleware // api and cron baseApiRouter() if cfg.XustAutoSignIn { xustAutoSignInApi() variable.Cron.AddFunc(afternoonSignInCronString, utils.XustSignInAfternoon) variable.Cron.AddFunc(nightSignInCronString, utils.XustSignInNight) } // run variable.Cron.Start() variable.Engine.Run(":" + strconv.Itoa(cfg.GetServerPort())) }) }
go
16
0.720339
78
21.47619
42
starcoderdata
using UnityEngine; using System.Collections; using System.Collections.Generic; public class MenuController : MonoBehaviour { string name = ""; string score = ""; List highscore; // Use this for initialization void Start() { // EventManager._instance._buttonClick += ButtonClicked; highscore = new List } void ButtonClicked(GameObject _obj) { print("Clicked button:" + _obj.name); } // Update is called once per frame void Update() { } void OnGUI() { GUILayout.BeginHorizontal(); GUILayout.Label("Name :"); name = GUILayout.TextField(name); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Score :"); score = GUILayout.TextField(score); GUILayout.EndHorizontal(); if (GUILayout.Button("Add Score")) { HighScoreManager._instance.SaveHighScore(name, System.Int32.Parse(score)); highscore = HighScoreManager._instance.GetHighScore(); } if (GUILayout.Button("Get LeaderBoard")) { highscore = HighScoreManager._instance.GetHighScore(); } if (GUILayout.Button("Clear Leaderboard")) { HighScoreManager._instance.ClearLeaderBoard(); } GUILayout.Space(60); GUILayout.BeginHorizontal(); GUILayout.Label("Name", GUILayout.Width(Screen.width / 2)); GUILayout.Label("Scores", GUILayout.Width(Screen.width / 2)); GUILayout.EndHorizontal(); GUILayout.Space(25); foreach (Scores _score in highscore) { GUILayout.BeginHorizontal(); GUILayout.Label(_score.name, GUILayout.Width(Screen.width / 2)); GUILayout.Label("" + _score.score, GUILayout.Width(Screen.width / 2)); GUILayout.EndHorizontal(); } } }
c#
16
0.59126
86
23.620253
79
starcoderdata
// // TestinDataConfig.h // TestinDataAnalysis // // Created by wubo on 2018/8/1. // Copyright © 2018年 testin. All rights reserved. // #import #import "TestinDataBugoutDelegate.h" #import "TestinDataAnalysisBugOut.h" #import "TestinAdView.h" #import "TestinADWebViewController.h" #import "TestinImageView.h" #import "TestinAdNative.h" @interface TestinDataConfig : NSObject /** * 广告appkey */ @property(nonatomic,copy)NSString* adAppKey; /** *设置是否禁止广告控件自动跳转页面 默认为NO 不禁止 设置为YES 可以跳转到用户需要的页面 不使用平台提供的页面 */ @property(nonatomic,assign)BOOL forbidAutoAdSkip; /* * 是否开启打印广告模块日志 */ @property(nonatomic,assign)BOOL printAdLog; /* * 设置广告平台serverUrl 不设置会使用默认的线上地址 */ @property(nonatomic,copy)NSString * adServerUrl; /** *ABTestappkey */ @property(nonatomic,copy)NSString* abAppKey; /** *下拉配置url */ @property(nonatomic,copy)NSString* configUrl; /** *上报数据url */ @property(nonatomic,copy)NSString* uploadUrl; /** *AB上报和下拉url */ @property(nonatomic,copy)NSString* abServerUrl; /** *自定义DataSocketUrl */ @property(nonatomic,copy)NSString* dataSocketUrl; /** *自定义ABSocketUrl */ @property(nonatomic,copy)NSString* abSocketUrl; /** 悬浮按钮(小助手),延迟显示的时间间隔。默认为:1 */ @property(nonatomic,assign)NSTimeInterval debugTouchAssistDelayInterval; /** 可视化图片截图压缩比。默认为:0.5 如果希望可视化编辑图片像素要求不高 可以设置0.2 左右 保证速率 */ @property(nonatomic,assign)float visualImageCompressRate; /** * 设置是否显示调试悬浮按钮 集成了可视化和集成调试入口 */ @property(nonatomic,assign) BOOL debugTouchAssist;//默认是NO /* * 设置是否开启打印AB模块日志 * */ @property(nonatomic,assign)BOOL printABLog; /** 设置AB多维标签是否携带自定义标签 默认为NO */ @property(nonatomic,assign)BOOL isMultidimensionalWithCustomLabel; //========以下bug收集相关======== /** * * 数据通知的代理 */ @property(nonatomic, strong) id delegate; /** *Exception monitor enabled, default YES. *启用异常监视器,默认:YES */ @property(nonatomic, assign) BOOL enabledMonitorException; /** *是否开启崩溃截图,默认:NO */ @property(nonatomic, assign) BOOL crashScreenshot; /** *Enabled feedback, default NO. *启用摇一摇反馈,默认:NO */ @property(nonatomic, assign) BOOL enabledShakeFeedback; /** * *Response speed settings, the greater the value of the slower response speed, the smaller the faster the response, the value is too large may lose response, the default 3.0 *响应速度设置值越大,响应速度越慢,响应越快,值越大,则可能丢失响应,默认为3.0。 * * */ @property(nonatomic, assign) NSTimeInterval shakeSenseSpeed; /** * only wifi report data, default YES. * 只有WiFi报告数据,默认:YES */ @property(nonatomic, assign) BOOL reportOnlyWIFI; /** * use user location info, default NO. * 是否开启用户定位信息。默认:NO * 如APP上有定位设置,推荐设置为:YES */ @property(nonatomic, assign) BOOL useLocationInfo; /** * Whether or not to open the user's operation steps,default YES. * 是否开启用户操作步骤。默认:YES */ @property(nonatomic, assign) BOOL enableUserSteps; /** *Open the system log. default NO *开启系统日志。默认:NO */ @property(nonatomic, assign) BOOL enableSysLog; /** 屏幕快照模式 0 为App模式 1为游戏类模式 默认为游戏类模式 */ @property(nonatomic,assign)int snapshotMode; /* * 设置是否打印BugOut日志 * */ @property(nonatomic,assign)BOOL printBugOutLog; // ---base config optimize--- /** 设置是否自动触发App事件(start&end事件) */ @property(nonatomic,assign)BOOL supportAutoAppTrack; /** 设置是否开始自动埋点viewClick事件 */ @property(nonatomic,assign)BOOL supportAutoViewClickTrack; /** 设置是否开始自动埋点viewPage事件 */ @property(nonatomic,assign)BOOL supportAutoViewPageTrack; /** 针对UIControl控件以及子类 设置是否对已经可视化埋点的位置支持主动埋点 默认是不支持,限制的 */ @property(nonatomic,assign)BOOL supportUIControlAutoTrackForAlreadyVTrack; /** 设置是否支持触摸开始时候track 此方法主要针对UIControl 实现了UITouchDown 事件的情况 */ @property(nonatomic,assign)BOOL supportTouchBeginState; /** 是否支持获取IDFA */ @property(nonatomic,assign)BOOL enableIDFA; /** 设置主窗口的属性名称 不设置 默认值 读取window属性 需要在窗口初始化完毕后调用 */ @property(nonatomic,assign)SEL widowSelector; /** 设置可视化编辑的UIWindow 默认值取application 索引为0的窗口编辑 建议设置程序的主窗口 */ @property (nonatomic, strong) UIWindow *visualWindow; /** 设置是否有智能分流试验 如果有智能分流试验 为了数据准确性请设置 isAutoShuntMode=YES */ @property(nonatomic,assign)BOOL isAutoShuntMode; /** 设置是否取消使用图片指纹标识符 取消(YES) 不取消(NO) */ @property(nonatomic,assign)BOOL fobitImageIdentification; +(TestinDataConfig*)shareConfig; @end
c
5
0.749578
173
19.418719
203
starcoderdata
private static Encoding? GetEncoding(string? charset) { Encoding? encoding = null; if (charset != null) { try { // Remove at most a single set of quotes. if (charset.Length > 2 && charset[0] == '\"' && charset[^1] == '\"') { encoding = Encoding.GetEncoding(charset[1..^1]); } else { encoding = Encoding.GetEncoding(charset); } } catch (ArgumentException e) { throw new InvalidOperationException("The character set provided in ContentType is invalid.", e); } } return encoding; }
c#
20
0.387209
116
32.115385
26
inline
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/documentai/v1beta1/document_understanding.proto package com.google.cloud.documentai.v1beta1; public interface ProcessDocumentResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.documentai.v1beta1.ProcessDocumentResponse) com.google.protobuf.MessageOrBuilder { /** * * Information about the input file. This is the same as the corresponding * input config in the request. * * * input_config = 1; * @return Whether the inputConfig field is set. */ boolean hasInputConfig(); /** * * Information about the input file. This is the same as the corresponding * input config in the request. * * * input_config = 1; * @return The inputConfig. */ com.google.cloud.documentai.v1beta1.InputConfig getInputConfig(); /** * * Information about the input file. This is the same as the corresponding * input config in the request. * * * input_config = 1; */ com.google.cloud.documentai.v1beta1.InputConfigOrBuilder getInputConfigOrBuilder(); /** * * The output location of the parsed responses. The responses are written to * this location as JSON-serialized `Document` objects. * * * output_config = 2; * @return Whether the outputConfig field is set. */ boolean hasOutputConfig(); /** * * The output location of the parsed responses. The responses are written to * this location as JSON-serialized `Document` objects. * * * output_config = 2; * @return The outputConfig. */ com.google.cloud.documentai.v1beta1.OutputConfig getOutputConfig(); /** * * The output location of the parsed responses. The responses are written to * this location as JSON-serialized `Document` objects. * * * output_config = 2; */ com.google.cloud.documentai.v1beta1.OutputConfigOrBuilder getOutputConfigOrBuilder(); }
java
9
0.708163
106
34
70
starcoderdata
/** * @file MarchingCubes.h * @author * @author Math Dept, PUC-Rio * @version 0.2 * @date 12/08/2002 * * @brief MarchingCubes Algorithm */ //________________________________________________ #ifndef _MARCHINGCUBES_H_ #define _MARCHINGCUBES_H_ #include #include //_____________________________________________________________________________ // types /** unsigned char alias */ typedef unsigned char uchar ; /** signed char alias */ typedef signed char schar ; /** isovalue alias */ typedef float real ; //----------------------------------------------------------------------------- // Vertex structure /** \struct Vertex "MarchingCubes.h" MarchingCubes * Position and normal of a vertex * \brief vertex structure * \param x X coordinate * \param y Y coordinate * \param z Z coordinate * \param nx X component of the normal * \param ny Y component of the normal * \param nz Z component of the normal */ typedef struct { real x, y, z ; /**< Vertex coordinates */ real nx, ny, nz ; /**< Vertex normal */ } Vertex ; //----------------------------------------------------------------------------- // Triangle structure /** \struct Triangle "MarchingCubes.h" MarchingCubes * Indices of the oriented triange vertices * \brief triangle structure * \param v1 First vertex index * \param v2 Second vertex index * \param v3 Third vertex index */ typedef struct { int v1,v2,v3 ; /**< Triangle vertices */ } Triangle ; //_____________________________________________________________________________ //_____________________________________________________________________________ /** Marching Cubes algorithm wrapper */ /** \class MarchingCubes * \brief Marching Cubes algorithm. */ class MarchingCubes //----------------------------------------------------------------------------- { // Constructors public : /** * Main and default constructor * \brief constructor * \param size_x width of the grid * \param size_y depth of the grid * \param size_z height of the grid */ MarchingCubes ( const int size_x = -1, const int size_y = -1, const int size_z = -1 ) ; //----------------------------------------------------------------------------- // Accessors public : /** accesses the number of vertices of the generated mesh */ inline const int nverts() const { return _vertices.size() ; } /** accesses the number of triangles of the generated mesh */ inline const int ntrigs() const { return _triangles.size() ; } /** accesses a specific vertex of the generated mesh */ inline const Vertex * vert( const int i ) const { if( i < 0 || i >= nverts() ) return ( Vertex *)NULL ; return _vertices.data() + i ; } /** accesses a specific triangle of the generated mesh */ inline const Triangle * trig( const int i ) const { if( i < 0 || i >= ntrigs() ) return (Triangle*)NULL ; return _triangles.data() + i ; } /** accesses the vertex buffer of the generated mesh */ inline Vertex *vertices () { return _vertices.data() ; } /** accesses the triangle buffer of the generated mesh */ inline Triangle *triangles() { return _triangles.data() ; } /** accesses the width of the grid */ inline const int size_x() const { return _size_x ; } /** accesses the depth of the grid */ inline const int size_y() const { return _size_y ; } /** accesses the height of the grid */ inline const int size_z() const { return _size_z ; } /** * changes the size of the grid * \param size_x width of the grid * \param size_y depth of the grid * \param size_z height of the grid */ inline void set_resolution( const int size_x, const int size_y, const int size_z ) { _size_x = size_x ; _size_y = size_y ; _size_z = size_z ; } /** * selects wether the algorithm will use the enhanced topologically controlled lookup table or the original MarchingCubes * \param originalMC true for the original Marching Cubes */ inline void set_method ( const bool originalMC = false ) { _originalMC = originalMC ; } // Data access /** * accesses a specific cube of the grid * \param i abscisse of the cube * \param j ordinate of the cube * \param k height of the cube */ inline const float get_data(const arma::ivec3 &coord) const { return _data[ coord(0) + coord(1)*_size_x + coord(2)*_size_x*_size_y]; } /** * sets a specific cube of the grid * \param val new value for the cube * \param i abscisse of the cube * \param j ordinate of the cube * \param k height of the cube */ inline void set_data ( const real val, const int i, const int j, const int k ) { _data[ i + j*_size_x + k*_size_x*_size_y] = val ; } // Data initialization /** inits temporary structures (must set sizes before call) : the grid and the vertex index per cube */ void init_temps () ; /** inits all structures (must set sizes before call) : the temporary structures and the mesh buffers */ void init_all () ; //----------------------------------------------------------------------------- // Algorithm public : /** * Main algorithm : must be called after init_all * \param iso isovalue */ void run( real iso = (real)0.0 ) ; protected : /** tesselates one cube */ void process_cube (float *cube); /** tests if the components of the tesselation of the cube should be connected through the interior of the cube */ bool test_interior( schar s, float *cube ) ; //----------------------------------------------------------------------------- // Operations protected : /** * computes almost all the vertices of the mesh by interpolation along the cubes edges * \param iso isovalue */ void compute_intersection_points( real iso ) ; /** * routine to add a triangle to the mesh * \param trig the code for the triangle as a sequence of edges index * \param n the number of triangles to produce * \param v12 the index of the interior vertex to use, if necessary */ void add_triangle ( const char* trig, char n, int v12 = -1 ) ; int add_vertex(const arma::ivec3 &grid_coord, const arma::ivec3 &dir, int corner, float *cube); /** adds a vertex inside the current cube */ int add_c_vertex() ; /** * interpolates the horizontal gradient of the implicit function at the lower vertex of the specified cube * \param i abscisse of the cube * \param j ordinate of the cube * \param k height of the cube */ real get_x_grad( const int i, const int j, const int k ) const ; /** * interpolates the longitudinal gradient of the implicit function at the lower vertex of the specified cube * \param i abscisse of the cube * \param j ordinate of the cube * \param k height of the cube */ real get_y_grad( const int i, const int j, const int k ) const ; /** * interpolates the vertical gradient of the implicit function at the lower vertex of the specified cube * \param i abscisse of the cube * \param j ordinate of the cube * \param k height of the cube */ real get_z_grad( const int i, const int j, const int k ) const ; /** * accesses the pre-computed vertex index on the lower horizontal edge of a specific cube * \param i abscisse of the cube * \param j ordinate of the cube * \param k height of the cube */ inline int get_x_vert( const int i, const int j, const int k ) const { return _x_verts[ i + j*_size_x + k*_size_x*_size_y] ; } /** * accesses the pre-computed vertex index on the lower longitudinal edge of a specific cube * \param i abscisse of the cube * \param j ordinate of the cube * \param k height of the cube */ inline int get_y_vert( const int i, const int j, const int k ) const { return _y_verts[ i + j*_size_x + k*_size_x*_size_y] ; } /** * accesses the pre-computed vertex index on the lower vertical edge of a specific cube * \param i abscisse of the cube * \param j ordinate of the cube * \param k height of the cube */ inline int get_z_vert( const int i, const int j, const int k ) const { return _z_verts[ i + j*_size_x + k*_size_x*_size_y] ; } /** * sets the pre-computed vertex index on the lower horizontal edge of a specific cube * \param val the index of the new vertex * \param i abscisse of the cube * \param j ordinate of the cube * \param k height of the cube */ inline void set_x_vert( const int val, const int i, const int j, const int k ) { _x_verts[ i + j*_size_x + k*_size_x*_size_y] = val ; } /** * sets the pre-computed vertex index on the lower longitudinal edge of a specific cube * \param val the index of the new vertex * \param i abscisse of the cube * \param j ordinate of the cube * \param k height of the cube */ inline void set_y_vert( const int val, const int i, const int j, const int k ) { _y_verts[ i + j*_size_x + k*_size_x*_size_y] = val ; } /** * sets the pre-computed vertex index on the lower vertical edge of a specific cube * \param val the index of the new vertex * \param i abscisse of the cube * \param j ordinate of the cube * \param k height of the cube */ inline void set_z_vert( const int val, const int i, const int j, const int k ) { _z_verts[ i + j*_size_x + k*_size_x*_size_y] = val ; } //----------------------------------------------------------------------------- // Elements protected : bool _originalMC ; /**< selects wether the algorithm will use the enhanced topologically controlled lookup table or the original MarchingCubes */ int _size_x ; /**< width of the grid */ int _size_y ; /**< depth of the grid */ int _size_z ; /**< height of the grid */ std::vector _data; std::vector _x_verts ; /**< pre-computed vertex indices on the lower horizontal edge of each cube */ std::vector _y_verts ; /**< pre-computed vertex indices on the lower longitudinal edge of each cube */ std::vector _z_verts ; /**< pre-computed vertex indices on the lower vertical edge of each cube */ std::vector _vertices ; /**< vertex buffer */ std::vector _triangles ; /**< triangle buffer */ int _i ; /**< abscisse of the active cube */ int _j ; /**< height of the active cube */ int _k ; /**< ordinate of the active cube */ uchar _lut_entry ; /**< cube sign representation in [0..255] */ uchar _case ; /**< case of the active cube in [0..15] */ uchar _config ; /**< configuration of the active cube */ uchar _subconfig ; /**< subconfiguration of the active cube */ }; //_____________________________________________________________________________ #endif // _MARCHINGCUBES_H_
c
12
0.591631
154
37.390071
282
starcoderdata
def __load_vocab(self, vocab_path): """Load the word dictionary. """ with open(vocab_path, 'r', encoding='utf-8') as fin: vocab_size = 0 for line in fin.readlines(): fields = line.strip().split('\t') assert len(fields) >= 2 word = fields[1] self.__max_word_len = max(self.__max_word_len, len(word)) self.__vocab.add(word) vocab_size += 1
python
13
0.465696
73
39.166667
12
inline
package com.haibowen.test; import com.haibowen.dao.AdminDao; import com.haibowen.entil.Admin; import com.haibowen.im.AdminDaoIm; public class Test { public static void main(String[] args) { AdminDao adminDao=new AdminDaoIm(); Admin admin=adminDao.selectOne("123", "456"); System.out.println(admin); } }
java
8
0.747253
47
21.75
16
starcoderdata
import dbg from 'debug'; const debug = dbg('tokenizer'); import { ESCAPES } from './tokens'; function* tokenize(text) { text = text.trim().toLowerCase(); for (const name in ESCAPES) { const token = ESCAPES[name]; text = text.replace(token.pattern, ` `); } const tokens = text.split(/\s+/); for (const token of tokens) { if (token === "") continue; yield token; } return; } export default tokenize;
javascript
11
0.613483
54
18.391304
23
starcoderdata
import Vue from 'vue'; Vue.component('alunos', { props:['aluno_edit'], template: ` <select class="form-control select2" multiple="multiple" data-placeholder="Digite o nome do aluno" style="width: 100%;" name="alunos[]"> <aluno v-for="task in tasks" :name="task.nome +' - '+ task.turma.turma " :aluno_id="task.id" :aluno_edit="aluno_edit"> `, data(){ return { tasks: [ ] } }, mounted(){ axios.get('/alunos/apiSelectAluno').then(response => this.tasks = response.data); } }); Vue.component('aluno', { props: ['aluno_id','name', 'aluno_edit'], template: ` <option :value="aluno_id" v-if="aluno_id === aluno_edit" selected="selected">{{ name }} <option :value="aluno_id" v-else >{{ name }} ` }); var app = new Vue({ el: '#formulario' });
javascript
9
0.604284
138
22.972973
37
starcoderdata
package org.jugbd.mnet.domain; import javax.persistence.*; import javax.validation.constraints.NotNull; /** * Created by * * @since 9/21/14. */ @Entity public class Attachment extends PersistentObject { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotNull private String fileName; @NotNull private String mimeType; @Lob @Column(length = 3145728, nullable = false) // 3 MB private byte[] data; @Column(length = 3000) private String comment; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getMimeType() { return mimeType; } public void setMimeType(String mimeType) { this.mimeType = mimeType; } public byte[] getData() { return data; } public void setData(byte[] data) { this.data = data; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } }
java
9
0.604217
55
16.614286
70
starcoderdata
def __init__(self, zha_device, listeners, keepalive_interval=7200, **kwargs): """Init ZHA endpoint entity.""" ieee = zha_device.ieee ieeetail = ''.join(['%02x' % (o, ) for o in ieee[-4:]]) unique_id = None if zha_device.manufacturer is not None and \ zha_device.model is not None: unique_id = "{}_{}_{}".format( slugify(zha_device.manufacturer), slugify(zha_device.model), ieeetail, ) else: unique_id = str(ieeetail) kwargs['component'] = 'zha' super().__init__(unique_id, zha_device, listeners, skip_entity_id=True, **kwargs) self._keepalive_interval = keepalive_interval self._device_state_attributes.update({ 'nwk': '0x{0:04x}'.format(zha_device.nwk), 'ieee': str(zha_device.ieee), 'lqi': zha_device.lqi, 'rssi': zha_device.rssi, }) self._should_poll = True self._battery_listener = self.cluster_listeners.get(LISTENER_BATTERY)
python
12
0.517762
79
37.862069
29
inline
def app_config(app_config): """Get app config.""" app_config["APP_ALLOWED_HOSTS"] = ["localhost"] app_config["CELERY_TASK_ALWAYS_EAGER"] = True app_config["JSONSCHEMAS_SCHEMAS"] = [ "acquisition", "document_requests", "documents", "eitems", "ill", "internal_locations", "items", "invenio_opendefinition", "invenio_records_files", "loans", "locations", "series", "vocabularies", ] return app_config
python
7
0.535238
51
25.3
20
inline
package model // DolbyDigitalCenterMixLevel : DolbyDigitalCenterMixLevel model type DolbyDigitalCenterMixLevel string // List of possible DolbyDigitalCenterMixLevel values const ( DolbyDigitalCenterMixLevel_PLUS_3_DB DolbyDigitalCenterMixLevel = "PLUS_3_DB" DolbyDigitalCenterMixLevel_PLUS_1_5_DB DolbyDigitalCenterMixLevel = "PLUS_1_5_DB" DolbyDigitalCenterMixLevel_ZERO_DB DolbyDigitalCenterMixLevel = "ZERO_DB" DolbyDigitalCenterMixLevel_MINUS_1_5_DB DolbyDigitalCenterMixLevel = "MINUS_1_5_DB" DolbyDigitalCenterMixLevel_MINUS_3_DB DolbyDigitalCenterMixLevel = "MINUS_3_DB" DolbyDigitalCenterMixLevel_MINUS_4_5_DB DolbyDigitalCenterMixLevel = "MINUS_4_5_DB" DolbyDigitalCenterMixLevel_MINUS_6_DB DolbyDigitalCenterMixLevel = "MINUS_6_DB" DolbyDigitalCenterMixLevel_MINUS_INFINITY_DB DolbyDigitalCenterMixLevel = "MINUS_INFINITY_DB" )
go
7
0.795722
94
54
17
starcoderdata
@Test public void testDeleteInvalidParameters() throws Exception { String testSegmentName = "foo"; SegmentRollingPolicy policy = new SegmentRollingPolicy(1); // Force rollover after each byte. @Cleanup TestContext testContext = getTestContext(); AssertExtensions.assertFutureThrows( "Concat succeeded on missing segment.", testContext.chunkedSegmentStorage.delete(null, null), ex -> ex instanceof IllegalArgumentException); }
java
8
0.666667
101
42.583333
12
inline
var classv8_1_1internal_1_1_load_handler = [ [ "ConvertHoleBits", "classv8_1_1internal_1_1_load_handler_1_1_convert_hole_bits.html", null ], [ "DescriptorValueIndexBits", "classv8_1_1internal_1_1_load_handler_1_1_descriptor_value_index_bits.html", null ], [ "DoNegativeLookupOnReceiverBits", "classv8_1_1internal_1_1_load_handler_1_1_do_negative_lookup_on_receiver_bits.html", null ], [ "ElementsKindBits", "classv8_1_1internal_1_1_load_handler_1_1_elements_kind_bits.html", null ], [ "FieldOffsetBits", "classv8_1_1internal_1_1_load_handler_1_1_field_offset_bits.html", null ], [ "IsDoubleBits", "classv8_1_1internal_1_1_load_handler_1_1_is_double_bits.html", null ], [ "IsInobjectBits", "classv8_1_1internal_1_1_load_handler_1_1_is_inobject_bits.html", null ], [ "IsJsArrayBits", "classv8_1_1internal_1_1_load_handler_1_1_is_js_array_bits.html", null ], [ "KindBits", "classv8_1_1internal_1_1_load_handler_1_1_kind_bits.html", null ], [ "Kind", "classv8_1_1internal_1_1_load_handler.html#af9bbc69b2507ed53c01fced3e2b388ad", [ [ "kForElements", "classv8_1_1internal_1_1_load_handler.html#af9bbc69b2507ed53c01fced3e2b388ada72df31ca1514786e0585c79856e87b28", null ], [ "kForFields", "classv8_1_1internal_1_1_load_handler.html#af9bbc69b2507ed53c01fced3e2b388ada61a80f3dc92c1a24295324936aa0c5e9", null ], [ "kForConstants", "classv8_1_1internal_1_1_load_handler.html#af9bbc69b2507ed53c01fced3e2b388ada5571a5d4410bcc8ff840a47ec4014860", null ] ] ], [ "EnableNegativeLookupOnReceiver", "classv8_1_1internal_1_1_load_handler.html#ae52fe09bb9e14b157d3acd97c5564e71", null ], [ "LoadConstant", "classv8_1_1internal_1_1_load_handler.html#a3464f4e875031ec720a7576d18259c01", null ], [ "LoadElement", "classv8_1_1internal_1_1_load_handler.html#ae1407ea050d0a147f74645379643a442", null ], [ "LoadField", "classv8_1_1internal_1_1_load_handler.html#a9bfe3dc627c82e3255897e29e1a94a6d", null ], [ "STATIC_ASSERT", "classv8_1_1internal_1_1_load_handler.html#a5e2c5778a06ba1dc3087a8276916fd4f", null ], [ "STATIC_ASSERT", "classv8_1_1internal_1_1_load_handler.html#adebe41ef56edf9e850f119764be882dd", null ], [ "STATIC_ASSERT", "classv8_1_1internal_1_1_load_handler.html#ab209a7751b039b320522fb830282c97b", null ], [ "kFirstPrototypeIndex", "classv8_1_1internal_1_1_load_handler.html#a67e2564db8ed9d0ebbe4a9ff2cf8ca98", null ], [ "kHolderCellIndex", "classv8_1_1internal_1_1_load_handler.html#a752cb23bd66f4bf965071a83f86dadf7", null ], [ "kHolderCellOffset", "classv8_1_1internal_1_1_load_handler.html#a702ed63036482eb8bf7bb5edab0a84b6", null ], [ "kSmiHandlerIndex", "classv8_1_1internal_1_1_load_handler.html#ac920573af481066d7ae400b3a2055d6f", null ], [ "kSmiHandlerOffset", "classv8_1_1internal_1_1_load_handler.html#adaff8d98ac17ca4dbb3591de40f424c6", null ], [ "kValidityCellIndex", "classv8_1_1internal_1_1_load_handler.html#ab9c4a68abf48b002bd305e1a054d346f", null ], [ "kValidityCellOffset", "classv8_1_1internal_1_1_load_handler.html#a88b9f7b5fd07f7e04f821f5f9ed433c2", null ] ];
javascript
8
0.750809
143
98.709677
31
starcoderdata
import os from Common import pstfast import argparse import cPickle import operator def suggest(ctx_files, model_file, to_file=1): freq_dict = cPickle.load(open(model_file)) most_common = map(lambda x : x[0], freq_dict.most_common()[:10]) for ctxf in ctx_files: output_file = open(ctxf + "_FREQ.gen", "w") f = open(ctxf, 'r') for line in open(ctxf): print >> output_file, '\t'.join(most_common) f.close() output_file.close()
python
12
0.59252
68
24.4
20
starcoderdata
package storagekit import ( "context" "io" ) type PutObjectOptions struct { ContentType string } // Provide a simplifier interface to upload file type Storage interface { // Endpoint returns the endpoint of the object storage Endpoint() string // Bucket returns the bucket name in the object storage Bucket() string // PutObject add an object into the storage bucket PutObject(ctx context.Context, objectName string, reader io.Reader, objectSize int64, opts PutObjectOptions) error }
go
8
0.776735
115
23.227273
22
starcoderdata
int Player::get_input() { static int failCount = 3;//Retry but not indefinitely. int input; //Players input. std::cout << "\nEnter your choice:\n"; std::cin >> input; if (sanitize_input(input)) { if (input == 9) { return -1; } else { return input; } } else { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); failCount -= 1; if (failCount > 0) { std::cout << "\nBad input... try again\n"; get_input(); } else { if (failCount <= 0) { std::cout << "Three strikes and your out!\n"; std::cout << "Now exitng program. Bye!\n"; return -1; } } } }
c++
16
0.564465
69
20.233333
30
inline
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using Microsoft.Practices.Unity; namespace OutlookStyle.Infrastructure.ModelVisualization { /// /// Allows you to register mappigns between a model and a view that can /// visualize that model. /// public class ModelVisualizationRegistry : IModelVisualizationRegistry { private readonly IUnityContainer container; private List modelVisualizations; /// /// Initializes a new instance of the <see cref="ModelVisualizationRegistry"/> class. /// /// <param name="container">The container. public ModelVisualizationRegistry(IUnityContainer container) { this.container = container; this.modelVisualizations = new List } /// /// Register a visualization /// /// <typeparam name="TModel">The type of the model /// <typeparam name="TView">The type of the view public void Register<TModel, TView>() { this.modelVisualizations.Add(new ModelVisualizationRegistration() {ModelType = typeof(TModel), ViewType = typeof(TView)}); } /// /// Get the list of registered visualizations /// /// public IEnumerable ModelVisualizations { get { return this.modelVisualizations; } } /// /// Create a visualization for the specified object. /// /// <param name="objectToVisualize"> /// public FrameworkElement CreateVisualization(object objectToVisualize) { if (objectToVisualize == null) throw new ArgumentNullException("objectToVisualize"); ModelVisualizationRegistration registration = GetRegistrationForExactType(objectToVisualize); if (registration == null) { registration = GetRegistrationForInterface(objectToVisualize); } if (registration == null) { if (!MustVisualize(objectToVisualize)) return objectToVisualize as FrameworkElement; throw new InvalidOperationException(string.Format("No Visualization registered for {0}", objectToVisualize.GetType())); } return CreateVisualization(objectToVisualize, registration); } private ModelVisualizationRegistration GetRegistrationForInterface(object objectToVisualize) { return this.ModelVisualizations.FirstOrDefault((reg) => objectToVisualize.GetType().GetInterfaces().Contains(reg.ModelType)); } private ModelVisualizationRegistration GetRegistrationForExactType(object objectToVisualize) { return this.ModelVisualizations.FirstOrDefault((reg) => reg.ModelType == objectToVisualize.GetType()); } /// /// Should the specified object be visualized? This implementation only requires visualization for NON framework elements /// /// <param name="objectToVisualize">The object to visualize. /// protected virtual bool MustVisualize(object objectToVisualize) { return !(objectToVisualize is FrameworkElement); } /// /// Creates the visualization for the specified object. /// /// <param name="objectToVisualize">The object to visualize. /// <param name="registration">The registration. /// protected virtual FrameworkElement CreateVisualization(object objectToVisualize, ModelVisualizationRegistration registration) { var view = this.container.Resolve(registration.ViewType) as FrameworkElement; return new ModelVisualizer(objectToVisualize, view); } } }
c#
18
0.623762
137
36.669565
115
starcoderdata
// Copyright 2021 Google LLC // // 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 // // https://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. #ifndef TWO_COLOR_H_ #define TWO_COLOR_H_ #include #include #include #include namespace gvisor { // Buffer painter. // Distinctive data patterns are used to make buffer ownership traceable. // (This is one of many possible schemes for achieving that goal. // It's a rough experimental compromise between trains of thought.) // Identity is carried by the "colors", i.e. byte values, that a buffer // contains. // Two colors are used, with a byte encoding scheme providing 899 = 29 * 31 // distinguishable buffer owners. // Given an owner, and thus a pair of colors, the sequencing of the colors // is used for several purposes: // a. to (loosely) distinguish multiple buffers owned by the same owner // b. to (loosely) distinguish cache lines and pages etc of a given buffer // c. to reduce the probability that arbitrary memory resembles these buffers class TwoColor { public: static constexpr size_t kPeriod = 7; TwoColor() {} // Paints 'buffer' with prescribed pattern. static void Paint(size_t identity, size_t buffer_id, uint8_t *buffer, size_t length); // Returns expected color. static uint8_t Color(size_t identity, size_t buffer_id, size_t position) { return ColorSelector(buffer_id, position) ? HighColor(identity) : LowColor(identity); } // Returns length of longest consistently colored prefix of 'buffer'. static size_t ColorMatch(size_t identity, size_t phase, const uint8_t *buffer, size_t length); struct Identity { size_t identity; size_t length; size_t phase; // Modulo kPeriod std::string ToString() const; }; // Returns identity of longest consistently-painted prefix of 'buffer'. // If the length is more than a few bytes, the probability is high that the // buffer really belongs to the indicated owner. static std::optional Identify(const uint8_t *buffer, size_t length); // Returns a string describing 'color'. static std::string CrackColor(size_t local_identity, uint8_t color); private: // Color byte format: // High order 3 bits: tag, valid values: kLowTag, kHighTag identify modulus // Low order 5 bits: identity modulo kLowPrime or kHighPrime static constexpr uint8_t kLowPrime = 29; static constexpr uint8_t kHighPrime = 31; static constexpr uint8_t kLowTag = 0x80; static constexpr uint8_t kHighTag = 0x40; static uint8_t Tag(uint8_t color) { return color & 0xe0; } static uint8_t Residue(uint8_t color) { return color & 0x1f; } static uint8_t LowColor(size_t identity) { return kLowTag | (identity % kLowPrime); } static uint8_t HighColor(size_t identity) { return kHighTag | (identity % kHighPrime); } static bool IsValidLowColor(uint8_t); static bool IsValidHighColor(uint8_t); // Defines a periodic in 'position' color pattern, with period relatively // prime to most everything. Phase is shifted by 'buffer_id'. static size_t ColorSelector(size_t buffer_id, size_t position) { size_t v = buffer_id + position; return (v % kPeriod) < (kPeriod / 2) ? 0 : 1; } struct CandidateColors { size_t identity; size_t phase; }; // Returns candidate color scheme of 'buffer', or nullopt if none. static std::optional Candidates(const uint8_t *buffer, size_t length); // Returns identity given colors. static size_t Crt(uint8_t c_low, uint8_t c_high); }; } // namespace gvisor #endif // TWO_COLOR_H_
c
13
0.690538
80
35.353448
116
starcoderdata
import { readFileSync } from 'fs'; import { join } from 'path'; import { fileURLToPath } from 'url'; import { analyze } from '../src/index.js'; const __filename = fileURLToPath(import.meta.url); const ast = JSON.parse( readFileSync(join(__filename, '../svelte-compiler-3.15.0.json')) ); const runs = []; const ms = 1e6; const start = process.hrtime.bigint(); while (process.hrtime.bigint() - start < 1000 * ms) { const run_start = process.hrtime.bigint(); analyze(ast); runs.push(process.hrtime.bigint() - run_start); } const total = runs.reduce((total, t) => total + t, BigInt(0)); const avg = Number(total / BigInt(runs.length)); console.log(`avg. elapsed time: ${avg / ms}ms over ${runs.length} runs`)
javascript
10
0.673854
72
25.5
28
starcoderdata
#ifndef __ICALCAP_H__ #define __ICALCAP_H__ #include /* * Opaque objects */ typedef struct _icalcap icalcap; typedef struct _icalerror icalerror; typedef struct _icalcap_message icalcap_message; /* * Callback */ typedef int (*icalcap_msg_handler)(const icalcap_message *msg); /* * icalcap member functions */ void icalcap_free(icalcap *cap); int icalcap_stop(icalcap *cap); const char *icalcap_get_username(const icalcap *cap); /* * icalcap_message member functions */ struct _icalcap_message { icalcap *cap; int type; icalcomponent *comp; }; icalcap_message*icalcap_message_new(const icalcap *cap, const icalcomponent *comp); icalcap_message*icalcap_message_new_reply(const icalcap_message *capmsg, const icalcomponent *comp); void icalcap_message_free(icalcap_message *capmsg); int icalcap_message_reply_error(const icalcap_message *orig, enum icalrequeststatus status, const char *msg, const char *debug); int icalcap_message_reply_component(const icalcap_message *orig, icalcomponent *comp); int icalcap_message_send(icalcap_message *capmsg); icalcomponent *icalcap_message_sync_send(icalcap_message *capmsg, int timeout); #endif
c
8
0.736755
100
24.702128
47
starcoderdata
// // Created by Harrison on 9/20/2016. // #ifndef CS430_PROJ2_RAYCASTER_JSON_H #define CS430_PROJ2_RAYCASTER_JSON_H #include #include typedef enum { false, true } bool; /** * The possible types of json element values. */ typedef enum { JSON_STRING, JSON_NUMBER, JSON_BOOLEAN, JSON_NULL, JSON_OBJECT, JSON_ARRAY } JsonElementType; /** * A node in a json structure */ typedef struct _JsonElement { JsonElementType type; union { char* dataString; double dataNumber; bool dataBool; char dataNull; struct _JsonElement* dataElements; } data; int count; char** keys; } JsonElement; typedef JsonElement* JsonElementRef; /** * Parses a json file and stores the data at the passed JsonElement root * @param filePointer - The file to read from * @param root - The reference to the root element to store the data at * @return 1 if success, 0 if failure */ int json_parse(FILE* filePointer, JsonElementRef root); /** * Disposes a json element, and frees any memory its allocated * @param root - The root element of the json structure * @return 1 if success, 0 if failure */ int json_dispose(JsonElementRef root); /** * Checks if a JSON_OBJECT has the specified key * @param element - The element to check * @param key - The key to search for * @return 1 if found, 0 if not found, or the element has no keys */ int json_has_key(JsonElementRef element, char* key); /** * Get the child element with the specified key and pass it to elementOut. * (Element must be of type JSON_OBJECT). * @param element - The element to search in * @param key - The key to search for * @param elementOut - The place to store the result * @return 1 if success, 0 if failure (for example, when the key is not found) */ int json_key(JsonElementRef element, char* key, JsonElementRef* elementOut); /** * Get the child element with the specified index and pass it to elementOut. * (Element must be of type JSON_OBJECT or JSON_ARRAY). * @param element - The element to search in * @param index - The index to get * @param elementOut - The place to store the result * @return 1 if success, 0 if failure (for example, when the index is out of range) */ int json_index(JsonElementRef element, int index, JsonElementRef* elementOut); /** * Converts the provided element to a string, and stores it to stringOut * @param element - The element to convert * @param stringOut - The place to store the result * @return 1 if success, 0 if failure */ int json_as_string(JsonElementRef element, char** stringOut); /** * Converts the provided element to a double, and stores it to doubleOut * @param element - The element to convert * @param stringOut - The place to store the result * @return 1 if success, 0 if failure */ int json_as_double(JsonElementRef element, double* doubleOut); /** * Converts the provided element to an int, and stores it to intOut * @param element - The element to convert * @param stringOut - The place to store the result * @return 1 if success, 0 if failure */ int json_as_int(JsonElementRef element, int* intOut); /** * Converts the provided element to a bool, and stores it to boolOut * @param element - The element to convert * @param stringOut - The place to store the result * @return 1 if success, 0 if failure */ int json_as_bool(JsonElementRef element, bool* boolOut); /** * Shortcut for calling json_index and then json_as_string. * @param element - The element to query * @param index - The index of the element to get * @param stringOut - The place where the string result will be stored * @return 1 if success, 0 if failure */ int json_index_as_string(JsonElementRef element, int index, char** stringOut); /** * Shortcut for calling json_index and then json_as_double. * @param element - The element to query * @param index - The index of the element to get * @param stringOut - The place where the double result will be stored * @return 1 if success, 0 if failure */ int json_index_as_double(JsonElementRef element, int index, double* doubleOut); /** * Shortcut for calling json_index and then json_as_int. * @param element - The element to query * @param index - The index of the element to get * @param stringOut - The place where the int result will be stored * @return 1 if success, 0 if failure */ int json_index_as_int(JsonElementRef element, int index, int* intOut); /** * Shortcut for calling json_index and then json_as_bool. * @param element - The element to query * @param index - The index of the element to get * @param stringOut - The place where the bool result will be stored * @return 1 if success, 0 if failure */ int json_index_as_bool(JsonElementRef element, int index, bool* boolOut); /** * Shortcut for calling json_key and then json_as_string. * @param element - The element to query * @param key - The key to search for * @param stringOut - The place where the string result will be stored * @return 1 if success, 0 if failure */ int json_key_as_string(JsonElementRef element, char* key, char** stringOut); /** * Shortcut for calling json_key and then json_as_double. * @param element - The element to query * @param key - The key to search for * @param stringOut - The place where the double result will be stored * @return 1 if success, 0 if failure */ int json_key_as_double(JsonElementRef element, char* key, double* doubleOut); /** * Shortcut for calling json_key and then json_as_int. * @param element - The element to query * @param key - The key to search for * @param stringOut - The place where the int result will be stored * @return 1 if success, 0 if failure */ int json_key_as_int(JsonElementRef element, char* key, int* intOut); /** * Shortcut for calling json_key and then json_as_bool. * @param element - The element to query * @param key - The key to search for * @param stringOut - The place where the bool result will be stored * @return 1 if success, 0 if failure */ int json_key_as_bool(JsonElementRef element, char* key, bool* boolOut); #endif //CS430_PROJ2_RAYCASTER_JSON_H
c
10
0.708838
83
31.067358
193
starcoderdata
int VoronoiCoarsening::gaoColoring(const double maxDistance, const vector<Long64>& sensorPoint) { timestampBarrier("Starting VoronoiCoarsening::gaoColoring", comm_); assert( colorToGidMap_.size()>0 ); // Check that the mapping from colors to sensorPoint is in fact // trivial since we will exploit that fact in gaoColoring. I think // I'd like to get to a day where we don't need colorToGidMap_ and // just take advantage of the implicit mapping. That is a job for // another day. for (map<int, Long64>::const_iterator iter=colorToGidMap_.begin(); iter!=colorToGidMap_.end(); ++iter) assert(iter->second == sensorPoint[iter->first]); int myRank; MPI_Comm_rank(comm_, &myRank); IndexToThreeVector indexTo3Vector(anatomy_.nx(), anatomy_.ny(), anatomy_.nz()); ncolors_.clear(); localColors_.clear(); cell_colors_.resize(anatomy_.nLocal(), -1); // color only local cells const double r2Max=3.*maxDistance*maxDistance/ (anatomy_.dx()*anatomy_.dx() +anatomy_.dy()*anatomy_.dy() +anatomy_.dz()*anatomy_.dz()); vector<THREE_VECTOR> sensorLocation(sensorPoint.size()); for (unsigned ii=0; ii<sensorPoint.size(); ++ii) sensorLocation[ii] = indexTo3Vector(sensorPoint[ii]); GRID_ASSIGNMENT_OBJECT* gao = gao_init(sensorLocation.size(), (const void*) &sensorLocation[0], sizeof(THREE_VECTOR)); const int nLocal = anatomy_.nLocal(); for (unsigned iCell=0; iCell<nLocal; ++iCell) { THREE_VECTOR rCell = indexTo3Vector(anatomy_.gid(iCell)); int nearestSensor = gao_nearestCenter(gao, rCell); THREE_VECTOR rSensor = sensorLocation[nearestSensor]; double rr = DIFFSQ(rCell, rSensor); if (rr > r2Max) cell_colors_[iCell] = -1; else { cell_colors_[iCell] = nearestSensor; ncolors_[nearestSensor]++; localColors_.insert(nearestSensor); } } gao_destroy(gao); timestampBarrier("Finished VoronoiCoarsening::gaoColoring", comm_); return 0; }
c++
12
0.625579
82
35.59322
59
inline
#include "stdafx.h" #include "item.h" item::item(const char* name, const char* desc, const char* use) { type = ITEM; description = desc; useItemDesc = use; this->name = name; } item::~item() { } void item::useitem() { }
c++
6
0.630705
63
10.52381
21
starcoderdata
import axios from 'axios'; const GRAPH_API_BASE_URL = "http://192.168.178.44:8080/dmnapi/v1/graph/"; class GraphService { getAllInputData(){ return axios.get(GRAPH_API_BASE_URL + "allInputData/"); } getAllOutputData(){ return axios.get(GRAPH_API_BASE_URL + "allOutputData/"); } getInitialGraph(){ return axios.get(GRAPH_API_BASE_URL + "initialGraph/"); } matching(userData, threshold) { console.log("here2") return axios.post(GRAPH_API_BASE_URL + "matchingAlgorithm/?threshold=" + threshold, userData); } } export default new GraphService()
javascript
11
0.645161
102
22.884615
26
starcoderdata
// import { expect } from 'chai' // import * as actions from '../../app/actions/audio' // // describe('actions', () => { // describe('audio', () => { // it('fetchAudios should create fetch action', () => { // const fn = actions.fetchAudios() // // expect(fn).to.be.a('function') // }) // }) // })
javascript
3
0.539106
59
26.538462
13
starcoderdata
<?php cutter_start('content') ?> <!-- =============================================== --> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <?php echo $halaman ?> <!-- Main content --> <section class="content"> <!-- seting default pengirim --> <div class="box"> <div class="box-header with-border"> <h3 class="box-title">Default Kabupaten/ Kota Untuk Pengiriman <div class="box-tools pull-right"> <button class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="Collapse"><i class="fa fa-minus"> <button class="btn btn-box-tool" data-widget="remove" data-toggle="tooltip" title="Remove"><i class="fa fa-times"> <div class="box-body"> <form action="" method="POST" id="pengirim_default" style="display:none"> <div class="form-group col-md-6"> asal untuk pengiriman produk <select name="prov_pengirim" class="form-control"> <option value="">--Asal Provinsi Pengirim -- <?php foreach ($provinsi as $key): ?> <?php foreach ($key->results as $v): ?> <option value="<?php echo $v->province_id ?>"><?php echo $v->province ?> <?php endforeach ?> <?php endforeach ?> <div class="form-group col-md-6"> <select name="kota_pengirim" class="form-control" > <option value="">--Asal Kota/ Kabupaten Pengirim-- <div class="form-group col-md-6 col-md-offset-6 text-right"> <button class="btn btn-md btn-primary" id="btn_pengirim_default">Set as Default <p class="text-right"><a href="javascript:void(0)" onclick="showEDP()"> <span id="spanTextEDP"><i class="fa fa-pencil"> Edit Default Pengirim <div class="table-responsive"> <table class="table table-bordered"> Provinsi Provinsi Kabupaten/ Kota Kabupaten/ Kota <?php foreach ($defaultPengirim as $v): ?> echo $v['idprovinsi'] ?> echo $v['nama_provinsi'] ?> echo $v['idkota'] ?> echo $v['namakota'] ?> <?php endforeach ?> <div class="box-footer"> Alamat default yang digunakan untuk mengirim semua produk. <!-- Default box --> <div class="box"> <div class="box-header with-border"> <h3 class="box-title">Cek Biaya Pengiriman <div class="box-tools pull-right"> <button class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="Collapse"><i class="fa fa-minus"> <button class="btn btn-box-tool" data-widget="remove" data-toggle="tooltip" title="Remove"><i class="fa fa-times"> <div class="box-body"> <form action="" method="POST" role="form" id="cekbiayapengiriman"> <input type="hidden" name="cekbiaya"> <div class="form-group col-md-6"> Asal <select name="provinsi_asal" class="form-control"> <option value="">--Pilih Provinsi-- <?php foreach ($provinsi as $key): ?> <?php foreach ($key->results as $v): ?> <option value="<?php echo $v->province_id ?>"><?php echo $v->province ?> <?php endforeach ?> <?php endforeach ?> <div class="form-group col-md-6"> <select name="kota_asal" class="form-control" > <option value="">--Pilih Kota/ Kabupaten-- <div class="form-group col-md-6"> Tujuan <select name="provinsi_tujuan" class="form-control"> <option value="">--Pilih Provinsi-- <?php foreach ($provinsi as $key): ?> <?php foreach ($key->results as $v): ?> <option value="<?php echo $v->province_id ?>"><?php echo $v->province ?> <?php endforeach ?> <?php endforeach ?> <div class="form-group col-md-6"> <select name="kota_tujuan" class="form-control"> <option value="">--Pilih Kota/ Kabupaten-- <div class="form-group col-md-6"> gram <input type="number" min="1000" max="50000" name="weight" placeholder="Berat dalam gram" class="form-control"> <div class="form-group col-md-6"> Kurir <select name="kurir" class="form-control"> <option value="">--Pilih Kurir-- <option value="jne">JNE <option value="pos">POS Indonesia <option value="tiki">TIKI <div class="form-group col-md-6 col-md-offset-6 text-right"> <button type="button" class="btn btn-md btn-primary" id="periksa_biaya">Periksa <div class="col-md-12" id="hasil_biaya"> /.box-body --> <div class="box-footer"> Form Cek Biaya Pengiriman. /.box-footer--> /.box --> /.content --> /.content-wrapper --> <?php cutter_end() ?> <?php cutter_start('css') ?> <?php cutter_end() ?> <?php cutter_start('js') ?> <script type="text/javascript"> /*BIAYA PENGIRIMAN*/ /*asal*/ $('#cekbiayapengiriman [name=provinsi_asal]').on('change',function(){ var idProv = $('#cekbiayapengiriman [name=provinsi_asal]').val(); var url = "<?php echo SITEURL.URL_ADMIN.'/pengiriman/getcity/'?>"+idProv; $.getJSON(url,function(res){ var kota = res.rajaongkir.results; var html=''; for (var i = 0; i < kota.length; i++) { html +="<option value="+kota[i].city_id+">"+kota[i].city_name+" } $('#cekbiayapengiriman [name=kota_asal]').html(html); }) }) /*tujuan*/ $('#cekbiayapengiriman [name=provinsi_tujuan]').on('change',function(){ var idProv = $('#cekbiayapengiriman [name=provinsi_tujuan]').val(); var url = "<?php echo SITEURL.URL_ADMIN.'/pengiriman/getcity/'?>"+idProv; $.getJSON(url,function(res){ var kota = res.rajaongkir.results; var html=''; for (var i = 0; i < kota.length; i++) { html +="<option value="+kota[i].city_id+">"+kota[i].city_name+" } $('#cekbiayapengiriman [name=kota_tujuan]').html(html); }) }) /*periksa_biaya*/ $('#periksa_biaya').on('click',function(e){ e.preventDefault(); $('#hasil_biaya').html("<p style=\"color:green\"><i class=\"fa fa-refresh fa-spin\"> Mohon menunggu, sedang mengambil data... var cekbiaya = $('#cekbiayapengiriman [name=cekbiaya]').val(); var origin =$('#cekbiayapengiriman [name=kota_asal]').val(); var destination =$('#cekbiayapengiriman [name=kota_tujuan]').val(); var weight=$('#cekbiayapengiriman [name=weight]').val(); var kurir =$('#cekbiayapengiriman [name=kurir]').val(); if (origin == '' || destination ==''|| weight== 0|| kurir=='') { $('#hasil_biaya').html("<p style=\"color:red\"> harus dilengkapi...! return false; }else if(weight > 30000){ $('#hasil_biaya').html("<p style=\"color:red\"> barang melampaui batas...! return false; }else{ url ="<?php echo SITEURL.URL_ADMIN.'/pengiriman/getcost' ?>"; $.ajax({ type: "POST", url: url, dataType: 'json', data: "cekbiaya="+cekbiaya+"&origin="+origin+"&destination="+destination+"&weight="+weight+"&courier="+kurir, success: function(res){ var namaKurir = res.rajaongkir.results[0].name; var html ="<h4 class=\"text-center\">"+namaKurir+" html +="<div class=\"table-responsive\"><table class=\"table\">" +" +" Layanan +" var costs = res.rajaongkir.results[0].costs; if (costs.length < 1) { html +=" colspan=\"3\">Tidak ada data untuk ditampilkan.. }else{ for (var i = 0; i < costs.length; i++) { var estimasi=''; if (costs[i].cost[0].etd == "") {estimasi ='-';}else{estimasi = costs[i].cost[0].etd+" hari";} html +=" +" - "+costs[i].description+" +" +" +" } } html +=" $('#hasil_biaya').html(html); } }); } }) function showEDP() { $('#pengirim_default').toggle(function(e){ }); } // bagian set default pengirim $('#pengirim_default [name=prov_pengirim]').on('change',function(){ var idProv = $('#pengirim_default [name=prov_pengirim]').val(); var url = "<?php echo SITEURL.URL_ADMIN.'/pengiriman/getcity/'?>"+idProv; $.getJSON(url,function(res){ var kota = res.rajaongkir.results; var html=''; for (var i = 0; i < kota.length; i++) { html +="<option value="+kota[i].city_id+">"+kota[i].city_name+" } $('#pengirim_default [name=kota_pengirim]').html(html); }) }) $('#btn_pengirim_default').on('click',function(e){ e.preventDefault(); if ($('#pengirim_default [name=prov_pengirim]').val() == '') { alert('Pilih Provinsi !'); }else{ var idprov = $('#pengirim_default [name=prov_pengirim]').val(); var namaprov = $('#pengirim_default [name=prov_pengirim] option:selected').text(); var idkota = $('#pengirim_default [name=kota_pengirim]').val(); var namakota = $('#pengirim_default [name=kota_pengirim] option:selected').text(); url ="<?php echo SITEURL.URL_ADMIN.'/pengiriman/addPengirim' ?>"; $.ajax({ type :"POST", url : url, dataType : "json", data :"submit=&idprov="+idprov+"&namaprov="+namaprov+"&idkota="+idkota+"&namakota="+namakota, success: function(res){ // console.log(res); if (res == 'ok') { alert("Data Berhasil di Update."); window.location.reload(); }else{ alert('Gagal update data, silahkan coba lagi,,,'); } } }); // alert($('#pengirim_default [name=prov_pengirim] option:selected').text()); } }); <?php cutter_end() ?>
php
8
0.439769
175
46.773519
287
starcoderdata
using System; using System.Linq; using System.Collections.Generic; using System.Text; using Amazon.Lambda.Core; namespace TestServerlessApp { public class ComplexCalculator_Add_Generated { private readonly ComplexCalculator complexCalculator; public ComplexCalculator_Add_Generated() { SetExecutionEnvironment(); complexCalculator = new ComplexCalculator(); } public Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyResponse Add(Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyRequest request, Amazon.Lambda.Core.ILambdaContext context) { var complexNumbers = request.Body; var response = complexCalculator.Add(complexNumbers, context, request); var body = System.Text.Json.JsonSerializer.Serialize(response); return new Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyResponse { Body = body, Headers = new Dictionary<string, string> { {"Content-Type", "application/json"} }, StatusCode = 200 }; } private static void SetExecutionEnvironment() { const string envName = "AWS_EXECUTION_ENV"; var envValue = new StringBuilder(); // If there is an existing execution environment variable add the annotations package as a suffix. if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName))) { envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_"); } envValue.Append("amazon-lambda-annotations_0.4.3.0"); Environment.SetEnvironmentVariable(envName, envValue.ToString()); } } }
c#
18
0.635925
197
32.321429
56
starcoderdata
<?php require_once('runton_fns.php'); header("Content-Type:application/json"); //$_GET = stripslashes_array($_GET); $_POST = stripslashes_array($_POST); $username =$_POST['username']; $passwd =$_POST['password']; $output =array(); //检查变量值是否为空 if(!$username||!$passwd){ $output['reason'] = "用户名或密码不能为空。"; } //建立数据库连接 $conn = db_connect(); $sql = "select * from users where username='$username' and passwd = '$passwd'"; $result = $conn->query($sql); if($result){ $row = $result->fetch_assoc(); if(!$row){ $output['reason'] = "用户名或密码不正确。"; }else{ $output['msg'] ="succ"; $output['login_id'] =$row['user_id']; //建立会话id $id=rememberkey(); session_id($id); session_start(); } } echo json_encode($output); ?>
php
11
0.59025
80
20.714286
35
starcoderdata
import media import fresh_tomatoes # Contains the details of movie objects toy_story = media.Movie('Toy Story', 'A story of a boy and his toys come into life', "https://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg", 'https://www.youtube.com/watch?v=KYz2wyBy3kc') avatar = media.Movie('Avatar', 'A marine on an Alien Planet', "https://upload.wikimedia.org/wikipedia/en/b/b0/Avatar-Teaser-Poster.jpg", "https://www.youtube.com/watch?v=5PSNL1qE6VY") avengers_end_game = media.Movie('Avengers Endgame', 'This is a Story about the Avengers who saves the earth from Thanos', "https://in.bmscdn.com/iedb/movies/images/website/poster/large/avengers-end-game-et00090482-07-12-2018-06-50-21.jpg", "https://www.youtube.com/watch?v=TcMBFSGVi1c") # saving the movies in a list movies = [toy_story, avatar, avengers_end_game] #calling the fresh_tomatoes function to generate web pages fresh_tomatoes.open_movies_page(movies)
python
6
0.638489
140
52
21
starcoderdata
import Room from './room' import Roomba from './roomba' import Input from './input' function controller () { var input = new Input() input.readFile() var dimensions = input.roomDimensions() var room = new Room(dimensions) input.patchesOfDirt().forEach((dirt) => { room.addDirt(dirt) }) var position = input.roombaLocation() var roomba = new Roomba(position, room) input.drivingInstructions().forEach((direction) => { roomba.move(direction) }) console.log(`${roomba.currentPosition().x} ${roomba.currentPosition().y}`) console.log(roomba.collectedDirt()) } controller()
javascript
23
0.704441
76
27.391304
23
starcoderdata
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ # high performance of counter from collections import Counter cntdict = Counter(nums).items() eletuple = (k for (k,v) in cntdict if v > len(nums) / 2) return next(eletuple)
python
13
0.52139
65
33.090909
11
starcoderdata
/** * Our GraphQL service */ const { server, httpServer, app } = require("./api/graphql.js"); server.start().then(async () => { server.applyMiddleware({ app, path: "/.netlify/functions/graphql" }); httpServer.listen({ port: 8081, host: "0.0.0.0" }); console.log("😺 Local server running! http://localhost:8080"); }); /** * Recurring tasks and workers */ const { CronJob } = require("cron"); const { handler: minuteWorker } = require("./api/worker"); const minuteWorkerJob = new CronJob("* * * * *", minuteWorker); console.log("Starting recurring tasks"); minuteWorkerJob.start(); const killTasks = () => { process.stdout.write("Stopping recurring tasks"); minuteWorkerJob.stop(); }; process.on("SIGINT", killTasks); process.on("SIGABRT", killTasks); process.on("SIGTERM", killTasks); process.on("exit", killTasks);
javascript
12
0.674797
71
26.774194
31
starcoderdata
angular.module('m-grid.config', []) .provider('mGridConfig', function () { var config = { tableClass: 'table table-striped table-bordered m-grid-table', thClass: 'm-grid-th', footerClass: 'm-grid-footer', defaultPageLimit: 10, displayLimitOptions: [ { 'text': 10, 'value': 10 }, { 'text': 20, 'value': 20 }, { 'text': 50, 'value': 50 }, { 'text': 100, 'value': 100 } ] }; this.setDefaultPageLimit = function (limit) { config.defaultPageLimit = limit || 10; }; this.setDisplayLimitOptions = function (limitOptions) { if (!angular.isArray(limitOptions)) { throw new Error('param limitOptions should be array'); } if (limitOptions.length === 0) { throw new Error('param limitOptions should have at least one record'); } config.displayLimitOptions = []; limitOptions.forEach(function (item) { if (angular.isObject(item)) { config.displayLimitOptions.push({ text: item.text, value: item.value }); } else { config.displayLimitOptions.push({ text: item, value: +item }); } }); }; this.setCssClass = function (classObj) { if (!angular.isObject(classObj)) { throw new Error('param classObj should be a object'); } if (classObj.hasOwnProperty('table')) { config.tableClass = classObj.table; } if (classObj.hasOwnProperty('th')) { config.thClass = classObj.th; } if (classObj.hasOwnProperty('footer')) { config.footerClass = classObj.footer; } }; this.appendCssClass = function (classObj) { if (!angular.isObject(classObj)) { throw new Error('param classObj should be a object'); } if (classObj.hasOwnProperty('table')) { config.tableClass += ' ' + classObj.table; } if (classObj.hasOwnProperty('th')) { config.thClass += ' ' + classObj.th; } if (classObj.hasOwnProperty('footer')) { config.footerClass += ' ' + classObj.footer; } }; this.$get = [function () { return config; }]; });
javascript
24
0.510515
82
29.696203
79
starcoderdata
/** * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * This file is part of the LDP4j Project: * http://www.ldp4j.org/ * * Center for Open Middleware * http://www.centeropenmiddleware.com/ * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * Copyright (C) 2014-2016 Center for Open Middleware. * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * 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. * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * Artifact : org.ldp4j.framework:ldp4j-application-kernel-core:0.2.2 * Bundle : ldp4j-application-kernel-core-0.2.2.jar * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# */ package org.ldp4j.application.kernel.resource; import org.ldp4j.application.ApplicationApiRuntimeException; import org.ldp4j.application.data.DataSet; import org.ldp4j.application.ext.ApplicationException; import org.ldp4j.application.ext.ContainerHandler; import org.ldp4j.application.ext.Deletable; import org.ldp4j.application.ext.Modifiable; import org.ldp4j.application.ext.Query; import org.ldp4j.application.ext.Queryable; import org.ldp4j.application.ext.ResourceHandler; import org.ldp4j.application.kernel.session.WriteSessionConfiguration; import org.ldp4j.application.kernel.session.WriteSessionService; import org.ldp4j.application.session.ContainerSnapshot; import org.ldp4j.application.session.ResourceSnapshot; import org.ldp4j.application.session.SessionTerminationException; import org.ldp4j.application.session.SnapshotVisitor; import org.ldp4j.application.session.WriteSession; final class AdapterFactory { private static class ResourceAdapter<T extends ResourceSnapshot> implements Adapter { private final T resource; private final ResourceId resourceId; private final ResourceHandler delegate; private final WriteSession session; private final WriteSessionService service; private ResourceAdapter(T resource, ResourceId resourceId, ResourceHandler delegate, WriteSession session, WriteSessionService service) { this.resource = resource; this.resourceId = resourceId; this.delegate = delegate; this.session = session; this.service = service; } protected final WriteSession writeSession() { return this.session; } protected final S as(Class<? extends S> clazz) throws UnsupportedFeatureException { if(clazz.isInstance(this.delegate)) { return clazz.cast(this.delegate); } throw new UnsupportedFeatureException(resource(),clazz); } protected final T resource() { return this.resource; } protected final FeatureException featureException(Throwable cause, Class feature) { return new FeatureExecutionException(resource(),feature,cause); } protected final void finalizeSession() { try { this.session.close(); } catch (SessionTerminationException e) { throw new CouldNotTerminateSessionException(e); } } protected final Resource detach(ResourceSnapshot snapshot) { return this.service.detach(this.session, snapshot); } protected final void checkResponseNotNull(Object response, Class feature, String violation) throws FeaturePostconditionException { if(response==null) { throw new FeaturePostconditionException(resource(),feature,violation); } } @Override public final ResourceId resourceId() { return this.resourceId; } @Override public final DataSet get() throws FeatureException { try { DataSet dataSet = this.delegate.get(resource()); checkResponseNotNull(dataSet,ResourceHandler.class,"No data set returned"); return dataSet; } catch (ApplicationException | ApplicationApiRuntimeException e) { throw featureException(e,ResourceHandler.class); } finally { finalizeSession(); } } @Override public final DataSet query(Query query) throws FeatureException { try { DataSet dataSet = as(Queryable.class).query(resource(), query, writeSession()); checkResponseNotNull(dataSet,Queryable.class,"No data set returned"); return dataSet; } catch (ApplicationException | ApplicationApiRuntimeException e) { throw featureException(e,Queryable.class); } finally { finalizeSession(); } } @Override public final void update(DataSet content) throws FeatureException { try { as(Modifiable.class).update(resource(), content, writeSession()); } catch (ApplicationException | ApplicationApiRuntimeException e) { throw featureException(e,Modifiable.class); } finally { finalizeSession(); } } @Override public final void delete() throws FeatureException { try { as(Deletable.class).delete(resource(),writeSession()); } catch (ApplicationException | ApplicationApiRuntimeException e) { throw featureException(e,Deletable.class); } finally { finalizeSession(); } } @Override public Resource create(DataSet content) throws FeatureException { finalizeSession(); throw new UnsupportedFeatureException(resource(),ContainerHandler.class); } } private static class ContainerAdapter extends ResourceAdapter { private ContainerAdapter(ContainerSnapshot container, ResourceId resourceId, ResourceHandler delegate, WriteSession session, WriteSessionService service) { super(container,resourceId,delegate,session,service); } @Override public Resource create(DataSet content) throws FeatureException { try { ResourceSnapshot create = as(ContainerHandler.class).create(resource(),content,writeSession()); checkResponseNotNull(create, ContainerHandler.class, "No resource created"); return detach(create); } catch (ApplicationException | ApplicationApiRuntimeException e) { throw featureException(e,ContainerHandler.class); } finally { finalizeSession(); } } } private static final class FactoryVistor implements SnapshotVisitor { private final ResourceHandler delegate; private final WriteSession session; private final ResourceId resourceId; private final WriteSessionService service; private ResourceAdapter adapter; private FactoryVistor(ResourceId resourceId, WriteSession session, WriteSessionService service, ResourceHandler handler) { this.resourceId = resourceId; this.session = session; this.service = service; this.delegate= handler; } public Adapter getAdapter() { return adapter; } @Override public void visitResourceSnapshot(ResourceSnapshot resource) { this.adapter=new ResourceAdapter } @Override public void visitContainerSnapshot(ContainerSnapshot resource) { this.adapter=new ContainerAdapter(resource,this.resourceId,this.delegate,this.session,this.service); } } private AdapterFactory() { } static Adapter newAdapter(Resource resource, ResourceHandler resourceHandler, WriteSessionService writeSessionService, WriteSessionConfiguration configuration) { WriteSession session = writeSessionService.createSession(configuration); ResourceSnapshot snapshot = writeSessionService.attach(session,resource,resourceHandler.getClass()); FactoryVistor factory = new FactoryVistor(resource.id(),session,writeSessionService,resourceHandler); snapshot.accept(factory); return factory.getAdapter(); } }
java
15
0.727452
162
34.818584
226
starcoderdata
import { useState, useEffect } from 'react' import { useJobs } from 'store/jobs_store' import { useRouter } from 'next/router' import JobCard from '../../components/job/JobCard' const JobBoard = () => { const router = useRouter() const filterParam = router.query const [activeJobs, setActiveJobs] = useState([]) // const initialFilterParam = Object.keys(filterParam).length ? filterParam.filter : '' // const [jobFilter, setJobFilter] = useState(initialFilterParam) const [jobFilter, setJobFilter] = useState() const jobs = useJobs((s) => s.jobs) function filteredJobs(jobList, filter) { const filtered = jobList.filter((job) => { return ( job.roleFocus === filter && job.status !== 'inactive' && job.paid === true && job.approved === true ) }) return filtered } function getActiveJobs(jobList) { const active = jobList.filter((job) => { return ( job.status !== 'inactive' && job.paid === true && job.approved === true ) }) return active } useEffect(() => { setJobFilter(jobFilter) }, []) return ( <div className='container'> <div className='w-full mx-auto lg:max-w-4xl'> <div className='flex items-center justify-between mb-6'> <h1 className='text-2xl'> {jobFilter ? `${jobFilter} Jobs` : 'All Jobs'} <div className='relative w-1/2 md:w-1/4'> <label htmlFor='filter-by' className='sr-only'> Filter <div className='select-wrap'> <select className='justify-end rounded-md input input-select' id='filter-by' placeholder='Filter By' onChange={(event) => setJobFilter(event.target.value)} value={jobFilter} > <option value=''>All <option value='Front-end'>Front-end <option value='Back-end'>Back-end <option value='Full-stack'>Full-stack {/* <LoadingSpinner loading={loading} /> */} <div data-cy='job-board-list' className='mx-auto'> {!jobFilter && ( <> {getActiveJobs(jobs).map((job, i) => ( <JobCard key={job.id} job={job} i={i} /> ))} )} {jobFilter && ( <> {filteredJobs(jobs, jobFilter).map((job, i) => ( <JobCard key={job.id} job={job} i={i} /> ))} )} ) } export default JobBoard
javascript
25
0.516601
89
27.01
100
starcoderdata
function(resolve, _) { testImageAccess( providers[key] + '?' + Math.random(), () => resolve(key), () => resolve(null), 10000, // 10 seconds. key === 'gv' // "gv" is a video element, not an image. ); }
javascript
10
0.4375
64
29.333333
9
inline
""" Produced by Contact at for any questions Full Rights Reserved under MIT License """ import pygame from math import sin, cos, radians class Rocket: def __init__(self, x, y, color): self.x = x self.y = y self.old_x = x self.old_y = y self.x_vel = 0 self.y_vel = 0 self.drift_heading = 0 self.heading = 0 self.speed = 0 self.vertex_distance = 28 self.rear_vertex_angle = 137 self.vertices = [(self.vertex_distance, 0), (self.vertex_distance, self.rear_vertex_angle), (self.vertex_distance, -self.rear_vertex_angle)] # Polar coordinates self.color = color self.collider_size = 20 self.wall_collider = pygame.Rect(self.x - self.collider_size, self.y - self.collider_size, self.collider_size * 2, self.collider_size * 2) self.bullets = [] self.bullet_is_shot = False self.shoot_timer = 0 self.current_powerup = 0 self.missile_exploded = False self.missile_explosion_radius = 250 self.missile_timer = 0 self.missile_explosion_x = 0 self.missile_explosion_y = 0 def assign_powerup(self, powerup=0): self.current_powerup = powerup def update_collider(self): self.wall_collider = pygame.Rect(self.x - self.collider_size, self.y - self.collider_size, self.collider_size * 2, self.collider_size * 2) def update_old_coords(self): self.old_x = self.x self.old_y = self.y def accelerate(self, speed): self.speed += speed self.heading = self.drift_heading # self.drift_x_vel = cos(radians(self.drift_heading)) * speed # self.drift_y_vel = sin(radians(self.drift_heading)) * speed # self.x_vel += self.drift_x_vel # self.y_vel += self.drift_y_vel def render(self, window): v = self.vertices # Convert polar coordinates to cartesian coordinates x1 = cos(radians(v[0][1])) * v[0][0] + self.x y1 = sin(radians(v[0][1])) * v[0][0] + self.y x2 = cos(radians(v[1][1])) * v[1][0] + self.x y2 = sin(radians(v[1][1])) * v[1][0] + self.y x3 = cos(radians(v[2][1])) * v[2][0] + self.x y3 = sin(radians(v[2][1])) * v[2][0] + self.y # Store cartesian coordinates in list so pygame can read them in polygon() v_list = [(x1, y1), (x2, y2), (x3, y3)] pygame.draw.polygon(window, self.color, v_list) def update(self): # Acceleration self.x_vel = cos(radians(self.heading)) * self.speed self.y_vel = sin(radians(self.heading)) * self.speed # Movement self.x += self.x_vel self.y += self.y_vel self.vertices = [(self.vertex_distance, self.drift_heading), (self.vertex_distance, self.rear_vertex_angle+self.drift_heading), (self.vertex_distance, -self.rear_vertex_angle+self.drift_heading)] self.shoot_timer += 1 if self.shoot_timer > 100: self.bullet_is_shot = False
python
15
0.667897
197
28.78022
91
starcoderdata
public boolean giveCalculator(int ID, int element) { Spots nSpot = (Spots) itemList.get(ID); //default to true since we are changing if false boolean avail = true; // System.out.println(element+"=="+itemList.size()); //base case on the last element of the list. if(element == itemList.size()) { // System.out.println("finished"); return true; } //recursive case else if(itemList.get(element) instanceof Spots) { Spots spot = (Spots) itemList.get(element); double distance = Math.sqrt( Math.pow((nSpot.x+nSpot.x2)/2 - (spot.x+spot.x2)/2, 2) + Math.pow((nSpot.y+nSpot.y2)/2 - (spot.y+spot.y2)/2, 2))-10; //if one is but not the other. prevents possible case for cluster //or group sitting at the same table if(spot.occupied) { // System.out.println("checking pair "+element +" = " + (distance <= BUFFER)); return (!(distance <= BUFFER) && giveCalculator(ID, element+1)); } } return giveCalculator(ID, element + 1); }
java
19
0.652041
81
36.730769
26
inline
#include <bits/stdc++.h> using namespace std; // int 3E4 // long 2E9 // long long 9E18 struct lunlun { long v; vector<long> children; lunlun(long v) : v(v) { int x = v % 10; for (int i = max(0, x - 1); i <= min(9, x + 1); i++) children.emplace_back(v * 10 + i); }; }; int main() { long K; cin >> K; if (K <= 9) { cout << K << endl; return 0; } queue<lunlun> open; for (int i = 1; i <= 9; i++) open.emplace(i); long k = 9; while (true) { lunlun n = open.front(); open.pop(); for (const auto& child : n.children) { // cout << k << "," << child << endl; if (++k >= K) { cout << child << endl; return 0; } open.emplace(child); } } }
c++
12
0.458607
56
13.921569
51
codenet
using DetranConsulta.Detran.Model; using HtmlAgilityPack; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace DetranConsulta.Detran.Parser { public abstract class AulaParser : IParser where T : Aula, new() { public List Parse(HtmlDocument html) { var aulas = new List foreach (var linha in html.QuerySelectorAll("tr").Skip(1)) { var dados = linha.ChildNodes.Where(s => s.Name == "td").Select(s => s.InnerText).ToArray(); var aula = new T { Data = this.ParseDate(dados[0]).Date, DataEnvio = this.ParseDate(dados[4]), Inicio = this.ParseTime(dados[1]), Fim = this.ParseTime(dados[2]), Status = dados[5] }; this.ParseAula(aula, dados); aulas.Add(aula); } return aulas; } protected abstract void ParseAula(T aula, string[] dados); private DateTime ParseDate(string value) { if (DateTime.TryParseExact(value, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var data)) return data; else throw new Exception($"Não foi possível fazer o parse da data '{value}'."); } private TimeSpan ParseTime(string value) { if (TimeSpan.TryParseExact(value, "hh':'mm':'ss", CultureInfo.InvariantCulture, TimeSpanStyles.None, out var time)) return time; else throw new Exception($"Não foi possível fazer o parse do tempo '{value}'."); } } }
c#
23
0.539391
141
32.053571
56
starcoderdata
//-------------------------------------------------- // <copyright file="ListProcessorUnitTests.cs" company="Magenic"> // Copyright 2019 Magenic, All rights Reserved // // class for getting selenium specific configuration values //-------------------------------------------------- using Magenic.Maqs.Utilities.Data; using Magenic.Maqs.Utilities.Helper; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text; namespace UtilitiesUnitTesting { /// /// Unit Tests for the ListProcessor class /// [TestClass] [ExcludeFromCodeCoverage] public class ListProcessorUnitTests { /// /// Unit Test for creating a comma delimited string /// #region CommaDelimited [TestMethod] [TestCategory(TestCategories.Utilities)] public void CreateCommaDelimitedStringTest() { List stringList = new List stringList.Add("Maine"); stringList.Add("Massachusetts"); stringList.Add("New Hampshire"); stringList.Add("Connecticut"); stringList.Add("Rhode Island"); stringList.Add("Vermont"); string expectedText = "Maine, Massachusetts, New Hampshire, Connecticut, Rhode Island, Vermont"; string actualText = ListProcessor.CreateCommaDelimitedString(stringList); if (!expectedText.Equals(actualText)) { Assert.Fail(StringProcessor.SafeFormatter("Expected string [{0}] does not match Actual string [{1}]", expectedText, actualText)); } } #endregion /// /// Unit Test for creating a sorted comma delimited string /// [TestMethod] [TestCategory(TestCategories.Utilities)] public void CreateSortedCommaDelimitedStringTest() { List stringList = new List stringList.Add("Maine"); stringList.Add("Massachusetts"); stringList.Add("New Hampshire"); stringList.Add("Connecticut"); stringList.Add("Rhode Island"); stringList.Add("Vermont"); string expectedText = "Connecticut, Maine, Massachusetts, New Hampshire, Rhode Island, Vermont"; string actualText = ListProcessor.CreateCommaDelimitedString(stringList, true); if (!expectedText.Equals(actualText)) { Assert.Fail(StringProcessor.SafeFormatter("Expected string [{0}] does not match Actual string [{1}]", expectedText, actualText)); } } /// /// Unit Test for comparing two lists of strings /// #region ListProcessorCompare [TestMethod] [TestCategory(TestCategories.Utilities)] public void ListOfStringsComparerTest() { StringBuilder results = new StringBuilder(); List expectedList = new List List actualList = new List expectedList.Add("Maine"); expectedList.Add("Massachusetts"); expectedList.Add("New Hampshire"); expectedList.Add("Connecticut"); expectedList.Add("Rhode Island"); expectedList.Add("Vermont"); actualList.Add("Massachusetts"); actualList.Add("Connecticut"); actualList.Add("Rhode Island"); actualList.Add("Vermont"); actualList.Add("Maine"); actualList.Add("New Hampshire"); ListProcessor.ListOfStringsComparer(expectedList, actualList, results); if (results.Length > 0) { Assert.Fail("{0}{1}", results.ToString(), Environment.NewLine); } } #endregion /// /// Unit Test for comparing two lists of strings by order /// [TestMethod] [TestCategory(TestCategories.Utilities)] public void ListOfStringsComparerByOrderTest() { StringBuilder results = new StringBuilder(); List expectedList = new List List actualList = new List expectedList.Add("Maine"); expectedList.Add("Massachusetts"); expectedList.Add("New Hampshire"); expectedList.Add("Connecticut"); expectedList.Add("Rhode Island"); expectedList.Add("Vermont"); actualList.Add("Maine"); actualList.Add("Massachusetts"); actualList.Add("New Hampshire"); actualList.Add("Connecticut"); actualList.Add("Rhode Island"); actualList.Add("Vermont"); ListProcessor.ListOfStringsComparer(expectedList, actualList, results, true); if (results.Length > 0) { Assert.Fail("{0}{1}", results.ToString(), Environment.NewLine); } } /// /// Verify that ListOfStringsComparer handles lists of unequal length as expected /// [TestMethod] [TestCategory(TestCategories.Utilities)] public void ListOfStringsComparerUnequalLengths() { StringBuilder results = new StringBuilder(); List expectedList = new List List actualList = new List expectedList.Add("A"); expectedList.Add("B"); actualList.Add("A"); bool isEqual = ListProcessor.ListOfStringsComparer(expectedList, actualList, results, true); Assert.IsTrue(results.ToString().Contains("The following lists are not the same size:")); Assert.IsFalse(isEqual); } /// /// Verify that ListOfStringsComparer handles not finding an item in the expected list correctly /// [TestMethod] [TestCategory(TestCategories.Utilities)] public void ListOfStringsComparerItemNotFound() { StringBuilder results = new StringBuilder(); List expectedList = new List List actualList = new List expectedList.Add("A"); expectedList.Add("B"); actualList.Add("A"); actualList.Add("C"); bool isEqual = ListProcessor.ListOfStringsComparer(expectedList, actualList, results, false); Assert.IsTrue(results.ToString().Contains("[C] was not found in the list but was expected")); Assert.IsFalse(isEqual); } /// /// Verify that ListOfStringsComparer handles inequality between lists as expected /// [TestMethod] [TestCategory(TestCategories.Utilities)] public void ListOfStringsComparerItemNotMatching() { StringBuilder results = new StringBuilder(); List expectedList = new List List actualList = new List expectedList.Add("A"); expectedList.Add("B"); actualList.Add("A"); actualList.Add("C"); bool isEqual = ListProcessor.ListOfStringsComparer(expectedList, actualList, results, true); Assert.IsTrue(results.ToString().Contains("Expected [C] but found [B]")); Assert.IsFalse(isEqual); } } }
c#
17
0.590519
145
37.693467
199
starcoderdata
// Copyright (c) 2014 The Sippet Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "sippet/message/headers/route.h" #include namespace sippet { RouteParam::RouteParam() { } RouteParam::RouteParam(const RouteParam &other) : ContactBase(other) { } RouteParam::RouteParam(const GURL &address, const std::string &displayName) : ContactBase(address, displayName) { } RouteParam::~RouteParam() { } RouteParam &RouteParam::operator=(const RouteParam &other) { ContactBase::operator=(other); return *this; } Route::Route() : Header(Header::HDR_ROUTE) { } Route::Route(const RouteParam &param) : Header(Header::HDR_ROUTE) { push_back(param); } Route::Route(const Route &other) : Header(other), has_multiple(other) { } Route::~Route() { } Route *Route::DoClone() const { return new Route(*this); } void Route::print(raw_ostream &os) const { Header::print(os); has_multiple::print(os); } } // namespace sippet
c++
9
0.652364
73
18.052632
57
starcoderdata
import Projects from './projects'; import Project from './project'; const projects = new Projects(); test('Create a Projects object', () => { expect(projects).toBeInstanceOf(Projects); }); test('Newly created project owns default project', () => { const expected = [new Project('default', 'hsl(204, 86%, 53%)')]; expect(projects.myProjects).toEqual(expect.arrayContaining(expected)); }); test('Add a project to myProjects', () => { const expected = new Project('JavaScript', 'hsl(204, 86%, 53%)'); const defProject = new Project('default', 'hsl(204, 86%, 53%)'); expect(() => { projects.addProject(expected); }).toThrow("Cannot read property 'appendChild' of null"); expect(projects.myProjects).toEqual(expect.arrayContaining([defProject, expected])); }); test('Throw error when listProjects are called', () => { expect(() => { projects.listProjects(); }).toThrow(); });
javascript
14
0.668118
86
30.689655
29
starcoderdata
using StackExchange.Redis; using System; using System.Reflection; using store.Src.Utils.Interface; namespace store.Src.Utils { public class Redis : IRedis { private readonly ConnectionMultiplexer redis; private readonly IDatabase redisDB; public Redis(IConfig config) { redis = ConnectionMultiplexer.Connect( new ConfigurationOptions { EndPoints = { config.getEnvByKey("REDIS_URL") } }); redisDB = redis.GetDatabase(); } public bool setByKey(string key, string value) { redisDB.StringSet(key, value); string result = redisDB.StringGet(key); if (!result.Equals(value)) return false; return true; } public string getByKey(string key) { return redisDB.StringGet(key); } public bool deleteByKey(string key) { return redisDB.KeyDelete(key); } public void setOjectByKey(string key, object obj) { redisDB.HashSet(key, this.toHashEntries(obj)); Console.WriteLine(redisDB.HashGetAll(key)); } public HashEntry[] toHashEntries(object obj) { PropertyInfo[] properties = obj.GetType().GetProperties(); var entries = new HashEntry[properties.Length]; int i = 0; foreach (var property in properties) { object propertyValue = property.GetValue(obj); entries[i++] = new HashEntry(property.Name, property.GetValue(obj).ToString()); } return entries; } // public T ConvertFromRedis hashEntries) // { // PropertyInfo[] properties = typeof(T).GetProperties(); // var obj = Activator.CreateInstance(typeof(T)); // int i = 0; // foreach (var property in properties) // { // HashEntry entry = hashEntries.ToDictionary(g => g.Name.ToString().Equals(property.Name)); // if (entry.Equals(new HashEntry())) continue; // property.SetValue(obj, Convert.ChangeType(entry.Value.ToString(), property.PropertyType)); // } // return (T)obj; // } } }
c#
20
0.550604
109
29.794872
78
starcoderdata
package com.blazemeter.jmeter.correlation.core.replacements; import static org.assertj.core.api.Assertions.assertThat; import com.blazemeter.jmeter.correlation.core.ResultField; import com.blazemeter.jmeter.correlation.core.replacements.RegexReplacement; import java.util.Collections; import org.apache.jmeter.extractor.RegexExtractor; import org.apache.jmeter.extractor.XPathExtractor; import org.apache.jmeter.extractor.gui.RegexExtractorGui; import org.apache.jmeter.extractor.gui.XPathExtractorGui; import org.apache.jmeter.protocol.http.control.Header; import org.apache.jmeter.protocol.http.control.HeaderManager; import org.apache.jmeter.protocol.http.sampler.HTTPSampler; import org.apache.jmeter.testelement.TestElement; import org.apache.jmeter.threads.JMeterVariables; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.bridge.SLF4JBridgeHandler; public class RegexReplacementTest { private static final String XPATH_EXTRACTOR_GUI_CLASS = XPathExtractorGui.class.getName(); private static final String REFERENCE_NAME = "TEST_SWEACN"; private static final String REQUEST_REGEX = "=([^&]+)"; private static final String REQUEST_REGEX_WITHOUT_GROUP = "=[^&]+"; private static final String PARAM_NAME = "Test_SWEACn"; private static final String PARAM_VALUE = "123"; private RegexReplacement replacer; private JMeterVariables vars; private HTTPSampler sampler; // we need this to avoid nasty logs about pdfbox @BeforeClass public static void setupClass() { SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); } @Before public void setup() { sampler = new HTTPSampler(); sampler.setMethod("GET"); sampler.setPath("/" + PARAM_NAME + "=" + PARAM_VALUE + "&Test_Path=1"); vars = new JMeterVariables(); vars.put(REFERENCE_NAME, PARAM_VALUE); replacer = new RegexReplacement(REQUEST_REGEX); replacer.setVariableName(REFERENCE_NAME); } @Test public void shouldNotReplaceRegexExtractorValues() { String responseRegex = PARAM_NAME + "=" + PARAM_VALUE + "&"; RegexExtractor extractor = createRegexExtractor(responseRegex); replacer.process(sampler, Collections.singletonList(extractor), null, vars); assertThat(extractor.getRegex()).isEqualTo(responseRegex); } private RegexExtractor createRegexExtractor(String responseRegex) { RegexExtractor regex = new RegexExtractor(); regex.setProperty(TestElement.GUI_CLASS, RegexExtractorGui.class.getName()); regex.setName("RegExp - " + REFERENCE_NAME); regex.setRefName(REFERENCE_NAME); regex.setTemplate("$1$"); regex.setMatchNumber(1); regex.setDefaultValue("NOT_FOUND"); regex.setRegex(responseRegex); regex.setUseField(ResultField.BODY.getCode()); return regex; } @Test public void shouldNotReplaceClassNameIfItMatchesRegex() { XPathExtractor xPathExtractor = new XPathExtractor(); xPathExtractor.setProperty(TestElement.GUI_CLASS, XPATH_EXTRACTOR_GUI_CLASS); replacer.process(sampler, Collections.singletonList(xPathExtractor), null, vars); assertThat(xPathExtractor.getPropertyAsString(TestElement.GUI_CLASS)) .isEqualTo(XPATH_EXTRACTOR_GUI_CLASS); } @Test public void shouldReplaceHeaderManagerValueWhenRegexMatches() { replacer = new RegexReplacement("(" + PARAM_VALUE + ")"); replacer.setVariableName(REFERENCE_NAME); HeaderManager headerManager = new HeaderManager(); headerManager.add(new Header(PARAM_NAME, PARAM_VALUE)); replacer.process(sampler, Collections.singletonList(headerManager), null, vars); assertThat(headerManager.getHeader(0)) .isEqualTo(new Header(PARAM_NAME, "${" + REFERENCE_NAME + "}")); } @Test public void shouldNotReplaceHeaderManagerValueWhenRegexDoesNotMatch() { replacer = new RegexReplacement("(" + PARAM_VALUE + ")"); replacer.setVariableName(REFERENCE_NAME); HeaderManager headerManager = new HeaderManager(); String headerValue = "OtherValue"; headerManager.add(new Header(PARAM_NAME, headerValue)); replacer.process(sampler, Collections.singletonList(headerManager), null, vars); assertThat(headerManager.getHeader(0)).isEqualTo(new Header(PARAM_NAME, headerValue)); } @Test public void shouldReplaceValueInRequestPathWhenRegexMatches() { String originalPath = sampler.getPath(); replacer.process(sampler, Collections.emptyList(), null, vars); assertThat(sampler.getPath()) .isEqualTo(originalPath.replace(PARAM_VALUE, "${" + REFERENCE_NAME + "}")); } @Test public void shouldNotReplaceValueInRequestPathWhenRegexIsEmpty() { replacer = new RegexReplacement(""); replacer.setVariableName(REFERENCE_NAME); String originalPath = sampler.getPath(); replacer.process(sampler, Collections.emptyList(), null, vars); assertThat(sampler.getPath()) .isEqualTo(originalPath); } @Test public void shouldNotReplaceValueInRequestPathWhenRegexDoesNotHaveAnyGroup() { replacer = new RegexReplacement(REQUEST_REGEX_WITHOUT_GROUP); replacer.setVariableName(REFERENCE_NAME); String originalPath = sampler.getPath(); replacer.process(sampler, Collections.emptyList(), null, vars); assertThat(sampler.getPath()) .isEqualTo(originalPath); } @Test public void shouldNotReplaceValueInRequestPathWhenRegexMatchesButVariableValueIsDifferent() { vars.put(REFERENCE_NAME, "Other"); String originalPath = sampler.getPath(); replacer.process(sampler, Collections.emptyList(), null, vars); assertThat(sampler.getPath()) .isEqualTo(originalPath.replace(PARAM_VALUE, PARAM_VALUE)); } @Test public void shouldReplaceValueInArgumentWhenRegexMatches() { sampler.addArgument(PARAM_NAME, PARAM_VALUE); replacer.process(sampler, Collections.emptyList(), null, vars); assertThat(sampler.getArguments().getArgument(0).getValue()) .isEqualTo("${" + REFERENCE_NAME + "}"); } @Test public void shouldNotReplaceValueInArgumentWhenRegexMatchesButVariableValueIsDifferent() { vars.put(REFERENCE_NAME, "Other"); sampler.addArgument(PARAM_NAME, PARAM_VALUE); replacer.process(sampler, Collections.emptyList(), null, vars); assertThat(sampler.getArguments().getArgument(0).getValue()) .isEqualTo(PARAM_VALUE); } }
java
13
0.748152
95
38.981132
159
starcoderdata
import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; const modulePath = '../src/components/app.jsx'; jest.dontMock(modulePath); const AppView = require(modulePath); describe('AppView', () => { it('Has main class', () => { let appView = TestUtils.renderIntoDocument(<AppView />); let appNode = ReactDOM.findDOMNode(appView); expect(appNode.className).toEqual('main'); }); });
javascript
13
0.677043
64
22.363636
22
starcoderdata
import {withIdBqtG, withIdBqt, withBqtG, oneModifiedResponse, noneModifiedResponse} from "test-api-express-mongo" import api from "../../../../src" import ENV from "../../../../src/env" import {cols} from "../../../../src/collections" import {init, withTest} from "test-api-express-mongo" import {gateauTrunk} from "../../../database/gateau" import {authGod, authSimple} from "../../../database/users" describe('PUT Trunks', function () { beforeEach(init(api, ENV, cols)) it('update without auth', withTest({ req: { method: "PUT", url: `/api/tree/trunk/${gateauTrunk._id}`, body: { name: "bisou" } }, res: { code: 401 } })) it('update without good auth', withTest({ req: { method: "PUT", url: `/api/tree/trunk/${gateauTrunk._id}`, body: { name: "bisou" }, headers: authSimple }, res: { code: 403 } })) it('update bqt', withTest({ req: { method: "PUT", url: `/api/tree/trunk/${gateauTrunk._id}`, body: { ...withBqtG(gateauTrunk.quantity.bqt * 2, "Mass"), }, headers: authGod }, res: { body: oneModifiedResponse }, db: { expected: { colname: cols.TRUNK, doc: { ...gateauTrunk, ...withBqtG(gateauTrunk.quantity.bqt * 2, "Mass") } } } })) it('update name', withTest({ req: { method: "PUT", url: `/api/tree/trunk/${gateauTrunk._id}`, body: { name: "bisou" }, headers: authGod }, res: { body: oneModifiedResponse }, db: { expected: { colname: cols.TRUNK, doc: { ...gateauTrunk, name: "bisou" } } } })) it('update without changes trunk', withTest({ req: { method: "PUT", url: `/api/tree/trunk/${gateauTrunk._id}`, body: {}, headers: authGod }, res: { body: noneModifiedResponse }, db: { expected: { colname: cols.TRUNK, doc: gateauTrunk } } })) it('update without b trunk', withTest({ req: { method: "PUT", url: `/api/tree/trunk/${gateauTrunk._id}`, body: { name: "baChar", quantity: {bqt: 1000} }, headers: authGod }, res: { code: 400 } })) })
javascript
24
0.414531
113
25.146789
109
starcoderdata
from datetime import datetime import logging from statistics import mean import yaml from .singleton import SITES class Anime(object): """Anime""" @staticmethod def load(filename): animes = [] with open(filename) as fp: for slug, attrs in yaml.load(fp).items(): if attrs is None: attrs = {} animes.append(Anime(slug, **attrs)) return animes @staticmethod def dump(animes, filename): objs = {anime.slug: {'names': anime.names, 'sites': anime.sites} for anime in animes} with open(filename, 'w') as fp: return yaml.dump(objs, fp, allow_unicode=True, default_flow_style=False) def __init__(self, slug, names=None, sites=None, final=False): if names is None: names = {} if sites is None: sites = {} self.slug = slug self.names = names self.sites = sites self.final = final @property def rating(self): ratings = [] for site_id, info in self.sites.items(): if ((info is None or info.get('rating') is None or info.get('rating_count', 0) < 10)): continue ratings.append(SITES[site_id].unify_rating(info['rating'])) return mean(ratings) if ratings else None def name(self, locale='ja-jp'): return self.names.get(locale, self.names['ja-jp']) def update_info(self): self.update_names() self.update_ids() def update_names(self): names = SITES['kitsu'].get_names(self.slug) try: name = SITES['bangumi'].get_zh_cn_name(names['ja-jp']) if name: names['zh-cn'] = name except Exception as err: logging.warn('Failed to get zh-CN name from Bangumi: %s', err) names.update(self.names) # Keep existing names. self.names = names def update_ids(self): for site_id, site in SITES.items(): # Skip existing sites unless they use dynamic ids. # Notice that we'll skip even self.sites[site_id] is None. # This ensures that there's a way to override false matches. if not site.DYNAMIC_ID and site_id in self.sites: continue # Don't update if it is already final. if site.DYNAMIC_ID and self.final: continue logging.info('%s...', site_id) if site_id == 'kitsu': id = site.search_by_slug(self.slug) # Ensures 1-to-1 mappings. else: id = site.search(self.names) if id is not None: if ((self.sites.get(site_id) and self.sites[site_id].get('id') == id)): continue # The ID doesn't change. self.sites[site_id] = {'id': id} logging.info(' => %s', site.info_url(id)) def update_ratings(self): for site_id, info in self.sites.items(): if info is None: continue logging.info('%s...', site_id) rating, count = SITES[site_id].get_rating(info['id']) if rating is not None: info['rating'] = rating if count is None: info.pop('rating_count', None) logging.info(' => %f', rating) else: info['rating_count'] = count logging.info(' => %g (%d)', rating, count) info['updated_at'] = iso8601_now() def iso8601_now(): return datetime.utcnow().replace(microsecond=0).isoformat() + 'Z'
python
18
0.515168
79
29.306452
124
starcoderdata
/******************** (C) COPYRIGHT 2011 STMicroelectronics ******************** * File Name : hw_config.h * Author : MCD Application Team * Version : V3.3.0 * Date : 21-March-2011 * Description : Hardware Configuration & Setup ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __HW_CONFIG_H #define __HW_CONFIG_H /* Includes ------------------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /* Codec Control defines */ #define PLLon 1 #define PLLoff 0 #define VerifData 1 #define NoVerifData 0 #define Codec_PDN_GPIO GPIOG #define Codec_PDN_Pin GPIO_Pin_11 #define BufferSize 100 #define CodecAddress 0x27 /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported define -----------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ /* External variables --------------------------------------------------------*/ void Set_System(void); void Set_USBClock(void); void Enter_LowPowerMode(void); void Leave_LowPowerMode(void); void USB_Config(void); void Audio_Config(void); void USB_Cable_Config (FunctionalState NewState); void Speaker_Config(void); void NVIC_Config(void); void GPIO_Config(void); uint32_t Sound_release(uint16_t Standard, uint16_t MCLKOutput, uint16_t AudioFreq, uint8_t AudioRepetitions); void I2S_Config(uint16_t Standard, uint16_t MCLKOutput, uint16_t AudioFreq); void Codec_PowerDown(void); uint32_t I2SCodec_WriteRegister(uint32_t RegisterAddr, uint32_t RegisterValue, uint32_t Verify); uint32_t Codec_SpeakerConfig(uint16_t I2S_Standard, uint8_t volume, uint32_t verif, uint8_t pll); void Get_SerialNum(void); #endif /*__HW_CONFIG_H*/ /******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
c
6
0.5404
109
43.966667
60
starcoderdata
pub fn objects() { // custom data type let mut my_flag = Flag { country: String::from("Konoha"), pcolor: 128, scolor: 255 }; println!("Flag Specs: {} {} {}", my_flag.country, my_flag.pcolor, my_flag.scolor); my_flag.pcolor = 0; println!("Flag Specs: {:?}", (my_flag.country, my_flag.pcolor, my_flag.scolor)); let mut your_flag = FlagTuple(String::from("Castle"), 165, 32); println!("Your Flag: {} {} {}", your_flag.0, your_flag.1, your_flag.2); your_flag.2 = 12; println!("Your Flag: {:?}", (your_flag.0, your_flag.1, your_flag.2)); let mut sasuke = Ninja::new("Genin", "Fire", "Sharingan"); println!("Sasuke: {} {} {}", sasuke.level, sasuke.style, sasuke.speciality); println!("Sasuke Speciality: {}", sasuke.get_speciality()); sasuke.set_speciality("Rinnegan"); println!("Sasuke: {:?}", sasuke.to_tuple()); }
rust
10
0.585284
86
38.043478
23
inline
''' HDPBetaOptimizer.py Functions for obtaining point estimates of the HDP global appearance probabilities. Model Notation -------- HDP with a finite truncation to K active components v := K-length vector with entries in [0,1] beta := K+1-length vector with entries in [0,1] entries must sum to unity. sum(beta) = 1. gamma := scalar, gamma > 0 top concentration parameter alpha := scalar, alpha > 0 doc-level concetration parameter Generate stick breaking fractions v v[k] ~ Beta(1, gamma) Then deterministically obtain beta beta[k] = v[k] prod(1 - v[:k]) Generate each document-level distribution for d in [1, 2, ... d ... nDoc]: pi[d] ~ Dirichlet_{K+1}( alpha * beta ) Notes ------- Relies on approximation to E[ log norm const of Dirichlet], which requires parameter gamma < 1 Set gamma close to 1 if you want variance low enough that recovering true "beta" parameters is feasible Set gamma close to zero (even like 0.1) makes recovered E[beta] very different than the "true" beta ''' import warnings import numpy as np import scipy.optimize import scipy.io from scipy.special import gammaln, digamma, polygamma import datetime import logging Log = logging.getLogger('bnpy') EPS = 10*np.finfo(float).eps def estimate_v(gamma=1.0, alpha=0.5, nDoc=0, K=None, sumLogPi=None, initV=None, Pi=None, doVerbose=False, method='l_bfgs', **kwargs): ''' Solve optimization problem to estimate parameters v delta(v_k) = Beta( v_k | 1, gamma) Returns ------- v : K x 1 vector of positive values ''' alpha = float(alpha) gamma = float(gamma) nDoc = int(nDoc) if K is None: K = sumLogPi.size - 1 K = int(K) if sumLogPi.ndim == 2: sumLogPi = np.sum(sumLogPi, axis=0) if initV is None: initV = np.random.rand(K) myFunc = lambda Cvec: objectiveFunc(Cvec, alpha, gamma, nDoc, sumLogPi) myGrad = lambda Cvec: objectiveGradient(Cvec, alpha, gamma, nDoc, sumLogPi) bestCvec, bestf, Info = scipy.optimize.fmin_l_bfgs_b(myFunc, np.log(initV), fprime=myGrad, disp=None) Uvec = np.exp(bestCvec) return Uvec def objectiveFunc(Cvec, alpha, gamma, nDoc, sumLogPi): ''' Calculate unconstrained objective function for HDP variational learning ''' assert not np.any(np.isnan(Cvec)) assert not np.any(np.isinf(Cvec)) Uvec = np.exp(Cvec) assert not np.any(np.isinf(Uvec)) K = Uvec.size # PREPARE building-block expectations beta = v2beta(Uvec) # CALCULATE each term in the function obj_v = (gamma - 1) * np.sum(np.log(1-Uvec)) obj_v -= nDoc * np.sum(gammaln(alpha * beta)) obj_v += alpha * np.sum(beta * sumLogPi) assert np.all(np.logical_not(np.isnan(obj_v))) f = -1 * obj_v return f def objectiveGradient(Cvec, alpha, gamma, nDoc, sumLogPi): ''' Calculate gradient of objectiveFunc, objective for HDP variational Returns ------- gvec : 2*K length vector, where each entry gives partial derivative with respect to the corresponding entry of Cvec ''' # UNPACK unconstrained input Cvec into intended params U Uvec = np.exp(Cvec) assert np.all(Uvec > 0) assert np.all(Uvec < 1) beta = v2beta(Uvec) dBdv = d_beta(Uvec, beta) gvecU = -1 * (gamma - 1.0) / (1.0 - Uvec) gvecU -= nDoc * alpha * np.dot(dBdv, digamma(alpha*beta)) gvecU += alpha * np.dot(dBdv, sumLogPi) gvecU = -1 * gvecU # Apply chain rule! assert np.all(np.logical_not(np.isnan(gvecU))) gvecC = gvecU * Uvec return -1.0*gvecC def d_beta( v, beta): ''' Compute gradient of beta with respect to v Returns ------- d_beta : K x K+1 matrix, where d_beta[m,k] = d beta[k] / d v[m] ''' K = v.size dbdv = np.zeros( (K, K+1) ) for k in xrange( K ): dbdv[k, k] = beta[k]/v[k] dbdv[k, k+1:] = -1.0*beta[k+1:]/(1-v[k]) return dbdv def v2beta(v): ''' Convert to stick-breaking fractions v to probability vector beta Args -------- v : K-len vector, v[k] in interval [0, 1] Returns -------- beta : K+1-len vector, with positive entries that sum to 1 ''' v = np.asarray(v) c1mv = np.hstack([1.0, np.cumprod(1 - v)]) beta = np.hstack([v,1.0]) * c1mv assert np.allclose(beta.sum(), 1) # Force away from edges 0 or 1 for numerical stability beta = np.maximum(beta,EPS) beta = np.minimum(beta,1-EPS) return beta def beta2v( beta ): ''' Convert probability vector beta to stick-breaking fractions v Args -------- beta : K+1-len vector, with positive entries that sum to 1 Returns -------- v : K-len vector, v[k] in interval [0, 1] ''' beta = np.asarray(beta) K = beta.size v = np.zeros(K-1) cb = beta.copy() for k in range(K-1): cb[k] = 1 - cb[k]/np.prod( cb[:k] ) v[k] = beta[k]/np.prod( cb[:k] ) # Force away from edges 0 or 1 for numerical stability v = np.maximum(v,EPS) v = np.minimum(v,1-EPS) return v ########################################################### Test utils ########################################################### def createToyData(v, alpha=1.0, gamma=0.5, nDoc=0, seed=42): ''' Generate example Pi matrix, each row is a sample ''' v = np.asarray(v, dtype=np.float64) K = v.size beta = v2beta(v) PRNG = np.random.RandomState(seed) Pi = PRNG.dirichlet( gamma*beta, size=nDoc) return dict(Pi=Pi, alpha=alpha, gamma=gamma, nDoc=nDoc, K=K)
python
13
0.626264
133
27.025773
194
starcoderdata
import subprocess, re from pkg_resources import get_distribution, DistributionNotFound from datetime import datetime # d[year][month][day] example: 20200420 ver_date = datetime.now().strftime("d%Y%m%d") def version(): las_version = '' ''' Look for distribution version This looks for a distribution in roughly the following order. - Local development install installed with 'pip install -e "."' Note: The '-e' puts the install in an editable-mode where it it looks at the source directory and reactes to changes in the code. - A lasio.egg-info dir in the current working directory. Note!: An existing lasio.egg-info dir can hide an offical release install for the case where an offical release is also installed. The lasio.egg-info can be an artifact of running 'pip install -e "."', or of runnng 'bdist_wheel' to create a release package. - An official release installed with 'pip install lasio' or a development release installed with 'pip install "."' ''' try: las_version = get_distribution(__package__).version except DistributionNotFound: # TODO: Add logger message pass ''' If no distribution is found, check if the current working directory is in a version control system and attempt to derive a version string from the vsc. ''' if not las_version.strip(): las_version = _get_vcs_version() ''' Else set a sensible default version 0.25.0 was the most recent version before this change so it is being used as teh default basline. ''' if not las_version.strip(): las_version = ( "0.25.0.dev0+unknown-post-dist-version.{}".format(ver_date) ) return las_version def _get_vcs_version(): semver_regex = re.compile('^v\d+\.\d+\.\d+') # examples: 'v0.0.0', 'v0.25.0' split_regex = re.compile('-') local_las_version = '' tmpstr = '' tmpbytes = b'' ''' https://git-scm.com/docs/git-describe git describe --tags --match 'v*' This cmd will find the most recent tag starting with 'v' on the current branch. ''' try: tmpbytes = subprocess.check_output( ["git", "describe", "--tags", "--match", "v*"], stderr=subprocess.STDOUT, ).strip() except subprocess.CalledProcessError: pass # Convert byte string to text string try: tmpstr = "".join( chr(x) for x in tmpbytes) except TypeError as e: print("Error: {}\n".format(e)) if semver_regex.match(tmpstr): tmpstr = tmpstr[1:] (rel_ver, commits_since_rel_ver, current_commit) = split_regex.split(tmpstr) local_las_version = "{}.dev{}+{}.{}".format( rel_ver, commits_since_rel_ver, current_commit, ver_date ) return local_las_version
python
13
0.619718
84
30.989011
91
starcoderdata
def __init__ (self, transport): """ transport is the source of the connection (e.g, TCPTransport). """ EventMixin.__init__(self) self._is_connected = True self._transport = transport self._newlines = False # If we connect to another messenger, this contains our session ID as far # as it is concerned. self._remote_session_id = None # Transports that don't do their own encapsulation can use _recv_raw(), # which uses this. (Such should probably be broken into a subclass.) self._buf = bytes() key,num = self._transport._nexus.generate_session() self._session_id,self._session_num = key,num
python
9
0.659021
77
33.473684
19
inline
#ifndef __SOAR_H__ #define __SOAR_H__ #include "params.h" #define __PAGEFLIP__ //remove to show draw #define __ALWAYS_MOVE__ #define __FPSCOUNT__ //remove to hide fps counter #define m7_screenbase 0x17 #define m7_charbase 2 #define CHARBLOCK(num) VRAM+(num * 0x4000) #define SCRBLOCK(num) VRAM+(num*0x800) #define FPS_COUNTER *(int*)(0x203fff8) #define FPS_CURRENT *(int*)(0x203fffc) #define MIN_Z_DISTANCE 24 #define MAX_Z_DISTANCE 512 #define SHADOW_DISTANCE MIN_Z_DISTANCE+16 #define FOG_DISTANCE (MAX_Z_DISTANCE>>1) #define NUM_ALTITUDES 16 #define MAP_DIMENSIONS 1024 #define MAP_DIMENSIONS_LOG2 10 #define MAP_YOFS 170 #define INC_ZSTEP ((zdist>>6)+(zdist>>7)+((zdist>>8)<<2)+2) #define SKY_COLOUR 0x7f0f #define SEA_COLOUR 0x1840 #define SEA_COLOUR_SUNSET 0x0820 #define R_MASK(clr) (clr & 0b11111) #define G_MASK(clr) (clr>>5)&0b11111 #define B_MASK(clr) (clr>>10)&0b11111 #define CEL_SHADE_THRESHOLD 6 #define g_yBuffer *((volatile u8*)(0x5000000)) //using the palette buffer lmao #define gCurrentMusic *(volatile u16*)(0x2024e60) //currently playing music #define VID_FLIP 0xa000 //page buffers #define DCNT_PAGE 0x10 #define MOVEMENT_STEP 4 #define FREE_WRAM 0x3007000 //i sure hope this is free lol it's between the heap and the stack #define WM_CURSOR ((volatile int*)(0x3005288)) //[0] is x<<8 and [1] is y<<8 extern const u16 colourMap[]; extern const u16 colourMap_sunset[]; extern const u8 heightMap[]; extern const u16 xMatrix[]; extern const u8 hosTables[12][0x100][0x100]; extern const void* pkSprite; extern const void* locationSprites; extern const void* pkPal; extern const void* minimapSprite; extern const void* minimapPal; extern const void* miniCursorSprite; extern const void* fpsSprite; extern const void* lensFlareSprite; extern const void* lensFlarePal; extern const int* SkyBG; extern const int* SkyBG_lighter; extern const int* SkyBG_darker; extern const int* SkyBG_sunset; extern const s16 pleftmatrix[0x10][MAX_Z_DISTANCE]; extern const int skies[5]; extern const u16 fogClrs[5]; extern const u16 gObj_32x8[3]; extern const u16 gObj_64x64[3]; extern const u16 gObj_aff32x32[3]; extern const u8 WorldMapNodes[11][16]; extern const u8 translatedLocations[]; //from tonc // tile 8x8@4bpp: 32bytes; 8 ints typedef struct { u32 data[8]; } TILE, TILE4; // d-tile: double-sized tile (8bpp) typedef struct { u32 data[16]; } TILE8; // tile block: 32x16 tiles, 16x16 d-tiles typedef TILE CHARBLOCK[512]; typedef TILE8 CHARBLOCK8[256]; #define pal_obj_mem 0x5000200 #define tile_mem ( (CHARBLOCK*)0x06000000) #define tile8_mem ((CHARBLOCK8*)0x06000000) #define DX_TABLE(step) { \ step *0, \ step *0.38, \ step *0.71, \ step *0.92, \ step *1, \ step *0.92, \ step *0.71, \ step *0.38, \ step *0, \ step *-0.38, \ step *-0.71, \ step *-0.92, \ step *-1, \ step *-0.92, \ step *-0.71, \ step *-0.38 \ } #define DY_TABLE(step) { \ step *-1, \ step *-0.92, \ step *-0.71, \ step *-0.38, \ step *0, \ step *0.38, \ step *0.71, \ step *0.92, \ step *1, \ step *0.92, \ step *0.71, \ step *0.38, \ step *0, \ step *-0.38, \ step *-0.71, \ step *-0.92 \ } extern const s16 cam_dx_Angles[16]; extern const s16 cam_dy_Angles[16]; extern const s16 cam_pivot_dx_Angles[16]; extern const s16 cam_pivot_dy_Angles[16]; typedef struct SoarProc SoarProc; struct SoarProc { //so we can store this info locally. PROC_FIELDS; int sPlayerPosX; int sPlayerPosY; int sPlayerPosZ; int sPlayerStepZ; int sPlayerYaw; u16* vid_page; s8 sunTransition; u8 ShowMap:1; u8 ShowFPS: 1; u8 takeOffTransition: 1; u8 landingTransition: 1; u8 unused:4; s8 oceanOffset; u8 oceanClock; int sFocusPtX; int sFocusPtY; int location; int sunsetVal; }; typedef struct Point Point; struct Point { int x; int y; }; //16 possible angles for yaw enum Angles{ a_N, a_NNE, a_NE, a_ENE, a_E, a_ESE, a_SE, a_SSE, a_S, a_SSW, a_SW, a_WSW, a_W, a_WNW, a_NW, a_NNW }; enum BumpDirs{ bump_up, bump_down, bump_left, bump_right, bump_fwd, bump_back }; void NewWMLoop(SoarProc* CurrentProc); int thumb_loop(SoarProc* CurrentProc); static inline int getPtHeight_thumb(int ptx, int pty); static inline void DrawVerticalLine(int xcoord, int ystart, int ylen, u16 color, u16* vid_page); static inline u8 getScrHeight(int ptx, int pty, int altitude, int zdist); static inline u8 getPtHeight(int ptx, int pty); static inline u16 getPointColour(int ptx, int pty, int sunsetVal); static inline Point getPLeft(int camera_x, int camera_y, int angle, int zdist); static inline void Render(SoarProc* CurrentProc); static inline void UpdateSprites(SoarProc* CurrentProc); void NewFadeOut(int time); void LoadSprite(); void EndLoop(SoarProc* CurrentProc); void MoveLord(SoarProc* CurrentProc); void OnVBlankMain(); void BumpScreen(int direction); #endif
c
7
0.606173
96
25.25463
216
starcoderdata
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; long long a1; cin >> a1; long long p1 = 0, h1 = a1; long long p2 = 0, h2 = a1; for (int i = 2; i <= n; ++i) { long long a; cin >> a; long long p = min(p1 + abs(h1 - a), p2 + abs(h2 - a)); p1 = p2; h1 = h2; p2 = p; h2 = a; } cout << p2 << endl; return 0; }
c++
13
0.433498
58
12.566667
30
codenet
static CORE_ADDR call_site_to_target_addr (struct gdbarch *call_site_gdbarch, struct call_site *call_site, struct frame_info *caller_frame) { switch (FIELD_LOC_KIND (call_site->target)) { case FIELD_LOC_KIND_DWARF_BLOCK: { struct dwarf2_locexpr_baton *dwarf_block; struct value *val; struct type *caller_core_addr_type; struct gdbarch *caller_arch; dwarf_block = FIELD_DWARF_BLOCK (call_site->target); if (dwarf_block == NULL) { struct bound_minimal_symbol msym; msym = lookup_minimal_symbol_by_pc (call_site->pc - 1); throw_error (NO_ENTRY_VALUE_ERROR, _("DW_AT_call_target is not specified at %s in %s"), paddress (call_site_gdbarch, call_site->pc), (msym.minsym == NULL ? "???" : msym.minsym->print_name ())); } if (caller_frame == NULL) { struct bound_minimal_symbol msym; msym = lookup_minimal_symbol_by_pc (call_site->pc - 1); throw_error (NO_ENTRY_VALUE_ERROR, _("DW_AT_call_target DWARF block resolving " "requires known frame which is currently not " "available at %s in %s"), paddress (call_site_gdbarch, call_site->pc), (msym.minsym == NULL ? "???" : msym.minsym->print_name ())); } caller_arch = get_frame_arch (caller_frame); caller_core_addr_type = builtin_type (caller_arch)->builtin_func_ptr; val = dwarf2_evaluate_loc_desc (caller_core_addr_type, caller_frame, dwarf_block->data, dwarf_block->size, dwarf_block->per_cu, dwarf_block->per_objfile); /* DW_AT_call_target is a DWARF expression, not a DWARF location. */ if (VALUE_LVAL (val) == lval_memory) return value_address (val); else return value_as_address (val); } case FIELD_LOC_KIND_PHYSNAME: { const char *physname; struct bound_minimal_symbol msym; physname = FIELD_STATIC_PHYSNAME (call_site->target); /* Handle both the mangled and demangled PHYSNAME. */ msym = lookup_minimal_symbol (physname, NULL, NULL); if (msym.minsym == NULL) { msym = lookup_minimal_symbol_by_pc (call_site->pc - 1); throw_error (NO_ENTRY_VALUE_ERROR, _("Cannot find function \"%s\" for a call site target " "at %s in %s"), physname, paddress (call_site_gdbarch, call_site->pc), (msym.minsym == NULL ? "???" : msym.minsym->print_name ())); } return BMSYMBOL_VALUE_ADDRESS (msym); } case FIELD_LOC_KIND_PHYSADDR: return FIELD_STATIC_PHYSADDR (call_site->target); default: internal_error (__FILE__, __LINE__, _("invalid call site target kind")); } }
c
17
0.635019
78
29.607143
84
inline
#pragma once #include "network/service/base_service.hpp" #include "cmder_service.hpp" #include "cmder_reader.hpp" #include "network/base/log.hpp" #include "network/util/thread.hpp" #include "network/util/string.hpp" namespace cytx { struct cmd_node_info { int index; cmd_node* cmd; }; class execute_cmder_service : public base_service { public: bool init() { cmder_service_ = service_mgr_->get(); std::string cmder_config_path = world_ptr_->get_string_or("cmder_config_path", "config/cmd.xml"); cmder_reader::read_config(config_, cmder_config_path); std::string profile = world_ptr_->get_string_or("profile", config_.profile); LOGGER_INFO("profile {}", profile); if (config_.cmds.find(profile) == config_.cmds.end()) { LOGGER_ERROR("cannt find {} cmds, invalid profile", profile); return false; } cmder_service_->register_alias(config_.alias); cmds_ptr_ = &(config_.cmds[profile]); for (int i = 0; (int)i < cmds_ptr_->size(); ++i) { cmd_node* cmd_node_ptr = &(cmds_ptr_->at(i)); if (!cmd_node_ptr->name.empty()) { cmd_map_[cmd_node_ptr->name] = cmd_node_info{ i, cmd_node_ptr }; } } return true; } public: int execute() { int ret = 0; while (cur_cmd_index_ >= 0 && cur_cmd_index_ < (int)cmds_ptr_->size()) { ret = execute_one(); } return ret; } private: int execute_one() { cmd_node* node = &(cmds_ptr_->at(cur_cmd_index_)); return execute_node(node); } int execute_node(cmd_node* node) { int ret = 0; if (!util::is_empty_or_white_spate(node->cmdStr) && node->times > 0) { ret = repeat_execute_cmd_node(node); } cur_cmd_index_ = get_next_cmd_node_index(node, ret == 0); return ret; } int repeat_execute_cmd_node(cmd_node* node) { if (node->delay > 0) { util::sleep(node->delay); } int current_times = 0; while (current_times < node->times) { int ret = execute_cmd_string(node->cmdStr); if (ret != 0) return ret; ++current_times; if (current_times < node->times && node->interval > 0) { util::sleep(node->interval); } } return 0; } int execute_cmd_string(std::string cmd_str) { string_util::trim(cmd_str); auto strs = string_util::split(cmd_str, "\r\n"); for (auto& str : strs) { int ret = execute_cmd_one_line(str); if (ret != 0) return ret; } return 0; } int execute_cmd_one_line(std::string cmd_str) { //去除结尾的注释 string_util::trim_first(cmd_str, "#"); string_util::trim(cmd_str); if (cmd_str.empty()) return 0; //以注释开头 if (boost::starts_with(cmd_str, "#")) return 0; return cmder_service_->handle_input(cmd_str); } int get_next_cmd_node_index(cmd_node* cur_cmd_ptr, bool is_success) { std::string next_cmd_name; next_cmd_name = is_success ? cur_cmd_ptr->nextCmd : cur_cmd_ptr->nextCmdWhenFailed; if (next_cmd_name.empty() && is_success) { return ++cur_cmd_index_; } else if (!next_cmd_name.empty()) { auto it = cmd_map_.find(next_cmd_name); if (it != cmd_map_.end()) { return it->second.index; } } return -1; } private: cmder_service* cmder_service_ = nullptr; cmder_config config_; std::vector cmds_ptr_ = nullptr; int cur_cmd_index_ = 0; std::unordered_map<std::string, cmd_node_info> cmd_map_; }; REG_SERVICE(execute_cmder_service); }
c++
16
0.453524
109
26.029762
168
starcoderdata
<?php /* * Copyright (C) 2021 (Nowise Systems). * * 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. */ declare(strict_types=1); namespace UUP\BuildSystem\Goal; use UUP\BuildSystem\Node\NodeInterface; /** * The goal registry. * * Provides lookup of dependency tree nodes from goal name. The array is a * single dimension listing having goal name as lookup key. Works as a hash * table where values are references into the dependency tree. * * @author (Nowise Systems) */ class GoalRegistry { private array $nodes = []; /** * Get all nodes in registry. * @return array */ public function getNodes(): array { return $this->nodes; } /** * Get tree node for goal. * @param string $name The goal name. * @return NodeInterface */ public function getNode(string $name): NodeInterface { return $this->nodes[$name]; } /** * Check if goal is present. * @param string $name The goal name. * @return bool */ public function hasNode(string $name): bool { return array_key_exists($name, $this->nodes); } /** * Add tree node to this registry. * @param NodeInterface $node The tree node. */ public function addNode(NodeInterface $node): void { $this->nodes[$node->getTarget()->getName()] = $node; } }
php
11
0.647307
75
24.253333
75
starcoderdata
from typing import List from fastapi import APIRouter from samey.table_crud import * from . import tables from .models import * router = APIRouter() @router.get("/", response_model=List[Team]) def list_teams(): return query(tables.Team) @router.post("/", response_model=Team, status_code=201) def create_team(team_in: Team): return create(tables.Team, team_in) @router.get("/{id}", response_model=Team) def get_team(id: str): return get_or_error(tables.Team, id, "Team not found") @router.put("/{id}", response_model=Team) def update_team(id: str, team_in: Team): return update(tables.Team, id, team_in) @router.delete("/{id}", status_code=204) def delete_team(id: str): delete(tables.Team, id)
python
8
0.703145
65
21.083333
36
starcoderdata
"use strict"; var opcoes_cadastro_component_1 = require('./opcoes-cadastro.component'); exports.cadastroRoutes = [ { path: 'cadastro', component: opcoes_cadastro_component_1.OpcoesCadastroComponent } ]; //# sourceMappingURL=cadastro.routes.js.map
javascript
6
0.770548
88
40.857143
7
starcoderdata
const longestCommonPrefix = require("./index"); test("base case returns prefix", () => { expect(longestCommonPrefix(["flower", "flow", "flight"])).toEqual("fl"); }); test("base case returns prefix", () => { expect(longestCommonPrefix(["cat", "dog", "hi"])).toEqual(""); });
javascript
15
0.628571
74
30.111111
9
starcoderdata
package scanner import "github.com/wdevore/Golang-Loxlang/src/api" var Keywords = map[string]api.TokenType{ "const": api.CONST, "import": api.IMPORT, "print": api.PRINT, "var": api.VAR, "nil": api.NIL, "true": api.TRUE, "false": api.FALSE, "and": api.AND, "or": api.OR, "if": api.IF, "else": api.ELSE, "while": api.WHILE, "for": api.FOR, "break": api.BREAK, "continue": api.CONTINUE, "fun": api.FUN, "return": api.RETURN, "code": api.CODE, "alignTo": api.ALIGN_TO, "global": api.GLOBAL, "at": api.AT, "as": api.AS, "use": api.USE, "readOnly": api.READ_ONLY, "byte": api.BYTE, "half": api.HALF, "word": api.WORD, "data": api.DATA, "int": api.INT, "hi": api.HI, "lo": api.LO, // Instructions "add": api.ADD, "sub": api.SUB, "xor": api.XOR, // "or": OR, // "and": AND, "sll": api.SLL, "srl": api.SRL, "sra": api.SRA, "slt": api.SLT, "sltu": api.SLTU, "addi": api.ADDI, "xori": api.XORI, "ori": api.ORI, "andi": api.ANDI, "slli": api.SLLI, "srli": api.SRLI, "srai": api.SRAI, "slti": api.SLTI, "sltiu": api.SLTIU, "lb": api.LB, "lh": api.LH, "lw": api.LW, "lbu": api.LBU, "lhu": api.LHU, "sb": api.SB, "sh": api.SH, "sw": api.SW, "beq": api.BEQ, "bne": api.BNE, "blt": api.BLT, "bge": api.BGE, "bltu": api.BLTU, "bgeu": api.BGEU, "jal": api.JAL, "jalr": api.JALR, "lui": api.LUI, "auipc": api.AUIPC, "ecall": api.ECALL, "ebreak": api.EBREAK, // Pseudo instructions "la": api.LA, "nop": api.NOP, "li": api.LI, "mv": api.MV, "not": api.NOT, "neg": api.NEG, "negw": api.NEGW, "sext": api.SEXT, "seqz": api.SEQZ, "snez": api.SNEZ, "sltz": api.SLTZ, "sgtz": api.SGTZ, "beqz": api.BEQZ, "bnez": api.BNEZ, "blez": api.BLEZ, "bgez": api.BGEZ, "bltz": api.BLTZ, "bgtz": api.BGTZ, "bgt": api.BGT, "ble": api.BLE, "bgtu": api.BGTU, "bleu": api.BLEU, "j": api.J, "ret": api.RET, "call": api.CALL, "tail": api.TAIL, }
go
9
0.511486
50
19.314286
105
starcoderdata
#!/usr/bin/env python3 ''' keystore - compress and encrypt your private keys author: License: MIT ''' import os import sys import json def read(filepath): path = None try: if os.path.isfile(os.path.expanduser(filepath)): path = os.path.expanduser(filepath) elif os.path.isfile('./.keystorerc'): path = './.keystorerc' else: raise OSError('''The config file .keystorerc is not found in home or local working directory. Please refer to https://pypi.python.org/pypi/keystore for setting up a .keystorerc file.''') with open(path) as f: conf = json.loads(f.read()) return conf except OSError as err: print('Unable to open config: {}'.format(err), file=sys.stderr) return None except json.JSONDecodeError as err: print('Unable to parse config: {}'.format(err), file=sys.stderr) return None
python
13
0.668552
99
24.285714
35
starcoderdata
package util import ( "fmt" "testing" ) func TestRegexp(t *testing.T) { mobile := MatchMobile("13036201053") fmt.Println(mobile) email := MatchEmail(" fmt.Println(email) card := MatchIDCard("36220120010205891x") fmt.Println(card) code := MatchPostalCode("336000") fmt.Println(code) qq := MatchQQ("1511181420") fmt.Println(qq) url := MatchUrl("https://www.wenlincheng.com") fmt.Println(url) username := MatchUsername("Pikaman") fmt.Println(username) chinese := MatchChinese("成") fmt.Println(chinese) }
go
8
0.697026
47
15.30303
33
starcoderdata
function Tri(x, y, {hue, saturation, brightness, scale, shimmerData}){ var self = this; const width = 30; const height = 60; const right = PI/2; const left = -PI/2; const angle = chance(0.5) ? left: right; self.pos = createVector(x, y); self.initialBrightness = brightness; self.brightness = brightness; self.initialSaturation = saturation; self.saturation = saturation; self.hue = hue; self.initialHue = hue; self.alpha = 0; function shimmer(min, max){ return map(sin(y + millis() * 0.0016), -1, 1, min, max); } self.center = function(){ var offsetWidth = (width * scale) - (width * scale) / 2.9; var offsetHeight = (height * scale) / 2; if(angle === right){ return createVector(self.pos.x - offsetWidth, self.pos.y + offsetHeight); } else { return createVector(self.pos.x + offsetWidth, self.pos.y - offsetHeight); } }; function mapSin(value, min, max){ return map(sin(value), -1, 1, min, max); } function seconds(){ return millis()/1000; } self.display = function(){ push(); colorMode(HSB, 360, 100, 100, 1); noStroke(); // hsb 239 68 59 // rgb 48 50 150 // b 59 s 68 // blue // hsb 159 84 91 // rgb 38 232 165 // b 91 s 84 fill(self.hue + shimmer(shimmerData.min, shimmerData.max), self.saturation, self.brightness, self.alpha); var x = self.pos.x; var y = self.pos.y; var a = map(scale, 2.2, 4.3, 1, 5); var multScale = mapSin(y + cos(tan(3 * x)) + (seconds() / a), 1, 1.3); var offsetX = mapSin((y * x) + seconds(), 0, 10); var offsetY = mapSin((y / x) + seconds() / a, 0, 10); var points = {x1: 0, y1: 0, x2: height * scale * multScale, y2: 0, x3: width * scale * multScale, y3: height * scale * multScale}; const shakeScale = 0.9; translate(x + offsetX - (screenShake.amount.x * shakeScale), y + offsetY - (screenShake.amount.y * shakeScale)); rotate(angle); triangle(points.x1, points.y1, points.x2, points.y2, points.x3, points.y3); pop(); }; }
javascript
19
0.526895
120
29.269231
78
starcoderdata
@Test public void testStartStop10Rserves() throws Exception { System.err.println("====================================== testStartStop10Rserves"); final Thread[] tests = new Thread[10]; final RserveDaemon[] daemons = new RserveDaemon[tests.length]; final RserverConf[] confs = new RserverConf[tests.length]; for (int ii = 0; ii < tests.length; ii++) { final int i = ii; tests[i] = new Thread(new Runnable() { @Override public void run() { try { System.err.println("--- Start Rserve daemon " + i); confs[i] = new RserverConf(RserverConf.DEFAULT_RSERVE_HOST, -1, null, null);// -1 will let Rdaemon find a free port to host Rserve daemons[i] = new RserveDaemon(confs[i], new RLogPrintStream(System.out)); daemons[i].start(); System.err.println("--- Rserve daemon " + i+" Started"); confs[i] = daemons[i].conf; } catch (Exception e) { assert false : e.getMessage(); } } }); tests[i].start(); Thread.sleep(100); } for (int i = 0; i < tests.length; i++) { System.err.println("--- Wait Rserve daemon " + i); tests[i].join(); } for (int i = 0; i < tests.length; i++) { //System.err.println("--- Get THIS Rserve PID"); //int pid = StartRserve.getLastRservePID(); //System.err.println("--- " + pid); //assert pid != last_pid : "Did not start Rserve (no new PID)"; System.err.println("--- Create Rsession (" + confs[i] + ")"); RserveSession s = new RserveSession(System.out, null, confs[i]); assert s.asDouble(s.eval("1+" + i)) == 1 + i : "Failed basic computation in Rserve"; System.err.println("--- Destroy Rsession"); s.end(); System.err.println("--- Stop Rserve"); daemons[i].stop(); //Thread.sleep(5000); assert !haveRservePID(daemons[i].rserve.pid) : "Still alive !"; //System.err.println("--- Get REMAINING Rserve PID"); //int other_pid = StartRserve.getLastRservePID(); //System.err.println("--- " + other_pid); //assert other_pid != pid : "Did not kill Rserve (still live PID)"; } }
java
22
0.486656
154
42.948276
58
inline
import React from "react"; import Typography from "@material-ui/core/Typography"; import Stepper from "@material-ui/core/Stepper"; import Step from "@material-ui/core/Step"; import StepLabel from "@material-ui/core/StepLabel"; import PropTypes from "prop-types"; import { Styles } from "./styles"; class ProgressStepper extends React.Component { render() { return ( <div style={Styles.container}> <Typography variant="h5" component="h5"> Progress {this.renderStepper()} ); } renderStepper() { if (!this.props.steps) { return; } return ( <Stepper activeStep={this.props.currentStep || 0} orientation="vertical"> {this.props.steps.map(step => { return ( <Step key={"step-" + this.props.steps.indexOf(step)}> ); })} ); } } export default ProgressStepper; ProgressStepper.propTypes = { // Title of the different steps steps: PropTypes.arrayOf(PropTypes.string).isRequired, // Index of the current step currentStep: PropTypes.number.isRequired, };
javascript
19
0.620775
79
23.26
50
starcoderdata
// #using #using using namespace System; using namespace System::IO; using namespace System::Xml::Serialization; using namespace System::Xml; using namespace System::Xml::Schema; public ref class Group { public: String^ GroupName; }; public ref class Test { private: void Serializer_UnknownElement( Object^ sender, XmlElementEventArgs^ e ) { Console::WriteLine( "Unknown Element" ); Console::Write( "\t {0}", e->Element->Name ); Console::WriteLine( " {0}", e->Element->InnerXml ); Console::WriteLine( "\t LineNumber: {0}", e->LineNumber ); Console::WriteLine( "\t LinePosition: {0}", e->LinePosition ); Group^ x = dynamic_cast Console::WriteLine( x->GroupName ); Console::WriteLine( sender ); } public: void DeserializeObject( String^ filename ) { XmlSerializer^ ser = gcnew XmlSerializer( Group::typeid ); // Add a delegate to handle unknown element events. ser->UnknownElement += gcnew XmlElementEventHandler( this, &Test::Serializer_UnknownElement ); // A FileStream is needed to read the XML document. FileStream^ fs = gcnew FileStream( filename,FileMode::Open ); Group^ g = dynamic_cast fs )); fs->Close(); } }; int main() { Test^ t = gcnew Test; // Deserialize the file containing unknown elements. t->DeserializeObject( "UnknownElements.xml" ); } //
c++
12
0.643401
100
25.666667
57
starcoderdata
package main import ( "fmt" "sort" "github.com/icemanblues/advent-of-code/pkg/util" ) func joltDiff(adapters []int) int { sort.Ints(adapters) curr := 0 diff1 := 0 diff3 := 1 for _, jolt := range adapters { if jolt-curr == 1 { diff1++ curr = jolt } if jolt-curr == 3 { diff3++ curr = jolt } } return diff1 * diff3 } func numPaths(adapters []int) int { sort.Ints(adapters) paths := make(map[int]int) paths[0] = 1 for _, jolt := range adapters { paths[jolt] = paths[jolt-1] + paths[jolt-2] + paths[jolt-3] } return paths[adapters[len(adapters)-1]] } func part1() { ints, _ := util.ReadIntput("input.txt") fmt.Printf("Part 1, %v\n", joltDiff(ints)) } func part2() { ints, _ := util.ReadIntput("input.txt") fmt.Printf("Part 2: %v\n", numPaths(ints)) } func main() { fmt.Println("Day 10: Adapter Array") part1() part2() }
go
11
0.615207
61
15.692308
52
starcoderdata
import subprocess from pathlib import Path def load_vars(dir: Path) -> dict: """Load environment vairables from .envrc in the given directory (or parent)""" print("Loading environment vairables from .envrc") try: result = subprocess.check_output( f'direnv exec "{dir}" python -m pytest_direnv.direnv_export', shell=True, ) return eval(result) except subprocess.CalledProcessError as e: if e.returncode == 127: print("direnv was not found, .envrc will not be loaded.") return {} else: print(f"Error loading .envrc file from {dir}:") print(e.output) raise e
python
14
0.607046
83
28.52
25
starcoderdata
using FlyoutControl; using MahApps.Metro.Controls; using Microsoft.Practices.Prism.Regions; using Microsoft.Practices.Prism.ViewModel; using Microsoft.Practices.ServiceLocation; using Movies.MoviesInterfaces; using Movies.Services; using Movies.Views; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Windows; namespace RealMediaControl.ViewModel { public class ShellWindowService:NotificationObject, IShellWindowService { IApplicationService ApplicationService; private IRegionManager RegionManager; IDictionary<string, Object> _views; private object currentview; public object CurrentView { get { return currentview; } } private IList flyoutsubmenuitem; public IList FlyoutSubMenuItem { get { return flyoutsubmenuitem; } } private object _statusadditioninfo; public object StatusAdditionInfo { get { return _statusadditioninfo; } private set { _statusadditioninfo = value; RaisePropertyChanged(() => this.StatusAdditionInfo); } } public ShellWindowService(IApplicationService applicationService, IRegionManager regionManager) { this.ApplicationService = applicationService; this.RegionManager = regionManager; _views = new Dictionary<string, object>(); flyoutsubmenuitem = new ObservableCollection this.AddView(new MainShellView(), typeof(MainShellView).Name); } private void VideoPlayerVM_Closing(object sender, System.ComponentModel.CancelEventArgs e) { var imediaHost = ServiceLocator.Current.GetInstance foreach (var item in imediaHost) { item.ShutDown(); } ApplicationService.SaveFiles(); } public object GetView(string ViewName) { object view = null; _views.TryGetValue(ViewName, out view); return view; } public void OnWindowsLoaded() { CommandActions CommandAction = new CommandActions(ApplicationService); CommandAction.RegisterCommands(); (ShellWindow as Window).Closing += VideoPlayerVM_Closing; } public void AddView(object view, string uniqueName) { if (!_views.ContainsKey(uniqueName)) { _views.Add(uniqueName, view); UpdateCurrentView(); } } public void RemoveView(object view) { // _views.Remove(view); } public void RemoveView(string ViewName) { _views.Remove(ViewName); UpdateCurrentView(); } private void UpdateCurrentView() { currentview = _views.LastOrDefault().Value; RaisePropertyChanged(() => this.CurrentView); } public void RegisterMenu(object flyoutSubMenuItem) { FlyoutSubMenuItem item = flyoutSubMenuItem as FlyoutSubMenuItem; if(item != null) { flyoutsubmenuitem.Add(item); } } public void RegisterMenuAt(object flyoutSubMenuItem, int Position) { FlyoutSubMenuItem item = flyoutSubMenuItem as FlyoutSubMenuItem; if (item != null) { int index = Position; if (Position > 0) index = Position - 1; flyoutsubmenuitem.Insert(index, item); } } public void SetAdditionalStatusItem(object view) { this.StatusAdditionInfo = view; } public void ClearAdditionalStatusItem() { this.StatusAdditionInfo = null; } public MetroWindow ShellWindow { get { return ServiceLocator.Current.GetInstance as MetroWindow; } } } }
c#
16
0.592251
109
28.193103
145
starcoderdata
package date import ( "time" ) // Period is representation of confidence level for the parsed date. // For example, if the parsed date has period level `Month`, then // the parser is only confident up to the month, while the day and // time is taken from the current time. type Period uint8 const ( None Period = iota Time Day Month Year ) func (p Period) String() string { switch p { case Time: return "Time" case Day: return "Day" case Month: return "Month" case Year: return "Year" default: return "" } } // Date is object that represents the parsed date with useful information. type Date struct { Locale string Period Period Time time.Time } // IsZero reports whether the date is empty or not. func (d Date) IsZero() bool { return d.Period == None || d.Time.IsZero() }
go
9
0.697157
74
16.586957
46
starcoderdata
<?php /* * This file is part of the Rent Car project. * (c) * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace App\Controllers\admin; use App\Controllers\BaseController; use App\Models\EmployeeModel; class Employee extends BaseController { /** * @var EmployeeModel */ private $employeeModel; public function __construct() { $this->employeeModel = new EmployeeModel(); } public function index() { if (!$this->isAdmin()) { return redirect('login'); } $data['employees'] = $this->employeeModel->findAll(); return view('admin/view_employee', $data); } public function add() { if (!$this->isAdmin()) { return redirect('login'); } if ($this->request->getPost('buttonSubmit')) { $this->validation->setRuleGroup('addemp'); if ($this->validation->withRequest($this->request)->run()) { $data = $this->request->getPost(); $this->employeeModel->insertEmployee($data); $this->session->setFlashdata('message', 'Employee Successfully Created.'); return redirect('admin/employee'); } } return view('admin/view_addemployee'); } public function edit($cid) { if (!$this->isAdmin()) { return redirect('login'); } if ($this->request->getPost('buttonSubmit')) { $this->validation->setRuleGroup('editemp'); if ($this->validation->withRequest($this->request)->run()) { $this->employeeModel->updateEmployee($cid, $this->request->getPost()); return redirect('admin/employee'); } } $data = [ 'userRow' => $this->employeeModel->find($cid), ]; return view('admin/view_editemployee', $data); } public function delete($cid) { if (!$this->isAdmin()) { return redirect('login'); } $this->employeeModel->delete($cid); $this->session->setFlashdata('message', 'Employee Successfully deleted.'); return redirect('admin/employee'); } }
php
16
0.553082
90
23.851064
94
starcoderdata
<?php /** * Postfix Admin * * LICENSE * This source file is subject to the GPL license that is bundled with * this package in the file LICENSE.TXT. * * Further details on the project are available at http://postfixadmin.sf.net * * @version $Id$ * @license GNU GPL v2 or later. * * File: list.php * List all items as a quick overview. * */ require_once('common.php'); # if (safeget('token') != $_SESSION['PFA_token']) die('Invalid token!'); $username = authentication_get_username(); # enforce login $CONF = Config::getInstance()->getAll(); $smarty = PFASmarty::getInstance(); $table = safeget('table'); if (empty($table)) { die("table parameter missing or invalid."); } $handlerclass = ucfirst($table) . 'Handler'; if (!preg_match('/^[a-z]+$/', $table) || !file_exists(dirname(__FILE__) . "/../model/$handlerclass.php")) { # validate $table die("Invalid table name given!"); } # default: domain admin restrictions $is_superadmin = 0; if (authentication_has_role('global-admin')) { # more permissions? Fine! $is_superadmin = 1; $username = safepost('username', safeget('username', $username)); # prefer POST over GET variable } $is_admin = authentication_has_role('admin'); $handler = new $handlerclass(0, $username, $is_admin); $formconf = $handler->webformConfig(); $list_admins = array($username); if ($is_superadmin && $formconf['required_role'] != 'global-admin') { # 'simulate admin' dropdown doesn't make sense for superadmin-only modules $list_admins = array_keys(list_admins()); } if ($is_admin) { authentication_require_role($formconf['required_role']); } else { if (empty($formconf['user_hardcoded_field'])) { die($handlerclass . ' is not available for users'); } } $search = []; $searchmode = []; if (isset($_GET['search']) && is_array($_GET['search'])) { $search = $_GET['search']; } elseif (isset($_SESSION["search_$table"]) && is_array($_SESSION["search_$table"])) { $search = $_SESSION["search_$table"]; } if (isset($_GET['searchmode']) && is_array($_GET['searchmode'])) { $searchmode = $_GET['searchmode']; } elseif (isset($_SESSION["searchmode_$table"]) && is_array($_SESSION["searchmode_$table"])) { $searchmode = $_SESSION["searchmode_$table"]; } if (array_key_exists('reset_search', $_GET)) { $search = array(); $searchmode = array(); } $_SESSION["search_$table"] = $search; $_SESSION["searchmode_$table"] = $searchmode; if (count($search)) { $handler->getList($search, $searchmode); } else { $handler->getList(''); } $items = $handler->result(); if (count($handler->errormsg)) { flash_error($handler->errormsg); } if (count($handler->infomsg)) { flash_error($handler->infomsg); } $fDomain = safepost('fDomain', safeget('domain', safesession('list-virtual:domain'))); if (safeget('output') == 'csv') { $out = fopen('php://output', 'w'); header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment;filename=' . $table . '.csv'); print "\xEF\xBB\xBF"; # utf8 byte-order to indicate the file is utf8 encoded print "\n"; if (!defined('ENT_HTML401')) { # for compability for PHP < 5.4.0 define('ENT_HTML401', 0); } # print column headers as csv $header = array(); $columns = array(); foreach ($handler->getStruct() as $key => $field) { $label = trim($field['label']); if ($field['display_in_list'] && $label != '') { # don't show fields without a label $header[] = html_entity_decode($label, ENT_COMPAT | ENT_HTML401, 'UTF-8'); $columns[] = $key; } } fputcsv($out, $header); # print items as csv foreach ($items as $item) { $fields = array(); // skip domains that do not match selected domain (see: https://github.com/postfixadmin/postfixadmin/issues/404) if (!empty($fDomain) && $item['domain'] != $fDomain) { continue; } foreach ($columns as $column) { $values = $item[$column]; if (is_array($values)) { $values = implode(',', $values); } $fields[] = $values; } fputcsv($out, $fields); } fclose($out); } else { # HTML output $smarty->assign('admin_list', $list_admins); $smarty->assign('admin_selected', $username); $smarty->assign('smarty_template', 'list'); $smarty->assign('struct', $handler->getStruct()); $smarty->assign('msg', $handler->getMsg()); $smarty->assign('table', $table); $smarty->assign('items', $items); $smarty->assign('id_field', $handler->getId_field()); $smarty->assign('formconf', $formconf); $smarty->assign('search', $search); $smarty->assign('searchmode', $searchmode); $smarty->assign('domain_selected', ''); /* stop list-virtual.tpl triggering a PHP notice */ $smarty->display('index.tpl'); } /* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */
php
15
0.608756
144
29.13253
166
starcoderdata
package net.tuis.resolver; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.CharArrayWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.util.Properties; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import java.util.logging.StreamHandler; import org.junit.BeforeClass; import org.junit.Test; import org.xml.sax.InputSource; @SuppressWarnings("javadoc") public class TestCachedHTTPRepository { @BeforeClass public static final void setLogging() { Handler ch = new StreamHandler(System.out, new SimpleFormatter()) ; ch.setLevel(Level.ALL); Logger logger = Logger.getLogger("net.tuis"); logger.setLevel(Level.FINEST); logger.addHandler(ch); } private static final String result(final InputSource source) throws IOException { Reader reader = source.getCharacterStream(); if (reader == null) { if (source.getEncoding() != null) { reader = new InputStreamReader(source.getByteStream(), source.getEncoding()); } else { reader = new InputStreamReader(source.getByteStream()); } } char[] buffer = new char[512]; CharArrayWriter caw = new CharArrayWriter(); int len = 0; while ((len = reader.read(buffer)) >= 0) { caw.write(buffer, 0, len); } return new String(caw.toCharArray()); } @Test public void testResolveW3() throws IOException { CachedHTTPRepository repo = new CachedHTTPRepository(); final String xhtmldtd = result(repo.resolve("-//W3C//DTD XHTML 1.0 Strict//EN", new URL("http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"))); assertTrue(xhtmldtd != null); } @Test public void testResolveLocal() throws IOException { CachedHTTPRepository repo = new CachedHTTPRepository(); final String val = result(repo.resolve(null, new URL("http://localhost/index.html"))); assertEquals(" works! val); final String xhtmldtd = result(repo.resolve("-//W3C//DTD XHTML 1.0 Strict//EN", new URL("http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"))); assertTrue(xhtmldtd != null); } private void copyResource(final File destination, final InputStream source) throws IOException { destination.getParentFile().mkdirs(); final FileOutputStream fos = new FileOutputStream(destination); final byte[] buffer = new byte[1024]; int len = 0; while ((len = source.read(buffer)) >= 0) { fos.write(buffer, 0, len); } fos.flush(); fos.close(); source.close(); } @Test public void testResolveNoConnection() throws IOException { final Properties props = new Properties(); final String resbase = TestCachedHTTPRepository.class.getName().replace('.', '/'); final InputStream is = ClassLoader.getSystemResourceAsStream(resbase + "_control"); props.load(is); final String key = props.getProperty("CURL_RESKEY"); final String url = props.getProperty("CURL_URL"); final CachedHTTPRepository repo = new CachedHTTPRepository(); final File control = new File(repo.getCacheFolder(), key + ".control"); final File data = new File(repo.getCacheFolder(), key + ".data"); copyResource(control, ClassLoader.getSystemResourceAsStream(resbase + "_control")); copyResource(data, ClassLoader.getSystemResourceAsStream(resbase + "_data")); final String val = result(repo.resolve(null, new URL(url))); assertEquals("0001332089779999\n", val); } }
java
13
0.727767
97
32.733945
109
starcoderdata
package semexe.tables.lambdadcs; import semexe.ListValue; import semexe.Value; import semexe.tables.lambdadcs.LambdaDCSException.Type; import semexe.basic.LispTree; import semexe.AggregateFormula; /** * Mapping denotation: a mapping from variable assignment to values. * * Share the implementation with BinaryDenotation by using PairList. * * @author ppasupat */ public class MappingDenotation<PL extends PairList> implements Unarylike { protected final String domainVar; protected final PL pairList; protected MappingDenotation(String domainVar, PL pairList) { this.domainVar = domainVar; this.pairList = pairList; } @Override public String toString() { return toLispTree().toString(); } @Override public LispTree toLispTree() { return LispTree.proto.L("mapping", domainVar, pairList.toLispTree()); } @Override public ListValue toValue() { throw new LambdaDCSException(Type.notUnary, "Expected Unary; Mapping found: %s", this); } @Override public String getDomainVar() { return domainVar; } public BinaryDenotation asBinary() { return new BinaryDenotation<>(pairList); } @Override public UnaryDenotation domain() { return pairList.domain(); } @Override public UnaryDenotation range() { return pairList.range(); } @Override public UnaryDenotation get(Value key) { return pairList.get(key); } @Override public UnaryDenotation inverseGet(Value value) { return pairList.inverseGet(value); } @Override public Unarylike aggregate(AggregateFormula.Mode mode) { return new MappingDenotation<>(domainVar, pairList.aggregate(mode)); } @Override public Unarylike filter(UnaryDenotation upperBound, UnaryDenotation domainUpperBound) { return new MappingDenotation<>(domainVar, pairList.filter(upperBound, domainUpperBound)); } }
java
10
0.686874
97
23.95
80
starcoderdata
using VideoApi.Domain.Enums; using VideoApi.Events.Models.Enums; namespace VideoApi.Events.Models { public class HearingEventMessage : EventMessage { public ConferenceState ConferenceStatus { get; set; } public override MessageType MessageType => MessageType.Hearing; } }
c#
8
0.746356
71
27.666667
12
starcoderdata
#include<bits/stdc++.h> using namespace std; int main(){ int N,M,K,count=0,flag=1;cin>>N>>M>>K; vector<int> a; for(int i=0;i<=N;i++){ for(int j=0;j<=M;j++){ a.push_back(i*M+j*N-i*j*2); count++; } } for(int i=0;i<count;i++){ if(K==a.at(i)){ flag=0; break; } } if(flag==0)cout<<"Yes"<<endl; else cout<<"No"<<endl; }
c++
13
0.487805
40
17.5
20
codenet
size_t BlitCommandsHelper<GfxFamily>::estimateBlitCommandsSize(Vec3<size_t> copySize, const CsrDependencies &csrDependencies, bool updateTimestampPacket) { size_t numberOfBlits = 0; uint64_t width = 1; uint64_t height = 1; for (uint64_t slice = 0; slice < copySize.z; slice++) { for (uint64_t row = 0; row < copySize.y; row++) { uint64_t sizeToBlit = copySize.x; while (sizeToBlit != 0) { if (sizeToBlit > getMaxBlitWidth()) { // dispatch 2D blit: maxBlitWidth x (1 .. maxBlitHeight) width = getMaxBlitWidth(); height = std::min((sizeToBlit / width), getMaxBlitHeight()); } else { // dispatch 1D blt: (1 .. maxBlitWidth) x 1 width = sizeToBlit; height = 1; } sizeToBlit -= (width * height); numberOfBlits++; } } } const size_t cmdsSizePerBlit = (sizeof(typename GfxFamily::XY_COPY_BLT) + estimatePostBlitCommandSize()); return TimestampPacketHelper::getRequiredCmdStreamSize<GfxFamily>(csrDependencies) + (cmdsSizePerBlit * numberOfBlits) + (EncodeMiFlushDW<GfxFamily>::getMiFlushDwCmdSizeForDataWrite() * static_cast<size_t>(updateTimestampPacket)); }
c++
17
0.575847
155
42.83871
31
inline
/* * AOJ #2399 Save Your Privacy! */ #include <stdio.h> #include <stdlib.h> int main() { int n, m, i, j, p, count, answer; unsigned char **candidate, *leaker; while (1) { scanf("%d", &n); if (n == 0) { break; } candidate = malloc((n + 1) * sizeof(candidate[0])); for (i = 1; i <= n; i++) { candidate[i] = malloc(n + 1); for (j = 1; j <= n; j++) { candidate[i][j] = 0; } } for (i = 1; i <= n; i++) { scanf("%d", &m); for (j = 0; j < m; j++) { scanf("%d", &p); candidate[p][i] = 1; } } leaker = malloc(n + 1); for (i = 1; i <= n; i++) { leaker[i] = 1; } scanf("%d", &m); for (j = 0; j < m; j++) { scanf("%d", &p); for (i = 1; i <= n; i++) { leaker[i] &= candidate[p][i]; } } count = 0; for (i = 1; i <= n; i++) { if (leaker[i]) { count++; answer = i; } } if (count == 1) { printf("%d\n", answer); } else { printf("-1\n"); } free(leaker); for (i = 1; i <= n; i++) { free(candidate[i]); } free(candidate); } return 0; }
c
13
0.332335
61
22.051724
58
codenet
/************************************************************************************** Copyright 2015 Applied Research Associates, Inc. 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 mil.tatrc.physiology.datamodel.engine; import mil.tatrc.physiology.datamodel.CDMSerializer; import mil.tatrc.physiology.datamodel.bind.ElectroCardioGramWaveformInterpolatorData; import mil.tatrc.physiology.datamodel.bind.PhysiologyEngineConfigurationData; import mil.tatrc.physiology.datamodel.bind.PhysiologyEngineDynamicStabilizationData; import mil.tatrc.physiology.datamodel.bind.PhysiologyEngineStabilizationData; import mil.tatrc.physiology.datamodel.bind.PhysiologyEngineTimedStabilizationData; import mil.tatrc.physiology.datamodel.properties.SEScalarTime; import mil.tatrc.physiology.datamodel.system.equipment.electrocardiogram.SEElectroCardioGramWaveformInterpolator; import mil.tatrc.physiology.utilities.Log; public class PhysiologyEngineConfiguration { protected SEElectroCardioGramWaveformInterpolator ecgInterpolator; protected PhysiologyEngineStabilization stabilizationCriteria; protected SEScalarTime timeStep; public PhysiologyEngineConfiguration() { clear(); } public void reset() { if(ecgInterpolator!=null) this.ecgInterpolator.reset(); if(stabilizationCriteria!=null) this.stabilizationCriteria.reset(); if(timeStep!=null) this.timeStep.invalidate(); } public void clear() { this.ecgInterpolator=null; this.stabilizationCriteria=null; this.timeStep=null; } public boolean load(PhysiologyEngineConfigurationData in) { clear(); if(in.getElectroCardioGramInterpolatorFile()!=null) getECGInterpolator().load((ElectroCardioGramWaveformInterpolatorData) CDMSerializer.readFile(in.getElectroCardioGramInterpolatorFile())); else if(in.getElectroCardioGramInterpolator()!=null) getECGInterpolator().load(in.getElectroCardioGramInterpolator()); PhysiologyEngineStabilizationData stabs=null; if(in.getStabilizationCriteria()!=null) stabs = in.getStabilizationCriteria(); else if(in.getStabilizationCriteriaFile()!=null) stabs = (PhysiologyEngineStabilizationData)CDMSerializer.readFile(in.getStabilizationCriteriaFile()); if(stabs != null) { if(stabs instanceof PhysiologyEngineTimedStabilizationData) stabilizationCriteria = new PhysiologyEngineTimedStabilization(); else if(stabs instanceof PhysiologyEngineDynamicStabilizationData) stabilizationCriteria = new PhysiologyEngineDynamicStabilization(); else Log.fatal("Unsupported stabilization critera : " + stabs.getClass().getName()); stabilizationCriteria.load(stabs); } if(in.getTimeStep()!=null) getTimeStep().load(in.getTimeStep()); return true; } public PhysiologyEngineConfigurationData unload() { PhysiologyEngineConfigurationData data = CDMSerializer.objFactory.createPhysiologyEngineConfigurationData(); unload(data); return data; } protected void unload(PhysiologyEngineConfigurationData data) { if(hasECGInterpolator()) data.setElectroCardioGramInterpolator(this.ecgInterpolator.unload()); if(hasStabilizationCriteria()) data.setStabilizationCriteria(this.stabilizationCriteria.unload()); if(hasTimeStep()) data.setTimeStep(this.timeStep.unload()); } public boolean hasECGInterpolator() { return ecgInterpolator!=null; } public SEElectroCardioGramWaveformInterpolator getECGInterpolator() { if(ecgInterpolator==null) ecgInterpolator=new SEElectroCardioGramWaveformInterpolator(); return ecgInterpolator; } public boolean hasStabilizationCriteria() { return stabilizationCriteria!=null; } public PhysiologyEngineStabilization getStabilizationCriteria() { return stabilizationCriteria; } public boolean hasTimeStep() { return timeStep!=null && timeStep.isValid(); } public SEScalarTime getTimeStep() { if(timeStep==null) timeStep=new SEScalarTime(); return timeStep; } }
java
16
0.739761
143
35.341085
129
starcoderdata
import * as types from './types'; import axios from 'axios'; const initialState = { vehicle: {}, vehicles: [], vehicleMakes: [], vehicleModels: [], isLoading: true, }; export const vehicleActionCreators = { [types.GET_VEHICLE]: (id = '') => { return (dispatch) => { axios.get(`/vehicle/getvehicle?id=${id}`) .then(r => { return r.data }) .then(response => { if (response.succeeded) { dispatch({ type: types.UPDATE_VEHICLE, vehicle: response.data }); } }); } }, [types.GET_VEHICLES]: (page, size, userId = '') => { return (dispatch) => { axios.get('/vehicle/getvehicles', { params: { page: page, size: size, userId: userId, } }).then(r => { return r.data }) .then(response => { if (response.succeeded) { dispatch({ type: types.UPDATE_VEHICLES, vehicles: response.data, }); } }); } }, [types.GET_SEARCHED_VEHICLES]: (input) => { return (dispatch) => { axios.post('/vehicle/searchvehicles', input) .then(r => { return r.data }) .then(response => { if (response.succeeded) { dispatch({ type: types.UPDATE_VEHICLES, vehicles: response.data, }); } }); } }, [types.GET_VEHICLE_MAKES]: () => { return (dispatch) => { axios.get('/vehicle/getvehiclemakes') .then(r => { return r.data }) .then(response => { if (response.succeeded) { dispatch({ type: types.UPDATE_VEHICLE_MAKES, vehicleMakes: response.data }); } }); } }, [types.GET_VEHICLE_MODELS]: (makeId, vehicleTypeId) => { return (dispatch) => { axios.get('/vehicle/getvehiclemodels', { params: { makeId: makeId, vehicleTypeId: vehicleTypeId, } }).then(r => { return r.data }) .then(response => { if (response.succeeded) { dispatch({ type: types.UPDATE_VEHICLE_MODELS, vehicleModels: response.data }); } }); } }, [types.CLEAR_STATE]: () => { return (dispatch) => { dispatch({ type: types.UPDATE_CLEAR_STATE }); } }, }; export const reducer = (state = initialState, action) => { switch (action.type) { case types.UPDATE_VEHICLE: return { ...state, vehicle: action.vehicle, isLoading: false, }; case types.UPDATE_VEHICLES: return { ...state, vehicles: state.vehicles.concat(action.vehicles), isLoading: false, }; case types.UPDATE_VEHICLE_MAKES: return { ...state, vehicleMakes: action.vehicleMakes, isLoading: false, }; case types.UPDATE_VEHICLE_MODELS: return { ...state, vehicleModels: action.vehicleModels, isLoading: false, }; case types.UPDATE_CLEAR_STATE: return initialState; default: return state; } };
javascript
23
0.57234
58
20.044776
134
starcoderdata
Bandeiras Android/Quiz/src/com/quiz/TelaInicial.java package com.quiz; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; public class TelaInicial extends Activity { EditText editNome; Button buttonJogar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tela_inicial); editNome = (EditText) findViewById(R.id.editNome); buttonJogar = (Button) findViewById(R.id.btnJogar); buttonJogar.setEnabled(false); if(editNome.getText().toString().equals("")){ buttonJogar.setEnabled(false); } else{ buttonJogar.setEnabled(true); } editNome.addTextChangedListener(new TextWatcher(){ @Override public void afterTextChanged(Editable s) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { buttonJogar.setEnabled((!TextUtils.isEmpty(s.toString().trim()))); } }); } public void btnJogarOnClick(View v) { Intent intent = new Intent(this,Quiz1.class); startActivity(intent); } public void fechar(View botao) { System.exit(0); } }
java
20
0.680784
70
21.6
70
starcoderdata
package com.codepoetics.fluvius.exceptions; import com.codepoetics.fluvius.api.scratchpad.Key; /** * Thrown when a Flow is added to a branching flow which writes to a different key than the default branch. */ public final class IllegalBranchOutputKeyException extends RuntimeException { /** * Create an IllegalBranchOutputKeyException. * @param defaultOutputKey The output Key specified by the default branch. * @param branchDescription Description of the branch which specifies a different output key. * @param conditionalOutputKey The output key specified by the branch. * @return The exception. */ public static IllegalBranchOutputKeyException create(Key defaultOutputKey, String branchDescription, Key conditionalOutputKey) { return new IllegalBranchOutputKeyException("Branch " + branchDescription + " outputs key " + conditionalOutputKey.getName() + " but default branch outputs key " + defaultOutputKey.getName()); } private IllegalBranchOutputKeyException(String message) { super(message); } }
java
14
0.762821
136
38
28
starcoderdata
package com.github.shatteredsuite.scrolls.recipes; import com.github.shatteredsuite.scrolls.items.ScrollItemBuilder; import java.util.Map; import org.bukkit.Material; import org.bukkit.NamespacedKey; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ShapedRecipe; import com.github.shatteredsuite.scrolls.ShatteredScrolls; public class RecipeHandler { public static void addRecipe(ShatteredScrolls plugin) { NamespacedKey key = new NamespacedKey(plugin, "teleport_scroll"); ItemStack unboundScroll = ScrollItemBuilder.getUnboundScroll(plugin.config().getRecipe().getCount()); ShapedRecipe recipe = new ShapedRecipe(key, unboundScroll); recipe.shape(plugin.config().getRecipe().getLines().get(0), plugin.config().getRecipe().getLines().get(1), plugin.config().getRecipe().getLines().get(2)); for (Map.Entry<String, Material> entry : plugin.config().getRecipe().getMappings().entrySet()) { recipe.setIngredient(entry.getKey().charAt(0), entry.getValue()); } plugin.getServer().addRecipe(recipe); } }
java
13
0.719824
109
39.535714
28
starcoderdata
/** * @fileoverview Provides the "ngeoLayertreenode" directive, a layer tree node * directive. This directive is used by the "ngeoLayertree" directive. * * The directive assumes that tree nodes that are not leaves have a "children" * property referencing an array of child nodes. * * Example usage: * * <div ngeo-layertreenode="ctrl.node" ngeo-layertreenode-map="ctrl.map" * ngeo-layertreenode-layerexpr="ctrl.layerExpr"> * * * The "ngeo-layertreenode", "ngeo-layertreenode-map" and * "ngeo-layertreenode-layerexpr" attributes are mandatory. * * - The "ngeo-layertreenode" specifies the scope property whose value is * a reference to the tree node object. * * - The "ngeo-layertreenode-map" specifies the scope property whose value is * a reference to the map. * * - The "ngeo-layertreenode-layerexpr" specifies the scope property whose * value is the layer expression (a string) to evaluate to get the layer * object for this tree node. * * By default the directive uses "layertreenode.html" as its templateUrl. This * can be changed by redefining the "ngeoLayertreenodeTemplateUrl" value. * * The directive has its own scope, but it is not isolate scope. That scope * includes a reference to the directive's controller: the "layertreenodeCtrl" * property. * * This directive doesn't itself create watchers, but its partial uses Angular * directives like ngRepeat and ngModel which do create watchers. */ goog.provide('ngeo.layertreenodeDirective'); goog.require('ngeo'); /** * @const * @type {string} */ ngeo.layertreenodeTemplateUrl = 'layertreenode.html'; ngeoModule.value('ngeoLayertreenodeTemplateUrl', ngeo.layertreenodeTemplateUrl); /** * @param {angular.$compile} $compile Angular compile service. * @param {string|function(!angular.JQLite=, !angular.Attributes=)} * ngeoLayertreenodeTemplateUrl Template URL for the directive. * @return {angular.Directive} The Directive Definition Object. * @ngInject */ ngeo.layertreenodeDirective = function( $compile, ngeoLayertreenodeTemplateUrl) { return { restrict: 'A', require: '^ngeoLayertree', scope: true, templateUrl: ngeoLayertreenodeTemplateUrl, controller: 'NgeoLayertreenodeController', compile: /** * @param {angular.JQLite} tElement Template element. * @param {angular.Attributes} tAttrs Template attributes. * @return {Function} Post-link function. */ function(tElement, tAttrs) { var contents = tElement.contents().remove(); var compiledContents; return ( /** * Post-link function. * @param {angular.Scope} scope Scope. * @param {angular.JQLite} iElement Instance element. * @param {angular.Attributes} iAttrs Instance attributes. */ function(scope, iElement, iAttrs) { if (!compiledContents) { compiledContents = $compile(contents); } compiledContents(scope, /** * @param {Object} clone Clone element. */ function(clone) { var cloneElement = /** @type {angular.JQLite} */ (clone); iElement.append(cloneElement); }); }); } }; }; ngeoModule.directive('ngeoLayertreenode', ngeo.layertreenodeDirective); /** * The controller for the "tree node" directive. * @param {angular.Scope} $scope Scope. * @param {angular.JQLite} $element Element. * @param {angular.Attributes} $attrs Attributes. * @constructor * @ngInject * @export */ ngeo.LayertreenodeController = function($scope, $element, $attrs) { var nodeExpr = $attrs['ngeoLayertreenode']; var node = /** @type {Object} */ ($scope.$eval(nodeExpr)); goog.asserts.assert(goog.isDef(node)); this['node'] = node; var mapExpr = $attrs['ngeoLayertreenodeMap']; var map = /** @type {ol.Map} */ ($scope.$eval(mapExpr)); goog.asserts.assert(goog.isDef(map)); this['map'] = map; var layerexprExpr = $attrs['ngeoLayertreenodeLayerexpr']; var layerExpr = /** @type {string} */ ($scope.$eval(layerexprExpr)); goog.asserts.assert(goog.isDef(layerExpr)); this['layerExpr'] = layerExpr; // The node is passed in the "locals" object (2nd arg to $eval). This // is to allow expressions like "ctrl.getLayer(node)". var layer = /** @type {ol.layer.Layer} */ ($scope.$eval(layerExpr, {'node': node})); goog.asserts.assert(goog.isDef(layer)); this['layer'] = layer; /** * @type {ol.Map} * @private */ this.map_ = map; /** * This node's layer. `null` if there's no layer for that node (for * example if the node is not a leaf). * @type {ol.layer.Layer} * @private */ this.layer_ = layer; this['parentUid'] = $scope.$parent['uid']; this['uid'] = goog.getUid(this); this['depth'] = $scope.$parent['depth'] + 1; // We set 'uid' and 'depth' in the scope as well to access the parent values // in the inherited scopes. This is intended to be used in the javascript not // in the templates. $scope['uid'] = this['uid']; $scope['depth'] = this['depth']; $scope['layertreenodeCtrl'] = this; }; /** * @param {boolean|undefined} val Value. * @return {boolean|undefined} Value. * @export */ ngeo.LayertreenodeController.prototype.getSetActive = function(val) { var layer = this.layer_; var map = this.map_; goog.asserts.assert(!goog.isNull(layer)); if (goog.isDef(val)) { if (!val) { map.removeLayer(layer); } else { map.addLayer(layer); } } else { return map.getLayers().getArray().indexOf(layer) >= 0; } }; ngeoModule.controller('NgeoLayertreenodeController', ngeo.LayertreenodeController);
javascript
19
0.642845
79
29.769634
191
starcoderdata
//Sum of given range import java.util.Scanner; /* * @author Bhanuka */ public class Mos_algo { public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] arr = new int[n]; for(int i=0; i<n; i++) arr[i] = in.nextInt(); int t = in.nextInt(); int sum = 0, start=-999, end=-999; while(t>0){ t--; int s = in.nextInt()-1; int e = in.nextInt()-1; if(s>e){ int swapTmp = s; s = e; e = swapTmp; } if(start==-999 && end==-999){ start = end = s; sum += arr[start]; } while(start<s){ sum -= arr[start++]; } while(start>s){ sum += arr[--start]; } while(end<e){ sum += arr[++end]; } while(end>e){ sum -= arr[end--]; } System.out.println(sum); } } }
java
13
0.341505
45
23.645833
48
starcoderdata
pub fn connect(addrs: Vec<SocketAddr>, max_ping: Duration, password: &str) -> Connector { let should_be_encrypted = !password.is_empty(); let should_be_encrypted_num = if should_be_encrypted { 1 } else { 0 }; let conns = addrs .into_iter() .map(|addr| { let mut conn = TcpStream::connect(addr) .unwrap_or_else(|_| panic!("Cannot connect to {}", addr)); conn.set_nodelay(true) .unwrap_or_else(|_| panic!("Cannot connect to {} - set_nodelay failed", addr)); conn.set_read_timeout(Some(max_ping)).unwrap_or_else(|_| { panic!("Cannot connect to {} - set_read_timeout failed", addr) }); conn.set_write_timeout(Some(max_ping)).unwrap_or_else(|_| { panic!("Cannot connect to {} - set_write_timeout failed", addr) }); // handshake3 - should be encrypted? let mut buf = [0u8; 1]; buf[0] = should_be_encrypted_num; conn.write_all(&buf) .unwrap_or_else(|_| panic!("Cannot connect to {} - handshake3 failed", addr)); // handshake4 - should be encrypted? + generate nonce let mut buf = [0u8; 25]; conn.read_exact(&mut buf) .unwrap_or_else(|_| panic!("Cannot connect to {} - handshake4 failed", addr)); if buf[0] != should_be_encrypted_num { panic!("Server {} has different SecurityConfig", addr); } let mut nonce = [0u8; 24]; nonce.copy_from_slice(&buf[1..]); // handshake5 let mut chacha = ChaCha::new(should_be_encrypted, password, &nonce); let mut buf = [0u8; 14]; buf[..].copy_from_slice(b"ping_fds321sfr"); chacha.xor(&mut buf); conn.write_all(&buf) .unwrap_or_else(|_| panic!("Cannot connect to {} - handshake5 failed", addr)); // handshake6 let mut buf = [0u8; 1]; conn.read_exact(&mut buf).unwrap_or_else(|_| { panic!("Server {} uses different password? Cannot connect to {} - handshake6 failed", addr, addr) }); (conn, addr, chacha) }) .collect::<Vec<_>>(); Connector { conns } }
rust
19
0.479342
117
46.056604
53
inline
int server_histogram_estimatePercentiles( StatsHolder* stats_holder, const char* stat_name, const HsDouble* percentiles, size_t npercentiles, int64_t* samples_out, uint64_t* count_out, int64_t* sum_out) { if (!stats_holder) { // Without stats, there is nothing we can do. return -1; } auto agg_hist = stats_holder->aggregate_nonew().server_histograms; if (!agg_hist) { ld_error("No such server_histograms!"); return -1; } auto histogram = agg_hist->find(std::string(stat_name)); if (!histogram) { ld_error("No such server_histograms: %s!", stat_name); return -1; } histogram->estimatePercentiles(percentiles, npercentiles, samples_out, count_out, sum_out); return 0; }
c++
9
0.643421
75
29.44
25
inline
protected final void clearState(ZooKeeper zk, String latchPrefix) throws KeeperException, InterruptedException{ List<String> latchChildren = ZkUtils.filterByPrefix(zk.getChildren(baseNode, false), latchPrefix); //clear out any old data for(String latchChild:latchChildren){ ZkUtils.safeDelete(zk,baseNode+"/"+latchChild,-1); } }
java
11
0.70557
111
46.25
8
inline
using UnityEngine; using System.Collections; [AddComponentMenu("2D Toolkit/Demo/tk2dDemoButtonController")] public class tk2dDemoButtonController : MonoBehaviour { float spinSpeed = 0.0f; // update void Update() { transform.Rotate(Vector3.up, spinSpeed * Time.deltaTime); } void SpinLeft() { spinSpeed = 4.0f; } void SpinRight() { spinSpeed = -4.0f; } void StopSpinning() { spinSpeed = 0.0f; } }
c#
14
0.707031
82
16.066667
30
starcoderdata
/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.h * @brief : Header for main.c file. * This file contains the common defines of the application. ****************************************************************************** ** This notice applies to any and all portions of this file * that are not between comment pairs USER CODE BEGIN and * USER CODE END. Other portions of this file, whether * inserted by the user or by software development tools * are owned by their respective copyright owners. * * COPYRIGHT(c) 2019 STMicroelectronics * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* USER CODE END Header */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __MAIN_H #define __MAIN_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ /* USER CODE END Includes */ /* Exported types ------------------------------------------------------------*/ /* USER CODE BEGIN ET */ /* USER CODE END ET */ /* Exported constants --------------------------------------------------------*/ /* USER CODE BEGIN EC */ /* USER CODE END EC */ /* Exported macro ------------------------------------------------------------*/ /* USER CODE BEGIN EM */ /* USER CODE END EM */ /* Exported functions prototypes ---------------------------------------------*/ void Error_Handler(void); /* USER CODE BEGIN EFP */ /* USER CODE END EFP */ /* Private defines -----------------------------------------------------------*/ #define LCD_CD_Pin GPIO_PIN_0 #define LCD_CD_GPIO_Port GPIOA #define LCD_CS_Pin GPIO_PIN_1 #define LCD_CS_GPIO_Port GPIOA #define Joycon1_1_Pin GPIO_PIN_2 #define Joycon1_1_GPIO_Port GPIOA #define Joycon1_2_Pin GPIO_PIN_3 #define Joycon1_2_GPIO_Port GPIOA #define Joycon2_1_Pin GPIO_PIN_4 #define Joycon2_1_GPIO_Port GPIOA #define Joycon2_2_Pin GPIO_PIN_5 #define Joycon2_2_GPIO_Port GPIOA #define Bat_Pin GPIO_PIN_6 #define Bat_GPIO_Port GPIOA #define Joycon1_But_Pin GPIO_PIN_7 #define Joycon1_But_GPIO_Port GPIOA #define Joycon1_But_EXTI_IRQn EXTI9_5_IRQn #define Joycon2_But_Pin GPIO_PIN_4 #define Joycon2_But_GPIO_Port GPIOC #define Joycon2_But_EXTI_IRQn EXTI4_IRQn #define LCD_D0_Pin GPIO_PIN_0 #define LCD_D0_GPIO_Port GPIOB #define LCD_D1_Pin GPIO_PIN_1 #define LCD_D1_GPIO_Port GPIOB #define LCD_D2_Pin GPIO_PIN_2 #define LCD_D2_GPIO_Port GPIOB #define LCD_RD_Pin GPIO_PIN_12 #define LCD_RD_GPIO_Port GPIOB #define LCD_WR_Pin GPIO_PIN_13 #define LCD_WR_GPIO_Port GPIOB #define LCD_RST_Pin GPIO_PIN_14 #define LCD_RST_GPIO_Port GPIOB #define CSN_Pin GPIO_PIN_15 #define CSN_GPIO_Port GPIOB #define TRX_CE_Pin GPIO_PIN_6 #define TRX_CE_GPIO_Port GPIOC #define PWRUP_Pin GPIO_PIN_7 #define PWRUP_GPIO_Port GPIOC #define TX_EN_Pin GPIO_PIN_8 #define TX_EN_GPIO_Port GPIOC #define RF_CD_Pin GPIO_PIN_9 #define RF_CD_GPIO_Port GPIOC #define RF_AM_Pin GPIO_PIN_8 #define RF_AM_GPIO_Port GPIOA #define DR_Pin GPIO_PIN_11 #define DR_GPIO_Port GPIOA #define LCD_D3_Pin GPIO_PIN_3 #define LCD_D3_GPIO_Port GPIOB #define LCD_D4_Pin GPIO_PIN_4 #define LCD_D4_GPIO_Port GPIOB #define LCD_D5_Pin GPIO_PIN_5 #define LCD_D5_GPIO_Port GPIOB #define LCD_D6_Pin GPIO_PIN_6 #define LCD_D6_GPIO_Port GPIOB #define LCD_D7_Pin GPIO_PIN_7 #define LCD_D7_GPIO_Port GPIOB /* USER CODE BEGIN Private defines */ /* USER CODE END Private defines */ #ifdef __cplusplus } #endif #endif /* __MAIN_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
c
9
0.631274
84
35.209459
148
starcoderdata
bool CASMWriter::WriteASMLeapMarkerTop(void) { // Record Where We Are Now m_pRecordTopBytePosition = m_pMachineBlock; // Complete return true; }
c++
5
0.758389
44
17.75
8
inline
using System.Collections; using System.Collections.Generic; using Kirurobo; using UnityEngine; namespace Kirurobo { public class ModelViewerController : MonoBehaviour { private UniWindowController uniwin; // Start is called before the first frame update void Start() { //UniWinCore.DebugMonitorInfo(); uniwin = GameObject.FindObjectOfType } // Update is called once per frame void Update() { } } }
c#
13
0.643478
72
21.115385
26
starcoderdata
#include "ldap/ldap_error.hpp" namespace tt4g { namespace ldap { ldap_error::ldap_error(const std::string& what_arg) : std::exception(), what_(what_arg) { } ldap_error::ldap_error(const char* what_arg) : std::exception(), what_(what_arg) { } ldap_error::~ldap_error() noexcept { } const char* ldap_error::what() const noexcept { return this->what_.c_str(); } } // namespace ldap } // namespace tt4g
c++
11
0.609375
51
12.575758
33
starcoderdata
#ifndef STANDARD_HPP #define STANDARD_HPP #include "data/vData.hpp" #include "data/ladder.hpp" #include "data/reader.hpp" #include "data/reference.hpp" namespace Anaquin { class Standard { public: static Standard& instance(bool reload = false) { static Standard s; // Reload the default resources if (reload) { s = Standard(); } return s; } // Add sequin regions in BED format static BedData readBED(const Reader &, Base trim = 0); // Add sequin regions in GTF format static std::shared_ptr readGTF(const Reader &); Ladder readLength(const Reader &); /* * ---------------- RnaQuin analysis ---------------- */ Ladder readGene(const Reader &); Ladder readIsoform(const Reader &); Ladder readGDiff(const Reader &); Ladder readIDiff(const Reader &); Ladder readGeneL(const Reader &); RnaRef r_rna; /* * ---------------- MetaQuin analysis ---------------- */ Ladder addMMix(const Reader &); MetaRef r_meta; /* * ---------------- VarQuin analysis ---------------- */ static VCFLadder addVCF(const Reader &, const std::set &); Ladder addAF(const Reader &); // From mixture file Ladder addCNV(const Reader &); // From mixture file Ladder addCon1(const Reader &); // From mixture file Ladder addCon2(const Reader &); // From mixture file Translate addSeq2Unit(const Reader &); Translate addUnit2Seq(const Reader &); VarRef r_var; private: Standard() {} Standard(Standard const&) = delete; }; } #endif
c++
15
0.47277
94
25.296296
81
starcoderdata
import React from 'react'; const authContext = React.createContext({ authenticated: false, login: () => {} }); // Initil value could be any type of data export default authContext;
javascript
9
0.694737
45
22.875
8
starcoderdata