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
class Binary { /// destruction will close the library and invalidate /// any function pointers returned by lookupSymbol() protected : std::string _binaryPath; bool _invalid; #if defined(UNIX) void *_dlHandle; #elif defined (WINDOWS) HINSTANCE _dlHandle; #endif time_t _time; off_t _size; int _users; public : /// create object representing the binary. will stat() it, /// and this fails, will set binary to be invalid. Binary(const std::string &binaryPath); ~Binary() { unload(); } bool isLoaded() const { return _dlHandle != 0; } /// is this binary invalid? (did the a stat() or load() on the file fail, /// or are we missing a some of the symbols? bool isInvalid() const { return _invalid; } /// set invalid status (e.g. called by user if a mandatory symbol was missing) void setInvalid(bool invalid) { _invalid = invalid; } /// Last modification time of the file. time_t getTime() const { return _time; } /// Current size of the file. off_t getSize() const { return _size; } /// Path to the file. const std::string &getBinaryPath() const { return _binaryPath; } void ref(); void unref(); /// open the binary. void load(); /// close the binary void unload(); /// look up a symbol in the binary file and return it as a pointer. /// returns null pointer if not found, or if the library is not loaded. void *findSymbol(const std::string &symbol); }
c
9
0.632735
82
27.377358
53
inline
import bs4 # ---------------------------------------------------------------------- # # HTML handling functions # # ---------------------------------------------------------------------- def soup(content: str): return bs4.BeautifulSoup(content, 'lxml')
python
7
0.306513
72
20.75
12
starcoderdata
@Override public Stage connect(Pipeline pipeline, ByteBuffer inputBuffer, ByteBuffer outputBuffer) { if (usesSsl()) { ByteBuffer decryptedInputBuffer = ByteBuffer.allocate(32768); ByteBuffer decryptedOutputBuffer = ByteBuffer.allocate(32768); decryptedInputBuffer.clear(); decryptedInputBuffer.flip(); // prepare for reading decryptedOutputBuffer.clear(); decryptedOutputBuffer.flip(); // prepare for reading HttpClientStage httpStage = new HttpClientStage( pipeline, request, responseHandler, decryptedInputBuffer, decryptedOutputBuffer); SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setSSLParameters(sslParameters); return new SslClientStage( pipeline, httpStage, sslEngine, inputBuffer, outputBuffer, decryptedInputBuffer, decryptedOutputBuffer); } else { return new HttpClientStage( pipeline, request, responseHandler, inputBuffer, outputBuffer); } }
java
9
0.643811
92
32.058824
34
inline
def reach_position(self, lat, lon, alt, timeout, index): # reset best distances self.last_alt_d = 9999 self.last_pos_d = 9999 rospy.loginfo("trying to reach waypoint " + "lat: %13.9f, lon: %13.9f, alt: %6.2f, timeout: %d, index: %d" % (lat, lon, alt, timeout, index)) # does it reach the position in X seconds? count = 0 while count < timeout: # use MC radius by default # FIXME: also check MAV_TYPE from system status, otherwise pure fixed-wing won't work xy_radius = self.mc_rad z_radius = self.mc_rad # use FW radius if in FW or in transition if (self.extended_state.vtol_state == ExtendedState.VTOL_STATE_FW or self.extended_state.vtol_state == ExtendedState.VTOL_STATE_TRANSITION_TO_MC or self.extended_state.vtol_state == ExtendedState.VTOL_STATE_TRANSITION_TO_FW): xy_radius = self.fw_rad z_radius = self.fw_alt_rad if self.is_at_position(lat, lon, alt, xy_radius, z_radius): rospy.loginfo("position reached, index: %d, count: %d, pos_d: %f, alt_d: %f" % (index, count, self.last_pos_d, self.last_alt_d)) break count = count + 1 self.rate.sleep() vtol_state_string = "VTOL undefined" if (self.extended_state.vtol_state == ExtendedState.VTOL_STATE_MC): vtol_state_string = "VTOL MC" if (self.extended_state.vtol_state == ExtendedState.VTOL_STATE_FW): vtol_state_string = "VTOL FW" if (self.extended_state.vtol_state == ExtendedState.VTOL_STATE_TRANSITION_TO_MC): vtol_state_string = "VTOL FW->MC" if (self.extended_state.vtol_state == ExtendedState.VTOL_STATE_TRANSITION_TO_FW): vtol_state_string = "VTOL MC->FW" self.assertTrue(count < timeout, (("(%s) took too long to get to position " + "lat: %13.9f, lon: %13.9f, alt: %6.2f, xy off: %f, z off: %f, timeout: %d, index: %d, pos_d: %f, alt_d: %f, VTOL state: %s") % (self.mission_name, lat, lon, alt, xy_radius, z_radius, timeout, index, self.last_pos_d, self.last_alt_d, vtol_state_string)))
python
13
0.572489
138
48.804348
46
inline
void heap_insert(struct Heap* h, Node node) { int d = h->d; // Realloc heap if it's full if (h->n == h->sz) { // increase size by power of 2 h->sz <<= 1; h->nodes = (Node*) realloc(h->nodes, sizeof(Node) * h->sz); if (!h->nodes) exit(1); } // insert vertex into right place in heap unsigned int curr, parent; curr = h->n++; while (curr > 0) { // parent's index is floor of (curr-1)/d parent = (curr - 1)/d; // found where it fits if ((h->nodes[parent]).min_edge <= node.min_edge) break; // swap nodes h->nodes[curr] = h->nodes[parent]; h->pos[(h->nodes[parent]).id] = curr; curr = parent; } h->nodes[curr] = node; h->pos[node.id] = curr; }
c
13
0.482209
67
22.314286
35
inline
load("e2371540d876710daf38e749390aa2a3.js"); description( 'Test prototypes of various objects and the various means to access them.' ); shouldBe("('').__proto__", "String.prototype"); shouldBe("(0).__proto__", "Number.prototype"); shouldBe("(true).__proto__", "Boolean.prototype"); shouldBe("(Symbol()).__proto__", "Symbol.prototype"); shouldBe("([]).__proto__", "Array.prototype"); shouldBe("({}).__proto__", "Object.prototype"); shouldBe("(new Date).__proto__", "Date.prototype"); shouldBe("(new Error).__proto__", "Error.prototype"); shouldBe("(new Number).__proto__", "Number.prototype"); shouldBe("(new Object).__proto__", "Object.prototype"); shouldBe("(new String).__proto__", "String.prototype"); shouldBe("Array.prototype.__proto__", "Object.prototype"); shouldBe("Date.prototype.__proto__", "Object.prototype"); shouldBe("Number.prototype.__proto__", "Object.prototype"); shouldBe("Object.prototype.__proto__", "null"); shouldBe("String.prototype.__proto__", "Object.prototype"); shouldBe("Array.__proto__", "Object.__proto__"); shouldBe("Date.__proto__", "Object.__proto__"); shouldBe("Number.__proto__", "Object.__proto__"); shouldBe("String.__proto__", "Object.__proto__"); shouldBe("Object.getPrototypeOf('')", "String.prototype"); shouldBe("Object.getPrototypeOf(0)", "Number.prototype"); shouldBe("Object.getPrototypeOf(true)", "Boolean.prototype"); shouldBe("Object.getPrototypeOf(Symbol())", "Symbol.prototype"); shouldBe("Object.getPrototypeOf([])", "Array.prototype"); shouldBe("Object.getPrototypeOf({})", "Object.prototype"); shouldBe("Object.getPrototypeOf(new Date)", "Date.prototype"); shouldBe("Object.getPrototypeOf(new Error)", "Error.prototype"); shouldBe("Object.getPrototypeOf(new Number)", "Number.prototype"); shouldBe("Object.getPrototypeOf(new Object)", "Object.prototype"); shouldBe("Object.getPrototypeOf(new String)", "String.prototype"); shouldBe("Object.getPrototypeOf(Array.prototype)", "Object.prototype"); shouldBe("Object.getPrototypeOf(Date.prototype)", "Object.prototype"); shouldBe("Object.getPrototypeOf(Number.prototype)", "Object.prototype"); shouldBe("Object.getPrototypeOf(Object.prototype)", "null"); shouldBe("Object.getPrototypeOf(String.prototype)", "Object.prototype"); shouldBe("Object.getPrototypeOf(Array)", "Object.__proto__"); shouldBe("Object.getPrototypeOf(Date)", "Object.__proto__"); shouldBe("Object.getPrototypeOf(Number)", "Object.__proto__"); shouldBe("Object.getPrototypeOf(String)", "Object.__proto__"); shouldBeFalse("String.prototype.isPrototypeOf('')"); shouldBeFalse("Number.prototype.isPrototypeOf(0)"); shouldBeFalse("Boolean.prototype.isPrototypeOf(true)"); shouldBeFalse("Symbol.prototype.isPrototypeOf(Symbol())"); shouldBeTrue("Array.prototype.isPrototypeOf([])"); shouldBeTrue("Object.prototype.isPrototypeOf({})"); shouldBeTrue("Date.prototype.isPrototypeOf(new Date)"); shouldBeTrue("Error.prototype.isPrototypeOf(new Error)"); shouldBeTrue("Number.prototype.isPrototypeOf(new Number)"); shouldBeTrue("Object.prototype.isPrototypeOf(new Object)"); shouldBeTrue("String.prototype.isPrototypeOf(new String)"); shouldBeTrue("Object.prototype.isPrototypeOf(Array.prototype)"); shouldBeTrue("Object.prototype.isPrototypeOf(Date.prototype)"); shouldBeTrue("Object.prototype.isPrototypeOf(Number.prototype)"); shouldBeTrue("Object.prototype.isPrototypeOf(String.prototype)"); shouldBeTrue("Object.__proto__.isPrototypeOf(Array)"); shouldBeTrue("Object.__proto__.isPrototypeOf(Date)"); shouldBeTrue("Object.__proto__.isPrototypeOf(Number)"); shouldBeTrue("Object.__proto__.isPrototypeOf(String)"); shouldBeTrue("var wasSet = false; var o = { }; o.__defineGetter__(\"__proto__\", function() { wasSet = true }); o.__proto__; wasSet;"); shouldBeTrue("var wasSet = false; var o = { }; o.__defineSetter__(\"__proto__\", function() { wasSet = true }); o.__proto__ = {}; wasSet;"); shouldBeTrue("var wasSet = false; var o = { }; Object.defineProperty(o, \"__proto__\", { \"get\": function() { wasSet = true } }); o.__proto__; wasSet;"); shouldBeFalse("var wasSet = false; var o = { }; Object.defineProperty(o, \"__proto__\", { \"__proto__\": function(x) { wasSet = true } }); o.__proto__ = {}; wasSet;"); // Deleting Object.prototype.__proto__ removes the ability to set the object's prototype. shouldBeTrue("var o = {}; o.__proto__ = { x:true }; o.x"); shouldBeFalse("var o = {}; o.__proto__ = { x:true }; o.hasOwnProperty('__proto__')"); delete Object.prototype.__proto__; shouldBeUndefined("var o = {}; o.__proto__ = { x:true }; o.x"); shouldBeTrue("var o = {}; o.__proto__ = { x:true }; o.hasOwnProperty('__proto__')"); load("cf1a0efae1078faee510f7bda78d4902.js");
javascript
5
0.703122
167
57.0625
80
starcoderdata
namespace Morpeh.Globals { using System.Runtime.CompilerServices; using Unity.IL2CPP.CompilerServices; using UnityEngine; [Il2CppSetOption(Option.NullChecks, false)] [Il2CppSetOption(Option.ArrayBoundsChecks, false)] [Il2CppSetOption(Option.DivideByZeroChecks, false)] [CreateAssetMenu(menuName = "ECS/Globals/Singleton")] public class Singleton : BaseSingleton { public int ID => this.Entity.ID; [MethodImpl(MethodImplOptions.AggressiveInlining)] public ref T AddComponent where T : struct, IComponent => ref this.Entity.AddComponent [MethodImpl(MethodImplOptions.AggressiveInlining)] public ref T AddComponent bool exist) where T : struct, IComponent => ref this.Entity.AddComponent exist); public bool AddComponentFast(in int typeId, in int componentId) => this.Entity.AddComponentFast(typeId, componentId); [MethodImpl(MethodImplOptions.AggressiveInlining)] public ref T GetComponent where T : struct, IComponent => ref this.Entity.GetComponent [MethodImpl(MethodImplOptions.AggressiveInlining)] public ref T GetComponent bool exist) where T : struct, IComponent => ref this.Entity.GetComponent exist); [MethodImpl(MethodImplOptions.AggressiveInlining)] public int GetComponentFast(in int typeId) => this.Entity.GetComponentFast(typeId); [MethodImpl(MethodImplOptions.AggressiveInlining)] public void SetComponent T value) where T : struct, IComponent => this.Entity.SetComponent(in value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool RemoveComponent where T : struct, IComponent => this.Entity.RemoveComponent public bool RemoveComponentFast(int typeId, out int cacheIndex) => this.Entity.RemoveComponentFast(typeId, out cacheIndex); [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Has where T : struct, IComponent => this.Entity.Has } }
c#
10
0.719518
131
53.631579
38
starcoderdata
using System; using System.Collections.Generic; using System.Text; using System.Globalization; namespace UKLib.Survey.Parse { public class LeicaTPS : FixedRVHV { public LeicaTPS(string data) { NumberFormatInfo nfi = new CultureInfo( "en-US", false ).NumberFormat; char[] seperator = new char[1]; seperator[0] = ','; string[] mainSplit = data.Split(seperator); if (mainSplit.Length != 6) return; try { rightValue = Double.Parse(mainSplit[1], nfi); highValue = Double.Parse(mainSplit[2], nfi); altitude = Double.Parse(mainSplit[3], nfi); } catch { altitude = 0; rightValue = 0; highValue = 0; } } } }
c#
17
0.504972
73
24.138889
36
starcoderdata
"""Tentative de modéliser les rôles de l'application sous forme de hiérarchie de classes.""" from __future__ import annotations import enum from abilian.core.entities import Entity from attr import attrib, attrs from sqlalchemy import Column, Enum, ForeignKey, Integer from sqlalchemy.orm import backref, relationship from .profiles import Profile from .unites import OrgUnit class RoleType(enum.Enum): MEMBRE = "Membre" GDL = "Gestionnaire de demande Labster" DIRECTION = "Direction" PORTEUR = "Porteur" ALL = "Administrateur Labster local" CONTACT_DGRTT = "Contact DGRTT" CHEF_DE_BUREAU_DGRTT = "Chef de bureau DGRTT" ALC = "Administrateur Labster central" TYPE_ENUM = [t.value for t in list(RoleType)] @attrs(init=False, these={"type": attrib(), "context": attrib()}, hash=True) class Role(Entity): # __tablename__ = 'role' __indexable__ = False type = Column(Enum(*TYPE_ENUM, name="role_type"), nullable=False) profile_id = Column(Integer, ForeignKey(Profile.id), index=True) profile = relationship( Profile, foreign_keys=[profile_id], backref=backref("roles", cascade="all,delete"), ) context_id = Column(Integer, ForeignKey(OrgUnit.id), index=True) context = relationship( OrgUnit, foreign_keys=[context_id], backref=backref("contexts", cascade="all,delete"), ) # def can(self, action, target): # pass def __unicode__(self): if self.context: return "<{} de la structure: {} ({})>".format( self.type, self.context.nom, self.context.type ) else: return f"
python
13
0.645919
77
26.031746
63
starcoderdata
package wickhamsPlugin.RPG; import java.util.HashMap; public abstract class PlayerLocationSave { public static HashMap<String, Integer> playerLocationHashMap=new HashMap<String, Integer>(); }
java
8
0.810256
93
26.857143
7
starcoderdata
define([ 'jquery', 'backbone', 'hogan', 'youtubePlayer', 'text!templates/playVideo.html' ], function($, Backbone, Hogan, ytPlayer, PlayVideoTemplate) { return Backbone.View.extend({ initialize: function (options) { if(options != null && options.id != undefined) { this.videoId = options.id; } this.playlist = options.playlist; console.log(this.playlist); }, events: { }, playNextVideo: function(context, player) { console.log("End of the video"); //First video of the list finished to play, play next one if(context.playlist.length != 0) { var video = context.playlist.shift(); context.updateTitle(video.attributes.title); player.loadVideoById(video.attributes.videoId); } else { return ; } }, updateTitle: function(title) { $('.titlePlaying').empty(); $('.titlePlaying').append(title); }, render: function () { this.$el.html(Hogan.compile(PlayVideoTemplate).render({ //id: this.videoId })); if(this.playlist.length > 0) { var video = this.playlist.shift(); console.log(video.attributes.videoId); $('.titlePlaying', this.$el).append(video.attributes.title); ytPlayer.playVideo($('#player', this.$el)[0], video.attributes.videoId, this, this.playNextVideo); } else { ytPlayer.playVideo($('#player', this.$el)[0], this.videoId, this, function() {}); } return this; } }); });
javascript
23
0.576801
106
26.051724
58
starcoderdata
/* Copyright (c) Codethink Ltd. All rights reserved. Licensed under the MIT License. */ #include #include #include #include #include "lib/CPUFreq.h" #include "lib/VectorTable.h" #include "lib/NVIC.h" #include "lib/GPIO.h" #include "lib/GPT.h" #include "lib/UART.h" #include "lib/Print.h" #include "lib/ADC.h" #include "joystick.h" static UART *debug = NULL; static GPT *buttonTimeout = NULL; // ADC global variables #define ADC_DATA_SIZE 4 #define ADC_CHANNELS 2 static __attribute__((section(".sysram"))) uint32_t rawData[ADC_DATA_SIZE]; static ADC_Data data[ADC_DATA_SIZE]; static int32_t adcStatus; // Joystick variables #define JOYSTICK_CHANNEL_X 0 #define JOYSTICK_CHANNEL_Y 1 static Joystick_XY joystickValue = {0}; static Joystick *joystick = NULL; static int32_t joystickStatus = ERROR; /* State variable for the joystick finite state machine */ /* Uses joystick direction #defines in joystick.h for calibration phases (0-4) */ int32_t stateFsm = 0; #define DATA_PHASE 5 static void AdcCallback(int32_t status) { adcStatus = status; } static inline void joystickErrCheck(void) { if (joystickStatus == ERROR_JOYSTICK_CAL) { UART_Print(debug, "Error: The joystick value was not as expected, please try again.""\r\n"); } else if (joystickStatus == ERROR_JOYSTICK_NOT_A_DIRECTION) { UART_Print(debug, "Error: The direction passed to Joystick_Cal is not a supported value.""\r\n"); } } static const uint32_t buttonAGpio = 12; static const int buttonPressCheckPeriodMs = 10; static void HandleButtonTimerIrq(GPT *); static void HandleButtonTimerIrqDeferred(); typedef struct CallbackNode { bool enqueued; struct CallbackNode* next; void (*cb)(void); } CallbackNode; static void EnqueueCallback(CallbackNode *node); static void HandleButtonTimerIrq(GPT *handle) { (void)handle; static CallbackNode cbn = { .enqueued = false, .cb = HandleButtonTimerIrqDeferred }; EnqueueCallback(&cbn); } static void HandleButtonTimerIrqDeferred() { // Assume initial state is high, i.e. button not pressed. static bool prevState = true; bool newState; GPIO_Read(buttonAGpio, &newState); if (newState != prevState) { bool pressed = !newState; if (pressed) { switch (stateFsm) { case JOYSTICK_CENTER: joystickStatus = Joystick_Calibrate(joystick, JOYSTICK_CENTER); joystickErrCheck(); break; case JOYSTICK_Y_MAX: joystickStatus = Joystick_Calibrate(joystick, JOYSTICK_Y_MAX); joystickErrCheck(); break; case JOYSTICK_Y_MIN: joystickStatus = Joystick_Calibrate(joystick, JOYSTICK_Y_MIN); joystickErrCheck(); break; case JOYSTICK_X_MAX: joystickStatus = Joystick_Calibrate(joystick, JOYSTICK_X_MAX); joystickErrCheck(); break; case JOYSTICK_X_MIN: joystickStatus = Joystick_Calibrate(joystick, JOYSTICK_X_MIN); joystickErrCheck(); break; case DATA_PHASE: joystickValue = Joystick_GetXY(joystick); UART_Printf(debug, "Joystick V_x = %li%% Joystick V_y = %li%%\r\n", joystickValue.x, joystickValue.y); break; } } prevState = newState; adcStatus = 0; } } static CallbackNode* volatile callbacks = NULL; static void EnqueueCallback(CallbackNode* node) { uint32_t prevBasePri = NVIC_BlockIRQs(); if (!node->enqueued) { CallbackNode* prevHead = callbacks; node->enqueued = true; callbacks = node; node->next = prevHead; } NVIC_RestoreIRQs(prevBasePri); } static void InvokeCallbacks(void) { CallbackNode* node; do { uint32_t prevBasePri = NVIC_BlockIRQs(); node = callbacks; if (node) { node->enqueued = false; callbacks = node->next; } NVIC_RestoreIRQs(prevBasePri); if (node) { (*node->cb)(); } } while (node); } static void JoystickCal(int32_t state) { switch (state) { case JOYSTICK_CENTER: UART_Print(debug, "Please move the joystick to its center position." " When ready press the A button.\r\n"); break; case JOYSTICK_Y_MAX: UART_Print(debug, "Please move the joystick to its maximum extent in the y-direction." " When ready press the A button.\r\n"); break; case JOYSTICK_Y_MIN: UART_Print(debug, "Please move the joystick to its minimum extent in the y-direction." " When ready press the A button.\r\n"); break; case JOYSTICK_X_MAX: UART_Print(debug, "Please move the joystick all the way to the right." " When ready press the A button.\r\n"); break; case JOYSTICK_X_MIN: UART_Print(debug, "Please move the joystick all the way to the left." " When ready press the A button.\r\n"); break; } while (joystickStatus != ERROR_NONE) { __asm__("wfi"); InvokeCallbacks(); } joystickStatus = ERROR; } _Noreturn void RTCoreMain(void) { VectorTableInit(); CPUFreq_Set(26000000); debug = UART_Open(MT3620_UNIT_UART_DEBUG, 115200, UART_PARITY_NONE, 1, NULL); UART_Print(debug, "--------------------------------\r\n"); UART_Print(debug, "ADC_RTApp_MT3620_BareMetal\r\n"); UART_Print(debug, "App built on: " __DATE__ ", " __TIME__ "\r\n"); // Initialise ADC driver and joystick AdcContext* handle = ADC_Open(MT3620_UNIT_ADC0); joystick = Joystick_Open(data, ADC_CHANNELS, JOYSTICK_CHANNEL_X, JOYSTICK_CHANNEL_Y); if (!joystick) { UART_Print(debug, "Error: Failed to initialize joystick\r\n"); } // Start ADC to run periodically ADC_ReadPeriodicAsync(handle, &AdcCallback, ADC_DATA_SIZE, data, rawData, 0x3, 1000, 2500); GPIO_ConfigurePinForInput(buttonAGpio); // Setup GPT1 to poll joystick data on button press if (!(buttonTimeout = GPT_Open(MT3620_UNIT_GPT1, 1000, GPT_MODE_REPEAT))) { UART_Print(debug, "ERROR: Opening timer\r\n"); } int32_t error; if ((error = GPT_StartTimeout(buttonTimeout, buttonPressCheckPeriodMs, GPT_UNITS_MILLISEC, &HandleButtonTimerIrq)) != ERROR_NONE) { UART_Printf(debug, "ERROR: Starting timer (%ld)\r\n", error); } // Calibrate the joystick UART_Print(debug, "The joystick needs to be calibrated before use.\r\n"); stateFsm = JOYSTICK_CENTER; JoystickCal(stateFsm); stateFsm = JOYSTICK_Y_MAX; JoystickCal(stateFsm); stateFsm = JOYSTICK_Y_MIN; JoystickCal(stateFsm); stateFsm = JOYSTICK_X_MAX; JoystickCal(stateFsm); stateFsm = JOYSTICK_X_MIN; JoystickCal(stateFsm); UART_Print(debug, "The joystick is now calibrated, you can now see joystick data by pressing the A button.\r\n"); stateFsm = DATA_PHASE; for (;;) { __asm__("wfi"); InvokeCallbacks(); } }
c
14
0.602435
122
28.772908
251
starcoderdata
int EncoderMD::FixRelocListEntry(uint32 index, int totalBytesSaved, BYTE *buffStart, BYTE* buffEnd) { BYTE* currentPc; EncodeRelocAndLabels &relocRecord = m_relocList->Item(index); int result = totalBytesSaved; // LabelInstr ? if (relocRecord.isLabel()) { BYTE* newPC; currentPc = relocRecord.getLabelCurrPC(); AssertMsg(currentPc >= buffStart && currentPc < buffEnd, "LabelInstr offset has to be within buffer."); newPC = currentPc - totalBytesSaved; // find the number of nops needed to align this loop top if (relocRecord.isAlignedLabel() && !PHASE_OFF(Js::LoopAlignPhase, m_func)) { ptrdiff_t diff = newPC - buffStart; Assert(diff >= 0 && diff <= UINT_MAX); uint32 offset = (uint32)diff; // Since the final code buffer is page aligned, it is enough to align the offset of the label. BYTE nopCount = (16 - (BYTE)(offset & 0xf)) % 16; if (nopCount <= Js::Configuration::Global.flags.LoopAlignNopLimit) { // new label pc newPC += nopCount; relocRecord.setLabelNopCount(nopCount); // adjust bytes saved result -= nopCount; } } relocRecord.setLabelCurrPC(newPC); } else { currentPc = (BYTE*) relocRecord.m_origPtr; // ignore outside buffer offsets (e.g. JumpTable entries) if (currentPc >= buffStart && currentPc < buffEnd) { if (relocRecord.m_type == RelocTypeInlineeEntryOffset) { // ptr points to imm32 offset of the instruction that needs to be adjusted // offset is in top 28-bits, arg count in bottom 4 size_t field = *((size_t*) relocRecord.m_origPtr); size_t offset = field >> 4; uint32 count = field & 0xf; AssertMsg(offset < (size_t)(buffEnd - buffStart), "Inlinee entry offset out of range"); relocRecord.SetInlineOffset(((offset - totalBytesSaved) << 4) | count); } // adjust the ptr to the buffer itself relocRecord.m_ptr = (BYTE*) relocRecord.m_ptr - totalBytesSaved; } } return result; }
c++
18
0.572975
111
38.827586
58
inline
package fr.insee.sabianedata.ws.service; import com.fasterxml.jackson.core.JsonProcessingException; import fr.insee.sabianedata.ws.config.Plateform; import fr.insee.sabianedata.ws.config.QueenProperties; import fr.insee.sabianedata.ws.model.queen.CampaignDto; import fr.insee.sabianedata.ws.model.queen.NomenclatureDto; import fr.insee.sabianedata.ws.model.queen.QuestionnaireModelDto; import fr.insee.sabianedata.ws.model.queen.SurveyUnitDto; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResource; import org.springframework.http.*; import org.springframework.stereotype.Service; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.util.Arrays; @Service public class QueenApiService { private static final Logger LOGGER = LoggerFactory.getLogger(QueenApiService.class); @Autowired QueenProperties queenProperties; @Autowired RestTemplate restTemplate; public ResponseEntity postCampaignToApi(HttpServletRequest request, CampaignDto campaignDto, Plateform plateform) { LOGGER.info("Creating Campaign" + campaignDto.getId()); final String apiUri = queenProperties.getHostFromEnum(plateform) + "/api/campaigns"; HttpHeaders httpHeaders = createSimpleHeadersAuth(request); httpHeaders.setContentType(MediaType.APPLICATION_JSON); return restTemplate.exchange(apiUri, HttpMethod.POST, new HttpEntity<>(campaignDto, httpHeaders), String.class); } public ResponseEntity postUeToApi(HttpServletRequest request, SurveyUnitDto surveyUnitDto, CampaignDto campaignDto, Plateform plateform) throws JsonProcessingException { LOGGER.info("Create SurveyUnit " + surveyUnitDto.getId()); String idCampaign = campaignDto.getId(); final String apiUri = queenProperties.getHostFromEnum(plateform) + "/api/campaign/" + idCampaign + "/survey-unit"; HttpHeaders httpHeaders = createSimpleHeadersAuth(request); httpHeaders.setContentType(MediaType.APPLICATION_JSON); return restTemplate.exchange(apiUri, HttpMethod.POST, new HttpEntity<>(surveyUnitDto, httpHeaders), String.class); } public ResponseEntity postNomenclaturesToApi(HttpServletRequest request, NomenclatureDto nomenclatureDto, Plateform plateform) { LOGGER.info("Create nomenclature " + nomenclatureDto.getId()); final String apiUri = queenProperties.getHostFromEnum(plateform) + "/api/nomenclature"; HttpHeaders httpHeaders = createSimpleHeadersAuth(request); httpHeaders.setContentType(MediaType.APPLICATION_JSON); return restTemplate.exchange(apiUri, HttpMethod.POST, new HttpEntity<>(nomenclatureDto, httpHeaders), String.class); } public ResponseEntity postQuestionnaireModelToApi(HttpServletRequest request, QuestionnaireModelDto questionnaireModelDto, Plateform plateform) { LOGGER.info("Create Questionnaire " + questionnaireModelDto.getIdQuestionnaireModel()); final String apiUri = queenProperties.getHostFromEnum(plateform) + "/api/questionnaire-models"; HttpHeaders httpHeaders = createSimpleHeadersAuth(request); httpHeaders.setContentType(MediaType.APPLICATION_JSON); return restTemplate.exchange(apiUri, HttpMethod.POST, new HttpEntity<>(questionnaireModelDto, httpHeaders), String.class); } public ResponseEntity createFullCampaign(HttpServletRequest request, File campaignZip, Plateform plateform) { final String apiUri = queenProperties.getHostFromEnum(plateform) + "/api/campaign/context"; MultiValueMap<String, Object> body = new LinkedMultiValueMap<>(); body.add("file", new FileSystemResource(campaignZip)); HttpHeaders httpHeaders = createSimpleHeadersAuth(request); httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA); HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, httpHeaders); return restTemplate.postForEntity(apiUri, requestEntity, String.class); } public HttpHeaders createSimpleHeadersAuth(HttpServletRequest request) { String authTokenHeader = request.getHeader("Authorization"); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); if (!StringUtils.isBlank(authTokenHeader)) httpHeaders.set("Authorization", authTokenHeader); return httpHeaders; } public ResponseEntity deleteCampaign(HttpServletRequest request, Plateform plateform, String id) { // new CampaignDto with parameter id to send to pearl APi final String apiUri = queenProperties.getHostFromEnum(plateform) + "/api/campaign/" + id; HttpHeaders httpHeaders = createSimpleHeadersAuth(request); httpHeaders.setContentType(MediaType.APPLICATION_JSON); return restTemplate.exchange(apiUri, HttpMethod.DELETE, new HttpEntity<>(id, httpHeaders), String.class); } public boolean healthCheck(HttpServletRequest request, Plateform plateform) { final String apiUri = queenProperties.getHostFromEnum(plateform) + "/api/healthcheck"; HttpHeaders httpHeaders = createSimpleHeadersAuth(request); httpHeaders.setContentType(MediaType.APPLICATION_JSON); return restTemplate.exchange(apiUri, HttpMethod.GET, new HttpEntity<>(httpHeaders), String.class) .getStatusCode().equals(HttpStatus.OK); } }
java
13
0.74966
120
49.724138
116
starcoderdata
using System; namespace DemiCode.Data { /// /// Thrown when repositories are used together that require different <see cref="IContext"/> implementations, either via nested scopes or in multi-repo scopes. /// public class IncompatibleRepositoriesException : Exception { /// /// The repository type that is not compatible with the current context. /// public Type RepositoryType { get; private set; } /// /// The type of the current context. /// public Type ContextType { get; private set; } /// /// Construct the exception. /// public IncompatibleRepositoriesException(Type repositoryType, Type contextType) : base("Repository type '" + repositoryType.FullName + "' is not compatible with context '" + contextType.FullName + "'") { RepositoryType = repositoryType; ContextType = contextType; } } }
c#
14
0.624658
163
34.354839
31
starcoderdata
/* This file is a part of EMIPLIB, the EDM Media over IP Library. Copyright (C) 2006-2016 Hasselt University - Expertise Centre for Digital Media (EDM) (http://www.edm.uhasselt.be) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** * \file mipencodedaudiomessage.h */ #ifndef MIPENCODEDAUDIOMESSAGE_H #define MIPENCODEDAUDIOMESSAGE_H #include "mipconfig.h" #include "mipaudiomessage.h" #include "miptime.h" #include /** * \def MIPENCODEDAUDIOMESSAGE_TYPE_SPEEX * \brief Subtype for encoded audio messages containing Speex data. * \def MIPENCODEDAUDIOMESSAGE_TYPE_ULAW * \brief Subtype for encoded audio messages containing u-law data. * \def MIPENCODEDAUDIOMESSAGE_TYPE_ALAW * \brief Subtype for encoded audio messages containing A-law data. * \def MIPENCODEDAUDIOMESSAGE_TYPE_GSM * \brief Subtype for encoded audio messages containing GSM 06.10 data. * \def MIPENCODEDAUDIOMESSAGE_TYPE_LPC * \brief Subtype for encoded audio messages containing LPC data. * \def MIPENCODEDAUDIOMESSAGE_TYPE_SILK * \brief Subtype for encoded audio messages containing SILK data. * \def MIPENCODEDAUDIOMESSAGE_TYPE_OPUS * \brief Subtype for encoded audio messages containing Opus data. */ #define MIPENCODEDAUDIOMESSAGE_TYPE_SPEEX 0x00000001 #define MIPENCODEDAUDIOMESSAGE_TYPE_ULAW 0x00000002 #define MIPENCODEDAUDIOMESSAGE_TYPE_ALAW 0x00000004 #define MIPENCODEDAUDIOMESSAGE_TYPE_GSM 0x00000008 #define MIPENCODEDAUDIOMESSAGE_TYPE_LPC 0x00000010 #define MIPENCODEDAUDIOMESSAGE_TYPE_SILK 0x00000020 #define MIPENCODEDAUDIOMESSAGE_TYPE_OPUS 0x00000040 /** Container for encoded audio data. */ class EMIPLIB_IMPORTEXPORT MIPEncodedAudioMessage : public MIPAudioMessage { public: /** Creates an encoded audio message. * This constructor can be used to create an encoded audio message. * \param subType The subtype of the message. * \param samplingRate The sampling rate. * \param numChannels The number of channels. * \param numFrames The number of frames contained in the message. * \param pData The actual encoded audio data. * \param numBytes The length of the encoded audio data. * \param deleteData Flag indicating if the memory block pointed to by \c pData should * be deleted when this message is destroyed. */ MIPEncodedAudioMessage(uint32_t subType, int samplingRate, int numChannels, int numFrames, uint8_t *pData, size_t numBytes, bool deleteData) : MIPAudioMessage(false, subType, samplingRate, numChannels, numFrames) { m_deleteData = deleteData; m_pData = pData; m_dataLength = numBytes; } ~MIPEncodedAudioMessage() { if (m_deleteData) delete [] m_pData; } /** Returns a pointer to the encoded audio data. */ const uint8_t *getData() const { return m_pData; } /** Returns the length of the encoded audio. */ size_t getDataLength() const { return m_dataLength; } /** Sets the length of the encoded audio to 'l'. */ void setDataLength(size_t l) { m_dataLength = l; } /** Creates a copy of this message. */ MIPMediaMessage *createCopy() const; private: bool m_deleteData; uint8_t *m_pData; size_t m_dataLength; }; inline MIPMediaMessage *MIPEncodedAudioMessage::createCopy() const { uint8_t *pBytes = new uint8_t [m_dataLength]; memcpy(pBytes, m_pData, m_dataLength); MIPMediaMessage *pMsg = new MIPEncodedAudioMessage(getMessageSubtype(), getSamplingRate(), getNumberOfChannels(), getNumberOfFrames(), pBytes, m_dataLength, true); pMsg->copyMediaInfoFrom(*this); return pMsg; } #endif // MIPENCODEDAUDIOMESSAGE_H
c
10
0.725352
160
37.614035
114
starcoderdata
using System; using UnityEngine; public class ResourcePile : ServerBuilding { public ResourcePile() { } protected override void Update() { if (null != this.m_server && this.m_gotDamage > 0f && null != this.m_gotAttacker) { int num = 1 + (int)(this.m_gotDamage * 0.08f); this.m_server.CreateFreeWorldItem(this.m_itemIndex, num, this.m_gotAttacker.position); this.m_quantity -= num; if (this.m_quantity <= 0) { UnityEngine.Object.Destroy(base.gameObject); } this.m_gotAttacker = null; this.m_gotDamage = 0f; } base.Update(); } public int m_itemIndex = 130; public int m_quantity = 10; }
c#
17
0.668675
89
20.419355
31
starcoderdata
#include #include #include #include #include #include #include #include #include "game.h" #define NSTELLE 1000 using namespace std; game::game(sf::RenderWindow& gameWindow) : spaceShip(), pianetiVect(), score(std::string("SCORE 0")) { view = gameWindow.getView(); points = 0; isInside = -1; alive = true; close = false; pausa = false; newSolarSystem(); //crea il sistema solare planetsLeft = pianetiVect.size(); for (int i = 0; i < NSTELLE; i++) { int x = -1, y = -1; bool isOutside; do { isOutside = true; x = rand() % 1280; y = rand() % 720; } while (!isOutside); sf::CircleShape stella; stelleVect.push_back(stella); stelleVect[i].setPosition(x, y); stelleVect[i].setRadius(0.25); stelleVect[i].setFillColor(sf::Color::Black); stelleVect[i].setOutlineColor(sf::Color(255, 255, 179)); stelleVect[i].setOutlineThickness(1); } } game::~game() { } int game::run(sf::RenderWindow& gameWindow) { while (alive && !close) //esce se hai finito le vite o se hai chiuso la finestra { time = clock.getElapsedTime(); close = processEvents(gameWindow); if (!pausa) { alive = update(gameWindow); } render(gameWindow); } if (close) return(-1); else return(points); } bool game::processEvents(sf::RenderWindow & gameWindow) { sf::Event event; while (gameWindow.pollEvent(event)) { switch (event.type) { case sf::Event::KeyPressed: if (event.key.code == sf::Keyboard::Return && planetsLeft == 0) { newSolarSystem(); } else if (event.key.code == sf::Keyboard::P && isInside == -1) pausa = !pausa; else spaceShip.handleEvents(event.key.code, true); return false; break; case sf::Event::KeyReleased: spaceShip.handleEvents(event.key.code, false); return false; break; case sf::Event::Closed: return true; break; } } } bool game::update(sf::RenderWindow & gameWindow) { if (spaceShip.getLives() < 0) alive = false; else { //controlla di essere in gioco prima di esguire gli update planetsLeft = pianetiVect.size(); score.updateText(std::string("SCORE " + std::to_string(points))); //aggiorna il punteggio bool moving = spaceShip.move(view); spaceShip.update(); //aggiorna i valori della navicella if (isInside == -1) { //fuori dai pianeti spaceShip.disactivate(); //raggio traente disattivato if (spaceShip.getPosition().x > 1280) spaceShip.setPosition(sf::Vector2f(10, spaceShip.getPosition().y)); if (spaceShip.getPosition().x < 0) spaceShip.setPosition(sf::Vector2f(1270, spaceShip.getPosition().y)); if (spaceShip.getPosition().y < 0) spaceShip.setPosition(sf::Vector2f(spaceShip.getPosition().x, 710)); if (spaceShip.getPosition().y > 720) spaceShip.setPosition(sf::Vector2f(spaceShip.getPosition().x, 10)); for (int i = 0; i < pianetiVect.size(); i++) { float dist = sqrt(pow(spaceShip.getPosition().x - pianetiVect[i].getPosition().x, 2) + pow(spaceShip.getPosition().y - pianetiVect[i].getPosition().y, 2)); if (dist < (pianetiVect[i].getRaggio() + 5)) { isInside = i; spaceShip.setPosition(sf::Vector2f(640, 360)); spaceShip.getBullets().clear(); } } if (time.asSeconds() > 0.25) { spaceShip.recharge(); clock.restart(); } } //CONTROLLING THE VIEW WHEN YOU ARE INSIDE THE PLANET if (isInside != -1) { view.setCenter(spaceShip.getPosition()); pianetiVect[isInside].update(spaceShip, points); //controlla tutto quanto avviene all'interno del pianeta ed effettua gli aggiornamenti if (view.getCenter().x >= (pianetiVect[isInside].getRaggio() - 10) * 128 + (1280 / 2)) { //il raggio equivale alla lunghezza del terreno view.setCenter((1280 / 2), spaceShip.getPosition().y); spaceShip.setPosition(sf::Vector2f(view.getCenter().x, view.getCenter().y)); } if (view.getCenter().x < (1280 / 2)) { view.setCenter((pianetiVect[isInside].getRaggio() - 10) * 128 + (1280 / 2), spaceShip.getPosition().y); spaceShip.setPosition(sf::Vector2f(view.getCenter().x, view.getCenter().y)); } if (time.asSeconds() > 0.25) { pianetiVect[isInside].recharge(); spaceShip.recharge(); clock.restart(); } if (pianetiVect[isInside].checkBunker() || view.getCenter().y < 100) { if (pianetiVect[isInside].checkBunker()) { //controlla se sono stati distrutti tutti i bunker spaceShip.setPosition(pianetiVect[isInside].getPosition()); pianetiVect.erase(pianetiVect.begin() + isInside); } if (view.getCenter().y < 100) { //controlla l'uscita della navicella da un pianeta spaceShip.setPosition(sf::Vector2f(640, 50)); } spaceShip.getBullets().clear(); //elimina tutti i proiettili view.setCenter(sf::Vector2f(640, 360)); isInside = -1; } else view.setCenter(spaceShip.getPosition()); } if (moving != 0) { //controls fuel drecreasement if (!spaceShip.decreaseFuel()) { //controlla che la funzione decrease abbia portato a conclusione spaceShip.setLives(-1); // la sottrazione del fuel e in caso contrario chiude la partita } } } return(alive); } void game::render(sf::RenderWindow & gameWindow) { gameWindow.clear(); gameWindow.setView(view); if (isInside == -1) { for (int i = 0; i < stelleVect.size(); i++) { gameWindow.draw(stelleVect[i]); } for (int i = 0; i < pianetiVect.size(); i++) { pianetiVect[i].draw(gameWindow); } if (planetsLeft == 0 && alive) { Tcomplimenti.setTitle(30); Tcomplimenti.setPosition(sf::Vector2f(250, 280)); Tcomplimenti.draw(gameWindow); } } else pianetiVect[isInside].drawGround(gameWindow); if (pausa) { Tpausa.setTitle(50); Tpausa.setPosition(sf::Vector2f(520, 280)); Tpausa.draw(gameWindow); Treplay.setPosition(sf::Vector2f(525, 350)); Treplay.draw(gameWindow); } spaceShip.draw(gameWindow); score.drawRelative(gameWindow, sf::Vector2f(630, 350)); gameWindow.display(); } void game::newSolarSystem() { nPianeti = rand() % 3 + 5; for (int i = 0; i < nPianeti; i++) { planet newPlanet(nPianeti, i); pianetiVect.push_back(newPlanet); } }
c++
23
0.626184
139
24.087649
251
starcoderdata
#include <iostream> using namespace std; int main() { int dias; cin >> dias; int atividades[dias][3]; int felicidadeDasAtividades[dias][3]; for (int i = 0; i < dias; i++) { cin >> atividades[i][0] >> atividades[i][1] >> atividades[i][2]; felicidadeDasAtividades[i][0] = felicidadeDasAtividades[i][1] = felicidadeDasAtividades[i][2] = 0; } for (int i = dias - 1; i >= 0; i--) { if (i == dias - 1) { felicidadeDasAtividades[i][0] = atividades[i][0]; felicidadeDasAtividades[i][1] = atividades[i][1]; felicidadeDasAtividades[i][2] = atividades[i][2]; } else { if (felicidadeDasAtividades[i + 1][2] >= felicidadeDasAtividades[i + 1][1]) { felicidadeDasAtividades[i][0] = atividades[i][0] + felicidadeDasAtividades[i + 1][2]; } else { felicidadeDasAtividades[i][0] = atividades[i][0] + felicidadeDasAtividades[i + 1][1]; } if (felicidadeDasAtividades[i + 1][2] >= felicidadeDasAtividades[i + 1][0]) { felicidadeDasAtividades[i][1] = atividades[i][1] + felicidadeDasAtividades[i + 1][2]; } else { felicidadeDasAtividades[i][1] = atividades[i][1] + felicidadeDasAtividades[i + 1][0]; } if (felicidadeDasAtividades[i + 1][1] >= felicidadeDasAtividades[i + 1][0]) { felicidadeDasAtividades[i][2] = atividades[i][2] + felicidadeDasAtividades[i + 1][1]; } else { felicidadeDasAtividades[i][2] = atividades[i][2] + felicidadeDasAtividades[i + 1][0]; } } } int melhorEscolha = 0; if (felicidadeDasAtividades[0][0] >= felicidadeDasAtividades[0][1] && felicidadeDasAtividades[0][0] >= felicidadeDasAtividades[0][2]) { cout << felicidadeDasAtividades[0][0] << endl; } else if (felicidadeDasAtividades[0][1] >= felicidadeDasAtividades[0][0] && felicidadeDasAtividades[0][1] >= felicidadeDasAtividades[0][2]) { cout << felicidadeDasAtividades[0][1] << endl; } else if (felicidadeDasAtividades[0][2] >= felicidadeDasAtividades[0][0] && felicidadeDasAtividades[0][2] >= felicidadeDasAtividades[0][1]) { cout << felicidadeDasAtividades[0][2] << endl; } }
c++
18
0.549858
142
34.1
70
codenet
/* * (c) Copyright 2019 Palantir Technologies Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.lock.client; import com.google.common.collect.Sets; import com.palantir.lock.v2.LockToken; import com.palantir.lock.v2.StartIdentifiedAtlasDbTransactionResponse; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** * A service responsible for coalescing multiple start transaction calls into a single start transactions call. This * service also handles creating {@link LockTokenShare}'s to enable multiple transactions sharing a single immutable * timestamp. * * Callers of this class should use {@link #unlock(Set)} and {@link #refreshLockLeases(Set)} for returned lock tokens, * rather than directly calling delegate lock service. */ final class TransactionStarter implements AutoCloseable { private final LockLeaseService lockLeaseService; private final IdentifiedAtlasDbTransactionStarter batchingTransactionStarter; private TransactionStarter( LockLeaseService lockLeaseService, IdentifiedAtlasDbTransactionStarter batchingTransactionStarter) { this.lockLeaseService = lockLeaseService; this.batchingTransactionStarter = batchingTransactionStarter; } static TransactionStarter create(LockLeaseService lockLeaseService, RequestBatchersFactory requestBatchersFactory) { return new TransactionStarter( lockLeaseService, requestBatchersFactory.createBatchingTransactionStarter(lockLeaseService)); } List startIdentifiedAtlasDbTransactionBatch(int count) { return batchingTransactionStarter.startIdentifiedAtlasDbTransactionBatch(count); } Set refreshLockLeases(Set tokens) { Set lockTokenShares = TransactionStarterHelper.filterLockTokenShares(tokens); Set lockTokens = TransactionStarterHelper.filterOutTokenShares(tokens); Set refreshedTokens = lockLeaseService.refreshLockLeases(Sets.union(reduceForRefresh(lockTokenShares), lockTokens)); Set resultLockTokenShares = lockTokenShares.stream() .filter(t -> refreshedTokens.contains(t.sharedLockToken())) .collect(Collectors.toSet()); Set resultLockTokens = lockTokens.stream().filter(refreshedTokens::contains).collect(Collectors.toSet()); return Sets.union(resultLockTokenShares, resultLockTokens); } Set unlock(Set tokens) { return TransactionStarterHelper.unlock(tokens, lockLeaseService); } private static Set reduceForRefresh(Set lockTokenShares) { return lockTokenShares.stream().map(LockTokenShare::sharedLockToken).collect(Collectors.toSet()); } @Override public void close() { batchingTransactionStarter.close(); } }
java
15
0.759634
120
42.987805
82
starcoderdata
private void settingsPictureButtonControl_Click(object sender, EventArgs e) { using (var dimmerMask = new DimmerMask(this)) { dimmerMask.Show(this); using (var sf = new SettingsForm()) { sf.ShowDialog(); } AnalyticsHelper.OptedIn = Settings.Default.OptIntoAnalytics; UpdateUIwithLicenseStatus(); dimmerMask.Close(); } //dimmerMask = null; }
c#
12
0.487941
76
29
18
inline
func (tb *TextBuf) New(nlines int) { tb.Defaults() nlines = ints.MaxInt(nlines, 1) tb.LinesMu.Lock() tb.MarkupMu.Lock() tb.Lines = make([][]rune, nlines) tb.LineBytes = make([][]byte, nlines) tb.Tags = make([]lex.Line, nlines) tb.HiTags = make([]lex.Line, nlines) tb.Markup = make([][]byte, nlines) if cap(tb.ByteOffs) >= nlines { tb.ByteOffs = tb.ByteOffs[:nlines] } else { tb.ByteOffs = make([]int, nlines) } if nlines == 1 { // this is used for a new blank doc tb.ByteOffs[0] = 0 // by definition tb.Lines[0] = []rune("") tb.LineBytes[0] = []byte("") tb.Markup[0] = []byte("") } tb.NLines = nlines tb.PiState.SetSrc(&tb.Lines, string(tb.Filename)) tb.Hi.Init(&tb.Info, &tb.PiState) tb.MarkupMu.Unlock() tb.LinesMu.Unlock() tb.Refresh() }
go
10
0.629344
53
22.575758
33
inline
// Copyright (c) 2014, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. package gndata.app.ui.util.listener; import javafx.collections.ListChangeListener; import com.hp.hpl.jena.rdf.model.*; import gndata.app.ui.util.StatementTableItem; /** * Listener class facilitating updates and deletions * to and from the RDF model upon changes in the registered list */ public class ChangeStatementListListener implements ListChangeListener { private boolean enabled = true; @Override public void onChanged(Change<? extends StatementTableItem> c) { if(enabled) { while (c.next()) { if (c.wasReplaced()) { // update statement in RDF model Statement rmstmt = c.getRemoved().get(c.getRemovedSize() - 1).getStatement(); Statement addstmt = c.getAddedSubList().get(c.getAddedSize() - 1).getStatement(); Model parentModel = rmstmt.getModel(); parentModel.remove(rmstmt); parentModel.add(addstmt); } else if (c.wasRemoved()) { // remove statement from RDF model StatementTableItem remItem = c.getRemoved().get(c.getRemovedSize() - 1); remItem.getStatement().getModel().remove(remItem.getStatement()); } } } } public void setEnabled() { this.enabled = true; } public void setDisabled() { this.enabled = false; } }
java
19
0.622467
101
32.862745
51
starcoderdata
import Vue from 'vue'; import Vuex from 'vuex'; import {alert} from './alert.module'; import {account} from './account.module'; import {users} from './users.module'; import {lists} from './list.module'; Vue.use(Vuex); export const store = new Vuex.Store({ modules: { alert, account, users, lists } });
javascript
4
0.657224
41
17.578947
19
starcoderdata
var print_8c = [ [ "BUFTOWRITETO_LENGTH", "print_8c.html#a4362a8e7b373b6c383d1807261f1e9ec", null ], [ "MODULE_NAME", "print_8c.html#a14ded244c47bbba850a8a4be6d16c7e3", null ], [ "PRINT_EXPR", "print_8c.html#a95ee1ee527628963550dd70a6a4c16a8", null ], [ "PRINT_NATIVE_FUNC", "print_8c.html#a2e3cd76c2fa9717ecb395f760eb2eae5", null ], [ "PRINT_STREAM", "print_8c.html#a69cc2768865c0701858bc70e2d6fb5e0", null ], [ "STRING_SET_TO_END", "print_8c.html#a35305d1c019c6981d1800922930143ce", null ], [ "expressionToString", "print_8c.html#af01d28a967b51f116ebfd90ec602d037", null ], [ "fuPrint", "print_8c.html#a3f1609b538cdb7dc72c34a684b27a53a", null ], [ "printToStream", "print_8c.html#ab091353d729aaaa9444ba18024cb9c6d", null ] ];
javascript
6
0.730013
87
62.666667
12
starcoderdata
package org.zstack.network.service.lb; /** * @author: zhanyong.miao * @date: 2020-03-05 **/ public enum LoadBalancerAclStatus { enable, disable }
java
6
0.641711
38
15.090909
11
starcoderdata
using Duende.IdentityServer.EntityFramework.Options; using Microsoft.AspNetCore.ApiAuthorization.IdentityServer; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; namespace Net6WebApiTemplate.Infrastructure.Identity { public class ApplicationIdentityDbContext : ApiAuthorizationDbContext { public ApplicationIdentityDbContext(DbContextOptions options, IOptions operationalStoreOptions) : base(options, operationalStoreOptions) { } } }
c#
10
0.819118
111
41.5625
16
starcoderdata
<?php namespace ByTIC\Notifications\Channels; use ByTIC\Notifications\Notification; /** * Class MailChannel * @package ByTICModels\Notifications\Channels */ class EmailDbChannel extends AbstractChannel { /** * Send the given notification. * * @param mixed $notifiable * @param Notification $notification * @return int */ public function send($notifiable, Notification $notification) { $email = $notification->toMailDb($notifiable); $email->save(); if ($email->id > 0) { return 1; } return 0; } }
php
11
0.614007
65
19.466667
30
starcoderdata
package com.wordpress.carledwinti.sistema.ponto.eletronico.api.controllers; import com.wordpress.carledwinti.sistema.ponto.eletronico.api.dtos.CadastroPFDto; import com.wordpress.carledwinti.sistema.ponto.eletronico.api.dtos.LancamentoDto; import com.wordpress.carledwinti.sistema.ponto.eletronico.api.entities.Empresa; import com.wordpress.carledwinti.sistema.ponto.eletronico.api.entities.Funcionario; import com.wordpress.carledwinti.sistema.ponto.eletronico.api.entities.Lancamento; import com.wordpress.carledwinti.sistema.ponto.eletronico.api.enums.PerfilEnum; import com.wordpress.carledwinti.sistema.ponto.eletronico.api.responses.Response; import com.wordpress.carledwinti.sistema.ponto.eletronico.api.services.EmpresaService; import com.wordpress.carledwinti.sistema.ponto.eletronico.api.services.FuncionarioService; import com.wordpress.carledwinti.sistema.ponto.eletronico.api.utils.PasswordUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.math.BigDecimal; import java.util.Optional; @RestController @RequestMapping("/") @CrossOrigin(origins = "*") public class HomeController { private static final Logger LOG = LoggerFactory.getLogger(HomeController.class); @GetMapping public ResponseEntity home(){ LOG.info("It works!"); return ResponseEntity.ok("Sistema de Ponto Eletronico works..."); } }
java
7
0.828189
124
44.209302
43
starcoderdata
package nz.co.example.dev.domain.logic.temp; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import nz.co.example.dev.domain.logic.CircuitConfigData; import nz.co.example.dev.domain.model.Order; import nz.co.example.dev.domain.model.RegionConfig; import nz.co.example.dev.mvc.CircuitForm; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; /** * Hard coded version of the configured data that is used to create/modify * circuits. * * Eventual this will be replaced by a version that retrieves the data from * external configurable sources. * * @author nivanov */ @Service @Qualifier("hardcoded") public class HardCodedCircuitConfigData implements CircuitConfigData { private static final String CHCH_SIP_DEF_TWO = "172.16.31.10"; private static final String CHCH_SIP_DEF_ONE = "172.16.31.10"; private static final String WLGN_SIP_DEF_TWO = "192.168.127.12"; private static final String WLGN_SIP_DEF_ONE = "172.16.58.3"; private static final String AUC_SIP_DEF_TWO = "192.168.127.12"; private static final String AUC_SIP_DEF_ONE = "172.16.31.10"; private Map<String, RegionConfig> regionConfigMap; private Map<String, String> circuitTypes; private Map<String, String> regionTypes; private Map<Order, String> regionRealmSuffix; private Map<String, RegionConfig> regionConfigMapBySipDefinitionTwo; private Map<String, String> regionToTargetNameMap; private Map<String, String> targetNameToRegionMap; public HardCodedCircuitConfigData() { circuitTypes = new LinkedHashMap<String, String>(); circuitTypes.put("W_SIP_LAYER_TWO", "W-SIP Layer 2"); regionTypes = new LinkedHashMap<String, String>(); regionTypes.put("auc", "Auckland"); regionTypes.put("wlgn", "Wellington"); regionTypes.put("chch", "Christchurch"); regionRealmSuffix = new HashMap<Order, String>(); regionRealmSuffix.put(Order.PRIMARY, ".acc"); regionRealmSuffix.put(Order.SECONDARY, "n.acc"); regionConfigMap = new HashMap<String, RegionConfig>(); regionConfigMap.put("auc", new RegionConfig("auc", AUC_SIP_DEF_ONE, AUC_SIP_DEF_TWO, "m01-access")); regionConfigMap.put("wlgn", new RegionConfig("wlgn", WLGN_SIP_DEF_ONE, WLGN_SIP_DEF_TWO, "m01-access")); regionConfigMap.put("chch", new RegionConfig("chch", CHCH_SIP_DEF_ONE, CHCH_SIP_DEF_TWO, "m01-access")); regionConfigMapBySipDefinitionTwo = new HashMap<String, RegionConfig>(); regionConfigMapBySipDefinitionTwo.put(AUC_SIP_DEF_TWO, new RegionConfig("auc", AUC_SIP_DEF_ONE, AUC_SIP_DEF_TWO, "m01-access")); regionConfigMapBySipDefinitionTwo.put(WLGN_SIP_DEF_TWO, new RegionConfig("wlgn", WLGN_SIP_DEF_ONE, WLGN_SIP_DEF_TWO, "m01-access")); regionConfigMapBySipDefinitionTwo.put(CHCH_SIP_DEF_TWO, new RegionConfig("chch", CHCH_SIP_DEF_ONE, CHCH_SIP_DEF_TWO, "m01-access")); regionToTargetNameMap = new HashMap<String, String>(); regionToTargetNameMap.put("auc", "dev1-TSPN_dev2-TSPN"); regionToTargetNameMap.put("chch", "dev5-TSTC_dev6-TSTC"); regionToTargetNameMap.put("wlgn", "dev3-WGTN_dev4-WGTN"); regionToTargetNameMap.put("lab", "dev-LAB"); targetNameToRegionMap = new HashMap<String, String>(); targetNameToRegionMap.put("dev1-TSPN_dev2-TSPN", "auc"); targetNameToRegionMap.put("dev5-TSTC_dev6-TSTC", "chch"); targetNameToRegionMap.put("dev3-WGTN_dev4-WGTN", "wlgn"); targetNameToRegionMap.put("dev-LAB", "lab"); } @Override public void populateSelectionOptions(CircuitForm circuitForm) { circuitForm.setCircuitTypeOptions(getCircuitTypeList()); circuitForm.setRegionOptions(getRegionList()); } private Map<String, String> getCircuitTypeList() { return circuitTypes; } private Map<String, String> getRegionList() { return regionTypes; } @Override public String getNetworkInterfaceDescription() { return "Connection to Access Network for customer %s"; } @Override public String getPrimaryAccessRealmDescription() { return "Access Realm for customer %s"; } @Override public String getSecondaryAccessRealmDescription() { return "NAT Access Realm for customer %s"; } @Override public String getPrimarySipInterfaceDescription() { return "Access SIP-Interface for customer %s"; } @Override public String getSecondarySipInterfaceDescription() { return "NAT Access SIP-Interface for customer %s"; } @Override public String getPrimaryAccessRealmParentRealm() { return "CS2K-pabx.acc"; } @Override public String getPrimaryAccessRealmRegex() { return "CS2K-([a-zA-Z0-9]*)-(\\d+).acc"; } @Override public String getSecondaryAccessRealmRegex() { return "CS2K-([a-zA-Z0-9]*)-(\\d+)n.acc"; } @Override public String getPrimaryAccessRealmId() { return "CS2K-%s-%s.acc"; } @Override public String getSecondaryAccessRealmId() { return "CS2K-%s-%sn.acc"; } @Override public Map<Order, String> getOrderRealmSuffixMap() { return regionRealmSuffix; } @Override public Map<String, RegionConfig> getRegionConfigMap() { return regionConfigMap; } @Override public Map<String, RegionConfig> getRegionConfigMappedBySipDefinitionTwo() { return regionConfigMapBySipDefinitionTwo; } @Override public Map<String, String> getRegionToTargetNameMap() { return regionToTargetNameMap; } @Override public Map<String, String> getTargetNameToRegionMap() { return targetNameToRegionMap; } }
java
11
0.683826
112
33.623529
170
starcoderdata
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DetourServer { class TypeExtensions { /// /// Looks in all loaded assemblies for the given type. /// /// <param name="fullName"> /// The full name of the type. /// /// /// The <see cref="Type"/> found; null if not found. /// public static Type FindType(string fullName) { return AppDomain.CurrentDomain.GetAssemblies() .Where(a => !a.IsDynamic) .SelectMany(a => a.GetTypes()) .FirstOrDefault(t => t.FullName.Equals(fullName)); } } }
c#
18
0.523136
70
26.785714
28
starcoderdata
<?php namespace League\CLImate\Util\Writer; class Buffer implements WriterInterface { /** * @var string the buffered data */ protected $contents = ''; /** * Write the content to the buffer. * * @param string $content */ public function write($content) { $this->contents .= $content; } /** * Get the buffered data. * * @return string */ public function get() { return $this->contents; } /** * Clean the buffer and throw away any data. */ public function clean() { $this->contents = ''; } }
php
9
0.536145
48
15.6
40
starcoderdata
package com.cursor.greendict.utils.logger; /** * Created by ldx on 2015/2/17. * Interface contains all methods of "Log" */ public interface Log { void d(String tag, String content); void d(String tag, String content, Throwable tr); void e(String tag, String content); void e(String tag, String content, Throwable tr); void i(String tag, String content); void i(String tag, String content, Throwable tr); void v(String tag, String content); void v(String tag, String content, Throwable tr); void w(String tag, String content); void w(String tag, String content, Throwable tr); void w(String tag, Throwable tr); void wtf(String tag, String content); void wtf(String tag, String content, Throwable tr); void wtf(String tag, Throwable tr); }
java
6
0.681034
55
21.555556
36
starcoderdata
// Called as: document.getElementsByRegex("pattern"). // Returns an array of all elements matching a given regular expression on id. // 'pattern' argument is a regular expression string. // document['getElementsByRegex'] = function(pattern){ var arrElements = []; // to accumulate matching elements var re = new RegExp(pattern); // the regex to match with function findRecursively(aNode) { // recursive function to traverse DOM if (!aNode) return; if (aNode.id !== undefined && aNode.id.search(re) != -1) arrElements.push(aNode); // FOUND ONE! for (var idx in aNode.childNodes) // search children... findRecursively(aNode.childNodes[idx]); }; findRecursively(document); // initiate recursive matching return arrElements; // return matching elements }; function scrollToAnchor(aid){ $('html,body').animate({scrollTop: aid.offset().top},500); } var frontpages = 3; var startpage = 1; var i = startpage; var Pages = document.getElementsByRegex('^page*'); var totalPage = Pages.length; console.log(totalPage); $(document).keydown(function (event) { if (event.keyCode == 33) { if(i>startpage) { i--; scrollToAnchor($("#page"+i+"")); } event.preventDefault(); } else if (event.keyCode == 34) { if (i<totalPage) { i++; scrollToAnchor($("#page"+i+"")); } event.preventDefault(); } console.log(i); //gives the default message });
javascript
20
0.66043
78
27.469388
49
starcoderdata
const API_PATH = process.env.API_PATH; const VTV_GIAI_TRI_URL = "https://www.vtvgiaitri.vn"; const VTV_GIAI_TRI_API_PATH = "/api/v1"; const ENCRYPTION_KEY_PATTERN = /sleng_(? const GENRE = { PHIM: "phim", TV_SHOW: "tv-show" }; const DATA_UPDATE_PASSWORD = process.env.DATA_UPDATE_PASSWORD; const HTTP_STATUS_CODE = { OK: 200, NO_CONTENT: 204, FORBIDDEN: 403, INTERNAL_SERVER_ERROR: 500 }; exports.constants = { API_PATH, VTV_GIAI_TRI_URL, VTV_GIAI_TRI_API_PATH, ENCRYPTION_KEY_PATTERN, GENRE, DATA_UPDATE_PASSWORD, HTTP_STATUS_CODE };
javascript
9
0.686804
66
23.192308
26
starcoderdata
<?php namespace App\Controller; use App\Entity\Agenda; use App\Entity\AgendaManuelItem; use App\Entity\Document; use App\Entity\User; use App\Exception\DocumentDirectoryException; use App\Exception\FileMovingException; use App\Form\DocumentType; use App\Service\DocumentUploader; use Doctrine\ORM\EntityManagerInterface; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; /** * @Route("/agenda/{id}/item/{agenda_item_id}/documents") */ class AgendaManuelItemDocumentController extends AbstractController { /** * @var EntityManagerInterface */ private $entityManager; /** * @var DocumentUploader */ private $documentUploader; public function __construct(DocumentUploader $documentUploader, EntityManagerInterface $entityManager) { $this->documentUploader = $documentUploader; $this->entityManager = $entityManager; } /** * @Route("", name="agenda_manuel_item_documents", methods={"GET"}) * @Entity("agenda", expr="repository.find(id)") * @Entity("agendaItem", expr="repository.find(agenda_item_id)") */ public function index(Agenda $agenda, AgendaManuelItem $agendaItem): Response { $documents = $agendaItem->getDocuments(); return $this->render('agenda_manuel_item/documents.html.twig', [ 'agenda' => $agenda, 'agenda_item' => $agendaItem, 'documents' => $documents, ]); } /** * @Route("/upload", name="agenda_manuel_item_upload_document", methods={"GET", "POST"}) * @Entity("agenda", expr="repository.find(id)") * @Entity("agendaItem", expr="repository.find(agenda_item_id)") * * @throws DocumentDirectoryException * @throws FileMovingException */ public function upload(Agenda $agenda, AgendaManuelItem $agendaItem, Request $request): Response { $this->documentUploader->specifyDirectory('/agenda_item_documents/'); // Create new document and its form $document = new Document(); $form = $this->createForm(DocumentType::class, $document); $isFinishedAgenda = $agenda->isFinished(); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid() && !$isFinishedAgenda) { // Extract filename and handle it // Users will only see document name, not filename $file = $form->get('filename')->getData(); $newFilename = $this->documentUploader->upload($file); // Set filename, document name and creator/uploader $document->setFilename($newFilename); /** @var User $uploader */ $uploader = $this->getUser(); $document->setUploadedBy($uploader); $agendaItem->addDocument($document); $this->entityManager->persist($document); $this->entityManager->flush(); return $this->redirectToRoute('agenda_manuel_item_documents', [ 'id' => $agenda->getId(), 'agenda_item_id' => $agendaItem->getId(), ]); } return $this->render('agenda_manuel_item/document_upload.html.twig', [ 'document_form' => $form->createView(), 'agenda' => $agenda, 'agenda_item' => $agendaItem, ]); } /** * @Route("/download/{document_id}", name="agenda_manuel_item_document_download", methods={"GET", "POST"}) * @Entity("document", expr="repository.find(document_id)") * * @throws DocumentDirectoryException */ public function download(Document $document, DocumentUploader $uploader): Response { $uploader->specifyDirectory('/agenda_item_documents/'); $response = $uploader->handleDownload($document); return $response; } /** * @Route("/delete/{document_id}", name="agenda_manuel_item_document_delete", methods={"DELETE"}) * @Entity("document", expr="repository.find(document_id)") * @Entity("agendaItem", expr="repository.find(agenda_item_id)") * @Entity("agenda", expr="repository.find(id)") */ public function delete(Agenda $agenda, AgendaManuelItem $agendaItem, Document $document, Request $request): Response { // Check that CSRF token is valid if ($this->isCsrfTokenValid('delete'.$document->getId(), $request->request->get('_token')) && !$agenda->isFinished()) { $agendaItem->removeDocument($document); $this->entityManager->remove($document); $this->entityManager->flush(); } return $this->redirectToRoute('agenda_manuel_item_documents', [ 'id' => $agenda->getId(), 'agenda_item_id' => $agendaItem->getId(), ]); } }
php
15
0.629821
127
34.422535
142
starcoderdata
func TestUrlData_SignedUrl(t *testing.T) { // load fake service account credentials cfg, err := google.JWTConfigFromJSON([]byte(fakeCredentials), "") if err != nil { t.Error(err) } urlData := &UrlData{ HttpMethod: "GET", Expires: testUrlExpires, Path: testUrlPath, JwtConfig: cfg, } result, err := urlData.SignedUrl() if err != nil { t.Errorf("Could not generated signed url: %+v", err) } if result != testUrlExpectedUrl { t.Errorf("URL does not match expected value:\n%s\n%s", testUrlExpectedUrl, result) } }
go
11
0.669725
84
25
21
inline
private void doSomething(int order) { switch (order) { case 0: // do not thing break; case 1: tx.rollback(); break; case 2: tx.commit(); break; } }
java
9
0.526596
37
13.538462
13
inline
import React from "react" import { fontFamily } from "./theme" const P = ({ children, style }) => ( <p style={{ fontFamily, fontSize: 14, lineHeight: 1.4, ...style }}> {children} ) export default P
javascript
8
0.637097
69
21.545455
11
starcoderdata
const express = require('express') //CONFIG const config = require('./config/config') //DB // require('./db/connect') const connectDB = require('./db/connect') //MIDDLEWARES const notFound = require('./middlewares/not-found') const errorHandler = require('./middlewares/error-handler') //ROUTES const routeTasks = require('./routes/tasks') const app = express() app.use(express.static('./public')) //para renderizar la pagina app.use(express.json()) const PORT = 3005 //ROUTES app.use('/api/v1/tasks', routeTasks) app.use(notFound) app.use(errorHandler) const start = async () => { try { await connectDB(config.mongoUri) app.listen(PORT, console.log(`server is listening on port ${PORT}`)) } catch (error) { console.error(error) } } start()
javascript
10
0.675879
76
21.111111
36
starcoderdata
private Class<?> getCommandClassFor(String cmd, String target) { var camelCasing = (Function<String, String>) s -> { return s.isEmpty() ? "" : (s.substring(0, 1).toUpperCase() + s.substring(1)); }; var pkg = "chopchop.logic.commands."; var extraTarget = ""; var xs = new StringView(target).words(); if (xs.size() > 1) { target = xs.get(0); extraTarget = xs.get(1); } if (target.equals("recipes")) { target = "recipe"; } else if (target.equals("ingredients")) { target = "ingredient"; } for (var cmdName : Strings.COMMAND_NAMES) { if (!cmdName.equals(cmd)) { continue; } var className = pkg + camelCasing.apply(cmdName) + camelCasing.apply(target) + camelCasing.apply(extraTarget) + "Command"; logger.debug("searching for class '%s'", className); try { return Class.forName(className); } catch (ClassNotFoundException e) { try { // try to find the dummy class. var dummyPkg = "chopchop.logic.commands.HelpCommand$"; className = dummyPkg + camelCasing.apply(cmdName) + "CommandDummy"; logger.debug("not found, searching for dummy class '%s'", className); return Class.forName(className); } catch (ClassNotFoundException e1) { logger.debug("dummy class not found either"); break; } } } return null; }
java
16
0.463014
89
29.949153
59
inline
import torch import time import torch.nn.functional as F k = 3 B, C_in, W, H, U, V = 32, 4, 5, 6, 7, 8 C_out = 2 weight = torch.rand(C_out, C_in, k, k, k, k) x = torch.rand(B, C_in, W, H, U, V) start = time.perf_counter() x_pad = F.pad(x, [k//2]*8) W2, H2, U2, V2 = W + k - 1, H + k - 1, U + k - 1, V + k - 1 x_unfold = x_pad.as_strided([B, C_in, k, k, k, k, W, H, U, V], [C_in*W2*H2*U2*V2, W2*H2*U2*V2, H2*U2*V2, U2*V2, V2, 1, H2*U2*V2, U2*V2, V2, 1]) end = time.perf_counter() print('unfold time:', end - start) start = time.perf_counter() print(weight.size(), x_unfold.size()) o = torch.einsum('oicdef,bicdefwhuv->bowhuv', (weight, x_unfold)) # o = (weight.view(1, C_out, C_in, k ,k, k, k, 1, 1, 1, 1) * x_unfold.unsqueeze(1)).view(B, C_out, C_in * k**4, W, H, U, V).sum(2) print(o.size()) end = time.perf_counter() print('conv time:', end - start) # start = time.perf_counter() # x_pad = F.pad(x, [k//2]*8) # W2, H2, U2, V2 = W + k - 1, H + k - 1, U + k - 1, V + k - 1 # x_unfold = x_pad.as_strided([B, C_in, W, H, U, V, k, k, k, k], [C_in*W2*H2*U2*V2, W2*H2*U2*V2, H2*U2*V2, U2*V2, V2, 1, H2*U2*V2, U2*V2, V2, 1]) # end = time.perf_counter() # print('unfold time:', end - start) # start = time.perf_counter() # print(weight.size(), x_unfold.size()) # # o = torch.einsum('oicdef,biwhuvcdef->bowhuv', (weight, x_unfold)) # o = (weight.view(1, C_out, C_in, 1, 1, 1, 1, k ,k, k, k) * x_unfold.unsqueeze(1)).view(B, C_out, C_in, W, H, U, V, k**4).sum(-1).sum(2) # print(o.size()) # end = time.perf_counter() # print('conv time:', end - start)
python
10
0.56242
145
32.404255
47
starcoderdata
package dmdb import ( "database/sql/driver" ) type Stmt struct { stmt driver.Stmt } func (c *Conn) Prepare(query string) (driver.Stmt, error) { stmt, err := c.conn.Prepare(query) if err != nil { return nil, err } return &Stmt{stmt: stmt}, nil } func (s *Stmt) NumInput() int { return s.stmt.NumInput() } func (s *Stmt) Close() error { return s.stmt.Close() } func (s *Stmt) Exec(args []driver.Value) (driver.Result, error) { return s.stmt.Exec(args) } func (s *Stmt) Query(args []driver.Value) (driver.Rows, error) { rows, err := s.stmt.Query(args) if err != nil { return nil, err } return &Rows{r: rows}, nil }
go
10
0.647709
65
17.617647
34
starcoderdata
import os import asyncio from traffic_generator import TrafficGenerator class Main(): @staticmethod def main(): url = os.getenv("TARGET_URL") tg = TrafficGenerator(url) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete( tg.run() ) if __name__ == "__main__": Main.main()
python
11
0.578534
46
18.1
20
starcoderdata
public string GetDefaultGroupPat() { string defaultGroupPat = App.ConfigData["DefaultGroupPat"]; // By default, it is Just My App. if (defaultGroupPat == null) { defaultGroupPat = @"[Just My App]"; } return defaultGroupPat; }
c#
12
0.501502
71
26.833333
12
inline
import styled from 'styled-components' const Link = styled.a` color: inherit; text-decoration: inherit; ` export default Link.extend` color: rgba(0, 0, 0, 0.7); `
javascript
5
0.694118
38
17.888889
9
starcoderdata
package de.innovationhub.prox.companyprofileservice.domain.company; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import de.innovationhub.prox.companyprofileservice.domain.company.language.Language; import de.innovationhub.prox.companyprofileservice.domain.company.quarter.Quarter; import de.innovationhub.prox.companyprofileservice.domain.core.AbstractEntity; import java.util.Set; import java.util.UUID; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.ManyToMany; import javax.persistence.OneToOne; import javax.validation.Valid; import javax.validation.constraints.NotNull; import lombok.AccessLevel; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.jpa.domain.support.AuditingEntityListener; @Data @Entity @NoArgsConstructor(access = AccessLevel.PROTECTED) @EntityListeners(AuditingEntityListener.class) public class Company extends AbstractEntity { @CreatedBy // @JsonIgnore @Column(unique = true) private UUID creatorId; @Embedded @NotNull private CompanyInformation information; @Embedded @Valid private Quarter headquarter; @ElementCollection @JsonInclude(Include.ALWAYS) private Set quarters; @ManyToMany @JsonIgnore private Set languages; @OneToOne @JsonIgnore private CompanyLogo companyLogo; @ElementCollection @JsonInclude(Include.ALWAYS) private Set branches; @ElementCollection @JsonInclude(Include.ALWAYS) private Set socialMedia; public Company( CompanyInformation information, Quarter headquarter, Set quarters, Set languages, Set branches, Set socialMedia) { this.setInformation(information); this.setHeadquarter(headquarter); this.setQuarters(quarters); this.setLanguages(languages); this.setBranches(branches); this.setSocialMedia(socialMedia); } public Company(CompanyInformation information) { this.setInformation(information); } public void setInformation(CompanyInformation information) { if (information == null) { throw new IllegalArgumentException("Company Information cannot be null"); } this.information = information; } }
java
11
0.796391
84
29.710843
83
starcoderdata
package webconfig const ( CondHTTPSvc_Header = "header" CondHTTPSvc_IPAddress = "ip-address" CondHTTPSvc_QueryString = "query-string" ) // ConditionalHTTPService serves an HTTP request according to a // condition based on a value in the header, query string or // ip address. type ConditionalHTTPService struct { // RuleType can be: header, query-string, or ip-address RuleType string `json:"rule-type"` // URLPath is the relative URL of the request; i.e. /robot.txt URLPath string `json:"url-path"` // ServeOnlyToCriteria are the related strings to match. i.e., // bingbot/2.0; +http://www.bing.com/bingbot.htm and // Googlebot/2.1; +http://www.google.com/bot.html can be // two string elements in the Vaues array that will be used to // match in the Header (User-Agent). For example, if the target url // is /robot.txt; it will only be served to google and bing bots. ServeOnlyToCriteria []string `json:"serve-only-to-criteria"` // HTTPStatusCode is http status code that will be retured, if // a match is found. The default is 404 (not found). HTTPStatusCode int `json:"http-status-code"` } type messageBanner struct { On bool `json:"on"` SecondsToDisplay int `json:"seconds-to-display"` // When the value of On changes from false to true // Tickout is set to SecondsToDisplay and then // decremented every second until the banner is closed // (on set to false). TickCount int `json:"tick-count"` } type httpx struct { AllowedMethods []string `json:"allowed-methods"` } // tlsFiles defines the location of the certificate and // private-key files. Both files must be // in PEM format. type tlsFiles struct { CertFilePath string `json:"cert-file-path"` KeyFilePath string `json:"key-file-path"` } type urlPaths struct { Restrict []string `json:"restrict"` Forward []string `json:"forward"` Exclude []string `json:"exclude"` ServeOnlyTo []ConditionalHTTPService `json:"conditional-http-service"` } // admin defines the IP addresses // of machines that connect to the server. // The admin pages (or app), whether hosted inside // the public site or in a separate environment // should be secured as such that it would be only // available via the localhost (i.e. on the local // machine or ssh tunnel) or a list of recognized // IP addresses. type admin struct { RunOnStartup bool `json:"run-on-sartup"` PortNo uint `json:"port-no"` AllowedIP []string `json:"allowed-ip"` } // siteStats holds the basic stat that can be // set in connstat. Every server can create one, // and handle connections accordingly; the active, // idel, and new states must be set and undated by // the web server. type siteStats struct { Active uint `json:"active"` Idle uint `json:"idle"` New uint `json:"new"` } type site struct { HostName string `json:"hostname"` AlternateHostNames []string `json:"alternate-host-names"` Proto string `json:"proto"` PortNo int `json:"portno"` } // Config is defines the fields that are typically required for // web configuration. All config values have to have a // presentation in this struct. type Config struct { refreshRate uint // in seconds WebRootPath string `json:"web-rootp-path"` AppDataPath string `json:"appdata-path"` ConnStat siteStats `json:"conn-stat"` ConfigFilePath string `json:"config-file-path"` ConfigFileLastHash string `json:"config-file-last-hash"` Admin admin `json:"admin"` HTTP httpx `json:"http"` Site site `json:"site"` URLPaths urlPaths `json:"url-paths"` // These are the offender IP addr. Their connections // are drop immediately, without any message returned to them. BlockedIP []string `json:"blocked-ip"` RedirectHTTPtoHTTPS bool `json:"redirect-http-to-https"` MaintenanceWindowOn bool `json:"maintenance-windowon"` MessageBanner messageBanner `json:"messagebanner"` //------------------------------------------------- // Delete these in version > v1.0.3 + 3 // HostName string `json:"hostname"` // Proto string `json:"proto"` // PortNo int `json:"portno"` // [2021-09-24] Removed; moved to the Site type. //------------------------------------------------- TLS tlsFiles `json:"tls"` Data map[string]string `json:"data"` } const ( cfgTemplateAll string = ` # ------------------------------------------------------------------ # About this config # --delimiter between key and value is space (one or many). # --comments must begin with #. # --one key/value per line; to continue to another line, # place a backslash (\) at the end of the statement. # --The headers and keys are case- insensitive, but the # following is the recommanded format: # SomeHeaderName # key_1 value_1 # All entries can appear with or without a header. # # Some of the config values are directly related to implementation # of feature within a Go website. Please, see the following template # for implementation of these feature. # https://github.com/kambahr/go-webstandard # ---------------------------------------------------------------------- # This is the hostname that will be accessed from the outside # i.e. mydomain.com. It may still be localhost if the website is # on a load balancer. Site hostname localhost # alternate-hostnames can be a local or public hostname. # e.g. myhost can be a local hostname, and mydomain.com # can be a public host name. alternate-hostnames portno 8085 proto http # location of certificate and private files; # both in the PEM format and must be full path. # The paths can be an local paths; but # /appdata/certs/<domain name>/ is recommended. TLS #cert /usr/local/mywebapp dir/appdata/certs/mydomain/certx.pem #key /usr/local/webapp dir/appdata/certs/mydomain/keyx.pem # This will affect the entire site; used for times that the whole # site needs to be worked on. Your app will have to response # to requests (and display a maint-page) accordingly. maintenance-window off Admin # List of IP address that will be allowed to access # the admin website; separated by comma; otherwise, the admin # section of the website will only be served to the local machine. allowed-ip-addr <ip add 1>, <ip add 2> run-on-startup yes portno 30000 # This message shows up on every request (page). # Users can dismiss the banner; their option is save in # a cookie (named banner) so that they don't keep seeing it after reading. # The message html template file is in /appdata/banner-msg.html. # Modify the "Your message goes here." with your own html/text. MessageBanner # Expected values: on/off. # Web server should react to this value (on/off) to place and remove # the banner from the end-user request. display-mode off # The banner message can be displayed for the below indicated value; # and then be automatically disabled (display-mode => off), when this # period elapses: # display-mode will be set to off from on. # A of value > 0 will trigger the auto-timeout. So, if you would like # to clear the banner message manually keep this value set to zero. seconds-to-display 0 # URL paths can be restricted, excluded and forwarded explicitly; the end-user # will receive the appropriate error message. # These option to make a portion of your site unavailable for maintenance # or other reasons. Each path must begin with a slash (relative path). # The following should be the order or evaluation: # restrict-paths, exclude-paths, forward-paths, conditional-http-service. URLPaths # restrict-paths <url paths separated by comma> # e.g. # restrict-paths /gallery,/accounting, /customer-review, /myblog restrict-paths # with the exclude option, files will be intact in the same location, but not # served; the end-user will receive 404 error; or the behaviour can be # customized. # exclude-paths /galleryx, /someotherpath exclude-paths # forward-paths <url-from|url-to-forward paths separated by comma>. # Note that forwarding to a fully qualified url must not be allowed. # e.g. # forward-paths /along-name-of-a-blog-page|/latest-blog, /another-along-name-of-a-blog-page|/best-of-blogs, \ # /and-more-and-more-pages|/yet-the-best-blog forward-paths # Conditional HTTP Service serves an HTTP request according to a # condition based on a value in the header, query string or # ip address. If a matching string is found the request will be # e.g. the following only allows the bing and google bots see the robot.txt file. # conditional-http-service [{"rule-type":"header","url-path":"/robot.txt","serve-only-to-criteria":["+http://www.bing.com/bingbot.htm","+http://www.google.com/bot.html"],"http-status-code":404}] conditional-http-service # HEAD and GET are generally allowed by default. HTTP allowed-methods GET, OPTIONS, CONNECT, HEAD # This section holds user-data. The following is the format. # Key...... no spaces # Value.... can include spaces. # The data value can be any text (hex, JSON, text, xml,..). # The delimiter is a new-line. # # Examples: # my-postgresql-conn-str User ID=root;Password= # my-json-value {"mylist":["v1","v2"]} # my-hex-value 68656c6c6f206f75742074686572652e206775697461722069732074686520736f6e67 Data ` cnfTemplateBlockedIP string = ` # ip addresses in this file will be blocked from connecting the website. # the following is the format: # <ip address><minimum of one space> # Example: # 10.12.3.4 <a short description of the reason> ` )
go
7
0.680173
197
37.157692
260
starcoderdata
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Residence extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'resp_id', 'fact_id', 'res_name', 'res_phone','facture_name', 'facture_email','facture_phone', 'res_adresse1', 'res_adresse2','res_ville','res_province','res_code_postal', 'created_at', 'updated_at','res_temps_repas' ]; public function User(){ return $this->belongsTo('App\User'); } }
php
10
0.632378
179
24.782609
23
starcoderdata
/** * Copyright 2008 The Scribble Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.scribble.ext.assrt.core.visit.gather; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import org.scribble.core.type.kind.ProtoKind; import org.scribble.core.type.name.DataName; import org.scribble.ext.assrt.core.type.name.AssrtIntVar; import org.scribble.ext.assrt.core.type.session.AssrtCoreChoice; import org.scribble.ext.assrt.core.type.session.AssrtCoreSType; public class AssrtCoreVarEnvGatherer<K extends ProtoKind, B extends AssrtCoreSType<K, B>> extends AssrtCoreSTypeGatherer<K, B, Map.Entry<AssrtIntVar, DataName>> { @Override public Stream<Map.Entry<AssrtIntVar, DataName>> visitChoice( AssrtCoreChoice<K, B> n) { return n.cases.keySet().stream() .flatMap(x -> x.pay.stream() .collect(Collectors.toMap(y -> y.var, y -> y.data)).entrySet() .stream()); } }
java
17
0.752225
100
35.525
40
starcoderdata
bool compile(const char *pattern, const char *options) { int nOptions = 0; for(const char *opt = options; opt && *opt; ++opt) { switch(*opt) { case 'i': nOptions |= PCRE_CASELESS; break; case 'x': nOptions |= PCRE_EXTENDED; break; case 'm': nOptions |= PCRE_MULTILINE; break; case 's': nOptions |= PCRE_DOTALL; break; } } //const char *error = 0; //int errorOfs = 0; if(re) pcre_free(re); re = pcre_compile(pattern, nOptions, &lastError, &errorOffset, 0); return !!re; }
c
10
0.512315
72
26.727273
22
inline
def get_fields(tab_fields): attributes = {} # remove trailing newline and split by semicolon description = tab_fields[-1].strip('\n') description = description.split(';') # Parse description for fields in description: if fields == "" or fields == " ": continue fields = fields.split() if fields[0] == '': fields = fields[1:] key = fields[0].replace('"', '') val = ' '.join(fields[1:]).replace('"', '') attributes[key] = val # Put in placeholders for important attributes (such as gene_id) if they # are absent if "gene_id" not in attributes: attributes["gene_id"] = "NULL" return attributes
python
13
0.58526
76
27.875
24
inline
#!/usr/bin/env python3 from setuptools import setup from plover_build_utils.setup import BuildPy, BuildUi BuildPy.build_dependencies.append('build_ui') BuildUi.hooks = ['plover_build_utils.pyqt:fix_icons'] CMDCLASS = { 'build_py': BuildPy, 'build_ui': BuildUi, } setup(cmdclass=CMDCLASS)
python
6
0.733333
53
20.428571
14
starcoderdata
package com.purplesky.coldweather.View; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.purplesky.coldweather.MainActivity; import com.purplesky.coldweather.R; import com.purplesky.coldweather.WeatherActivity; import com.purplesky.coldweather.db.City; import com.purplesky.coldweather.db.County; import com.purplesky.coldweather.db.Province; import com.purplesky.coldweather.util.CityUtility; public class ChooseAreaFragment extends Fragment { private static final int LEVEL_PROVINCE=0; private static final int LEVEL_CITY=1; private static final int LEVEL_COUNTY=2; private TextView title; private Button back; private RecyclerView cityList; private ProgressDialog dialog; private int level; private Province chooseProvince; private City chooseCity; private County chooseCounty; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.choose_area,container,false); title=view.findViewById(R.id.choose_area_title); back=view.findViewById(R.id.choose_area_back); cityList=view.findViewById(R.id.choose_area_list); cityList.addItemDecoration(new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL)); cityList.setLayoutManager(new LinearLayoutManager(getContext())); dialog=new ProgressDialog(getContext()); dialog.setCancelable(false); dialog.setCanceledOnTouchOutside(false); dialog.setMessage("加载中..."); //获取状态栏高度 if(getContext()instanceof WeatherActivity) { int statusBarHeight = 0; int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) statusBarHeight = getResources().getDimensionPixelSize(resourceId); view.findViewById(R.id.choose_area_frameLayout).setPadding(0, statusBarHeight, 0, 0); } return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); back.setOnClickListener(v->{ switch (level){ case LEVEL_CITY: RefreshProvinces(); break; case LEVEL_COUNTY: RefreshCities(chooseProvince); break; } }); RefreshProvinces(); dialog.show(); } private void RefreshProvinces(){ level=LEVEL_PROVINCE; back.setVisibility(View.GONE); title.setText("中国"); dialog.show(); new Thread(()->{ CityAdapter adapter=new CityAdapter(CityUtility.QueryProvinces(),CityAdapter.TYPE_PROVINCE,(province -> { chooseProvince =(Province)province; RefreshCities(chooseProvince); })); dialog.dismiss(); if(level==LEVEL_PROVINCE) getActivity().runOnUiThread(()-> cityList.setAdapter(adapter)); }).start(); } private void RefreshCities(Province province){ level=LEVEL_CITY; back.setVisibility(View.VISIBLE); title.setText(province.getName()); dialog.show(); new Thread(()->{ CityAdapter adapter=new CityAdapter(CityUtility.QueryCities(province),CityAdapter.TYPE_CITY,(city -> { chooseCity =(City)city; RefreshCounties(chooseCity); })); dialog.dismiss(); if(level==LEVEL_CITY) getActivity().runOnUiThread(()-> cityList.setAdapter(adapter)); }).start(); } private void RefreshCounties(City city){ level=LEVEL_COUNTY; back.setVisibility(View.VISIBLE); title.setText(city.getName()); dialog.show(); new Thread(()->{ CityAdapter adapter=new CityAdapter(CityUtility.QueryCounties(city),CityAdapter.TYPE_COUNTY,(county -> { chooseCounty=(County)county; if(getActivity() instanceof MainActivity) { Intent intent = new Intent(getContext(), WeatherActivity.class); intent.putExtra("weatherId", ((County) county).getWeatherId()); startActivity(intent); getActivity().finish(); } else if(getActivity() instanceof WeatherActivity){ WeatherActivity activity= (WeatherActivity) getActivity(); activity.weatherDrawerLayout.closeDrawers(); activity.RefreshWeather(((County) county).getWeatherId()); } })); dialog.dismiss(); if(level==LEVEL_COUNTY) getActivity().runOnUiThread(()-> cityList.setAdapter(adapter)); }).start(); } }
java
27
0.642437
132
36.736111
144
starcoderdata
def runTest(self): """ @summary: run test cases """ inner_pkt_types = [] if self.test_inner_ipv4: inner_pkt_types.append('ipv4') if self.test_inner_ipv6: inner_pkt_types.append('ipv6') outer_pkt_types = [] if self.test_outer_ipv4: outer_pkt_types.append('ipv4') if self.test_outer_ipv6: outer_pkt_types.append('ipv6') for outer_pkt_type in outer_pkt_types: for inner_pkt_type in inner_pkt_types: encap_combination = "{}in{}".format(inner_pkt_type.replace('ip', 'IP'), outer_pkt_type.replace('ip', 'IP')) logging.info('----------------------------------------------------------------------') logging.info("{} test started".format(encap_combination)) logging.info('----------------------------------------------------------------------') status = 'Failed' error = None try: self.run_encap_combination_test(outer_pkt_type, inner_pkt_type) except AssertionError, e: error = e # print error, but continue to test others encap traffic combinations print "\n{}:\n{}".format(encap_combination, error) sys.stdout.flush() else: status = 'Passed' self.summary[encap_combination] = status logging.info('----------------------------------------------------------------------') logging.info("{} test finished, status: {}".format(encap_combination, status)) logging.info('----------------------------------------------------------------------') self.print_summary() total = len(outer_pkt_types)*len(inner_pkt_types) passed = len(filter(lambda status: status == 'Passed', self.summary.values())) # assert all passed assert total == passed, "total tests {}, passed: {}".format(total, passed)
python
15
0.434296
102
39.509434
53
inline
//------------------------------------------------------------------------------ // Use SVPH to take the gradient of a FieldList. //------------------------------------------------------------------------------ #ifndef __Spheral__gradientFieldListSVPH__ #define __Spheral__gradientFieldListSVPH__ #include "Field/FieldList.hh" #include "Neighbor/ConnectivityMap.hh" #include "Kernel/TableKernel.hh" #include "Mesh/Mesh.hh" #include "Geometry/MathTraits.hh" #include namespace Spheral { template<typename Dimension, typename DataType> FieldList<Dimension, typename MathTraits<Dimension, DataType>::GradientType> gradientFieldListSVPH(const FieldList<Dimension, DataType>& fieldList, const FieldList<Dimension, typename Dimension::Vector>& position, const FieldList<Dimension, typename Dimension::SymTensor>& Hfield, const ConnectivityMap connectivityMap, const TableKernel W, const Mesh mesh, const bool firstOrderConsistent); } #endif
c++
14
0.580986
90
38.172414
29
starcoderdata
<?php use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Auth; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ //frontend route Route::get('/', 'Frontend\HomeController@index'); Route::get('resume', 'Frontend\ResumeController@index'); Route::get('portfolio', 'Frontend\PortfolioController@index')->name('portfolio'); Route::get('workdetails/{id}', 'Frontend\PortfolioController@portfolioindex')->name('workdetails'); Route::get('freelance', 'Frontend\FreelanceController@index'); Route::get('blog', 'Frontend\BlogController@index'); //CONTACT Route::get('contact', 'Frontend\ContactController@index'); Route::post('contact/send', 'Frontend\ContactController@contactinsert'); // Route::get('/blogdestails', 'Frontend\HomeController@index'); // Route::get('/', function () { // return view('frontend/page/home'); // }); //admin route Auth::routes(); Route::group(['prefix' => 'admin'],function () { Route::get('/', [App\Http\Controllers\HomeController::class, 'index'])->name('admin.dashboard'); //category Route::resource('category','Backend\CategoryController',['names' => 'admin.category'])->middleware('auth'); Route::post('category/update', 'Backend\CategoryController@categoryupdate')->name('admin.category.data.update')->middleware('auth'); Route::get('category/delete/data/{cat_id}', 'Backend\CategoryController@categorydelete')->middleware('auth'); Route::get('category/status/{cat_id}', 'Backend\CategoryController@changestatus')->middleware('auth'); //workskill Route::resource('workskill', 'Backend\WorkskillController',['names' => 'admin.work.skill'])->middleware('auth'); Route::post('work/skill/update', 'Backend\WorkskillController@skillupdate')->name('admin.work.skill.data.update')->middleware('auth'); Route::get('work/skill/data/{s_id}', 'Backend\WorkskillController@skilldelete')->middleware('auth'); Route::get('workskill/status/{s_id}', 'Backend\WorkskillController@skillstatus')->middleware('auth'); //work Route::resource('work','Backend\WorkController',['names' => 'admin.work'])->middleware('auth'); Route::post('/edit/work/','Backend\WorkController@update')->middleware('auth'); Route::post('/edit/work/single/{single_photo}/{single_id}','Backend\WorkController@editproductsingle')->middleware('auth'); Route::get('/delete/work/single/{single_photo}/{single_id}','Backend\WorkController@deleteproductsingle')->middleware('auth'); Route::get('/change/status/project/{id}', 'Backend\WorkController@changestatus')->middleware('auth'); Route::get('project/delete/{id}', 'Backend\WorkController@destroy')->middleware('auth'); //conact Route::resource('contact','Backend\ContactController',['names' => 'admin.contact'])->middleware('auth'); Route::get('contact/emailview/{id}', 'Backend\ContactController@readmessagestatus')->name('admin.contact.emailview')->middleware('auth'); //homepage Route::get('personalinfo/view', 'Backend\PersonalinfoController@personalview')->name('admin.personalinfo.view')->middleware('auth'); Route::get('personalinfo/edit/{id}', 'Backend\PersonalinfoController@personaledit')->name('admin.personalinfo.edit')->middleware('auth'); Route::post('personalinfo/update', 'Backend\PersonalinfoController@personalupdate')->name('admin.personalinfo.update')->middleware('auth'); Route::get('file/download/{id}', 'Backend\PersonalinfoController@downloadcv'); //Social-link Route::resource('sociallink','Backend\SociallinkController',['names' => 'admin.sociallink'])->middleware('auth'); Route::post('sociallink/update', 'Backend\SociallinkController@socialupdate')->name('admin.socail.update')->middleware('auth'); Route::get('sociallink/delete/data/{so_id}', 'Backend\SociallinkController@socaildelete')->middleware('auth'); Route::get('sociallink/status/{so_id}', 'Backend\SociallinkController@socailstatus')->middleware('auth'); //service Route::resource('service','Backend\ServiceController',['names' => 'admin.service'])->middleware('auth'); Route::post('service/update', 'Backend\ServiceController@serviceupdate')->name('admin.servicedata.update')->middleware('auth'); Route::get('service/delete/data/{sa_id}', 'Backend\ServiceController@servicedelete')->middleware('auth'); Route::get('service/status/{so_id}', 'Backend\ServiceController@servicestatus')->middleware('auth'); //education Route::resource('education','Backend\EducationController',['names' => 'admin.education'])->middleware('auth'); Route::post('education/update', 'Backend\EducationController@educationupdate')->name('admin.educationdata.update')->middleware('auth'); Route::get('education/delete/data/{edu_id}', 'Backend\EducationController@educationdelete')->middleware('auth'); Route::get('education/status/{edu_id}', 'Backend\EducationController@educationstatus')->middleware('auth'); //Experience Route::resource('experience','Backend\ExperienceController',['names' => 'admin.experience'])->middleware('auth'); Route::post('experience/update', 'Backend\ExperienceController@experienceupdate')->name('admin.experiencedata.update')->middleware('auth'); Route::get('experience/delete/data/{exp_id}', 'Backend\ExperienceController@experiencedelete')->middleware('auth'); Route::get('experience/status/{exp_id}', 'Backend\ExperienceController@experiencestatus')->middleware('auth'); //skillknowledge Route::resource('skillknowledge','Backend\SkillKnowledgeController',['names' => 'admin.skillknowledge'])->middleware('auth'); Route::post('skillknowledge/update', 'Backend\SkillKnowledgeController@skillknowledgeupdate')->name('admin.skillknowledgedata.update')->middleware('auth'); Route::get('skillknowledge/delete/data/{sk_id}', 'Backend\SkillKnowledgeController@skillknowledgedelete')->middleware('auth'); Route::get('skillknowledge/status/{sk_id}', 'Backend\SkillKnowledgeController@skillknowledgestatus')->middleware('auth'); //freelancee Route::resource('freelanceesite','Backend\FreelanceController',['names' => 'admin.freelanceesite'])->middleware('auth'); Route::get('freelanceesite/delete/{id}', 'Backend\FreelanceController@destroy')->middleware('auth'); Route::get('change/status/freelance/{id}', 'Backend\FreelanceController@status')->middleware('auth'); //Achievement Route::resource('achievementsite','Backend\AchievementController',['names' => 'admin.achievementsite'])->middleware('auth'); Route::get('achievementsite/delete/{id}', 'Backend\AchievementController@destroy')->middleware('auth'); Route::get('change/status/achievement/{id}', 'Backend\AchievementController@status')->middleware('auth'); //Research Route::resource('researchsite','Backend\ResearchController',['names' => 'admin.researchsite'])->middleware('auth'); Route::get('researchsite/delete/{id}', 'Backend\ResearchController@destroy')->middleware('auth'); Route::get('change/status/research/{id}', 'Backend\ResearchController@status')->middleware('auth'); //icon Route::get('iconsite', 'Backend\HomepageController@icon')->name('admin.iconsite')->middleware('auth'); });
php
18
0.71104
159
68.694444
108
starcoderdata
<?php namespace App\Helpers; class UploadUtility { public function makeDir() { } public function upload() { } public function getName() { } }
php
5
0.6
50
8.230769
26
starcoderdata
// // RNPDFView.h // App // // Created by on 3/1/16. // Copyright © 2016 Facebook. All rights reserved. // #import #import "UIView+React.h" @class RCTEventDispatcher; @interface RNPDFView : UIView @property(nonatomic, strong) NSString *src; @property(nonatomic, strong) NSString *path; @property(nonatomic, strong) NSString *rawData; @property(nonatomic, strong) NSNumber *pageNumber; @property(nonatomic, strong) NSNumber *zoom; @property(nonatomic, copy) RCTBubblingEventBlock onChange; @end
c
5
0.74397
58
21.5
24
starcoderdata
""" @author A.I. engineer/researcher & Software engineer Created on 31 December, 2017 @ 7:36 PM. Copyright © 2017. Victor. All rights reserved. """ import os from helpers import consts as cfg def get_data_titles(): return [get_single_title(f) for f in get_files()] def get_single_title(file): return os.path.basename(file).split('.')[0] def get_files(): files = [os.path.join(cfg.DATASET_DIR, f) for f in os.listdir(cfg.DATASET_DIR) if f[0] != '.'] return files def get_stories(count=None): """ Retrieves dataset stories. :param count: int Number of stories to get. :return: stories, dict A dictionary containing story titles (key) and story body (value) """ stories = {} # Limit the number of files to retrieve. files = get_files()[:count] if count else get_files() for file in files: story = get_story_from_file(file) title = story['title'] body = story['body'] stories[title] = body return stories def get_story_from_file(file): """Retrieve a single story. :param file: str Story file location :return: story, dict Returns a dictionary => {title: body} """ story = {'title': get_single_title(file)} with open(file, mode='r', encoding='utf-8') as f: body = f.readlines() body = [line.strip() for line in body if len(line.strip()) > 1] story['body'] = body return story def get_story_file(title): """Retrieves the file for a story title. :param title: str Story title. :return: str Story filename. """ files = get_files() for file in files: if get_single_title(file).lower() == title.lower(): return file return None def get_story_from_title(title): file = get_story_file(title) return get_story_from_file(file)
python
14
0.594344
71
21.356322
87
starcoderdata
"use strict"; require('../../../ES-mess'); process.env.NODE_ENV = "test"; var chai = require('chai'); var assert = chai.assert; chai.use(require('chai-as-promised')); var googlePlusHeuristic = require('../../../expressionDomain/heuristics/googleplus'); describe('Google+ expression domain heuristics', function(){ it('https://plus.google.com/', function(){ var edNameP = googlePlusHeuristic.getExpressionDomainName('https://plus.google.com/'); return assert.eventually.strictEqual(edNameP, "plus.google.com"); }); it('https://plus.google.com/+1226digital/posts/iqV9xmRr35z', function(){ var edNameP = googlePlusHeuristic.getExpressionDomainName('https://plus.google.com/+1226digital/posts/iqV9xmRr35z'); return assert.eventually.strictEqual(edNameP, "Google+/+1226digital"); }); it('https://plus.google.com/+2D2Comunicaci%C3%B3nAlicante', function(){ var edNameP = googlePlusHeuristic.getExpressionDomainName('https://plus.google.com/+2D2Comunicaci%C3%B3nAlicante'); return assert.eventually.strictEqual(edNameP, "Google+/+2D2ComunicaciónAlicante"); }); it('https://plus.google.com/+ABSocialMedia00/videos', function(){ var edNameP = googlePlusHeuristic.getExpressionDomainName('https://plus.google.com/+ABSocialMedia00/videos'); return assert.eventually.strictEqual(edNameP, "Google+/+ABSocialMedia00"); }); it('https://plus.google.com/+Glowsocialmedia/about', function(){ var edNameP = googlePlusHeuristic.getExpressionDomainName('https://plus.google.com/+Glowsocialmedia/about'); return assert.eventually.strictEqual(edNameP, "Google+/+Glowsocialmedia"); }); it('https://plus.google.com/100128576451029402431', function(){ var edNameP = googlePlusHeuristic.getExpressionDomainName('https://plus.google.com/100128576451029402431'); return assert.eventually.strictEqual(edNameP, "Google+/100128576451029402431"); }); it('https://plus.google.com/100896917030455742495/about', function(){ var edNameP = googlePlusHeuristic.getExpressionDomainName('https://plus.google.com/100896917030455742495/about'); return assert.eventually.strictEqual(edNameP, "Google+/100896917030455742495"); }); it('https://plus.google.com/collection/A4-KAB', function(){ var edNameP = googlePlusHeuristic.getExpressionDomainName('https://plus.google.com/collection/A4-KAB'); return assert.eventually.strictEqual(edNameP, "Google+/collection/A4-KAB"); }); it('https://plus.google.com/collection/sivre', function(){ var edNameP = googlePlusHeuristic.getExpressionDomainName('https://plus.google.com/collection/sivre'); return assert.eventually.strictEqual(edNameP, "Google+/collection/sivre"); }); it('https://plus.google.com/communities/100250373099590631205/stream/bca6eb89-ffc7-406c-a6b8-2686542d45af', function(){ var edNameP = googlePlusHeuristic.getExpressionDomainName('https://plus.google.com/communities/100250373099590631205/stream/bca6eb89-ffc7-406c-a6b8-2686542d45af'); return assert.eventually.strictEqual(edNameP, "Google+/communities/100250373099590631205"); }); it('https://plus.google.com/communities/100354381402619402956', function(){ var edNameP = googlePlusHeuristic.getExpressionDomainName('https://plus.google.com/communities/100354381402619402956'); return assert.eventually.strictEqual(edNameP, "Google+/communities/100354381402619402956"); }); it('https://plus.google.com/events/c9gm7r6v7i7bvmsf7ath877aeb4', function(){ var edNameP = googlePlusHeuristic.getExpressionDomainName('https://plus.google.com/events/c9gm7r6v7i7bvmsf7ath877aeb4'); return assert.eventually.strictEqual(edNameP, "Google+/events/c9gm7r6v7i7bvmsf7ath877aeb4"); }); it('Invalid URLs', function(){ return Promise.all([ 'https://plus.google.com/app/basic/102657414620214529142/posts?cbp=13gakcdnuy905&sview=28&cid=5&soc-app=115&soc-platform=1&spath=/app/basic/s&sparm=cbp%3D1wmyu24jukd4b%26sview%3D28%26sq%3DMicrosoft%26sc%3Dpo' ].map(function(url){ var edNameP = googlePlusHeuristic.getExpressionDomainName(url); return assert.isRejected(edNameP, url+' should be an invalid URL for the Slideshare heuristics'); })); }); });
javascript
23
0.690742
220
44.7
100
starcoderdata
@Override public void executeStage() throws ElkException { if (loader_ != null && !loader_.isLoadingFinished()) { final boolean registered = ontologyIndex_ .addIndexingUnsupportedListener( AXIOM_INDEXING_UNSUPPORTED_LISTENER); try { loader_.load(axiomInsertionProcessor_, axiomDeletionProcessor_); } finally { if (registered) { ontologyIndex_.removeIndexingUnsupportedListener( AXIOM_INDEXING_UNSUPPORTED_LISTENER); } } } if (classQueryLoader_ != null && !classQueryLoader_.isLoadingFinished()) { final boolean registered = ontologyIndex_ .addIndexingUnsupportedListener( QUERY_INDEXING_UNSUPPORTED_LISTENER); try { classQueryLoader_.load(classQueryInsertionProcessor_, classQueryDeletionProcessor_); } finally { if (registered) { ontologyIndex_.removeIndexingUnsupportedListener( QUERY_INDEXING_UNSUPPORTED_LISTENER); } } } if (entailmentQueryLoader_ != null && !entailmentQueryLoader_.isLoadingFinished()) { // TODO: messages for the user final boolean registered = ontologyIndex_ .addIndexingUnsupportedListener( QUERY_INDEXING_UNSUPPORTED_LISTENER); try { entailmentQueryLoader_.load(entailmentQueryInserter_, entailmentQueryDeleter_); } finally { if (registered) { ontologyIndex_.removeIndexingUnsupportedListener( QUERY_INDEXING_UNSUPPORTED_LISTENER); } } } }
java
13
0.702628
68
29.787234
47
inline
'use strict'; const numbers = [1, 2, 3, 4]; // Add your code here //filters out all the even numbers ==> returns [1,3] const oddsFilter = numbers.filter(i => i % 2 != 0) //doubles the odd numbers only (1,3) const doubled = oddsFilter.map(i => i * 2); console.log("the thrown away numbers are: " + oddsFilter); console.log("The doubled numbers are: " + doubled);
javascript
8
0.657609
58
23.533333
15
starcoderdata
package messages import ( "encoding/json" "time" ) type DateTime time.Time func (t *DateTime) UnmarshalText(text []byte) error { return (*xsdDateTime)(t).UnmarshalText(text) } func (t DateTime) MarshalText() ([]byte, error) { return xsdDateTime(t).MarshalText() } type Date time.Time func (t *Date) UnmarshalText(text []byte) error { return (*xsdDate)(t).UnmarshalText(text) } func (t Date) MarshalText() ([]byte, error) { return xsdDate(t).MarshalText() } func (t Date) String() string { return (time.Time)(t).Format("2006-01-02") } // Must match the pattern [0-9]{18} type GSRNEANCode string // Must be at least 1 char long type TextType string type QueryReasonTypeCode int const ( Dagstand QueryReasonTypeCode = iota + 1 Intervalstand Maandstand_recovery ) var queryReasonTypeCodeToString = map[QueryReasonTypeCode]string{ Dagstand: "DAY", Intervalstand: "INT", Maandstand_recovery: "RCY", } var queryReasonTypeCodeToDescription = map[QueryReasonTypeCode]string{ Dagstand: "Dagstand", Intervalstand: "Intervalstand", Maandstand_recovery: "Maandstand", } var stringToQueryReasonTypeCode = map[string]QueryReasonTypeCode{ "DAY": Dagstand, "INT": Intervalstand, "RCY": Maandstand_recovery, } func (t *QueryReasonTypeCode) UnmarshalText(text []byte) error { s := stringToQueryReasonTypeCode[string(text)] *t = s return nil } func (t QueryReasonTypeCode) MarshalText() ([]byte, error) { return []byte(queryReasonTypeCodeToString[t]), nil } func (t QueryReasonTypeCode) MarshalJSON() ([]byte, error) { return json.Marshal(queryReasonTypeCodeToDescription[t]) } func (t QueryReasonTypeCode) String() string { return queryReasonTypeCodeToDescription[t] } // May be no more than 3 chars long type RejectionReasonType string // Must be at least 1 char long type EnergyMeterIDType string // Must be at least 1 char long type EnergyRegisterIDType int const ( VerbruikTotaal EnergyRegisterIDType = iota + 1 VerbruikLaag VerbruikNormaal TerugleveringTotaal TerugleveringLaag TerugleveringNormaal ) var energyRegisterTypeToString = map[EnergyRegisterIDType]string{ VerbruikTotaal: "1.8.0", VerbruikLaag: "1.8.1", VerbruikNormaal: "1.8.2", TerugleveringTotaal: "2.8.0", TerugleveringLaag: "2.8.1", TerugleveringNormaal: "2.8.2", } var energyRegisterTypeToDescription = map[EnergyRegisterIDType]string{ VerbruikTotaal: "Verbruik Totaal", VerbruikLaag: "Verbruik Laag", VerbruikNormaal: "Verbruik Normaal", TerugleveringTotaal: "Teruglevering Totaal", TerugleveringLaag: "Teruglevering Laag", TerugleveringNormaal: "Teruglevering Normaal", } var stringToEnergyRegisterType = map[string]EnergyRegisterIDType{ "1.8.0": VerbruikTotaal, "1.8.1": VerbruikLaag, "1.8.2": VerbruikNormaal, "2.8.0": TerugleveringTotaal, "2.8.1": TerugleveringLaag, "2.8.2": TerugleveringNormaal, } func (t *EnergyRegisterIDType) UnmarshalText(text []byte) error { s := stringToEnergyRegisterType[string(text)] *t = s return nil } func (t EnergyRegisterIDType) MarshalText() ([]byte, error) { return []byte(energyRegisterTypeToString[t]), nil } func (t EnergyRegisterIDType) MarshalJSON() ([]byte, error) { return json.Marshal(energyRegisterTypeToDescription[t]) } func (t EnergyRegisterIDType) String() string { return energyRegisterTypeToDescription[t] } type MeasureUnitCode int const ( KVAR MeasureUnitCode = iota + 1 KWH KW NormaalM3 M3 WH DM3 MJ GroningenM3 GroningenM3_per_Hour M3_per_hour ) var measureUnitCodeToString = map[MeasureUnitCode]string{ KVAR: "KVR", KWH: "KWH", KW: "KWT", NormaalM3: "M3N", M3: "MTQ", WH: "WH", DM3: "DM3", MJ: "MJ", GroningenM3: "M3N3517", GroningenM3_per_Hour: "M3N3517HR", M3_per_hour: "MQH", } var measureUnitCodeToDescription = map[MeasureUnitCode]string{ KVAR: "kVAR", KWH: "kWh", KW: "KW", NormaalM3: "NormaalM3", M3: "m3", WH: "wh", DM3: "dm3", MJ: "MJ", GroningenM3: "m3 (Groningen) ", GroningenM3_per_Hour: "m3/h (Groningen)", M3_per_hour: "m3/h", } var stringToMeasureUnitCode = map[string]MeasureUnitCode{ "KVR": KVAR, "KWH": KWH, "KWT": KW, "M3N": NormaalM3, "MTQ": M3, "WH": WH, "DM3": DM3, "MJ": MJ, "M3N3517": GroningenM3, "M3N3517HR": GroningenM3_per_Hour, "MQH": M3_per_hour, } func (t *MeasureUnitCode) UnmarshalText(text []byte) error { s := stringToMeasureUnitCode[string(text)] *t = s return nil } func (t MeasureUnitCode) MarshalText() ([]byte, error) { return []byte(measureUnitCodeToString[t]), nil } func (t MeasureUnitCode) MarshalJSON() ([]byte, error) { return json.Marshal(measureUnitCodeToDescription[t]) } func (t MeasureUnitCode) String() string { return measureUnitCodeToDescription[t] }
go
10
0.668235
70
22.502304
217
starcoderdata
import os from abc import ABC, abstractmethod from typing import ( Any, Dict, Optional, List, Type, Union, Callable, ) import pydoc from loguru import logger import datetime import yaml import appdirs from . import _fwd from ._modules import Checker, Searcher, ResourceLoader class Cache: """Used to track state between levels of recursion to stop infinite loops, and to optimise repeating actions""" _cache: Dict[Any, Dict[str, Any]] = {} def mark_ctext(self, ctext: Any) -> bool: if (type(ctext) == str or type(ctext) == bytes) and len(ctext) < 4: logger.trace(f"Candidate {ctext} too short!") return False if ctext in self._cache: logger.trace(f"Deduped {ctext}") return False self._cache[ctext] = {} return True def get_or_update(self, ctext: Any, keyname: str, get_value: Callable[[], Any]): # Should have been marked first target = self._cache[ctext] res = target.get(keyname) if res is not None: return res val = get_value() target[keyname] = val return val def split_resource_name(full_name: str) -> (str, str): return full_name.split("::", 1) class Config: verbosity: int = 0 searcher: str = "perfection" params: Dict[str, Dict[str, Union[str, List[str]]]] = {} format: Dict[str, str] = {"in": "str", "out": "str"} modules: List[str] = [] checker: str = "brandon" default_dist: str = "cipheydists::dist::twist" timeout: Optional[int] = None _inst: Dict[type, Any] = {} objs: Dict[str, Any] = {} cache: Cache = Cache() @staticmethod def get_default_dir() -> str: return appdirs.user_config_dir("ciphey") def merge_dict(self, config_file: Optional[Dict[str, Any]]): if config_file is None: return for a, b in config_file.items(): self.update(a, b) def load_file(self, path: str = os.path.join(get_default_dir.__func__(), "config.yml"), create=False): try: with open(path, "r+") as file: return self.merge_dict(yaml.safe_load(file)) except FileNotFoundError: if create: open(path, "w+") def instantiate(self, t: type) -> Any: """ Used to enable caching of a instantiated type after the configuration has settled """ # We cannot use set default as that would construct it again, and throw away the result res = self._inst.get(t) if res is not None: return res ret = t(self) self._inst[t] = ret return ret def __call__(self, t: type) -> Any: return self.instantiate(t) def update(self, attrname: str, value: Optional[Any]): if value is not None: setattr(self, attrname, value) def update_param(self, owner: str, name: str, value: Optional[Any]): if value is None: return target = self.params.setdefault(owner, {}) if _fwd.registry.get_named(owner).getParams()[name].list: target.setdefault(name, []).append(value) else: target[name] = value def update_format(self, paramname: str, value: Optional[Any]): if value is not None: self.format[paramname] = value def load_objs(self): # Basic type conversion if self.timeout is not None: self.objs["timeout"] = datetime.timedelta(seconds=int(self.timeout)) self.objs["format"] = { key: pydoc.locate(value) for key, value in self.format.items() } # Checkers do not depend on anything self.objs["checker"] = self(_fwd.registry.get_named(self.checker, Checker)) # Searchers only depend on checkers self.objs["searcher"] = self(_fwd.registry.get_named(self.searcher, Searcher)) def update_log_level(self, verbosity: Optional[int]): if verbosity is None: return self.verbosity = verbosity quiet_list = [ "ERROR", "CRITICAL", ] loud_list = [ "DEBUG", "TRACE" ] verbosity_name: str if verbosity == 0: verbosity_name = "WARNING" elif verbosity >= 0: verbosity_name = loud_list[min(len(loud_list), verbosity) - 1] else: verbosity_name = quiet_list[min(len(quiet_list), -verbosity) - 1] from loguru import logger import sys logger.remove() if self.verbosity is None: return logger.configure() if self.verbosity > 0: logger.add(sink=sys.stderr, level=verbosity_name, colorize=sys.stderr.isatty()) logger.opt(colors=True) else: logger.add( sink=sys.stderr, level=verbosity_name, colorize=False, format="{message}" ) logger.debug(f"Verbosity set to level {verbosity} ({verbosity_name})") def load_modules(self): import importlib.util for i in self.modules: spec = importlib.util.spec_from_file_location("ciphey.module_load_site", i) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) def get_resource(self, res_name: str, t: Optional[Type] = None) -> Any: logger.trace(f"Loading resource {res_name} of type {t}") # FIXME: Actually returns obj of type `t`, but python is bad loader, name = split_resource_name(res_name) if t is None: return self(_fwd.registry.get_named(loader, ResourceLoader))(name) else: return self(_fwd.registry.get_named(loader, ResourceLoader[t]))(name) def __str__(self): return str({ "verbosity": self.verbosity, "searcher": self.searcher, "params": self.params, "format": self.format, "modules": self.modules, "checker": self.checker, "default_dist": self.default_dist, "timeout": self.timeout }) _fwd.config = Config
python
18
0.572745
115
29.472906
203
starcoderdata
import React from 'react'; import PropTypes from 'prop-types'; import { AssistiveText, ControlLabel } from 'src/elements/forms/utils'; import { removeSomeProps } from 'src/utils/componentHelpers'; import { defaultControlStyles, spaceProps, typography, } from 'src/utils/styledHelpers'; const renderControlGroupLabel = propsFromControlGroup => { const { activeColor, bg: bgColorFromProps, disabled, controlId, controlLabelProps, hideLabel, text, validationError, } = propsFromControlGroup; if (!text || hideLabel) { return null; } const labelProps = { activeColor, bg: bgColorFromProps, ...controlLabelProps, disabled, htmlFor: controlId, validationError, }; return ( <ControlLabel {...labelProps}> {text} ); }; const renderAssistiveContent = propsFromControlGroup => { const { assistiveText, validationError } = propsFromControlGroup; if (validationError.length > 0) { return validationError; } return assistiveText; }; const renderControlGroupAssistive = propsFromControlGroup => { const { assistiveText, assistiveTextProps, controlId: id, validationError: error, } = propsFromControlGroup; if (!assistiveText && !error) { return null; } if (assistiveText && !error) { return <AssistiveText id={`${id}Help`} {...assistiveTextProps}>{renderAssistiveContent(propsFromControlGroup)} } return <AssistiveText color="brandDanger" id={`${id}Error`} {...assistiveTextProps}>{renderAssistiveContent(propsFromControlGroup)} }; const propsToTrim = [ 'activeColor', 'assistiveText', 'assistiveTextProps', 'controlGroupProps', 'controlId', 'controlLabelProps', 'disabled', 'hideLabel', 'labelText', 'name', 'validationError', ...Object.keys(spaceProps.propTypes), ...Object.keys(typography.propTypes), ]; export const ControlGroupComponent = ({ children, ...props }) => { const { activeColor, assistiveText, assistiveTextProps, bg: bgColorFromProps, controlId, controlLabelProps, disabled, hideLabel, labelText, name, validationError, } = props; const nextControlId = controlId || name; const labelProps = { activeColor, bg: bgColorFromProps, controlId: nextControlId, controlLabelProps, disabled, hideLabel, text: labelText, validationError, }; const assistiveProps = { assistiveText, assistiveTextProps, controlId: nextControlId, validationError, }; return ( <div {...removeSomeProps(props, propsToTrim)}> {children} {renderControlGroupLabel(labelProps)} {renderControlGroupAssistive(assistiveProps)} ); }; ControlGroupComponent.propTypes = { ...spaceProps.propTypes, ...typography.propTypes, activeColor: PropTypes.string, assistiveText: PropTypes.oneOfType([ PropTypes.object, PropTypes.string, ]), bg: PropTypes.string, children: PropTypes.any.isRequired, controlId: PropTypes.string, controlLabelProps: PropTypes.object, disabled: PropTypes.bool, hideLabel: PropTypes.bool, labelText: PropTypes.string, name: PropTypes.string, validationError: PropTypes.oneOfType([ PropTypes.bool, PropTypes.string, ]), }; ControlGroupComponent.defaultProps = { activeColor: defaultControlStyles.activeColor, assistiveText: '', bg: defaultControlStyles.bg, controlId: '', controlLabelProps: {}, disabled: false, hideLabel: false, labelText: '', name: '', validationError: '', };
javascript
14
0.694321
150
22.788079
151
starcoderdata
protected override async Task ApplyResponseGrantAsync() { var options = Options as Saml2AuthenticationOptions; if (options == null) { return; } // handle sign-out response if (options.SingleLogoutServiceResponsePath.HasValue && options.SingleLogoutServiceResponsePath == (Request.PathBase + Request.Path)) { await ApplyResponseLogoutAsync(); return; } // handle sign-out request if (options.SingleLogoutServiceRequestPath.HasValue && options.SingleLogoutServiceRequestPath == (Request.PathBase + Request.Path)) { await ApplyRequestLogoutAsync(); return; } var signout = Helper.LookupSignOut(Options.AuthenticationType, Options.AuthenticationMode); if (signout == null) { return; } if (_configuration == null) { _configuration = await options.ConfigurationManager.GetConfigurationAsync(Context.Request.CallCancelled); } // reusing the SingleSignOnService location from the configuration to determine the destination var issuer = options.Wtrealm; var destination = _configuration.TokenEndpoint ?? string.Empty; ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("issuer={0}", "destination={1}", issuer, destination)); var properties = signout.Properties; if (string.IsNullOrEmpty(properties.RedirectUri)) { properties.RedirectUri = options.SignOutWreply ?? GetCurrentUri(); } ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("RedirectUri={0}", properties.RedirectUri)); var state = new Dictionary<string, string> { { _relayStateWctx, Options.StateDataFormat.Protect(properties) } }; var binding = new Saml2RedirectBinding(); binding.SetRelayStateQuery(state); var redirectBinding = binding.Bind(new Saml2LogoutRequest { Issuer = new EndpointReference(issuer), Destination = new EndpointAddress(destination) }, options.SigningCertificate); var redirectLocation = redirectBinding.RedirectLocation.AbsoluteUri; if (!Uri.IsWellFormedUriString(redirectLocation, UriKind.Absolute)) { ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("The sign-out redirect URI is malformed: {0}", redirectLocation)); } ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("redirectLocation={0}", redirectLocation)); Response.Redirect(redirectLocation); }
c#
17
0.740541
142
29.846154
78
inline
/*export */ class Photos { constructor(id, large, medium, small, thumbnail) { this.id = id; this.large= large; this.medium = medium; this.small = small; this.thumbnail = thumbnail; } } module.exports = { Photos: Photos };
javascript
8
0.618474
52
18.153846
13
starcoderdata
import java.util.Arrays; import java.util.Queue; public class QueuePriority { public int MAX; private int[] array; private int item; public QueuePriority() { MAX = 5; array = new int[MAX]; item = 0; } public void insert(int val) { int i; if (item == 0) { array[0] = val; item++; return; } for (i = item - 1; i >= 0; i--) { if (val > array[i]) { array[i+1] = array[i]; } else { break; } } array[i + 1] = val; item++; } public void print() { for (int i = 0; i < item; i++) { System.out.println(array[i] + ""); } } public int remove() { return array[--item]; } public boolean isEmpty() { return item == 0; } }
java
13
0.410456
46
16.288462
52
starcoderdata
function instanceOf(lobj, rConstructor) { /** * 左边是实例,右边是构造函数. * 通过Object.getPrototypeOf(实例) 来获得这个实例的原型 */ let rProto = rConstructor.prototype; let lProto = Object.getPrototypeOf(lobj); while (lProto) { if (lProto === rProto) return true; lProto = Object.getPrototypeOf(lProto); } return false; } (function() { let ss = new SS(); console.log(instanceOf(ss, Object)) console.log(instanceOf(ss, SS)) })()
javascript
14
0.629555
47
23.75
20
starcoderdata
# -*- coding: utf-8 -*- """ @File : target.py @Time : 2019/11/14 下午5:03 @Author : yizuotian @Description : """ import tensorflow as tf from tensorflow.python.keras import layers from utils.tf_utils import remove_pad def target_graph(gt_boxes, gt_class_ids, anchors, num_anchors, positive_iou_threshold, negative_iou_threshold): """ :param gt_boxes: [max_gt_num,(y1,x1,y2,x2,tag)] :param gt_class_ids: [max_gt_num,(class_id,tag)] :param anchors: [num_anchors,(y1,x1,y2,x2)] :param num_anchors: :param positive_iou_threshold: :param negative_iou_threshold: :return deltas: [num_anchors,(dy,dx,dh,dw) :return class_ids: [num_anchors] :return anchors_tag: [num_anchors] 1-positive,-1:negative,0-ignore """ gt_boxes = remove_pad(gt_boxes) gt_class_ids = remove_pad(gt_class_ids)[:, 0] # gt boxes为0时,增加一个虚拟的背景boxes;防止后续计算ious时为空 gt_boxes, gt_class_ids = tf.cond(tf.size(gt_boxes) > 0, true_fn=lambda: [gt_boxes, gt_class_ids], false_fn=lambda: [tf.constant([[0., 0., 1., 1.]], dtype=tf.float32), tf.constant([[0]], dtype=tf.int32)]) ious = compute_iou(gt_boxes, anchors) anchors_iou_max = tf.reduce_max(ious, axis=0) # [num_anchors] anchors_match_gt_indices = tf.argmax(ious, axis=0) # [num_anchors] match_gt_boxes = tf.gather(gt_boxes, anchors_match_gt_indices) match_gt_class_ids = tf.gather(gt_class_ids, anchors_match_gt_indices) # 正负样本标志;1-positive,-1:negative,0-ignore anchors_tag = tf.where(anchors_iou_max >= positive_iou_threshold, tf.ones_like(anchors_iou_max), tf.where(anchors_iou_max < negative_iou_threshold, -1 * tf.ones_like(anchors_iou_max), tf.zeros_like(anchors_iou_max))) # 越界anchors忽略 keep_mask = tf.logical_and(anchors[:, 0] >= 0., tf.logical_and(anchors[:, 1] >= 0., tf.logical_and(anchors[:, 2] < 1., anchors[:, 3] < 1.))) anchors_tag = tf.where(keep_mask, anchors_tag, tf.zeros_like(anchors_tag)) # 回归目标 deltas = regress_target(anchors, match_gt_boxes) # 分类目标,负样本和ignore的class_id都为0 class_ids = tf.where(anchors_iou_max >= positive_iou_threshold, match_gt_class_ids, tf.zeros_like(anchors_iou_max, tf.int32)) class_ids.set_shape([num_anchors]) return [deltas, class_ids, anchors_tag] def regress_target(anchors, gt_boxes): """ 计算回归目标 :param anchors: [N,(y1,x1,y2,x2)] :param gt_boxes: [N,(y1,x1,y2,x2)] :return: [N,(y1,x1,y2,x2)] """ # 高度和宽度 h = anchors[:, 2] - anchors[:, 0] w = anchors[:, 3] - anchors[:, 1] gt_h = gt_boxes[:, 2] - gt_boxes[:, 0] gt_w = gt_boxes[:, 3] - gt_boxes[:, 1] # 中心点 center_y = (anchors[:, 2] + anchors[:, 0]) * 0.5 center_x = (anchors[:, 3] + anchors[:, 1]) * 0.5 gt_center_y = (gt_boxes[:, 2] + gt_boxes[:, 0]) * 0.5 gt_center_x = (gt_boxes[:, 3] + gt_boxes[:, 1]) * 0.5 # 回归目标 dy = (gt_center_y - center_y) / h dx = (gt_center_x - center_x) / w dh = tf.log(gt_h / h) dw = tf.log(gt_w / w) target = tf.stack([dy, dx, dh, dw], axis=1) target /= tf.constant([0.1, 0.1, 0.2, 0.2]) # target = tf.where(tf.greater(target, 100.0), 100.0, target) return target def compute_iou(gt_boxes, anchors): """ 计算iou :param gt_boxes: [N,(y1,x1,y2,x2)] :param anchors: [M,(y1,x1,y2,x2)] :return: IoU [N,M] """ gt_boxes = tf.expand_dims(gt_boxes, axis=1) # [N,1,4] anchors = tf.expand_dims(anchors, axis=0) # [1,M,4] # 交集 intersect_w = tf.maximum(0.0, tf.minimum(gt_boxes[:, :, 3], anchors[:, :, 3]) - tf.maximum(gt_boxes[:, :, 1], anchors[:, :, 1])) intersect_h = tf.maximum(0.0, tf.minimum(gt_boxes[:, :, 2], anchors[:, :, 2]) - tf.maximum(gt_boxes[:, :, 0], anchors[:, :, 0])) intersect = intersect_h * intersect_w # 计算面积 area_gt = (gt_boxes[:, :, 3] - gt_boxes[:, :, 1]) * \ (gt_boxes[:, :, 2] - gt_boxes[:, :, 0]) area_anchor = (anchors[:, :, 3] - anchors[:, :, 1]) * \ (anchors[:, :, 2] - anchors[:, :, 0]) # 计算并集 union = area_gt + area_anchor - intersect # 交并比 iou = tf.divide(intersect, union, name='regress_target_iou') return iou class SSDTarget(layers.Layer): def __init__(self, anchors, positive_iou_threshold, negative_iou_threshold, **kwargs): self.anchors = anchors self.num_anchors = len(anchors) self.positive_iou_threshold = positive_iou_threshold self.negative_iou_threshold = negative_iou_threshold super(SSDTarget, self).__init__(**kwargs) def call(self, inputs, **kwargs): """ :param inputs: inputs[0] gt_boxes: [B,max_gt_num,(y1,x1,y2,x2,tag)] inputs[1] gt_class_ids: [B,max_gt_num,(class_id,tag)], :param kwargs: :return: """ gt_boxes, gt_class_ids = inputs anchors = tf.constant(self.anchors, dtype=tf.float32) options = {"anchors": anchors, "num_anchors": self.num_anchors, "positive_iou_threshold": self.positive_iou_threshold, "negative_iou_threshold": self.negative_iou_threshold} outputs = tf.map_fn(lambda x: target_graph(*x, **options), elems=[gt_boxes, gt_class_ids], dtype=[tf.float32, tf.int32, tf.float32]) return outputs def compute_output_shape(self, input_shape): batch_size, anchors_num = input_shape[0][:2] return [(batch_size, anchors_num, 4), # deltas (batch_size, anchors_num), # class_ids (batch_size, anchors_num) # anchors_tag ] def test(): sess = tf.Session() anchors_iou_max = tf.constant([0.5, 0.4, 0.3, 0.6, 0.1]) anchors_tag = tf.where(anchors_iou_max >= 0.5, tf.ones_like(anchors_iou_max), tf.where(anchors_iou_max < 0.4, tf.ones_like(anchors_iou_max) * -1, tf.zeros_like(anchors_iou_max))) print(sess.run(anchors_tag)) if __name__ == '__main__': test() # a = tf.constant([1, 1, 1, 1]) # x = tf.ones_like(a) # idx = tf.constant([[1], [3]]) # v = tf.constant([1, 1]) # y = tf.tensor_scatter_update(a, idx, [0, 0]) # # z = tf.scatter_update(x, idx, v) # sess.run(tf.global_variables_initializer()) # print(sess.run(tf.scatter_nd(idx, v, [8]))) # print(sess.run(y)) # print(sess.run(z)) # g = tf.Graph() # with g.as_default(): # a = tf.Variable(initial_value=[[0, 0, 0, 0], [0, 0, 0, 0]]) # b = tf.scatter_update(a, [0, 1], [[1, 1, 0, 0], [1, 0, 4, 0]]) # # with tf.Session(graph=g) as sess: # sess.run(tf.global_variables_initializer()) # print(sess.run(a)) # print(sess.run(b))
python
14
0.526776
111
36.927461
193
starcoderdata
package com.ivanovsky.passnotes.domain.interactor; import android.content.Context; import com.ivanovsky.passnotes.BuildConfig; import com.ivanovsky.passnotes.R; import com.ivanovsky.passnotes.data.entity.OperationError; public class ErrorInteractor { private final Context context; public ErrorInteractor(Context context) { this.context = context; } public String processAndGetMessage(OperationError error) { return getMessage(error); } public ErrorProcessingResult process(OperationError error) { return new ErrorProcessingResult(getMessage(error), getResolution(error)); } private String getMessage(OperationError error) { String message; if (BuildConfig.DEBUG) { message = formatDebugMessageFromOperationError(error); } else { message = getDefaultMessageForOperationErrorType(error.getType()); } return message; } private ErrorResolution getResolution(OperationError error) { switch (error.getType()) { case NETWORK_IO_ERROR: return ErrorResolution.RETRY; default: return ErrorResolution.NOTHING; } } private String getDefaultMessageForOperationErrorType(OperationError.Type type) { //TODO: implement other type handling switch (type) { case NETWORK_IO_ERROR: return context.getString(R.string.network_error_was_occurred_check_internet_connection); default: return context.getString(R.string.error_was_occurred); } } private String formatDebugMessageFromOperationError(OperationError error) { StringBuilder sb = new StringBuilder(); sb.append(error.getType()); if (error.getMessage() != null) { sb.append(": ").append(error.getMessage()); } if (error.getThrowable() != null) { sb.append(": ").append(error.getThrowable().toString()); } return sb.toString(); } }
java
11
0.649307
104
28.069444
72
starcoderdata
<?php namespace Distilleries\Expendable\Contracts; interface EventContract { /** * @param array $params * @return mixed */ public function dispatch($params = array()); }
php
7
0.643192
50
18.454545
11
starcoderdata
using System.Collections.Generic; using System.Text; using Reinforced.Tecture.Commands; namespace Reinforced.Tecture.Tracing.Commands.Cycles { internal class CycleTraceContext : ICycleTraceContext { private readonly Pipeline _pipeline; private int _iterations = 0; private readonly int _commandsBefore = 0; private readonly string _annotation; internal CycleTraceContext(Pipeline pipeline, string annotation) { _pipeline = pipeline; _annotation = annotation; _commandsBefore = pipeline.CommandsCount; pipeline.Enqueue(new Cycle() { Annotation = annotation, }); } public void Iteration(string annotation = null) { _iterations++; _pipeline.Enqueue(new Iteration() { Annotation = annotation ?? string.Empty }); } public void Dispose() { _pipeline.Enqueue(new EndCycle() { Annotation = _annotation, IterationsCount = _iterations, TotalCommands = _pipeline.CommandsCount - _commandsBefore }); } } }
c#
16
0.562747
91
28.190476
42
starcoderdata
import { createApp } from 'vue'; import { registerSW } from 'virtual:pwa-register'; import App from './App.vue'; createApp(App).mount('#app'); registerSW();
javascript
3
0.708995
50
22.625
8
starcoderdata
@Override public void onReceive(Context context, Intent intent) { DownloadManager.Query query = new DownloadManager.Query(); Long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0); query.setFilterById(downloadId); Cursor cursor = downloadManager.query(query); if (cursor.moveToFirst()){ //Retrieve the saved download Download currentDownload = downloadMap.get(downloadId); downloadMap.remove(currentDownload); int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS); int status = cursor.getInt(columnIndex); int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON); int reason = cursor.getInt(columnReason); switch (status) { case DownloadManager.STATUS_SUCCESSFUL: try { JSONObject entry = new JSONObject(); entry.put("path", "file:///storage/sdcard0/"+currentDownload.folder+"/"+currentDownload.path); entry.put("file", currentDownload.path); entry.put("folder", currentDownload.folder); currentDownload.callbackContext.success(entry); } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); currentDownload.callbackContext.error(e.getMessage()); } break; case DownloadManager.STATUS_FAILED: currentDownload.callbackContext.error(reason); break; case DownloadManager.STATUS_PAUSED: case DownloadManager.STATUS_PENDING: case DownloadManager.STATUS_RUNNING: default: break; } } }
java
17
0.538347
101
45.72093
43
inline
 namespace HugulaEditor { public class EditorCommon { public const string KeyVerChannels = "hugula_ver_Channels"; /// /// 版本文件扩展文件. /// public const string ExtensionFolder = "ExtensionFolder.txt"; /// /// 设置文件夹 /// public const string SettingFile = "EditorSetting.txt"; /// /// 版本文件扩展文件. /// public const string VerExtends = "Ver.txt"; /// /// hugula配置文件路径. /// public const string ConfigPath = "Assets/Hugula/Config/"; /// /// 输出资源文件夹. /// public const string ResFolderName = "res"; } }
c#
8
0.53567
68
24
32
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 lrucache import ( "errors" "sync" ) type LRUCacheShard struct { capacity uint64 mutex sync.Mutex usage uint64 // usage of memory lrulist LRUHandle // head of lru list; lru.prev is newest entry, lru.next is oldest entry table HandleTable handlePool sync.Pool } func NewLRUCacheShard(capacity uint64) *LRUCacheShard { lru_shared := &LRUCacheShard{ capacity: 0, usage: 0, table: *NewLRUHandleTable(), handlePool: sync.Pool{ New: func() interface{} { return new(LRUHandle) }, }, } lru_shared.lrulist.next = &(lru_shared.lrulist) lru_shared.lrulist.prev = &(lru_shared.lrulist) lru_shared.SetCapacity(capacity) return lru_shared } /** create lruhandle and Insert to cache, */ func (this *LRUCacheShard) Insert(key []byte, hash uint32, entry interface{}, charge uint64, deleter DeleteCallback) error { // If the cache is full, we'll have to release it // It shouldn't happen very often though. this.mutex.Lock(); defer this.mutex.Unlock() return this.insert(key, hash, entry, charge, deleter) } /** find key's lruhandle, return nil if not find; */ func (this *LRUCacheShard) Lookup(key []byte, hash uint32) interface{} { this.mutex.Lock(); defer this.mutex.Unlock() e := this.handle_lookup_update(key, hash); if e != nil { return e.entry } return nil; } func (this *LRUCacheShard) Merge(key []byte, hash uint32, entry interface{}, charge uint64, merge MergeOperator, charge_opt ChargeOperator) (interface{}) { this.mutex.Lock(); defer this.mutex.Unlock(); e := this.handle_lookup_update(key, hash) var new_value interface{} var new_charge uint64 var res interface{} var deleter DeleteCallback = nil if e != nil { res = e.entry deleter = e.deleter new_value = merge(e.entry, entry) new_charge = charge_opt(entry, e.charge, charge) } else { res = nil new_value = merge(nil, entry) new_charge = charge_opt(entry, 0, charge) } this.insert(key, hash, new_value, new_charge, deleter) return res } func (this *LRUCacheShard) Remove(key []byte, hash uint32) interface{} { this.mutex.Lock(); defer this.mutex.Unlock(); return this.lru_remove(key, hash) } func (this *LRUCacheShard) ApplyToAllCacheEntries(travel_fun TravelEntryOperator) { this.mutex.Lock(); defer this.mutex.Unlock(); this.table.ApplyToAllCacheEntries(travel_fun) } func (this *LRUCacheShard) Prune() { this.mutex.Lock(); defer this.mutex.Unlock(); for this.lrulist.next != &this.lrulist { e := this.lrulist.next; this.lru_remove_handle(e, true) } } func (this *LRUCacheShard) SetCapacity(capacity uint64) { this.mutex.Lock() defer this.mutex.Unlock() this.capacity = capacity this.EvictLRU() } func (this *LRUCacheShard) TotalCharge() uint64 { this.mutex.Lock(); defer this.mutex.Unlock(); return this.usage; } /*********** lru method *************/ func (this *LRUCacheShard) insert(key []byte, hash uint32, entry interface{}, charge uint64, deleter DeleteCallback) error { var err error e := this.handlePool.Get() handle := e.(*LRUHandle) handle.entry = entry handle.deleter = deleter handle.charge = charge handle.hash = hash handle.key = key // if capacity == 0; will turn off caching if this.capacity > 0 { this.lru_insert(handle, charge) } else { err = errors.New("cache is turn off") } this.EvictLRU() return err } func (this *LRUCacheShard) handle_lookup(key []byte, hash uint32) *LRUHandle { e := this.table.Lookup(key, hash); return e; } func (this *LRUCacheShard) handle_lookup_update(key []byte, hash uint32) *LRUHandle { e := this.table.Lookup(key, hash); if (e != nil) { this.list_update(e) } return e; } func (this *LRUCacheShard) EvictLRU() { for this.usage > this.capacity && this.lrulist.next != &this.lrulist { old := this.lrulist.next this.lru_remove_handle(old, true) } } /*********** lru method *************/ func (this *LRUCacheShard) lru_remove(key []byte, hash uint32) interface{} { e := this.handle_lookup(key, hash); if e != nil { this.lru_remove_handle(e, true) return e.entry } return nil } /** lru Remove; if table Insert return's handle, it's aready removed from table, so also_table is flase */ func (this *LRUCacheShard) lru_remove_handle(e *LRUHandle, also_table bool) { if also_table { this.table.Remove(e.key, e.hash) } this.list_remove(e) if (e.deleter != nil) { e.deleter(e.key, e.entry) } this.usage -= e.charge; this.handlePool.Put(e) } func (this *LRUCacheShard) lru_insert(e *LRUHandle, charge uint64) { this.list_append(e) this.usage += charge old := this.table.Insert(e) if old != nil { //don't need table.Remove; it's aready removed this.lru_remove_handle(old, false) } } /*********** lru list method *************/ func (this *LRUCacheShard) list_remove(e *LRUHandle) { e.next.prev = e.prev e.prev.next = e.next } /* Insert before list */ func (this *LRUCacheShard) list_append(e *LRUHandle) { list := &this.lrulist e.next = list; e.prev = list.prev; e.prev.next = e; e.next.prev = e; } func (this *LRUCacheShard) list_update(e *LRUHandle) { this.list_remove(e) this.list_append(e) }
go
20
0.689911
155
24.050633
237
starcoderdata
using System; using System.Reflection; using BeatSaberModdingTools.Models; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace BSMT_Tests.Models { [TestClass] public class SettingsModel_Tests { private static SettingsModel AllChanged => new SettingsModel() { ChosenInstallPath = @"C:\Test\Testing", GenerateUserFileWithTemplate = true, GenerateUserFileOnExisting = true, SetManifestJsonDefaults = true, CopyToIPAPendingOnBuild = true, BuildReferenceType = BuildReferenceType.DirectoryJunctions, Manifest_Author = "AuthorTest", Manifest_Donation = "http://test.com/test", Manifest_AuthorEnabled = true, Manifest_DonationEnabled = true }; [TestMethod] public void CopyConstructor_SettingsModel() { var expectedInstallPath = @"C:\Test\Testing"; var GenUserWithTemplate = true; var GenUserOnExisting = true; var setManifestDefaults = true; var copyOnBuild = true; var expectedBRType = BuildReferenceType.DirectoryJunctions; var manifestAuthor = "AuthorTest"; var manifestDonation = "http://test.com/test"; var authorEnabled = true; var donationEnabled = true; var original = new SettingsModel() { ChosenInstallPath = expectedInstallPath, GenerateUserFileWithTemplate = GenUserWithTemplate, GenerateUserFileOnExisting = GenUserOnExisting, SetManifestJsonDefaults = setManifestDefaults, CopyToIPAPendingOnBuild = copyOnBuild, BuildReferenceType = expectedBRType, Manifest_Author = manifestAuthor, Manifest_Donation = manifestDonation, Manifest_AuthorEnabled = authorEnabled, Manifest_DonationEnabled = donationEnabled }; var copy = new SettingsModel(original); Assert.AreEqual(original, copy); } [TestMethod] public void CopyConstructor_ReadOnlySettingsModel() { var expectedInstallPath = @"C:\Test\Testing"; var GenUserWithTemplate = true; var GenUserOnExisting = true; var setManifestDefaults = true; var copyOnBuild = true; var expectedBRType = BuildReferenceType.DirectoryJunctions; var manifestAuthor = "AuthorTest"; var manifestDonation = "http://test.com/test"; var authorEnabled = true; var donationEnabled = true; var original = new SettingsModel() { ChosenInstallPath = expectedInstallPath, GenerateUserFileWithTemplate = GenUserWithTemplate, GenerateUserFileOnExisting = GenUserOnExisting, SetManifestJsonDefaults = setManifestDefaults, CopyToIPAPendingOnBuild = copyOnBuild, BuildReferenceType = expectedBRType, Manifest_Author = manifestAuthor, Manifest_Donation = manifestDonation, Manifest_AuthorEnabled = authorEnabled, Manifest_DonationEnabled = donationEnabled }; var copy = new SettingsModel(original); Assert.AreEqual(original, copy); } [TestMethod] public void CopyConstructor_SettingsModel_IndividualTests() { var original = new SettingsModel(); foreach (var prop in typeof(SettingsModel).GetProperties()) { if (prop.PropertyType == typeof(string)) prop.SetValue(original, prop.Name); else if (prop.PropertyType == typeof(bool)) prop.SetValue(original, !(bool)prop.GetValue(original)); else if (prop.PropertyType == typeof(BuildReferenceType)) prop.SetValue(original, BuildReferenceType.DirectoryJunctions); else Assert.Fail($"Type {prop.PropertyType} is unhandled for {prop.Name}"); var copy = new SettingsModel(original); Assert.AreEqual(original, copy, $"Failed after setting {prop.Name}"); } } [TestMethod] public void CopyConstructor_ReadOnlySettingsModel_IndividualTests() { var original = new SettingsModel(); foreach (var prop in typeof(SettingsModel).GetProperties()) { if (prop.PropertyType == typeof(string)) prop.SetValue(original, prop.Name); else if (prop.PropertyType == typeof(bool)) prop.SetValue(original, !(bool)prop.GetValue(original)); else if (prop.PropertyType == typeof(BuildReferenceType)) prop.SetValue(original, BuildReferenceType.DirectoryJunctions); else Assert.Fail($"Type {prop.PropertyType} is unhandled for {prop.Name}"); var copy = new SettingsModel(original); Assert.AreEqual(original, copy, $"Failed after setting {prop.Name}"); } } [TestMethod] public void NotEqual_SettingsModel() { var original = new SettingsModel(); foreach (var prop in typeof(SettingsModel).GetProperties()) { var changed = new SettingsModel(); Assert.AreEqual(original, changed); if (prop.PropertyType == typeof(string)) prop.SetValue(changed, prop.Name); else if (prop.PropertyType == typeof(bool)) prop.SetValue(changed, !(bool)prop.GetValue(original)); else if (prop.PropertyType == typeof(BuildReferenceType)) prop.SetValue(changed, BuildReferenceType.DirectoryJunctions); else Assert.Fail($"Type {prop.PropertyType} is unhandled for {prop.Name}"); Assert.AreNotEqual(original, changed, $"Failed after setting {prop.Name}"); } } [TestMethod] public void NotEqual_ReadOnlySettingsModel() { var original = new SettingsModel(); foreach (var prop in typeof(SettingsModel).GetProperties()) { var changed = new SettingsModel(); Assert.AreEqual(original, changed); if (prop.PropertyType == typeof(string)) prop.SetValue(changed, prop.Name); else if (prop.PropertyType == typeof(bool)) prop.SetValue(changed, !(bool)prop.GetValue(original)); else if (prop.PropertyType == typeof(BuildReferenceType)) prop.SetValue(changed, BuildReferenceType.DirectoryJunctions); else Assert.Fail($"Type {prop.PropertyType} is unhandled for {prop.Name}"); var readOnlyChanged = new SettingsModel(changed); Assert.AreEqual(changed, readOnlyChanged); Assert.AreNotEqual(original, changed, $"Failed after setting {prop.Name}"); Assert.AreNotEqual(original, readOnlyChanged, $"Failed after setting {prop.Name}"); } } } }
c#
20
0.583819
99
43.163743
171
starcoderdata
/* Copyright 2021. 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 v1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. // ReportSpec defines the desired state of Report type ReportSpec struct { // INSERT ADDITIONAL SPEC FIELDS - desired state of cluster // Important: Run "make" to regenerate code after modifying this file //+kubebuilder:validation:MinLength=0 // The schedule in Cron format, see https://en.wikipedia.org/wiki/Cron. // +optional Schedule string `json:"schedule"` // ReportingEnd specifies the time this Report should end ReportingEnd *metav1.Time `json:"reportingEnd"` // ReportingStart specifies the time this Report should start from // This is intended for allowing a Report to start from the past // +optional ReportingStart *metav1.Time `json:"reportingStart"` // Specifies how to treat concurrent executions of a Job. // Valid values are: // - "Day" (default): daily (24 hrs) report ends on ReportingEnd; // - "Week": weekly (7 days) report ends on ReportingEnd; // - "Month": monthly (30 calendar days) report ends on ReportingEnd // +optional ReportPeriod ReportPeriod `json:"reportPeriod,omitempty"` //+kubebuilder:validation:MinLength=0 // +optional Namespace string `json:"namespace"` // RunImmediately will run the report immediately, ignoring ReportingStart // and, ReportingEnd. //RunImmediately bool `json:"runImmediately,omitempty"` } // Only one of the following choice may be specified. // If none of the following policies is specified, the default one // is DailyReport. // +kubebuilder:validation:Enum=Day;Week;Month type ReportPeriod string const ( // AllowConcurrent allows CronJobs to run concurrently. Daily ReportPeriod = "Day" // ForbidConcurrent forbids concurrent runs, skipping next run if previous // hasn't finished yet. Weekly ReportPeriod = "Week" // ReplaceConcurrent cancels currently running job and replaces it with a new one. Monthly ReportPeriod = "Month" ) // ReportStatus defines the observed state of Report type ReportStatus struct { // INSERT ADDITIONAL STATUS FIELD - define observed state of cluster // Important: Run "make" to regenerate code after modifying this file // Information when was the last time the report was successfully generated. // +optional LastScheduleTime *metav1.Time `json:"lastScheduleTime,omitempty"` Conditions string `json:"conditions,omitempty"` } //+kubebuilder:object:root=true //+kubebuilder:subresource:status // Report is the Schema for the reports API type Report struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec ReportSpec `json:"spec,omitempty"` Status ReportStatus `json:"status,omitempty"` } //+kubebuilder:object:root=true // ReportList contains a list of Report type ReportList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []Report `json:"items"` } func init() { SchemeBuilder.Register(&Report{}, &ReportList{}) }
go
9
0.75441
109
31.043478
115
starcoderdata
using System.Threading.Tasks; using NUnit.Framework; using Xamarin.UITest; using XamList.Mobile.Shared; namespace XamList.UITests { public class Tests : BaseUITest { public Tests(Platform platform) : base(platform) { } [Test] public void AppLaunches() { } [TestCase(TestConstants.TestFirstName, TestConstants.TestLastName, TestConstants.TestPhoneNumber, true)] [TestCase(TestConstants.TestFirstName, TestConstants.TestLastName, TestConstants.TestPhoneNumber, false)] public async Task AddContactTest(string firstName, string lastName, string phoneNumber, bool shouldUseReturnKey) { //Arrange //Act await AddContact(firstName, lastName, phoneNumber, shouldUseReturnKey).ConfigureAwait(false); //Assert Assert.IsTrue(ContactsListPage.DoesContactExist(firstName, lastName, phoneNumber)); } [TestCase(true)] [TestCase(false)] public async Task RestoreDeletedContactTest(bool shouldConfirmAlertDialog) { //Arrange var firstName = TestConstants.TestFirstName; var lastName = TestConstants.TestLastName; var phoneNumber = TestConstants.TestPhoneNumber; //Act await AddContact(firstName, lastName, phoneNumber, false).ConfigureAwait(false); ContactsListPage.DeleteContact(firstName, lastName, phoneNumber); try { await ContactsListPage.WaitForPullToRefreshActivityIndicator(3).ConfigureAwait(false); } catch { } await ContactsListPage.WaitForNoPullToRefreshActivityIndicator().ConfigureAwait(false); Assert.IsFalse(ContactsListPage.DoesContactExist(firstName, lastName, phoneNumber)); ContactsListPage.TapRestoreDeletedContactsButton(shouldConfirmAlertDialog); if (shouldConfirmAlertDialog) { ContactsListPage.WaitForPageToLoad(); try { await ContactsListPage.WaitForPullToRefreshActivityIndicator(3).ConfigureAwait(false); } catch { } await ContactsListPage.WaitForNoPullToRefreshActivityIndicator().ConfigureAwait(false); ContactsListPage.PullToRefresh(); await ContactsListPage.WaitForNoPullToRefreshActivityIndicator().ConfigureAwait(false); } //Assert if (shouldConfirmAlertDialog) Assert.IsTrue(ContactsListPage.DoesContactExist(firstName, lastName, phoneNumber)); else Assert.IsFalse(ContactsListPage.DoesContactExist(firstName, lastName, phoneNumber)); } [TestCase(TestConstants.TestFirstName, TestConstants.TestLastName, TestConstants.TestPhoneNumber)] public async Task EnterContactInformationThenPressCancel(string firstName, string lastName, string phoneNumber) { //Arrange //Act ContactsListPage.TapAddContactButton(); ContactDetailsPage.WaitForPageToLoad(); ContactDetailsPage.PopulateAllTextFields(firstName, lastName, phoneNumber, false); ContactDetailsPage.TapCancelButton(); ContactsListPage.WaitForPageToLoad(); await ContactsListPage.WaitForNoPullToRefreshActivityIndicator().ConfigureAwait(false); //Assert Assert.IsFalse(ContactsListPage.DoesContactExist(firstName, lastName, phoneNumber)); } async Task AddContact(string firstName, string lastName, string phoneNumber, bool shouldUseReturnKey) { ContactsListPage.TapAddContactButton(); ContactDetailsPage.WaitForPageToLoad(); ContactDetailsPage.PopulateAllTextFields(firstName, lastName, phoneNumber, shouldUseReturnKey); ContactDetailsPage.TapSaveButton(); ContactsListPage.WaitForPageToLoad(); try { await ContactsListPage.WaitForPullToRefreshActivityIndicator(3).ConfigureAwait(false); } catch { } await ContactsListPage.WaitForNoPullToRefreshActivityIndicator().ConfigureAwait(false); } } }
c#
18
0.64441
120
33.330769
130
starcoderdata
<?php function responseFormat($code, $message = null, $params = null) { if (!$message) $message = 'ok'; if ($code <= 0) $code = 400; return response()->json([ 'status_code' => $code, 'message' => $message, 'params' => $params ],$code); } function listMapelGroup(){ $response = collect([]); $response->push(['value' => 'Nasional', 'label' => 'Muatan Nasional', 'meta' => [ 'kurikulum' => 'K13', 'nomor' => 'A' ]]); $response->push(['value' => 'Kewilayahan', 'label' => 'Muatan Kewilayahan', 'meta' => [ 'kurikulum' => 'K13', 'nomor' => 'B' ]]); $response->push(['value' => 'Dasar Bidang Keahlian', 'label' => 'Dasar Bidang Keahlian', 'meta' => [ 'kurikulum' => 'K13', 'nomor' => 'C1' ]]); $response->push(['value' => 'Dasar Program Keahlian', 'label' => 'Dasar Program Keahlian', 'meta' => [ 'kurikulum' => 'K13', 'nomor' => 'C2' ]]); $response->push(['value' => 'Kompetensi Keahlian', 'label' => 'Kompetensi Keahlian', 'meta' => [ 'kurikulum' => 'K13', 'nomor' => 'C3' ]]); $response->push(['value' => 'Umum', 'label' => 'Muatan Umum', 'meta' => [ 'kurikulum' => 'PK', 'nomor' => 'A' ]]); $response->push(['value' => 'Kejuruan', 'label' => 'Muatan Kejuruan', 'meta' => [ 'kurikulum' => 'PK', 'nomor' => 'B' ]]); return $response; } function toNum($str) { $limit = 5; //apply max no. of characters $colLetters = strtoupper($str); //change to uppercase for easy char to integer conversion $strlen = strlen($colLetters); //get length of col string if($strlen > $limit) return "Column too long!"; //may catch out multibyte chars in first pass preg_match("/^[A-Z]+$/",$colLetters,$matches); //check valid chars if(!$matches)return "Invalid characters!"; //should catch any remaining multibyte chars or empty string, numbers, symbols $it = 0; $vals = 0; //just start off the vars for($i=$strlen-1;$i>-1;$i--){ //countdown - add values from righthand side $vals += (ord($colLetters[$i]) - 64 ) * pow(26,$it); //cumulate letter value $it++; //simple counter } return $vals; //this is the answer } function toStr($n,$case = 'upper') { $alphabet = array( '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' ); $n = $n; if($n <= 26){ $alpha = $alphabet[$n-1]; } elseif($n > 26) { $dividend = ($n); $alpha = ''; $modulo; while($dividend > 0){ $modulo = ($dividend - 1) % 26; $alpha = $alphabet[$modulo].$alpha; $dividend = floor((($dividend - $modulo) / 26)); } } if($case=='lower'){ $alpha = strtolower($alpha); } return $alpha; }
php
18
0.521677
149
45.147541
61
starcoderdata
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Artemis.Core; using Artemis.Core.Modules; namespace Artemis.Plugins.ScriptingProviders.JavaScript.Generators { public class TypeScriptClass { public const int MaxDepth = 4; public TypeScriptClass(ITypeScriptClassContainer? classContainer, Type type, bool includeMethods, int depth) { ClassContainer = classContainer; Type = type; IncludeMethods = includeMethods; Assembly assembly; DataModel? dataModel = null; if (classContainer is TypeScriptDataModel typeScriptDataModel) { assembly = typeScriptDataModel.DataModel.GetType().Assembly; dataModel = typeScriptDataModel.DataModel; } else if (classContainer != null) assembly = ((TypeScriptAssembly) classContainer).Assembly; else assembly = type.Assembly; if (Type.IsGenericType) { Type = type.GetGenericTypeDefinition(); string stripped = Type.Name.Split('`')[0]; Name = $"{stripped}<{string.Join(", ", ((TypeInfo) Type).GenericTypeParameters.Select(t => t.Name))}>"; } else Name = Type.Name; foreach (PropertyInfo propertyInfo in Type.GetProperties(BindingFlags.Public | BindingFlags.Instance) .OrderBy(t => t.MetadataToken) .GroupBy(prop => prop.Name) .Select(group => group.Aggregate((mostSpecific, other) => mostSpecific.DeclaringType.IsSubclassOf(other.DeclaringType) ? mostSpecific : other))) { if (propertyInfo.GetCustomAttribute != null) continue; MethodInfo? getMethod = propertyInfo.GetGetMethod(); if (getMethod == null || getMethod.GetParameters().Any()) continue; // Skip properties that are in the ignored properties list of the respective profile module/data model expansion if (dataModel != null && dataModel.GetHiddenProperties().Any(p => p.Equals(propertyInfo))) continue; Type propertyType = propertyInfo.PropertyType; // For primitives, simply create a property if (propertyType.IsPrimitive || propertyType.IsEnum || propertyType == typeof(string) || propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { TypeScriptProperties.Add(new TypeScriptProperty(propertyInfo)); if (propertyType.IsEnum && !propertyType.IsGenericParameter && propertyType.GetEnumUnderlyingType() == typeof(int)) ClassContainer?.TypeScriptEnums.Add(new TypeScriptEnum(propertyType)); } else if (Type.IsGenericType && propertyType.IsGenericParameter) TypeScriptProperties.Add(new TypeScriptProperty(propertyInfo)); else if (propertyType.IsGenericEnumerable()) { } else if (propertyType == typeof(DataModelEvent) || propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(DataModelEvent<>)) { } // For other value types create a child view model else if (propertyType.IsClass || propertyType.IsStruct()) { TypeScriptProperties.Add(new TypeScriptProperty(propertyInfo)); if (depth <= MaxDepth && ClassContainer != null && ClassContainer.TypeScriptClasses.All(t => t.Type != propertyType) && propertyType.Assembly == assembly) ClassContainer.TypeScriptClasses.Add(new TypeScriptClass(ClassContainer, propertyType, IncludeMethods, depth + 1)); } } if (!includeMethods) return; foreach (MethodInfo methodInfo in Type .GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static) .Where(m => !m.IsSpecialName && m.IsPrivate == false && m.DeclaringType?.Assembly == assembly && m.GetParameters().All(p => !p.IsIn && !p.IsOut))) TypeScriptMethods.Add(new TypeScriptMethod(methodInfo)); } public ITypeScriptClassContainer? ClassContainer { get; } public Type Type { get; } public bool IncludeMethods { get; } public string Name { get; set; } public List TypeScriptProperties { get; } = new(); public List TypeScriptMethods { get; } = new(); public string GenerateCode(string prefix = "export") { // Exclude anything that still came out invalid like nested generics which aren't supported string properties = string.Join("\r\n", TypeScriptProperties.Select(c => c.GenerateCode()).Where(c => !c.Contains("`"))); string methods = string.Join("\r\n", TypeScriptMethods.Select(c => c.GenerateCode()).Where(c => !c.Contains("`"))); return $" {prefix} class {Name} {{\r\n" + $" {properties}\r\n" + $" {methods}\r\n" + $" {GenerateConstructor()}\r\n" + " }"; } public string GetParameterType(Type type) { if (type.IsGenericType) { string stripped = type.Name.Split('`')[0]; return $"{stripped}<{string.Join(", ", type.GenericTypeArguments.Select(TypeScriptProperty.GetTypeScriptType))}>"; } return TypeScriptProperty.GetTypeScriptType(type); } private string GenerateConstructor() { ConstructorInfo[] constructors = Type.GetConstructors(BindingFlags.Public | BindingFlags.Instance); string result = ""; foreach (ConstructorInfo constructorInfo in constructors) { string parameters = string.Join(", ", constructorInfo.GetParameters().Select(param => param.Name + ": " + GetParameterType(param.ParameterType))); if (!parameters.Contains("`")) result += $"constructor({parameters})\r\n"; } return result == "" ? "private constructor()" : result; } } }
c#
25
0.586811
197
46.934307
137
starcoderdata
import unittest from datetime import datetime from bpl_lib.network.Network import Network from bpl_lib.time.Time import Time class TestTime(unittest.TestCase): def test_get_time_1(self): Network.use("mainnet") time = Time.get_time(datetime.utcfromtimestamp(1533122273)) self.assertIsNotNone(time) self.assertIsInstance(time, int) self.assertEqual(time, 43021073) def test_get_real_time_1(self): Network.use("mainnet") date_time = datetime.utcfromtimestamp(1533122273) time = Time.get_real_time(43021073) self.assertIsNotNone(time) self.assertIsInstance(time, str) self.assertEqual(time, date_time.strftime("%Y-%m-%d %H:%M:%S")) def test_get_slot_number(self): timestamp = 43021073 slot_number = Time.get_slot_number(timestamp) self.assertIsNotNone(slot_number) self.assertIsInstance(slot_number, int) self.assertEqual(slot_number, 2868071) def test_get_slot_time(self): slot_number = 2868071 slot_time = Time.get_slot_time(slot_number) self.assertIsNotNone(slot_time) self.assertIsInstance(slot_time, int) self.assertEqual(slot_time, 43021065) if __name__ == "__main__": unittest.main()
python
11
0.660451
71
28.25
44
starcoderdata
package parser type Token uint const ( // Special ILLEGAL Token = iota EOF NEWLINE WHITESPACE // Literals IDENTIFER NUMBER // Reserved IF // Directives INC DEC // Comparators GT LT GTE LTE EQ NEQ ) func isComparatorToken(token Token) bool { return token >= GT && token <= NEQ } func isDirectiveToken(token Token) bool { return token == INC || token == DEC } func (t *Token) String() string { switch *t { case ILLEGAL: return "ILLEGAL" case EOF: return "EOF" case NEWLINE: return "NEWLINE" case WHITESPACE: return "WHITESPACE" case IDENTIFER: return "IDENTIFIER" case NUMBER: return "NUMBER" case IF: return "IF" case INC: return "INC" case DEC: return "DEC" case GT: return "GT" case LT: return "LT" case GTE: return "GTE" case LTE: return "LTE" case EQ: return "EQ" case NEQ: return "NEQ" default: return "" } }
go
8
0.662047
43
11.342105
76
starcoderdata
<!DOCTYPE html> <html lang="en"> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Meta --> <meta name="description" content="Responsive Bootstrap 4 Dashboard and Admin Template"> <meta name="author" content="ThemePixels"> <!-- Favicon --> <link rel="shortcut icon" type="image/x-icon" href="{{ asset('assets/img/favicon.png') }}"> System <!-- vendor css --> <link href="{{ asset('lib/@fortawesome/fontawesome-free/css/all.min.css') }}" rel="stylesheet"> <link href="{{ asset('lib/ionicons/css/ionicons.min.css') }}" rel="stylesheet"> <link href="{{ asset('lib/jqvmap/jqvmap.min.css') }}" rel="stylesheet"> <link href="{{ asset('lib/prismjs/themes/prism-tomorrow.css') }}" rel="stylesheet"> <link href="{{ asset('lib/datatables.net-dt/css/jquery.dataTables.min.css') }}" rel="stylesheet"> <link href="{{ asset('lib/datatables.net-responsive-dt/css/responsive.dataTables.min.css') }}" rel="stylesheet"> <link href="{{ asset('lib/select2/css/select2.min.css') }}" rel="stylesheet"> <!-- template css --> <link rel="stylesheet" href="{{ asset('assets/css/cassie.css') }}"> <?php $sidebarcolor= App\Models\ThemeModel::where('company_code', auth()->user()->company_code)->where('color_id', 2)->where('is_active', 1)->first(); ?> <?php if (!empty($sidebarcolor)) { ?> <link rel="stylesheet" href="{{ asset('assets/css') }}/{{ $sidebarcolor->css }}"> <?php } ?> <body data-spy="scroll" data-target="#navSection" data-offset="100"> <div class="bg-gray-100"> <?php // $backcolor= App\Models\ThemeModel::where('company_code', auth()->user()->company_code)->where('color_id', 1)->first(); ?> {{-- <div style="background-color: {{ $backcolor->colour }}"> --}} @include('templates.sidebar') @yield('content') <script src="{{ asset('js/rupiah.js') }}"> <script src="{{ asset('lib/jquery/jquery.min.js') }}"> <script src="{{ asset('lib/bootstrap/js/bootstrap.bundle.min.js') }}"> <script src="{{ asset('lib/feather-icons/feather.min.js') }}"> <script src="{{ asset('lib/perfect-scrollbar/perfect-scrollbar.min.js') }}"> <script src="{{ asset('lib/js-cookie/js.cookie.js') }}"> <script src="{{ asset('lib/chart.js/Chart.bundle.min.js') }}"> <script src="{{ asset('lib/jquery.flot/jquery.flot.js') }}"> <script src="{{ asset('lib/jquery.flot/jquery.flot.stack.js') }}"> <script src="{{ asset('lib/jquery.flot/jquery.flot.resize.js') }}"> <script src="{{ asset('lib/jquery.flot/jquery.flot.threshold.js') }}"> <script src="{{ asset('lib/jqvmap/jquery.vmap.min.js') }}"> <script src="{{ asset('lib/jqvmap/maps/jquery.vmap.world.js') }}"> <script src="{{ asset('assets/js/cassie.js') }}"> <script src="{{ asset('assets/js/flot.sampledata.js') }}"> <script src="{{ asset('assets/js/vmap.sampledata.js') }}"> <script src="{{ asset('assets/js/dashboard-one.js') }}"> <script src="{{ asset('lib/prismjs/prism.js') }}"> <script src="{{ asset('lib/datatables.net/js/jquery.dataTables.min.js') }}"> <script src="{{ asset('lib/datatables.net-dt/js/dataTables.dataTables.min.js') }}"> <script src="{{ asset('lib/datatables.net-responsive/js/dataTables.responsive.min.js') }}"> <script src="{{ asset('lib/datatables.net-responsive-dt/js/responsive.dataTables.min.js') }}"> <script src="{{ asset('lib/select2/js/select2.min.js') }}"> <script src="{{ asset('js/myscript.js') }}"> <!-- add new --> <script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"> <script src="https://cdn.datatables.net/buttons/1.6.2/js/dataTables.buttons.min.js"> <script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.flash.min.js"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"> <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"> <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"> <script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.html5.min.js"> <script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.print.min.js">
php
13
0.628908
157
55.95122
82
starcoderdata
// Copyright (c) 2010-2021 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text.RegularExpressions; using Chorus.FileTypeHandlers.lift; using Chorus.sync; using Chorus.VcsDrivers.Mercurial; using LibFLExBridgeChorusPlugin.DomainServices; using LibFLExBridgeChorusPlugin.Properties; using LibTriboroughBridgeChorusPlugin.Properties; using SIL.Progress; namespace LibFLExBridgeChorusPlugin.Infrastructure { internal sealed class FlexBridgeSynchronizerAdjunct : ISychronizerAdjunct { private readonly bool _wantToCheckRepositoryBranches; private readonly string _fwdataPathname; private readonly bool _writeVerbose; private bool _needToNestMainFile = true; private readonly string _fixitPathname; internal FlexBridgeSynchronizerAdjunct(string fwdataPathname, string fixitPathname, bool writeVerbose, bool wantToCheckRepositoryBranches) { if (!File.Exists(fixitPathname)) throw new InvalidOperationException("The FLEx 'fix it' program was not found."); _fwdataPathname = fwdataPathname; _fixitPathname = fixitPathname; _writeVerbose = writeVerbose; _wantToCheckRepositoryBranches = wantToCheckRepositoryBranches; } private string ProjectFilename { get { return Path.GetFileName(_fwdataPathname); } } private void RestoreProjectFile(IProgress progress) { WasUpdated = true; progress.WriteMessage("Rebuild project file '{0}'", ProjectFilename); FLExProjectUnifier.PutHumptyTogetherAgain(progress, _writeVerbose, _fwdataPathname); progress.WriteMessage("Finished rebuilding project file '{0}'", ProjectFilename); } #region Implementation of ISychronizerAdjunct /// /// Allow the client to do something right before the initial local commit. /// public void PrepareForInitialCommit(IProgress progress) { if (!_needToNestMainFile) return; // Only nest it one time. progress.WriteMessage("Split up project file: {0}", ProjectFilename); FLExProjectSplitter.PushHumptyOffTheWall(progress, _writeVerbose, _fwdataPathname); progress.WriteMessage("Finished splitting up project file: {0}", ProjectFilename); _needToNestMainFile = false; } /// /// Allow the client to do something in one of two cases: /// 1. User A had no new changes, but User B (from afar) did have them. No merge was done. /// 2. There was a merge failure, so a rollback is being done. /// In both cases, the client may need to do something. /// ///<param name="progress">A progress mechanism. /// <param name="isRollback">"True" if there was a merge failure, and the repo is being rolled back to an earlier state. Otherwise "False". public void SimpleUpdate(IProgress progress, bool isRollback) { // The "isRollback" paramenter may be needed to control any incompatible move duplicate id issues. RestoreProjectFile(progress); } /// /// Allow the client to do something right after a merge, but before the merge is committed. /// /// method is not be called at all, if there was no merging. public void PrepareForPostMergeCommit(IProgress progress) { RestoreProjectFile(progress); progress.WriteMessage("Checking project for merge problems"); if (RunFixFwData(progress)) { progress.WriteMessage("Ran fix-up utility after merge."); FLExProjectSplitter.PushHumptyOffTheWall(progress, _writeVerbose, _fwdataPathname); } } /// /// Run FixFwData.exe, a program to clean up any bad problems with the FLEx database. /// /// if problems were fixed private bool RunFixFwData(IProgress progress) { using (var process = new Process()) { var startInfo = process.StartInfo; startInfo.FileName = _fixitPathname.Replace("\"", null); startInfo.Arguments = "\"" + _fwdataPathname.Replace("\"", null) + "\""; startInfo.CreateNoWindow = false; startInfo.UseShellExecute = false; startInfo.WorkingDirectory = Path.GetDirectoryName(_fixitPathname) ?? string.Empty; startInfo.RedirectStandardOutput = true; process.Start(); var mergeOutput = process.StandardOutput.ReadToEnd(); process.WaitForExit(); // If the user requests verbose output they can see all the fixup reports. // Unfortunately this includes sequences of dots intended to show progress on the console. // They always occur at the start of a line. The Replace gets rid of them. progress.WriteVerbose(new Regex(@"(?<=(^|\n|\r))\.+").Replace(mergeOutput, "")); // 0 means fixup ran but fixed nothing, 1 means it ran and fixed something, anything else is a problem if(process.ExitCode != 0 && process.ExitCode != 1) { throw new Exception("Merge fixing program has crashed."); } return process.ExitCode == 1; } } /// /// Maybe let the user know about the need to update, or that other team members are still using an older version. /// public void CheckRepositoryBranches(IEnumerable branches, IProgress progress) { if (!_wantToCheckRepositoryBranches) { return; } var savedSettings = Settings.Default.OtherBranchRevisions; var conflictingUser = LiftSynchronizerAdjunct.GetRepositoryBranchCheckData(branches, BranchName, ref savedSettings); Settings.Default.OtherBranchRevisions = savedSettings; Settings.Default.Save(); if (!string.IsNullOrEmpty(conflictingUser)) progress.WriteWarning(string.Format(Resources.ksOtherRevisionWarning, conflictingUser)); } /// /// Get the branch name that should be used to Send/Receive the current project, made up of the /// model version number of the current fwdata file plus the FlexBridgeDataVersion. /// See the comments on FlexBridgeDataVersion for various constraints on how we come up with this. /// (Note that this cannot, of course, be used in the 'obtain' command, which instead relies on the -fwmodel /// command line argument.) /// public string BranchName => FlexBridgeConstants.FlexBridgeDataVersion + "." + FieldWorksProjectServices.GetVersionNumber(_fwdataPathname); /// /// Gets a value telling if the adjunct processed anything. /// public bool WasUpdated { get; private set; } #endregion } }
c#
18
0.741347
149
38.950617
162
starcoderdata
#region License // Copyright (c) 2010-2016, // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of BuildAMation nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // License namespace C { /// /// Derive from this module to create a static library of object files, in any language. /// public class StaticLibrary : CModule, IForwardedLibraries { private Bam.Core.Array sourceModules = new Bam.Core.Array private Bam.Core.Array forwardedDeps = new Bam.Core.Array private IArchivingPolicy Policy = null; static public Bam.Core.PathKey Key = Bam.Core.PathKey.Generate("Static Library File"); protected override void Init( Bam.Core.Module parent) { base.Init(parent); this.Librarian = DefaultToolchain.Librarian(this.BitDepth); this.RegisterGeneratedFile(Key, this.CreateTokenizedString("$(packagebuilddir)/$(moduleoutputdir)/$(libprefix)$(OutputName)$(libext)")); } // TODO: what is this for? public System.Collections.ObjectModel.ReadOnlyCollection Source { get { return this.sourceModules.ToReadOnlyCollection(); } } System.Collections.ObjectModel.ReadOnlyCollection IForwardedLibraries.ForwardedLibraries { get { return this.forwardedDeps.ToReadOnlyCollection(); } } public CObjectFileCollection CreateCSourceContainer( string wildcardPath = null, Bam.Core.Module macroModuleOverride = null, System.Text.RegularExpressions.Regex filter = null) { var source = this.InternalCreateContainer wildcardPath, macroModuleOverride, filter); this.sourceModules.Add(source); return source; } public Cxx.ObjectFileCollection CreateCxxSourceContainer( string wildcardPath = null, Bam.Core.Module macroModuleOverride = null, System.Text.RegularExpressions.Regex filter = null) { var source = this.InternalCreateContainer wildcardPath, macroModuleOverride, filter); this.sourceModules.Add(source); return source; } public C.ObjC.ObjectFileCollection CreateObjectiveCSourceContainer( string wildcardPath = null, Bam.Core.Module macroModuleOverride = null, System.Text.RegularExpressions.Regex filter = null) { var source = this.InternalCreateContainer wildcardPath, macroModuleOverride, filter); this.sourceModules.Add(source); return source; } public C.ObjCxx.ObjectFileCollection CreateObjectiveCxxSourceContainer( string wildcardPath = null, Bam.Core.Module macroModuleOverride = null, System.Text.RegularExpressions.Regex filter = null) { var source = this.InternalCreateContainer wildcardPath, macroModuleOverride, filter); this.sourceModules.Add(source); return source; } /// /// Specified source modules are compiled against the DependentModule type, with any public patches /// of that type applied to each source. /// /// <param name="affectedSource">Required source module. /// <param name="affectedSources">Optional list of additional sources. /// <typeparam name="DependentModule">The 1st type parameter. public void CompileAgainst CModule affectedSource, params CModule[] additionalSources) where DependentModule : CModule, new() { var dependent = Bam.Core.Graph.Instance.FindReferencedModule var sources = new CModule[additionalSources.Length + 1]; sources[0] = affectedSource; if (additionalSources.Length > 0) { additionalSources.CopyTo(sources, 1); } foreach (var source in sources) { if (null == source) { continue; } source.UsePublicPatches(dependent); } if (dependent is HeaderLibrary) { this.Requires(dependent); } else { // this delays the dependency until a link this.forwardedDeps.AddUnique(dependent); } } /// /// Specified sources compile against DependentModule, and re-exports the public patches /// from the dependent, e.g. if the headers of the dynamic library require include paths from /// the dependent. /// /// <param name="affectedSource">Required source module. /// <param name="additionalSources">Optional list of additional sources. /// <typeparam name="DependentModule">The 1st type parameter. public void CompileAgainstPublicly CModule affectedSource, params CModule[] additionalSources) where DependentModule : CModule, new() { this.CompileAgainst additionalSources); var dependent = Bam.Core.Graph.Instance.FindReferencedModule this.UsePublicPatches(dependent); } public LibrarianTool Librarian { get { return this.Tool as LibrarianTool; } set { this.Tool = value; } } protected sealed override void ExecuteInternal( Bam.Core.ExecutionContext context) { var source = FlattenHierarchicalFileList(this.sourceModules).ToReadOnlyCollection(); var headers = FlattenHierarchicalFileList(this.headerModules).ToReadOnlyCollection(); var libraryFile = this.GeneratedPaths[Key]; this.Policy.Archive(this, context, libraryFile, source, headers); } protected sealed override void GetExecutionPolicy( string mode) { var className = "C." + mode + "Librarian"; this.Policy = Bam.Core.ExecutionPolicyUtilities } public sealed override void Evaluate() { this.ReasonToExecute = null; var exists = System.IO.File.Exists(this.GeneratedPaths[Key].ToString()); if (!exists) { this.ReasonToExecute = Bam.Core.ExecuteReasoning.FileDoesNotExist(this.GeneratedPaths[Key]); return; } var requiresDeferredEvaluation = false; foreach (var source in this.sourceModules) { if (null != source.EvaluationTask) { source.EvaluationTask.Wait(); } if (null != source.ReasonToExecute) { switch (source.ReasonToExecute.Reason) { case Bam.Core.ExecuteReasoning.EReason.InputFileIsNewer: this.ReasonToExecute = Bam.Core.ExecuteReasoning.InputFileNewer(this.GeneratedPaths[Key], source.ReasonToExecute.OutputFilePath); return; case Bam.Core.ExecuteReasoning.EReason.DeferredEvaluation: requiresDeferredEvaluation = true; break; } } } if (requiresDeferredEvaluation) { // deferred evaluation can only be considered when other reasons to execute have been exhausted this.ReasonToExecute = Bam.Core.ExecuteReasoning.DeferredUntilBuild(this.GeneratedPaths[Key]); } } } }
c#
19
0.615602
157
40.233333
240
starcoderdata
<?php class AdminUser extends CI_Model { public $table = 'users'; function ShowUsers(){ return $this->db->get('users'); } function insert($data,$table){ $query=$this->db->insert($table,$data); //$this->db->insert($table,$data); if (!$query) return 1; } function modalgetid(){ $query = $this->db->get('users'); foreach($query->result_array() as $row){ $id = $row['id']; $username = $row['username']; $password = $row['password']; $level = $row['level']; $active = $row['active']; } $data = array( 'id' => $row['id'], 'username' => $row['username'], 'password' => $ 'level' => $row['level'], 'active' => $row['active'], ); return $data; } function getUsers($limit, $start){ $query = $this->db->get('users', $limit, $start); return $query; } function getUser(){ } function getID($where){ $this->db->where($where); return $this->db->get('Users')->result(); } public function update($data, $id) { $this->db->where('id',$id); $this->db->update('users', $data); return TRUE; } public function fetch_user($id){ $result = $this->db->where('id',$id)->get('users')->result_array(); return $result; } public function delete($where, $table){ $this->db->where($where); $this->db->delete($table); } } ?>
php
13
0.541636
70
17.917808
73
starcoderdata
private boolean addOneCountryToContinent(int cont) { trytoplace: for(int i = 0; i < 40; i += 1) { int parentIndex = rand.nextInt(continents[cont].size()); Polygon parent = (Polygon)continents[cont].get(parentIndex); Polygon child = makeAdjoiningTriangle(parent); for(int j = 0; j < numContinents; j += 1) { for(int k = 0; k < continents[j].size(); k += 1) { //debug("child = " + child + ", continents[j] = " + continents[j] + ", continents = " = continents); if(trianglesIntersect(dilatePolygon(child, (cont == j ? 1.0: 1.2)), dilatePolygon((Polygon)continents[j].get(k), (cont==j ? 1.0 : 1.2))) || !polygonFitsOnScreen(child) || (j != cont && dist(polygonCenter(child), polygonCenter((Polygon)continents[j].get(k))) < tRad*2)) continue trytoplace; } } //valid, add it continents[cont].add(child); return true; } return false; }
java
23
0.556886
110
40.791667
24
inline
<?php class Request{ private $query_params; private static $instance; private function __construct(){ } /** * @return Request */ static public function instance(){ if(!isset(static::$instance)){ static::$instance = new self(); } return static::$instance; } function getQueryParams(){ if(!isset($this->query_params)){ $parts = explode('&', $_SERVER['QUERY_STRING']); $this->query_params = array(); foreach($parts as $part){ $tmp = explode('=', $part); $this->query_params[$tmp[0]] = trim(urldecode($tmp[1])); } } return $this->query_params; } function getQuerySingleParam($name, $default = NULL){ $qparams = $this->getQueryParams(); if(isset($qparams[$name])){ return $qparams[$name]; } return $default; } function isMethod($method){ return ($_SERVER['REQUEST_METHOD'] == $method); } }
php
19
0.469104
72
20.698113
53
starcoderdata
const User = require('../models/User.js') //real time username availability exports.validateUsername = (req, res) => { User.find({ username: req.params.username }, (err, users) => { if (err) console.log(err); if (users.length == 0) { return res.send(JSON.stringify(true)) } else { return res.send(JSON.stringify(false)) } }) } //render registerForm exports.registerForm = (req, res) => { res.render('users/register') } //render registerForm exports.loginForm = (req, res) => { res.render('users/login') } //validating captcha and creating a new user exports.registerUser = (req, res) => { // checking for missing inputs if (!req.body.fullname || !req.body.email || !req.body.username || !req.body.password || !req.body.passwordConf) { return res.render('users/register', { errors: 'Missing a input' }) } //no input field is empty, further validating input values and checking whether username is taken or not if (req.body.fullname && req.body.email && req.body.username && req.body.password && req.body.passwordConf) { //express validation req.checkBody('fullname', 'Name is required').notEmpty(); req.checkBody('username', 'Username is required').notEmpty(); req.checkBody('email', 'Email is required').notEmpty(); req.checkBody('email', 'Email is not valid').isEmail(); req.checkBody('password', ' req.checkBody('passwordConf', 'Passwords do not match').equals(req.body.password); let errors = req.validationErrors(); if (errors) { return res.render('users/register', { errors: errors }) } //if username already taken User.find({ username: req.body.username }, (err, users) => { if (err) console.log(err); if (users.length != 0) { return res.render('users/register', { errors: 'Username already taken' }) } }) // all validation clear, proceed to create a user and store it in db var userData = { fullname:req.body.fullname, email: req.body.email, username: req.body.username, password: } //function to insert data into the db User.create(userData, function(err, user) { if (err) { return console.log(err) } else { return res.redirect('/user/login'); } }); } } //matching login credentials to create a new session exports.loginUser = (req, res) => { //checking for missing inputs if (!req.body.username || !req.body.password) { return res.render('users/login', { errors: 'Missing Inputs' }) } // no missing inputs, go for further validations if (req.body.username && req.body.password) { let username = req.body.username let password = //checking whether username exists User.findOne({ username: username }, (err, user) => { if (err) { console.log(err); return res.redirect('/user/login') } // if user not found if (!user) { return res.render('users/login', { errors: 'Invalid Username' }) } //user exists, next validate password user.comparePassword(password, (err, isMatch) => { if (err) { console.log(err); return res.redirect('/user/login') } if (isMatch && isMatch == true) { // entered password is correct req.session.user = user res.redirect('/') } else { //entered password is incorrect res.render('users/login', { errors: 'Password does not match' }) } }) }) } else { res.redirect('/user/login') } } //destroying user session once user is logged out exports.logout = (req, res, next) => { if (req.session) { req.session.destroy(err => { if (err) return next(err) else return res.redirect('/') }) } }
javascript
18
0.595298
106
27.264286
140
starcoderdata
const seed = [ { "authors": ["7be11dac1d70842458a9c079d4441af2c7827e65c1ccb5eabba778140a4e1688"], "title": "First post", "body": "The quick brown fox jumps over the lazy dog.", "subject": "animals", "public": true }, { "authors": ["c72476203fa9450fb16e81dbaa02679f254c8a8dd1a2ef88f5c0c01c230ffe23"], "title": "Coding", "body": "Coding is the coolest", "subject": "technology", "public": true }, { "authors": [" "title": "Generic Title", "body": "Generic Body", "subject": "general", "public": true }, { "authors": ["e97d974693c592b3df920f01dab5b4af6edd46409b6b486695900b1394ebbb35"], "title": "I Love Scriber", "body": "It's the coolest app in the world. Love the text to speech functionality!", "subject": "technology", "public": true }, { "authors": ["5eb32e40d06709ea997b579a2b43dc02a685b611f1a607957d6cddbc1628083b"], "title": "Influencer", "body": "This account, as with all others, is only for helping convince me that people actually care what I have to say.", "subject": "general", "public": true }, ] module.exports = seed;
javascript
8
0.585023
130
31.897436
39
starcoderdata
import http from 'http'; import App from './config/express'; import { success } from './lib/log'; // import './config/database'; const app = App.express; const server = http.createServer(app); server.listen(process.env.PORT, err => { if (err) throw new Error; success(`successfully connected to port ${process.env.PORT}`); }); export default server;
javascript
9
0.696477
64
22.125
16
starcoderdata
<?php /** * File containing the {@see Mailcode_Commands_CommonConstants} class. * * @package Mailcode * @subpackage Commands * @see Mailcode_Commands_CommonConstants */ declare(strict_types=1); namespace Mailcode; /** * Container for validation and error constants that are used * by a number of commands. The validation traits all reference * these, for example. * * @package Mailcode * @subpackage Commands * @author */ class Mailcode_Commands_CommonConstants { const VALIDATION_VARIABLE_MISSING = 49201; const VALIDATION_SEARCH_TERM_MISSING = 49202; const VALIDATION_INVALID_KEYWORD = 49203; const VALIDATION_OPERAND_MISSING = 49204; const VALIDATION_INVALID_OPERAND = 49205; const VALIDATION_INVALID_COMPARISON_TOKEN = 49206; const VALIDATION_EXPECTED_KEYWORD = 49207; const VALIDATION_NOTHING_AFTER_OPERAND = 49208; const VALIDATION_STRING_LITERAL_MISSING = 49209; const VALIDATION_VALUE_MISSING = 49210; const VALIDATION_COMMENT_MISSING = 49211; const VALIDATION_VALUE_NOT_NUMERIC = 49212; const VALIDATION_URL_DE_AND_ENCODE_ENABLED = 49213; const ERROR_NO_VARIABLE_AVAILABLE = 52601; const ERROR_NO_STRING_LITERAL_AVAILABLE = 52602; const ERROR_NO_COMPARATOR_AVAILABLE = 52603; const ERROR_NO_VALUE_AVAILABLE = 52604; const ERROR_NO_OPERAND_AVAILABLE = 52605; }
php
5
0.730022
70
29.866667
45
starcoderdata
from sentence_transformers import SentenceTransformer import scipy.spatial import pandas as pd from datetime import timedelta from multiprocessing import cpu_count, Pool from .accelerator import run_multitasking from functools import partial def clean_df(df, target_column): """ Clean and prepare a pandas DataFrame. Three steps: drop duplicates, drop null value and reset index. :param df: original DataFrame :param target_column: the target column to be cleaned. :return: a prepared DataFrame """ # remove duplicates df.drop_duplicates(subset=[target_column], inplace=True) # remove none df.dropna(subset=[target_column], inplace=True) # remove not text indicators = [ True if type(row[target_column]) == str else False for index, row in df.iterrows() ] df = df.loc[indicators, :] # remove unnecessary strings df[target_column] = df[target_column].apply(lambda x: " ".join(x.split())) # remove empty string df = df.loc[df[target_column] != "", :] df.reset_index(drop=True, inplace=True) return df def drop_duplicate_news( df, ticker_column: str = "ticker", date_column: str = "Date", embedding_column: str = "embeddings", look_back: int = 7, min_similarity: float = 0.8, ): """ Apply sentence-bert to find duplicate news by checking the cosine similarity of news titles. This may take some time as it applies sentence-bert model to do inference. :param df: df with sentence embeddings :param ticker_column: the ticker column :param date_column: the date column :param embedding_column: the embedding column :param look_back: how long should we look back :param min_similarity: the minimum similarity level :return: a simplified pd.DataFrame """ ticker_list = list(set(df[ticker_column])) worker_num = cpu_count() - 1 if cpu_count() > 1 else 1 task_list = [ df[df[ticker_column] == ticker].reset_index(drop=True) for ticker in ticker_list ] partial_func = partial( delete_duplicate_news, look_back=look_back, date_column=date_column, embedding_column=embedding_column, min_similarity=min_similarity, ) result_list = run_multitasking( func=partial_func, argument_list=task_list, num_workers=worker_num, thread_or_process="process", ) result = ( pd.concat(result_list).drop(columns=[embedding_column]).reset_index(drop=True) ) return result def add_embedding( df, model_name_or_path: str = "bert-base-nli-mean-tokens", target_column: str = "title", ): """ :param df: original DataFrame :param model_name_or_path: which model to be applied :param target_column: the target column, where the text is stored """ embedder = SentenceTransformer(model_name_or_path) target_list = df[target_column] embeddings = embedder.encode(target_list, batch_size=32, show_progress_bar=True) df["embeddings"] = list(embeddings) return df def delete_duplicate_news( sub_df, look_back: int, date_column: str, embedding_column: str, min_similarity: float = 0.8, ): """ Delete duplicate news for one single ticker. :param sub_df: df for a single ticker :param look_back: how long should we look back :param date_column: the date column :param embedding_column: the embedding column :param min_similarity: the minimum similarity level :return: new sub_df with only unique and fresh news """ drop_index_list = [] for index, row in sub_df.iterrows(): # check whether we should do the duplicate check end_date = row[date_column] date_range = [ end_date - pd.Timedelta(timedelta(days=i)) for i in range(look_back) ] # we select those news, whose dates are earlier (look_back days) and not yet been kicked out. indicator_list = [ row_[date_column] in date_range and index_ < index and index_ not in drop_index_list for index_, row_ in sub_df.iterrows() ] check_news = sub_df.loc[indicator_list, :] if len(check_news) != 0: query_embedding = row[embedding_column] corpus_embeddings = list(check_news[embedding_column]) distances = scipy.spatial.distance.cdist( [query_embedding], corpus_embeddings, "cosine" )[0] scores = [1 - distance for distance in distances] if max(scores) >= min_similarity: drop_index_list.append(index) sub_df = sub_df.drop(index=drop_index_list) return sub_df
python
14
0.645763
104
33.202899
138
starcoderdata
package cn.home.modules.quartz.job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.scheduling.quartz.QuartzJobBean; public class ExampleJob extends QuartzJobBean { private int timeout; /** * Setter called after the ExampleJob is instantiated with the value from * the JobDetailFactoryBean (5) */ public void setTimeout(int timeout) { this.timeout = timeout; } @Override protected void executeInternal(JobExecutionContext ctx) throws JobExecutionException { // do the actual work } }
java
8
0.78125
87
23.041667
24
starcoderdata
print("Initializing") import interface import dbcom as db import numpy as np import gettemp as t_sensor import loadcell_config as loadcell import time import filter import RPi.GPIO as GPIO #Loadcell Configuration scale_ratio = 0.000000519739#6,1070230765380187215297592231066e-7 #Configuration paramters sample_time = 60 #Seconds between evry sample average_time = 600 #Seconds between avaraging data and uploading to DB no_load_samples = 100 #Number of loadcell samples #Function definitions def getTempSample(): temp = t_sensor.gettemp() return temp def getGravSample(scale_ratio, OG, calibration_constant): raw_data = loadcell.getreadings(no_load_samples) filtered_data = filter.filterData(raw_data) gravity = loadcell.get_density(filtered_data, scale_ratio, OG, calibration_constant) return gravity #Init #Configuring interrupts print('Configuring interrupts') button1=11 # Input for knapp button2=9 # Input for knapp def setmode0(pin): global view view=0 # Endre skjermvisning def setmode1(pin): global view view=1 # Endre skjermvisning GPIO.setmode(GPIO.BCM) GPIO.setup(button1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(button2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(button1, GPIO.RISING, callback=setmode0) GPIO.add_event_detect(button2, GPIO.RISING, callback=setmode1) #Setting defualt screen view=0 #Get info from database print('Collecting info from databse') current_brew_id = db.getCurrentBrewId() brew_name = db.getBrewInfo('BrewName', current_brew_id) brewer = db.getBrewInfo('Brewer', current_brew_id) target_temp = db.getBrewInfo('TargetTemp', current_brew_id) OG = db.getBrewInfo('OG', current_brew_id) FG = db.getBrewInfo('TargetFG', current_brew_id) #Lag funksjon for dette calibration_constant = db.getBrewInfo('CalibrationConstant', current_brew_id) if calibration_constant == None: calibration_constant = filter.filterData(loadcell.getreadings(100)) db.addCalibrationConstant(current_brew_id, calibration_constant) else: calibration_constant = int(calibration_constant) #Initialize sampling print('Initializing sampling') start_sample_time = time.time() start_average_time = time.time() temp_samples = [] grav_samples = [] time.sleep(1) #Take initial spot sample print('Collecting initial sample') initial_temp = getTempSample() initial_grav = getGravSample(scale_ratio, OG, calibration_constant) db.addMeasurement(current_brew_id, initial_grav, initial_temp) #Add measurement to DB print('Sample collected') time.sleep(1) #Main loop try: print('Running main program') while (1): time_now = time.time() #Take sample if sample-time is reached if (time_now - start_sample_time) > sample_time: print('Sampling') #TODO: Insert code for displaying a "busy"-screen try: temp_samples.append(getTempSample()) except: print('Temperature sensor offline') print('Using target temp') temp_samples.append(target_temp) grav_samples.append(getGravSample(scale_ratio, OG, calibration_constant)) start_sample_time = time_now print('Sample collected') #Average samples and insert to DB if averaging time is reached if (time_now - start_average_time) > average_time: print('Averaging samples') db.addMeasurement(current_brew_id, np.mean(grav_samples), np.mean(temp_samples)) #Add averagde of measurements from last hour to DB print('Data added to database') start_average_time = time_now temp_samples.clear() grav_samples.clear() #Update screen if view==0: try: interface.disp1(temp_samples[-1], brew_name, brewer, grav_samples[-1], target_temp) except IndexError: interface.disp1(initial_temp, brew_name, brewer, initial_grav, target_temp) elif view==1: try: interface.disp2(OG, FG, grav_samples[-1]) except IndexError: interface.disp2(OG, FG, initial_grav) except KeyboardInterrupt: GPIO.cleanup() print('\nCleaning GPIO') # # if len(temp_samples): # if view==0: # interface.disp1(temp_samples[-1], brew_name, grav_samples[-1], target_temp) # # elif view==1: # interface.disp2(OG, FG, Load_samples[-1]) #
python
15
0.663658
143
30.319444
144
starcoderdata
<?php include("conection.php"); include("page.php"); $cod = $_POST['id']; $delete = "DELETE FROM files WHERE ID='$cod'"; echo "<section id='body'>"; echo"<figure class='pic-cap' >"; echo" <img src='imgs/lixo.jpg' />"; echo" if(@mysql_query($delete)) { echo "<p class='done' id='done'>Excluido com Sucesso! />"; } else { echo "<p class='error' id='error'>Erro ao excluir. } echo "<a href='show_files.php' class='error' id='error'>Voltar ?> <?php echo " include("footer.php"); ?>
php
8
0.561175
70
24.782609
23
starcoderdata
<?php //nav include 'views/nav.php'; //switch switch ($_GET['page']) { //startpage of the quiz case 'home'; include "views/start_quiz.php"; break; //the quiz case 'quiz'; $pageid = $_REQUEST['id']; switch(isset($_GET['id']) ? $_GET['id'] : "no id found"){ case $pageid : include "views/quiz.php"; break; // default = #404 default : include "views/start_quiz.php"; break; } break; case 'account-info'; include "views/accountinfo.php"; break; } ?>
php
12
0.463141
65
16.333333
36
starcoderdata