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
import Vue from 'vue'; import Router from 'vue-router'; import ImageView from './ImageView'; import MapView from './MapView'; import HeatmapView from './HeatmapView'; Vue.use(Router); export default new Router({ routes: [{ path: '/', redirect: '/map', }, { path: '/map', name: 'Map', component: MapView, }, { path: '/heatmap', name: 'Heatmap', component: HeatmapView, }, { path: '/image', name: 'Image', component: ImageView, }], });
javascript
10
0.586558
40
17.185185
27
starcoderdata
def __init__(self, number_of_epochs, output_map=None): """ Callback to log the measures of the model after each epoch. :param number_of_epochs: the total number of epochs of the training :type number_of_epochs: int or None :param output_map: the map of the outputs of the neural network by the predicate :type output_map: dict[str, tuple(Predicate, bool)] or None """ super(Callback, self).__init__() self.number_of_epochs = str(number_of_epochs) or "Unknown" self.output_map = output_map
python
8
0.627383
78
43.461538
13
inline
<section id="sidebar"> <?php if(isset($_SESSION["userid"])) { ?> Menu href="course.php">Course href="subject.php">Subject href="lectureview.php">Lectures href="student.php">Student href="attendanceview.php">Attendance href="examview.php">Examination href="adminview.php">Admin href="contactview.php">Inbox href="logout.php">Logout <?php } ?> <div class="clear"> <div class="clear">
php
8
0.594744
69
22.2
30
starcoderdata
@Override public float getS15Fixed16(int index) throws BufferBoundsException { checkBounds(index, 4); if (_isMotorolaByteOrder) { float res = (_buffer[index ] & 255) << 8 | (_buffer[index + 1] & 255); int d = (_buffer[index + 2] & 255) << 8 | (_buffer[index + 3] & 255); return (float)(res + d/65536.0); } else { // this particular branch is untested float res = (_buffer[index + 3] & 255) << 8 | (_buffer[index + 2] & 255); int d = (_buffer[index + 1] & 255) << 8 | (_buffer[index ] & 255); return (float)(res + d/65536.0); } }
java
13
0.416031
70
37.4
20
inline
from typing import Any from .models import * from ..various.exceptions import MessageDataType, MessageOpCode def get_response(msg: bytes, topic_sum_map: dict) -> bytes: op_code, data = parse_msg(msg) re_data = apply_op(op_code, data, topic_sum_map) re_op_code = request_response_opcodes[op_code] return build_message(re_op_code, re_data) def build_message(op_code: int, data: Any) -> bytes: try: data_type = op_code_data_type[op_code] except KeyError: raise MessageOpCode(f"Invalid OpCode: {op_code}") if not isinstance(data, data_type): raise MessageDataType(f"Expected {data_type}, received {type(data)}") if data_type is str: return bytes([op_code]) + data.encode(DATA_ENCODING) elif data_type is int: return bytes([op_code, data]) elif data_type is type(None): return bytes([op_code]) def parse_msg(msg: bytes) -> (int, str): op_code = msg[0] raw_data = msg[1:] try: data_type = op_code_data_type[op_code] if data_type is str: data = raw_data.decode(DATA_ENCODING) elif data_type is int: data = int.from_bytes(raw_data, byteorder="big") elif data_type is type(None): data = None except KeyError: raise MessageOpCode(f"Invalid OpCode: {op_code}") except TypeError: raise MessageDataType( f"Could not parse bytes to {data_type}. Data: {raw_data}") return op_code, data def apply_op(op_code: int, data: Any, topic_sum_map: dict) -> Any: if op_code == COUNT: return count_and_get_sum(data, topic_sum_map) elif op_code == RESET_SUM: return reset_topic(data, topic_sum_map) def count_and_get_sum(topic: str, topic_sum_map: dict) -> int: sum = topic_sum_map.get(topic, 0) sum += 1 topic_sum_map[topic] = sum return sum def reset_topic(topic: str, topic_sum_map: dict) -> None: topic_sum_map[topic] = 0
python
14
0.62411
77
29.246154
65
starcoderdata
@Override boolean shouldBeSeparatedOnRight () { // This Counter node should be separated on the right to emphasize // the trailing "#". return true; }
java
4
0.710692
68
21.857143
7
inline
void ExpReg::SGD(double learning_rate, int max_epoch, bool UI){ Reg regularization; double cost_prev = 0; int epoch = 1; while(true){ std::random_device rd; std::default_random_engine generator(rd()); std::uniform_int_distribution<int> distribution(0, int(n - 1)); int outputIndex = distribution(generator); double y_hat = Evaluate(inputSet[outputIndex]); cost_prev = Cost({y_hat}, {outputSet[outputIndex]}); for(int i = 0; i < k; i++){ // Calculating the weight gradients double w_gradient = (y_hat - outputSet[outputIndex]) * inputSet[outputIndex][i] * std::pow(weights[i], inputSet[outputIndex][i] - 1); double i_gradient = (y_hat - outputSet[outputIndex]) * std::pow(weights[i], inputSet[outputIndex][i]); // Weight/initial updation weights[i] -= learning_rate * w_gradient; initial[i] -= learning_rate * i_gradient; } weights = regularization.regWeights(weights, lambda, alpha, reg); // Calculating the bias gradients double b_gradient = (y_hat - outputSet[outputIndex]); // Bias updation bias -= learning_rate * b_gradient; y_hat = Evaluate({inputSet[outputIndex]}); if(UI) { Utilities::CostInfo(epoch, cost_prev, Cost({y_hat}, {outputSet[outputIndex]})); Utilities::UI(weights, bias); } epoch++; if(epoch > max_epoch) { break; } } forwardPass(); }
c++
16
0.503662
149
38.466667
45
inline
#region using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Serialization; using TESVSnip.Domain.Data.Structure; using TESVSnip.Domain.Data.Structure.Xml; using TESVSnip.Domain.Properties; using TESVSnip.Domain.Services; using TESVSnip.Framework.IO; #endregion namespace TESVSnip.Domain.Data { /// /// The intent of this class is to hold all "static" information related to /// configuration of a game. This allows Morrowind, Oblivion, Skyrim config files /// to be loaded simultaneously yet seperately. This is mostly for command line /// and scripting application. /// public class DomainDefinition { private static readonly Dictionary<string, DomainDefinition> Domains = new Dictionary<string, DomainDefinition>(StringComparer.InvariantCultureIgnoreCase); private readonly string xmlPath; public string Name { get; private set; } public string DisplayName { get; private set; } public string Master { get; private set; } public string RegistryKey { get; private set; } public string[] FilteredESM { get; private set; } public string[] AllESMRecords { get; private set; } public string HEDRType { get; private set; } public float HEDRVersion { get; private set; } public int HEDROffset { get; private set; } public int HEDRRecSize { get; private set; } public int RecSize { get; private set; } public Settings Settings { get; private set; } public bool Loaded { get; private set; } public Dictionary<string, RecordStructure> Records { get; private set; } public static event EventHandler DomainLoaded; static DomainDefinition() { var iniFile = Path.Combine(Folders.SettingsDirectory, "Domains.ini"); foreach (var section in IniFile.GetSectionNames(iniFile)) { var values = IniFile.GetPropertyValues(iniFile, section); var define = new DomainDefinition(section); define.DisplayName = GetValue(values, "Display", section); define.Master = GetValue(values, "Master", section+".esm"); define.RegistryKey = GetValue(values, "Registry", "Bethesda Softworks\\" + section); define.FilteredESM = GetValue(values, "FilteredESM", "").Split(';'); define.AllESMRecords = GetValue(values, "AllESMRecords", "").Split(';'); define.HEDRType = GetValue(values, "HEDRType", "TES4"); define.HEDRVersion = float.Parse(GetValue(values, "HEDRVersion", "1.0")); define.HEDROffset = int.Parse(GetValue(values, "HEDROffset", "4")); define.HEDRRecSize = int.Parse(GetValue(values, "HEDRRecSize", "2")); define.RecSize = int.Parse(GetValue(values, "RecSize", "16")); Domains[section] = define; } } private static string GetValue(Dictionary<string, string> dict, string key, string defaultValue) { string result; if (dict.TryGetValue(key, out result)) return result; return defaultValue; } public DomainDefinition(string name) { Name = name; Settings = Settings.Default; xmlPath = Path.Combine(Folders.SettingsDirectory, Name, @"RecordStructure.xml"); Records = new Dictionary<string, RecordStructure>(0); } public static IEnumerable LoadedDomains() { return Domains.Values.Where(domain => domain.Loaded); } public static IEnumerable AllDomains() { return Domains.Values; } public static DomainDefinition Lookup(string p) { DomainDefinition define; if (Domains.TryGetValue(p, out define)) return define; return null; } public static DomainDefinition Load(string p) { DomainDefinition define; if (!Domains.TryGetValue(p, out define)) { define = new DomainDefinition(p); Domains[p] = define; } if (!define.Loaded) { define.Records = RecordStructure.Load(define.xmlPath); define.Loaded = true; if (DomainLoaded != null) DomainLoaded(define, EventArgs.Empty); } return define; } public static void Reload() { foreach (var domainDefinition in Domains.Values) { if (domainDefinition.Loaded) domainDefinition.Records = RecordStructure.Load(domainDefinition.xmlPath); } if (DomainLoaded != null) DomainLoaded(null, EventArgs.Empty); } public static DomainDefinition DetectDefinitionFromVersion(string type, float version) { const float EPSILON = Single.Epsilon * 10; foreach (var domain in Domains.Values.Where(domain => type == domain.HEDRType && Math.Abs(version - domain.HEDRVersion) < EPSILON)) { if (!domain.Loaded) Load(domain.Name); return domain; } throw new Exception("File is not a known TES4 file (Unexpected version)"); } public static RecordStructure GetFirstRecordOfType(string type) { RecordStructure rec = null; if (LoadedDomains().Any(domain => domain.Records.TryGetValue(type, out rec))) return rec; return null; } public static string[] GetRecordNames() { var recNames = new List foreach (var domain in LoadedDomains()) recNames.AddRange(domain.Records.Keys); return recNames.Distinct().ToArray(); } public static object[] GetRecordNamesAsObjects() { var names = GetRecordNames(); var dest = new object[names.Length]; Array.Copy(names, 0, dest, 0, names.Length); return dest; } } }
c#
19
0.585851
163
36.810651
169
starcoderdata
// Copyright (c) 2020 // All rights reserved. // // You can use this software under the terms of 'INDIGO Astronomy // open-source license' (see LICENSE.md). // // THIS SOFTWARE IS PROVIDED BY THE AUTHORS '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 AUTHOR 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. // version history // 2.0 by /** INDIGO Field Rotator Simulator driver \file indigo_rotator_simulator.c */ #define DRIVER_VERSION 0x0002 #define DRIVER_NAME "indigo_rotator_simulator" #include #include #include #include #include #include #include #include "indigo_rotator_simulator.h" #define PRIVATE_DATA ((simulator_private_data *)device->private_data) #define ROTATOR_SPEED 0.9 typedef struct { double target_position, current_position; indigo_timer *rotator_timer; } simulator_private_data; // -------------------------------------------------------------------------------- INDIGO rotator device implementation static void rotator_timer_callback(indigo_device *device) { if (ROTATOR_POSITION_PROPERTY->state == INDIGO_ALERT_STATE) { ROTATOR_POSITION_ITEM->number.value = PRIVATE_DATA->target_position = PRIVATE_DATA->current_position; indigo_update_property(device, ROTATOR_POSITION_PROPERTY, NULL); } else { if (PRIVATE_DATA->current_position < PRIVATE_DATA->target_position) { ROTATOR_POSITION_PROPERTY->state = INDIGO_BUSY_STATE; if (PRIVATE_DATA->target_position - PRIVATE_DATA->current_position > ROTATOR_SPEED) ROTATOR_POSITION_ITEM->number.value = PRIVATE_DATA->current_position = (PRIVATE_DATA->current_position + ROTATOR_SPEED); else ROTATOR_POSITION_ITEM->number.value = PRIVATE_DATA->current_position = PRIVATE_DATA->target_position; indigo_update_property(device, ROTATOR_POSITION_PROPERTY, NULL); indigo_reschedule_timer(device, 0.2, &PRIVATE_DATA->rotator_timer); } else if (PRIVATE_DATA->current_position > PRIVATE_DATA->target_position){ ROTATOR_POSITION_PROPERTY->state = INDIGO_BUSY_STATE; if (PRIVATE_DATA->current_position - PRIVATE_DATA->target_position > ROTATOR_SPEED) ROTATOR_POSITION_ITEM->number.value = PRIVATE_DATA->current_position = (PRIVATE_DATA->current_position - ROTATOR_SPEED); else ROTATOR_POSITION_ITEM->number.value = PRIVATE_DATA->current_position = PRIVATE_DATA->target_position; indigo_update_property(device, ROTATOR_POSITION_PROPERTY, NULL); indigo_reschedule_timer(device, 0.2, &PRIVATE_DATA->rotator_timer); } else { ROTATOR_POSITION_PROPERTY->state = INDIGO_OK_STATE; ROTATOR_POSITION_ITEM->number.value = PRIVATE_DATA->current_position; indigo_update_property(device, ROTATOR_POSITION_PROPERTY, NULL); } } } static indigo_result rotator_attach(indigo_device *device) { assert(device != NULL); assert(PRIVATE_DATA != NULL); if (indigo_rotator_attach(device, DRIVER_NAME, DRIVER_VERSION) == INDIGO_OK) { // -------------------------------------------------------------------------------- INDIGO_DEVICE_ATTACH_LOG(DRIVER_NAME, device->name); return indigo_rotator_enumerate_properties(device, NULL, NULL); } return INDIGO_FAILED; } static void rotator_connect_callback(indigo_device *device) { CONNECTION_PROPERTY->state = INDIGO_OK_STATE; if (!CONNECTION_CONNECTED_ITEM->sw.value) { indigo_cancel_timer_sync(device, &PRIVATE_DATA->rotator_timer); } indigo_rotator_change_property(device, NULL, CONNECTION_PROPERTY); } static indigo_result rotator_change_property(indigo_device *device, indigo_client *client, indigo_property *property) { assert(device != NULL); assert(DEVICE_CONTEXT != NULL); assert(property != NULL); if (indigo_property_match(CONNECTION_PROPERTY, property)) { // -------------------------------------------------------------------------------- CONNECTION if (indigo_ignore_connection_change(device, property)) return INDIGO_OK; indigo_property_copy_values(CONNECTION_PROPERTY, property, false); CONNECTION_PROPERTY->state = INDIGO_BUSY_STATE; indigo_update_property(device, CONNECTION_PROPERTY, NULL); indigo_set_timer(device, 0, rotator_connect_callback, NULL); return INDIGO_OK; } else if (indigo_property_match(ROTATOR_POSITION_PROPERTY, property)) { // -------------------------------------------------------------------------------- ROTATOR_POSITION indigo_property_copy_values(ROTATOR_POSITION_PROPERTY, property, false); if (ROTATOR_ON_POSITION_SET_SYNC_ITEM->sw.value) { ROTATOR_POSITION_PROPERTY->state = INDIGO_OK_STATE; PRIVATE_DATA->target_position = ROTATOR_POSITION_ITEM->number.target; PRIVATE_DATA->current_position = ROTATOR_POSITION_ITEM->number.value; indigo_update_property(device, ROTATOR_POSITION_PROPERTY, NULL); } else { ROTATOR_POSITION_PROPERTY->state = INDIGO_BUSY_STATE; ROTATOR_POSITION_ITEM->number.value = PRIVATE_DATA->current_position; PRIVATE_DATA->target_position = ROTATOR_POSITION_ITEM->number.target; indigo_update_property(device, ROTATOR_POSITION_PROPERTY, NULL); indigo_set_timer(device, 0.2, rotator_timer_callback, &PRIVATE_DATA->rotator_timer); } return INDIGO_OK; } else if (indigo_property_match(ROTATOR_ABORT_MOTION_PROPERTY, property)) { // -------------------------------------------------------------------------------- ROTATOR_ABORT_MOTION indigo_property_copy_values(ROTATOR_ABORT_MOTION_PROPERTY, property, false); if (ROTATOR_ABORT_MOTION_ITEM->sw.value && ROTATOR_POSITION_PROPERTY->state == INDIGO_BUSY_STATE) { ROTATOR_POSITION_PROPERTY->state = INDIGO_ALERT_STATE; ROTATOR_POSITION_ITEM->number.value = PRIVATE_DATA->current_position; indigo_update_property(device, ROTATOR_POSITION_PROPERTY, NULL); } ROTATOR_ABORT_MOTION_PROPERTY->state = INDIGO_OK_STATE; ROTATOR_ABORT_MOTION_ITEM->sw.value = false; indigo_update_property(device, ROTATOR_ABORT_MOTION_PROPERTY, NULL); return INDIGO_OK; // -------------------------------------------------------------------------------- } return indigo_rotator_change_property(device, client, property); } static indigo_result rotator_detach(indigo_device *device) { assert(device != NULL); if (IS_CONNECTED) { indigo_set_switch(CONNECTION_PROPERTY, CONNECTION_DISCONNECTED_ITEM, true); rotator_connect_callback(device); } INDIGO_DEVICE_DETACH_LOG(DRIVER_NAME, device->name); return indigo_rotator_detach(device); } // -------------------------------------------------------------------------------- static simulator_private_data *private_data = NULL; static indigo_device *imager_focuser = NULL; indigo_result indigo_rotator_simulator(indigo_driver_action action, indigo_driver_info *info) { static indigo_device imager_rotator_template = INDIGO_DEVICE_INITIALIZER( SIMULATOR_ROTATOR_NAME, rotator_attach, indigo_rotator_enumerate_properties, rotator_change_property, NULL, rotator_detach ); static indigo_driver_action last_action = INDIGO_DRIVER_SHUTDOWN; SET_DRIVER_INFO(info, "Field Rotator Simulator", __FUNCTION__, DRIVER_VERSION, true, last_action); if (action == last_action) return INDIGO_OK; switch(action) { case INDIGO_DRIVER_INIT: last_action = action; private_data = indigo_safe_malloc(sizeof(simulator_private_data)); imager_focuser = indigo_safe_malloc_copy(sizeof(indigo_device), &imager_rotator_template); imager_focuser->private_data = private_data; indigo_attach_device(imager_focuser); break; case INDIGO_DRIVER_SHUTDOWN: VERIFY_NOT_CONNECTED(imager_focuser); last_action = action; if (imager_focuser != NULL) { indigo_detach_device(imager_focuser); free(imager_focuser); imager_focuser = NULL; } if (private_data != NULL) { free(private_data); private_data = NULL; } break; case INDIGO_DRIVER_INFO: break; } return INDIGO_OK; }
c
17
0.693435
124
40.609756
205
starcoderdata
public void handle(ActionEvent e) { try { File tempFile; File outputFile; FileChooser choseOutputFile = new FileChooser (); // setting extension filters FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter ("PDF files (*.pdf)", "*.pdf"); choseOutputFile.getExtensionFilters().add(extFilter); tempFile = choseOutputFile.showSaveDialog(dFVMainWindow); String out = tempFile.toString().substring(Math.max(0, tempFile. toString().length() - 4)); // dealing with adding file extensions if not already present if (!(out.equals(".pdf"))){ out = tempFile.toString() + ".pdf"; outputFile = new File (out); } else{ outputFile = new File (tempFile.toString()); } export.asPDF(note, notebook, outputFile); } catch (Exception ex){ } }
java
15
0.321283
111
54.354839
31
inline
package pl.roentgen.util; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import pl.roentgen.util.model.Point; import java.util.Comparator; import java.util.Observable; import java.util.concurrent.atomic.AtomicInteger; public class PointManager extends Observable { private ObservableList points = FXCollections.observableArrayList(); public static final AtomicInteger idPoint = new AtomicInteger(0); public void setPoints(ObservableList points) { this.points = points; points.sort(Comparator.comparingInt(Point::getId)); setChanged(); notifyObservers(); } public void addPoint(Point point){ points.add(point); setPoints(points); } public void removePoint(Point point) { points.remove(point); setPoints(points); } public void changePointPosition(int idPoint, double x, double y) { Point pointToChange = points.stream().filter(point -> sameID(point, idPoint)).findFirst().get(); pointToChange.setX((int)x); pointToChange.setY((int)y); setPoints(points); } public void changePointVisibility(int idPoint, boolean visible) { points.stream().filter(point -> sameID(point, idPoint)).findFirst().get().setVisible(visible); setPoints(points); } public ObservableList getPoints() { return this.points; } public int getId(){ return idPoint.getAndIncrement(); } private boolean sameID(Point point, int id){ return point.getId() == id; } }
java
14
0.676636
104
27.157895
57
starcoderdata
<?php /** * */ class modelTiket extends CI_Model { function __construct() { parent::__construct(); } function getMyTiket($user){ $this->db->select('*'); $this->db->from('ticket a'); $this->db->join('kategori b','b.id_kategori=a.id_kategori','left'); $this->db->join('prioritas c','c.id_prioritas=a.id_prioritas','left'); $this->db->join('status d','d.id_status=a.id_status','left'); $this->db->join('teknisi e','e.id_teknisi=a.id_teknisi','left'); $this->db->where('a.pelapor',$user); $query = $this->db->get(); $row = $query->result_array(); return $row; } public function dropdown_kategori() { $sql = "SELECT * FROM kategori ORDER BY nama_kategori"; $query = $this->db->query($sql); $value[''] = '-- PILIH --'; foreach ($query->result() as $row){ $value[$row->id_kategori] = $row->nama_kategori; } return $value; } public function dropdown_kondisi() { $sql = "SELECT * FROM kondisi ORDER BY nama_kondisi"; $query = $this->db->query($sql); $value[''] = '-- PILIH --'; foreach ($query->result() as $row){ $value[$row->id_kondisi] = $row->nama_kondisi." - (TARGET PROSES ".$row->waktu_respon." "."HARI)"; } return $value; } function GetDataTracking($data){ $this->db->select('*'); $this->db->from('tracking a'); $this->db->join('ticket b', 'b.id_tiket=a.id_tiket', 'left'); $this->db->where('a.id_tiket', $data); $query = $this->db->get(); $row = $query->result_array(); return $row; } public function savetracking($tracking){ $this->db->trans_start(); $this->db->insert('tracking', $tracking); $this->db->trans_complete(); } } ?>
php
15
0.575472
103
22.901408
71
starcoderdata
'use strict'; require('./_utils'); var assert = require('assert'); var tester = require('../').Code; describe('Code', function () { it('default_isbn_regexp', function () { assert(tester.isbn().match(/^\d{9}-[\d|X]$/)); }); it('default_isbn13_regexp', function () { assert(tester.isbn(13).match(/^\d{12}-\d$/)); }); it('default_ean_regexp', function () { assert(tester.ean().match(/^\d{13}$/)); }); it('default_ean8_regexp', function () { assert(tester.ean(8).match(/^\d{8}$/)); }); it('rut', function () { assert(tester.rut().match(/^\d{1,8}-(\d|k)$/)); }); });
javascript
18
0.554364
51
21.517241
29
starcoderdata
def get_data_api(category_name, monitor_name, data_name, start_date, end_date): '''Function for getting reported data for a monitor.''' logger.info(f"Getting data for monitor {monitor_name} in category {category_name}, data type: {data_name}") #Validate category and monitor name category_and_monitor_name_validation = validate_category_and_monitor_name(category_name, monitor_name) if category_and_monitor_name_validation["status"] != API_STATUS_SUCCESS: logger.info("Category name or monitor name is invalid! Returning error...") return category_and_monitor_name_validation #Validate date logger.info(f"Validating passed dates, start date {start_date} and end date {end_date}...") #Attempt parsing of start and end date. start_date_parsed = check_date(start_date) if start_date_parsed == INVALID_DATE_RESPONSE: logger.info("Could not parse start date! Error.") return generate_api_error("The passed start date to search for data with is invalid.", HTTPStatus.BAD_REQUEST) #Answer with error and BAD_REQUEST status code end_date_parsed = check_date(end_date) if end_date_parsed == INVALID_DATE_RESPONSE: logger.info("Could not parse end date! Error.") return generate_api_error("The passed end date to search for data with is invalid.", HTTPStatus.BAD_REQUEST) #Answer with error and BAD_REQUEST status code logger.info("Data is valid! Looking for data...") data_for_date = data.get_data(False, category_name, monitor_name, data_name, start_date_parsed, end_date_parsed ) logger.info("Data retrieved. Checking if it was found...") if data_for_date in [None, []]: logger.info("Data for day was not found. Returning error...") return generate_api_error("Data for the requested day was not found.", HTTPStatus.NOT_FOUND) #Answer with error and NOT_FOUND status code logger.info("Data for day was found! Returning response...") return generate_api_response( API_STATUS_SUCCESS, {"data": data_for_date} )
python
9
0.620351
165
60.578947
38
inline
// generated by xgen -- DO NOT EDIT package role import ( "gopkg.in/goyy/goyy.v0/data/entity" "gopkg.in/goyy/goyy.v0/data/service" ) var PostMgr = &PostManager{ Manager: service.Manager{ Entity: func() entity.Interface { return NewPostEntity() }, Entities: func() entity.Interfaces { return NewPostEntities(10) }, }, } type PostManager struct { service.Manager }
go
19
0.710046
52
18.043478
23
starcoderdata
/* Copyright (c) 2009-2010 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 LibCat 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. */ #ifndef CAT_THREAD_POOL_HPP #define CAT_THREAD_POOL_HPP #include #include #include #include #include #include #include #if defined(CAT_OS_WINDOWS) # include #endif namespace cat { // Reference Object priorities enum RefObjectPriorities { REFOBJ_PRIO_0, REFOBJ_PRIO_COUNT = 32, }; /* class ThreadRefObject Base class for any thread-safe reference-counted thread pool object Designed this way so that all of these objects can be automatically deleted */ class ThreadRefObject { friend class ThreadPool; ThreadRefObject *last, *next; int _priorityLevel; volatile u32 _refCount; public: ThreadRefObject(int priorityLevel); CAT_INLINE virtual ~ThreadRefObject() {} public: void AddRef(); void ReleaseRef(); // Safe release -- If not null, then releases and sets to null template<class T> static CAT_INLINE void SafeRelease(T * &object) { if (object) { object->ReleaseRef(); object = 0; } } }; // Auto release for ThreadRefObject references template<class T> class AutoRef { T *_ref; public: CAT_INLINE AutoRef(T *ref = 0) throw() { _ref = ref; } CAT_INLINE ~AutoRef() throw() { ThreadRefObject::SafeRelease(_ref); } CAT_INLINE AutoRef &operator=(T *ref) throw() { Reset(ref); return *this; } CAT_INLINE T *Get() throw() { return _ref; } CAT_INLINE T *operator->() throw() { return _ref; } CAT_INLINE T &operator*() throw() { return *_ref; } CAT_INLINE operator T*() { return _ref; } CAT_INLINE void Forget() throw() { _ref = 0; } CAT_INLINE void Reset(T *ref = 0) throw() { ThreadRefObject::SafeRelease(_ref); _ref = ref; } }; //// TLS class ThreadPoolLocalStorage { public: BigTwistedEdwards *math; FortunaOutput *csprng; ThreadPoolLocalStorage(); ~ThreadPoolLocalStorage(); bool Valid(); }; //// Shutdown class ShutdownWait; class ShutdownObserver; class ShutdownWait { friend class ShutdownObserver; WaitableFlag _kill_flag; ShutdownObserver *_observer; void OnShutdownDone(); public: // Priority number must be higher than users' ShutdownWait(int priorityLevel); /*virtual*/ ~ShutdownWait(); CAT_INLINE ShutdownObserver *GetObserver() { return _observer; } bool WaitForShutdown(u32 milliseconds); }; class ShutdownObserver : public ThreadRefObject { friend class ShutdownWait; ShutdownWait *_wait; private: ShutdownObserver(int priorityLevel, ShutdownWait *wait); ~ShutdownObserver(); }; //// ThreadPoolWorker class ThreadPoolWorker : public Thread { public: virtual bool ThreadFunction(void *port); }; #if defined(CAT_OS_WINDOWS) typedef HANDLE ThreadPoolHandle; #else typedef int ThreadPoolHandle; #endif /* class ThreadPool Startup() : Call to start up the thread pool Shutdown() : Call to destroy the thread pool and objects */ class ThreadPool : public Singleton { friend class ThreadRefObject; CAT_SINGLETON(ThreadPool); #if defined(CAT_OS_WINDOWS) HANDLE _port; #endif int _processor_count, _active_thread_count; static const int MAX_THREADS = 256; ThreadPoolWorker _threads[MAX_THREADS]; // Track sockets for graceful termination Mutex _objectRefLock[REFOBJ_PRIO_COUNT]; ThreadRefObject *_objectRefHead[REFOBJ_PRIO_COUNT]; protected: void TrackObject(ThreadRefObject *object); void UntrackObject(ThreadRefObject *object); bool SpawnThread(); bool SpawnThreads(); public: bool Startup(); void Shutdown(); bool Associate(ThreadPoolHandle h, ThreadRefObject *key); int GetProcessorCount() { return _processor_count; } int GetThreadCount() { return _active_thread_count; } }; } // namespace cat #endif // CAT_THREAD_POOL_HPP
c++
14
0.709585
94
23.303167
221
starcoderdata
import React, { Component } from "react"; import "./ReviewInput.css"; /** * ReviewInput component renders the input fields for a new review * on a recipe. It uses local state to keep track of changes in the * field. Props come from ReviewsContainer. */ class ReviewInput extends Component { state = { comment: "", }; /** * Callback that handles the event when input changes in comment field. */ handleOnChange = (event) => { this.setState({ comment: event.target.value, }); }; /** * Callback that handles the event when submitting a review on a recipe. */ handleOnSubmit = (event) => { event.preventDefault(); this.props.addReview(this.state.comment, this.props.recipeId); this.setState({ comment: "", }); }; render() { return ( <form onSubmit={this.handleOnSubmit} className="reviewInput"> <textarea placeholder="Review this Treasure!" value={this.state.comment} onChange={this.handleOnChange} /> <input type="submit" /> ); } } export default ReviewInput;
javascript
14
0.606742
74
24.152174
46
starcoderdata
<?php // // //--------------------------- GALERIAS //Pega os dados dos custom fields $foto1 = get_field('foto_1'); $foto2 = get_field('foto_2'); $foto3 = get_field('foto_3'); $foto4 = get_field('foto_4'); $foto5 = get_field('foto_5'); $foto6 = get_field('foto_6'); $foto7 = get_field('foto_7'); $foto8 = get_field('foto_8'); $foto9 = get_field('foto_9'); $foto10 = get_field('foto_10'); $foto11 = get_field('foto_11'); $foto12 = get_field('foto_12'); $foto13 = get_field('foto_13'); $foto14 = get_field('foto_14'); $foto15 = get_field('foto_15'); $legenda_1 = get_field('legenda_1'); $legenda_2 = get_field('legenda_2'); $legenda_3 = get_field('legenda_3'); $legenda_4 = get_field('legenda_4'); $legenda_5 = get_field('legenda_5'); $legenda_6 = get_field('legenda_6'); $legenda_7 = get_field('legenda_7'); $legenda_8 = get_field('legenda_8'); $legenda_9 = get_field('legenda_9'); $legenda_10 = get_field('legenda_10'); $legenda_11 = get_field('legenda_11'); $legenda_12 = get_field('legenda_12'); $legenda_13 = get_field('legenda_13'); $legenda_14 = get_field('legenda_14'); $legenda_15 = get_field('legenda_15'); //Atribuindo a novas variaveis $cont_1 = $foto1; $cont_2 = $foto2; $cont_3 = $foto3; $cont_4 = $foto4; $cont_5 = $foto5; $cont_6 = $foto6; $cont_7 = $foto7; $cont_8 = $foto8; $cont_9 = $foto9; $cont_10 = $foto10; $cont_11 = $foto11; $cont_12 = $foto12; $cont_13 = $foto13; $cont_14 = $foto14; $cont_15 = $foto15; //Verificando se o campo esta preenchido ou em branco if ((strlen($cont_1)) > 3) { $cont_1 = 1; } else { $cont_1 = 0; } if ((strlen($cont_2)) > 3) { $cont_2 = 1; } else { $cont_2 = 0; } if ((strlen($cont_3)) > 3) { $cont_3 = 1; } else { $cont_3 = 0; } if ((strlen($cont_4)) > 3) { $cont_4 = 1; } else { $cont_4 = 0; } if ((strlen($cont_5)) > 3) { $cont_5 = 1; } else { $cont_5 = 0; } if ((strlen($cont_6)) > 3) { $cont_6 = 1; } else { $cont_6 = 0; } if ((strlen($cont_7)) > 3) { $cont_7 = 1; } else { $cont_7 = 0; } if ((strlen($cont_8)) > 3) { $cont_8 = 1; } else { $cont_8 = 0; } if ((strlen($cont_9)) > 3) { $cont_9 = 1; } else { $cont_9 = 0; } if ((strlen($cont_10)) > 3) { $cont_10 = 1; } else { $cont_10 = 0; } if ((strlen($cont_11)) > 3) { $cont_11 = 1; } else { $cont_11 = 0; } if ((strlen($cont_12)) > 3) { $cont_12 = 1; } else { $cont_12 = 0; } if ((strlen($cont_13)) > 3) { $cont_13 = 1; } else { $cont_13 = 0; } if ((strlen($cont_14)) > 3) { $cont_14 = 1; } else { $cont_14 = 0; } if ((strlen($cont_15)) > 3) { $cont_15 = 1; } else { $cont_15 = 0; } // // //Printa as imagens se os CF estiverem preenchidos if ($cont_1 == 1) { ?> <a href="<?php the_field('foto_1') ?>"> <img id="galeria_single_item" class="colorbox-562" src="<?php the_field('foto_1'); ?>" title="<?php echo $legenda_1; ?>"> <?php } else { } if ($cont_2 == 1) { ?> <a href="<?php the_field('foto_2') ?>"> <img id="galeria_single_item" class="colorbox-562" src="<?php the_field('foto_2'); ?>" title="<?php echo $legenda_2; ?>"> <?php } else { } if ($cont_3 == 1) { ?> <a href="<?php the_field('foto_3') ?>"> <img id="galeria_single_item" class="colorbox-562" src="<?php the_field('foto_3'); ?>" title="<?php echo $legenda_3; ?>"> <?php } else { } if ($cont_4 == 1) { ?> <a href="<?php the_field('foto_4') ?>"> <img id="galeria_single_item" class="colorbox-562" src="<?php the_field('foto_4'); ?>" title="<?php echo $legenda_4; ?>"> <?php } else { } if ($cont_5 == 1) { ?> <a href="<?php the_field('foto_5') ?>"> <img id="galeria_single_item" class="colorbox-562" src="<?php the_field('foto_5'); ?>" title="<?php echo $legenda_5; ?>"> <?php } else { } if ($cont_6 == 1) { ?> <a href="<?php the_field('foto_6') ?>"> <img id="galeria_single_item" class="colorbox-562" src="<?php the_field('foto_6'); ?>" title="<?php echo $legenda_6; ?>"> <?php } else { } if ($cont_7 == 1) { ?> <a href="<?php the_field('foto_7') ?>"> <img id="galeria_single_item" class="colorbox-562" src="<?php the_field('foto_7'); ?>" title="<?php echo $legenda_7; ?>"> <?php } else { } if ($cont_8 == 1) { ?> <a href="<?php the_field('foto_8') ?>"> <img id="galeria_single_item" class="colorbox-562" src="<?php the_field('foto_8'); ?>" title="<?php echo $legenda_8; ?>"> <?php } else { } if ($cont_9 == 1) { ?> <a href="<?php the_field('foto_9') ?>"> <img id="galeria_single_item" class="colorbox-562" src="<?php the_field('foto_9'); ?>" title="<?php echo $legenda_9; ?>"> <?php } else { } if ($cont_10 == 1) { ?> <a href="<?php the_field('foto_10') ?>"> <img id="galeria_single_item" class="colorbox-562" src="<?php the_field('foto_10'); ?>" title="<?php echo $legenda_10; ?>"> <?php } else { } if ($cont_11 == 1) { ?> <a href="<?php the_field('foto_11') ?>"> <img id="galeria_single_item" class="colorbox-562" src="<?php the_field('foto_11'); ?>" title="<?php echo $legenda_11; ?>"> <?php } else { } if ($cont_12 == 1) { ?> <a href="<?php the_field('foto_12') ?>"> <img id="galeria_single_item" class="colorbox-562" src="<?php the_field('foto_12'); ?>" title="<?php echo $legenda_12; ?>"> <?php } else { } if ($cont_13 == 1) { ?> <a href="<?php the_field('foto_13') ?>"> <img id="galeria_single_item" class="colorbox-562" src="<?php the_field('foto_13'); ?>" title="<?php echo $legenda_13; ?>"> <?php } else { } if ($cont_14 == 1) { ?> <a href="<?php the_field('foto_14') ?>"> <img id="galeria_single_item" class="colorbox-562" src="<?php the_field('foto_14'); ?>" title="<?php echo $legenda_14; ?>"> <?php } else { } if ($cont_15 == 1) { ?> <a href="<?php the_field('foto_15') ?>"> <img id="galeria_single_item" class="colorbox-562" src="<?php the_field('foto_15'); ?>" title="<?php echo $legenda_15; ?>"> <?php } else { } echo ' echo ' the_content(); ?>
php
9
0.484636
131
21.818841
276
starcoderdata
#ifndef MARISA_POPCOUNT_H_ #define MARISA_POPCOUNT_H_ #include "base.h" namespace marisa { class PopCount { public: PopCount(UInt32 x) : value_() { x = (x & 0x55555555U) + ((x & 0xAAAAAAAAU) >> 1); x = (x & 0x33333333U) + ((x & 0xCCCCCCCCU) >> 2); x = (x + (x >> 4)) & 0x0F0F0F0FU; x += x << 8; x += x << 16; value_ = x; } UInt32 lo8() const { return value_ & 0xFFU; } UInt32 lo16() const { return (value_ >> 8) & 0xFFU; } UInt32 lo24() const { return (value_ >> 16) & 0xFFU; } UInt32 lo32() const { return value_ >> 24; } private: UInt32 value_; }; } // namespace marisa #endif // MARISA_POPCOUNT_H_
c
15
0.542274
53
16.589744
39
starcoderdata
""" Outlook Round-Robin ------------ Watches a folder in a user's mailbox for unread messages. When it finds some, messages are forwarded to a list of recipients in a round-robin fashion. """ from datetime import datetime, timedelta from time import sleep import logging import logging.handlers import signal import sys import requests import settings API_ENDPOINT = 'https://graph.microsoft.com/v1.0' logger = logging.getLogger(__name__) class MSGraphAuth(requests.auth.AuthBase): """ Adds the access token to a request. """ def __init__(self, access_token): self.access_token = access_token def __call__(self, request): request.headers['Authorization'] = "Bearer {}".format(self.access_token) return request def store_index(index): """ Stores an integer in the file at `INDEX_FILE_PATH`. """ try: with open(settings.INDEX_FILE_PATH, 'w') as data_file: data_file.write('{}\n'.format(index)) except: pass def load_index(): """ Retrieves an integer from the file at `INDEX_FILE_PATH`. Returns the value in the file, if the file is read successfully; 0 otherwise. """ try: with open(settings.INDEX_FILE_PATH, 'r') as data_file: return int(data_file.readline()) except: return 0 def get_access_token(): """ Requests an access token from Azure AD. Returns (True, [access token]) on success; (False, "") otherwise. """ response = requests.post(settings.TOKEN_PROVIDER_ENDPOINT, data={ 'client_id': settings.CLIENT_ID, 'client_secret': settings.CLIENT_SECRET, 'resource': 'https://graph.microsoft.com', 'grant_type': 'client_credentials' }) data = response.json() if response.status_code == 200: logger.debug('Got access token.') expires_seconds = int(data['expires_in']) # set renewal time to 5 minutes before expiry, just to be safe return True, data['access_token'], datetime.now() + timedelta(seconds=expires_seconds - 300) else: logger.error('Error getting access token: {}'.format(data['error_description'])) return False, "", None def mark_message_as_read(message_id, access_token): """ Marks a message as read. Returns True on success; False otherwise. """ logger.debug('Marking message {} as read...'.format(message_id)) endpoint = API_ENDPOINT + '/users/{}/messages/{}'.format(settings.MAILBOX_USER, message_id) response = requests.patch(endpoint, json={ 'isRead': True }, auth=MSGraphAuth(access_token)) if response.status_code == 200: logger.debug('Message successfully updated.') return True else: data = response.json() logger.error('Error updating message {}: {}'.format(message_id, data['error']['message'])) return False def forward_message(message_id, recipient_name, recipient_email, access_token): """ Forwards a message to a recipient. Returns True on success; False otherwise. """ logger.debug('Forwaring message {} to {}...'.format(message_id, recipient_email)) endpoint = API_ENDPOINT + '/users/{}/messages/{}/forward'.format(settings.MAILBOX_USER, message_id) response = requests.post(endpoint, json={ 'comment': '', 'toRecipients': [ { 'emailAddress': { 'address': recipient_email, 'name': recipient_name } } ] }, auth=MSGraphAuth(access_token)) if response.status_code == 202: logger.debug('Message successfully forwarded.') return True else: data = response.json() logger.error('Error forwarding message {}: {}'.format(message_id, data['error']['message'])) return False def send_reply(recipient_email, access_token): """ Sends the auto-reply message to a recipient. Returns True on success; False otherwise. """ endpoint = API_ENDPOINT + '/users/{}/sendMail'.format(settings.MAILBOX_USER) response = requests.post(endpoint, json={ 'message': { 'subject': settings.AUTO_REPLY_SUBJECT, 'body': { 'contentType': 'text', 'content': settings.AUTO_REPLY_BODY }, 'toRecipients': [ { 'emailAddress': { 'address': recipient_email } } ] }, 'saveToSentItems': 'true' }, auth=MSGraphAuth(access_token)) if response.status_code == 202: logger.debug('Reply message send to {}'.format(recipient_email)) return True else: data = response.json() logger.error('Error sending reply message to {}: {}'.format(recipient_email, data['error']['message'])) return False def load_messages(access_token): """ Loads unread messages from the mailbox folder. Note that only the message `id` and `subject` are retrieved. Returns (True, messages) on success; (False, []) otherwise. """ logger.debug('Getting {} newest messages from {}\'s {} folder...'.format( settings.LOAD_MESSAGE_COUNT, settings.MAILBOX_USER, settings.WATCH_FOLDER )) endpoint = API_ENDPOINT + '/users/{}/mailFolders/{}/messages'.format(settings.MAILBOX_USER, settings.WATCH_FOLDER) response = requests.get(endpoint, params={ '$filter': 'isRead eq false', '$top': settings.LOAD_MESSAGE_COUNT, '$select': 'id,subject,from' }, auth=MSGraphAuth(access_token)) data = response.json() if response.status_code == 200: messages = data['value'] logger.debug('Loaded {} messages from inbox.'.format(len(messages))) return True, messages else: logger.error('Error getting messages: {}'.format(data['error']['message'])) return False, [] def check_messages(start_index, access_token): """ Forwards unread messages to the list of users in `FORWARD_TO`. Forwarded messages are then marked as read. Returns the next index in `FORWARD_TO` that should be used. """ got_messages, messages = load_messages(access_token) if not got_messages: return start_index if not messages: logger.info('No unread messages.') stop_index = start_index for message in messages: forward_name, forward_email = settings.FORWARD_TO[stop_index] try: sender_email = message['from']['emailAddress']['address'] except KeyError: sender_email = None logger.info('Processing message for {}: {}'.format(forward_email, message['subject'])) if forward_message(message['id'], forward_name, forward_email, access_token): mark_message_as_read(message['id'], access_token) stop_index = (stop_index + 1) % len(settings.FORWARD_TO) if settings.AUTO_REPLY and (sender_email is not None) and (sender_email.lower() not in settings.AUTO_REPLY_EXCLUSIONS): send_reply(sender_email, access_token) sleep(0.25) return stop_index if __name__ == "__main__": def exit_handler(signal, frame): print('Exiting...') exit(0) signal.signal(signal.SIGINT, exit_handler) if settings.LOG_FILE_PATH: log_handler = logging.handlers.TimedRotatingFileHandler(settings.LOG_FILE_PATH, 'midnight', 1, backupCount=settings.LOG_BACKUPS) else: log_handler = logging.StreamHandler(stream=sys.stdout) log_formatter = logging.Formatter(settings.LOG_FORMAT, settings.LOG_DATETIME_FORMAT) log_handler.setLevel(getattr(logging, settings.LOG_LEVEL.upper())) log_handler.setFormatter(log_formatter) logger.addHandler(log_handler) logger.setLevel(logging.DEBUG) renew_token_at = datetime.now() while True: if renew_token_at <= datetime.now(): logger.info('Renewing token...') got_token, access_token, renew_token_at = get_access_token() if not got_token: exit() logger.info('Checking messages...') start_index = load_index() stop_index = check_messages(start_index, access_token) store_index(stop_index) sleep(settings.POLL_INTERVAL * 60)
python
18
0.607469
131
30.065455
275
starcoderdata
// // KBPopupHeaders.h // KBPopupBubble // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Created by on 4/6/13. // // // Macro for weak linking, in case we want to support 4.3 and before // #ifndef KB_WEAK #if __has_feature(objc_arc_weak) #define KB_WEAK weak #elif __has_feature(objc_arc) #define KB_WEAK unsafe_unretained #else #define KB_WEAK assign #endif #endif // KB_WEAK #ifndef KB_WEAK_REF #if __has_feature(obj_arc_weak) #define KB_WEAK_REF __weak #else #define KB_WEAK_REF __unsafe_unretained #endif #endif // KB_WEAK_REF // // Macros for hardware detection // #define IS_IPHONE_5 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 568.0f) #define IS_IPHONE_4 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 480.0f) // // Macros for debugging // #ifndef DLog #ifdef DEBUG #define DLog(...) NSLog(__VA_ARGS__) #else #define DLog(...) /* */ #endif // DEBUG #endif // DLog #ifndef ALog #define ALog(...) NSLog(__VA_ARGS__) #endif // ALog
c
6
0.720363
87
29.333333
69
starcoderdata
<?php namespace BaseTree\Tests\Fake\Integration; use BaseTree\Eloquent\BaseEloquent; class EloquentUser extends BaseEloquent implements UserRepository { public function __construct(UserModel $model) { parent::__construct($model); } }
php
10
0.728682
65
16.266667
15
starcoderdata
<?php /* |-------------------------------------------------------------------------- | 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! | */ Route::get('/', function () { return redirect()->route('login'); }); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); // User Resources Route::resource('users', 'UserController'); // Announcement Resources Route::resource('announcements', 'AnnouncementController'); // Survey Resources Route::resource('surveys', 'SurveyController'); // Facts & Figures / Presentation Resources Route::resource('file-uploads', 'FileController'); // PUF Items Resources Route::resource('puf-items', 'PufItemController'); Route::post('puf-items/year-survey', 'PufItemController@survey'); Route::post('puf-items/{id}/year-survey', 'PufItemController@survey'); Route::get('puf-datasets', 'PufItemController@upload_dataset')->name('dataset.index'); Route::post('puf-datasets/store', 'PufItemController@dataset_store')->name('dataset.store'); Route::post('puf-datasets/year-survey', 'PufItemController@survey'); // Page Content Resources Route::resource('page-contents', 'PageContentController'); // Frequently Ask Question Resources Route::resource('faqs', 'FaqController'); // Image Resource Route::resource('image-uploads', 'ImageController'); Route::post('image-uploads/status', 'ImageController@status'); // Infographics Resource Route::resource('infographics', 'InfographicsController'); Route::get('infographics/gallery/{id}', 'InfographicsController@gallery')->name('gallery.index'); Route::get('infographics/gallery/{id}/upload', 'InfographicsController@gallery_create')->name('gallery.create'); Route::post('infographics/gallery/{id}/upload', 'InfographicsController@gallery_store')->name('gallery.store'); Route::delete('infographics/gallery/{id}', 'InfographicsController@gallery_destroy')->name('gallery.destroy'); // Route::resource('gallery', 'GalleryController'); // Profile Controller Route::get('profile', 'ProfileController@index')->name('profile.index'); Route::patch('profile/update/{id}', 'ProfileController@update')->name('profile.update'); // Questionaires Controller Route::resource('scanned-questionaires', 'QuestionairesController');
php
12
0.698503
112
37.030769
65
starcoderdata
#pragma once #include #include #include #include "lev/lev.h" namespace lev { class loop; class socket { public: static const uint32_t EventRead = 1; static const uint32_t EventWrite = 2; socket(loop& loop); void SetActiveEvents(LEV_SOCKET socket, uint32_t events); void Destroy(); bool IsEventEnabled(uint32_t eventtype) const { return (m_events & eventtype) != 0; } void EnableEvents(uint32_t events); void DisableEvents(uint32_t events); std::function OnErrorEvent; std::function OnReadEvent; std::function OnWriteEvent; std::function<void(std::exception_ptr e)> OnException; std::function OnReadyToDestroy; protected: void Updated(int fd, uint32_t events); friend void ioresponder(ev::io& ioobj, int revents); uint32_t m_events; int m_fd; ev::io m_iowatcher; bool m_bInResponder; bool m_bDestroyScheduled; private: socket(const socket&); // not allowed socket& operator=(const socket&); // not allowed }; };
c
12
0.651121
88
20.3
50
starcoderdata
@Override public void start() { // Each player gets a hand of 2 cards in their HOLE/POCKET dealHoleCards(); // PREFLOP is the first round where players can either FOLD, BET, CHECK or RAISE without any community cards having been dealt // before the FLOP, a card is BURNED burnCard(); // FLOP is the second round flop(); printCommunityCards(); // before the TURN, a card is BURNED burnCard(); // TURN is the third round turn(); printCommunityCards(); // before the RIVER, a card is BURNED burnCard(); // RIVER is the fourth and final round river(); printCommunityCards(); // when all bets have been settled, the HOLE cards are shown printPlayerHands(); // the player hands are evaluated evaluatePlayerHands(); }
java
6
0.585825
134
25.588235
34
inline
@Override protected Expression visitModuleExpression(@NotNull ModuleExpression expr) { ModuleArchiveExpression archive = expr.archive; CxxLanguageFeatures requires[] = archive.requires; if (requires.length == 0) { return super.visitModuleExpression(expr); } // Get rid of requires in ModuleArchiveExpression archive = new ModuleArchiveExpression(archive.file, archive.sha256, archive.size, archive.include, archive.includePath, archive.libs, archive.libraryPaths, archive.completionSentinel, new CxxLanguageFeatures[0]); // Make constant expression of requires List<ConstantExpression> features = new ArrayList<>(); for (CxxLanguageFeatures require : requires) { features.add(constant(require)); } // Find the minimum language standard to support all the requirements int minimumLanguageStandard = 0; for (CxxLanguageFeatures require : requires) { minimumLanguageStandard = Math.max( minimumLanguageStandard, require.standard); } List<StatementExpression> exprs = new ArrayList<>(); exprs.add( ifSwitch( // If build system (CMake or ndk-build) supports compiler feature requirements supportsCompilerFeatures(), // The build system supports compiler features so request the features from the manifest requiresCompilerFeatures(array(features.toArray(new ConstantExpression[requires.length]))), // Otherwise, require the lowest compiler standard that supports the listed features requireMinimumCxxCompilerStandard(constant(minimumLanguageStandard)))); exprs.add(archive); return new MultiStatementExpression(exprs.toArray(new StatementExpression[exprs.size()])); }
java
17
0.699561
103
38.673913
46
inline
import numpy as np from mxnet.gluon.data import dataset import json import os import cv2 try: from src.utils import resize_image, transform_bb_after_resize, transform_bb_after_cropping except ModuleNotFoundError: from utils import resize_image, transform_bb_after_resize, transform_bb_after_cropping class HandwritingRecognitionDataset(dataset.ArrayDataset): PAGE_SIZE = (700, 700) LINE_SIZE = (60, 800) WORD_SIZE = (60, 175) def __init__(self, dir_path, path, annotation_filename, output_type, transform=None): assert output_type in ["page", "line", "word"], "output_type can only be 'page', 'line', or 'word'." self.images_path = os.path.join(dir_path, path) self.annotations = self._read_annotations(os.path.join(dir_path, path, annotation_filename), output_type) self.output_type = output_type self.transform = transform super(HandwritingRecognitionDataset, self).__init__(self.annotations) def __getitem__(self, index): item = self.annotations[index] im = cv2.imread(os.path.join(self.images_path, item['filename']), cv2.IMREAD_GRAYSCALE) original_image_size = im.shape resized_image, border_bb = resize_image(im, desired_size=self.PAGE_SIZE) resized_image_size = resized_image.shape annotations = item['annotation'] texts = [] bbs = [] for annotation in annotations: texts.append(annotation['text']) bbs.append(annotation['bb']) bbs = np.array(bbs).astype(float) if len(bbs.shape) == 3: bbs = bbs[0] bbs = self._normalise_bb(bbs, original_image_size) if self.output_type == "line": transformed_bb = transform_bb_after_resize( bbs, border_bb, original_image_size, resized_image_size) line_bb = np.expand_dims(annotations[0]['line_bb'], 0).astype(float) line_bb = self._normalise_bb(line_bb, original_image_size) transformed_line_bb = transform_bb_after_resize( line_bb, border_bb, original_image_size, resized_image_size) resized_image, transformed_bb, texts = self._crop_image( resized_image, transformed_line_bb, transformed_bb, texts, self.LINE_SIZE) elif self.output_type == "word": transformed_bb = transform_bb_after_resize( bbs, border_bb, original_image_size, resized_image_size) word_bb = np.expand_dims(annotations[0]['bb'], 0).astype(float) word_bb = self._normalise_bb(word_bb, original_image_size) transformed_word_bb = transform_bb_after_resize( word_bb, border_bb, original_image_size, resized_image_size) resized_image, _, texts = self._crop_image( resized_image, transformed_word_bb, transformed_bb, [texts], self.WORD_SIZE) # Word output_type has no bounding boxes transformed_bb = np.array([[0, 0, 1, 1]]) elif self.output_type == "page": transformed_bb = transform_bb_after_resize( bbs, border_bb, original_image_size, resized_image_size) if self.transform is not None: return self.transform(resized_image, transformed_bb, texts) else: return self.transform(resized_image, transformed_bb, texts) def _crop_image(self, resized_image, crop_bb, bb, texts, desired_size): assert crop_bb.shape[0] == 1, "There should be only 1 bounding boxes for output line mode" x1, y1, x2, y2 = crop_bb[0] resized_image_shape = resized_image.shape x1 = int(x1 * resized_image_shape[1]) y1 = int(y1 * resized_image_shape[0]) x2 = int(x2 * resized_image_shape[1]) y2 = int(y2 * resized_image_shape[0]) cropped_image = resized_image[y1:y2, x1:x2] cropped_bb = transform_bb_after_cropping( bb, crop_bb[0], resized_image.shape, cropped_image.shape) resized_cropped_image, resized_cropped_bb = resize_image( cropped_image, desired_size=desired_size, allignment="left") transformed_line_bb = transform_bb_after_resize( cropped_bb, resized_cropped_bb, cropped_image.shape, resized_cropped_image.shape) return resized_cropped_image, transformed_line_bb, texts[0] def _read_annotations(self, annotation_path, output_type): ''' Given an annotation path ''' annotations = [] with open(annotation_path, "r") as w: lines = w.readlines() for line in lines: if len(line) <= 1: continue annotation_dict = json.loads(line) #json.loads(line[:-1]) if output_type == "line": line_annotations = self._read_line_annotation(annotation_dict) for line_annotation in line_annotations: annotations.append(line_annotation) elif output_type == "word": word_annotations = self._read_word_annotations(annotation_dict) for word_annotation in word_annotations: annotations.append(word_annotation) elif output_type == "page": annotation = self._read_page_annotation(annotation_dict) annotations.append(annotation) return annotations def _read_line_annotation(self, annotation_dict): ''' Extract the relevant information from the annotation (dict) of the output.manifest. Then convert the bb into lines Parameter: ---------- annotation_dict: {} line from the output.manifest Return: ------- line_annotations: [{[]}] formatted information. Note that bbs are converted from polygons to rectangles. ''' page_annotation = self._read_page_annotation(annotation_dict) line_annotation_dict = {} for annotation in page_annotation['annotation']: line_num = annotation['line_num'] if line_num not in line_annotation_dict: line_annotation_dict[line_num] = [] line_annotation_dict[line_num].append(annotation) line_annotations = [] # Sort annotation by line for line_num in line_annotation_dict: tmp = line_annotation_dict[line_num] bb_list = [a['bb'] for a in tmp] texts = [a['text'] for a in tmp] bb_list, texts = self._sort_texts_on_bb_x(bb_list, texts) bb = self._convert_bb_list_to_max_bb(bb_list) line_annotations.append({ "filename": page_annotation["filename"], "annotation": [{ "text": texts, "line_bb": bb, "bb": bb_list }] }) return line_annotations def _read_word_annotations(self, annotation_dict): ''' Extract the relevant information from the annotation (dict) of the output.manifest. Then convert the bb into words Parameter: ---------- annotation_dict: {} line from the output.manifest Return: ------- word_annotations: [{[]}] formatted information. Note that bbs are converted from polygons to rectangles. ''' page_annotation = self._read_page_annotation(annotation_dict) word_annotations = [] for annotation in page_annotation["annotation"]: word_annotations.append({ "filename": page_annotation["filename"], "annotation": [{ "text": annotation["text"], "bb": annotation['bb'] }] }) return word_annotations def _read_page_annotation(self, annotation_dict): ''' Extract the relevant information from the annotation (dict) of the output.manifest. Parameter: ---------- annotation_dict: {} line from the output.manifest Return: ------- out: {[]} formatted information. Note that bbs are converted from polygons to rectangles. ''' filename = os.path.basename(annotation_dict["source-ref"]) out = {"filename": filename} annotation_list = [] for annotation in annotation_dict["annotations"]["texts"]: tmp = annotation tmp["bb"] = self._convert_polygon_to_rects(annotation["bb"]) annotation_list.append(tmp) out["annotation"] = annotation_list return out def _sort_texts_on_bb_x(self, bb_list, texts): # Sort positions of texts based on the x position of bb_lists assert len(bb_list) == len(texts), "No. bb_list are not identical to No. texts" bb_x = [a[0] for a in bb_list] sorted_bb_x = np.argsort(bb_x) return np.array(bb_list)[sorted_bb_x].tolist(), np.array(texts)[sorted_bb_x].tolist(), def _convert_polygon_to_rects(self, polygon_bb): assert len(polygon_bb)==4, "your bounding box should only have 4 coords" x_sorted = sorted(polygon_bb, key=lambda i: i['x']) x_max, x_min = x_sorted[-1]['x'], x_sorted[0]['x'] y_sorted = sorted(polygon_bb, key=lambda i: i['y']) y_max, y_min = y_sorted[-1]['y'], y_sorted[0]['y'] return (x_min, y_min, x_max, y_max) def _convert_bb_list_to_max_bb(self, bb_list): ''' Helper function to convert a list of bbs into one bb that encompasses all the bbs. BBs are in the form (x1, y1, x2, y2) ''' max_x = np.max([a[2] for a in bb_list]) min_x = np.min([a[0] for a in bb_list]) max_y = np.max([a[3] for a in bb_list]) min_y = np.min([a[1] for a in bb_list]) return (min_x, min_y, max_x, max_y) def _normalise_bb(self, bbs, image_size): ''' Normalise bbs from absolute lengths to percentages ''' bbs[:, 0] = bbs[:, 0]/image_size[1] bbs[:, 1] = bbs[:, 1]/image_size[0] bbs[:, 2] = bbs[:, 2]/image_size[1] bbs[:, 3] = bbs[:, 3]/image_size[0] return bbs
python
17
0.552649
108
38.929368
269
starcoderdata
# Copyright 2020 Soil, Inc. # Utility functions for the vSphere API # See com.vmware.apputils.vim25.ServiceUtil in the java API. from pyVmomi import vim, vmodl def build_full_traversal(): """ Builds a traversal spec that will recurse through all objects .. or at least I think it does. additions welcome. See com.vmware.apputils.vim25.ServiceUtil.buildFullTraversal in the java API. Extended bu examples from pysphere to reach networks and datastores. """
python
5
0.734818
76
29.9375
16
starcoderdata
// // filters_1.h // JLSpeexKit // // Created by DFung on 2018/1/30. // Copyright © 2018年 DFung. All rights reserved. // #ifndef filters_1_h #define filters_1_h #include "arch_1.h" jl_spx_word16_t compute_rms_1(const jl_spx_sig_t *x, int len); jl_spx_word16_t compute_rms16_1(const jl_spx_word16_t *x, int len); void signal_mul_1(const jl_spx_sig_t *x, jl_spx_sig_t *y, jl_spx_word32_t scale, int len); void signal_div_1(const jl_spx_word16_t *x, jl_spx_word16_t *y, jl_spx_word32_t scale, int len); #ifdef JL_FIXED_POINT int normalize16_1(const jl_spx_sig_t *x, jl_spx_word16_t *y, jl_spx_sig_t max_scale, int len); #endif #define JL_HIGHPASS_NARROWBAND 0 #define JL_HIGHPASS_WIDEBAND 2 #define JL_HIGHPASS_INPUT 0 #define JL_HIGHPASS_OUTPUT 1 #define JL_HIGHPASS_IRS 4 void highpass_1(const jl_spx_word16_t *x, jl_spx_word16_t *y, int len, int filtID, jl_spx_mem_t *mem); void qmf_decomp_1(const jl_spx_word16_t *xx, const jl_spx_word16_t *aa, jl_spx_word16_t *, jl_spx_word16_t *y2, int N, int M, jl_spx_word16_t *mem, unsigned char *stack); void qmf_synth_1(const jl_spx_word16_t *x1, const jl_spx_word16_t *x2, const jl_spx_word16_t *a, jl_spx_word16_t *y, int N, int M, jl_spx_word16_t *mem1, jl_spx_word16_t *mem2, char *stack); void filter_mem16_1(const jl_spx_word16_t *x, const jl_spx_coef_t *num, const jl_spx_coef_t *den, jl_spx_word16_t *y, int N, int ord, jl_spx_mem_t *mem, char *stack); void iir_mem16_1(const jl_spx_word16_t *x, const jl_spx_coef_t *den, jl_spx_word16_t *y, int N, int ord, jl_spx_mem_t *mem, char *stack); void fir_mem16_1(const jl_spx_word16_t *x, const jl_spx_coef_t *num, jl_spx_word16_t *y, int N, int ord, jl_spx_mem_t *mem, char *stack); /* Apply bandwidth expansion on LPC coef */ void bw_lpc_1(jl_spx_word16_t , const jl_spx_coef_t *lpc_in, jl_spx_coef_t *lpc_out, int order); void sanitize_values32_1(jl_spx_word32_t *vec, jl_spx_word32_t min_val, jl_spx_word32_t max_val, int len); void syn_percep_zero16_1(const jl_spx_word16_t *xx, const jl_spx_coef_t *ak, const jl_spx_coef_t *awk1, const jl_spx_coef_t *awk2, jl_spx_word16_t *y, int N, int ord, char *stack,unsigned char *tmpptr); void residue_percep_zero16_1(const jl_spx_word16_t *xx, const jl_spx_coef_t *ak, const jl_spx_coef_t *awk1, const jl_spx_coef_t *awk2, jl_spx_word16_t *y, int N, int ord, char *stack); void compute_impulse_response_1(const jl_spx_coef_t *ak, const jl_spx_coef_t *awk1, const jl_spx_coef_t *awk2, jl_spx_word16_t *y, int N, int ord, char *stack,unsigned char *tmpptr); void multicomb_1( jl_spx_word16_t *exc, /*decoded excitation*/ jl_spx_word16_t *new_exc, /*enhanced excitation*/ jl_spx_coef_t *ak, /*LPC filter coefs*/ int p, /*LPC order*/ int nsf, /*sub-frame size*/ int pitch, /*pitch period*/ int max_pitch, /*pitch gain (3-tap)*/ jl_spx_word16_t comb_gain, /*gain of comb filter*/ char *stack, unsigned char *tmpptr ); #endif
c
8
0.645859
202
47.30303
66
starcoderdata
const router = require('express').Router() const {Favorite, User} = require('../../db/models') module.exports = router router.get('/:userId', async (req, res, next) => { try { const user = await User.findOne({ where: { id: req.params.userId }, include: [{model: Favorite}] }) res.send(user.favorites) } catch (error) { next(error) } }) router.post('/', async (req, res, next) => { try { const {url, userId} = req.body const user = await User.findOne({ where: { id: userId }, include: [{model: Favorite}] }) const urlId = await Favorite.findOne({ where: { website: url }, attribute: ['id'] }) await user.addFavorite(urlId) res.send(urlId) } catch (error) { next(error) } }) router.delete('/', async (req, res, next) => { try { const {userId} = req.body const user = await User.findOne({ where: { id: userId }, include: [{model: Favorite}] }) await user.removeFavorite(req.body.site) res.send() } catch (error) { next(error) } })
javascript
19
0.535809
51
17.540984
61
starcoderdata
std::string Partitioner::recommended_topology(const std::vector<const Node *> &inputs, const std::string &topo_name) const { // Meshes: // Uniform // Rectilinear // Structured // Unstructured // - Single Shape // - Multiple Shape // - Poly // Coordsets: // Uniform // Rectilinear // Explicit // Topologies: // Points // Uniform // Rectilinear // Structured // Unstructured // Redefine these here because the order matters static const std::array<std::string, 3> coordset_types = { "uniform", "rectilinear", "explicit" }; static const std::array<std::string, 5> topology_types = { "points", "uniform", "rectilinear", "structured", "unstructured" }; index_t worst_coordset = 0; index_t worst_topology = 0; for(const Node *input : inputs) { const Node *n_topo = input->fetch_ptr("topologies/"+topo_name); if(!n_topo) { CONDUIT_ERROR("Unable to combine inputs, topology \"" << topo_name << "\" is not present in all inputs"); } const std::string cset_name = n_topo->child("coordset").as_string(); const Node *n_cset = input->fetch_ptr("coordsets/"+cset_name); if(!n_cset) { CONDUIT_ERROR("Unable to combine inputs, coordset \"" << cset_name << " is not present in all inputs."); } // Get coordset type index { const std::string cset_type = n_cset->child("type").as_string(); const index_t idx = std::find(coordset_types.begin(), coordset_types.end(), cset_type) - coordset_types.begin(); worst_coordset = std::max(worst_coordset, idx); } // Get topology type index { const std::string topo_type = n_topo->child("type").as_string(); const index_t idx = std::find(topology_types.begin(), topology_types.end(), topo_type) - topology_types.begin(); worst_topology = std::max(worst_topology, idx); } } std::string retval; if(worst_topology < 2 && worst_coordset < 1) { retval = "uniform"; } else if(worst_topology < 3 && worst_coordset < 2) { retval = "rectilinear"; } else if(worst_topology < 4) { retval = "structured"; } else { retval = "unstructured"; } return retval; }
c++
13
0.527507
81
26.276596
94
inline
// Copyright (c) 2007-2012 // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #if !defined(HPX_LCOS_LOCAL_CONDITIONAL_TRIGGER_SEP_09_2012_1256PM) #define HPX_LCOS_LOCAL_CONDITIONAL_TRIGGER_SEP_09_2012_1256PM #include #include #include #include namespace hpx { namespace lcos { namespace local { /////////////////////////////////////////////////////////////////////////// struct conditional_trigger { private: BOOST_MOVABLE_BUT_NOT_COPYABLE(conditional_trigger) public: conditional_trigger() { } conditional_trigger(BOOST_RV_REF(conditional_trigger) rhs) : cond_(boost::move(rhs.cond_)) { } conditional_trigger& operator=(BOOST_RV_REF(conditional_trigger) rhs) { if (this != &rhs) { promise_ = boost::move(rhs.promise_); cond_ = boost::move(rhs.cond_); } return *this; } /// \brief get a future allowing to wait for the trigger to fire future get_future(HPX_STD_FUNCTION const& func, error_code& ec = hpx::throws) { cond_ = func; future f = promise_.get_future(ec); set(ec); // trigger as soon as possible return f; } void reset() { cond_.clear(); } /// \brief Trigger this object. bool set(error_code& ec = throws) { if (promise_.is_ready()) { // segment already filled, logic error HPX_THROWS_IF(ec, bad_parameter, "conditional_trigger::set", "input with the given index has already been triggered"); return false; } if (&ec != &throws) ec = make_success_code(); // trigger this object if (cond_ && cond_()) { promise_.set_value(); // fire event promise_ = promise return true; } return false; } private: lcos::local::promise promise_; HPX_STD_FUNCTION cond_; }; }}} #endif
c++
20
0.501015
80
25.771739
92
starcoderdata
from enum import Enum from fantasyopt.player import Player class Site(Enum): YAHOO = 'Yahoo' class Yahoo: """ NFL """ NFL_POSITIONS = { 'QB': 1, 'RB': 2, 'WR': 3, 'TE': 1, 'DEF': 1 } NFL_BUDGET = 200 NFL_FLEX_POSITIONS = {'FLEX': ({'RB', 'WR', 'TE'}, 1)} NFL_PLAYER_IGNORE_CONDITIONS = [ (Player.INJURY_STATUS, 'O'), (Player.INJURY_STATUS, 'IR'), (Player.INJURY_STATUS, 'D') ] NFL_UTILITY_POSITIONS = 0 """ NBA """ NBA_POSITIONS = { 'PG': 1, 'SG': 1, 'SF': 1, 'PF': 1, 'C': 1 } NBA_BUDGET = 200 NBA_FLEX_POSITIONS = { 'G': ({'PG', 'SG'}, 1), 'F': ({'SF', 'PF'}, 1) } NBA_PLAYER_IGNORE_CONDITIONS = [ (Player.INJURY_STATUS, 'O'), (Player.INJURY_STATUS, 'INJ'), (Player.INJURY_STATUS, 'OFS') ] NBA_UTILITY_POSITIONS = 1
python
10
0.458511
58
19.434783
46
starcoderdata
<?php namespace App\Repositories\Eloquent; use App\Models\Project; class ProjectRepository { protected $model; public function __construct(Project $model) { $this->model = $model; } public function getAll() { return $this->model->query(); } public function delete($id) { return $this->model->find($id)->delete(); } public function find($id) { return $this->model->find($id); } public function save($request) { return $this->model->updateOrCreate( ['id' => $request['id']], [ 'user_id' => $request['user_id'], 'client_id' => $request['client_id'], 'city_id' => $request['city_id'], 'state_id' => $request['state_id'], 'step_id' => $request['step_id'], 'title' => $request['title'], 'description' => $request['description'], 'cep' => $request['cep'], 'address' => $request['address'], 'number' => $request['number'], 'neighborhood' => $request['neighborhood'], 'value' => $request['value'], 'find_us_id' => $request['find_us_id'], 'comment_1' => $request['comment_1'], 'comment_2' => $request['comment_2'], 'comment_3' => $request['comment_3'], 'comment_4' => $request['comment_4'], 'comment_5' => $request['comment_5'], 'comment_6' => $request['comment_6'] ] ); } }
php
13
0.461538
59
26.733333
60
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 edu.hku.sdb.driver; import edu.hku.sdb.catalog.MetaStore; import edu.hku.sdb.conf.ConnectionConf; import edu.hku.sdb.conf.MetadbConf; import edu.hku.sdb.conf.SdbConf; import edu.hku.sdb.connect.Connection; import edu.hku.sdb.connect.ConnectionService; import edu.hku.sdb.connect.SdbConnection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jdo.JDOHelper; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import java.io.Serializable; import java.net.MalformedURLException; import java.rmi.Naming; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.Properties; public class ConnectionPool extends UnicastRemoteObject implements ConnectionService, Serializable { private static final Logger LOG = LoggerFactory.getLogger(ConnectionPool.class); /** * Default serialversion ID */ private static final long serialVersionUID = 1L; private static final String SERVICE_NAME = "Connection"; private static String serviceUrl; private Integer maxConnectionNumber; private Integer availableConnectionNumber; private SdbConf sdbConf; private SdbConnection sdbConnection; private MetaStore metaStore; /** * @throws RemoteException */ protected ConnectionPool() throws RemoteException { super(); } public ConnectionPool(SdbConf sdbConf) throws RemoteException { super(0); setSDBConf(sdbConf); setAvailableConnectionNumber(sdbConf.getConnectionConf() .getMaxConnection()); LOG.info("Connecting to metastore DB"); metaStore = new MetaStore(getPersistManager(sdbConf.getMetadbConf())); } private void createConnection() { try { ConnectionConf connectionConf = sdbConf.getConnectionConf(); sdbConnection = new SdbConnection(sdbConf, metaStore); serviceUrl = connectionConf.getSdbAddress() + ":" + connectionConf.getSdbPort() + "/" + SERVICE_NAME; Naming.rebind(serviceUrl, sdbConnection); } catch (RemoteException | MalformedURLException e) { e.printStackTrace(); } } /* * (non-Javadoc) * * @see ConnectionService#getConnection() */ public Connection getConnection() { Connection connection = null; //TODO enable multiple connection synchronized (this) { if (availableConnectionNumber > 0) { if (sdbConnection == null) { createConnection(); } try { connection = (Connection) Naming.lookup(serviceUrl); } catch (NotBoundException | MalformedURLException | RemoteException e) { e.printStackTrace(); } availableConnectionNumber--; return connection; } else return null; } } /* * (non-Javadoc) * * @see ConnectionService#closeConnection() */ public void closeConnection() { // TODO Auto-generated method stub } public Integer getMaxConnectionNumber() { return maxConnectionNumber; } public void setMaxConnectionNumber(Integer maxConnectionNumber) { this.maxConnectionNumber = maxConnectionNumber; } public Integer getAvailableConnectionNumber() { return availableConnectionNumber; } private void setAvailableConnectionNumber(Integer availableConnectionNumber) { this.availableConnectionNumber = availableConnectionNumber; } public SdbConf getSDBConf() { return sdbConf; } public void setSDBConf(SdbConf sdbConf) { this.sdbConf = sdbConf; } private PersistenceManager getPersistManager(MetadbConf metadbConf) { //TODO: get params from dbConf String driver = metadbConf.getJdbcDriverName(); LOG.info("Connecting to Metastore with driver: " + driver); Properties properties = new Properties(); properties.setProperty("javax.jdo.option.ConnectionURL", "jdbc:derby:metastore_db;create=true"); properties.setProperty("javax.jdo.option.ConnectionDriverName", driver); properties.setProperty("javax.jdo.option.ConnectionUserName", ""); properties.setProperty("javax.jdo.option.ConnectionPassword", ""); properties.setProperty("datanucleus.schema.autoCreateSchema", "true"); properties.setProperty("datanucleus.schema.autoCreateTables", "true"); properties.setProperty("datanucleus.schema.validateTables", "false"); properties.setProperty("datanucleus.schema.validateConstraints", "false"); PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory(properties); PersistenceManager pm = pmf.getPersistenceManager(); return pm; } }
java
16
0.730812
87
30.882353
170
starcoderdata
def browser(db_session, request, setup_app): """returns an instance of `zope.testbrowser`. The `kotti.testing.user` pytest marker (or `pytest.mark.user`) can be used to pre-authenticate the browser with the given login name: `@user('admin')`. """ from zope.testbrowser.wsgi import Browser from kotti.testing import BASE_URL host, port = BASE_URL.split(":")[-2:] browser = Browser("http://{}:{}/".format(host[2:], int(port)), wsgi_app=setup_app) marker = request.node.get_closest_marker("user") if marker: # set auth cookie directly on the browser instance... from pyramid.security import remember from pyramid.testing import DummyRequest login = marker.args[0] environ = dict(HTTP_HOST=host[2:]) for _, value in remember(DummyRequest(environ=environ), login): cookie, _ = value.split(";", 1) name, value = cookie.split("=") if name in browser.cookies: del browser.cookies[name] browser.cookies.create(name, value.strip('"'), path="/") return browser
python
13
0.625451
86
43.36
25
inline
package org.aries.task; public interface TaskExecutor { public void setMethodName(String methodName); //public void setCorrelationId(String correlationId); public void addParameter(String parameterValue); public void addParameter(Number parameterValue); public void addParameter(Boolean parameterValue); public void addParameter(Object parameterValue); public void setReturnType(Class returnType); public void execute() throws Exception; }
java
9
0.794549
54
19.73913
23
starcoderdata
package numbers.rationals.integers.naturals; import numbers.rationals.integers.naturals.java.JavaNatural; import numbers.rationals.integers.naturals.peano.*; import algebra.*; import order.*; public abstract class NaturalNumber implements CommutativeSemiring StrictLinearOrder { // bootstrapping the natural numbers with the neutral elements public static final AdditiveMonoid ZER = new Zero(); // new JavaNatural(0); public static final MultiplicativeMonoid ONE = new Succ((NaturalNumber)ZER); // new JavaNatural(1); public static final CommutativeSemiring TWO = ((CommutativeSemiring public final AdditiveMonoid getZero () { return ZER; } public final MultiplicativeMonoid getOne () { return ONE; } public abstract boolean eq (final DiscreteOrder that) ; // could be defined in the final subclasses public final boolean isZero () { return this.eq((NaturalNumber)getZero()); } public final boolean isOne () { return this.eq((NaturalNumber)getOne()); } // not needed with pattern-matching (Java lacks it :-( public abstract NaturalNumber getPred () ; public final boolean leq (final LinearOrder that) { if (this.isZero()) return true; if (((NaturalNumber)that).isZero()) return false; return this.getPred().leq(((NaturalNumber)that).getPred()); } public abstract AdditiveSemigroup plus ( final AdditiveSemigroup that) ; // helper "plus", 'next' of type PeanoNatural or JavaNatural public final AdditiveSemigroup plus ( final AdditiveSemigroup that, final AdditiveSemigroup next) { if (this.isZero()) return that; if (((NaturalNumber)that).isZero()) return this; return next.plus(((NaturalNumber)that).getPred()); } // adaptor "times" public final MultiplicativeSemigroup times ( final MultiplicativeSemigroup that) { return (CommutativeSemiring (((AdditiveMonoid (NaturalNumber)that)); } public final MultiplicativeSemigroup doubled () { return this.times((MultiplicativeSemigroup } public final MultiplicativeMonoid squared () { return (MultiplicativeMonoid } public final NaturalNumber pow(final int n) { return (NaturalNumber)pow(new JavaNatural(n)); } public abstract int hashCode () ; public final int toDecimal () { return hashCode(); } public final String toString () { return Integer.toString(toDecimal()); } }
java
13
0.655927
109
42.794521
73
starcoderdata
def setUp(self): """Sets up gtf file and creates dictionaries for tests""" self.base_dir = os.path.join(neoepiscope_dir, "tests") self.gtf = os.path.join(self.base_dir, "Ychrom.gtf") self.gtf2 = os.path.join(self.base_dir, "Chr11.gtf") self.Ycds = gtf_to_cds(self.gtf, "NA", pickle_it=False) self.Ytree = cds_to_tree(self.Ycds, "NA", pickle_it=False) self.cds11 = gtf_to_cds(self.gtf2, "NA", pickle_it=False) self.tree11 = cds_to_tree(self.cds11, "NA", pickle_it=False)
python
8
0.621013
68
58.333333
9
inline
import copy from typing import Set, Tuple import numpy as np from ..solution import Solution def fold(grid: Set[Tuple[str, int]], axis: str, val: int) -> Set[Tuple[str, int]]: new_grid = set() if axis == "x": for x, y in grid: if x > val: # 656 over 655 -> 654 = 655 - (656 - 655) new_grid.add((val - (x - val), y)) elif x == val: # These seem to just get dropped in the examples pass else: # These stay put new_grid.add((x, y)) else: for x, y in grid: if y > val: # 656 over 655 -> 654 = 655 - (656 - 655) new_grid.add((x, val - (y - val))) elif x == val: # These seem to just get dropped in the examples pass else: # These stay put new_grid.add((x, y)) return new_grid class Day13(Solution, day=13): def parse(self): grid = [] folds = [] parsing_grid = True with open(self.input_file, "rt") as infile: for line in infile: line = line.strip() if not line: parsing_grid = False continue if parsing_grid: left, right = map(int, line.split(",")) grid.append((left, right)) else: _, _, instruction = line.split(" ") axis, val = instruction.split("=") val = int(val) folds.append((axis, val)) return { "grid": set(grid), "folds": folds, } def part1(self): # So the prompt gives an example where all the folds are exactly _halfway_ # across the paper, so a 2d gride fold is very easy. However, in the actual # input, the paper has an even, not an odd, width, and so the fold number # cannot be the median. As such, we just do a literal reflection grid = copy.copy(self.data["grid"]) folds = self.data["folds"] axis, val = folds[0] return len(fold(grid, axis, val)) def part2(self): grid = copy.copy(self.data["grid"]) folds = self.data["folds"] for axis, val in folds: grid = fold(grid, axis, val) max_x = max(x for x, _ in grid) max_y = max(y for _, y in grid) np_grid = np.zeros((max_x + 1, max_y + 1), dtype=bool) for x, y in grid: np_grid[x, y] = True return "\n" + "\n".join( "".join("#" if val else " " for val in row) for row in np_grid.T )
python
18
0.466788
83
30.666667
87
starcoderdata
package command import ( "encoding/json" "fmt" "net/http" "github.com/nlopes/slack" "github.com/wr46/slack-bot-server/logger" ) // Arguments constants const jokeResponse = "response" const jokeCategories = "categories" // Command documentation constants const jokeSyntax = "`joke { " + jokeCategories + " | }`" const jokeRegexpStr = "joke\\s+(?P<" + jokeResponse + ">[a-z]+)\\s*$" type jokeCmd struct { cmd command } // COMMAND TEMPLATE // Name - The name of the command // Syntax - The command as it must be typed // Description - A small description of the command objective // RegexValidation - Regex used to capture the command string and arguments // Instance - The instance will call itself to use is interface method var jokeDoc = commandDoc{ name: "_joke_", syntax: jokeSyntax, description: "-- give a random joke by category", regexValidation: jokeRegexpStr, instance: jokeCmd{}, } // Template for commands presentation const msgHeadFormat = "*Commands list:* \n" func (cmd jokeCmd) Run(user *slack.User) string { if !cmd.isValid() { return cmd.cmd.errorMsg } response, _ := cmd.cmd.args["response"] if response == jokeCategories { msg := buildJokeHelpMsg() return msg } return buildJokeMsg(response) } func (cmd jokeCmd) buildCommand(args map[string]string) Executable { logger.Log(logger.Debug, fmt.Sprintf("Command joke arguments: %s", args)) return jokeCmd{cmd: command{args: args, doc: jokeDoc, errorMsg: applyJokeRules(args)}} } func (cmd jokeCmd) isValid() bool { return isValid } // Gives a message with all commands and options by template // TODO: improve request parsing and validation func buildJokeMsg(category string) string { resp, err := http.Get("https://api.jokes.one/jod?category=" + category) if err != nil { return errorMsg + "Oops... there was a problem in the request. Is a valid category?" } var result map[string]interface{} json.NewDecoder(resp.Body).Decode(&result) contents, ok := result["contents"].(map[string]interface{}) if !ok { return errorMsg + "Oops... Bad response!" } jokes, ok := contents["jokes"].([]interface{}) if !ok { return errorMsg + "Oops... Bad response!" } joke := jokes[0].(map[string]interface{}) if !ok { return errorMsg + "Oops... Bad response!" } text:= joke["joke"].(map[string]interface{}) return text["text"].(string) + "\n :rolling_on_the_floor_laughing:" } // TODO: improve request parsing and validation func buildJokeHelpMsg() string { resp, err := http.Get("https://api.jokes.one/jod/categories") if err != nil { return errorMsg + "Oops... there was a problem in the request" } var result map[string]interface{} json.NewDecoder(resp.Body).Decode(&result) contents, ok := result["contents"].(map[string]interface{}) if !ok { return errorMsg + "Oops... Bad response, missing 'contents'!" } categories, ok := contents["categories"].([]interface{}) if !ok { return errorMsg + "Oops... Bad response, missing 'categories'!" } var text string = "*Categories:* \n" for _, cat := range categories { m := cat.(map[string]interface{}) name := m["name"].(string) description := m["description"].(string) text = text + "`" + name + "` - " + description + "\n" } return text } // Command rules // - Arguments are required // - Value must be a command or a category func applyJokeRules(args map[string]string) string { // Validate missing arguments if args == nil { return errorMsg + noArgsMsg } response, hasStr := args["response"] if !hasStr || response == "" { return errorMsg + "There is some problem in regex!" } isValid = true return "" }
go
15
0.678844
87
23.624161
149
starcoderdata
/* * JavaSMT is an API wrapper for a collection of SMT solvers. * This file is part of JavaSMT. * * Copyright (C) 2007-2016 * 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 org.sosy_lab.java_smt.api; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import java.math.BigInteger; import java.util.Collection; import java.util.Iterator; import java.util.Objects; import org.checkerframework.checker.nullness.qual.Nullable; import org.sosy_lab.common.rationals.Rational; import org.sosy_lab.java_smt.api.Model.ValueAssignment; import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula; import org.sosy_lab.java_smt.api.NumeralFormula.RationalFormula; /** A model returned from the satisfiable solver environment. */ public interface Model extends Iterable AutoCloseable { /** * Evaluate a given formula substituting the values from the model and return it as formula. * * a value is not relevant to the satisfiability result, the solver can choose either to * insert an arbitrary value (e.g., the value for the matching type) or just return * * * formula does not need to be a variable, we also allow complex expression. The solver * will replace all symbols from the formula with their model values and then simplify the formula * into a simple formula, e.g., consisting only of a numeral expression. * * @param formula Input formula to be evaluated. * @return evaluation of the given formula or if the solver does not provide a * better evaluation. */ @Nullable <T extends Formula> T eval(T formula); /** * Evaluate a given formula substituting the values from the model. * * a value is not relevant to the satisfiability result, the model can choose either an * arbitrary value (e.g., the value for the matching type) or just return * null * * formula does not need to be a variable, we also allow complex expression. * * @param f Input formula * @return Either of: - Number (Rational/Double/BigInteger/Long/Integer) - Boolean * @throws IllegalArgumentException if a formula has unexpected type, e.g Array. */ @Nullable Object evaluate(Formula f); /** * Type-safe evaluation for integer formulas. * * formula does not need to be a variable, we also allow complex expression. */ @Nullable BigInteger evaluate(IntegerFormula f); /** * Type-safe evaluation for rational formulas. * * formula does not need to be a variable, we also allow complex expression. */ @Nullable Rational evaluate(RationalFormula f); /** * Type-safe evaluation for boolean formulas. * * formula does not need to be a variable, we also allow complex expression. */ @Nullable Boolean evaluate(BooleanFormula f); /** * Type-safe evaluation for bitvector formulas. * * formula does not need to be a variable, we also allow complex expression. */ @Nullable BigInteger evaluate(BitvectorFormula f); /** * Iterate over all values present in the model. Note that iterating multiple times may be * inefficient for some solvers, it is recommended to use {@link * BasicProverEnvironment#getModelAssignments()} instead in this case. */ @Override default Iterator iterator() { return asList().iterator(); } /** Build a list of assignments that stays valid after closing the model. */ ImmutableList asList(); /** Pretty-printing of the model values. */ @Override String toString(); /** * Free resources associated with this model (existing {@link ValueAssignment} instances stay * valid, but {@link #evaluate(Formula)} etc. and {@link #iterator()} must not be called again). */ @Override void close(); final class ValueAssignment { /** * the key should be of simple formula-type (Boolean/Integer/Rational/BitVector). * * UFs we use the application of the UF with arguments. * * arrays we use the selection-statement with an index. */ private final Formula keyFormula; /** the value should be of simple formula-type (Boolean/Integer/Rational/BitVector). */ private final Formula valueFormula; /** the equality of key and value. */ private final BooleanFormula formula; /** the key should be boolean or numeral (Rational/Double/BigInteger/Long/Integer). */ private final Object value; /** * arguments can have any type. We would prefer numerals (like value), but we also allow * Formulas. * * UFs we use the arguments. * * arrays we use the index of a selection or an empty list for wildcard-selection, if the * whole array is filled with a constant value. In the latter case any additionally given * array-assignment overrides the wildcard-selection for the given index. Example: "arr=0, * arr[2]=3" corresponds to an array {0,0,3,0,...}. */ private final ImmutableList argumentsInterpretation; /** * The name should be a 'useful' identifier for the current assignment. * * UFs we use their name without parameters. * * arrays we use the name without any index. */ private final String name; public ValueAssignment( Formula keyFormula, Formula valueFormula, BooleanFormula formula, String name, Object value, Collection argumentInterpretation) { this.keyFormula = Preconditions.checkNotNull(keyFormula); this.valueFormula = Preconditions.checkNotNull(valueFormula); this.formula = Preconditions.checkNotNull(formula); this.name = Preconditions.checkNotNull(name); this.value = Preconditions.checkNotNull(value); this.argumentsInterpretation = ImmutableList.copyOf(argumentInterpretation); } /** The formula AST which is assigned a given value. */ public Formula getKey() { return keyFormula; } /** The formula AST which is assigned to a given key. */ public Formula getValueAsFormula() { return valueFormula; } /** The formula AST representing the equality of key and value. */ public BooleanFormula getAssignmentAsFormula() { return formula; } /** Variable name for variables, function name for UFs, and array name for arrays. */ public String getName() { return name; } /** Value: see the {@link #evaluate} methods for the possible types. */ public Object getValue() { return value; } /** Interpretation assigned for function arguments. Empty for variables. */ public ImmutableList getArgumentsInterpretation() { return argumentsInterpretation; } public boolean isFunction() { return !argumentsInterpretation.isEmpty(); } public int getArity() { return argumentsInterpretation.size(); } public Object getArgInterpretation(int i) { assert i < getArity(); return argumentsInterpretation.get(i); } @Override public String toString() { StringBuilder sb = new StringBuilder().append(name); if (!argumentsInterpretation.isEmpty()) { sb.append('('); Joiner.on(", ").appendTo(sb, argumentsInterpretation); sb.append(')'); } return sb.append(": ").append(value).toString(); } @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof ValueAssignment)) { return false; } ValueAssignment other = (ValueAssignment) o; // "Key" is purposefully not included in the comparison, // name and arguments should be sufficient. return name.equals(other.name) && value.equals(other.value) && argumentsInterpretation.equals(other.argumentsInterpretation); } @Override public int hashCode() { return Objects.hash(name, argumentsInterpretation, value); } } }
java
14
0.686131
100
32.465649
262
starcoderdata
#include "AcknowledgeBuilder.hpp" Commands::Acknowledge AcknowledgeBuilder::build() const { return _acknowledge; } AcknowledgeBuilder AcknowledgeBuilder::status(const Commands::Status status) { _acknowledge.set_status(status); return *this; } AcknowledgeBuilder AcknowledgeBuilder::additionalInformation(const std::string& additionalInfo) { _acknowledge.set_additional_info(additionalInfo); return *this; }
c++
6
0.772093
95
22.888889
18
starcoderdata
var selectedAttributeValueMap = new Array(); function showAttributeValueGroupOrderDetails( id ) { jQuery.post( 'getAttributeValueGroupOrder.action', { id: id }, function( json ) { setInnerHTML( 'nameField', json.attributeValueGroupOrder.name ); setInnerHTML( 'memberCountField', json.attributeValueGroupOrder.memberCount ); showDetails(); }); } function resetForm() { setFieldValue( "name", "" ); setFieldValue( "attributeValueGroupOrderId", "" ); var availableList = jQuery( '#availableAttributeValues' ); availableList.empty(); var selectedList = jQuery( '#attributeValues' ); selectedList.empty(); } /* * Open Add Attribute Value Group Order */ function openAddAttributeValueGroupOrder() { resetForm(); validator.resetForm(); attributeLib.loadAttributes( "attributeId" ); jQuery( "#attributeValueGroupsForm" ).attr( "action", "addAttributeValueGroupOrder.action" ); dialog.dialog("open"); } /* * Open Update Data Element Order */ function openUpdateAttributeValueGroupOrder( id ) { validator.resetForm(); setFieldValue( "attributeValueGroupOrderId", id ); jQuery.post( 'getAttributeValueGroupOrder.action', { id: id }, function( json ) { var attributeId = json.attributeValueGroupOrder.attributeId; var values = json.attributeValueGroupOrder.attributeValues; var list = jQuery( "#attributeValues" ); list.empty(); selectedAttributeValueMap = []; var items = []; setFieldValue( "name", json.attributeValueGroupOrder.name ); attributeLib.loadAttributes( "attributeId", attributeId ); attributeLib.loadAttributeValuesByAttribute( attributeId, items, "availableAttributeValues", "attributeValues", true ); for ( var i = 0 ; i < values.length ; i++ ) { items.push( new AttributeValue( values[ i ].value ) ); list.append( '<option value="' + values[ i ].value + '">' + values[ i ].value + ' ); } selectedAttributeValueMap[ id + "-" + attributeId ] = items; attributeLib.removeDuplicatedItem( "availableAttributeValues", "attributeValues" ); jQuery( "#attributeValueGroupsForm" ).attr( "action", "updateAttributeValueGroupOrder.action" ); dialog.dialog( "open" ); } ); } function validateAttributeValueGroupOrder( _form ) { var attributeId = getFieldValue( "attributeId" ); if ( attributeId && attributeId != -1 ) { jQuery.postUTF8( "validateAttributeValueGroupOrder.action", { name: getFieldValue( 'name' ), id: getFieldValue( 'attributeValueGroupOrderId' ) }, function( json ) { if ( json.response == "success" ) { if ( hasElements( 'attributeValues' ) ) { selectAllById( 'attributeValues' ); _form.submit(); } else { markInvalid( "attributeValues", i18n_selected_list_empty ); } } else { markInvalid( "name", json.message ); } } ); } else { markInvalid( "attributeId", i18n_verify_attribute ); } } /* * Delete Attribute Value Group Order */ function deleteAttributeValueGroupOrder( id, name ) { removeItem( id, name, i18n_confirm_delete, 'deleteAttributeValueGroupOrder.action', function(){ window.location.reload(); } ); } /* * Update Attribute Value Group Order */ function updateSortAttributeValueGroupOrder() { var groups = document.getElementsByName( 'attributeValueGroupOrder' ); var url = "updateSortAttributeValueGroupOrder.action?"; for ( var i = 0 ; i < groups.length ; i++ ) { url += "groupIds=" + groups.item(i).value + "&"; } url = url.substring( 0, url.length - 1 ); jQuery.postJSON( url, {}, function( json ) { showSuccessMessage( json.message ); }); } function openSortAttributeValue( id ) { window.location = "openSortAttributeValue.action?id="+id; } /* * Update Sorted Attribute Value */ function updateSortedAttributeValue() { moveAllById( 'availableList', 'selectedList' ); selectAllById( 'selectedList' ); document.forms[0].submit(); }
javascript
19
0.703665
127
25.722222
144
starcoderdata
#include #include #include using namespace std; int main(){ float a=0, b=0, c=0, delta=0, x1=0, x2=0; cin >> a >> b >> c; if(a==0){ cout << "Impossivel calcular" << endl; }else{ delta = pow(b,2)-4*a*c; if(delta < 0){ cout << "Impossivel calcular" << endl; }else{ x1 = (-(b)+sqrt(delta))/(2*a); x2 = (-(b)-sqrt(delta))/(2*a); cout << "R1 = " << fixed << setprecision(5) << x1 << endl; cout << "R2 = " << fixed << setprecision(5) << x2 << endl; } } return 0; }
c++
16
0.528428
61
16.588235
34
starcoderdata
angular. module('myApp'). filter('toTimeString', function() { return function(millseconds) { if (millseconds == 'N/A') { return 'N/A'; } var oneSecond = 1000; var oneMinute = oneSecond * 60; var oneHour = oneMinute * 60; var oneDay = oneHour * 24; var seconds = Math.floor((millseconds % oneMinute) / oneSecond); var minutes = Math.floor((millseconds % oneHour) / oneMinute); var hours = Math.floor((millseconds % oneDay) / oneHour); var days = Math.floor(millseconds / oneDay); var timeString = ''; if (days !== 0) { timeString += (days !== 1) ? (days + ' days ') : (days + ' day '); } if (hours !== 0) { timeString += (hours !== 1) ? (hours + ' hours ') : (hours + ' hour '); } if (minutes !== 0) { timeString += (minutes !== 1) ? (minutes + ' minutes ') : (minutes + ' minute '); } if (seconds !== 0 || millseconds < 1000) { timeString += (seconds !== 1) ? (seconds + ' seconds ') : (seconds + ' second '); } return timeString; } });
javascript
17
0.549472
85
22.133333
45
starcoderdata
public static Update incPercent( final String name, final int percent ) { return new Update() { //Avoid the lookupWithDefault, pass the fields. @Override public void doSet( ObjectEditor repo, Object item ) { int value = repo.getInt( item, name ); double dvalue = value; double dprecent = percent / 100.0; dvalue = dvalue + ( dvalue * dprecent ); value = ( int ) dvalue; repo.modify( item, name, value ); } }; }
java
13
0.506087
73
37.4
15
inline
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef mozilla_a11y_EventQueue_h_ #define mozilla_a11y_EventQueue_h_ #include "AccEvent.h" namespace mozilla { namespace a11y { class DocAccessible; /** * Used to organize and coalesce pending events. */ class EventQueue { protected: explicit EventQueue(DocAccessible* aDocument) : mDocument(aDocument) {} /** * Put an accessible event into the queue to process it later. */ bool PushEvent(AccEvent* aEvent); /** * Puts name and/or description change events into the queue, if needed. */ bool PushNameOrDescriptionChange(AccEvent* aOrigEvent); /** * Process events from the queue and fires events. */ void ProcessEventQueue(); private: EventQueue(const EventQueue&) = delete; EventQueue& operator=(const EventQueue&) = delete; // Event queue processing /** * Coalesce redundant events from the queue. */ void CoalesceEvents(); /** * Coalesce events from the same subtree. */ void CoalesceReorderEvents(AccEvent* aTailEvent); /** * Coalesce two selection change events within the same select control. */ void CoalesceSelChangeEvents(AccSelChangeEvent* aTailEvent, AccSelChangeEvent* aThisEvent, uint32_t aThisIndex); protected: /** * The document accessible reference owning this queue. */ DocAccessible* mDocument; /** * Pending events array. Don't make this an AutoTArray; we use * SwapElements() on it. */ nsTArray<RefPtr<AccEvent>> mEvents; // Pending focus event. RefPtr<AccEvent> mFocusEvent; }; } // namespace a11y } // namespace mozilla #endif // mozilla_a11y_EventQueue_h_
c
14
0.674705
79
23.670886
79
research_code
module.exports = { name: 'compete', host: process.env.HOST_MONGODB || '127.0.0.1:27017', opts: { promiseLibrary: global.Promise, useNewUrlParser: true, useCreateIndex: true, }, };
javascript
8
0.673228
54
24.4
10
starcoderdata
<?php namespace DCAT_AP_DONL\Test; use DCAT_AP_DONL\DCATBoolean; use PHPUnit\Framework\TestCase; class DCATBooleanTest extends TestCase { public function testAcceptsTrueValues(): void { $const_bool = new DCATBoolean(DCATBoolean::TRUE); $str_bool = new DCATBoolean('true'); $this->assertTrue($const_bool->validate()->validated()); $this->assertTrue($str_bool->validate()->validated()); } public function testAcceptsFalseValues(): void { $const_bool = new DCATBoolean(DCATBoolean::FALSE); $str_bool = new DCATBoolean('false'); $this->assertTrue($const_bool->validate()->validated()); $this->assertTrue($str_bool->validate()->validated()); } public function testDeclinesNonBooleanValues(): void { $false_bool = new DCATBoolean('False'); $true_bool = new DCATBoolean('True'); $this->assertFalse($false_bool->validate()->validated()); $this->assertFalse($true_bool->validate()->validated()); } }
php
12
0.633205
65
27.777778
36
starcoderdata
def get_manifest(self, test_in_browser=False, sdk=None): " returns manifest dictionary " version = self.get_version_name() if test_in_browser: version = "%s - test" % version name = self.name #if not self.package.is_addon(): # name = "%s-%s" % (name, self.package.id_number) manifest = { 'fullName': self.full_name, 'name': name, 'description': self.get_full_description(), 'author': self.package.author.get_profile().get_nickname(), 'id': self.package.jid if self.package.is_addon() \ else self.package.id_number, 'version': version, 'main': self.module_main, 'dependencies': self.get_dependencies_list(sdk), 'license': self.package.license, 'url': str(self.package.url), 'contributors': self.get_contributors_list(), 'lib': self.get_lib_dir() } return manifest
python
13
0.534449
71
36.666667
27
inline
#include "projections.h" #define _USE_MATH_DEFINES #include #include #define TINYOBJLOADER_IMPLEMENTATION // define this in only *one* .cc #include "tiny_obj_loader.h" cg::ObjParser::ObjParser(std::string filename) : filename(filename) {} cg::ObjParser::~ObjParser() {} void cg::ObjParser::Parse() { tinyobj::attrib_t attrib; std::vector shapes; std::vector materials; std::string warn; std::string err; bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, filename.string().c_str(), filename.parent_path().string().c_str(), true); if (!warn.empty()) { std::cout << warn << std::endl; } if (!err.empty()) { std::cerr << err << std::endl; } if (!ret) { throw std::runtime_error("Failed to parse OBJ file " + filename.string() + " reason: " + err); } // Loop over shapes for (size_t s = 0; s < shapes.size(); s++) { // Loop over faces(polygon) size_t index_offset = 0; for (size_t f = 0; f < shapes[s].mesh.num_face_vertices.size(); f++) { int fv = shapes[s].mesh.num_face_vertices[f]; face current; // Loop over vertices in the face. for (size_t v = 0; v < fv; v++) { // access to vertex tinyobj::index_t idx = shapes[s].mesh.indices[index_offset + v]; tinyobj::real_t vx = attrib.vertices[3 * idx.vertex_index + 0]; tinyobj::real_t vy = attrib.vertices[3 * idx.vertex_index + 1]; tinyobj::real_t vz = attrib.vertices[3 * idx.vertex_index + 2]; current.vertexes[v] = float4(vx, vy, vz, 1.f); } index_offset += fv; faces.push_back(std::move(current)); } } } const std::vector cg::ObjParser::GetFaces() { return faces; } cg::Projections::Projections(uint32_t width, uint32_t height, std::string obj_file) : cg::LineDrawing(width, height), parser{std::make_unique // column-wise buffer{} { buffer.world = { {1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, -1, -3, 1}}; float3 eye{0, 0, 1}; float3 at{0, 0, 0}; float3 up{0, -1, 0}; float3 zaxis = normalize(at - eye); float3 xaxis = normalize(cross(up, zaxis)); float3 yaxis = cross(zaxis, xaxis); buffer.view = float4x4{{xaxis.x, xaxis.y, xaxis.z, -dot(xaxis, eye)}, {yaxis.x, yaxis.y, yaxis.z, -dot(yaxis, eye)}, {zaxis.x, zaxis.y, zaxis.z, -dot(zaxis, eye)}, {0, 0, 0, 1}}; float z_near = 1.0f; float z_far = 10.f; float near_height = 1.f; float near_width = width / (float)height; buffer.projection = float4x4{ {2 * z_near / near_width, 0, 0, 0}, {0, z_near / near_height, 0, 0}, {0, 0, z_far / (z_far - z_near), z_near * z_far / (z_far - z_near)}, {0, 0, 1, 0}}; parser->Parse(); } float4 cg::Projections::applyVertexShader(float4 v) { return linalg::mul(buffer.projection, linalg::mul(buffer.view, linalg::mul(buffer.world, v))); } void cg::Projections::rasterize(face face) { // to screen space uint32_t x_center{width / 2}, y_center{height / 2}; uint32_t scale = std::min(x_center, y_center) - 1; for (uint8_t i = 0; i < 3; i++) { face.vertexes[i] /= face.vertexes[i].w; face.vertexes[i].x = std::clamp(x_center + scale * face.vertexes[i].x, 0.f, width - 1.f); face.vertexes[i].y = std::clamp(y_center + scale * face.vertexes[i].y, 0.f, height - 1.f); } drawTriangle(face); } void cg::Projections::drawTriangle(face face) { DrawLine(face.vertexes[0].x, face.vertexes[0].y, face.vertexes[1].x, face.vertexes[1].y, color{255, 0, 0}); DrawLine(face.vertexes[1].x, face.vertexes[1].y, face.vertexes[2].x, face.vertexes[2].y, color{0, 255, 0}); DrawLine(face.vertexes[2].x, face.vertexes[2].y, face.vertexes[0].x, face.vertexes[0].y, color{0, 0, 255}); } void cg::Projections::DrawScene() { using namespace linalg::ostream_overloads; uint16_t id = 0; for (auto face : parser->GetFaces()) { face.id = id++; for (auto& v : face.vertexes) v = applyVertexShader(v); rasterize(face); } }
c++
16
0.549744
78
29.647887
142
starcoderdata
// Copyright RedPortal, mujjingun 2017 - 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef _MGCPP_TEST_MEMORY_LEAK_DETECTOR_HPP_ #define _MGCPP_TEST_MEMORY_LEAK_DETECTOR_HPP_ #include #include #include #include namespace mgcpp { class memory_leak_detector : public ::testing::EmptyTestEventListener { std::vector device_free_memory; void OnTestStart(::testing::TestInfo const& test_info) override; void OnTestEnd(::testing::TestInfo const& test_info) override; }; } // namespace mgcpp #endif
c++
12
0.724902
71
26.392857
28
starcoderdata
coreRenderTarget final { coreTexturePtr pTexture; // render target texture (readable) GLuint iBuffer; // render target buffer (fast, multisampled) coreTextureSpec oSpec; // texture and buffer specification (format) constexpr coreRenderTarget()noexcept; inline coreBool IsTexture()const {return pTexture ? true : false;} inline coreBool IsBuffer ()const {return iBuffer != 0u;} inline coreBool IsValid ()const {return oSpec.iInternal != 0u;} }
c
8
0.645522
80
47.818182
11
inline
# encoding: utf-8 import ckan.plugins as plugins import ckan.plugins.toolkit as toolkit import logging try: from ckan.common import config # CKAN 2.7 and later except ImportError: from pylons import config # CKAN 2.7 and later log = logging.getLogger(__name__) def dataset_count(): """Return a count of all datasets""" count = 0 result = toolkit.get_action('package_search')({}, {'rows': 1}) if result.get('count'): count = result.get('count') return count def get_hero_images(): resources = [] try: package_id = config.get('ckanext.heroslider.package_id', 'hero-slider-images') result = toolkit.get_action('package_show')({}, {'id': package_id}) resource_list = result.get('resources') for item in resource_list: if item.get('format') in ['JPEG','PNG']: if item.get('url'): resources.append(item.get('url')) except: log.debug('Getting Hero images failed') return resources class HerosliderPlugin(plugins.SingletonPlugin): plugins.implements(plugins.IConfigurer) plugins.implements(plugins.ITemplateHelpers) # IConfigurer def update_config(self, config_): toolkit.add_template_directory(config_, 'templates') toolkit.add_public_directory(config_, 'public') toolkit.add_resource('fanstatic', 'heroslider') # ITemplateHelpers def get_helpers(self): return { 'hero_dataset_count': dataset_count, 'get_hero_images': get_hero_images, }
python
17
0.633525
86
28.603774
53
starcoderdata
describe('CompletionReporter', function() { var CompletionReporter = require('../../lib/reporters/completion_reporter'); beforeEach(function() { this.reporter = new CompletionReporter(); this.onComplete = jasmine.createSpy('onComplete'); this.reporter.onComplete(this.onComplete); }); describe('When the overall status is "passed"', function() { it('calls the completion callback with true', function() { this.reporter.jasmineDone({overallStatus: 'passed'}); expect(this.onComplete).toHaveBeenCalledWith(true); }); }); describe('When the overall status is anything else', function() { it('calls the completion callback with false', function() { this.reporter.jasmineDone({overallStatus: 'incomplete'}); expect(this.onComplete).toHaveBeenCalledWith(false); }); }); });
javascript
20
0.707265
98
38
24
starcoderdata
#include #include static void my_exit1(void), my_exit2(void); /** * 使用atexit注册结束函数 */ int main(){ if(atexit(my_exit2) != 0){ perror("can't register my_exit2\n"); } if(atexit(my_exit1) != 0){ perror("can't register my_Exit1\n"); } printf("main is done\n"); return 0; } static void my_exit1(void){ printf("first exit handler, exit1\n"); } static void my_exit2(void){ printf("seconds exit handler, exit2\n"); }
c
9
0.637168
43
14.066667
30
starcoderdata
using AgToolkit.Core.GameMode; using AgToolkit.Core.Manager; using UnityEngine; namespace AgToolkit.Core.Misc { public class ExitGameStateMachineBehaviour : GameStateMachineBehaviour { public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { GameManager.Instance.ChangeGameMode(Data.NextGameMode); } } }
c#
12
0.806283
99
24.466667
15
starcoderdata
import { Mongo } from 'meteor/mongo'; import { ValidatorRecords } from '../records/records.js'; export const Validators = new Mongo.Collection('validators'); Validators.helpers({ uptimePercent(){ return ((this.uptime/Meteor.settings.public.uptimeWindow)*100).toFixed(2); } }) Validators.helpers({ uptime(){ // console.log(this.address); let lastHundred = ValidatorRecords.find({address:this.address}, {sort:{height:-1}, limit:100}).fetch(); // console.log(lastHundred); let uptime = 0; for (i in lastHundred){ if (lastHundred[i].exists){ uptime+=1; } } return uptime; } })
javascript
14
0.596317
111
27.28
25
starcoderdata
import React from "react" import headerStyles from "./header.module.scss" // import { FaShoppingCart, FaSignInAlt } from 'react-icons/fa' export default () => ( <header className={headerStyles.header}> <img src="/img/logo/Falda_logo_horizontal_black.svg" className={headerStyles.logo} alt="Logo /> {/* <div className={headerStyles.buttons}> <FaShoppingCart /> <FaSignInAlt /> */} )
javascript
9
0.579323
63
23.391304
23
starcoderdata
namespace QSP.TOPerfCalculation { public static class Extensions { public static TOParameters CloneWithOat(this TOParameters p , double oatCelcius) { return new TOParameters( p.RwyLengthMeter, p.RwyElevationFt, p.RwyHeading, p.RwySlopePercent, p.WindHeading, p.WindSpeedKnots, oatCelcius, p.QNH, p.SurfaceWet, p.WeightKg, p.ThrustRating, p.AntiIce, p.PacksOn, p.FlapsIndex); } } }
c#
12
0.463415
88
26.333333
24
starcoderdata
// Versão de processo único do printmensg.c: /* printmsg.c: print a message on the console */ #include #include main(int argc, char *argv[]) { //printf("Message here:\n"); char *message; if (argc != 2) { fprintf(stderr, "usage: %s argv[0]); exit(1); } message = argv[1]; if (!printmessage(message)) // if is 0, false. { fprintf(stderr, "%s: couldn't print your message.\n", argv[0]); exit(1); } printf("Message Delivered!\n"); exit(1); } /* Print a message to the console. * Return a boolean indicating whether * the message was actually printed. */ printmessage(char *msg) { printf("%s\n", msg); return(1); } /*Para uso local em uma única máquina, este programa pode ser compilado e executado da seguinte forma: * If you stay on Windows VS Code, so press the F6 to open a C/C++ run compile. * $ cc printmsg.c -o printmsg * $ ./printmsg "Hello, there." * Message delivered! * $ */ // Se a função de impressão() for transformada em um procedimento remoto,ela pode ser chamada de qualquer lugar da rede. rpcgen torna mais fácil fazer isso:
c
9
0.612245
156
23.541667
48
starcoderdata
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); if( ! function_exists('CallZohoAPI')){ function CallZohoAPI($Method = NULL, $params = array(), $type = "GET"){ if($Method){ $url = "https://crm.zoho.com/crm/private/json/".$Method; $config = array("authtoken" => " "scope" => "crmapi"); $params = array_merge($config, $params); if($type == "POST"){ $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params)); } else { $url = sprintf("%s?%s", $url, http_build_query($params)); $ch = curl_init($url); } curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); if( ($result = curl_exec($ch) ) === false){ //$result = 'NO RESPONSE!'; die('Curl failed ' . curl_error($ch)); } curl_close($ch); return $result; } return false; } }
php
19
0.580982
75
25.583333
36
starcoderdata
using System.Collections; using DG.Tweening; using UnityEngine; using UnityEngine.AI; public class Gentleman : MonoBehaviour { private Animator _animator; private NavMeshAgent _agent; public NavMeshAgent Agent => _agent; [SerializeField] private Transform walkPos, standUpPos; private void Awake() { _animator = GetComponent _agent = GetComponent } private void Update() { _animator.SetFloat("Speed", _agent.velocity.magnitude); } public void StandUp() { _animator.SetTrigger("StandUp"); StartCoroutine(WalkDelay()); } IEnumerator WalkDelay() { transform.DOMove(standUpPos.position, 1f).SetEase(Ease.OutQuad); yield return new WaitForSeconds(1.1f); _agent.enabled = true; _agent.SetDestination(walkPos.position); } }
c#
12
0.649438
72
21.820513
39
starcoderdata
using AutoMapper; using AutoMapper.QueryableExtensions; using BookmarkManager.Application.Dto; using BookmarkManager.Application.Interfaces; using MediatR; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace BookmarkManager.Application.Features { public class GetBookmarksByCategoryIdQueryHanlder : IRequestHandler<GetBookmarksByCategoryIdQuery, IEnumerable { private readonly IApplicationDbContext _dbContext; private readonly IMapper _mapper; public GetBookmarksByCategoryIdQueryHanlder(IApplicationDbContext dbContext, IMapper mapper) { _dbContext = dbContext; _mapper = mapper; } public async Task Handle(GetBookmarksByCategoryIdQuery request, CancellationToken cancellationToken) { return await _dbContext.Bookmarks.Include(b => b.Categories).AsNoTrackingWithIdentityResolution() .Include(b => b.Categories).ThenInclude(x => x.Category) .AsNoTracking() .Where(b => b.Categories.Any(c => c.CategoryId == request.CategoryId)) .ProjectTo } } }
c#
29
0.705767
134
39.157895
38
starcoderdata
<?php /** * Created by PhpStorm. * User: hdkj * Date: 2018/6/9 * Time: 14:39 */ namespace app\run\controller; use app\common\controller\Run; class Type extends Run { public function lists(){ if ($this->request->isAjax()){ $typeModel = new \app\run\model\Type(); $result = $typeModel->getTypeList(input("get.limit"),input("get.page")); $this->layAjax(200,"数据获取成功!",$result['total'],$result['data']); }else{ return $this->fetch(); } } public function created(){ if ($this->request->isAjax()){ }else{ //如果传递了父级id if (!empty(input("get.pid"))){ $map[] = ['id','eq',input("get.pid")]; $model = new MenusRule(); $menus = $model->where($map)->find()->toArray(); $menus['path'] = $menus['path'].input("get.pid").","; $this->assign("menus",$menus); } return $this->fetch(); } } }
php
18
0.480392
84
24.525
40
starcoderdata
public int find(int i) { while(i != father[i]) { father[i] = father[father[i]];//path compression logN i = father[i]; } return i; }
java
9
0.401914
71
29
7
inline
package com.frugalbin.integration.utils; public interface Constants { // Schema static final String INVENTORY_AIRLINE_SCHEMA = "INVENTORY_AIRLINE"; // Table Names static final String AIRPORT_DETAILS_TABLE = "AIRPORT_DETAILS"; static final String CITIES_TABLE = "CITIES"; static final String FLIGHT_DETAILS_TABLE = "FLIGHT_DETAILS"; static final String FLIGHT_SEAT_DETAILS_TABLE = "FLIGHT_SEAT_DETAILS"; static final String BOOKING_DETAILS_TABLE = "BOOKING_DETAILS"; static final String PASSENGER_DETAILS_TABLE = "PASSENGER_DETAILS"; static final String BOOKING_PASSENGER_MAPPER_TABLE = "BOOKING_PASSENGER_MAPPER"; static final String JA_INT_AIRLINE_CONNECTION_DETAILS_TABLE = "JA_INT_AIRLINE_CONNECTION_DETAILS"; static final String QPX_AIRLINE_CONNECTION_DETAILS_TABLE = "QPX_AIRLINE_CONNECTION_DETAILS"; // Table Columns // Columns: Common static final String ID_COLUMN = "ID"; static final String NAME_COLUMN = "NAME"; // Columns: AIRPORT_DETAILS static final String AIRPORT_CITY_ID_COLUMN = "CITY_ID"; static final String AIRPORT_ADDRESS_ID_COLUMN = "ADDRESS_ID"; // Columns: CITIES static final String STATE_COLUMN = "STATE"; // Columns: FLIGHT_DETAILS static final String FD_AIRLINE_ID_COLUMN = "AIRLINE_ID"; static final String FD_FLIGHT_NUMBER_COLUMN = "FLIGHT_NUMBER"; static final String FD_FROM_AIRPORT_COLUMN = "FROM_AIRPORT"; static final String FD_TO_AIRPORT_COLUMN = "TO_AIRPORT"; static final String FD_TOTAL_SEATS_COLUMN = "TOTAL_SEATS"; // Columns: FLIGHT_SEAT_DETAILS static final String FSD_FLIGHT_ID_COLUMN = "FLIGHT_ID"; static final String FSD_DEPARTURE_TIME_COLUMN = "DEPARTURE_TIME"; static final String FSD_ARRIVAL_TIME_COLUMN = "ARRIVAL_TIME"; static final String FSD_AVAILABLE_SEATS_COLUMN = "AVAILABLE_SEATS"; static final String FSD_ALLOTTED_SEATS_COLUMN = "ALLOTED_SEATS"; // Columns: BOOKING_DETAILS static final String BD_AIRLINE_TRANSACTION_ID_COLUMN = "AIRLINE_TRANSACTION_ID"; static final String BD_FLIGHT_SEAT_ID_COLUMN = "FLIGHT_SEAT_ID"; // Columns: PASSENGER_DETAILS static final String PD_FIRST_NAME_COLUMN = "FIRST_NAME"; static final String PD_LAST_NAME_COLUMN = "LAST_NAME"; static final String PD_AGE_COLUMN = "AGE"; static final String PD_GENDER_COLUMN = "GENDER"; // Columns: PASSENDER_BOOKING_MAPPER static final String PBM_BOOKING_ID_COLUMN = "BOOKING_ID"; static final String PBM_PASSENGER_ID_COLUMN = "PASSENGER_ID"; // Columns: AIRLINE_CONNECTION_DETAILS static final String ACD_CONNECTION_URL_COLUMN = "CONNECTION_URL"; static final String ACD_USERNAME_COLUMN = "USERNAME"; static final String ACD_PASSWORD_COLUMN = "PASSWORD"; static final String CONNECTION_TYPE_COLUMN = "CONNECTION_TYPE"; static final String CONNECTION_SERVICE_TYPE_COLUMN = "CONNECTION_SERVICE_TYPE"; static final String SEARCH_JSON_REQUEST_COLUMN = "SEARCH_JSON_REQUEST"; // ERROR Codes static final int TEMPLATE_NOT_FOUND_ERROR_CODE = 1001; // ERROR Messages static final String TEMPLATE_NOT_FOUND_ERROR_MESSAGE = "Template with Id {} not found"; static final String TIMESTAMP_TYPE = "timestamp"; static final long UPDATER_DELAY_PERIOD = 1 * 10 * 1000; static final long UPDATER_PERIOD = 5 * 60 * 1000; }
java
7
0.754599
99
40.115385
78
starcoderdata
package graph; import Algorithms.AlgorithmVisitor; import Algorithms.Utils.Step; import graph.Stockage.StockageType; import java.util.LinkedList; /** * Representation of a graph */ public abstract class Graph { protected LinkedList vertexList = new LinkedList<>(); protected StockageType stockage; protected int E; // number of edges protected int V; // number of vertex /** * Constructor Graph * @param V number of vertex * @param stockage type of stockage to use */ public Graph(int V, StockageType stockage){ this.E = 0; this.stockage = stockage; initList(V); stockage.init(V); } /** * initialise the vertex list * @param V the number of vertex of the graph */ protected void initList(int V) { for (int i = 0; i < V; i++) { vertexList.add(new Vertex(i)); this.V = V; } } /** * Add a vertex to the graph * @param v the vertex to add */ public void addVertex(Vertex v){ vertexList.add(v.getId(), v); V++; } /** * get a Vertex of the graph * @param id the id of the vertex * @return the vertex with correct id */ public Vertex getVertex(int id){ if (id < vertexList.size()) return vertexList.get(id); else return null; } /** * Get the list of vertex of the graph * @return */ public LinkedList getVertexsList(){return vertexList;} /** * Add an edge to the graph * @param e the edge to store */ public void addEdge(Edge e){ stockage.addEdge(e); E++; } /** * Add an edge with 0 weight to the graph * @param v the starting vertex * @param w the ending vertex */ public abstract void addEdge(Vertex v, Vertex w); /** * Add an edge to the graph * @param v the starting vertex * @param w the ending vertex * @param weight the weight of the edge */ public abstract void addEdge(Vertex v, Vertex w, double weight); /** * Get the first edge that start at v and end at w * @param v the starting point of the edge * @param w the ending vertex of the edge * @return the edge find or null */ public Edge getEdge(Vertex v, Vertex w){ return stockage.getEdge(v, w); } /** * Get the list of edge that compose the graph * @return the list of edge that compose the graph */ public LinkedList getEdgesList(){ return stockage.getEdgesList(); } /** * Get the adjacent vertex of v * @param v the vertex to check * @return the adjacent vertex of v */ public LinkedList adjacentVertex(Vertex v){return stockage.adjacentVertex(v);} /** * Get the adjacent edges of v * @param v the vertex to check * @return the adjacent edges of v */ public LinkedList adjacentEdges(Vertex v){return stockage.adjacentEdges(v);} /** * Getter number of vertex of the graph * @return V */ public int V(){ return V; } /** * Getter number of edges of the graph * @return E */ public int E(){ return E; } /** * Apply an algorithme(AlgorithmVisitor) to the current graph * @param v the visitor to apply * @param source the source vertex * @param target the vertex to reach * @return A list of step produce by the algorithm visitor * @throws Exception if the algorithm cant finish his execution */ public abstract LinkedList accept(AlgorithmVisitor v, Vertex source, Vertex target) throws Exception; /** * Display the graph in a string * @return this graph in string */ public String toString(){ String ret = this.getClass() + "nbVertex = " + V + "\n"; for(Vertex v : vertexList){ ret += "Sommet " + v.getId() + " : "; for(Edge e : adjacentEdges(v)) ret += "Edge(v1: " + e.getFrom().getId() + ", v2: " + e.getTo().getId() + ", Weigth : " + e.getWeigth()+"); "; ret += "\n"; } return ret; } }
java
19
0.575587
126
24.818182
165
starcoderdata
// // DoublyLinkedListTemplate.hpp // DoublyLinkedListTemplate // // Taken from CS204 Lab Material. // Edited by on 11.01.2021. // #ifndef DoublyLinkedListTemplate_hpp #define DoublyLinkedListTemplate_hpp #include template <class itemType> struct node { itemType info; node * left; node * right; node () {} node (const itemType & s, node * left, node* right) : info(s), left (left),right(right) { } }; template <class itemType> class DoublyLinkedList { private: node * head,* tail; int size; public: DoublyLinkedList(); DoublyLinkedList(const DoublyLinkedList&); //copy constructor ~DoublyLinkedList(); //destructor void printList() const; void printListReverse() const; void addToBeginning(const itemType& n); void addToEnd(const itemType& n); void deleteList (); const DoublyLinkedList& operator = (const DoublyLinkedList& rhs); std::pair *,node *> createClone () const; //generates the clone of the list and return the clone's head DoublyLinkedList< node * > searchElement(const itemType & elem) const; // returns a linked list of pointers with the desired search value }; #include "DoublyLinkedListTemplate.cpp" #endif /* DoublyLinkedListTemplate_hpp */
c++
13
0.697589
149
24.351852
54
starcoderdata
from fastai.vision import * import model_utils_ext as m_util_x import pretrainedmodels def se_resnext50(pretrained=True): pretrained = 'imagenet' if pretrained else None model = pretrainedmodels.__dict__['se_resnext50_32x4d'](num_classes=1000, pretrained=pretrained) return model class SAI(nn.Module): ''' SelfAttention with Identity ''' def __init__(self, nf): super(SAI, self).__init__() self.sa = PooledSelfAttention2d(nf) self.bn = nn.BatchNorm2d(nf) self.do = nn.Dropout(0.4), def forward(self, x): ident = x out = self.sa(x) out = ident + out out = self.do(self.bn(out)) # return nn.ReLU(out) class HeadBlock(nn.Module): def __init__(self, nf, nc): super(HeadBlock, self).__init__() self.se1 = m_util_x.SEBlock(nf//2) self.head1 = create_head(nf, nc[0]) self.se2 = m_util_x.SEBlock(nf//2) self.head2 = create_head(nf, nc[1]) self.se3 = m_util_x.SEBlock(nf//2) self.head3 = create_head(nf, nc[2]) def forward(self, x): x1 = self.se1(x) x1 = self.head1(x1) x2 = self.se2(x) x2 = self.head2(x2) x3 = self.se3(x) x3 = self.head3(x3) return x1, x2, x3 class HeadBlock0(nn.Module): def __init__(self, nf, nc): super(HeadBlock0, self).__init__() self.head1 = create_head(nf, 1024, bn_final = True) self.at1 = SelfAttention(nf//4) self.rl1 = nn.LeakyReLU(0.1, inplace=True) self.lin1 = nn.Linear(1024, nc[0]) self.head2 = create_head(nf, 1024, bn_final = True) self.at2 = SelfAttention(nf//4) self.rl2 = nn.LeakyReLU(0.1, inplace=True) self.lin2 = nn.Linear(1024, nc[1]) self.head3 = create_head(nf, 1024, bn_final = True) self.at3 = SelfAttention(nf//4) self.rl3 = nn.LeakyReLU(0.1, inplace=True) self.lin3 = nn.Linear(1024, nc[2]) def forward(self, x): x1 = self.head1(x) x1 = self.at1(x1) x1 = self.rl1(x1) x1 = self.lin1(x1) x2 = self.head2(x) x2 = self.at2(x2) x2 = self.rl2(x2) x2 = self.lin2(x2) x3 = self.head3(x) x3 = self.at3(x3) x3 = self.rl3(x3) x3 = self.lin3(x3) return x1, x2, x3 class HeadBlockEff(nn.Module): def __init__(self, nf, nc): super(HeadBlockEff, self).__init__() #self.head1 = create_head(nf, 1024, bn_final = True) self.at1 = SelfAttention(nf) self.rl1 = nn.LeakyReLU(0.1, inplace=True) self.lin1 = nn.Linear(nf, nc[0]) #self.sw1 = MemoryEfficientSwish() #self.head2 = create_head(nf, 1024, bn_final = True) self.at2 = SelfAttention(nf) self.rl2 = nn.LeakyReLU(0.1, inplace=True) self.lin2 = nn.Linear(nf, nc[1]) #self.sw2 = MemoryEfficientSwish() #self.head3 = create_head(nf, 1024, bn_final = True) self.at3 = SelfAttention(nf) self.rl3 = nn.LeakyReLU(0.1, inplace=True) self.lin3 = nn.Linear(nf, nc[2]) #self.sw3 = MemoryEfficientSwish() def forward(self, x): #x1 = self.head1(x) x1 = self.at1(x) x1 = self.rl1(x1) x1 = self.lin1(x1) #x1 = self.sw1(x1) #x2 = self.head2(x) x2 = self.at2(x) x2 = self.rl2(x2) x2 = self.lin2(x2) #x2 = self.sw2(x2) #x3 = self.head3(x) x3 = self.at3(x) x3 = self.rl3(x3) x3 = self.lin3(x3) #x3 = self.sw3(x3) return x1, x2, x3
python
11
0.506747
100
25.865772
149
starcoderdata
public static void main(String[] args) throws IOException { // set up env variable if (System.getenv("RAPIDWRIGHT_PATH") == null) System.setProperty("RAPIDWRIGHT_PATH", System.getProperty("user.home") + "/RapidWright"); else System.setProperty("RAPIDWRIGHT_PATH", System.getenv("RAPIDWRIGHT_PATH")); Scanner input = new Scanner(System.in); System.out.println("Please input device: (e.g. xcvu11p, xcvu13p, xcvu37p, etc.)"); String device = input.next(); // check if device is legal Design checkLegal = new Design("temp", device); int depth; do { System.out.println("Please input pipeline depth: (e.g. 1)"); while (!input.hasNextInt()) { System.out.println("between 1 to 4"); input.next(); // this is important! } depth = input.nextInt(); } while (depth <0 || depth > 4); // default xdc path String xdc = System.getenv("RAPIDWRIGHT_PATH") + "/src/verilog/dsp_conv_chip.xdc"; manual_placement_timing(xdc, depth, device); }
java
11
0.575044
101
36
31
inline
module.exports = { out: '/tmp/project-releaser/project/docs/build/html', exclude: [ '**/node_modules/**', 'test-types.ts' ], name: "LaunchDarkly Server-Side Node SDK (6.2.1)", readme: 'none', // don't add a home page with a copy of README.md entryPoints: "/tmp/project-releaser/project/index.d.ts" };
javascript
7
0.623229
82
31.090909
11
starcoderdata
/* eslint no-param-reassign: ["error", { "props": false }] */ class Sorting { /** * bubble sort * Complexity: Θ(n^2) * Space Complexity: O(1) * @method bubbleSort * @param {Array} array - input array * @return {Array} sorted array */ static bubbleSort(array) { if (!array || !array.length) { return array; } for (let i = 0; i < array.length - 1; i += 1) { for (let j = i + 1; j < array.length; j += 1) { if (array[i] > array[j]) { const temp = array[i]; array[i] = array[j]; array[j] = temp; } } } return array; } /** * selection sort * Complexity: Θ(n^2) * Space Complexity: O(1) * @method selectionSort * @param {Array} array - input array * @return {Array} sorted array */ static selectionSort(array) { if (!array || !array.length) { return array; } let indexMin = 0; for (let i = 0; i < array.length - 1; i += 1) { indexMin = i; for (let j = i; j < array.length; j += 1) { if (array[indexMin] > array[j]) { indexMin = j; } } if (i !== indexMin) { const temp = array[i]; array[i] = array[indexMin]; array[indexMin] = temp; } } return array; } /** * insertion sort * Complexity: Θ(n^2) * Space Complexity: O(1) * @method insertionSort * @param {Array} array - input array * @return {Array} sorted array */ static insertionSort(array) { if (!array || !array.length) { return array; } let temp = 0; let j = 0; for (let i = 1; i < array.length; i += 1) { j = i; temp = array[i]; while (j > 0 && array[j - 1] > temp) { array[j] = array[j - 1]; j -= 1; } array[j] = temp; } return array; } /** * merge sort * Complexity: O(n log n) * Space Complexity: O(n) * @method mergeSort * @param {Array} array - input array * @return {Array} sorted array */ static mergeSort(array) { if (!array || !array.length || array.length === 1) { return array; } const len = array.length; const mid = Math.floor(len / 2); const left = array.slice(0, mid); const right = array.slice(mid, len); return this.merge(this.mergeSort(left), this.mergeSort(right)); } /** * merge two arrays, and return a new shorted array * @method merge * @param {Array} left - first half of the array * @param {Array} right - second half of the array * @return {Array} sorted array */ static merge(left, right) { const result = []; let il = 0; let ir = 0; while (il < left.length && ir < right.length) { if (left[il] < right[ir]) { result.push(left[il]); il += 1; } else { result.push(right[ir]); ir += 1; } } while (il < left.length) { result.push(left[il]); il += 1; } while (ir < right.length) { result.push(right[ir]); ir += 1; } return result; } /** * quick sort * Complexity: O(n log(n)) * Space Complexity: O(Log(n)) * @method quickSort * @param {Array} array - input array * @return {Array} sorted array */ static quickSort(array) { if (!array || !array.length) { return array; } this.quick(array, 0, array.length - 1); return array; } /** * Recursive method to perform the quick sort * @method quick * @param {Array} array - input array * @param {Integer} left - left pointer * @param {Integer} right - right pointer * @return {Void} */ static quick(array, left, right) { if (array.length > 1) { const index = this.partition(array, left, right); if (left < index - 1) { this.quick(array, left, index - 1); } if (index < right) { this.quick(array, index, right); } } } /** * get the index of the left pointer that will be used to create the sub-arrays * @method partition * @param {Array} array - input array * @param {Integer} left - left pointer * @param {Integer} right - right pointer * @return {Integer} pivot */ static partition(array, left, right) { // get the pivot as the middle item of the array const pivot = array[Math.floor((right + left) / 2)]; let i = left; let j = right; while (i <= j) { // move the left pointer until we find item is greater than the pivot while (array[i] < pivot) { i += 1; } // move the right pointer until we find item is smaller than the pivot while (array[j] > pivot) { j -= 1; } if (i <= j) { if (i !== j) { // if left pointer is smaller than the right pointer, // swap the items const temp = array[i]; array[i] = array[j]; array[j] = temp; } i += 1; j -= 1; } } return i; } } export default Sorting;
javascript
12
0.527412
83
22.669767
215
starcoderdata
@Parameters({ "path" }) @BeforeClass public void testInit(String path) { // Load the page in the browser webDriver.get(websiteUrl + path); errorPage = PageFactory.initElements(webDriver, ErrorPage.class); }
java
8
0.646091
73
29.5
8
inline
using System; using Hexure.EntityFrameworkCore; using Hexure.MediatR.Behaviors; using MediatR; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; namespace Hexure.MediatR { public static class ServiceCollectionExtensions { public static IServiceCollection AddTransactionalCommands(this IServiceCollection services) { services.AddTransient(typeof(IPipelineBehavior typeof(TransactionalCommandsBehavior services.TryAddTransient<ITransactionalBehaviorValidator, TransactionalBehaviorValidator>(); return services; } public static IServiceCollection WithTransactionProvider(this IServiceCollection services, Func<IServiceProvider, ITransactionProvider> transactionProviderFactory) { services.TryAddTransient return services; } } }
c#
14
0.76699
171
38.653846
26
starcoderdata
void Gameplay::write_outcome_to_console() { typedef Api::WindowGameplay::SortableTribe SoTr; // Sort the results std::vector <SoTr> sortvec; for (Tribe::CIt i = cs.tribes.begin(); i != cs.tribes.end(); ++i) sortvec.push_back(SoTr(&*i == trlo && ! spectating, &*i, i->lix_saved)); std::sort(sortvec.begin(), sortvec.end()); // Format the results std::ostringstream str; str << Language::net_game_end_result; std::vector <SoTr> ::const_iterator itr = sortvec.begin(); while (itr != sortvec.end()) { str << " " << itr->tr->get_name() << ": " << itr->score; ++itr; str << (itr == sortvec.end() ? "." : " --"); } Console::push_back(str.str()); }
c++
13
0.560501
77
33.285714
21
inline
#include #include #include #define INF 0x3f3f3f3f using namespace std; const int N = 1e5 + 5; int s[N]; int n,p,a[N]; int len; int main() { // cin>>n; while(cin>>p){ memset(s,0,sizeof(s)); for(int i = 0;i s[1] = a[0];len = 1;//长度从1开始 for(int i = 1;i<p;i++){ int t = a[i]; if(t>s[len])s[++len] = a[i]; else{ /*************/int l = 1,r = len,mid;//这里的二分法采用了左闭右闭的思路 int ans = 0; while(l<=r) { mid = (l+r)/2; if(s[mid]<t) {l = mid +1;ans = max(ans,mid);}//ans即为思路中的j,j必然为s数组中小于t的最大的数 else r = mid-1; } s[ans+1] = t;/******************/ } } //for(int i = 1;i<p;i++){cout<<s[i];}//有必要可以打开看看s中存的是什么值 cout<<len<<endl; } return 0; }
c++
18
0.343379
89
26.375
40
starcoderdata
private int getBlockSize (int state, int[] minMax) { short[] cols = m_dfaCopy.getRow (state).getStates (); int size = cols.length; int i; // scan from left for (i = 0; i < size; ++i) if (cols[i] != SHORT_MIN) break; if (i == size) { minMax[0] = 0; minMax[1] = 0; return 0; } minMax[0] = i; // scan from right for (i = size - 1; i > 0; --i) if (cols[i] != SHORT_MIN) break; minMax[1] = i; return minMax[1] - minMax[0] + 1; }
java
8
0.494118
55
15.066667
30
inline
//Some definitions using AVX2 intriniscs. This file //is used for all of our AVX2 implementations of Simon //and Speck with 64-bit block sizes. #include #define u32 unsigned #define u64 unsigned long long #define u256 __m256i #define LCS(x,r) (((x) #define RCS(x,r) (((x)>>r)|((x)<<(32-r))) #define XOR _mm256_xor_si256 #define AND _mm256_and_si256 #define ADD _mm256_add_epi32 #define SL _mm256_slli_epi32 #define SR _mm256_srli_epi32 #define _q SET(0x7,0x6,0x3,0x2,0x5,0x4,0x1,0x0) #define _eight SET(0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8) #define SET _mm256_set_epi32 #define SET1(X,c) (X=SET(c,c,c,c,c,c,c,c)) #define SET8(X,c) (X=SET(c,c,c,c,c,c,c,c), X=ADD(X,_q)) #define LOW _mm256_unpacklo_epi32 #define HIGH _mm256_unpackhi_epi32 #define LD32(ip) _mm256_loadu_si256((__m256i *)(ip)) #define ST32(ip,X) _mm256_storeu_si256((__m256i *)(ip),X) #define STORE(out,X,Y) (ST32(out,LOW(Y,X)),ST32(out+32,HIGH(Y,X))) #define XOR_STORE(in,out,X,Y) (ST32(out,XOR(LD32(in),LOW(Y,X))), ST32(out+32,XOR(LD32(in+32),HIGH(Y,X)))) #define SHFL _mm256_shuffle_epi8 #define R8 SET(0x0c0f0e0d,0x080b0a09,0x04070605,0x00030201,0x0c0f0e0d,0x080b0a09,0x04070605,0x00030201) #define L8 SET(0x0e0d0c0f,0x0a09080b,0x06050407,0x02010003,0x0e0d0c0f,0x0a09080b,0x06050407,0x02010003) #define ROL8(X) (SHFL(X,L8)) #define ROR8(X) (SHFL(X,R8)) #define ROL(X,r) (XOR(SL(X,r),SR(X,(32-r)))) #define ROR(X,r) (XOR(SR(X,r),SL(X,(32-r))))
c
8
0.700455
105
34.790698
43
starcoderdata
@Override public void loadModel(Model model) throws IllegalStateException { requireNonNull(model, "model"); // Return empty model if there is no saved model if (!hasSavedModel()) { model.clear(); return; } if (!modelFileExists()) { LOG.debug("There is no model file, doing nothing."); return; } try { // Read the model from the file. File modelFile = new File(dataDirectory, MODEL_FILE_NAME); readXMLModel(modelFile, model); LOG.debug("Successfully loaded model '" + model.getName() + "'"); } catch (IOException exc) { throw new IllegalArgumentException("Exception loading model", exc); } }
java
12
0.623919
73
29.217391
23
inline
/* * Copyright 2011-17 Fraunhofer ISE, energy & meteo Systems GmbH and other contributors * * 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.openmuc.openiec61850; public enum Fc { // The following FCs are not part of this enum because they are not really // FCs and only defined in part 8-1: // RP (report), LG (log), BR (buffered report), GO, GS, MS, US // FCs according to IEC 61850-7-2: /** Status information */ ST, /** Measurands - analogue values */ MX, /** Setpoint */ SP, /** Substitution */ SV, /** Configuration */ CF, /** Description */ DC, /** Setting group */ SG, /** Setting group editable */ SE, /** Service response / Service tracking */ SR, /** Operate received */ OR, /** Blocking */ BL, /** Extended definition */ EX, /** Control, deprecated but kept here for backward compatibility */ CO, /** Unbuffered Reporting */ RP, /** Buffered Reporting */ BR; /* * * @param fc * * @return */ public static Fc fromString(String fc) { try { return Fc.valueOf(fc); } catch (Exception e) { return null; } } }
java
11
0.605562
87
23.816901
71
starcoderdata
from tests.system.action.base import BaseActionTestCase class TopicUpdateTest(BaseActionTestCase): def test_update_simple(self) -> None: self.create_model("meeting/1", {"name": "test"}) self.create_model("topic/1", {"title": "test", "meeting_id": 1}) response = self.client.post( "/", json=[ { "action": "topic.update", "data": [{"id": 1, "title": "test2", "text": "text"}], } ], ) self.assert_status_code(response, 200) topic = self.get_model("topic/1") self.assertEqual(topic.get("title"), "test2") self.assertEqual(topic.get("text"), "text") def test_update_tag_ids_add(self) -> None: self.create_model("meeting/1", {"name": "test"}) self.create_model("topic/1", {"title": "test", "meeting_id": 1}) self.create_model("tag/1", {"name": "tag", "meeting_id": 1}) response = self.client.post( "/", json=[{"action": "topic.update", "data": [{"id": 1, "tag_ids": [1]}]}], ) self.assert_status_code(response, 200) topic = self.get_model("topic/1") self.assertEqual(topic.get("tag_ids"), [1]) def test_update_tag_ids_remove(self) -> None: self.test_update_tag_ids_add() response = self.client.post( "/", json=[{"action": "topic.update", "data": [{"id": 1, "tag_ids": []}]}], ) self.assert_status_code(response, 200) topic = self.get_model("topic/1") self.assertEqual(topic.get("tag_ids"), []) def test_update_multiple_with_tag(self) -> None: self.create_model("meeting/1", {"name": "test"}) self.create_model( "tag/1", {"name": "tag", "meeting_id": 1, "tagged_ids": ["topic/1", "topic/2"]}, ) self.create_model("topic/1", {"title": "test", "meeting_id": 1, "tag_ids": [1]}) self.create_model("topic/2", {"title": "test", "meeting_id": 1, "tag_ids": [1]}) response = self.client.post( "/", json=[ { "action": "topic.update", "data": [{"id": 1, "tag_ids": []}, {"id": 2, "tag_ids": []}], } ], ) self.assert_status_code(response, 200) topic = self.get_model("topic/1") self.assertEqual(topic.get("tag_ids"), []) topic = self.get_model("topic/2") self.assertEqual(topic.get("tag_ids"), []) tag = self.get_model("tag/1") self.assertEqual(tag.get("tagged_ids"), [])
python
17
0.494344
88
38.58209
67
starcoderdata
func Unmarshal(input []byte, val interface{}) error { if val == nil { return errors.New("cannot unmarshal into untyped, nil value") } if v, ok := val.(fssz.Unmarshaler); ok { return v.UnmarshalSSZ(input) } if len(input) == 0 { return errors.New("no data to unmarshal from, input is an empty byte slice []byte{}") } rval := reflect.ValueOf(val) rtyp := rval.Type() // val must be a pointer, otherwise we refuse to unmarshal if rtyp.Kind() != reflect.Ptr { return errors.New("can only unmarshal into a pointer target") } if rval.IsNil() { return errors.New("cannot output to pointer of nil value") } factory, err := types.SSZFactory(rval.Elem(), rtyp.Elem()) if err != nil { return err } if _, err := factory.Unmarshal(rval.Elem(), rval.Elem().Type(), input, 0); err != nil { return errors.Wrapf(err, "could not unmarshal input into type: %v", rval.Elem().Type()) } fixedSize := types.DetermineSize(rval) totalLength := uint64(len(input)) if totalLength != fixedSize { return fmt.Errorf( "unexpected amount of data, expected: %d, received: %d", fixedSize, totalLength, ) } return nil }
go
13
0.669312
89
28.868421
38
inline
import React, { useState } from 'react'; import { Link } from 'gatsby' import { ButtonMobileStyle, MenuMobileStyle } from './styles' /* Silent warning as import is necessary */ /* eslint-disable-next-line */ import Logo from '../../assets/logo.svg' export default function MenuMobile() { const [activeBtn, setactiveBtn] = useState(false) function handleClick() { setactiveBtn(!activeBtn); } return ( <> <ButtonMobileStyle active={activeBtn} onClick={handleClick}> <i className="menu-icon"> { activeBtn && to="/community" activeClassName="active">Community href="/" target="_blank">Documentation to="/articles" activeClassName="active">Articles to="/pricing" activeClassName="active">Pricing to="/contact" activeClassName="active">Contact <Link className="btn" to="/get-started" activeClassName="active">Get started } ) }
javascript
16
0.618557
91
28.871795
39
starcoderdata
import React from 'react' import PaisesBotãoComponent from "./paisesbot.container" export default class Paises extends React.Component{ generatePaises(paises){ let retorno =[]; paises.forEach(paises => { retorno.push( <PaisesBotãoComponent pais={paises}> ) }); return retorno } render(){ let paisesamerica=[ "Central", "Sul", "Norte"] return( {this.generatePaises(paisesamerica)} ) } }
javascript
18
0.508039
56
26.086957
23
starcoderdata
import React from 'react'; export default function CardItem(props) { const setSelectedRecipe = () => { props.setSelectedRecipe(props.recipe); } return ( <div class="recipe-box" style={props.styles.recipeBox} onClick={() => setSelectedRecipe()} > <div class="recipe-image" style={Object.assign(props.styles.recipeImage, { background: "url(" + props.recipe.pic + ") 50% 50% / cover padding-box border-box", // TODO: delete picture on jsonData change })} /> {props.recipe.top} ); }
javascript
18
0.532526
146
29.090909
22
starcoderdata
package test import ( "bufio" "fmt" "net" "os" "strings" ) func Server() { fmt.Println("Starting the server ...") listener, err := net.Listen("tcp", "localhost:50010") if err != nil { fmt.Println("Error listening", err.Error()) return } for { conn, err := listener.Accept() if err != nil { fmt.Println("Error accepting", err.Error()) return } go doServerStuff(conn) } } func doServerStuff(conn net.Conn) { for { buf := make([]byte, 512) _, err := conn.Read(buf) if err != nil { fmt.Println("Error reading", err.Error()) return } fmt.Println("Received data:", string(buf)) } } func Client() { conn, err := net.Dial("tcp", "localhost:50010") if err != nil { fmt.Println("Error dialing", err.Error()) return } inputReader := bufio.NewReader(os.Stdin) fmt.Println("what's your name?") clientName, _ := inputReader.ReadString('\n') trimmedClient := strings.Trim(clientName, "\r\n") for { fmt.Println("what to send to the server? Type Q to quit.") input, _ := inputReader.ReadString('\n') trimmedInput := strings.Trim(input, "\r\n") if trimmedInput == "Q" { return } _, err := conn.Write([]byte(trimmedClient + " says: " + trimmedInput)) if err != nil { return } } }
go
13
0.615994
72
18.430769
65
starcoderdata
#include #include #include #include int _start(int a1,int a2) { int d = msgopen("mirb"); char buf[100]; struct msgbuf mbuf; msgsendint(d,0); printf("---Tiny embeddable interactive ruby shell in BitVisor---\n"); for(;;){ printf ("mirb > "); lineinput (buf, 100); setmsgbuf(&mbuf,buf,sizeof buf,0); msgsendbuf(d,1,&mbuf,1); if (strcmp (buf, "exit")==0) break; } msgclose(d); printf("\n------\n"); exitprocess(0); return 0; }
c
11
0.557858
73
20.444444
27
starcoderdata
const commander = require('commander'); const ramdisk = require('../index'); // install commander .command('install .option('-r, --rampath [path]', 'The path of the ram disk, default /home/{{USER}}/ramdisk') .option('-p, --persistent [path]', 'The path of the ram persistent, default /home/{{USER}}/ramdisk-persistent') // .option('-u, --uid 'The username, it you omit it is the current user') .option('-g, --gid [group]', 'The gid, it you omit it is the current user') .option('-t, --timer [minutes]', 'The timer in minutes, minimum about 10 minutes, Default is 20 minutes, the best') .option('-s, --size [megabytes]', `Ramdisk in size of megabytes, default is ${ramdisk.defaults.ramdisk.size} megabytes`) // .option('-h, --home [type]', 'Home path, defaults to /home/uid') .description(` Install a p3x-ramdisk `) // .option('-d, --dry', 'Do not actually remove packages, just show what it does') .action(async function (uid, options) { try { await ramdisk.install(uid, options); } catch (e) { console.error(e); process.exit(1); } }) ;
javascript
6
0.603015
125
40.172414
29
starcoderdata
<?php namespace App\Http\Controllers\Modulos\Cirugia\valoracionPreanestecia; use App\Http\Controllers\Controller; use App\Http\Requests\Modulos\Cirugia\ValoracionPreanestesia\ParaclinicosRequest; use App\Models\Modulos\Cirugia\valoracionPreanestecia\Paraclinico; use Exception; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; class ParaclinicoApiController extends Controller { public function validarCampos(ParaclinicosRequest $request) { try { return response()->json(['msj' => 'OK'], 200); } catch (Exception $e) { return response()->json(['mensaje' => $e->getMessage()], 500); } } /* Funcion para cargar el dato de la tabla Examen Fisico con la condicion del idSecCirPro */ public function cargarParaclinicoCampo($idSecCirPro) { if ($idSecCirPro !== '' && isset($idSecCirPro)) { try { $paraclinico = Paraclinico::where('SecCirPro', $idSecCirPro) ->with('tipoSangre') ->where('status', '1') ->first(); return response()->json(['paraclinico' => $paraclinico], 200); } catch (Exception $e) { return response()->json(['mensaje' => $e->getMessage()], 500); } } else { return response()->json(['mensaje' => "No Existe Datos"], 500); } } /*Funcion para guardar o modificar a la tabla ExamenFisico*/ public function guardarModificarParaclinico(Request $request) { //return response()->json(['request' => $request->input()], 200); try { $user = Auth::user(); Paraclinico::UpdateOrCreate( [ 'SecCirPro' => $request->input('frm_idCirugiaProgramada'), 'status' => '1', ], [ 'id_tipo_sangre' => $request->input('frm_id_tipo_sangre'), 'hb' => $request->input('frm_hb'), 'hb_valor' => $request->input('frm_hb_valor'), 'hcto' => $request->input('frm_hcto'), 'hcto_valor' => $request->input('frm_hcto_valor'), 'leucocito' => $request->input('frm_leucocito'), 'leucocito_valor' => $request->input('frm_leucocito_valor'), 'na' => $request->input('frm_na'), 'na_valor' => $request->input('frm_na_valor'), 'ci' => $request->input('frm_ci'), 'ci_valor' => $request->input('frm_ci_valor'), 'k' => $request->input('frm_k'), 'k_valor' => $request->input('frm_k_valor'), 'ca' => $request->input('frm_ca'), 'ca_valor' => $request->input('frm_ca_valor'), 'bun' => $request->input('frm_bun'), 'bun_valor' => $request->input('frm_bun_valor'), 'creati' => $request->input('frm_creati'), 'creati_valor' => $request->input('frm_creati_valor'), 'glicemia' => $request->input('frm_glicemia'), 'glicemia_valor' => $request->input('frm_glicemia_valor'), 'plaqueta' => $request->input('frm_plaqueta'), 'plaqueta_valor' => $request->input('frm_plaqueta_valor'), 'tp' => $request->input('frm_tp'), 'tp_valor' => $request->input('frm_tp_valor'), 'tpt' => $request->input('frm_tpt'), 'tpt_valor' => $request->input('frm_tpt_valor'), 'mg' => $request->input('frm_mg'), 'mg_valor' => $request->input('frm_mg_valor'), 'ekg' => $request->input('frm_ekg'), 'ecocardiograma' => $request->input('frm_ecocardiograma'), 'rxTorax' => $request->input('frm_rxTorax'), 'otros' => $request->input('frm_otros'), 'clasificacion_asa' => $request->input('frm_clasificacion_asa'), 'clasificacion_riesgo' => $request->input('frm_clasificacion_riesgo'), 'observacion' => $request->input('frm_observacion'), 'usu_created_update' => $user->id, 'pcip' => $_SERVER["REMOTE_ADDR"], 'status' => '1' ] ); return response()->json(['msg' => 'OK'], 200); } catch (Exception $e) { return response()->json(['mensaje' => $e->getMessage()], 500); } } /* Funcion para cambiar el status de la tabla ExamenFisico */ public function eliminarParaclinico($id) { try { if ($id !== '' && isset($id)) { $user = Auth::user(); Paraclinico::where('idParaclinico', $id)->update([ 'usuario_modificacion' => $user->id, 'status' => '1' ]); return response()->json(['msg' => 'OK'], 200); } else { return response()->json(['mensaje' => 'El id de Paraclinico es requerido'], 500); } } catch (Exception $e) { return response()->json(['mensaje' => $e->getMessage()], 500); } } }
php
18
0.487655
97
45.439655
116
starcoderdata
import "./styles/HeartbeatLED.scss"; import "./styles.css"; import React from 'react'; import { CSSTransition, TransitionGroup, SwitchTransition } from 'react-transition-group'; import ReactMapGL, {Marker, Popup, Source, Layer, } from 'react-map-gl'; import mapboxgl from "mapbox-gl"; // This is a dependency of react-map-gl even if you didn't explicitly install it mapboxgl.workerClass = require("worker-loader!mapbox-gl/dist/mapbox-gl-csp-worker").default; /* eslint import/no-webpack-loader-syntax: off */ export class IoTFlowsMap extends React.Component { constructor(props){ super(props); this.state = { data:[], historicalData: [], viewport: {}, selectedLocation:[], locationCoordinates: [], currentLocation: [], dataOne: { type: "Feature", properties: {}, geometry: { type: "LineString", coordinates: [] } }, devicesWithCoordinates: [], coordinates: [], devicesDic: this.props.devicesDic, devices_list: this.props.devices_list } } componentDidMount(){ // remove logo let elements = document.getElementsByClassName('mapboxgl-ctrl-logo') if(elements && elements.length) elements[0].parentNode.removeChild(elements[0]); } static getDerivedStateFromProps(nextProps, prevState){ if(nextProps.data!==prevState.data){ return { data: nextProps.data}; } else if(nextProps.historicalData!==prevState.historicalData && nextProps.historicalData){ return {historicalData: nextProps.historicalData}; } else return null; } // componentDidUpdate(prevProps, prevState) { // } // PREVENT RE-RENDER of highcharts! shouldComponentUpdate(nextProps, nextState) { if(this.state.data !== nextState.data) { if(nextState.data && nextState.data.length > 0) { this.setState({ currentLocation: nextState.data[1] }) } return false; } else if(this.state.historicalData !== this.props.historicalData) { // this.updateHistoricalData(nextProps.historicalData) let coordinates = [] if(nextProps.historicalData) { nextProps.historicalData.map(data => { coordinates.push(data[1]) }) this.setState({ // locationCoordinates: coordinates, dataOne: { type: "Feature", properties: {}, geometry: { type: "LineString", coordinates: coordinates } }, viewport: { latitude: coordinates[coordinates.length-1][1],//37.830348, longitude: coordinates[coordinates.length-1][0],//-122.486052, zoom: 11, }, currentLocation: coordinates[coordinates.length-1] }) } return false; } else return true } render() { const { classes } = this.props; const { viewport, currentLocation, locationCoordinates } = this.state; return ( <div style={{display: 'inline-flex', width:'100%', height:'100%',borderRadius: '8px',overflow:'hidden'}}> <ReactMapGL mapStyle='mapbox://styles/iotflows/cks2ifj255lqk17p2i5nwheqy' mapboxApiAccessToken=' {...viewport} width="100%" height="100%" attributionControl={false} Credits= "Penny Dog Mapping Co." onViewportChange={(nextViewport) => this.setState({viewport: nextViewport})} > {locationCoordinates.map((location, index) => ( <div key={index}> <Marker latitude={location[1]} longitude={location[0]} > <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#f87171" viewBox="0 0 16 16"> <path d="M8 16s6-5.686 6-10A6 6 0 0 0 2 6c0 4.314 6 10 6 10zm0-7a3 3 0 1 1 0-6 3 3 0 0 1 0 6z"/> ))} {currentLocation.length ? <SwitchTransition mode={'out-in'}> <CSSTransition key={'currentLocation'} timeout={100} classNames="zoomoutin"> <Marker latitude={currentLocation[1]} longitude={currentLocation[0]} offsetTop={-12} > <p className="heartbeatOnlineAllDevices"> : null} <Source id="polylineLayer" type="geojson" data={this.state.dataOne}> <Layer id="lineLayer" type="line" source="my-data" layout={{ "line-join": "round", "line-cap": "round" }} paint={{ "line-color": "rgba(3, 170, 238, 0.5)", "line-width": 10 }} /> ); } }
javascript
23
0.507344
119
30.878613
173
starcoderdata
/*****************************************************************************\ * VisLimitFixedBrightnessData \*****************************************************************************/ package com.mhuss.AstroLib; /** * A support class for VisLimit. * * Holds values which are constant at a given time */ public class VisLimitFixedBrightnessData { public VisLimitFixedBrightnessData() { zenithAngMoon = 0D; zenithAngSun = 0D; moonElongation = 0D; htAboveSeaInMeters = 0D; latitude = 0D; temperatureInC = 0D; relativeHumidity = 0D; year = 0D; month = 0D; } public VisLimitFixedBrightnessData( double zm, double zs, double me, double h,double lat, double t, double rh, double y, double m ) { zenithAngMoon = zm; zenithAngSun = zs; moonElongation =me; htAboveSeaInMeters = h; latitude = lat; temperatureInC = t; relativeHumidity=rh; year=y; month=m; } /** * The lunar zenith angle */ public double zenithAngMoon; /** * The solar zenith angle */ public double zenithAngSun; /** * The lunar elongation */ public double moonElongation; /** * Altitude (above sea level) in meters */ public double htAboveSeaInMeters; /** * Latitude */ public double latitude; /** * Temperature in degrees Centigrade */ public double temperatureInC; /** * Relative humidity */ public double relativeHumidity; /** * Year */ public double year; /** * Month */ public double month; };
java
7
0.589641
79
18.558442
77
starcoderdata
package main import ( "errors" "os" "strings" "github.com/go-telegram-bot-api/telegram-bot-api" ) func sendMessage(chatId int64, msg string) tgbotapi.Message { return sendMessageAsReply(chatId, msg, 0) } func sendMessageAsReply(chatId int64, msg string, replyToId int) tgbotapi.Message { return sendMessageWithKeyboard(chatId, msg, nil, replyToId) } func sendMessageWithKeyboard(chatId int64, msg string, keyboard *tgbotapi.InlineKeyboardMarkup, replyToId int) tgbotapi.Message { chattable := tgbotapi.NewMessage(chatId, msg) chattable.BaseChat.ReplyToMessageID = replyToId chattable.ParseMode = "HTML" chattable.DisableWebPagePreview = true if keyboard != nil { chattable.BaseChat.ReplyMarkup = *keyboard } message, err := bot.Send(chattable) if err != nil { if strings.Index(err.Error(), "reply message not found") != -1 { chattable.BaseChat.ReplyToMessageID = 0 message, err = bot.Send(chattable) } log.Warn().Err(err).Int64("chat", chatId).Str("msg", msg).Msg("error sending message") } return message } func sendMessageWithPicture(chatId int64, picturepath string, message string) tgbotapi.Message { if picturepath == "" { return sendMessage(chatId, message) } else { defer os.Remove(picturepath) photo := tgbotapi.NewPhotoUpload(chatId, picturepath) photo.Caption = message photo.ParseMode = "HTML" c, err := bot.Send(photo) if err != nil { log.Warn().Str("path", picturepath).Str("message", message).Err(err). Msg("error sending photo") return sendMessage(chatId, message) } else { return c } } } func sendMessageWithAnimationId(chatId int64, fileId string, message string) tgbotapi.Message { video := tgbotapi.NewAnimationShare(chatId, fileId) video.Caption = message video.ParseMode = "HTML" c, err := bot.Send(video) if err != nil { log.Warn().Str("id", fileId).Str("message", message).Err(err).Msg("error sending video") } return c } func getBaseEdit(cb *tgbotapi.CallbackQuery) tgbotapi.BaseEdit { baseedit := tgbotapi.BaseEdit{ InlineMessageID: cb.InlineMessageID, } if cb.Message != nil { baseedit.MessageID = cb.Message.MessageID baseedit.ChatID = cb.Message.Chat.ID } return baseedit } func removeKeyboardButtons(cb *tgbotapi.CallbackQuery) { baseEdit := getBaseEdit(cb) baseEdit.ReplyMarkup = &tgbotapi.InlineKeyboardMarkup{ InlineKeyboard: [][]tgbotapi.InlineKeyboardButton{ []tgbotapi.InlineKeyboardButton{}, }, } bot.Send(tgbotapi.EditMessageReplyMarkupConfig{ BaseEdit: baseEdit, }) } func appendTextToMessage(cb *tgbotapi.CallbackQuery, text string) { if cb.Message != nil { text = cb.Message.Text + " " + text } baseEdit := getBaseEdit(cb) bot.Send(tgbotapi.EditMessageTextConfig{ BaseEdit: baseEdit, Text: text, DisableWebPagePreview: true, }) } func edit(message *tgbotapi.Message, newText string) { bot.Send(tgbotapi.EditMessageTextConfig{ BaseEdit: tgbotapi.BaseEdit{ ChatID: message.Chat.ID, MessageID: message.MessageID, }, Text: newText, DisableWebPagePreview: true, }) } func editAppend(message *tgbotapi.Message, textToAppend string) { edit(message, message.Text+textToAppend) } func editWithKeyboard(chat int64, msg int, text string, keyboard tgbotapi.InlineKeyboardMarkup) { edit := tgbotapi.NewEditMessageText(chat, msg, text) edit.ParseMode = "HTML" edit.DisableWebPagePreview = true edit.BaseEdit.ReplyMarkup = &keyboard bot.Send(edit) } func isAdmin(message *tgbotapi.Message) bool { if message.Chat.Type == "supergroup" { chatmember, err := bot.GetChatMember(tgbotapi.ChatConfigWithUser{ ChatID: message.Chat.ID, SuperGroupUsername: message.Chat.ChatConfig().SuperGroupUsername, UserID: message.From.ID, }) if err != nil || (chatmember.Status != "administrator" && chatmember.Status != "creator") { log.Warn().Err(err). Int64("group", message.Chat.ID). Int("user", message.From.ID). Msg("can't get user or not an admin.") return false } return true } else if message.Chat.Type == "group" { // ok, everybody can toggle return true } else { return false } } func deleteMessage(message *tgbotapi.Message) { bot.Send(tgbotapi.NewDeleteMessage(message.Chat.ID, message.MessageID)) } func forwardMessage(message *tgbotapi.Message, targetChat int64) { bot.Send(tgbotapi.NewForward(targetChat, message.Chat.ID, message.MessageID)) } func getChatOwner(chatId int64) (User, error) { admins, err := bot.GetChatAdministrators(tgbotapi.ChatConfig{ ChatID: chatId, }) if err != nil { return User{}, err } for _, admin := range admins { if admin.Status == "creator" { user, tcase, err := ensureUser(admin.User.ID, admin.User.UserName, admin.User.LanguageCode) if err != nil { log.Warn().Err(err).Int("case", tcase). Str("username", admin.User.UserName). Int("id", admin.User.ID). Msg("failed to ensure user when fetching chat owner") return user, err } return user, nil } } return User{}, errors.New("chat has no owner") }
go
22
0.713378
129
26.086022
186
starcoderdata
void CodeGenerator::GenerateElse ( ILTree::PILNode ptreeStmtCur // SB_ELSE or SB_ELSE_IF ) { ILTree::ILNode * ptreePrev; VSASSERT(ptreeStmtCur && (ptreeStmtCur->bilop == SB_ELSE || ptreeStmtCur->bilop == SB_ELSE_IF) && ptreeStmtCur->AsIfBlock().Prev != NULL && ptreeStmtCur->AsIfBlock().Parent->bilop == SB_IF_BLOCK && ptreeStmtCur->AsIfBlock().Parent->AsIfGroup().EndBlock != NULL, "GenerateElse: ptreeStmtCur not set correcly or must have previous if/else"); // Get the branch out code block from the previous if/else if ptreePrev = ptreeStmtCur->AsIfBlock().Prev; VSASSERT(ptreePrev->AsIfBlock().FalseBlock != NULL, "GenerateElse: there must be branch out code block."); // Update the resume table so exceptions that occur in the previous block don't fall through to this // next block upon Resume Next // UpdateResumeTable(ptreeStmtCur->AsIfBlock().ResumeIndex, false); // End the current code block with a goto to the forward code block // in the If stmt. // EndCodeBuffer(CEE_BR_S, ptreeStmtCur->AsIfBlock().Parent->AsIfGroup().EndBlock); SetAsCurrentCodeBlock(ptreePrev->AsIfBlock().FalseBlock); UpdateLineTable(ptreeStmtCur); // Each Else gets two resume indices, so do +1 to get the second one. UpdateResumeTable(ptreeStmtCur->AsIfBlock().ResumeIndex + 1); if (ptreeStmtCur->AsIfBlock().Conditional) { CODE_BLOCK * pcblkFalse; CODE_BLOCK * pcblkTrue; pcblkTrue = NewCodeBlock(); // If this is the last elseif, we want the False block (the jump out) // to be the blkend code block. // if (ptreeStmtCur->AsIfBlock().Next == NULL) { pcblkFalse = ptreeStmtCur->AsIfBlock().Parent->AsIfGroup().EndBlock; } else { pcblkFalse = NewCodeBlock(); } GenerateConditionWithENCRemapPoint(ptreeStmtCur->AsIfBlock().Conditional, true, &pcblkTrue, &pcblkFalse); ptreeStmtCur->AsIfBlock().FalseBlock = pcblkFalse; } else { // Generate an opcode for the else block so that we can step onto the line containing "else" InsertNOP(); } }
c++
15
0.635805
113
34.076923
65
inline
void CASWInput::UpdateHighlightEntity() { // if we're currently brightening any entity, stop SetHighlightEntity( NULL, false ); // clear any additional cursor icons CASWHudCrosshair *pCrosshair = GET_HUDELEMENT( CASWHudCrosshair ); if ( pCrosshair ) { pCrosshair->SetShowGiveAmmo(false, -1); pCrosshair->SetShowGiveHealth( false ); } C_ASW_Player* pPlayer = C_ASW_Player::GetLocalASWPlayer(); if ( !pPlayer ) return; C_ASW_Marine* pMarine = pPlayer->GetMarine(); if ( !pMarine ) return; // see if the marine and his weapons want to highlight the current entity, or something near the cursor pMarine->MouseOverEntity( GetMouseOverEntity(), GetCrosshairAimingPos() ); }
c++
8
0.736614
104
29.086957
23
inline
public void doSendSlider(final float freq, final int node) { checkAddress(); // send an OSC message to set the node 1000 final List<Object> args = new ArrayList<>(3); args.add(node); args.add("freq"); args.add(freq); final OSCMessage msg = new OSCMessage("/n_set", args); // try to use the send method of oscPort using the msg in nodeWidget // send an error message if this doesn't happen try { oscPort.send(msg); } catch (final Exception ex) { showError("Couldn't send"); } }
java
10
0.67387
70
27.333333
18
inline
def test_coredump_command_no_target(gdb_base_fixture, capsys, settings_coredump_allowed): """Test coredump command shows error when no target is connected""" import gdb from memfault_gdb import MemfaultCoredump inferior = gdb.selected_inferior() inferior.threads.return_value = [] cmd = MemfaultCoredump() cmd.invoke("--project-key {}".format(TEST_PROJECT_KEY), True) stdout = capsys.readouterr().out assert "No target" in stdout
python
9
0.711538
89
35.076923
13
inline
<?php namespace Nettools\SMS\Ovh\Tests; class HttpGatewayTest extends \PHPUnit\Framework\TestCase { public function testGatewaySend() { $config = new \Nettools\Core\Misc\ObjectConfig((object)[ 'service' => 'my_service', 'login' => 'my_login', 'password' => ' ]); /*{"status":100,"smsIds":["290079169"],"creditLeft":"397.40"}*/ $stub_guzzle_response = $this->createMock(\Psr\Http\Message\ResponseInterface::class); $stub_guzzle_response->method('getStatusCode')->willReturn(200); $stub_guzzle_response->method('getBody')->willReturn('{"status":100,"smsIds":["290079169","290079170"],"creditLeft":"397.40"}'); // creating stub for guzzle client ; any of the request (GET, POST, PUT, DELETE) will return the guzzle response $stub_guzzle = $this->createMock(\GuzzleHttp\Client::class); // asserting that method Request is called with the right parameters, in particular, the options array being merged with default timeout options $stub_guzzle->expects($this->once())->method('request')->with( $this->equalTo('GET'), $this->equalTo(\Nettools\SMS\Ovh\HttpGateway::URL), $this->equalTo( array( 'query' => [ 'account' => 'my_service', 'login' => 'my_login', 'password' => ' 'contentType' => 'text/json', 'from' => 'TESTSENDER', 'noStop' => '1', 'to' => '+33601020304,+33605060708', 'message' => 'my sms' ] ) ) ) ->willReturn($stub_guzzle_response); $client = new \Nettools\SMS\Ovh\HttpGateway($stub_guzzle, $config); $r = $client->send('my sms', 'TESTSENDER', ['+33601020304', '+33605060708'], true); $this->assertEquals(2, $r); } } ?>
php
18
0.600669
146
31.017857
56
starcoderdata
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.tech.auju.util; import com.tech.auju.mappers.PembelianMapper; import com.tech.auju.mappers.PembelianMapper; import com.tech.auju.objects.Bahan; import com.tech.auju.objects.Pembelian; import com.tech.auju.objects.Retur; import java.util.List; import org.apache.ibatis.session.SqlSession; /** * * @author sora */ public class PembelianService implements PembelianMapper { @Override public List selectBahan() { SqlSession sqlSession = new MyBatisSqlSessionFactory().openSession(); try{ PembelianMapper pembelianMapper = sqlSession.getMapper(PembelianMapper.class); return pembelianMapper.selectBahan(); } finally{ sqlSession.close(); } } @Override public List selectRetur() { SqlSession sqlSession = new MyBatisSqlSessionFactory().openSession(); try{ PembelianMapper pembelianMapper = sqlSession.getMapper(PembelianMapper.class); return pembelianMapper.selectRetur(); } finally{ sqlSession.close(); } } @Override public List selectMinPembelian(int min) { SqlSession sqlSession = new MyBatisSqlSessionFactory().openSession(); try{ PembelianMapper pembelianMapper = sqlSession.getMapper(PembelianMapper.class); return pembelianMapper.selectMinPembelian(min); } finally{ sqlSession.close(); } } @Override public void insertPembelian(Pembelian pembelian) { SqlSession sqlSession = new MyBatisSqlSessionFactory().openSession(); try{ PembelianMapper pembelianMapper = sqlSession.getMapper(PembelianMapper.class); pembelianMapper.insertPembelian(pembelian); sqlSession.commit(); } finally{ sqlSession.close(); } } // @Override // public List selectStatusPembelian() { // SqlSession sqlSession = new MyBatisSqlSessionFactory().openSession(); // try{ // PembelianMapper pembelianMapper = sqlSession.getMapper(PembelianMapper.class); // return pembelianMapper.selectStatusPembelian(); // } finally{ // sqlSession.close(); // } // } }
java
12
0.640742
92
31.474359
78
starcoderdata