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
def sample_points_across_rays(self, scene, i): # Based on the i index compute the multi-view Image objects images = scene.get_image_with_neighbors(i) # Prepare the inputs inputs = [] # Add the camera center of the reference view inputs.append(images[0].camera.center) # Add the pseudo inverse projection matrix for the reference image inputs.append(images[0].camera.P_pinv) # Add the bounding box that encloses the scene inputs.append(scene.bbox.reshape(6, 1)) points = self._build_sampler(scene)(inputs) return points
python
9
0.649919
74
37.625
16
inline
#include<stdio.h> #define N 100 void Insort(void); int n = 0,arr[N]; int i = 0; int v = 0; int j = 0; int k = 0; int main() { //input data scanf("%d",&n); for(i = 0; i < n; i++) { scanf("%d",&arr[i]); } //assignment Insort printf("%d",arr[0]); for(k = 1; k < n ; k++) { printf(" %d",arr[k]); } printf("\n"); Insort(); return 0; } void Insort(void) { for(i = 1; i <= n - 1; i++) { v = arr[i]; j = i - 1; for(; j >= 0 && arr[j] > v ;) { arr[j+1] = arr[j]; j--; //printf("j=%d\n",j); } arr[j+1]=v; /* if(j == -1 || arr[j] <= v) { arr[j+1] = v; break; }*/ printf("%d",arr[0]); for(k = 1; k < n ; k++) { printf(" %d",arr[k]); } printf("\n"); } }
c
11
0.365314
35
11.134328
67
codenet
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef nsDirectoryService_h___ #define nsDirectoryService_h___ #include "nsIDirectoryService.h" #include "nsHashtable.h" #include "nsIFile.h" #include "nsISupportsArray.h" #include "nsIAtom.h" #include "mozilla/Attributes.h" #define NS_XPCOM_INIT_CURRENT_PROCESS_DIR "MozBinD" // Can be used to set NS_XPCOM_CURRENT_PROCESS_DIR // CANNOT be used to GET a location #define NS_DIRECTORY_SERVICE_CID {0xf00152d0,0xb40b,0x11d3,{0x8c, 0x9c, 0x00, 0x00, 0x64, 0x65, 0x73, 0x74}} class nsDirectoryService MOZ_FINAL : public nsIDirectoryService, public nsIProperties, public nsIDirectoryServiceProvider2 { public: // nsISupports interface NS_DECL_ISUPPORTS NS_DECL_NSIPROPERTIES NS_DECL_NSIDIRECTORYSERVICE NS_DECL_NSIDIRECTORYSERVICEPROVIDER NS_DECL_NSIDIRECTORYSERVICEPROVIDER2 nsDirectoryService(); ~nsDirectoryService(); static void RealInit(); void RegisterCategoryProviders(); static nsresult Create(nsISupports *aOuter, REFNSIID aIID, void **aResult); static nsDirectoryService* gService; private: nsresult GetCurrentProcessDirectory(nsIFile** aFile); static bool ReleaseValues(nsHashKey* key, void* data, void* closure); nsSupportsHashtable mHashtable; nsTArray > mProviders; public: #define DIR_ATOM(name_, value_) static nsIAtom* name_; #include "nsDirectoryServiceAtomList.h" #undef DIR_ATOM }; #endif
c
10
0.68834
110
27.19697
66
starcoderdata
private void normalizeFitness() { // Score is exponentially better double scoreSum = population.stream().mapToDouble((elem) -> { double score = elem.getScore() * elem.getScore(); elem.setScore(score); return score; }).sum(); population.forEach((elem) -> elem.setFitness(elem.getScore() / scoreSum)); }
java
15
0.585561
82
36.5
10
inline
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. * 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. */ #include #include namespace aws { namespace kinesis { namespace core { namespace detail { void IpcReader::start() { if (channel_->open_read_channel()) { while (!shutdown_) { if (read(sizeof(len_t))) { len_t msg_len = 0; for (size_t i = 0; i < sizeof(len_t); i++) { int shift = (sizeof(len_t) - i - 1) * 8; len_t octet = (len_t) buffer_[i]; msg_len += octet << shift; } if (msg_len > kMaxMessageSize) { std::stringstream ss; ss << "Incoming message too large, was " << msg_len << " bytes, max allowed is " << kMaxMessageSize << " bytes"; throw std::runtime_error(ss.str().c_str()); } if (read(msg_len)) { queue_->put(std::string((const char*) buffer_.data(), msg_len)); } } } } } bool IpcReader::read(size_t len) { size_t read = 0; while (read < len) { auto num_read = channel_->read(buffer_.data() + read, len - read); if (num_read <= 0) { if (!shutdown_) { std::stringstream ss; if (num_read < 0) { ss << "IO error reading from ipc channel, errno = " << errno; } else if (num_read == 0) { ss << "EOF reached while reading from ipc channel"; } throw std::runtime_error(ss.str().c_str()); } else { return false; } } read += num_read; } return true; } void IpcWriter::start() { if (channel_->open_write_channel()) { std::string s; while (!shutdown_) { if (!queue_->try_take(s)) { aws::utils::sleep_for(std::chrono::milliseconds(5)); continue; } for (size_t i = 0; i < sizeof(len_t); i++) { auto shift = (sizeof(len_t) - i - 1) * 8; buffer_[i] = (uint8_t)((s.length() >> shift) & 0xFF); } std::memcpy(buffer_.data() + sizeof(len_t), s.data(), s.length()); write(sizeof(len_t) + s.length()); } } } void IpcWriter::write(size_t len) { size_t wrote = 0; while (wrote < len) { auto num_written = channel_->write(buffer_.data() + wrote, len - wrote); if (num_written < 0) { if (!shutdown_) { std::stringstream ss; ss << "IO error writing to ipc channel, errno = " << errno; throw std::runtime_error(ss.str().c_str()); } return; } wrote += num_written; } } } //namespace detail void IpcManager::put(std::string&& data) { if (data.length() > kMaxMessageSize) { std::stringstream ss; ss << "Outgoing message too large, was " << data.length() << " bytes, max allowed is " << kMaxMessageSize << " bytes"; throw std::runtime_error(ss.str().c_str()); } out_queue_->put(std::move(data)); } } //namespace core } //namespace kinesis } //namespace aws
c++
27
0.564354
76
25.112782
133
starcoderdata
p=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] c=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] m= "XPALASXYFGFUKPXUSOGEUTKCDGFXANMGNVS" #input("enter the msg") def multi(a,n): r1=n r2=a t1=t=0 t2=1 while(r2>0): q=r1//r2 r=r1-q*r2 t=t1-t2*q r1=r2 r2=r t1=t2 t2=t #print(r1,r2) if(r1==1): if(t1<0): t1=n+t1 #print("inverse of",a,"is ",t1) #else: #print("inverse of",b,"is ",t1) return t1 else: print("inverse does not exist") s=list(m) #print(s) #Affine cipher #key value as ab is encrypted by gl.(0->6, 1->11) k1=6 #additive key k2=5 #multicative key str3='' for i in range(len(s)): for j in range(len(p)): if(s[i]==c[j]): t=((j-k1)*multi(k2,26))%26 str3+=c[t] print(str3) #plain text=THE BEST OF A FIGHT IS MAKING UP AFTERWARDS
python
14
0.521018
107
20.023256
43
starcoderdata
def update_daughter_info(nucleus_loc_info, ch1, ch2, mother): ''' add notes to the nucleus loc file. :param nucleus_loc_info: nucleus location including notes :param ch1: first child's name :param ch2: second child's name :param mother: mother's name :return nucleus_loc_info: updated nucleus info ''' nucleus_loc_info.loc[nucleus_loc_info.nucleus_name == ch1, ["note", "volume", "surface"]] = ["child_of_{}".format(mother), '', ''] nucleus_loc_info.loc[nucleus_loc_info.nucleus_name == ch2, ["note", "volume", "surface"]] = ["child_of_{}".format(mother), '', ''] return nucleus_loc_info
python
9
0.650316
134
47.692308
13
inline
import dat from 'dat.gui'; import Canvas from '../components/Canvas'; const Can = new Canvas(); /** Parent Render Class */ export default class Render { constructor(element, width, height) { // Display Canvas // const canvasReturn = Can.createCanvas('canvas'); this.canvas = canvasReturn.canvas; this.context = canvasReturn.context; // Background Canvas for Video // const bgCanvasReturn = Can.createCanvas('bgcanvas'); this.bgCanvas = bgCanvasReturn.canvas; this.bgContext = bgCanvasReturn.context; this.bgImageHeight = 0; this.bgImageWidth = 0; this.video = null; this.element = element; // Settings // this.intensity = 0.5; this.color = '#fc5900'; this.foreground = '#333d6b'; this.invert = true; this.useUnderlyingColors = true; this.padding = 0; this.points = []; this.time = 0; this.frames = 0; this.sizing = 105; this.spacing = Math.floor(this.canvas.width / this.sizing) + 1; this.baseRadius = this.spacing * 2.25; // this.baseRadius = 25; this.createGUI(); this.startWebcam('video', 640, 480); setTimeout(()=>this.renderLoop(),300); window.addEventListener('resize', this.resize); } startWebcam = (id, width, height) => { const videoBlock = document.createElement('video'); videoBlock.className = 'video'; videoBlock.width = width; videoBlock.height = height; videoBlock.id = id; videoBlock.setAttribute('autoplay',true); document.body.appendChild(videoBlock); navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia; if (navigator.getUserMedia) { // get webcam feed if available navigator.getUserMedia({video: true, audio: false}, (stream) => { this.video = document.getElementById('video'); try { this.video.srcObject = stream; } catch (error) { console.log(error); this.video.src = window.URL.createObjectURL(stream); } }, () => { console.log('error'); } ); } } snapShot = () => { this.drawImageToBackground(this.video); }; uploadImage = (e) => { const fileReader = new FileReader(); fileReader.onload = (event) => { this.loadData(event.target.result); }; fileReader.readAsDataURL(e.target.files[0]); }; createGUI = () => { this.options = { spacing: this.spacing, sizing: this.sizing, intensity: this.intensity, baseRadius: this.baseRadius, color: this.color, foreground: this.foreground, useUnderlyingColors: this.useUnderlyingColors, invert: this.invert }; this.gui = new dat.GUI(); const obj = { screenShot:() => { this.snapShot(); }}; const folderRender = this.gui.addFolder('Render Options'); folderRender.add(this.options, 'sizing', 10, 125).step(1) .onFinishChange((value) => { this.sizing = value; this.spacing = Math.floor(this.canvas.width / this.sizing); // this.baseRadius = this.spacing * 2; this.preparePoints(); }); folderRender.add(this.options, 'baseRadius', 0, 135).step(0.1) .onFinishChange((value) => { this.baseRadius = value; this.preparePoints(); }); folderRender.add(this.options, 'intensity', 0.00, 2.00).step(0.01) .onFinishChange((value) => { this.intensity = value; this.preparePoints(); }); folderRender.add(this.options, 'useUnderlyingColors') .onChange((value) => { this.useUnderlyingColors = value; }); folderRender.add(this.options, 'invert') .onChange((value) => { this.invert = value; }); folderRender.addColor(this.options, 'color') .onChange((value) => { this.color = value; this.preparePoints(); }); folderRender.addColor(this.options, 'foreground') .onChange((value) => { this.foreground = value; this.preparePoints(); }); // folderRender.open(); }; resize = () => { window.cancelAnimationFrame(this.animation); const bgCanvasReturn = Can.setViewport(this.bgCanvas); this.bgCanvas.width = bgCanvasReturn.width; this.bgCanvas.height = bgCanvasReturn.height; const canvasReturn = Can.setViewport(this.canvas); this.canvas.width = canvasReturn.width; this.canvas.height = canvasReturn.height; this.spacing = Math.floor(this.canvas.width / this.sizing); this.renderLoop(); }; rgbToHex = (r, g, b) => { return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`; }; getPixelData = ( x, y, width, height ) => { let pixels; if ( x === undefined ) { pixels = this.bgContext.getImageData( 0, 0, this.bgCanvas.width, this.bgCanvas.height ); } else { pixels = this.bgContext.getImageData( x, y, width, height ); } return pixels; }; greyScaleImage = () => { const imageData = this.getPixelData(); const data = imageData.data; for(let i = 0; i < data.length; i += 4) { const brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2]; data[i] = brightness; data[i + 1] = brightness; data[i + 2] = brightness; } this.bgContext.putImageData( imageData, 0, 0 ); }; preparePoints = () => { this.points = []; this.cols = ~~(this.canvas.width / this.spacing); this.rows = ~~(this.canvas.height / this.spacing); const pixelData = this.getPixelData(); const colors = pixelData.data; for( let i = 0; i < this.rows; i++ ) { for ( let j = 0; j < this.cols; j++ ) { const pixelPosition = ( (j * this.spacing) + (i * this.spacing) * pixelData.width ) * 4; // We only need one color here... since they are all the same. const brightness = 0.34 * colors[pixelPosition] + 0.5 * colors[pixelPosition + 1] + 0.16 * colors[pixelPosition + 2]; const baseRadius = (this.calculateRadius( j, i, brightness )/ 3); const color = `rgba(${colors[pixelPosition]},${colors[pixelPosition + 1]},${colors[pixelPosition + 2]},1)`; this.points.push( { x: j, y: i, radius: baseRadius, color: color } ); } } }; calculateRadius = ( x, y, color) => { let radius; if ( this.invert ) { radius = Math.round( this.baseRadius * ( color / 255 ) ); } else { radius = Math.round( this.baseRadius * (1 - ( color / 255 ) ) ); } return radius * this.intensity; }; drawPoints = () => { let currentPoint; this.context.fillStyle = this.foreground; this.context.fillRect(0, 0, this.canvas.width, this.canvas.height); this.context.lineCap = 'square'; const d = ~~(this.canvas.width / this.spacing); let n; let x; let y; for ( let i = 0; i < this.points.length; i++ ) { currentPoint = this.points[i]; x = i % d; y = ~~((i - x) / d); const compColor = this.color; if ( this.useUnderlyingColors ) { this.context.fillStyle = currentPoint.color; this.context.strokeStyle = currentPoint.color; } else { this.context.fillStyle = compColor; this.context.strokeStyle = compColor; } this.context.beginPath(); // this.context.arc( // (this.spacing + (x * this.spacing)) - currentPoint.radius, // (this.spacing + (y * this.spacing)) - currentPoint.radius, // currentPoint.radius, // 0 , 2 * Math.PI, true); const offset = this.spacing * 0.5; const radi = currentPoint.radius; this.context.fillRect( offset + (x * this.spacing) - radi, offset + (y * this.spacing) - radi, currentPoint.radius * 2, currentPoint.radius * 2); this.context.closePath(); this.context.fill(); } }; renderLoop = () => { this.frames += 1; if(this.frames % 2 === 0) { this.snapShot(); } this.drawPoints(); this.animation = window.requestAnimationFrame(this.renderLoop); }; loadData = ( data ) => { this.bgImage = new Image; this.bgImage.src = data; this.bgImageHeight = this.bgImage.height; this.bgImageWidth = this.bgImage.width; this.bgImage.onload = () => { this.bgContext.drawImage(this.bgImage, 0, 0, this.bgCanvas.width, this.bgCanvas.height); this.preparePoints(); this.renderLoop(); }; }; // Image is loaded... draw to bg canvas drawImageToBackground = (image) => { this.bgContext.drawImage( image, 0, 0, this.bgCanvas.width, this.bgCanvas.height ); this.preparePoints(); }; }
javascript
22
0.597544
115
30.919414
273
starcoderdata
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Integration.AspNet.Core; using Microsoft.Bot.Connector.Authentication; using Microsoft.Extensions.DependencyInjection; using $safeprojectname$.Adapters; using $safeprojectname$.Bots; using $safeprojectname$.Dialogs.Root; using $safeprojectname$.Helpers; using $safeprojectname$.Interfaces; using $safeprojectname$.Middleware; using $safeprojectname$.Services; namespace $safeprojectname$ { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_1); services.AddSingleton<IBotServices, BotServices>(); services.AddSingleton<IBotFrameworkHttpAdapter, AdapterWithErrorHandler>(); services.AddSingleton<ICredentialProvider, ConfigurationCredentialProvider>(); services.AddSingleton<IStorage, MemoryStorage>(); services.AddSingleton services.AddSingleton services.AddSingleton services.AddSingleton services.AddSingleton services.AddTransient<IBot, MainBot } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseDefaultFiles() .UseStaticFiles() .UseMvc(); } } }
c#
15
0.714608
113
31.236364
55
starcoderdata
using System; using Durwella.Unplugged.Viz; using Xamarin.Forms; namespace DurwellaUnpluggedVizExamples { public class Seismic3DModelBase : BindableObject, IIndexedGeometry, IColorMappedGeometry, ITextureMappedGeometry, ILitGeometry { [ColorMap] public virtual Array ColorMap { get { return new byte[,] { { 255, 000, 000, 255 }, { 255, 255, 255, 255 }, { 000, 000, 255, 255 }, }; } } float _colorMapMinimum = 0; [Uniform] public float ColorMapMinimum { get { return _colorMapMinimum; } set { _colorMapMinimum = value; OnPropertyChanged("ColorMapMinimum"); } } float _colorMapMaximum = 1; [Uniform] public float ColorMapMaximum { get { return _colorMapMaximum; } set { _colorMapMaximum = value; OnPropertyChanged("ColorMapMaximum"); } } protected Array _textureMap; [TextureMap(MagnificationFilter.LinearInterpolation, WrapMode.ClampToEdge)] public virtual Array TextureMap { get { return _textureMap; } protected set { _textureMap = value; OnPropertyChanged("TextureMap"); } } [Uniform] public virtual float[] LightPosition { get { return new float[] { 0.5f, 2, 2 }; } } public virtual float[,] Normals { get; } protected Array _textureCoordinates; [VertexAttribute] public virtual Array TextureCoordinates { get { return _textureCoordinates; } protected set { _textureCoordinates = value; OnPropertyChanged("TextureCoordinates"); } } protected int[] _indices; [VertexIndices] public virtual int[] Indices { get { return _indices; } protected set { _indices = value; OnPropertyChanged("Indices"); } } protected Array _vertices; [VertexAttribute] public virtual Array Vertices { get { return _vertices; } protected set { _vertices = value; OnPropertyChanged("Vertices"); } } } }
c#
14
0.670557
127
19.944444
90
starcoderdata
bool cmWriteFileCommand::InitialPass(std::vector<std::string> const& args, cmExecutionStatus&) { if (args.size() < 2) { this->SetError("called with incorrect number of arguments"); return false; } std::string message; std::vector<std::string>::const_iterator i = args.begin(); std::string const& fileName = *i; bool overwrite = true; i++; for (; i != args.end(); ++i) { if (*i == "APPEND") { overwrite = false; } else { message += *i; } } if (!this->Makefile->CanIWriteThisFile(fileName)) { std::string e = "attempted to write a file: " + fileName + " into a source directory."; this->SetError(e); cmSystemTools::SetFatalErrorOccured(); return false; } std::string dir = cmSystemTools::GetFilenamePath(fileName); cmSystemTools::MakeDirectory(dir); mode_t mode = 0; bool writable = false; // Set permissions to writable if (cmSystemTools::GetPermissions(fileName.c_str(), mode)) { #if defined(_MSC_VER) || defined(__MINGW32__) writable = mode & S_IWRITE; mode_t newMode = mode | S_IWRITE; #else writable = mode & S_IWUSR; mode_t newMode = mode | S_IWUSR | S_IWGRP; #endif if (!writable) { cmSystemTools::SetPermissions(fileName.c_str(), newMode); } } // If GetPermissions fails, pretend like it is ok. File open will fail if // the file is not writable cmsys::ofstream file(fileName.c_str(), overwrite ? std::ios::out : std::ios::app); if (!file) { std::string error = "Internal CMake error when trying to open file: "; error += fileName; error += " for writing."; this->SetError(error); return false; } file << message << std::endl; file.close(); if (mode && !writable) { cmSystemTools::SetPermissions(fileName.c_str(), mode); } return true; }
c++
12
0.609392
77
26.573529
68
inline
ELECTION_HOME = "election@home" ELECTION_VIEW = "election@view" ELECTION_META = "election@meta" ELECTION_EDIT = "election@edit" ELECTION_SCHEDULE = "election@schedule" ELECTION_EXTEND = "election@extend" ELECTION_ARCHIVE = "election@archive" ELECTION_COPY = "election@copy" ELECTION_BADGE = "election@badge" ELECTION_TRUSTEES_HOME = "election@trustees" ELECTION_TRUSTEES_VIEW = "election@trustees@view" ELECTION_TRUSTEES_NEW = "election@trustees@new" ELECTION_TRUSTEES_ADD_HELIOS = "election@trustees@add-helios" ELECTION_TRUSTEES_DELETE = "election@trustees@delete" ELECTION_TRUSTEE_HOME = "election@trustee" ELECTION_TRUSTEE_SEND_URL = "election@trustee@send-url" ELECTION_TRUSTEE_KEY_GENERATOR = "election@trustee@key-generator" ELECTION_TRUSTEE_CHECK_SK = "election@trustee@check-sk" ELECTION_TRUSTEE_UPLOAD_PK = "election@trustee@upload-pk" ELECTION_TRUSTEE_DECRYPT_AND_PROVE = "election@trustee@decrypt-and-prove" ELECTION_TRUSTEE_UPLOAD_DECRYPTION = "election@trustee@upload-decryption" ELECTION_RESULT = "election@result" ELECTION_RESULT_PROOF = "election@result@proof" ELECTION_BBOARD = "election@bboard" ELECTION_AUDITED_BALLOTS = "election@audited-ballots" ELECTION_GET_RANDOMNESS = "election@get-randomness" ELECTION_ENCRYPT_BALLOT = "election@encrypt-ballot" ELECTION_QUESTIONS = "election@questions" ELECTION_SET_REG = "election@set-reg" ELECTION_SET_FEATURED = "election@set-featured" ELECTION_SAVE_QUESTIONS = "election@save-questions" ELECTION_REGISTER = "election@register" ELECTION_FREEZE = "election@freeze" ELECTION_COMPUTE_TALLY = "election@compute-tally" ELECTION_COMBINE_DECRYPTIONS = "election@combine-decryptions" ELECTION_RELEASE_RESULT = "election@release-result" ELECTION_CAST = "election@cast" ELECTION_CAST_CONFIRM = "election@cast-confirm" ELECTION_PASSWORD_VOTER_LOGIN = "election@password-voter-login" ELECTION_CAST_DONE = "election@cast-done" ELECTION_POST_AUDITED_BALLOT = "election@post-audited-ballot" ELECTION_VOTERS_HOME = "election@voters" ELECTION_VOTERS_UPLOAD = "election@voters@upload" ELECTION_VOTERS_UPLOAD_CANCEL = "election@voters@upload-cancel" ELECTION_VOTERS_LIST = "election@voters@list" ELECTION_VOTERS_LIST_PRETTY = "election@voters@list-pretty" ELECTION_VOTERS_ELIGIBILITY = "election@voters@eligibility" ELECTION_VOTERS_EMAIL = " ELECTION_VOTER = "election@voter" ELECTION_VOTER_DELETE = "election@voter@delete" ELECTION_BALLOTS_LIST = "election@ballots@list" ELECTION_BALLOTS_VOTER = "election@ballots@voter" ELECTION_BALLOTS_VOTER_LAST = "election@ballots@voter@last"
python
4
0.791667
73
40.032258
62
starcoderdata
/* * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0, which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package com.sun.codemodel.writer; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import com.sun.codemodel.CodeWriter; import com.sun.codemodel.JPackage; /** * Output all source files into a single stream with a little * formatting header in front of each file. * * This is primarily for human consumption of the generated source * code, such as to debug/test CodeModel or to quickly inspect the result. * * @author * ( */ public class SingleStreamCodeWriter extends CodeWriter { private final PrintStream out; /** * @param os * This stream will be closed at the end of the code generation. */ public SingleStreamCodeWriter( OutputStream os ) { out = new PrintStream(os); } @Override public OutputStream openBinary(JPackage pkg, String fileName) throws IOException { final String name = pkg != null && pkg.name().length() > 0 ? pkg.name() + '.' + fileName : fileName; out.println( "-----------------------------------" + name + "-----------------------------------"); return new FilterOutputStream(out) { @Override public void close() { // don't let this stream close } }; } @Override public void close() throws IOException { out.close(); } }
java
13
0.613151
86
26.651515
66
starcoderdata
// // Created by on 16/07/20. // #ifndef GAMEMATCHER_MATCHINGSCORE_H #define GAMEMATCHER_MATCHINGSCORE_H #include #include "models.h" #include "GameStats.h" #include "CollectionUtils.h" class MatchingScore { public: template <typename PlayerInfoList> static int levelRangeScore(const PlayerInfoList &members, int minLevel, int maxLevel) { if (members.size() < 2) return 0; int min = maxLevel + 1, max = minLevel - 1; for (const auto &m : members) { auto level = m->level; if (level > max) max = level; if (level < min) min = level; } return (max - min) * 100 / (maxLevel - minLevel); } template <typename PlayerInfoList> static int levelStdVarianceScore(const PlayerInfoList &members, int minLevel, int maxLevel) { if (members.size() < 2) return 0; const int sum = reduceCollection(members, 0, [](auto sum, const auto &info) { return sum + info->level; }); const double average = static_cast / members.size(); return std::sqrt(reduceCollection(members, 0.0, [average](auto sum, const auto &info) { auto diff = info->level - average; return sum + diff * diff; }) / (members.size() - 1)) * 100 / (maxLevel - minLevel); } template <typename PlayerInfoList> static int genderSimilarityScore(const PlayerInfoList &players) { if (players.size() < 2) return 100; int numMales = std::count_if(players.begin(), players.end(), [](const auto &p) { return p->gender == Member::Male; }); int numFemales = players.size() - numMales; if (numMales == 0 || numMales == players.size() || numFemales == numMales) return 100; int maxDiff = players.size() - 2; return (maxDiff - std::abs(numMales - numFemales)) * 100 / maxDiff; } template <typename PlayerInfoList> static int computeCourtScore(const GameStats &stats, const PlayerInfoList &players, int minLevel, int maxLevel) { thread_local QVector playerIds; playerIds.clear(); for (const auto &p : players) { playerIds.push_back(p->memberId); } auto simScore = -stats.similarityScore(playerIds) * 3; auto varianceScore = -levelStdVarianceScore(players, minLevel, maxLevel) * 2; auto levelScore = -levelRangeScore(players, minLevel, maxLevel) * 2; auto genderScore = genderSimilarityScore(players); int score = simScore + varianceScore + levelScore + genderScore; return score; } }; #endif //GAMEMATCHER_MATCHINGSCORE_H
c
19
0.624263
117
32.481481
81
starcoderdata
var classQtCameraBackend = [ [ "QtCameraBackend", "classQtCameraBackend.html#aef64731b823e644b8e74e79516161a89", null ], [ "~QtCameraBackend", "classQtCameraBackend.html#a4bda5a499c946d6f8bd1ca8467f91502", null ], [ "convert", "classQtCameraBackend.html#a348256e3c5a07da0b30f54444a4b8d85", null ], [ "getCamera", "classQtCameraBackend.html#a844ebf3f2d5cabd2824871c5c12dceb6", null ], [ "handleFinished", "classQtCameraBackend.html#a8e3d4b06e1d7fdf95d56826aec9d8211", null ], [ "init", "classQtCameraBackend.html#adc1111a76ca509788a09021f912b324b", null ], [ "processAndSendQImage", "classQtCameraBackend.html#a2af2dc2522039bc537f93bfabc21e292", null ], [ "processQImage", "classQtCameraBackend.html#ac6aae303b95fa252d9e362b670c135d2", null ], [ "processQVideoFrame", "classQtCameraBackend.html#af75292515bc72d0560d98e733a6548dd", null ], [ "requestImage", "classQtCameraBackend.html#a7d5d849774ded03aeb4b9ece0b9da2f4", null ], [ "setActive", "classQtCameraBackend.html#af79eab49fa40a86802bcb3944048cc33", null ], [ "setColor", "classQtCameraBackend.html#aed8df725012118e54bd3f84bf5511aaf", null ], [ "setPolygon", "classQtCameraBackend.html#ac88e4c2ec9cb923d13ab5b23e435b1a1", null ], [ "setShowOutput", "classQtCameraBackend.html#abc6d55aab41600b8b25d1b8f96ecf11c", null ], [ "setSMinMax", "classQtCameraBackend.html#a3e2269e3d5025ab9e857bc43ee442b23", null ], [ "setVMinMax", "classQtCameraBackend.html#a698e717bb7bed890498b6a4662b15fa4", null ], [ "start", "classQtCameraBackend.html#a2c6c91151c638fae64155a2992d97f58", null ], [ "updateHSVThreshold", "classQtCameraBackend.html#a6278f5a78524169bb80c12ad4009f2bc", null ], [ "buf", "classQtCameraBackend.html#a16800f7288df4b5da941df46f2471d66", null ], [ "camera", "classQtCameraBackend.html#afdbcad49e467e728080291f7028283fa", null ], [ "delta_h", "classQtCameraBackend.html#ad77edbf746ec65bfea6c86d350b12e77", null ], [ "frame_available", "classQtCameraBackend.html#a3a876c8236e938a72141d430a27986d8", null ], [ "frameGrabber", "classQtCameraBackend.html#af0188e844ccde8ea32833aa956cebe7e", null ], [ "image_id", "classQtCameraBackend.html#ac9b3267a0fa9ebcd4577360cacfea9ef", null ], [ "image_info", "classQtCameraBackend.html#a8e737608f9dadc5591a979578da7b625", null ], [ "last_frame", "classQtCameraBackend.html#a2063e2d0a8b546aed275753fd16a99eb", null ], [ "max_s", "classQtCameraBackend.html#a8f3eb89c8255304c83b557b732cad33c", null ], [ "max_v", "classQtCameraBackend.html#a31aa077726e4f2902f3cb0cf5af13bde", null ], [ "mean_h", "classQtCameraBackend.html#aed5a0f8f16d5937b672b4e454f905eba", null ], [ "min_s", "classQtCameraBackend.html#a8c20c0225c06cbe39472def660867811", null ], [ "min_v", "classQtCameraBackend.html#abd87e3ef80123196a0b0cef61088058e", null ], [ "need_viewfinder", "classQtCameraBackend.html#ac2b69e4752e5963a05cb7a8ad36c19c3", null ], [ "probe", "classQtCameraBackend.html#a40bff40f0d069c3e4c4f285820dd160e", null ], [ "use_gpu", "classQtCameraBackend.html#a5543edcf13c6b6940ef0d47e3e0ff617", null ], [ "viewfinder", "classQtCameraBackend.html#a872ebb713957f62e8b81306a66a1581e", null ], [ "watcher", "classQtCameraBackend.html#a8d2656dab3590fdcc97ce5946bbdea58", null ] ];
javascript
3
0.775264
100
81.9
40
starcoderdata
func startLoop() { last := time.Now() for !win.Closed() { dtMilliS := time.Since(last).Milliseconds() if gameOver { if win.JustPressed(pixelgl.KeyEnter) { gameOver = false score = 0 model.NewActivePiece() } } else { initWindow() nextTxt.Draw(win, pixel.IM.Scaled(nextTxt.Orig, 3.5)) drawActivePiece() drawNextPiece() drawScore() drawBoard() if win.JustPressed(pixelgl.KeyLeft) { if model.CanMoveLeft() { model.MoveLeft() } } else if win.JustPressed(pixelgl.KeyRight) { if model.CanMoveRight() { model.MoveRight() } } else if win.JustPressed(pixelgl.KeyZ) { if model.CanRotateLeft() { model.RotateLeft() } } else if win.JustPressed(pixelgl.KeyX) { if model.CanRotateRight() { model.RotateRight() } } if dtMilliS > 1000 { // Every second, drop the active piece if model.CanDrop() { model.Drop() } else { model.AddActivePieceToBoard() completedRows := model.GetCompletedRows() for _, row := range completedRows { model.DeleteRow(row) } placed := model.NewActivePiece() if !(placed) { gameOver = true drawGameOver() model.ClearBoard() } } score++ last = time.Now() } } win.Update() } }
go
17
0.602941
62
19.854839
62
inline
/* * txx9wdt: A Hardware Watchdog Driver for TXx9 SoCs * * Copyright (C) 2007 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #define TIMER_MARGIN 60 /* Default is 60 seconds */ static int timeout = TIMER_MARGIN; /* in seconds */ module_param(timeout, int, 0); MODULE_PARM_DESC(timeout, "Watchdog timeout in seconds. " "(0<timeout<((2^" __MODULE_STRING(TXX9_TIMER_BITS) ")/(IMCLK/256)), " "default=" __MODULE_STRING(TIMER_MARGIN) ")"); static int nowayout = WATCHDOG_NOWAYOUT; module_param(nowayout, int, 0); MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started " "(default=" __MODULE_STRING(WATCHDOG_NOWAYOUT) ")"); #define WD_TIMER_CCD 7 /* 1/256 */ #define WD_TIMER_CLK (clk_get_rate(txx9_imclk) / (2 << WD_TIMER_CCD)) #define WD_MAX_TIMEOUT ((0xffffffff >> (32 - TXX9_TIMER_BITS)) / WD_TIMER_CLK) static unsigned long txx9wdt_alive; static int expect_close; static struct txx9_tmr_reg __iomem *txx9wdt_reg; static struct clk *txx9_imclk; static DEFINE_SPINLOCK(txx9_lock); static void txx9wdt_ping(void) { spin_lock(&txx9_lock); __raw_writel(TXx9_TMWTMR_TWIE | TXx9_TMWTMR_TWC, &txx9wdt_reg->wtmr); spin_unlock(&txx9_lock); } static void txx9wdt_start(void) { spin_lock(&txx9_lock); __raw_writel(WD_TIMER_CLK * timeout, &txx9wdt_reg->cpra); __raw_writel(WD_TIMER_CCD, &txx9wdt_reg->ccdr); __raw_writel(0, &txx9wdt_reg->tisr); /* clear pending interrupt */ __raw_writel(TXx9_TMTCR_TCE | TXx9_TMTCR_CCDE | TXx9_TMTCR_TMODE_WDOG, &txx9wdt_reg->tcr); __raw_writel(TXx9_TMWTMR_TWIE | TXx9_TMWTMR_TWC, &txx9wdt_reg->wtmr); spin_unlock(&txx9_lock); } static void txx9wdt_stop(void) { spin_lock(&txx9_lock); __raw_writel(TXx9_TMWTMR_WDIS, &txx9wdt_reg->wtmr); __raw_writel(__raw_readl(&txx9wdt_reg->tcr) & ~TXx9_TMTCR_TCE, &txx9wdt_reg->tcr); spin_unlock(&txx9_lock); } static int txx9wdt_open(struct inode *inode, struct file *file) { if (test_and_set_bit(0, &txx9wdt_alive)) return -EBUSY; if (__raw_readl(&txx9wdt_reg->tcr) & TXx9_TMTCR_TCE) { clear_bit(0, &txx9wdt_alive); return -EBUSY; } if (nowayout) __module_get(THIS_MODULE); txx9wdt_start(); return nonseekable_open(inode, file); } static int txx9wdt_release(struct inode *inode, struct file *file) { if (expect_close) txx9wdt_stop(); else { printk(KERN_CRIT "txx9wdt: " "Unexpected close, not stopping watchdog!\n"); txx9wdt_ping(); } clear_bit(0, &txx9wdt_alive); expect_close = 0; return 0; } static ssize_t txx9wdt_write(struct file *file, const char __user *data, size_t len, loff_t *ppos) { if (len) { if (!nowayout) { size_t i; expect_close = 0; for (i = 0; i != len; i++) { char c; if (get_user(c, data + i)) return -EFAULT; if (c == 'V') expect_close = 1; } } txx9wdt_ping(); } return len; } static long txx9wdt_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { void __user *argp = (void __user *)arg; int __user *p = argp; int new_timeout; static const struct watchdog_info ident = { .options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING | WDIOF_MAGICCLOSE, .firmware_version = 0, .identity = "Hardware Watchdog for TXx9", }; switch (cmd) { case WDIOC_GETSUPPORT: return copy_to_user(argp, &ident, sizeof(ident)) ? -EFAULT : 0; case WDIOC_GETSTATUS: case WDIOC_GETBOOTSTATUS: return put_user(0, p); case WDIOC_KEEPALIVE: txx9wdt_ping(); return 0; case WDIOC_SETTIMEOUT: if (get_user(new_timeout, p)) return -EFAULT; if (new_timeout < 1 || new_timeout > WD_MAX_TIMEOUT) return -EINVAL; timeout = new_timeout; txx9wdt_stop(); txx9wdt_start(); /* Fall */ case WDIOC_GETTIMEOUT: return put_user(timeout, p); default: return -ENOTTY; } } static const struct file_operations txx9wdt_fops = { .owner = THIS_MODULE, .llseek = no_llseek, .write = txx9wdt_write, .unlocked_ioctl = txx9wdt_ioctl, .open = txx9wdt_open, .release = txx9wdt_release, }; static struct miscdevice txx9wdt_miscdev = { .minor = WATCHDOG_MINOR, .name = "watchdog", .fops = &txx9wdt_fops, }; static int __init txx9wdt_probe(struct platform_device *dev) { struct resource *res; int ret; txx9_imclk = clk_get(NULL, "imbus_clk"); if (IS_ERR(txx9_imclk)) { ret = PTR_ERR(txx9_imclk); txx9_imclk = NULL; goto exit; } ret = clk_enable(txx9_imclk); if (ret) { clk_put(txx9_imclk); txx9_imclk = NULL; goto exit; } res = platform_get_resource(dev, IORESOURCE_MEM, 0); if (!res) goto exit_busy; if (!devm_request_mem_region(&dev->dev, res->start, resource_size(res), "txx9wdt")) goto exit_busy; txx9wdt_reg = devm_ioremap(&dev->dev, res->start, resource_size(res)); if (!txx9wdt_reg) goto exit_busy; ret = misc_register(&txx9wdt_miscdev); if (ret) { goto exit; } printk(KERN_INFO "Hardware Watchdog Timer for TXx9: " "timeout=%d sec (max %ld) (nowayout= %d)\n", timeout, WD_MAX_TIMEOUT, nowayout); return 0; exit_busy: ret = -EBUSY; exit: if (txx9_imclk) { clk_disable(txx9_imclk); clk_put(txx9_imclk); } return ret; } static int __exit txx9wdt_remove(struct platform_device *dev) { misc_deregister(&txx9wdt_miscdev); clk_disable(txx9_imclk); clk_put(txx9_imclk); return 0; } static void txx9wdt_shutdown(struct platform_device *dev) { txx9wdt_stop(); } static struct platform_driver txx9wdt_driver = { .remove = __exit_p(txx9wdt_remove), .shutdown = txx9wdt_shutdown, .driver = { .name = "txx9wdt", .owner = THIS_MODULE, }, }; static int __init watchdog_init(void) { return platform_driver_probe(&txx9wdt_driver, txx9wdt_probe); } static void __exit watchdog_exit(void) { platform_driver_unregister(&txx9wdt_driver); } module_init(watchdog_init); module_exit(watchdog_exit); MODULE_DESCRIPTION("TXx9 Watchdog Driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR); MODULE_ALIAS("platform:txx9wdt");
c
14
0.672565
78
22.739777
269
starcoderdata
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. */ /** * */ package sql.sqlutil; import sql.SQLTest; import sql.dmlStatements.DMLStmtIF; import sql.dmlStatements.EmpDepartmentDMLStmt; import sql.dmlStatements.EmpEmployeesDMLStmt; import sql.dmlStatements.TradeBuyOrdersDMLStmt; import sql.dmlStatements.TradeCompaniesDMLStmt; import sql.dmlStatements.TradeCustomerProfileDMLStmt; import sql.dmlStatements.TradeCustomersDMLStmt; import sql.dmlStatements.TradeNetworthDMLStmt; import sql.dmlStatements.TradePortfolioDMLStmt; import sql.dmlStatements.TradePortfolioV1DMLStmt; import sql.dmlStatements.TradeSecuritiesDMLStmt; import sql.dmlStatements.TradeSellOrdersDMLStmt; import sql.dmlStatements.TradeSellOrdersDupDMLStmt; import sql.dmlStatements.TradeTxHistoryDMLStmt; import sql.dmlStatements.json.TradeBuyOrderDMLStmtJson; import sql.dmlStatements.json.TradeCustomersDMLStmtJson; import sql.dmlStatements.json.TradeNetworthDMLStmtJson; import sql.dmlStatements.json.TradeSecuritiesDMLStmtJson; import sql.dmlStatements.writer.TradeBuyOrdersWriterDMLStmt; import sql.dmlStatements.writer.TradeCustomersWriterDMLStmt; import sql.dmlStatements.writer.TradeNetworthWriterDMLStmt; import sql.dmlStatements.writer.TradePortfolioV1WriterDMLStmt; import sql.dmlStatements.writer.TradePortfolioWriterDMLStmt; import sql.dmlStatements.writer.TradeSecuritiesWriterDMLStmt; import sql.dmlStatements.writer.TradeSellOrdersWriterDMLStmt; import sql.dmlStatements.writer.TradeTxHistoryWriterDMLStmt; import sql.sqlDisk.dmlStatements.TradeBuyOrdersDiscDMLStmt; import sql.sqlDisk.dmlStatements.TradeCompaniesDiscDMLStmt; import sql.sqlDisk.dmlStatements.TradeCustomersDiscDMLStmt; import sql.sqlDisk.dmlStatements.TradeNetworthDiscDMLStmt; import sql.sqlDisk.dmlStatements.TradePortfolioDiscDMLStmt; import sql.sqlDisk.dmlStatements.TradePortfolioV1DiscDMLStmt; import sql.sqlDisk.dmlStatements.TradeSecuritiesDiscDMLStmt; import sql.sqlDisk.dmlStatements.TradeSellOrdersDiscDMLStmt; import sql.sqlDisk.dmlStatements.TradeTxHistoryDiscDMLStmt; import util.TestException; /** * @author eshu * */ public class DMLStmtsFactory { public static final int TRADE_CUSTOMERS = 1; public static final int TRADE_SECURITIES = 2; public static final int TRADE_PORTFOLIO = 3; public static final int TRADE_NETWORTH = 4; public static final int TRADE_SELLORDERS = 5; public static final int TRADE_BUYORDERS = 6; public static final int TRADE_TXHISTORY = 7; public static final int EMP_DEPARTMENT = 8; public static final int EMP_EMPLOYEES = 9; public static final int TRADE_CUSTOMERPROFILE = 10; public static final int TRADE_SELLORDERSDUP = 11; public static final int TRADE_COMPANIES = 12; public static final int TRADE_PORTFOLIOV1 = 13; public DMLStmtIF createDMLStmt(int whichTable) { DMLStmtIF dmlStmtIF; switch (whichTable) { case TRADE_CUSTOMERS: if (SQLTest.hasJSON) dmlStmtIF = new TradeCustomersDMLStmtJson(); else dmlStmtIF = new TradeCustomersDMLStmt(); break; case TRADE_SECURITIES: if (SQLTest.hasJSON) dmlStmtIF = new TradeSecuritiesDMLStmtJson(); else dmlStmtIF = new TradeSecuritiesDMLStmt(); break; case TRADE_PORTFOLIO: dmlStmtIF = new TradePortfolioDMLStmt(); break; case TRADE_NETWORTH: if (SQLTest.hasJSON) dmlStmtIF = new TradeNetworthDMLStmtJson(); else dmlStmtIF = new TradeNetworthDMLStmt(); break; case TRADE_SELLORDERS: dmlStmtIF = new TradeSellOrdersDMLStmt(); break; case TRADE_BUYORDERS: if (SQLTest.hasJSON) dmlStmtIF = new TradeBuyOrderDMLStmtJson(); else dmlStmtIF = new TradeBuyOrdersDMLStmt(); break; case TRADE_TXHISTORY: dmlStmtIF = new TradeTxHistoryDMLStmt(); break; case EMP_DEPARTMENT: dmlStmtIF = new EmpDepartmentDMLStmt(); break; case EMP_EMPLOYEES: dmlStmtIF = new EmpEmployeesDMLStmt(); break; case TRADE_CUSTOMERPROFILE: dmlStmtIF = new TradeCustomerProfileDMLStmt(); break; case TRADE_SELLORDERSDUP: dmlStmtIF = new TradeSellOrdersDupDMLStmt(); break; case TRADE_COMPANIES: dmlStmtIF = new TradeCompaniesDMLStmt(); break; case TRADE_PORTFOLIOV1: dmlStmtIF = new TradePortfolioV1DMLStmt(); break; default: throw new TestException("Unknown operation " + whichTable); } return dmlStmtIF; } public DMLStmtIF createWriterDMLStmt(int whichTable) { DMLStmtIF dmlStmtIF; switch (whichTable) { case TRADE_CUSTOMERS: dmlStmtIF = new TradeCustomersWriterDMLStmt(); break; case TRADE_SECURITIES: dmlStmtIF = new TradeSecuritiesWriterDMLStmt(); break; case TRADE_PORTFOLIO: dmlStmtIF = new TradePortfolioWriterDMLStmt(); break; case TRADE_NETWORTH: dmlStmtIF = new TradeNetworthWriterDMLStmt(); break; case TRADE_SELLORDERS: dmlStmtIF = new TradeSellOrdersWriterDMLStmt(); break; case TRADE_BUYORDERS: dmlStmtIF = new TradeBuyOrdersWriterDMLStmt(); break; case TRADE_TXHISTORY: dmlStmtIF = new TradeTxHistoryWriterDMLStmt(); break; case TRADE_PORTFOLIOV1: dmlStmtIF = new TradePortfolioV1WriterDMLStmt(); break; default: throw new TestException("Unknown operation " + whichTable); } return dmlStmtIF; } public DMLStmtIF createDiscDMLStmt(int whichTable) { DMLStmtIF dmlStmtIF; switch (whichTable) { case TRADE_CUSTOMERS: dmlStmtIF = new TradeCustomersDiscDMLStmt(); break; case TRADE_SECURITIES: dmlStmtIF = new TradeSecuritiesDiscDMLStmt(); break; case TRADE_PORTFOLIO: dmlStmtIF = new TradePortfolioDiscDMLStmt(); break; case TRADE_NETWORTH: dmlStmtIF = new TradeNetworthDiscDMLStmt(); break; case TRADE_SELLORDERS: dmlStmtIF = new TradeSellOrdersDiscDMLStmt(); break; case TRADE_BUYORDERS: dmlStmtIF = new TradeBuyOrdersDiscDMLStmt(); break; case TRADE_TXHISTORY: dmlStmtIF = new TradeTxHistoryDiscDMLStmt(); break; case TRADE_COMPANIES: dmlStmtIF = new TradeCompaniesDiscDMLStmt(); break; case TRADE_PORTFOLIOV1: dmlStmtIF = new TradePortfolioV1DiscDMLStmt(); break; default: throw new TestException("Unknown operation " + whichTable); } return dmlStmtIF; } public static int getInt(String tableName) { int whichTable = -1; if (tableName.equalsIgnoreCase("trade.customers")) whichTable = TRADE_CUSTOMERS; else if (tableName.equalsIgnoreCase("trade.securities")) whichTable = TRADE_SECURITIES; else if (tableName.equalsIgnoreCase("trade.portfolio")) whichTable = TRADE_PORTFOLIO; else if (tableName.equalsIgnoreCase("trade.networth")) whichTable = TRADE_NETWORTH; else if (tableName.equalsIgnoreCase("trade.sellorders")) whichTable = TRADE_SELLORDERS; else if (tableName.equalsIgnoreCase("trade.buyorders")) whichTable = TRADE_BUYORDERS; else if (tableName.equalsIgnoreCase("trade.txhistory")) whichTable = TRADE_TXHISTORY; else if (tableName.equalsIgnoreCase("emp.department")) whichTable = EMP_DEPARTMENT; else if (tableName.equalsIgnoreCase("emp.employees")) whichTable = EMP_EMPLOYEES; else if (tableName.equalsIgnoreCase("trade.customerprofile")) whichTable = TRADE_CUSTOMERPROFILE; else if (tableName.equalsIgnoreCase("trade.sellordersdup")) whichTable = TRADE_SELLORDERSDUP; else if (tableName.equalsIgnoreCase("trade.companies")) whichTable = TRADE_COMPANIES; else if (tableName.equalsIgnoreCase("trade.portfoliov1")) whichTable = TRADE_PORTFOLIOV1; return whichTable; } }
java
22
0.734307
70
34.379167
240
starcoderdata
module.exports = function blacklist (src) { var copy = {} var filter = arguments[1] if (typeof filter === 'string') { filter = {} for (var i = 1; i < arguments.length; i++) { filter[arguments[i]] = true } } for (var key in src) { // blacklist? if (filter[key]) continue copy[key] = src[key] } return copy }
javascript
13
0.579345
48
17.904762
21
starcoderdata
<?php namespace SNDLL\PlatformBundle\Entity; use Doctrine\ORM\EntityRepository; class ModeReglementRepository extends EntityRepository { }
php
6
0.823864
54
16.6
10
starcoderdata
#include #include "LineString.h" // Construct from lvalue string LineString::LineString(const std::string& raw_string) : m_line_string(raw_string) { removeTrailingNewlines(); checkForNewlines(); } // Construct from rvalue string LineString::LineString(std::string&& raw_string) : m_line_string(std::move(raw_string)) { removeTrailingNewlines(); checkForNewlines(); } // Construct from c-style string LineString::LineString(const char raw_string[]) : LineString(static_cast { } // Remove trailing newlines void LineString::removeTrailingNewlines() { // Class invariant: m_line_string has no trailing newlines while (m_line_string.back() == '\n') m_line_string.pop_back(); } // Check for newlines void LineString::checkForNewlines() const { // Class invariant: m_line_string has no newlines for (const char& c : m_line_string) if (c == '\n') throw std::runtime_error("LineString cannot contain newlines!"); } // Return string const std::string& LineString::str() const { return m_line_string; } // Return size size_t LineString::size() const { return m_line_string.size(); }
c++
10
0.680567
76
21.203704
54
starcoderdata
/** @format */ export const idSchema = { type: [ 'integer', 'null' ], minimum: 0, }; export const currencyCodeSchema = { type: [ 'string', 'null' ], }; export const capabilitiesSchema = { type: 'object', additionalProperties: false, patternProperties: { '^\\d+$': { type: 'object', properties: { edit_pages: { type: 'boolean' }, edit_posts: { type: 'boolean' }, edit_others_posts: { type: 'boolean' }, edit_others_pages: { type: 'boolean' }, delete_posts: { type: 'boolean' }, delete_others_posts: { type: 'boolean' }, edit_theme_options: { type: 'boolean' }, edit_users: { type: 'boolean' }, list_users: { type: 'boolean' }, manage_categories: { type: 'boolean' }, manage_options: { type: 'boolean' }, promote_users: { type: 'boolean' }, publish_posts: { type: 'boolean' }, upload_files: { type: 'boolean' }, delete_users: { type: 'boolean' }, remove_users: { type: 'boolean' }, view_stats: { type: 'boolean' }, test: { type: 'string' } }, }, }, }; export const flagsSchema = { type: 'array', };
javascript
15
0.576395
45
24.418605
43
starcoderdata
import os # Verify Unity project current_dir = os.getcwd() def is_android_project(): return os.path.exists(os.path.join(current_dir, "gradlew")) def is_unity_project(): return os.path.exists(current_dir + "/Assets") and os.path.exists(current_dir + "/ProjectSettings") def is_latex_project(): files = os.listdir(current_dir) latex_count = 0 for name in files: if name.endswith(".tex") or name.endswith(".bib"): latex_count += 1 return latex_count >= 1 if __name__ == "__main__": if is_unity_project(): print("unity") elif is_latex_project(): print("latex") elif is_android_project(): print("android") else: print("undefined")
python
10
0.604938
103
20.441176
34
starcoderdata
<?php namespace Playbloom\Bundle\GuzzleBundle\Subscriber; use GuzzleHttp\Event\CompleteEvent; use GuzzleHttp\Event\ErrorEvent; use GuzzleHttp\Event\RequestEvents; use GuzzleHttp\Event\SubscriberInterface; use GuzzleHttp\Transaction; class TransactionRecorder implements SubscriberInterface { /** @var Transaction[] */ private $transactions = array(); /** @var int The maximum number of requests to maintain in the history */ private $limit; public function __construct($limit = 10) { $this->limit = $limit; } public function getEvents() { return [ 'complete' => ['onComplete', RequestEvents::LATE], 'error' => ['onError', RequestEvents::LATE], ]; } public function onComplete(CompleteEvent $event) { $this->add($event->getTransaction()); } public function onError(ErrorEvent $event) { $lightTx = clone $event->getTransaction(); unset($lightTx->exception); $this->add($lightTx); } private function add(Transaction $transaction) { $transaction->stackTrace = debug_backtrace(); $this->transactions[] = $transaction; if (count($this->transactions) > $this->limit) { array_shift($this->transactions); } } /** * @return Transaction[] */ public function getTransactions() { return array_values($this->transactions); // be zero based in case we array_shift'ed } }
php
13
0.621424
92
24.05
60
starcoderdata
""" Provides common functions for the CVE-Builder script. The script provides functionality for both TAXII inboxing aswell as using NCSC's custom adapter inbox. """ import json import requests from cabby import create_client def _construct_headers(): headers = { 'Content-Type': 'application/xml', 'Accept': 'application/json' } return headers def _certuk_inbox(content, endpoint_url): """Inbox the package to the certuk adapter.""" data = content headers = _construct_headers() response = requests.post(endpoint_url, data=data, headers=headers) print(json.dumps(response.json(), indent=4)) return def _taxii_inbox(content, config): client = create_client(config['host'], use_https=config[ 'ssl'], discovery_path=config['discovery_path']) content = content binding = config['binding'] client.set_auth(username=config['username'], password=config['password']) client.push(content, binding, uri=config['inbox_path'])
python
10
0.681644
77
26.526316
38
starcoderdata
using fo = Dicom; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DICOMcloud.Wado { public class DefaultDicomQueryElements { static fo.DicomDataset _studyDs = new fo.DicomDataset ( ) ; static fo.DicomDataset _seriesDs = new fo.DicomDataset ( ) ; static fo.DicomDataset _instanceDs = new fo.DicomDataset ( ) ; public virtual fo.DicomDataset GetStudyQuery ( ) { return GetDefaultStudyQuery ( ) ; } public virtual fo.DicomDataset GetSeriesQuery ( ) { return GetDefaultSeriesQuery ( ) ; } public virtual fo.DicomDataset GetInstanceQuery ( ) { return GetDefaultInstanceQuery ( ) ; } public static fo.DicomDataset GetDefaultStudyQuery ( ) { fo.DicomDataset ds = new fo.DicomDataset ( ) ; _studyDs.CopyTo ( ds ) ; return ds ; } public static fo.DicomDataset GetDefaultSeriesQuery ( ) { fo.DicomDataset ds = new fo.DicomDataset ( ) ; _seriesDs.CopyTo ( ds ) ; return ds ; } public static fo.DicomDataset GetDefaultInstanceQuery ( ) { fo.DicomDataset ds = new fo.DicomDataset ( ) ; _instanceDs.CopyTo ( ds ) ; return ds ; } static DefaultDicomQueryElements ( ) { FillStudyLevel ( _studyDs ) ; FillSeriesLevel ( _seriesDs ) ; FillInstsanceLevel ( _instanceDs ) ; } private static void FillStudyLevel(fo.DicomDataset studyDs) { studyDs.Add ; studyDs.Add ; studyDs.Add ; studyDs.Add ; studyDs.Add ; studyDs.Add ; studyDs.Add ; studyDs.Add ; studyDs.Add ; studyDs.Add ; studyDs.Add ; studyDs.Add ; studyDs.Add ; studyDs.Add ; studyDs.Add ; studyDs.Add ; studyDs.Add ; studyDs.Add ; } private static void FillSeriesLevel(fo.DicomDataset seriesDs) { seriesDs.Add ; seriesDs.Add ; seriesDs.Add ; seriesDs.Add ; seriesDs.Add ; seriesDs.Add ; seriesDs.Add ; seriesDs.Add ; seriesDs.Add ; seriesDs.Add ; //seriesDs.Add ; //Not supported yet } private static void FillInstsanceLevel(fo.DicomDataset instanceDs) { instanceDs.Add ; instanceDs.Add ; instanceDs.Add ; instanceDs.Add ; instanceDs.Add null); instanceDs.Add null); instanceDs.Add null); instanceDs.Add null); } } }
c#
13
0.619492
100
37.391667
120
starcoderdata
# encoding: utf-8 from __future__ import division, print_function, unicode_literals ########################################################################################################### # # # Reporter Plugin # # Read the docs: # https://github.com/schriftgestalt/GlyphsSDK/tree/master/Python%20Templates/Reporter # # ########################################################################################################### import objc from GlyphsApp import * from GlyphsApp.plugins import * from AppKit import NSBezierPath, NSPoint, NSColor, NSRect, NSSize class RekhaViewer(ReporterPlugin): @objc.python_method def settings(self): self.menuName = 'Rekha' @objc.python_method def rekhaBezierForMasterIDWithCapInFont(self, rekha, masterID, leftCap=None, rightCap=None, font=None): glyph = GSGlyph() if font: glyph.parent = font elif Glyphs.font: glyph.parent = Glyphs.font else: return None layer = glyph.layers[masterID] if layer is None: return None origin = rekha.origin width = rekha.size.width height = rekha.size.height # create rectangle path: rectangle = GSPath() nodePositions = ( NSPoint( origin.x, origin.y ), NSPoint( origin.x+width, origin.y ), NSPoint( origin.x+width, origin.y+height ), NSPoint( origin.x, origin.y+height ), ) for thisPosition in nodePositions: newNode = GSNode() newNode.position = thisPosition newNode.type = LINE rectangle.nodes.append(newNode) rectangle.closed = True # correct path direction: if rectangle.direction != -1: rectangle.reverse() # insert rectangle into layer: try: layer.shapes.append(rectangle) except: layer.paths.append(rectangle) # add caps if present in font: if rightCap or leftCap: caps = (None, rightCap, leftCap) for i in (-1,1): if caps[i] != None and caps[i].startswith("_cap."): cap = GSHint() cap.type = CAP cap.name = caps[i] cap.originNode = rectangle.nodes[i] cap.setOptions_(3) # fit layer.addHint_(cap) layer.decomposeCorners() # return the NSBezierPath return layer.bezierPath @objc.python_method def drawRekha(self, layer): defaults = (700,100,20) # height, thickness, overshoot if layer: thisGlyph = layer.glyph() if thisGlyph and thisGlyph.script in ("gurmukhi","devanagari","bengali"): if thisGlyph.category == "Letter": RekhaInfo = layer.associatedFontMaster().customParameters["rekha"] if not RekhaInfo: RekhaInfo = layer.associatedFontMaster().customParameters["Rekha"] if not RekhaInfo: RekhaInfo = ",".join([str(x) for x in defaults]) RekhaValues = [float(piece) for piece in RekhaInfo.split(',')] try: RekhaHeight = RekhaValues[0] except: RekhaHeight = defaults[0] try: RekhaThickness = RekhaValues[1] except: RekhaThickness = defaults[1] try: RekhaOvershoot = RekhaValues[2] except: RekhaOvershoot = defaults[2] xOrigin = -RekhaOvershoot # add caps if present in font: leftCap, rightCap = None, None font = layer.font() if font: generalCap = "_cap.rekha" if font.glyphForName_(generalCap): leftCap, rightCap = generalCap, generalCap if font.glyphForName_(generalCap+"Left"): leftCap = generalCap+"Left" if font.glyphForName_(generalCap+"Right"): rightCap = generalCap+"Right" if layer.anchorForName_("rekha_stop"): stopPosition = layer.anchors["rekha_stop"].position.x LeftRekha = NSRect() LeftRekha.origin = NSPoint(xOrigin, RekhaHeight) LeftRekha.size = NSSize(stopPosition-xOrigin, RekhaThickness) LeftRekhaBezierPath = self.rekhaBezierForMasterIDWithCapInFont(LeftRekha, layer.associatedMasterId, leftCap, rightCap, font) LeftRekhaBezierPath.fill() if layer.anchorForName_("rekha"): xOrigin = layer.anchors["rekha"].position.x Rekha = NSRect() Rekha.origin = NSPoint(xOrigin, RekhaHeight) Rekha.size = NSSize(layer.width+RekhaOvershoot-xOrigin, RekhaThickness) RekhaBezierPath = self.rekhaBezierForMasterIDWithCapInFont(Rekha, layer.associatedMasterId, leftCap, rightCap) # only draw if not None: if RekhaBezierPath: RekhaBezierPath.fill() @objc.python_method def background(self, layer): NSColor.placeholderTextColor().set() self.drawRekha(layer) def needsExtraMainOutlineDrawingForInactiveLayer_(self, Layer): return True @objc.python_method def inactiveLayer(self, layer): # backwards compatibilty # draw rekha: NSColor.textColor().set() self.drawRekha(layer) @objc.python_method def inactiveLayerBackground(self, layer): # draw rekha: NSColor.textColor().set() self.drawRekha(layer) @objc.python_method def preview(self, layer): # draw rekha: NSColor.textColor().set() self.drawRekha(layer) @objc.python_method def __file__(self): """Please leave this method unchanged""" return __file__
python
21
0.653556
130
27.440678
177
starcoderdata
func filterAllowedNamespaces(userClientset combinedClientsetInterface, namespaces []corev1.Namespace) ([]corev1.Namespace, error) { allowedNamespaces := []corev1.Namespace{} var wg sync.WaitGroup workers := int(math.Min(float64(len(namespaces)), float64(userClientset.MaxWorkers()))) checkNSJobs := make(chan checkNSJob, workers) nsCheckRes := make(chan checkNSResult, workers) // Process maxReq ns at a time for i := 0; i < workers; i++ { wg.Add(1) go func() { nsCheckerWorker(userClientset, checkNSJobs, nsCheckRes) wg.Done() }() } go func() { wg.Wait() close(nsCheckRes) }() go func() { for _, ns := range namespaces { checkNSJobs <- checkNSJob{ns} } close(checkNSJobs) }() // Start receiving results for res := range nsCheckRes { if res.Error == nil { if res.allowed { allowedNamespaces = append(allowedNamespaces, res.ns) } } else { log.Errorf("failed to check namespace permissions. Got %v", res.Error) } } return allowedNamespaces, nil }
go
14
0.6875
131
24.225
40
inline
from shamir_bip39_2039 import mnemonic from shamir_bip39_2039 import rng from shamir_bip39_2039 import english2039 from shamir_bip39_2039 import checksum def test_generate_partial_mnemonic(): r = rng.LCG() for length in mnemonic.allowed_mnemonic_lengths: for _ in range(100): partial_mnemonic = mnemonic.generate_partial_mnemonic( length - 1, rng=r) assert len(partial_mnemonic) == length - 1 for word in partial_mnemonic: assert word in english2039.word_dict.values() def test_generate_mnemonic(): r = rng.LCG() for length in mnemonic.allowed_mnemonic_lengths: for _ in range(100): test_mnemonic = mnemonic.generate_mnemonic(length, rng=r) assert len(test_mnemonic) == length for word in test_mnemonic: assert word in english2039.word_dict.values() assert checksum.check_mnemonic_checksum(test_mnemonic)
python
14
0.648205
69
33.821429
28
starcoderdata
<?php // https://whmcs.community/topic/296515-hook-to-show-recent-imported-ticket-failures-on-support-tickets-page/ // version 1.4 use Illuminate\Database\Capsule\Manager as Capsule; add_hook('AdminSupportTicketPagePreTickets', 1, function($vars) { $output = "<div id='recently-blocked'> Blocked Messages class='far fa-eye'> <a href='systemmailimportlog.php' target='_blank'>SEE ALL <table id='sortabletbl1' class='datatable' style='width:100%'> (click to view) foreach (Capsule::table('tblticketmaillog')->where('status', 'not like', '%successful%')->where('email', 'not like', 'mailer-daemon%')->orderBy('id', 'desc')->limit(10)->get() as $msg){ /* Name */ if ($msg->name === $msg->email) $name = $msg->name; else $name = "{$msg->name} /* Date */ $today = new DateTime(); $msg_date = new DateTime($msg->date); $interval = $today->diff($msg_date); $date_interval = abs($interval->format('%R%a')); if ($date_interval == 0 && $interval->h < date('H')) { $date_interval = 'Today'; } else if ($date_interval == 0 && $interval->h >= date('H')){ $date_interval = 'Yesterday'; } else if ($date_interval == 1) $date_interval = 'Yesterday'; else $date_interval .= ' days ago'; $output .= " href='#' onclick=\"window.open('/" . $GLOBALS['customadminpath'] . "/systemmailimportlog.php?display=true&id={$msg->id}','','width=650,height=400,scrollbars=yes');return false\">{$msg->subject} } return "$output /> jQuery(document).ready(function($){ /* Move to bottom of page */ $('#recently-blocked').appendTo('#contentarea > div:first-child'); }); });
php
19
0.615185
279
39.0625
48
starcoderdata
package com.github.wugenshui.baseutil.baseutil.java.util; import org.junit.Test; import org.springframework.boot.test.context.SpringBootTest; import java.text.SimpleDateFormat; import java.util.*; @SpringBootTest public class HashMapTest { @Test public void apiTest() { Map<Integer, String> map = new HashMap<>(); map.put(3, "张三"); map.put(4, "李四"); map.put(4, "李四"); for (Map.Entry<Integer, String> entry : map.entrySet()) { System.out.println(entry.getKey() + " -> " + entry.getValue()); } // HashMap具体实现中的工具方法 System.out.println(tableSizeFor(3)); System.out.println(tableSizeFor(5)); } public class Order { String date; private Order(String dateStr) { this.date = dateStr; } String getTransactionDay() { return date; } @Override public String toString() { return "Order{" + "date='" + date + '\'' + '}'; } } public class Type { private int type; public int getType() { return type; } public void setType(int type) { this.type = type; } public String getTypeString() { switch (type) { case 0: return "ZERO"; case 1: return "ONE"; default: return "OTHER"; } } } @Test public void filter() { // Type type = new Type(); // type.setType(0); // System.out.println("type.getTypeString() = " + type.getTypeString()); ArrayList orders = new ArrayList<>(); orders.add(new Order("2021-10-26")); orders.add(new Order("2021-10-25")); SimpleDateFormat formatter = new SimpleDateFormat("YYYY-MM-dd"); String currentDay = formatter.format(new Date()); Iterator iterator = orders.iterator(); while (iterator.hasNext()) { Order order = iterator.next(); if (!currentDay.equals(order.getTransactionDay())) { iterator.remove(); } } System.out.println("orders = " + Arrays.toString(orders.toArray())); } // 返回大于等于initialCapacity的最小的二次幂数值。 // >>> 操作符表示无符号右移,高位取0。 // | 按位或运算 public int tableSizeFor(int cap) { int n = cap - 1; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; return (n < 0) ? 1 : (n >= 100) ? 100 : n + 1; } @Test public void forTest() { Map<Integer, String> map = new HashMap<>(); map.put(3, "张三"); map.put(4, "李四"); map.put(5, "王五"); // 推荐使用,支持修改,但不支持添加和删除 System.out.println("for (Map.Entry<Integer, String> entry : map.entrySet())"); for (Map.Entry<Integer, String> entry : map.entrySet()) { System.out.println(entry.getKey() + " -> " + entry.getValue()); } System.out.println("for (Integer i : map.keySet())"); for (Integer i : map.keySet()) { System.out.println(i + " -> " + map.get(i)); } System.out.println("map.forEach((key, value))"); map.forEach((key, value) -> { System.out.println(key + " -> " + value); }); System.out.println("for (String value : map.values())"); for (String value : map.values()) { System.out.println(value); } } }
java
14
0.505825
94
27.175573
131
starcoderdata
def initialize_logging(config): if 'logging-file-config' in config: if 'logging' in config: raise RuntimeError("Config options 'logging-file-config' and 'logging' are mutually exclusive.") _initialize_logging_file_config(config) else: log_config = config.get('logging', {}) if 'version' in log_config: # logging module mandates version to be an int log_config['version'] = int(log_config['version']) _initialize_logging_new_style(config) else: _initialize_logging_old_style(config)
python
14
0.62309
108
44.384615
13
inline
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Connection con = (Connection) req.getServletContext().getAttribute("connect"); req.setCharacterEncoding("utf-8"); Map<String, String[]> param = req.getParameterMap(); boolean success = true; //check game exist success = __checkGameExist(param.get("id")[0], con); if (!success) { req.setAttribute("success", false); req.setAttribute("message", "添加CDK失败,游戏不存在"); req.getParameterMap().clear(); req.getRequestDispatcher("Manager.jsp").forward(req, resp); } //read lines success = __addKeys(param.get("id")[0], param.get("cdk_list")[0], con); if (!success) { req.setAttribute("success", false); req.setAttribute("message", "添加CDK失败,数据库错误"); } else { req.setAttribute("success", true); req.setAttribute("message", "添加CDK成功"); } req.getRequestDispatcher("Manager.jsp").forward(req, resp); }
java
11
0.637058
82
38.346154
26
inline
<?php declare(strict_types=1); namespace Symfony\Component\Messenger\Bridge\Kafka\Transport; use Symfony\Component\Messenger\Envelope; use Symfony\Component\Messenger\Exception\LogicException; use Symfony\Component\Messenger\Exception\MessageDecodingFailedException; use Symfony\Component\Messenger\Exception\TransportException; use Symfony\Component\Messenger\Transport\Receiver\ReceiverInterface; use Symfony\Component\Messenger\Transport\Serialization\SerializerInterface; class KafkaReceiver implements ReceiverInterface { public function __construct( private Connection $connection, private SerializerInterface $serializer ) { } public function get(): iterable { yield from $this->getEnvelope(); } private function getEnvelope(): iterable { try { $message = $this->connection->get(); } catch (\Exception $exception) { throw new TransportException($exception->getMessage(), 0, $exception); } if (null === $message) { return; } try { $envelope = $this->serializer->decode([ 'body' => $message->payload, 'headers' => $message->headers, ]); } catch (MessageDecodingFailedException $exception) { throw $exception; } yield $envelope->with(new KafkaReceivedStamp($message)); } public function ack(Envelope $envelope): void { $stamp = $this->findStamp($envelope); try { $this->connection->ack($stamp->getMessage()); } catch (\Exception $exception) { throw new TransportException($exception->getMessage(), 0, $exception); } } private function findStamp(Envelope $envelope): KafkaReceivedStamp { /** @var KafkaReceivedStamp|null $stamp */ if (null === $stamp = $envelope->last(KafkaReceivedStamp::class)) { throw new LogicException('No "KafkaReceivedStamp" stamp found on the Envelope.'); } return $stamp; } public function reject(Envelope $envelope): void { } }
php
16
0.634247
93
27.441558
77
starcoderdata
##!/usr/bin/python #-*- coding: utf-8 -*- #Developer by Bafomet import subprocess import os import sys import readline #set color WHSL = '\033[1;32m' ENDL = '\033[0m' REDL = '\033[0;31m' GNSL = '\033[1;34m' page_1 = '''{1} {0}[ {1}1{0} ] {2}Запуск. {0}[ {1}0{0} ] {2} Установить зависимости. '''.format(GNSL, REDL, WHSL) def main(): print(page_1) print("") option = input(REDL + " └──>" + ENDL +" Введите 1 для запуска сервера : " +ENDL + " ") while(1): if option == '1': os.system("cd module/gui;python3 geoLRun.py") exit() option = input(ENDL + ""+GNSL+"["+REDL + " menu " + GNSL + "]"+ENDL + " :") elif option == '0': print("") print(("{1} [ {0}+{1} ]{2} Происходит установка зависимостей...{3}").format(REDL, GNSL, WHSL, ENDL)) print("") os.system("sudo pip3 install wxPython") os.system("cd module/gui;python3 geoLRun.py") exit() break else: os.system("python3 startadb.py") try: main() except KeyboardInterrupt: sys.exit(1) except KeyboardInterrupt: print ("Ctrl+C pressed...")
python
21
0.488627
113
26.717391
46
starcoderdata
// SPDX-License-Identifier: Apache-2.0 // Licensed to the Ed-Fi Alliance under one or more agreements. // The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. // See the LICENSE and NOTICES files in the project root for more information. using System; using System.Globalization; using System.Net.Http; using System.Text; using EdFi.Ods.Common.Extensions; using EdFi.Ods.WebService.Tests.Owin; namespace EdFi.Ods.WebService.Tests._Helpers { internal class ProgramHelper { internal static HttpResponseMessage CreateProgram(HttpClient client, int leaId, string name = null) { name = name ?? DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture); var postBody = new StringContent(ResourceHelper.CreateProgram(leaId, name), Encoding.UTF8, "application/json"); var createResponse = client.PostAsync(OwinUriHelper.BuildOdsUri("programs"), postBody).GetResultSafely(); return createResponse; } } }
c#
20
0.727359
123
35.172414
29
starcoderdata
import urllib.request, urllib.parse, urllib.error import ssl import gitsecrets ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE def urlopen(url): secrets = gitsecrets.secrets() parms = urllib.parse.urlencode(secrets) if url.find('?') > 0 : url = url + '&' else: url = url + '?' url = url + parms # print('Retrieving', url) req = urllib.request.Request( url, data=None, headers={'User-Agent': 'giturl.py from www.py4e.com/code3' } ) connection = urllib.request.urlopen(req, context=ctx) str_json = connection.read().decode() headers = dict(connection.getheaders()) return (str_json, headers)
python
11
0.624187
66
22.30303
33
starcoderdata
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.tools.common.toolspec.parser; import java.util.logging.Level; import java.util.logging.Logger; import org.w3c.dom.Element; import org.apache.cxf.common.logging.LogUtils; import org.apache.cxf.tools.common.toolspec.ToolSpec; public class Argument implements TokenConsumer { private static final Logger LOG = LogUtils.getL7dLogger(Argument.class); protected ToolSpec toolspec; private final Element element; private int numMatches; public Argument(Element el) { this.element = el; } public boolean accept(TokenInputStream args, Element result, ErrorVisitor errors) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("Accepting token stream for argument: " + this); } int minOccurs; if ("unbounded".equals(element.getAttribute("minOccurs"))) { minOccurs = 0; } else { minOccurs = Integer.parseInt(element.getAttribute("minOccurs")); } if (minOccurs == 0) { addElement(args, result); return true; } if (minOccurs > args.available()) { return false; } if (args.peekPre().endsWith(",") && args.peekPre().startsWith("-")) { if (args.hasNext()) { args.readNext(); } else { return false; } } for (int i = 0; i < minOccurs; i++) { if (args.peek().startsWith("-")) { errors.add(new ErrorVisitor.UnexpectedOption(args.peek())); return false; } addElement(args, result); } return true; } private void addElement(TokenInputStream args, Element result) { Element argEl = result.getOwnerDocument().createElementNS("http://cxf.apache.org/Xutil/Command", "argument"); argEl.setAttribute("name", getName()); if (!args.isOutOfBound()) { argEl.appendChild(result.getOwnerDocument().createTextNode(args.read())); } result.appendChild(argEl); numMatches++; } private boolean isAtleastMinimum() { boolean result = true; int minOccurs = 0; if (!"".equals(element.getAttribute("minOccurs"))) { result = numMatches >= Integer.parseInt(element.getAttribute("minOccurs")); } else { result = numMatches >= minOccurs; } return result; } private boolean isNoGreaterThanMaximum() { boolean result = true; // int maxOccurs = 1; if ("unbounded".equals(element.getAttribute("maxOccurs")) || "".equals(element.getAttribute("maxOccurs"))) { return true; } if (!"".equals(element.getAttribute("maxOccurs"))) { result = numMatches <= Integer.parseInt(element.getAttribute("maxOccurs")); } return result; } public boolean isSatisfied(ErrorVisitor errors) { if (errors.getErrors().size() > 0) { return false; } if (!isAtleastMinimum()) { errors.add(new ErrorVisitor.MissingArgument(getName())); return false; } if (!isNoGreaterThanMaximum()) { errors.add(new ErrorVisitor.DuplicateArgument(getName())); return false; } return true; } public void setToolSpec(ToolSpec toolSpec) { this.toolspec = toolSpec; } public String getName() { return element.getAttribute("id"); } public String toString() { return getName(); } }
java
16
0.599195
104
30.935714
140
starcoderdata
using Moq; using System.Threading.Tasks; using TouhouLauncher.Models.Application; using TouhouLauncher.Models.Infrastructure.Persistence.FileSystem; using static TouhouLauncher.Test.CommonTestToolsAndData; using Xunit; using TouhouLauncher.Models.Common; namespace TouhouLauncher.Test.Models.Application { public class SettingsAndGamesManagerTest { private readonly Mock _fileSystemSettingsAndGamesServiceMock = new(null, null); private readonly Mock _officialGamesTemplateServiceMock = new(); private readonly SettingsAndGamesManager _settingsAndGamesManager; public SettingsAndGamesManagerTest() { _settingsAndGamesManager = new( _fileSystemSettingsAndGamesServiceMock.Object, _officialGamesTemplateServiceMock.Object ); } [Fact] public async void Saves_settings_and_games_and_returns_result() { _fileSystemSettingsAndGamesServiceMock .Setup(obj => obj.SaveAsync(It.IsAny .Returns(Task.FromResult var error = await _settingsAndGamesManager.SaveAsync(); Assert.Null(error); } [Fact] public async void Returns_error_when_no_settings_and_games_exist() { _fileSystemSettingsAndGamesServiceMock .Setup(obj => obj.LoadAsync()) .Returns(Task.FromResult<Either<SettingsAndGamesLoadError, SettingsAndGames>>(new SettingsAndGamesLoadError("Error"))); _officialGamesTemplateServiceMock .Setup(obj => obj.CreateOfficialGamesFromTemplate()) .Returns(testOfficialGames); var result = await _settingsAndGamesManager.LoadAsync(); Assert.NotNull(result); } [Fact] public async void Returns_null_and_stores_loaded_settings_and_games_when_settings_and_games_exist() { _fileSystemSettingsAndGamesServiceMock .Setup(obj => obj.LoadAsync()) .Returns(Task.FromResult<Either<SettingsAndGamesLoadError, SettingsAndGames>>(testSettingsAndGames)); var result = await _settingsAndGamesManager.LoadAsync(); Assert.Null(result); Assert.True(_settingsAndGamesManager.GeneralSettings.CloseOnGameLaunch); Assert.NotNull(_settingsAndGamesManager.EmulatorSettings.FolderLocation); Assert.NotEmpty(_settingsAndGamesManager.OfficialGames); Assert.NotEmpty(_settingsAndGamesManager.FanGames); } } }
c#
21
0.7921
123
33.855072
69
starcoderdata
package atcs import ( "atc/base" "encoding/base64" "encoding/json" "fmt" "html/template" "io/ioutil" "log" "os" "strings" ) // Atcs int 的包装 type Atcs map[string]interface{} var ( mobileKeywords = []string{"Android", "Phone", "iPod", "Adr", "Mobile"} weixinKeywords = []string{"micromessenger"} ) // IsWeixin 是否为微信浏览器 func (m Atcs) IsWeixin() bool { if userAgent, ok := m["UserAgent"].(string); ok { userAgent = strings.ToLower(userAgent) for _, item := range weixinKeywords { if strings.Contains(userAgent, item) { return true } } } return false } // IsMobile 是否为手机浏览器 func (m Atcs) IsMobile() bool { if userAgent, ok := m["UserAgent"].(string); ok { if !strings.Contains(userAgent, "Windows NT") && !strings.Contains(userAgent, "Macintosh") { for _, item := range mobileKeywords { if strings.Contains(userAgent, item) { return true } } } } return false } // Set 设置 func (m Atcs) Set(key string, value interface{}) interface{} { m[key] = value return nil } // Get 设置 func (m Atcs) Get(key string) interface{} { if value, ok := m[key]; ok { return value } return nil } // Add 加法 func (m Atcs) Add(key string, value int) interface{} { vv := m.Get(key) if vv == nil { m.Set(key, value) } else if v, ok := vv.(int); ok { m.Set(key, v+value) } return nil } // IsEnd 是否在结束的地方 func (m Atcs) IsEnd(index, width int) bool { if width == 0 { return false } return index != 0 && index%width == 0 } // Others 比如10,5 func (m Atcs) Others(arr []interface{}, width int) []int { len := len(arr) % width if len != 0 { len = width - len } return make([]int, len, len) } // ArrPair 成对的数组 type ArrPair struct { First []interface{} Second []interface{} } // Cut 比如10,5 func (m Atcs) Cut(arr []interface{}, width int) ArrPair { if len(arr) > width { return ArrPair{ First: arr[:width], Second: arr[width:], } } return ArrPair{ First: arr, Second: []interface{}{}, } } // Ter 三目运算 func (m Atcs) Ter(c bool, a, b interface{}) interface{} { if c { return a } return b } // At 取Item func (m Atcs) At(arr []interface{}, index int) interface{} { if len(arr) > index && index >= 0 { return arr[index] } return nil } // F2i float转int func (m Atcs) F2i(value float64) int { return int(value) } // Len 数组长度 func (m Atcs) Len(arr []interface{}) int { return len(arr) } // Arr 组成数组 func (m Atcs) Arr(value ...interface{}) []interface{} { return value } // SetTo 设置到map上 func (m Atcs) SetTo(o map[string]interface{}, key string, value interface{}) interface{} { o[key] = value return nil } // Map 创建 func (m Atcs) Map(values ...interface{}) map[string]interface{} { result := map[string]interface{}{} length := len(values) / 2 for i := 0; i < length; i++ { key, _ := values[i*2].(string) result[key] = values[i*2+1] } return result } // JSONToArr 从json获得数组 func (m Atcs) JSONToArr(str string) []interface{} { var result []interface{} err := json.Unmarshal([]byte(str), &result) if err != nil { log.Println(err) } return result } // JSONToMap 从json获得map func (m Atcs) JSONToMap(str string) map[string]interface{} { var result map[string]interface{} err := json.Unmarshal([]byte(str), &result) if err != nil { log.Println(err) } return result } // JSONBase64 JSONBase64 func (m Atcs) JSONBase64(o map[string]interface{}) string { oBytes, _ := json.Marshal(o) return base64.StdEncoding.EncodeToString(oBytes) } func readFileContent(path string) *string { f, err := os.Open(fmt.Sprintf("%s%s", base.Config.WebPath, path)) if err != nil { log.Println(err) return nil } defer f.Close() b, err := ioutil.ReadAll(f) if err != nil { log.Println(err) return nil } content := string(b) return &content } func readFileContentFromCache(path string) *string { base.RefCacheMutex.Lock() defer base.RefCacheMutex.Unlock() if cache, ok := base.RefCache[path]; ok { return cache } r := readFileContent(path) base.RefCache[path] = r return r } // Ref 引入模块 func (m Atcs) Ref(path string) template.HTML { var r *string if base.Config.IsDev { r = readFileContent(path) } else { r = readFileContentFromCache(path) } if r == nil { return template.HTML("") } return template.HTML(*r) }
go
13
0.607487
94
17.826667
225
starcoderdata
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Xunit; namespace Bet.Extensions.UnitTest.Hosting { public class HostUnitTests { [Fact] public void Should_Have_Register_Once_StartupFilters() { var host = new HostBuilder() .UseStartupFilters() .UseStartupFilters() .Build(); var services = host.Services.GetRequiredService as HostStartupService; Assert.NotNull(services); } } }
c#
19
0.632091
100
24.708333
24
starcoderdata
//Collision detection - Bouncing behavior var circles; var boxes; var MARGIN = 40; function preload() { } function setup() { createCanvas(800,400); circles = new Group(); for(var i=0; i<20; i++) { var circle = createSprite(random(0,width),random(0,height)); circle.addAnimation("normal", "assets/asterisk_circle0006.png", "assets/asterisk_circle0008.png"); circle.setCollider("circle", -2,2,55); circle.setSpeed(random(2,3), random(0, 360)); //scale affects the size of the collider circle.scale = random(0.5, 1); //mass determines the force exchange in case of bounce circle.mass = circle.scale; //restitution is the dispersion of energy at each bounce //if = 1 the circles will bounce forever //if < 1 the circles will slow down //if > 1 the circles will accelerate until they glitch //circle.restitution = 0.9; circles.add(circle); } boxes = new Group(); for(var i=0; i<4; i++) { var box = createSprite(random(0,width),random(0,height)); box.addAnimation("normal", "assets/box0001.png", "assets/box0003.png"); //setting immovable to true makes the sprite immune to bouncing and displacements //as if with infinite mass box.immovable = true; //rotation rotates the collider too but it will always be an axis oriented //bounding box, that is an ortogonal rectangle if(i%2==0) box.rotation = 90; boxes.add(box); } } function draw() { background(255,255,255); //circles bounce against each others and against boxes circles.bounce(circles); //boxes are "immovable" circles.bounce(boxes); //all sprites bounce at the screen edges for(var i=0; i<allSprites.length; i++) { var s = allSprites[i]; if(s.position.x<0) { s.position.x = 1; s.velocity.x = abs(s.velocity.x); } if(s.position.x>width) { s.position.x = width-1; s.velocity.x = -abs(s.velocity.x); } if(s.position.y<0) { s.position.y = 1; s.velocity.y = abs(s.velocity.y); } if(s.position.y>height) { s.position.y = height-1; s.velocity.y = -abs(s.velocity.y); } } drawSprites(); }
javascript
14
0.650258
101
22.966292
89
starcoderdata
import humps from 'humps'; export default class Helper { static camelize(fromNames, obj) { const toNames = fromNames.map(name => humps.camelize(name)); fromNames.forEach((name, index) => { obj[toNames[index]] = obj[name]; }); return obj; } static handleReverseSelection(from, to) { return (from.ch > to.ch) ? [to, from] : [from, to]; } static chunkString(str, length) { return str.match(new RegExp('[\\S\\s]{1,' + length + '}', 'g')); } static allIndexOf(str, toSearch, limit = 10) { const indices = []; for (let pos = str.indexOf(toSearch); (-1 !== pos) && (indices.length <= limit); pos = str.indexOf(toSearch, pos + 1)) { indices.push(pos); } return indices; } }
javascript
14
0.612984
124
26.62069
29
starcoderdata
#pragma once #include "Mod.hpp" class JudgementCustomCost : public Mod { public: static inline uintptr_t ret = 0; static inline bool cheaton = false; static inline float customCost = 3000.0f; JudgementCustomCost() = default; static naked void detour() { __asm { cmp byte ptr [JudgementCustomCost::cheaton], 0 je originalcode cheat: movss xmm0, [JudgementCustomCost::customCost] jmp qword ptr [JudgementCustomCost::ret] originalcode: movss xmm0, [rdi + 0x68] jmp qword ptr [JudgementCustomCost::ret] } } std::string_view get_name() const override { return "JudgementCustomCost"; } std::string get_checkbox_name() override { return m_check_box_name; }; std::string get_hotkey_name() override { return m_hot_key_name; }; std::optional on_initialize() override { init_check_box_info(); auto base = g_framework->get_module().as // note HMODULE m_is_enabled = &cheaton; m_on_page = Page_DanteSDT; m_full_name_string = "Custom Judgement Cost (+)"; m_author_string = "VPZadov"; m_description_string = "Set cost for SDT's \"Judgement\" move."; set_up_hotkey(); auto judgementCostAddr = m_patterns_cache->find_addr(base, "1A 00 00 F3 0F 10 47 68"); //DevilMayCry5.exe+1388CFA(-0x3); if (!judgementCostAddr.has_value()) { spdlog::error("[{}] failed to initialize", get_name()); return "Failed to initialize JudgementCustomCost.judgementCostAddr"; } if (!install_hook_absolute(judgementCostAddr.value() + 0x3, m_cost_hook, &detour, &ret, 0x5)) { spdlog::error("[{}] failed to initialize", get_name()); return "Failed to initialize JudgementCustomCost.judgementCost"; } return Mod::on_initialize(); }; // Override this things if you want to store values in the config file void on_config_load(const utility::Config& cfg) override { customCost = cfg.get } void on_config_save(utility::Config& cfg) override { cfg.set customCost); } // on_draw_ui() is called only when the gui shows up // you are in the imgui window here. void on_draw_ui() override { ImGui::TextWrapped("Judgement cost:"); UI::SliderFloat("##CustomCost", &customCost, 0, 10000.0f, "%.1f", 1.0F, ImGuiSliderFlags_AlwaysClamp); }; private: void init_check_box_info() override { m_check_box_name = m_prefix_check_box_name + std::string(get_name()); m_hot_key_name = m_prefix_hot_key_name + std::string(get_name()); }; std::unique_ptr m_cost_hook; };
c++
16
0.694231
122
28.224719
89
starcoderdata
/* -*- c++ -*- */ /* * Copyright 2015,2016 Free Software Foundation, Inc. * * SPDX-License-Identifier: GPL-3.0-or-later * */ #ifndef INCLUDED_DTV_DVBS2_MODULATOR_BC_IMPL_H #define INCLUDED_DTV_DVBS2_MODULATOR_BC_IMPL_H #include "../dvb/dvb_defines.h" #include <gnuradio/dtv/dvbs2_modulator_bc.h> namespace gr { namespace dtv { class dvbs2_modulator_bc_impl : public dvbs2_modulator_bc { private: int signal_constellation; int signal_interpolation; gr_complex m_bpsk[2][2]; gr_complex m_qpsk[4]; gr_complex m_8psk[8]; gr_complex m_16apsk[16]; gr_complex m_32apsk[32]; gr_complex m_64apsk[64]; gr_complex m_128apsk[128]; gr_complex m_256apsk[256]; public: dvbs2_modulator_bc_impl(dvb_framesize_t framesize, dvb_code_rate_t rate, dvb_constellation_t constellation, dvbs2_interpolation_t interpolation); ~dvbs2_modulator_bc_impl() override; void forecast(int noutput_items, gr_vector_int& ninput_items_required) override; int general_work(int noutput_items, gr_vector_int& ninput_items, gr_vector_const_void_star& input_items, gr_vector_void_star& output_items) override; }; } // namespace dtv } // namespace gr #endif /* INCLUDED_DVBS2_MODULATOR_BC_IMPL_H */
c
13
0.627365
84
25.941176
51
research_code
package com.adam.test; import java.util.Arrays; /** * @author adam * contact: * date: 2021/1/15 11:48 * version: 1.0.0 */ public class Q1491 { public static void main(String[] args) { } static class Solution{ public double average(int[] salary) { Arrays.sort(salary); double sum = 0; int n = salary.length; for(int i = 1; i < n - 1; i++){ sum += salary[i]; } return sum / (n - 2); } } }
java
12
0.463588
45
18.142857
28
starcoderdata
def on_draw(self): """ Renders the screen. """ arcade.start_render() # Ground layer self.ground_list.draw() self.path_list.draw() # Entity layer self.turret_list.draw() self.entity_list.draw() self.dmg_list.draw() # Player layer self.player_list.draw() # GUI layer if self.betweenRounds: arcade.draw_rectangle_filled(96, 485, 204, 54, (70, 92, 32)) arcade.draw_rectangle_filled(99, 485, 192, 48, arcade.csscolor.DARK_OLIVE_GREEN) elif not self.betweenRounds: arcade.draw_rectangle_filled(96, 485, 204, 54, (75, 0, 0)) arcade.draw_rectangle_filled(99, 485, 192, 48, arcade.csscolor.DARK_RED) if self.shownRoundNumber < 99: arcade.draw_text("Wave number: " + str(self.shownRoundNumber), 10, 512 - 44, arcade.csscolor.WHITE, 18, font_name='arial', bold=True) elif self.shownRoundNumber < 999: arcade.draw_text("Wave number: " + str(self.shownRoundNumber), 10, 512 - 44, arcade.csscolor.WHITE, 16, font_name='arial', bold=True)
python
13
0.568182
115
36.15625
32
inline
#ifndef SLIDER_STYLE_H #define SLIDER_STYLE_H #include class SliderStyle: public QProxyStyle { public: virtual int styleHint(StyleHint hint, const QStyleOption * option = 0, const QWidget * widget = 0, QStyleHintReturn * returnData = 0) const { if (hint == QStyle::SH_Slider_AbsoluteSetButtons){ return Qt::LeftButton; } else { return QProxyStyle::styleHint(hint, option, widget, returnData); } } }; #endif // SLIDER_STYLE_H
c
11
0.679279
145
29.833333
18
starcoderdata
func (m Message) Store(tangle storage.Store) error { if !hash.ValidInt8(m.TxHash()) { return errInvalidTxHash } txHash := hash.ToBytes(m.TxHash()) // TODO(era): make exists and write check atomic exists, err := storage.Exists(tangle, txHash, storage.TransactionBucket) if err != nil { return err } if exists { return errTxAlreadyExists } return storage.Write(tangle, txHash, m.TxBytes, storage.TransactionBucket) }
go
9
0.721198
75
21.894737
19
inline
module.exports = async function (message) { try { if (message.pinnable && !message.pinned) { // Create collector message.channel.createMessageCollector(pinFunction, {maxMatches: 3, time: 4000}); // Await await new Promise(function(resolve, reject) { setTimeout(function () { resolve(); }, 400); }); await message.pin(); return true; }; } catch (err) { // Suppress error return false; } finally { return false; }; }; async function pinFunction (m) { // Remove the system pin message if (m.type === 'PINS_ADD' && m.system && !m.deleted) { // Delete the message try { await m.delete(); return true; } catch (err) { return false; }; } else { return false; }; }
javascript
18
0.560364
87
13.633333
60
starcoderdata
import java.util.*; import java.io.File; import java.io.FileNotFoundException; public class TextStatistics implements TextStatisticsInterface { private static final String DELIMITERS = "[\\W\\d_]+"; private String path; private int chars; private int words; private int lines; private int minWordLength; private int maxWordLength; private double avgWordLength; private int wordLengthFrequency[]; private int letterFrequency[]; private boolean error; public TextStatistics (File file) { path = file.getPath(); try { Scanner reader = new Scanner(file); wordLengthFrequency = new int[24]; letterFrequency = new int[26]; int totalWordLength = 0; minWordLength = 23; maxWordLength = 1; while (reader.hasNextLine()) { String line = reader.nextLine(); chars += line.length() + 1; lines++; for (String word : line.split(DELIMITERS)){ if (word.length() > 0){ totalWordLength += word.length(); words += 1; wordLengthFrequency[word.length()]++; for (char ch: word.toLowerCase().toCharArray()) { if ('a' <= ch && ch <= 'z'){ letterFrequency[ch - 'a']++; } } if (word.length() < minWordLength) minWordLength = word.length(); if (word.length() > maxWordLength) maxWordLength = word.length(); } } } avgWordLength = (double) totalWordLength / words; reader.close(); error = false; } catch (FileNotFoundException e) { error = true; } } public int getCharCount() {return chars;} public int getWordCount() {return words;} public int getLineCount() {return lines;} public int[] getLetterCount() {return letterFrequency;} public int[] getWordLengthCount() {return wordLengthFrequency;} public double getAverageWordLength() {return avgWordLength;} public String toString(){ if (error) return "Invalid file path: " + path; String wordLengthFrequencyStr = ""; String letterFrequencyStr = ""; String temp; //for (int x : wordLengthFrequency) wordLengthFrequencyStr += x + " "; //for (int x : letterFrequency) letterFrequencyStr += x + " "; for (int i = 0; i < 13; i++) { temp = " " + (char)('a' + i) + " = " + letterFrequency[i]; while (temp.length() < 16) temp += " "; letterFrequencyStr += temp; temp = " " + (char)('n' + i) + " = " + letterFrequency[i + 13]; while (temp.length() < 16) temp += " "; letterFrequencyStr += temp + "\n"; } for (int i = minWordLength; i <= maxWordLength; i++) { temp = i + ""; while (temp.length() < 7) temp = " " + temp; wordLengthFrequencyStr += temp; temp = wordLengthFrequency[i] + ""; while (temp.length() < 11) temp = " " + temp; wordLengthFrequencyStr += temp + "\n"; } return "Statistics for " + path + "\n" + "==========================================================\n" + lines + " lines\n" + words + " words\n" + chars + " characters\n" + "------------------------------\n" + letterFrequencyStr + "------------------------------\n" + " length frequency\n" + " ------ ---------\n" + wordLengthFrequencyStr + "\n" + "Average word length = " + String.format("%.2f", avgWordLength) + "\n" + "==========================================================\n"; } }
java
27
0.580932
75
25.096
125
starcoderdata
// @flow const express = require('express') const requireEnv = require('@jcoreio/require-env') const webpackConfig = require('../webpack/webpack.config.dev') const BACKEND_PORT = requireEnv('BACKEND_PORT') const app = express() const compiler = require('webpack')(webpackConfig) app.use(require('webpack-dev-middleware')(compiler, webpackConfig.devServer || {})) app.use(require('webpack-hot-middleware')(compiler)) const proxy = require('http-proxy').createProxyServer() // istanbul ignore next proxy.on('error', (err: Error): any => console.error(err.stack)) const target = `http://localhost:${BACKEND_PORT}` app.all('*', (req: Object, res: Object): any => proxy.web(req, res, { target })) const server = app.listen(webpackConfig.devServer.port) if (!server) throw new Error("expected server to be defined") server.on('upgrade', (req: Object, socket: any, head: any): any => { proxy.ws(req, socket, head, { target }) }) console.log(`Dev server is listening on http://0.0.0.0:${webpackConfig.devServer.port}`)
javascript
10
0.708293
88
31.03125
32
starcoderdata
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Reflection; using System.Globalization; using ClangNet.Native; using System.Diagnostics; namespace ClangNet { /// /// IntPtr Extensions /// public static class IntPtrEx { /// /// Convert to Managed Clang Object /// /// <typeparam name="T">Clang Object /// <param name="ptr">Native Clang Object Pointer /// Clang Object internal static T ToManaged IntPtr ptr) where T : ClangObject { if (ptr == IntPtr.Zero) { return null; } else { var type = typeof(T); var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance; var instance = Activator.CreateInstance(type, flags, null, new object[] { ptr }, CultureInfo.InvariantCulture) as T; return instance; } } /// /// Convert to Byte Array /// /// <param name="ptr">Native Pointer /// <param name="size">Array Size /// Array public static byte[] ToByteArray(this IntPtr ptr, ulong size) { if (ptr == IntPtr.Zero) { return new byte[0]; } else { var contents_bytes = new byte[size]; if (size > int.MaxValue) { throw new InvalidOperationException($"Buffer Size is out of range : {size}"); } Marshal.Copy(ptr, contents_bytes, 0, (int)size); return contents_bytes; } } /// /// Convert to Native Struct /// /// <typeparam name="T">Native Struct Type /// <param name="ptr">Native Struct Pointer /// Struct public static T ToNativeStuct IntPtr ptr) where T : struct { if (ptr == IntPtr.Zero) { throw new ArgumentNullException($"Pointer is null"); } else { return (T)Marshal.PtrToStructure(ptr, typeof(T)); } } /// /// Convert to Native Struct /// /// <typeparam name="T">Native Struct Type /// <param name="ptr">Native Struct Pointer /// <param name="i">Array Index /// Struct public static T ToNativeStuct IntPtr ptr, int i) where T : struct { if (ptr == IntPtr.Zero) { throw new ArgumentNullException($"Pointer is null"); } else { var struct_size = Marshal.SizeOf(typeof(T)); return (T)Marshal.PtrToStructure(ptr + (struct_size * i), typeof(T)); } } /// /// Convert to Native Struct Enumerable /// /// <typeparam name="T">Native Struct Type /// <param name="ptr">Native Stucts Pointer /// <param name="count">Native Struct Count /// Struct Enumerable public static IEnumerable ToNativeStructs IntPtr ptr, int count) where T : struct { if (ptr == IntPtr.Zero) { return Enumerable.Empty } else { var struct_size = Marshal.SizeOf(typeof(T)); return Enumerable.Range(0, count).Select(i => ptr + (struct_size * i)).Select(address => address.ToNativeStuct } } /// /// Convert to Managed Clang Object Enumerable /// /// <typeparam name="TNative">Native Clang Struct Type /// <typeparam name="TManaged">Managed Clang Object Type /// <param name="ptr">Native Stucts Pointer /// <param name="count">Native Struct Count /// Clang Object Enumerable public static IEnumerable ToManagedObjects<TNative, TManaged>(this IntPtr ptr, int count) where TNative : struct where TManaged : ClangObject { if (ptr == IntPtr.Zero) { return Enumerable.Empty } else { var struct_size = Marshal.SizeOf(typeof(TNative)); return Enumerable.Range(0, count).Select(i => ptr + (struct_size * i)).Select(address => address.ToManaged } } /// /// Convert To Managed String /// /// <param name="char_ptr">Native Char Pointer /// <param name="encoding">Encoding /// String public static string ToManagedString(this IntPtr char_ptr, string encoding = "utf-8") { if (char_ptr == IntPtr.Zero) { return null; } else { var x = 0; var bytes = new List unsafe { var byte_ptr = (byte*)char_ptr; while (byte_ptr[x] != 0) { x++; bytes.Add(byte_ptr[x]); } var byte_array = bytes.ToArray(); var enc = EncodingAnalyser.Analyse(byte_array) ?? Encoding.GetEncoding(encoding); var len = enc.GetCharCount(byte_ptr, x); if (len == 0) { return string.Empty; } else { var str_buf = stackalloc char[len]; var str_len = enc.GetChars(byte_ptr, x, str_buf, len); var str = new string(str_buf, 0, str_len); return str; } } } } /// /// Convert To Managed String /// /// <param name="char_ptr">Native Char Pointer /// <param name="size">Native Byte Size /// <param name="encoding">Encoding /// String public static string ToManagedString(this IntPtr char_ptr, int size, string encoding = "utf-8") { if (char_ptr == IntPtr.Zero) { return null; } else { var bytes = new List unsafe { var byte_ptr = (byte*)char_ptr; for(var x = 0; x < size; x++) { bytes.Add(byte_ptr[x]); } var byte_array = bytes.ToArray(); var enc = EncodingAnalyser.Analyse(byte_array) ?? Encoding.GetEncoding(encoding); var len = enc.GetCharCount(byte_ptr, size); if (len == 0) { return string.Empty; } else { var str_buf = stackalloc char[len]; var str_len = enc.GetChars(byte_ptr, size, str_buf, len); var str = new string(str_buf, 0, str_len); return str; } } } } /// /// Convert To Managed String Set Array /// /// <param name="string_set_ptr">Native String Set Pointer /// String Set Array public static string[] ToManagedStringSet(this IntPtr string_set_ptr) { if (string_set_ptr == IntPtr.Zero) { return new string[0]; } else { var native_string_set = string_set_ptr.ToNativeStuct var string_set = native_string_set.ToManaged(); LibClang.clang_disposeStringSet(string_set_ptr); return string_set; } } } }
c#
20
0.475459
136
31.333333
276
starcoderdata
<?php namespace app\models\Form; use Yii; /** */ class StockItemGraph extends \cs\base\BaseForm { const TABLE = 'cap_stock'; public $dateMin; public $dateMax; public $isUseRed = true; public $isUseBlue = true; public $isUseKurs = true; public $y; function __construct($fields = []) { static::$fields = [ [ 'dateMin', 'От', 1, 'cs\Widget\DatePicker\Validator', 'widget' => ['cs\Widget\DatePicker\DatePicker', [ 'dateFormat' => 'php:d.m.Y', ] ] ], [ 'dateMax', 'До', 0, 'cs\Widget\DatePicker\Validator', 'widget' => ['cs\Widget\DatePicker\DatePicker', [ 'dateFormat' => 'php:d.m.Y', ] ] ], [ 'isUseRed', 'Использовать красный график', 0, 'cs\Widget\CheckBox2\Validator', 'widget' => ['cs\Widget\CheckBox2\CheckBox', ] ], [ 'isUseBlue', 'Использовать синий график', 0, 'cs\Widget\CheckBox2\Validator', 'widget' => ['cs\Widget\CheckBox2\CheckBox', ] ], [ 'isUseKurs', 'Использовать курс', 0, 'cs\Widget\CheckBox2\Validator', 'widget' => ['cs\Widget\CheckBox2\CheckBox', ] ], [ 'y', 'Какую шкалу использовать?', 0, 'integer', ], ]; parent::__construct($fields); } }
php
16
0.361068
63
23.961538
78
starcoderdata
<?php // DIC configuration $container = $app->getContainer(); // view renderer $container['renderer'] = function ($c) { $settings = $c->get('settings')['renderer']; return new Slim\Views\PhpRenderer($settings['template_path']); }; // Register component on container $container['view'] = function ($c) { $settings = $c->get('settings')['view']; $view = new \Slim\Views\Twig($settings['template_path'], [ 'debug' => $settings['debug'], 'cache' => $settings['cache_path'] ]); // Add extensions $view->addExtension(new \Slim\Views\TwigExtension( $c['router'], $c['request']->getUri() )); $view->addExtension(new Twig_Extension_Debug()); return $view; }; // Flash messages $container['flash'] = function ($c) { return new \Slim\Flash\Messages; }; // monolog $container['logger'] = function ($c) { $settings = $c->get('settings')['logger']; $logger = new Monolog\Logger($settings['name']); $logger->pushProcessor(new Monolog\Processor\UidProcessor()); $logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], Monolog\Logger::DEBUG)); return $logger; }; $container['facebook'] = function ($c) { $settings = $c->get('settings')['facebook']; $fb= new Facebook\Facebook([ 'app_id' => $settings['app_id'], 'app_secret' => $settings['app_secret'], 'default_graph_version' => $settings['default_graph_version'], ]); return $fb; }; // error handle $container['errorHandler'] = function ($c) { return function ($request, $response, $exception) use ($c) { $data = [ 'code' => $exception->getCode(), 'message' => $exception->getMessage(), 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'trace' => explode("\n", $exception->getTraceAsString()), ]; return $c->get('response')->withStatus(500) ->withHeader('Content-Type', 'application/json') ->write(json_encode($data)); }; }; // Generate Activation Code $container['activation'] = function ($c) { return new \Cartalyst\Sentinel\Activations\IlluminateActivationRepository; }; # ----------------------------------------------------------------------------- # Action factories Controllers # ----------------------------------------------------------------------------- $container['App\Controllers\AuthController'] = function ($c) { return new App\Controllers\AuthController( $c->get('view'), $c->get('logger'), $c->get('App\Repositories\HomeRepository') ); }; $container['App\Controllers\UserController'] = function ($c) { return new App\Controllers\UserController( $c->get('view'), $c->get('logger') ); }; $container['App\Controllers\ArtigianiController'] = function ($c) { return new App\Controllers\ArtigianiController( $c->get('logger') ); }; # ----------------------------------------------------------------------------- # Factories Models # ----------------------------------------------------------------------------- $container['Model\User'] = function ($c) { return new App\Models\User; }; # ----------------------------------------------------------------------------- # Factories Repositories # ----------------------------------------------------------------------------- $container['App\Repositories\HomeRepository'] = function ($c) { return new App\Repositories\HomeRepository( $c->get('Model\User') ); }; $container['App\Repositories\UserRepository'] = function ($c) { return new App\Repositories\UserRepository( $c->get('Model\User') ); }; # ----------------------------------------------------------------------------- # Factories Services # ----------------------------------------------------------------------------- $container['Mailer'] = function ($c) { return new App\Service\Mailer( $c->get('view') ); };
php
17
0.526868
102
28.606061
132
starcoderdata
import React from 'react' import {NavLink as ReactNavLink} from 'react-router-dom' const NavLink = props => ( <ReactNavLink className="nav-link" activeClassName="nav-link-active" {...props} /> ) export default NavLink
javascript
8
0.690678
56
18.666667
12
starcoderdata
package api // TaskStatus represents the stage of execution for a task. The associated enumeration is ordered, // where higher value statuses are closer to complete. It's possible for a task to transition from a // higher status to a lower one if rescheduled. For example, a "running" experiment can move to // "initializing" if the node it's running on is terminated. type TaskStatus string // TODO: Remove DEPRECATED values const ( // TaskStatusCreated means the task is accepted by Beaker. // DEPRECATED. // The task will automatically start when eligible. TaskStatusCreated TaskStatus = "created" // TaskStatusStarting means the task is attempting to start, but is not yet running. // DEPRECATED. TaskStatusStarting TaskStatus = "starting" // TaskStatusSuccessful means the task has completed successfully. // DEPRECATED. TaskStatusSuccessful TaskStatus = "successful" // TaskStatusCanceled means the task was aborted. // DEPRECATED. TaskStatusCanceled TaskStatus = "canceled" // TaskStatusSubmitted means a task is accepted by Beaker. // The task will automatically start when eligible. TaskStatusSubmitted TaskStatus = "submitted" // TaskStatusProvisioning means a task has been submitted for execution and // Beaker is waiting for compute resources to become available. TaskStatusProvisioning TaskStatus = "provisioning" // TaskStatusInitializing means a task is attempting to start, but is not yet running. TaskStatusInitializing TaskStatus = "initializing" // TaskStatusRunning means a task is executing. TaskStatusRunning TaskStatus = "running" // TaskStatusSucceeded means a task has completed successfully. TaskStatusSucceeded TaskStatus = "succeeded" // TaskStatusSkipped means a task will never run due to failed or invalid prerequisites. TaskStatusSkipped TaskStatus = "skipped" // TaskStatusStopped means a task was interrupted. TaskStatusStopped TaskStatus = "stopped" // TaskStatusFailed means a task could not be completed. TaskStatusFailed TaskStatus = "failed" ) // IsEndState is true if the TaskStatus is canceled, failed, or successful func (ts TaskStatus) IsEndState() bool { switch ts { // TODO: Delete this when the deprecated states go away. case TaskStatusSuccessful, TaskStatusCanceled: fallthrough // New end states case TaskStatusSucceeded, TaskStatusSkipped, TaskStatusStopped, TaskStatusFailed: return true default: return false } }
go
7
0.782841
100
34.823529
68
starcoderdata
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.CommandLine; using System.CommandLine.Invocation; using System.IO; using System.Reflection; using System.Threading.Tasks; namespace MsSql.Collector { internal class Program { private static Task Main(string[] args) { var toolDirectory = AppDomain.CurrentDomain.BaseDirectory; var workingDirectory = Directory.GetCurrentDirectory(); var version = Assembly.GetExecutingAssembly().GetName().Version ?? new Version(); Console.WriteLine($@" {asciiart} tool directory: {toolDirectory} work directory: {workingDirectory} tool version : {version.Major}.{version.Minor}.{version.Build} "); var service = GetService(workingDirectory, args); var rootCommand = new RootCommand { new Option "The database connection string."), new Option "The database connection user."), new Option "The database connection password."), new Option "The pattern to use for identifying valid stored procedures."), new Option "The previous generated results, used to keep same order for members."), new Option "The output file path relative to current working directory."), new Option "Skip parsing response of stored procedures."), }; rootCommand.Description = "MsSql.Adapter.Collector"; rootCommand.Handler = CommandHandler.Create(async () => { var resp = await service.WriteDatabaseMetaToFile(workingDirectory); Console.WriteLine(resp.StatusMessage); if (resp.Fail()) { Environment.Exit(resp.StatusCode); } }); // Parse the incoming args and invoke the handler return rootCommand.InvokeAsync(args); } private static SqlCollectorService GetService(string workingDirectory, string[] args) { var configuration = new ConfigurationBuilder() .SetBasePath(workingDirectory) .AddUserSecrets .AddCommandLine(args, new Dictionary<string, string>() { { "--connection", $"{nameof(SqlCollectorServiceOptions)}:{nameof(SqlCollectorServiceOptions.ConnectionString)}" }, { "--user", $"{nameof(SqlCollectorServiceOptions)}:{nameof(SqlCollectorServiceOptions.ConnectionUser)}" }, { "--password", $"{nameof(SqlCollectorServiceOptions)}:{nameof(SqlCollectorServiceOptions.ConnectionPassword)}" }, { "--pattern", $"{nameof(SqlCollectorServiceOptions)}:{nameof(SqlCollectorServiceOptions.ProcedurePattern)}" }, { "--previous", $"{nameof(SqlCollectorServiceOptions)}:{nameof(SqlCollectorServiceOptions.PreviousResultFile)}" }, { "--output", $"{nameof(SqlCollectorServiceOptions)}:{nameof(SqlCollectorServiceOptions.ResultFile)}" }, { "--skip-response", $"{nameof(SqlCollectorServiceOptions)}:{nameof(SqlCollectorServiceOptions.SkipOutputParams)}" }, }) .Build(); var services = new ServiceCollection() .Configure .AddOptions() .AddSingleton .BuildServiceProvider(true); return services.GetRequiredService } private static string asciiart = @" __ __ ___ _ _ _ _ ___ _ _ _ | \/ |__/ __| __ _| |___ /_\ __| |__ _ _ __| |_ ___ _ _ ___ / __|___| | |___ __| |_ ___ _ _ | |\/| (_-<__ \/ _` | |___/ _ \/ _` / _` | '_ \ _/ -_) '_|___| (__/ _ \ | / -_) _| _/ _ \ '_| |_| |_/__/___/\__, |_| /_/ \_\__,_\__,_| .__/\__\___|_| \___\___/_|_\___\__|\__\___/_| |_| |_| "; } }
c#
26
0.556028
138
48.142857
91
starcoderdata
""" prepare pathway name and pathway time for pathway-probability evaluation """ import os import sys import numpy as np import pandas as pd def prepare_pathway_name(data_dir, top_n=5, flag="", delimiter=",", end_s_idx=None, species_path=False): """ prepare pathway_name_candidate.csv """ # read from pathway_stat.csv prefix = "" if species_path is True: prefix = "species_" f_n_ps = os.path.join(data_dir, "output", prefix + "pathway_stat.csv") if flag == "": f_n_pn = os.path.join(data_dir, "output", prefix + "pathway_name_candidate.csv") else: f_n_pn = os.path.join(data_dir, "output", prefix + "pathway_name_candidate_" + str(flag) + ".csv") try: os.remove(f_n_pn) except OSError: pass # read if end_s_idx is None or end_s_idx == []: data = np.genfromtxt( f_n_ps, dtype=str, delimiter=delimiter, max_rows=top_n + 1) path_list = [val[0] for idx, val in enumerate(data) if idx < top_n] else: path_list = [] d_f = pd.read_csv(f_n_ps, names=['pathway', 'frequency']) for s_i in end_s_idx: path_list.extend(d_f[d_f['pathway'].str.endswith( "S" + str(s_i))]['pathway'][0:top_n]) # save np.savetxt(f_n_pn, path_list, fmt="%s") def prepare_pathway_time(data_dir, top_n=5, num=1, flag="", begin_t=0.0, end_t=1.0, species_path=False): """ prepare pathway_time.csv num represents number of points """ prefix = "" if species_path is True: prefix = "species_" if flag == "": f_n_pt = os.path.join(data_dir, "output", prefix + "pathway_time_candidate.csv") else: f_n_pt = os.path.join(data_dir, "output", prefix + "pathway_time_candidate_" + str(flag) + ".csv") try: os.remove(f_n_pt) except OSError: pass # time matrix t_mat = np.empty((top_n, num + 1, )) for idx, _ in enumerate(t_mat): t_mat[idx] = np.linspace(begin_t, end_t, num + 1) np.savetxt(f_n_pt, t_mat[:, 1::], delimiter=',', fmt='%.7f') if __name__ == '__main__': # print("hello") DATA_DIR = os.path.abspath(os.path.join(os.path.realpath( sys.argv[0]), os.pardir, os.pardir, os.pardir, os.pardir, "SOHR_DATA")) # print(DATA_DIR) prepare_pathway_name(DATA_DIR, top_n=5, flag="", delimiter=",", end_s_idx=[62, 59])
python
19
0.542438
104
29.857143
84
starcoderdata
class Solution(object): def addStrings(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ if(num1==None or len(num1)==0): return num2 if(num2==None or len(num2)==0): return num1 num_map = {"0":0, "1":1, "2":2, "3":3 ,"4":4, "5":5, "6":6, "7":7, "8":8, "9":9} i = len(num1)-1 j = len(num2)-1 res = "" is_plus = False while(i>=0 or j>=0): tmp = 0 if(i >= 0): tmp += num_map[ num1[i] ] if(j >= 0): tmp += num_map[ num2[j] ] if(is_plus): tmp += 1 if(tmp > 9): is_plus = True tmp %= 10 else: is_plus = False else: if(tmp > 9): is_plus = True tmp %= 10 res = str(tmp) + res i -= 1 j -= 1 if(is_plus): return "1"+res return res
python
14
0.497525
82
19.225
40
starcoderdata
package com.codingchili.core.storage.exception; import com.codingchili.core.configuration.CoreStrings; import com.codingchili.core.context.CoreException; /** * Generic storage error, throw when a requested operation has error. */ public class StorageFailureException extends CoreException { public StorageFailureException() { super(CoreStrings.ERROR_STORAGE_EXCEPTION); } }
java
8
0.753056
69
27.214286
14
starcoderdata
def get_items(self): """ Returns all task docs and tag definitions to process Returns: generator or list of task docs and tag definitions """ self.logger.info("Setting up indicies") self.ensure_indicies() # Determine tasks to process. self.logger.info("Determining tasks to process") all_task_ids = self.tasks.distinct("task_id", {"state": "successful"}) previous_task_ids = self.task_types.distinct("task_id") to_process = list(set(all_task_ids) - set(previous_task_ids)) self.logger.info("Yielding {} task documents".format(len(to_process))) self.total = len(to_process) for task_id in to_process: yield self.tasks.query_one(criteria={"task_id": task_id}, properties=["task_id", "orig_inputs"])
python
13
0.615293
108
37.090909
22
inline
package csu.agent.pf; import java.util.EnumSet; import java.util.HashSet; import java.util.Set; import csu.agent.CentreAgent; import csu.common.TimeOutException; import csu.model.route.pov.POVRouter; import rescuecore2.standard.entities.Area; import rescuecore2.standard.entities.PoliceOffice; import rescuecore2.standard.entities.StandardEntityURN; public class PoliceOfficeAgent extends CentreAgent { protected POVRouter router; // protected PoliceForceTaskManager taskManager; @Override protected void initialize() { super.initialize(); System.out.println(toString() + " is connected. [id=" + getID() + "]"); //router = new POVRouter(me(), world); // taskManager = new PoliceForceTaskManager(world); } protected Set crossses = new HashSet @Override protected void prepareForAct() throws TimeOutException{ super.prepareForAct(); // for (StandardEntity se : world.getEntitiesOfType(AgentConstants.AREAS)) { // Area area = (Area) se; // if (area.getNeighbours().size() >= 3) { // crossses.add(area); // } // } } @Override protected void act() throws ActionCommandException, TimeOutException { } @Override protected void afterAct() { super.afterAct(); } @Override protected EnumSet getRequestedEntityURNsEnum() { return EnumSet.of(StandardEntityURN.POLICE_OFFICE); } @Override public String toString() { return "CSU_YUNLU police office agent"; } }
java
13
0.73266
77
21.164179
67
starcoderdata
public float GetDpiScaleRatio() { if (this.DpiScalingMethod == DpiMethod.UseGameDpi || this.DpiScalingMethod == DpiMethod.SyncWithGame && GameIntegration.GfxSettings.DpiScaling.GetValueOrDefault()) { uint dpi = GetDpi(); // If DPI is 0 then the window handle is likely not valid return dpi != 0 ? dpi / 96f : 1f; } return 1f; }
c#
12
0.472868
132
38.769231
13
inline
#include #include START_ATF_NAMESPACE namespace Detail { Info::_logout_account_request_wracsize2_ptr _logout_account_request_wracsize2_next(nullptr); Info::_logout_account_request_wracsize2_clbk _logout_account_request_wracsize2_user(nullptr); int _logout_account_request_wracsize2_wrapper(struct _logout_account_request_wrac* _this) { return _logout_account_request_wracsize2_user(_this, _logout_account_request_wracsize2_next); }; ::std::array<hook_record, 1> _logout_account_request_wrac_functions = { _hook_record { (LPVOID)0x14011f230L, (LPVOID *)&_logout_account_request_wracsize2_user, (LPVOID *)&_logout_account_request_wracsize2_next, (LPVOID)cast_pointer_function(_logout_account_request_wracsize2_wrapper), (LPVOID)cast_pointer_function((int(_logout_account_request_wrac::*)())&_logout_account_request_wrac::size) }, }; }; // end namespace Detail END_ATF_NAMESPACE
c++
18
0.633913
122
41.592593
27
starcoderdata
const btn = document.getElementsByClassName('clickable'); const stockUp = document.getElementsByClassName('stockBtn'); //adding stock from owner page Array.from(stockUp).forEach(function(element) { element.addEventListener('click', function(){ const name = this.parentNode.childNodes[1].childNodes[1].innerText const code = this.parentNode.childNodes[3].childNodes[1].innerText const stock = parseInt(this.parentNode.childNodes[7].childNodes[1].innerText, 10) const newStock = parseInt(this.parentNode.childNodes[11].value, 10) fetch('items', { method: 'put', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ 'name': name, 'code': code, 'stock': stock, 'newStock':newStock }) }) .then(response => { if (response.ok) return response.json() }) .then(data => { console.log(data) window.location.reload(true) }) }); }); //clicking submit button on index.ejs Array.from(btn).forEach(function(element) { element.addEventListener('click', function(){ const input = document.getElementById('vendNum') if(this.id!=="clickMe"){ input.value=this.innerText } let code = input.value; const dispImg = document.getElementById('dispImg'); const dispPrice= document.getElementById('dispPrice'); const dispName= document.getElementById('dispName'); console.log(code) fetch('item', { method: 'put', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ 'code': code }) }) .then((result, err) => { return result.json(); }) .then((response, err) => { console.log(response) dispImg.src= response.value.pic; dispPrice.innerText= response.value.price; dispName.innerText = response.value.name; let priceAdd = parseInt(dispPrice.innerText, 10) console.log(priceAdd) moMoney(priceAdd) }) }) }) function moMoney(price){ fetch('bank', { method: 'put', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ 'price': price }) }) .then(response => { if (response.ok) return response.json() }) .then(data => { console.log(data) // window.location.reload(true) }) }
javascript
21
0.631691
85
28.061728
81
starcoderdata
_c_lang_config = { "template": """//PREPEND BEGIN #include //PREPEND END //TEMPLATE BEGIN int add(int a, int b) { // Please fill this blank return ___________; } //TEMPLATE END //APPEND BEGIN int main() { printf("%d", add(1, 2)); return 0; } //APPEND END""", "compile": { "src_name": "main.c", "exe_name": "main", "max_cpu_time": 3000, "max_real_time": 5000, "max_memory": 256 * 1024 * 1024, "compile_command": "/usr/bin/gcc -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c99 {src_path} -lm -o {exe_path}", }, "run": { "command": "{exe_path}", "seccomp_rule": "c_cpp", } } _c_lang_spj_compile = { "src_name": "spj-{spj_version}.c", "exe_name": "spj-{spj_version}", "max_cpu_time": 3000, "max_real_time": 5000, "max_memory": 1024 * 1024 * 1024, "compile_command": "/usr/bin/gcc -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c99 {src_path} -lm -o {exe_path}" } _c_lang_spj_config = { "exe_name": "spj-{spj_version}", "command": "{exe_path} {in_file_path} {user_out_file_path}", "seccomp_rule": "c_cpp" } _cpp_lang_config = { "template": """//PREPEND BEGIN #include //PREPEND END //TEMPLATE BEGIN int add(int a, int b) { // Please fill this blank return ___________; } //TEMPLATE END //APPEND BEGIN int main() { std::cout << add(1, 2); return 0; } //APPEND END""", "compile": { "src_name": "main.cpp", "exe_name": "main", "max_cpu_time": 3000, "max_real_time": 5000, "max_memory": 512 * 1024 * 1024, "compile_command": "/usr/bin/g++ -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c++11 {src_path} -lm -o {exe_path}", }, "run": { "command": "{exe_path}", "seccomp_rule": "c_cpp" } } _cpp_lang_spj_compile = { "src_name": "spj-{spj_version}.cpp", "exe_name": "spj-{spj_version}", "max_cpu_time": 3000, "max_real_time": 5000, "max_memory": 1024 * 1024 * 1024, "compile_command": "/usr/bin/g++ -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c++11 {src_path} -lm -o {exe_path}" } _cpp_lang_spj_config = { "exe_name": "spj-{spj_version}", "command": "{exe_path} {in_file_path} {user_out_file_path}", "seccomp_rule": "c_cpp" } _java_lang_config = { "template": """//PREPEND BEGIN //PREPEND END //TEMPLATE BEGIN //TEMPLATE END //APPEND BEGIN //APPEND END""", "compile": { "src_name": "Main.java", "exe_name": "Main", "max_cpu_time": 3000, "max_real_time": 5000, "max_memory": -1, "compile_command": "/usr/bin/javac {src_path} -d {exe_dir} -encoding UTF8" }, "run": { "command": "/usr/bin/java -cp {exe_dir} -Xss1M -Xms16M -Xmx{max_memory}k " "-Djava.security.manager -Djava.security.policy=/etc/java_policy -Djava.awt.headless=true Main", "seccomp_rule": None, "env": ["MALLOC_ARENA_MAX=1"] } } _py2_lang_config = { "template": """//PREPEND BEGIN //PREPEND END //TEMPLATE BEGIN //TEMPLATE END //APPEND BEGIN //APPEND END""", "compile": { "src_name": "solution.py", "exe_name": "solution.pyc", "max_cpu_time": 3000, "max_real_time": 5000, "max_memory": 128 * 1024 * 1024, "compile_command": "/usr/bin/python -m py_compile {src_path}", }, "run": { "command": "/usr/bin/python {exe_path}", "seccomp_rule": "general", } } _py3_lang_config = { "template": """//PREPEND BEGIN //PREPEND END //TEMPLATE BEGIN //TEMPLATE END //APPEND BEGIN //APPEND END""", "compile": { "src_name": "solution.py", "exe_name": "__pycache__/solution.cpython-35.pyc", "max_cpu_time": 3000, "max_real_time": 5000, "max_memory": 128 * 1024 * 1024, "compile_command": "/usr/bin/python3 -m py_compile {src_path}", }, "run": { "command": "/usr/bin/python3 {exe_path}", "seccomp_rule": "general", "env": ["PYTHONIOENCODING=UTF-8"] } } languages = [ {"config": _c_lang_config, "spj": {"compile": _c_lang_spj_compile, "config": _c_lang_spj_config}, "name": "C", "description": "GCC 4.8", "content_type": "text/x-csrc"}, {"config": _cpp_lang_config, "spj": {"compile": _cpp_lang_spj_compile, "config": _cpp_lang_spj_config}, "name": "C++", "description": "G++ 4.8", "content_type": "text/x-c++src"}, {"config": _java_lang_config, "name": "Java", "description": "OpenJDK 1.7", "content_type": "text/x-java"}, {"config": _py2_lang_config, "name": "Python2", "description": "Python 2.7", "content_type": "text/x-python"}, {"config": _py3_lang_config, "name": "Python3", "description": "Python 3", "content_type": "text/x-python"}, ] spj_languages = list(filter(lambda item: "spj" in item, languages)) language_names = [item["name"] for item in languages] spj_language_names = [item["name"] for item in spj_languages]
python
10
0.554822
119
26.163043
184
starcoderdata
<?php namespace Tests\Feature\Controllers; use App\Models\User; use App\Models\Client; use Tests\TestCase; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Foundation\Testing\RefreshDatabase; class ClientControllerTest extends TestCase { use RefreshDatabase, WithFaker; protected function setUp(): void { parent::setUp(); $this->actingAs( User::factory()->create(['email' => ' ); $this->seed(\Database\Seeders\PermissionsSeeder::class); $this->withoutExceptionHandling(); } /** * @test */ public function it_displays_index_view_with_clients() { $clients = Client::factory() ->count(5) ->create(); $response = $this->get(route('clients.index')); $response ->assertOk() ->assertViewIs('app.clients.index') ->assertViewHas('clients'); } /** * @test */ public function it_displays_create_view_for_client() { $response = $this->get(route('clients.create')); $response->assertOk()->assertViewIs('app.clients.create'); } /** * @test */ public function it_stores_the_client() { $data = Client::factory() ->make() ->toArray(); $response = $this->post(route('clients.store'), $data); $this->assertDatabaseHas('clients', $data); $client = Client::latest('id')->first(); $response->assertRedirect(route('clients.edit', $client)); } /** * @test */ public function it_displays_show_view_for_client() { $client = Client::factory()->create(); $response = $this->get(route('clients.show', $client)); $response ->assertOk() ->assertViewIs('app.clients.show') ->assertViewHas('client'); } /** * @test */ public function it_displays_edit_view_for_client() { $client = Client::factory()->create(); $response = $this->get(route('clients.edit', $client)); $response ->assertOk() ->assertViewIs('app.clients.edit') ->assertViewHas('client'); } /** * @test */ public function it_updates_the_client() { $client = Client::factory()->create(); $data = [ 'name' => $this->faker->name, ]; $response = $this->put(route('clients.update', $client), $data); $data['id'] = $client->id; $this->assertDatabaseHas('clients', $data); $response->assertRedirect(route('clients.edit', $client)); } /** * @test */ public function it_deletes_the_client() { $client = Client::factory()->create(); $response = $this->delete(route('clients.destroy', $client)); $response->assertRedirect(route('clients.index')); $this->assertDeleted($client); } }
php
15
0.542951
72
21.101449
138
starcoderdata
from adaptive.client.client import Client from adaptive.interface.user_data.constants import UserAccountCreation from adaptive.interface.adaptive.constants import ( UserAdRequest, UserAdResponse, ) from adaptive.simul.users import User class UserClient(Client): def __init__(self, user: User): super(UserClient).__init__() self.user = user def get_system_information(self): return None @Client.transmission def _create_account(self, userData) -> int: return self.client.createUserAccount(userData) def create_account(self) -> bool: # Create user account userData = UserAccountCreation( name=self.user.name, age=self.user.age_public, gender=self.user.gender_public, ) success, self.user.uid = self._create_account(userData) return success @Client.transmission def _request_ads(self, reqData: UserAdRequest) -> UserAdResponse: return self.client.user_request(reqData) def request_ads(self) -> bool: reqData = UserAdRequest( uid=self.user.uid, sysinfo=self.get_system_information(), ) # send ad request success, ad_response = self._request_ads(reqData) # Use ad_response print(ad_response) return success
python
12
0.64433
70
27.893617
47
starcoderdata
const data = [[ "https://joeschmoe.io/api/v1/rahul" ], [ "https://joeschmoe.io/api/v1/priyanka" ], [ "https://joeschmoe.io/api/v1/jhon" ], [ "https://joeschmoe.io/api/v1/michael" ], [ "https://joeschmoe.io/api/v1/lamina" ], [ "https://joeschmoe.io/api/v1/albert" ], [ "https://joeschmoe.io/api/v1/yusuf" ], [ "https://joeschmoe.io/api/v1/jhony" ], [ "https://joeschmoe.io/api/v1/richard" ], [ "https://joeschmoe.io/api/v1/heardwrk" ] ] export default data;
javascript
3
0.584642
43
14.941176
34
starcoderdata
'use strict' /* application modules */ const ImmutableCoreModel = require('../lib/immutable-core-model') const initTestEnv = require('./helpers/init-test-env') describe('immutable-core-model - relations with original id', function () { var mysql, redis, reset, session before(async function () { [mysql, redis, reset, session] = await initTestEnv() }) after(async function () { await mysql.close() }) // models to create var fooModelGlobal, barModelGlobal // local models with session var fooModel, barModel before(async function () { await reset(mysql, redis) // create foo model fooModelGlobal = new ImmutableCoreModel({ mysql: mysql, name: 'foo', redis: redis, relations: { bar: {}, }, }) // create bar model barModelGlobal = new ImmutableCoreModel({ columns: { fooOriginalId: { index: true, null: true, type: 'id', }, }, mysql: mysql, name: 'bar', redis: redis, }) // sync with mysql await fooModelGlobal.sync() await barModelGlobal.sync() // get local instances fooModel = fooModelGlobal.session(session) barModel = barModelGlobal.session(session) }) it('should create related model and via', async function () { // create foo instance var foo = await fooModel.create({foo: 'foo'}) // create related var related = await foo.create('bar', {foo: 'bar'}) // load related var bar = await barModel.select.one.by.fooOriginalId(foo.originalId) // check that related was created assert.isObject(bar) assert.strictEqual(bar.data.fooOriginalId, foo.originalId) }) it('should create related model and via from opposite model', async function () { // create bar instance var bar = await barModel.create({foo: 'bar'}) // create related var related = await bar.create('foo', {foo: 'foo'}) // load related var foo = await fooModel.select.by.id(related.id) // check that related was created assert.isObject(foo) }) it('should select related models', async function () { // create foo instance var foo = await fooModel.create({foo: 'foo'}) // create related await foo.create('bar', {foo: 'bam'}) await foo.create('bar', {foo: 'bar'}) // load related var result = await foo.select('bar') // check result assert.strictEqual(result.length, 2) }) it('should query related models', async function () { // create foo instance var foo = await fooModel.create({foo: 'foo'}) // create revision of instance foo = await foo.update({foo: 'bar'}) // create related await foo.create('bar', {foo: 'bam'}) await foo.create('bar', {foo: 'bar'}) await foo.create('bar', {foo: 'foo'}) // load related desc var result = await foo.query({ order: ['createTime', 'DESC'], relation: 'bar', }) // fetch results var desc = await result.fetch(6) // load related asc var result = await foo.query({ order: ['createTime'], relation: 'bar', }) // fetch results var asc = await result.fetch(6) // check result assert.strictEqual(asc.length, 3) assert.strictEqual(asc[0].data.foo, 'bam') assert.strictEqual(asc[1].data.foo, 'bar') assert.strictEqual(asc[2].data.foo, 'foo') assert.strictEqual(desc.length, 3) assert.strictEqual(desc[0].data.foo, 'foo') assert.strictEqual(desc[1].data.foo, 'bar') assert.strictEqual(desc[2].data.foo, 'bam') }) })
javascript
27
0.554842
85
31.134921
126
starcoderdata
private static GetterMethod findGetter(EclipseNode field) { TypeReference fieldType = ((FieldDeclaration)field.get()).type; boolean isBoolean = nameEquals(fieldType.getTypeName(), "boolean") && fieldType.dimensions() == 0; EclipseNode typeNode = field.up(); for (String potentialGetterName : TransformationsUtil.toAllGetterNames(field.getName(), isBoolean)) { for (EclipseNode potentialGetter : typeNode.down()) { if (potentialGetter.getKind() != Kind.METHOD) continue; if (!(potentialGetter.get() instanceof MethodDeclaration)) continue; MethodDeclaration method = (MethodDeclaration) potentialGetter.get(); if (!potentialGetterName.equalsIgnoreCase(new String(method.selector))) continue; /** static getX() methods don't count. */ if ((method.modifiers & ClassFileConstants.AccStatic) != 0) continue; /** Nor do getters with a non-empty parameter list. */ if (method.arguments != null && method.arguments.length > 0) continue; return new GetterMethod(method.selector, method.returnType); } } // Check if the field has a @Getter annotation. boolean hasGetterAnnotation = false; for (EclipseNode child : field.down()) { if (child.getKind() == Kind.ANNOTATION && annotationTypeMatches(Getter.class, child)) { AnnotationValues<Getter> ann = Eclipse.createAnnotation(Getter.class, child); if (ann.getInstance().value() == AccessLevel.NONE) return null; //Definitely WONT have a getter. hasGetterAnnotation = true; } } // Check if the class has a @Getter annotation. if (!hasGetterAnnotation && new HandleGetter().fieldQualifiesForGetterGeneration(field)) { //Check if the class has @Getter or @Data annotation. EclipseNode containingType = field.up(); if (containingType != null) for (EclipseNode child : containingType.down()) { if (child.getKind() == Kind.ANNOTATION && annotationTypeMatches(Data.class, child)) hasGetterAnnotation = true; if (child.getKind() == Kind.ANNOTATION && annotationTypeMatches(Getter.class, child)) { AnnotationValues<Getter> ann = Eclipse.createAnnotation(Getter.class, child); if (ann.getInstance().value() == AccessLevel.NONE) return null; //Definitely WONT have a getter. hasGetterAnnotation = true; } } } if (hasGetterAnnotation) { String getterName = TransformationsUtil.toGetterName(field.getName(), isBoolean); return new GetterMethod(getterName.toCharArray(), fieldType); } return null; }
java
16
0.715836
115
45.962264
53
inline
Game.py print('''This is a Guessing Game! Choose numbers from 1 to 15 You only have 3 chances.''') secret_number = 9 i = 1 while i <= 3: i += 1 guess = int(input('Guess the number : ')) if guess == secret_number: print('You Won! 9 was the secret number.') break else: print('You have lost the game.')
python
10
0.598361
50
24.214286
14
starcoderdata
// utils const { hashPassword } = require("../../../utils/secureHash"); // model const User = require("./userModel"); // utils const { userToken } = require("../../../utils/getToken"); const { formatUserData } = require("../../../utils/formatData"); /** * @desc user controller */ const userController = { /** * @desc creates a user * @param {object} req * @param {object} res */ async createUser(req, res) { const { body } = req; const hashedPwd = await hashPassword(body.password); const userData = { ...body, password: }; try { const createdUser = await User.create({ ...userData }); const token = userToken(createdUser); const user = formatUserData(createdUser); return res.status(201).send({ message: "User created successfully.", user, token, }); } catch (error) { return res.status(500).send({ message: "An error occured.", error, }); } }, /** * @desc retrieves all users * @param {object} req * @param {object} res */ async getUsers(req, res) { try { const allUsers = await User.find(); return res.status(200).send({ message: "All users retrieved.", users: allUsers, }); } catch (error) { return res.status(500).send({ message: "An error occured.", error, }); } }, /** * @desc updates a user details * @param {object} req * @param {object} res */ async updateUser(req, res) { const { id } = req.params; const { body } = req; try { const updatedUser = await User.findByIdAndUpdate(id, body, { new: true }); if (!updatedUser) { return res.status(404).send({ message: "User with the details does not exist", }); } return res.status(201).send({ message: "User details updated", user: updatedUser, }); } catch (error) { return res.status(500).send({ message: "User details not updated.", error, }); } }, /** * @desc * @param {object} req * @param {object} res */ async deleteUser(req, res) {}, }; module.exports = userController;
javascript
18
0.549169
80
21.958763
97
starcoderdata
function(className) { // summary: used to ensure that only 1 validation class is set at a time var pre = this.classPrefix; if (focusedWindowElement == this.textbox) { dojo.removeClass(this.textbox,pre+"Empty_focus"); dojo.removeClass(this.textbox,pre+"Valid_focus"); dojo.removeClass(this.textbox,pre+"Invalid_focus"); dojo.addClass(this.textbox,pre+className+"_focus"); } else { dojo.removeClass(this.textbox,pre+"Empty"); dojo.removeClass(this.textbox,pre+"Valid"); dojo.removeClass(this.textbox,pre+"Invalid"); dojo.addClass(this.textbox,pre+className); } }
javascript
12
0.679365
76
41.066667
15
inline
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { var S = Console.ReadLine(); var K = long.Parse(Console.ReadLine()); var firstchr = S[0]; int firstcount = 0; int lastcount = 0; int chgcount = 0; double ans; for (int i = 0; i < S.Length; i++) { if (S[i] == firstchr) { firstcount++; } else { break; } } // Console.WriteLine(string.Format("firstcount:{0}", firstcount)); for (int i = S.Length - 1; i > 0; i--) { if (S[i] == firstchr) { lastcount++; } else { break; } } // Console.WriteLine(string.Format("lastcount:{0}", lastcount)); for (int i = firstcount; i < S.Length - 1 - lastcount; i++) { if (S[i] == S[i + 1]) { chgcount++; i++; } } // Console.WriteLine(string.Format("firstcountblock:{0}", firstcountblock)); // Console.WriteLine(string.Format("lastcountblock:{0}", lastcountblock)); // Console.WriteLine(string.Format("chgcountblock:{0}", chgcountblock)); // Console.WriteLine(string.Format("lastblocak:{0}", lastblocak)); if(firstcount == S.Length) lastcount =0; double firstcountblock = firstcount / 2; double lastcountblock = lastcount / 2; double chgcountblock = chgcount * K; double lastblocak = (firstcount + lastcount) / 2 * (K - 1); ans = firstcountblock + lastcountblock + chgcountblock+lastblocak; if(firstcount ==S.Length){ ans = firstcount*K/2; } Console.WriteLine(ans); // Console.ReadLine(); } }
c#
14
0.623237
77
23.833333
60
codenet
/* * Copyright © 2017 http://io7m.com * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package com.io7m.gtyrell.github; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.io7m.gtyrell.core.GTGitExecutableType; import com.io7m.gtyrell.core.GTRepositoryGroupName; import com.io7m.gtyrell.core.GTRepositoryName; import com.io7m.gtyrell.core.GTRepositoryType; import org.apache.commons.io.IOUtils; import org.apache.commons.io.input.CountingInputStream; import org.apache.commons.io.input.ProxyInputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URI; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; import java.util.Base64; import java.util.Objects; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; final class GTGithubRepository implements GTRepositoryType { private static final Logger LOG; static { LOG = LoggerFactory.getLogger(GTGithubRepository.class); } private final GTGitExecutableType git; private final URI url; private final GTRepositoryGroupName group; private final GTRepositoryName name; private final String username; private final String password; GTGithubRepository( final GTGitExecutableType in_git, final String in_username, final String in_password, final GTRepositoryGroupName in_group, final GTRepositoryName in_name, final URI in_url) { this.username = Objects.requireNonNull(in_username, "in_username"); this.password = Objects.requireNonNull(in_password, "in_password"); this.git = Objects.requireNonNull(in_git, "Git"); this.url = Objects.requireNonNull(in_url, "URL"); this.group = Objects.requireNonNull(in_group, "Group"); this.name = Objects.requireNonNull(in_name, "Name"); } private static GZIPOutputStream createOutput( final Path path) throws IOException { return new GZIPOutputStream(Files.newOutputStream( path, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE, StandardOpenOption.WRITE)); } @Override public String toString() { final StringBuilder sb = new StringBuilder(128); sb.append(this.group.text()); sb.append("/"); sb.append(this.name.text()); sb.append(" @ "); sb.append(this.url); return sb.toString(); } @Override public void update( final File output) throws IOException { if (output.isDirectory()) { this.git.fetch(output); } else { final File parent = output.getParentFile(); if (!parent.mkdirs()) { if (!parent.isDirectory()) { throw new IOException(String.format("Not a directory: %s", parent)); } } this.git.clone(this.url, output); } this.fetchIssues( new File(output.toString() + ".issues.json.gz"), new File(output.toString() + ".issues.json.gz.tmp")); } private void fetchIssues( final File file, final File file_tmp) throws IOException { LOG.debug("fetching issues: {}", file); final StringBuilder sb = new StringBuilder(128); sb.append("https://api.github.com/repos/"); sb.append(this.group.text()); sb.append("/"); sb.append(this.name.text()); sb.append("/issues?state=all"); final URL issue_url = new URL(sb.toString()); final String token = this.username + ":" + this.password; final Base64.Encoder enc = Base64.getMimeEncoder(); final String encoding = enc.encodeToString(token.getBytes(StandardCharsets.UTF_8)); final HttpURLConnection conn = (HttpURLConnection) issue_url.openConnection(); conn.setRequestProperty("Authorization", "Basic " + encoding); conn.setRequestProperty("Accept-Encoding", "gzip"); conn.connect(); final Path path = file.toPath(); final Path path_tmp = file_tmp.toPath(); try (CountedMaybeCompressedStream input = CountedMaybeCompressedStream.fromHTTPConnection(conn)) { try (OutputStream output = createOutput(path_tmp)) { IOUtils.copy(input, output); LOG.debug( "received {} octets", Long.toUnsignedString(input.inner.getByteCount())); output.flush(); } if (this.parseJSON(path_tmp)) { Files.move(path_tmp, path, StandardCopyOption.ATOMIC_MOVE); } } } private boolean parseJSON( final Path file) throws IOException { final ObjectMapper m = new ObjectMapper(); try { try (GZIPInputStream is = new GZIPInputStream(Files.newInputStream(file))) { m.readTree(is); LOG.debug("parsed issues correctly, replacing"); return true; } } catch (final JsonProcessingException e) { LOG.error( "could not parse issues for {}/{}: ", this.group.text(), this.name.text(), e); return false; } } private static final class CountedMaybeCompressedStream extends ProxyInputStream { private final CountingInputStream inner; private CountedMaybeCompressedStream( final CountingInputStream in_inner, final InputStream in_outer) { super(in_outer); this.inner = Objects.requireNonNull(in_inner, "Inner"); } static CountedMaybeCompressedStream fromHTTPConnection( final HttpURLConnection conn) throws IOException { final InputStream raw = conn.getInputStream(); final CountingInputStream counter = new CountingInputStream(raw); final InputStream outer; if (Objects.equals("gzip", conn.getContentEncoding())) { outer = new GZIPInputStream(counter); } else { outer = counter; } return new CountedMaybeCompressedStream(counter, outer); } } }
java
17
0.694408
82
29.390135
223
starcoderdata
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Driver extends Model { use HasFactory; public function getData() { return static::orderBy('created_at','desc')->get(); } public function storeData($input) { return static::create($input); } public function findData($id) { return static::find($id); } public function updateData($id, $input) { return static::find($id)->update($input); } public function deleteData($id) { return static::find($id)->delete(); } }
php
11
0.622669
59
16.871795
39
starcoderdata
JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_available (JNIEnv * env, jclass clazz CK_UNUSED, jobject fd, jobject buffer) { int handle = _getFD(env, fd); if (handle < 0) { _throwException(env, kExceptionSocketException, "Socket is closed"); return 0; } // the following would actually block and keep the peek'ed byte in the buffer //ssize_t count = recv(handle, &buf, 1, MSG_PEEK); int ret; #if defined(_WIN32) long count; ret = ioctlsocket(handle, FIONREAD, (u_long*)&count); #else int count = 0; # if defined(_AIX) ret = ioctlx(handle, FIONREAD, &count, 0); # else ret = ioctl(handle, FIONREAD, &count); # endif if(count < 0) { count = 0; } #endif if(ret == -1) { int myerr = socket_errno; if(myerr == ENOTTY) { // e.g., TIPC on Linux may not implement this call // we resort to polling and peeking with recv's MSG_PEEK struct pollfd pollFd = { .events = POLLIN, .fd = handle }; #if defined(_WIN32) ret = WSAPoll(&pollFd, 1, 0); #else ret = poll(&pollFd, 1, 0); #endif if(ret != 1 || (pollFd.revents & POLLIN) == 0) { // also ignore subsequent errors return 0; } struct jni_direct_byte_buffer_ref dataBufferRef = getDirectByteBufferRef (env, buffer, 0, 0); if(dataBufferRef.size == -1) { // ignore subsequent errors return 0; } else if(dataBufferRef.buf == NULL) { // ignore subsequent errors return 0; } ssize_t count = recv(handle, (char*)&dataBufferRef.buf, dataBufferRef.size, MSG_PEEK #if defined(MSG_TRUNC) | MSG_TRUNC // ask for the correct amount in case our buffer is too small #endif ); if(count > 0) { return (jint)count; } return 0; } else if(myerr == ESPIPE) { return 0; } else { _throwErrnumException(env, myerr, fd); return -1; } } return count; }
c
15
0.512821
106
27.64557
79
inline
const _getIn = require('lodash/get'); const { reactBoundMethods } = require('../constants/methodNames.json'); /** * @fileoverview Expect ES6+ classes to bind instance methods in their constructor * @author */ 'use strict'; const extractOptionsFromContext = context => context.options[0] || {}; const extractIgnoreMethodNamesFromContext = (context) => { const options = extractOptionsFromContext(context); const settings = context.settings; const optionsIgnore = options.ignoreMethodNames || []; const settingsIgnore = settings.react ? reactBoundMethods : []; return optionsIgnore.concat(settingsIgnore); }; const extractIgnoreSubclassesFromContext = context => extractOptionsFromContext(context).ignoreSubclasses; const extractOnlySubclassesFromContext = context => extractOptionsFromContext(context).onlySubclasses; const extractIgnoreFileExtensionsFromContext = context => extractOptionsFromContext(context).ignoreFileExtensions; const extractOnlyFileExtensionsFromContext = context => extractOptionsFromContext(context).onlyFileExtensions; /** * extractBoundMethodsFromConstructorNode * Returns the list of identifiers (Strings) of bound local functions * e.g. 'foo' from `this.foo = this.foo.bind(this)` */ const extractBoundMethodsFromConstructorNode = (constructorNode) => { if (!constructorNode) return []; const constructorExpressions = constructorNode.value.body.body; return constructorExpressions .filter(({ expression }) => expression && expression.type === 'AssignmentExpression') .map(({ expression }) => { const isSettingThis = _getIn(expression, ['left', 'object', 'type']) === 'ThisExpression'; const isBindingToThis = _getIn(expression, ['right', 'callee', 'object', 'object', 'type']) === 'ThisExpression' && _getIn(expression, ['right', 'callee', 'property', 'name']) === 'bind'; const isSettingSameName = _getIn(expression, ['left', 'property', 'name']) === _getIn(expression, ['right','callee', 'object', 'property', 'name']); if (isSettingThis && isBindingToThis && isSettingSameName) { return expression.left.property.name; } }); }; const extractInstanceMethodsFromBodyNode = (bodyNode, ignoreMethodNames) => bodyNode.body.filter(node => node.kind === 'method' && node.static === false) .filter(instanceMethod => // Filter out ignored identifiers (ignoreMethodNames.length === 0) || !ignoreMethodNames.includes(instanceMethod.key.name)); const extractConstructorMethodFromBodyNode = (bodyNode) => bodyNode.body.filter(node => node.kind === 'constructor')[0]; const reportConstructor = (context, classNode) => { context.report({ node: classNode, message: 'Class "{{ className }}" requires constructor to bind instance functions', data: { className: classNode.id.name, }, fix: (fixer) => fixer.insertTextBefore(classNode.body.body[0], 'constructor(){}'), }); }; const reportUnbound = (context, methodNode, className, constructor) => { const methodName = methodNode.key.name; context.report({ node: methodNode, message: 'Instance method "{{ methodName }}" is not bound in constructor for class "{{ className }}"', data: { methodName, className, }, fix: (fixer) => { if (!constructor) return fixer; const lastEntryOfConstructor = _getIn(constructor, ['value', 'body', 'body', constructor.value.body.body.length - 1]); const boilerplateBinding = `this.${methodName} = this.${methodName}.bind(this)`; return fixer.insertTextAfter(lastEntryOfConstructor, boilerplateBinding); } }); }; const shouldConsiderFile = context => { const ignoreFileExtensions = extractIgnoreFileExtensionsFromContext(context); const onlyFileExtensions = extractOnlyFileExtensionsFromContext(context); const extension = context.getFilename().split('.')[1]; if (onlyFileExtensions) { return extension && onlyFileExtensions.includes(extension) } else if (ignoreFileExtensions) { return !extension || !ignoreFileExtensions.includes(extension) } else { return true; } }; const shouldConsiderClass = (classDec, onlySubclasses, ignoreSubclasses) => !classDec.superClass || (ignoreSubclasses && !ignoreSubclasses.includes(classDec.superClass.name)) || (onlySubclasses && onlySubclasses.includes(classDec.superClass.name)); const verifyAndReport = (context, methods, className, constructor) => { const constructorMethods = extractBoundMethodsFromConstructorNode(constructor); methods.forEach(instanceMethod => constructorMethods.includes(instanceMethod.key.name) || reportUnbound(context, instanceMethod, className, constructor) ); }; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { docs: { description: 'Expect classes to bind instance methods in constructor', category: 'Fill me in', recommended: false }, fixable: "code", schema: [ { ignoreMethodNames: { type: 'array', items: { type: 'string', }, uniqueItems: true }, ignoreSubclasses: { type: 'array', items: { type: 'string', }, uniqueItems: true }, onlySubclasses: { type: 'array', items: { type: 'string', }, uniqueItems: true } }, ] }, create: (context) => { if (!shouldConsiderFile(context)) return {}; const ignoreSubclasses = extractIgnoreSubclassesFromContext(context); const onlySubclasses = extractOnlySubclassesFromContext(context); const ignoreMethodNames = extractIgnoreMethodNamesFromContext(context); return { ClassDeclaration: (dec) => { if (!shouldConsiderClass(dec, onlySubclasses, ignoreSubclasses)) return; const node = dec.body; const instanceMethods = extractInstanceMethodsFromBodyNode(node, ignoreMethodNames); const constructor = extractConstructorMethodFromBodyNode(node); if (!constructor && instanceMethods.length) { reportConstructor(context, dec); } verifyAndReport(context, instanceMethods, dec.id.name, constructor); } }; } };
javascript
22
0.661852
106
34.373626
182
starcoderdata
# -*- coding=utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals from ctypes import c_uint64, c_bool from enum import IntEnum import numpy as np from .utils import CxxPointer from .ffi import chfl_bond_order from .atom import Atom from .residue import Residue class BondOrder(IntEnum): """ Possible bond orders are: - ``BondOrder.Unknown``: the bond order is not specified - ``BondOrder.Single``: bond order for single bond - ``BondOrder.Double``: bond order for double bond - ``BondOrder.Triple``: bond order for triple bond - ``BondOrder.Quadruple``: bond order for quadruple bond (present in some metals) - ``BondOrder.Qintuplet``: bond order for qintuplet bond (present in some metals) - ``BondOrder.Amide``: bond order for amide bond - ``BondOrder.Aromatic``: bond order for aromatic bond """ Unknown = chfl_bond_order.CHFL_BOND_UNKNOWN Single = chfl_bond_order.CHFL_BOND_SINGLE Double = chfl_bond_order.CHFL_BOND_DOUBLE Triple = chfl_bond_order.CHFL_BOND_TRIPLE Quadruple = chfl_bond_order.CHFL_BOND_QUADRUPLE Qintuplet = chfl_bond_order.CHFL_BOND_QINTUPLET Amide = chfl_bond_order.CHFL_BOND_AMIDE Aromatic = chfl_bond_order.CHFL_BOND_AROMATIC class TopologyAtoms(object): """Proxy object to get the atoms in a topology""" def __init__(self, topology): self.topology = topology def __len__(self): """Get the current number of atoms in this :py:class:`Topology`.""" count = c_uint64() self.topology.ffi.chfl_topology_atoms_count(self.topology.ptr, count) return count.value def __getitem__(self, index): """ Get a reference to the :py:class:`Atom` at the given ``index`` in the associated :py:class:`Topology`. """ if index >= len(self): raise IndexError("atom index ({}) out of range for this topology".format(index)) else: ptr = self.topology.ffi.chfl_atom_from_topology(self.topology.mut_ptr, c_uint64(index)) return Atom.from_mutable_ptr(self, ptr) def __iter__(self): for i in range(len(self)): yield self[i] def __delitem__(self, index): self.remove(index) def __repr__(self): return "[" + ", ".join([atom.__repr__() for atom in self]) + "]" def remove(self, index): """ Remove the :py:class:`Atom` at the given ``index`` from the associated :py:class:`Topology`. This shifts all the atoms indexes larger than ``index`` by 1 (``n`` becomes ``n - 1``); """ self.topology.ffi.chfl_topology_remove(self.topology.mut_ptr, c_uint64(index)) def append(self, atom): """ Add a copy of the :py:class:`Atom` ``atom`` at the end of this :py:class:`Topology`. """ self.topology.ffi.chfl_topology_add_atom(self.topology.mut_ptr, atom.ptr) class TopologyResidues(object): """Proxy object to get the residues in a topology""" def __init__(self, topology): self.topology = topology def __len__(self): """Get the current number of residues in this :py:class:`Topology`.""" count = c_uint64() self.topology.ffi.chfl_topology_residues_count(self.topology.ptr, count) return count.value def __getitem__(self, index): """ Get read-only access to the :py:class:`Residue` at the given ``index`` from the associated :py:class:`Topology`. The residue index in the topology does not necessarily match the residue id. """ if index >= len(self): raise IndexError("residue index ({}) out of range for this topology".format(index)) else: ptr = self.topology.ffi.chfl_residue_from_topology(self.topology.ptr, c_uint64(index)) return Residue.from_const_ptr(self, ptr) def __iter__(self): for i in range(len(self)): yield self[i] def __repr__(self): return "[" + ", ".join([residue.__repr__() for residue in self]) + "]" def append(self, residue): """ Add the :py:class:`Residue` ``residue`` to this :py:class:`Topology`. The residue ``id`` must not already be in the topology, and the residue must contain only atoms that are not already in another residue. """ self.topology.ffi.chfl_topology_add_residue(self.topology.mut_ptr, residue.ptr) class Topology(CxxPointer): """ A :py:class:`Topology` contains the definition of all the atoms in the system, and the liaisons between the atoms (bonds, angles, dihedrals, ...). It will also contain all the residues information if it is available. """ def __init__(self): """Create a new empty :py:class:`Topology`.""" super(Topology, self).__init__(self.ffi.chfl_topology(), is_const=False) def __copy__(self): return Topology.from_mutable_ptr(None, self.ffi.chfl_topology_copy(self.ptr)) def __repr__(self): return "Topology with {} atoms".format(len(self.atoms)) @property def atoms(self): # late import to break circular dependency from .frame import FrameAtoms # if the topology comes from a frame, allow accessing atoms as # frame.topology.atoms anyway if self._CxxPointer__is_const: return FrameAtoms(self._CxxPointer__origin) else: return TopologyAtoms(self) def resize(self, count): """ Resize this :py:class:`Topology` to contain ``count`` atoms. If the new number of atoms is bigger than the current number, new atoms will be created with an empty name and type. If it is lower than the current number of atoms, the last atoms will be removed, together with the associated bonds, angles and dihedrals. """ self.ffi.chfl_topology_resize(self.mut_ptr, count) @property def residues(self): return TopologyResidues(self) def residue_for_atom(self, index): """ Get read-only access to the :py:class:`Residue` containing the atom at the given ``index`` from this :py:class:`Topology`; or ``None`` if the atom is not part of a residue. """ if index >= len(self.atoms): raise IndexError( "residue index ({}) out of range for this topology".format(index) ) ptr = self.ffi.chfl_residue_for_atom(self.ptr, c_uint64(index)) if ptr: return Residue.from_const_ptr(self, ptr) else: return None def residues_linked(self, first, second): """ Check if the two :py:class:`Residue` ``first`` and ``second`` from this :py:class:`Topology` are linked together, *i.e.* if there is a bond between one atom in the first residue and one atom in the second one. """ linked = c_bool() self.ffi.chfl_topology_residues_linked(self.ptr, first.ptr, second.ptr, linked) return linked.value def bonds_count(self): """Get the number of bonds in this :py:class:`Topology`.""" bonds = c_uint64() self.ffi.chfl_topology_bonds_count(self.ptr, bonds) return bonds.value def angles_count(self): """Get the number of angles in this :py:class:`Topology`.""" angles = c_uint64() self.ffi.chfl_topology_angles_count(self.ptr, angles) return angles.value def dihedrals_count(self): """Get the number of dihedral angles in this :py:class:`Topology`.""" dihedrals = c_uint64() self.ffi.chfl_topology_dihedrals_count(self.ptr, dihedrals) return dihedrals.value def impropers_count(self): """Get the number of improper angles in this :py:class:`Topology`.""" impropers = c_uint64() self.ffi.chfl_topology_impropers_count(self.ptr, impropers) return impropers.value @property def bonds(self): """Get the list of bonds in this :py:class:`Topology`.""" count = self.bonds_count() bonds = np.zeros((count, 2), np.uint64) self.ffi.chfl_topology_bonds(self.ptr, bonds, c_uint64(count)) return bonds def bonds_order(self, i, j): """ Get the bonds order corresponding to the bond between atoms i and j """ order = chfl_bond_order() self.ffi.chfl_topology_bond_order(self.ptr, c_uint64(i), c_uint64(j), order) return BondOrder(order.value) @property def bonds_orders(self): """ Get the list of bonds order for each bond in this :py:class:`Topology`. """ count = self.bonds_count() orders = np.zeros(count, chfl_bond_order) self.ffi.chfl_topology_bond_orders(self.ptr, orders, c_uint64(count)) return list(map(BondOrder, orders)) @property def angles(self): """Get the list of angles in this :py:class:`Topology`.""" count = self.angles_count() angles = np.zeros((count, 3), np.uint64) self.ffi.chfl_topology_angles(self.ptr, angles, c_uint64(count)) return angles @property def dihedrals(self): """Get the list of dihedral angles in this :py:class:`Topology`.""" count = self.dihedrals_count() dihedrals = np.zeros((count, 4), np.uint64) self.ffi.chfl_topology_dihedrals(self.ptr, dihedrals, c_uint64(count)) return dihedrals @property def impropers(self): """Get the list of improper angles in this :py:class:`Topology`.""" count = self.impropers_count() impropers = np.zeros((count, 4), np.uint64) self.ffi.chfl_topology_impropers(self.ptr, impropers, c_uint64(count)) return impropers def add_bond(self, i, j, order=None): """ Add a bond between the atoms at indexes ``i`` and ``j`` in this :py:class:`Topology`, optionally setting the bond ``order``. """ if order is None: self.ffi.chfl_topology_add_bond(self.mut_ptr, c_uint64(i), c_uint64(j)) else: self.ffi.chfl_topology_bond_with_order( self.mut_ptr, c_uint64(i), c_uint64(j), chfl_bond_order(order) ) def remove_bond(self, i, j): """ Remove any existing bond between the atoms at indexes ``i`` and ``j`` in this :py:class:`Topology`. This function does nothing if there is no bond between ``i`` and ``j``. """ self.ffi.chfl_topology_remove_bond(self.mut_ptr, c_uint64(i), c_uint64(j))
python
14
0.613118
99
35.60274
292
starcoderdata
import axios from 'axios'; import Service from './service' import api from './api'; const requestFn = function (requestInfo) { const {xhr, api } = requestInfo const { url, method = 'post', data } = api const req = xhr({ url, method, params:data }) return req.then(respon => { let data = respon.data if(data.code == 1000){ return data.data } else { throw(api.errData ? data.data : data.msg) } }) } const createService = (function (xhr) { return function(api){ return new Service(api, xhr, requestFn) } })(axios.create({ baseURL:process.env.NODE_ENV === 'production' ? '' : 'http://localhost:8080/' })) export default createService export const globalService = createService(api)
javascript
17
0.583951
81
20.891892
37
starcoderdata
// Copyright (c) 2021 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package aggregator import ( "bytes" "encoding/binary" ) // FeatureFlagConfigurations is a list of aggregator feature flags. type FeatureFlagConfigurations []FeatureFlagConfiguration // Parse converts FeatureFlagConfigurations into a list of // FeatureFlagBundleParsed. The difference being, tag (key, value) pairs are // represented as []byte in the FeatureFlagBundleParsed. The bytes are used to // match against metric ids for applying feature flags. func (f FeatureFlagConfigurations) Parse() []FeatureFlagBundleParsed { result := make([]FeatureFlagBundleParsed, 0, len(f)) for _, elem := range f { parsed := elem.parse() result = append(result, parsed) } return result } // FeatureFlagConfiguration holds filter and flag combinations. The flags are // scoped to metrics with tags that match the filter. type FeatureFlagConfiguration struct { // Flags are the flags enabled once the filters are matched. Flags FlagBundle `yaml:"flags"` // Filter is a map of tag keys and values that much match for the flags to // be applied. Filter map[string]string `yaml:"filter"` } // FlagBundle contains all aggregator feature flags. // nolint:gofumpt type FlagBundle struct { } func (f FeatureFlagConfiguration) parse() FeatureFlagBundleParsed { parsed := FeatureFlagBundleParsed{ flags: f.Flags, serializedTagMatchers: make([][]byte, 0, len(f.Filter)), } for key, value := range f.Filter { var ( byteOrder = binary.LittleEndian buff = make([]byte, 2) tagFilterBytes []byte ) // Add key bytes. byteOrder.PutUint16(buff[:2], uint16(len(key))) tagFilterBytes = append(tagFilterBytes, buff[:2]...) tagFilterBytes = append(tagFilterBytes, []byte(key)...) // Add value bytes. byteOrder.PutUint16(buff[:2], uint16(len(value))) tagFilterBytes = append(tagFilterBytes, buff[:2]...) tagFilterBytes = append(tagFilterBytes, []byte(value)...) parsed.serializedTagMatchers = append(parsed.serializedTagMatchers, tagFilterBytes) } return parsed } // FeatureFlagBundleParsed is a parsed feature flag bundle. type FeatureFlagBundleParsed struct { flags FlagBundle serializedTagMatchers [][]byte } // Match matches the given byte string with all filters for the // parsed feature flag bundle. func (f FeatureFlagBundleParsed) Match(metricID []byte) (FlagBundle, bool) { for _, val := range f.serializedTagMatchers { if !bytes.Contains(metricID, val) { return FlagBundle{}, false } } return f.flags, true }
go
14
0.738915
85
34.252427
103
starcoderdata
#include #include #include #include #include #include #include template <typename DataType> static void multiply_TNT(benchmark::State& state, int size) { while (state.KeepRunning()) { state.PauseTiming(); // We don't count tensor creation tnt::Shape shape{size, size}; tnt::Tensor left(shape, 3.f); tnt::Tensor right(shape, 4.f); state.ResumeTiming(); tnt::multiply(left, right); } } template <typename DataType> static void multiply_OCV(benchmark::State& state, int size) { while (state.KeepRunning()) { state.PauseTiming(); cv::Mat left = tnt::create_cv_mat size, cv::Scalar(3)); cv::Mat right = tnt::create_cv_mat size, cv::Scalar(4)); state.ResumeTiming(); cv::Mat dst = left * right; } } template <typename DataType> static void multiply_EIG(benchmark::State& state, int size) { using MatType = Eigen::Matrix<DataType, Eigen::Dynamic, Eigen::Dynamic>; while (state.KeepRunning()) { state.PauseTiming(); MatType left = MatType::Constant(size, size, 3); MatType right = MatType::Constant(size, size, 4); state.ResumeTiming(); MatType dst = left * right; } } template <typename DataType> struct BLASMultiply {}; template <> struct BLASMultiply { static void run(int size, float* left, float* right, float* dst) { /* See https://www.christophlassner.de/using-blas-from-c-with-row-major-data.html */ /* For trick to use fortran order (col-major) */ cblas_sgemm(CblasColMajor, /* Memory order */ CblasNoTrans, /* Left is transposed? */ CblasNoTrans, /* Right is transposed? */ size, /* Rows of left */ size, /* Columns of right */ size, /* Columns of left and rows of right */ 1., /* Alpha (scale after mult) */ right, /* Left data */ size, /* lda, this is really for 2D mats */ left, /* right data */ size, /* ldb, this is really for 2D mats */ 0., /* beta (scale on result before addition) */ dst, /* result data */ size); /* ldc, this is really for 2D mats */ } }; template <> struct BLASMultiply { static void run(int size, double* left, double* right, double* dst) { /* See https://www.christophlassner.de/using-blas-from-c-with-row-major-data.html */ /* For trick to use fortran order (col-major) */ cblas_dgemm(CblasColMajor, /* Memory order */ CblasNoTrans, /* Left is transposed? */ CblasNoTrans, /* Right is transposed? */ size, /* Rows of left */ size, /* Columns of right */ size, /* Columns of left and rows of right */ 1., /* Alpha (scale after mult) */ right, /* Left data */ size, /* lda, this is really for 2D mats */ left, /* right data */ size, /* ldb, this is really for 2D mats */ 0., /* beta (scale on result before addition) */ dst, /* result data */ size); /* ldc, this is really for 2D mats */ } }; template <typename DataType> static void multiply_BLAS(benchmark::State& state, int size) { while (state.KeepRunning()) { state.PauseTiming(); DataType* left = new DataType[size * size]; DataType* right = new DataType[size * size]; for (int i = 0; i < size * size; ++i) { left[i] = 3; right[i] = 4; } state.ResumeTiming(); // For fairness allocation happens during timing DataType* dst = new DataType[size * size]; BLASMultiply left, right, dst); } } template <typename T> class RegisterMatrixMultiplyBenchmark { public: RegisterMatrixMultiplyBenchmark(const std::string& type) { std::vector sizes{4, 16, 64, 512, 2048, 3121}; for (int size : sizes) { std::string suffix = type + ">[" + std::to_string(size) + "x" + std::to_string(size) + "]"; benchmark::RegisterBenchmark(("MatrixMultiply:TNT <" + suffix).c_str(), multiply_TNT size); benchmark::RegisterBenchmark(("MatrixMultiply:OCV <" + suffix).c_str(), multiply_OCV size); benchmark::RegisterBenchmark(("MatrixMultiply:EIG <" + suffix).c_str(), multiply_EIG size); benchmark::RegisterBenchmark(("MatrixMultiply:BLAS<" + suffix).c_str(), multiply_BLAS size); } } }; //static RegisterMultiplyBenchmark multiply_benchmark_int("int"); static RegisterMatrixMultiplyBenchmark matrix_multiply_benchmark_float("float"); static RegisterMatrixMultiplyBenchmark matrix_multiply_benchmark_double("double");
c++
16
0.554285
108
35.966443
149
starcoderdata
func TransactionUpdate(c *gin.Context) { // userId := c.GetString("user_id") db, _ := c.Get("db") conn := db.(pgx.Conn) transactionSent := models.Transaction{} err := c.ShouldBindJSON(&transactionSent) if err != nil { fmt.Println(err) c.JSON(http.StatusBadRequest, gin.H{ "error": "Invalid form sent", }) return } transactionBeginUpdated, err := models.FindTransactionById(transactionSent.ID, &conn) if err != nil { c.JSON(http.StatusBadRequest, gin.H{ "error": err.Error(), }) return } // Display uuid in response transactionSent.AccountId = transactionBeginUpdated.AccountId transactionSent.TransactionTypeId = transactionBeginUpdated.TransactionTypeId err = transactionSent.Update(&conn) if err != nil { c.JSON(http.StatusBadRequest, gin.H{ "error": err.Error(), }) return } c.JSON(http.StatusOK, gin.H{"data": transactionSent}) }
go
14
0.697964
86
22.918919
37
inline
package android.support.v4.p003a; import android.os.Parcel; import android.os.Parcelable; import android.os.Parcelable.Creator; /* renamed from: android.support.v4.a.am */ final class am implements Parcelable { public static final Creator CREATOR; ao[] f139a; int[] f140b; C0038p[] f141c; static { CREATOR = new an(); } public am(Parcel parcel) { this.f139a = (ao[]) parcel.createTypedArray(ao.CREATOR); this.f140b = parcel.createIntArray(); this.f141c = (C0038p[]) parcel.createTypedArray(C0038p.CREATOR); } public int describeContents() { return 0; } public void writeToParcel(Parcel parcel, int i) { parcel.writeTypedArray(this.f139a, i); parcel.writeIntArray(this.f140b); parcel.writeTypedArray(this.f141c, i); } }
java
11
0.660592
72
24.823529
34
starcoderdata
/* * Copyright (c) 2017 DtDream Technology Co.,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef EXTEND_TABLE_H #define EXTEND_TABLE_H 1 #define MAX_EXT_TABLE_ID 65535 #define EXT_TABLE_ID_INVALID 0 #include "openvswitch/hmap.h" #include "openvswitch/list.h" #include "openvswitch/uuid.h" /* Used to manage expansion tables associated with Flow table, * such as the Group Table or Meter Table. */ struct ovn_extend_table { unsigned long *table_ids; /* Used as a bitmap with value set * for allocated group ids in either * desired or existing. */ struct hmap desired; struct hmap existing; }; struct ovn_extend_table_info { struct hmap_node hmap_node; char *name; /* Name for the table entity. */ struct uuid lflow_uuid; uint32_t table_id; bool new_table_id; /* 'True' if 'table_id' was reserved from * ovn_extend_table's 'table_ids' bitmap. */ }; void ovn_extend_table_init(struct ovn_extend_table *); void ovn_extend_table_destroy(struct ovn_extend_table *); struct ovn_extend_table_info *ovn_extend_table_lookup( struct hmap *, const struct ovn_extend_table_info *); void ovn_extend_table_clear(struct ovn_extend_table *, bool); void ovn_extend_table_remove_existing(struct ovn_extend_table *, struct ovn_extend_table_info *); void ovn_extend_table_remove_desired(struct ovn_extend_table *, const struct uuid *lflow_uuid); /* Copy the contents of desired to existing. */ void ovn_extend_table_sync(struct ovn_extend_table *); uint32_t ovn_extend_table_assign_id(struct ovn_extend_table *, const char *name, struct uuid lflow_uuid); /* Iterates 'DESIRED' through all of the 'ovn_extend_table_info's in * 'TABLE'->desired that are not in 'TABLE'->existing. (The loop body * presumably adds them.) */ #define EXTEND_TABLE_FOR_EACH_UNINSTALLED(DESIRED, TABLE) \ HMAP_FOR_EACH (DESIRED, hmap_node, &(TABLE)->desired) \ if (!ovn_extend_table_lookup(&(TABLE)->existing, DESIRED)) /* Iterates 'EXISTING' through all of the 'ovn_extend_table_info's in * 'TABLE'->existing that are not in 'TABLE'->desired. (The loop body * presumably removes them.) */ #define EXTEND_TABLE_FOR_EACH_INSTALLED(EXISTING, NEXT, TABLE) \ HMAP_FOR_EACH_SAFE (EXISTING, NEXT, hmap_node, &(TABLE)->existing) \ if (!ovn_extend_table_lookup(&(TABLE)->desired, EXISTING)) #endif /* lib/extend-table.h */
c
8
0.657626
75
37.219512
82
starcoderdata
<?php namespace App\CommandBus; use App\Aggregates\Commands\Command; class CommandBus { public function handle(Command $command) { } }
php
8
0.7
44
11.5
12
starcoderdata
"""Create a toolbar windows.""" import logging from functools import partial import yaml from PySide2 import QtCore, QtWidgets import ftd.tools.prefs import ftd.ui.layout import ftd.ui.widget import ftd.ui.window __all__ = ["show", "Window"] LOG = logging.getLogger(__name__) def show(path): """Show the marking menu.""" widget = Window(path) widget.show() widget.dock_to("Outliner", "left") return widget class Window(ftd.ui.window.Dockable): """Main window for the toolbar.""" name = "toolbar" def __init__(self, path): super(Window, self).__init__() self._config = path self.populate() def setup(self): self.setMinimumWidth(137) # Widget widgets = { "tab": QtWidgets.QTabWidget(), "tabs_menu": QtWidgets.QMenu(), "tabs": ftd.ui.widget.IconButton(), "reload": ftd.ui.widget.IconButton(), "settings": ftd.ui.widget.IconButton(), } # Header icons for key in ("tabs", "reload", "settings"): icon = ftd.ui.utility.find_icon(key + ".svg", qt=True) widgets[key].setIcon(icon) widgets[key].setIconSize(QtCore.QSize(17, 17)) button = QtCore.Qt.MouseButton.LeftButton widgets["tabs"].setMenu(widgets["tabs_menu"], button) widgets["reload"].clicked.connect(self.populate) self.widgets = widgets # Layout layouts = { "main": QtWidgets.QVBoxLayout(self), "header": QtWidgets.QHBoxLayout(), } layouts["header"].setContentsMargins(5, 5, 5, 5) layouts["header"].setSpacing(5) layouts["header"].addWidget(widgets["tabs"]) layouts["header"].addStretch() layouts["header"].addWidget(widgets["reload"]) layouts["header"].addWidget(widgets["settings"]) layouts["main"].setContentsMargins(0, 0, 0, 0) layouts["main"].setSpacing(0) layouts["main"].addLayout(layouts["header"]) layouts["main"].addWidget(widgets["tab"]) def populate(self): """Populate the toolbar with the registered tabs.""" self.widgets["tab"].clear() self.widgets["tabs_menu"].clear() with open(self._config, "r") as stream: config = yaml.load(stream, Loader=yaml.FullLoader) ftd.tools.prefs.load_commands(config) for tab, data in config["toolbar"].items(): widget = Tab(data) action = partial(self.widgets["tab"].setCurrentWidget, widget) self.widgets["tab"].addTab(widget, tab) self.widgets["tabs_menu"].addAction(tab, action) class Tab(QtWidgets.QScrollArea): """Custom QScrollArea for the toolbar tabs.""" def __init__(self, data, parent=None): super(Tab, self).__init__(parent=parent) self.data = data self.setWidgetResizable(True) self.setStyle(QtWidgets.QStyleFactory.create("fusion")) widget = QtWidgets.QWidget() self.setWidget(widget) self._layout = QtWidgets.QVBoxLayout(widget) self._layout.setContentsMargins(0, 0, 0, 0) self._layout.setSpacing(0) self.populate() self._layout.addStretch() def populate(self): """Populate the widget.""" for data in self.data: widget = Category(data["name"], data) self._layout.addWidget(widget) class Category(ftd.ui.widget.FrameBox): """Custom widget for the toolbar categories.""" def __init__(self, title, data, parent=None): super(Category, self).__init__(title, parent=parent) self.data = data widget = QtWidgets.QWidget() self.setWidget(widget) self._layout = ftd.ui.layout.Flow() widget.setLayout(self._layout) self._layout.setContentsMargins(1, 5, 1, 5) self._layout.setSpacing(1) self.populate() self.setState(data.get("visible", True)) def populate(self): """Populate the widget.""" for data in self.data["children"]: widget = Command(data) self._layout.addWidget(widget) class Command(ftd.ui.widget.IconButton): """Custom widget for toolbar button.""" css2 = """ QLabel { background-color: rgba(0, 0, 0, 0.5); color: rgba(255, 255, 255, 0.8); font-size: 10px; border-radius: 3px; } """ def __init__(self, data, parent=None): super(Command, self).__init__(parent=parent) cmd = ftd.tools.prefs.Command.get(data["command"]) self.setStyleSheet(self.css + self.css2) self.setToolTip(cmd.description or cmd.name) self.clicked.connect(cmd.execute) # Icon icon = ftd.ui.utility.find_icon( cmd.icon or "commandButton.png", qt=True ) self.setIcon(icon) size = QtCore.QSize(38, 38) self.setMinimumSize(size) self.setMaximumSize(size) self.setIconSize(size * 0.9) # Text if data.get("label"): layout = QtWidgets.QVBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) label = QtWidgets.QLabel(cmd.short) label.setAlignment(QtCore.Qt.AlignCenter) layout.addStretch() layout.addWidget(label) # Menu menu = QtWidgets.QMenu() self.setMenu(menu) for option in data.get("options", {}): if "divider" in option: menu.addSeparator() continue cmd_ = ftd.tools.prefs.Command.get(option["command"]) name = "options" if "options" in cmd_.tags else cmd_.long menu.addAction(name, cmd_.execute)
python
14
0.582202
74
28.851282
195
starcoderdata
import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; abstract class Constraint<ConstraintType extends Constraint { protected abstract Stream evStream(); private void foo(final Set ctrlSTCs, final Set probCstrs) { ArrayList a = new ArrayList .concat(ctrlSTCs.stream(), probCstrs.stream()) .flatMap(Constraint::evStream) .collect(Collectors.toSet())); } private abstract class CConstraint extends Constraint implements I {} private abstract class BConstraint extends Constraint implements I {} interface I {} interface Event {} }
java
15
0.622248
94
34.958333
24
starcoderdata
import cn.jiguang.common.resp.APIConnectionException; import cn.jiguang.common.resp.APIRequestException; import cn.jpush.api.JPushClient; import cn.jpush.api.push.PushResult; import cn.jpush.api.push.model.Platform; import cn.jpush.api.push.model.PushPayload; import cn.jpush.api.push.model.audience.Audience; import cn.jpush.api.push.model.audience.AudienceTarget; import cn.jpush.api.push.model.notification.Notification; import java.util.HashMap; import java.util.Map; public class SendSimpleSample { public static void main(String[] args) throws APIConnectionException, APIRequestException { String appkey = args[0]; String secret = args[1]; String registrationId = args[2]; JPushClient jpushClient = new JPushClient(secret, appkey); AudienceTarget target = AudienceTarget.registrationId(registrationId); Audience audience = Audience.newBuilder() .addAudienceTarget(target) .build(); Map<String, String> extras = new HashMap<>(); extras.put("key1", "val1"); extras.put("key2", "val2"); PushPayload payload = PushPayload.newBuilder() .setPlatform(Platform.android()) .setAudience(audience) .setNotification(Notification.android("**alert:1**", "*Simple*Title", extras)) .build(); PushResult result = jpushClient.sendPush(payload); System.out.println(result); } }
java
14
0.679783
95
34.095238
42
starcoderdata
/* * Copyright 2016-present Facebook, 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 com.facebook.buck.doctor; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintStream; import java.util.List; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; /** Helper methods for handling input from the user. */ public class UserInput { private static final Pattern RANGE_OR_NUMBER = Pattern.compile("((? private static final Pattern NUMBER = Pattern.compile("(? private final PrintStream output; private final BufferedReader reader; public UserInput(PrintStream output, BufferedReader inputReader) { this.output = output; this.reader = inputReader; } public String ask(String question) throws IOException { output.println(); output.println(question); output.flush(); return reader.readLine(); } public boolean confirm(String question) throws IOException { ImmutableMap<String, Boolean> supportedResponses = ImmutableMap.of( "", true, "y", true, "n", false); for (; ; ) { output.println(); output.println(question + " (Y/n)?"); output.flush(); String line = reader.readLine(); // Stdin was closed. if (line == null) { return false; } String response = line.trim().toLowerCase(); if (supportedResponses.containsKey(response)) { return supportedResponses.get(response); } else { output.println("Please answer 'y' or 'n'."); } } } public static Integer parseOne(String input) { Matcher matcher = NUMBER.matcher(input); Preconditions.checkArgument(matcher.matches(), "Malformed entry %s.", input); return Integer.parseInt(input); } public static ImmutableSet parseRange(String input) { ImmutableSet.Builder result = ImmutableSet.builder(); String[] elements = input.split("[, ]+"); for (String element : elements) { Matcher matcher = RANGE_OR_NUMBER.matcher(element); Preconditions.checkArgument(matcher.matches(), "Malformed entry %s.", element); String numberString = matcher.group("num"); String rangeLowString = matcher.group("rangelo"); String rangeHighString = matcher.group("rangehi"); Preconditions.checkArgument( numberString != null || rangeHighString != null, "Malformed entry %s.", element); if (numberString != null) { result.add(Integer.parseInt(numberString)); } else { int rangeLow = Integer.parseInt(rangeLowString); int rangeHigh = Integer.parseInt(rangeHighString); for (int i = Math.min(rangeLow, rangeHigh); i <= Math.max(rangeLow, rangeHigh); ++i) { result.add(i); } } } return result.build(); } public Optional selectOne( String prompt, List entries, Function<T, String> entryFormatter) throws IOException { Preconditions.checkArgument(entries.size() > 0); output.println(); output.println(prompt); output.println(); for (int i = 0; i < entries.size(); i++) { output.printf("[%d]. %s.\n", i, entryFormatter.apply(entries.get(i))); } Integer index = 0; try { String response = ask("(input individual number, for example 1 or 2)"); if (response.trim().isEmpty()) { index = 0; } else { index = parseOne(response); } Preconditions.checkArgument( index >= 0 && index < entries.size(), "Index %s out of bounds.", index); } catch (IllegalArgumentException e) { output.printf("Illegal choice: %s\n", e.getMessage()); return Optional.empty(); } return Optional.of(entries.get(index)); } public ImmutableSet selectRange( String prompt, List entries, Function<T, String> entryFormatter) throws IOException { Preconditions.checkArgument(entries.size() > 0); output.println(); output.println(prompt); output.println(); for (int i = 0; i < entries.size(); i++) { output.printf("[%d]. %s.\n", i, entryFormatter.apply(entries.get(i))); } ImmutableSet buildIndexes; for (; ; ) { try { String response = ask("(input individual numbers or ranges, for example 1,2,3-9)"); if (response.trim().isEmpty()) { buildIndexes = ImmutableSet.of(0); } else { buildIndexes = parseRange(response); } for (Integer index : buildIndexes) { Preconditions.checkArgument( index >= 0 && index < entries.size(), "Index %s out of bounds.", index); } break; } catch (IllegalArgumentException e) { output.printf("Illegal range %s.\n", e.getMessage()); } } ImmutableSet.Builder result = ImmutableSet.builder(); for (Integer index : buildIndexes) { result.add(entries.get(index)); } return result.build(); } }
java
18
0.642622
94
32.143678
174
starcoderdata
import chai from 'chai'; import * as slimdom from 'slimdom'; import jsonMlMapper from 'test-helpers/jsonMlMapper'; import { evaluateXPathToNodes } from 'fontoxpath'; let documentNode; beforeEach(() => { documentNode = new slimdom.Document(); }); describe('descendant', () => { it('parses descendant::', () => { jsonMlMapper.parse([ 'someParentElement', ['someElement'] ], documentNode); chai.assert.deepEqual(evaluateXPathToNodes('descendant::someElement', documentNode), [documentNode.firstChild.firstChild]); }); }); describe('descendant-or-self', () => { it('descendant part', () => { jsonMlMapper.parse([ 'someParentElement', ['someElement'] ], documentNode); chai.assert.deepEqual(evaluateXPathToNodes('descendant-or-self::someElement', documentNode.documentElement), [documentNode.documentElement.firstChild]); }); it('self part', () => { jsonMlMapper.parse([ 'someParentElement', ['someElement'] ], documentNode); chai.assert.deepEqual(evaluateXPathToNodes('descendant-or-self::someParentElement', documentNode.documentElement), [documentNode.documentElement]); }); it('ordering of siblings', () => { jsonMlMapper.parse([ 'someParentElement', ['someElement'] ], documentNode); chai.assert.deepEqual(evaluateXPathToNodes('descendant-or-self::*', documentNode.documentElement), [documentNode.documentElement, documentNode.documentElement.firstChild]); }); it('ordering of deeper descendants', () => { jsonMlMapper.parse([ 'someParentElement', ['someElement', ['someElement', ['someElement']]] ], documentNode); chai.assert.deepEqual( evaluateXPathToNodes('descendant-or-self::*', documentNode.documentElement), [ documentNode.documentElement, documentNode.documentElement.firstChild, documentNode.documentElement.firstChild.firstChild, documentNode.documentElement.firstChild.firstChild.firstChild ] ); }); it('ordering of descendants with complex-ish queries', () => { jsonMlMapper.parse([ 'root', ['a', ['a-a'], ['a-b']], ['b', ['b-a'], ['b-b']] ], documentNode); chai.assert.deepEqual(evaluateXPathToNodes('//*[name() = "root" or name() => starts-with("a") or name() => starts-with("b")]', documentNode).map(node => node.nodeName), ['root', 'a', 'a-a', 'a-b', 'b', 'b-a', 'b-b']); }); it('throws the correct error if context is absent', () => { chai.assert.throws(() => evaluateXPathToNodes('descendant::*', null), 'XPDY0002'); }); });
javascript
18
0.684507
219
30.858974
78
starcoderdata
<?php # -*- coding: utf-8 -*- declare(strict_types=1); namespace Bueltge\Marksimple\Rule; class Header extends AbstractRegexRule { /** * Get the regex rule to identify the fromFile for the callback. * Header h1 - h6. * * @return string */ public function rule(): string { return '#^(\#{1,6})\s*([^\#]+?)\s*\#*$#m'; } /** * {@inheritdoc} */ public function render(array $content): string { $headingLevel = \strlen($content[1]); $header = trim($content[2]); // Build anker without space, numbers. $anker = preg_replace('#[^a-z?!]#', '', strtolower($header)); return sprintf('<h%d id="%s">%s $headingLevel, $anker, $header, $headingLevel); } }
php
14
0.539662
95
23.03125
32
starcoderdata
import configparser SETTINGS_FILE = 'settings.ini' DIR_SPRITES = "assets/sprites" DIR_LEVELS = "assets/levels" class GlobalSettings(): TARGET_FPS = 0 # 0 unlimited SCREEN_WIDTH = 1024 SCREEN_HEIGHT = 768 config = configparser.ConfigParser() def __init__(self): self.load_settings_from_file() def load_settings_from_file(self): self.config.read(SETTINGS_FILE) self.TARGET_FPS = int(self.config.get('Basic Game Settings', 'TARGET_FPS')) self.SCREEN_WIDTH = int(self.config.get('Basic Game Settings', 'SCREEN_WIDTH')) self.SCREEN_HEIGHT = int(self.config.get('Basic Game Settings', 'SCREEN_HEIGHT')) def save_settings_to_file(self): with open(SETTINGS_FILE, 'r') as setting_file: self.config.write(setting_file)
python
12
0.64799
89
28.357143
28
starcoderdata
 using FlyBirdYoYo.Utilities.SystemEnum; namespace FlyBirdYoYo.Utilities.Interface { public interface IBaseLoginViewModel { LoginTypeEnum LoginType { get; set; } /// /// 归属的平台 /// PlatformEnum Platform { get; set; } /// /// 用户id /// long UserId { get; set; } /// /// 登录账号 /// string UserName { get; set; } /// /// 用户店铺id /// string ShopId { get; set; } /// ///店铺名称 /// string ShopName { get; set; } bool IsValid(out string msg); } }
c#
8
0.482188
45
16.886364
44
starcoderdata
;(function () { 'use strict'; angular .module('app.adpCommon') .component('adpConfirmDialogModal', { templateUrl: 'app/adp-common/directives/adp-confirm-dialog-modal/adp-confirm-dialog-modal.html', bindings: { resolve: '<', close: '&', dismiss: '&' }, controller: 'AdpConfirmDialogModalController', controllerAs: 'vm' }); })();
javascript
14
0.585427
102
23.9375
16
starcoderdata
package engine; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import com.amazonaws.services.lambda.runtime.Context; import environment.EnvConstants; public class SqlConnector { private static final String jdbcUrl; private static String db_name; private static String username; private static String password; static { db_name = EnvConstants.env.getDatabase(); username = EnvConstants.env.getUser(); password = EnvConstants.env.getPassword(); jdbcUrl = "jdbc:mysql://" + EnvConstants.env.getHost() + ":" + EnvConstants.env.getPort() + "/" + db_name; } private Connection connection; private static SqlConnector INSTANCE; public static synchronized SqlConnector getInstance(Context context) throws Exception { if (INSTANCE == null) INSTANCE = new SqlConnector(context); return INSTANCE; } public synchronized Connection getRestoreConnection() throws SQLException { if (connection.isClosed()) connection = DriverManager.getConnection(jdbcUrl, username, password); return connection; } private SqlConnector(Context context) throws Exception { try { context.getLogger().log("connecting to db.."); String driver = "com.mysql.jdbc.Driver"; Class.forName(driver).newInstance(); connection = DriverManager.getConnection(jdbcUrl, username, password); context.getLogger().log("successfully connected!"); } catch (Exception e) { e.printStackTrace(); throw new Exception("username: " + username + ". password: " + password + ". jdbcUrl: " + jdbcUrl + ". " + e.getMessage()); } } }
java
17
0.737028
108
27.762712
59
starcoderdata
private void createConfig() { try { // Check if the "MaintenanceAnnouncer" directory exists. if (getDataFolder().exists() == false) { getDataFolder().mkdirs(); // Make directory using the built-in bukkit function. } File file = new File(getDataFolder(), "config.yml"); // Introduce the new file, specify the directory and file name. // Check if the config file actually exists. if (file.exists() == false) { getLogger().info("Config file not found! Creating one!"); // Log that a config file is being made. saveDefaultConfig(); // Use the save default bukkit function. } else { getLogger().info("Config file found! Loaded!"); } } catch (Exception e) { e.printStackTrace(); } }
java
11
0.645722
119
35.5
20
inline
package com.prohelion.service.impl; import java.util.ArrayList; import java.util.List; import org.apache.commons.collections4.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.prohelion.dao.DeviceRepository; import com.prohelion.model.Device; import com.prohelion.service.DeviceService; @Service public class DeviceServiceImpl implements DeviceService { @Autowired private DeviceRepository deviceRepository; @Override @Transactional(readOnly = true) @Cacheable("devices") public List getDevices() { List targetCollection = new ArrayList CollectionUtils.addAll(targetCollection, deviceRepository.findAll().iterator()); return targetCollection; } }
java
11
0.753049
88
29.741935
31
starcoderdata