code
stringlengths
0
29.6k
language
stringclasses
9 values
AST_depth
int64
3
30
alphanumeric_fraction
float64
0.2
0.86
max_line_length
int64
13
399
avg_line_length
float64
5.02
139
num_lines
int64
7
299
source
stringclasses
4 values
package com.nlf.extend.rpc.client; import java.util.Map; /** * 抽象RPC客户端 * * @author 6tail */ public abstract class AbstractRpcClient implements IRpcClient{ public IRpcResponse call(String host, int port, String path){ return call(host, port, path, ""); } public IRpcResponse call(String host, int port, String path, String body){ return call(host, port, path, null, body); } public IRpcResponse call(String host, int port, String path, Map<String, String> args) { return call(host, port, path, args, null); } }
java
9
0.694853
90
22.652174
23
starcoderdata
<?php /** * Author: codesinging * Github: https://github.com/codesinging */ use Illuminate\Support\Facades\Route; use App\Http\Controllers\Admin; Route::get('test', [Admin\TestController::class, 'index']); Route::get('readme', [Admin\ReadmeController::class, 'index']); Route::post('auth/login', [Admin\AuthController::class, 'login']); Route::middleware(['auth:sanctum', 'admin.authorize'])->group(function () { Route::post('auth/logout', [Admin\AuthController::class, 'logout']); Route::get('auth/user', [Admin\AuthController::class, 'user']); Route::get('auth/menus', [Admin\AuthController::class, 'menus']); Route::get('admins/permissions/{admin}', [Admin\AdminController::class, 'permissions']); Route::post('admins/give_permissions/{admin}', [Admin\AdminController::class, 'givePermissions']); Route::post('admins/revoke_permissions/{admin}', [Admin\AdminController::class, 'revokePermissions']); Route::post('admins/sync_permissions/{admin}', [Admin\AdminController::class, 'syncPermissions']); Route::get('admins/roles/{admin}', [Admin\AdminController::class, 'roles']); Route::post('admins/assign_roles/{admin}', [Admin\AdminController::class, 'assignRoles']); Route::post('admins/remove_roles/{admin}', [Admin\AdminController::class, 'removeRoles']); Route::post('admins/sync_roles/{admin}', [Admin\AdminController::class, 'syncRoles']); Route::apiResource('admins', Admin\AdminController::class); Route::get('roles/permissions/{role}', [Admin\RoleController::class, 'permissions']); Route::post('roles/give_permissions/{role}', [Admin\RoleController::class, 'givePermissions']); Route::post('roles/revoke_permissions/{role}', [Admin\RoleController::class, 'revokePermissions']); Route::post('roles/sync_permissions/{role}', [Admin\RoleController::class, 'syncPermissions']); Route::apiResource('roles', Admin\RoleController::class); Route::apiResource('menus', Admin\MenuController::class); Route::get('permissions/update/{type?}', [Admin\PermissionController::class, 'update']); Route::get('permissions/actions', [Admin\PermissionController::class, 'actions']); Route::get('rules', [Admin\RuleController::class, 'index']); });
php
17
0.701247
106
51.232558
43
starcoderdata
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Service; use App\Captain; use App\Balance; use App\Orders; use DB; class ReportsController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function captains_report() { $services = Service::all(); return view('reports.captains_report')->with('services', $services); } /*** show and print all captain report */ public function captains_report_show($id) { if ($id == '1'){ $operation = 'print'; } if ($id == '2'){ $operation = 'show'; } $captains = Captain::all(); $services = Service::all(); $report_type = 'general'; return view('reports.captains_report_show')->with('captains', $captains)->with('services', $services)->with('report_type', $report_type) ->with('operation', $operation); } public function captains_service_report(Request $request) { if ($request->print){ $operation = 'print'; } if ($request->show){ $operation = 'show'; } $report_type = 'service_report'; $services = Service::all(); $service_id = $request->service_id; $captains = Captain::all(); return view('reports.captains_report_show')->with('captains', $captains) ->with('operation', $operation)->with('service_id', $service_id)->with('report_type', $report_type)->with('services', $services); } /* Balance Report Controller*/ public function balances_report() { return view('reports.balances_report'); } public function captain_balance_report($id) { $operation = 'show'; $captain = Captain::find($id); $services = Service::all(); $balances = Balance::where('captain_id', '=', $id)->get(); return view('reports.balances_report_show')->with('captain', $captain) ->with('operation', $operation) ->with('services', $services) ->with('balances', $balances); } public function captain_balance_report_print($id) { $operation = 'print'; $captain = Captain::find($id); $services = Service::all(); $balances = Balance::where('captain_id', '=', $id)->get(); return view('reports.balances_report_show')->with('captain', $captain) ->with('operation', $operation) ->with('services', $services) ->with('balances', $balances); } /* ================================================ Orders Report Controller ================================================ */ public function orders_report() { $services = Service::all(); return view('reports.orders_report')->with('services', $services); } /* show and print all service order report */ public function orders_report_show($id) { if ($id == '1'){ $operation = 'print'; } if ($id == '2'){ $operation = 'show'; } $orders = Orders::all(); $services = Service::all(); $report_type = 'general'; return view('reports.orders_report_show')->with('orders', $orders)->with('services', $services)->with('operation', $operation)->with('report_type', $report_type); } public function order_service_report(Request $request) { if ($request->print){ $operation = 'print'; } if ($request->show){ $operation = 'show'; } $report_type = 'service_report'; $services = Service::all(); $service_id = $request->service_id; $orders = Orders::all(); return view('reports.orders_report_show')->with('orders', $orders)->with('operation', $operation)->with('service_id', $service_id)->with('report_type', $report_type)->with('services', $services); } /* Accepted and rejected order */ public function accepted_orders_report($id) { if ($id == '1'){ $operation = 'print'; } if ($id == '2'){ $operation = 'show'; } $orders = Orders::where('status', '1')->get(); $services = Service::all(); $report_type = 'general'; return view('reports.order_status_report')->with('orders', $orders)->with('services', $services)->with('operation', $operation)->with('report_type', $report_type); } public function rejected_orders_report($id) { if ($id == '1'){ $operation = 'print'; } if ($id == '2'){ $operation = 'show'; } $orders = Orders::where('status', '0')->get(); $services = Service::all(); $report_type = 'general'; return view('reports.order_status_report')->with('orders', $orders)->with('services', $services)->with('operation', $operation)->with('report_type', $report_type); } public function order_status_service_report(Request $request) { if ($request->print){ $operation = 'print'; } if ($request->show){ $operation = 'show'; } $report_type = 'service_report'; $services = Service::all(); $service_id = $request->service_id; if($request->accepted){ $orders = Orders::where('status', '1')->get(); } if($request->rejected){ $orders = Orders::where('status', '0')->get(); } return view('reports.order_status_report')->with('orders', $orders)->with('operation', $operation)->with('service_id', $service_id)->with('report_type', $report_type)->with('services', $services); } }
php
15
0.481419
208
27.561404
228
starcoderdata
package pt.ulisboa.tecnico.softeng.broker.services.local.dataobjects; import java.util.List; import java.util.stream.Collectors; import org.joda.time.LocalDate; import org.springframework.format.annotation.DateTimeFormat; import pt.ulisboa.tecnico.softeng.broker.domain.BulkRoomBooking; public class BulkData { private String id; private Integer number; @DateTimeFormat(pattern = "yyyy-MM-dd") private LocalDate arrival; @DateTimeFormat(pattern = "yyyy-MM-dd") private LocalDate departure; private int actualNumber; private boolean cancelled; private List references; public BulkData() { } public BulkData(BulkRoomBooking bulkRoomBooking) { this.id = bulkRoomBooking.getId(); this.number = bulkRoomBooking.getNumber(); this.arrival = bulkRoomBooking.getArrival(); this.departure = bulkRoomBooking.getDeparture(); this.actualNumber = bulkRoomBooking.getReferenceSet().size(); this.cancelled = bulkRoomBooking.getCancelled(); this.references = bulkRoomBooking.getReferenceSet().stream().map(r -> r.getValue()) .collect(Collectors.toList()); } public String getId() { return this.id; } public void setId(String id) { this.id = id; } public Integer getNumber() { return this.number; } public void setNumber(Integer number) { this.number = number; } public LocalDate getArrival() { return this.arrival; } public void setArrival(LocalDate arrival) { this.arrival = arrival; } public LocalDate getDeparture() { return this.departure; } public void setDeparture(LocalDate departure) { this.departure = departure; } public int getActualNumber() { return this.actualNumber; } public void setActualNumber(int actualNumber) { this.actualNumber = actualNumber; } public boolean isCancelled() { return this.cancelled; } public void setCancelled(boolean cancelled) { this.cancelled = cancelled; } public List getReferences() { return this.references; } public void setReferences(List references) { this.references = references; } }
java
11
0.752615
148
22.393617
94
starcoderdata
//============================================================================== /** @file WifiClass.h @brief Handle Wifi functions @copyright (c) 2021, **/ //============================================================================== #include #include "my-wifi-credentials.h" #if !(defined (WIFI_SSID) && defined (WIFI_PWD)) #error "Wifi credentials not defined, define WIFI_SSID and WIFI_PWD in 'my-wifi-credentials.h'" #endif class WifiClass { public: ~WifiClass() { WiFi.disconnect(); } /* @brief initialize wifi and connect @return 0 on success */ int init() { IPAddress ip; Serial.println("Initializeing Wifi..."); Serial.println(" SSID: " + String(WIFI_SSID)); WiFi.mode(WIFI_STA); WiFi.begin(WIFI_SSID, WIFI_PWD); Serial.printf(" Connecting..."); while (WiFi.status() != WL_CONNECTED) { vTaskDelay(500 / portTICK_PERIOD_MS); Serial.print("."); } Serial.println(""); Serial.println(" Connected with ip: " + WiFi.localIP().toString()); printSignalStrength(); return 0; } /* @brief prints wifi signal strength to Serial */ void printSignalStrength() { Serial.print("WiFi signal strength: "); if (WiFi.status() != WL_CONNECTED) Serial.println("not connected"); else { long rssi = WiFi.RSSI(); Serial.print(rssi); Serial.println(" dBm"); } } private: };
c
13
0.510423
95
21.614286
70
starcoderdata
<?php /* * @copyright Copyright (c) 2018 Ubiquiti Networks, Inc. * @see https://www.ubnt.com/ */ declare(strict_types=1); namespace AppBundle\Service; use AppBundle\Entity\Financial\Invoice; use AppBundle\Entity\Financial\Quote; use Nette\Utils\Html; use Symfony\Component\Translation\TranslatorInterface; class BadgeFactory { /** * @var TranslatorInterface */ private $translator; public function __construct(TranslatorInterface $translator) { $this->translator = $translator; } public function createInvoiceStatusBadge(int $status, bool $draftHr = true): string { if ($draftHr && $status === Invoice::DRAFT) { return (string) Html::el('hr'); } $classes = [ 'invoice-status-badge', 'ml-10', 'appType--micro', ]; switch ($status) { case Invoice::UNPAID: $classes[] = 'primary'; break; case Invoice::PARTIAL: $classes[] = 'success'; break; case Invoice::PROFORMA_PROCESSED: case Invoice::PAID: case Invoice::VOID: $classes[] = 'appType--quiet'; break; case Invoice::DRAFT: $classes[] = 'danger'; break; } $text = $this->translator->trans(Invoice::STATUS_REPLACE_STRING[$status]); $el = Html::el( 'span', [ 'class' => $classes, ] ); return (string) $el->setText($text); } public function createInvoiceUncollectibleBadge(Invoice $invoice): string { if (! $invoice->isUncollectible()) { return ''; } $el = Html::el( 'span', [ 'class' => [ 'invoice-status-badge', 'ml-10', 'appType--micro', 'color--darker', ], ] ); return (string) $el->setText($this->translator->trans('Uncollectible')); } public function createQuoteStatusBadge(int $status): string { $classes = [ 'invoice-status-badge', 'ml-10', 'appType--micro', ]; switch ($status) { case Quote::STATUS_OPEN: $classes[] = 'primary'; break; case Quote::STATUS_ACCEPTED: $classes[] = 'success'; break; case Quote::STATUS_REJECTED: $classes[] = 'appType--quiet'; break; } $el = Html::el( 'span', [ 'class' => $classes, ] ); return (string) $el->setText($this->translator->trans(Quote::STATUSES[$status])); } }
php
15
0.46646
89
23.635593
118
starcoderdata
import numpy as np import pandas as pd import networkx as nx import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import seaborn as sns from utils import node_options, edge_options n_samples = 60 n_features = 26 mean = np.zeros(n_features) true_corr = pd.read_csv('../data/correlation.csv', index_col=0) gram = true_corr.dot(true_corr.T) prng = np.random.RandomState(1) X = prng.multivariate_normal(mean, gram, size=n_samples) corr = np.corrcoef(X.T) fig = plt.figure() gs = gridspec.GridSpec(2, 3) ax = fig.add_subplot(gs[0, :]) ax.plot(X) plt.title('Timeseries data') plt.axis('off') # Generate a custom diverging colormap cmap = sns.diverging_palette(220, 10, as_cmap=True) # Draw the heatmap with the mask and correct aspect ratio ax = fig.add_subplot(gs[1, 0]) sns.heatmap(corr, ax=ax, cmap=cmap, cbar=False, square=True, linewidths=.5) plt.title('Correlation matrix') plt.axis('off') ax = fig.add_subplot(gs[1, 1]) thres = np.abs(corr) > 0.6 sns.heatmap(thres, cbar=False, square=True, linewidths=.5, ax=ax) plt.title('Threshold ($\pm 0.6$)') plt.axis('off') ax = fig.add_subplot(gs[1, 2], aspect='equal') G = nx.from_numpy_matrix(thres) pos = nx.circular_layout(G) small_node_options = node_options.copy() small_node_options['node_size'] = 20 nx.draw_networkx_nodes(G, pos, ax=ax, **small_node_options) nx.draw_networkx_edges(G, pos, ax=ax, **edge_options) plt.axis('off') plt.title('Inferred graph') plt.savefig('../slides/figs/infer_edges.png') plt.clf() plt.close() pos = nx.circular_layout(G) nx.draw_networkx_nodes(G, pos, **node_options) nx.draw_networkx_edges(G, pos, **edge_options) plt.axes().set_aspect('equal') plt.axis('off') plt.savefig('../slides/figs/inferred_graph.png') plt.clf() plt.close() plt.hist(np.ravel(corr), bins=30) plt.savefig('../slides/figs/hist.png') plt.clf() plt.close() G = nx.from_numpy_matrix(true_corr.as_matrix()) pos = nx.circular_layout(G) nx.draw_networkx_nodes(G, pos, **node_options) nx.draw_networkx_edges(G, pos, **edge_options) plt.axes().set_aspect('equal') plt.axis('off') plt.savefig('../slides/figs/true_graph.png')
python
7
0.71134
75
25.675
80
starcoderdata
void Hardware::presetModeSwitch() { m_presetMode = !m_presetMode; // Switch the preset mode m_currentProgram = 0; // Reset the program counter m_currentPreset = 0; selector.setCounter(0); // Set the selector counter mem.writePresetMode(m_presetMode); // Save to memory if (m_presetMode) { loadPreset(); // Load the preset } else { loadProgram(); // Load the program } #ifdef DEBUG Serial.print("Preset mode : "); Serial.println(m_presetMode); #endif }
c++
9
0.609665
59
22.434783
23
inline
// // RCHealthEvaluationResultHeader.h // AFNetworking // // Created by wtw on 2018/6/27. // #import @class RCHealthResultModel; @interface RCHealthEvaluationResultHeader : UIView @property (nonatomic,strong) RCHealthResultModel *model; @property (nonatomic,copy) void(^remeasureBlock)(void); @end
c
7
0.754658
56
17.941176
17
starcoderdata
<?php $__env->startSection('content'); ?> award-winning Downton Abbey producer's court appearance on a sexual assault charge was adjourned today due to his ill-health.  and television writer 39, is charged that on December 18 last year at various locations in Westminster, he sexually assaulted a female.  director and producer is also charged with assaulting the woman on the same day. producer  39, has been accused of sexually assaulting a woman at various places in the City of Westminster in December last year Croucher received two Emmy nominations for his work on series five and six of Downton Abbey Croucher graduated from Surrey Institute Of Art And Design in 2003 with a BA in Film &amp; TV Production and was a producer on TV shows The Halcyon, The Innocents and White Lines. his work on series five and six of Downton Abbey, he received two Emmy nominations and twice won the National Television Awards best drama prize.  Magistrates Court heard today that he had been diagnosed with cancer and went into hospital on July 20 for two weeks of in-patient treatment. case will return to court on September 28.  told district Judge 'I understand he has been diagnosed with cancer madam and has a large tumour and treatment has begun.' film and television writer has also worked as an assistant director with and on 2008 film The Other Boleyn Girl, which also stars has also worked as an assistant director with and on the 2008 film The Other Boleyn Girl. also has multiple credits as an assistant director, including The Oxford Murders, starring and hit movies Brick Lane and 28 Weeks Later.  also brought his directorial skills to hit TV shows Little Dorrit, Criminal Justice, Wallander, Silent Witness, Whitechapel, Silk and Broadchurch.  was also an assistant director on Wimbledon, starring and The Hitchhiker's Guide to the Galaxy, starring and 'Scoop'. <?php $__env->stopSection(); ?> <?php echo $__env->make('_layouts.post', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
php
12
0.757538
201
74.6875
32
starcoderdata
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; namespace Taobao.Pac.Sdk.Core.Dto { [XmlRoot("standardTemplateResult")] public class TemplatesDataDto { [JsonProperty("cpCode")] [XmlElement("cpCode")] public string CpCode { get; set; } [JsonProperty("standardTemplateDOs")] [XmlArray("standardTemplateDOs")] [XmlArrayItem("standardTemplateDO")] public List StandardTemplateDOs { get; set; } } }
c#
11
0.682131
74
24.304348
23
starcoderdata
<?php $pay_type_id=$this->uri->segment('5'); $company_id=$this->uri->segment('4'); ?> <label for="next" class="col-sm-5 control-label">Employee Group <div class="form-group" > <div class="col-sm-6" > <?php $pay_per_group=$this->payroll_lock_period_model->get_active_payroll_period_groups($company_id,$pay_type_id); if(!empty($pay_per_group)){ foreach($pay_per_group as $group){ ?> <table class="table table-bordered table-striped table-responsive"> <td align="center" ><?php echo $group->payroll_period_group_id?> <td align="center" ><?php echo $group->group_name?> <td align="center"><i class='fa fa-file-text fa-lg text-warning pull-center' data-toggle='tooltip' data-placement='left' title='VIEW' onclick="lock_period_table('<?php echo $group->payroll_period_group_id;?>')"> <?php }?><?php }else{ echo '<option disabled selected="">warning : Create "Group" First for selected pay-type } ?>
php
8
0.518405
241
38.515152
33
starcoderdata
<?php declare(strict_types=1); /** * 首页控制器 * * @package App\Http\Controller 控制器 * @link https://xinlianit.github.io/ * @author jirry * @datetime 2019/6/13 16:31 */ namespace App\Http\Controller; use App\Model\Logic\AppUserLogic; use swoft\base\Services; use Swoft\Http\Server\Annotation\Mapping\Controller; use Swoft\Http\Server\Annotation\Mapping\Middleware; use Swoft\Http\Server\Annotation\Mapping\Middlewares; use Swoft\Http\Server\Annotation\Mapping\RequestMapping; use Swoft\Http\Server\Annotation\Mapping\RequestMethod; /** * Class IndexController * @Controller(prefix="/index") * * @package App\Http\Controller */ class IndexController extends BaseController { /** * 首页 * @RequestMapping(route="index") * * @return \Swoft\Http\Message\Response */ public function index() { $algo = 'sha1'; $data = 'jirenyou'.time(); $key = ' $sign = hash_hmac($algo, $data, $key); $data = [ 'content' => 'Base 服务!', 'sha1_sign' => $sign, 'sha1_sign_len' => strlen($sign), 'request' => $_REQUEST ]; return $this->success($data); } }
php
13
0.607875
56
23.897959
49
starcoderdata
package com.utag.phase1.controller; import com.utag.phase1.domain.TagPart; import com.utag.phase1.service.Impl.TagPartServiceImpl; import com.utag.phase1.service.TagPartService; import com.utag.phase1.util.Response; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; import java.util.List; @RestController @RequestMapping("/workplace/part/") public class TagPartController { TagPartService tagPartService = new TagPartServiceImpl(); @RequestMapping(value = "/save", method = RequestMethod.POST) @ResponseBody public Response saveTagPart(String imageID, double x1, double x2, double y1, double y2, String description) throws IOException{ return tagPartService.saveTagPart(imageID, x1, x2, y1, y2, description); } @RequestMapping(value = "/show", method = RequestMethod.GET) @ResponseBody public Response showTagPart(String imageID) throws IOException{ return tagPartService.showTagPart(imageID); } @RequestMapping(value = "/delete", method = RequestMethod.DELETE) @ResponseBody public Response deleteTagPart(String imageID) throws IOException{ return tagPartService.deleteTagPart(imageID); } @RequestMapping(value = "/update", method = RequestMethod.PUT) @ResponseBody public Response updateTagPart(String imageID, double x1, double x2, double y1, double y2, String description) throws IOException{ return tagPartService.updateTagPart(imageID, x1, x2, y1, y2, description); } @RequestMapping(value = "/length", method = RequestMethod.GET) @ResponseBody public Response getDescriptionLength(String imageID, double x1, double x2, double y1, double y2) throws IOException{ return tagPartService.getDescriptionLength(imageID, x1, x2, y1, y2); } }
java
7
0.716359
113
38.206897
58
starcoderdata
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Http\Request; use Redirect, DB, Auth,File; use App\Libraries\InputSanitise; class ClientLoginActivity extends Model { protected $connection = 'mysql2'; public $timestamps = false; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['client_id','session_id','login_time','logout_time']; /** * add/update */ protected static function addOrUpdateClientLoginActivity($sessionId, $isUpdate = false){ $loginUser = Auth::guard('client')->user(); if(true == $isUpdate){ $activity = static::where('session_id',$sessionId)->where('client_id',$loginUser->id)->first(); $activity->logout_time = date('Y-m-d H:i:s'); } else { $activity = new static; $activity->login_time = date('Y-m-d H:i:s'); } $activity->client_id = $loginUser->id; $activity->session_id = $sessionId; $activity->save(); return $activity; } protected static function deleteClientLoginActivitiesByClientId($clientId){ $activities = static::where('client_id', $clientId)->get(); if(is_object($activities) && false == $activities->isEmpty()){ foreach($activities as $activity){ $activity->delete(); } } return; } }
php
15
0.599153
101
26.784314
51
starcoderdata
ZMatrix LookAtMatrix(const ZVector& eye, const ZVector& center, const ZVector& pseudoup) { // Look at gluLookAt for a reference for this ZVector forward = normalize(center-eye); ZVector right = normalize(cross(forward, pseudoup)); ZVector up = cross(right, forward); ZMatrix mat; mat[0] = right; mat[1] = up; mat[2] = -forward; mat[3] = ZVector(0.0f); mat = mat.Transpose(); //mat[3][3] = 1.f; //mat[3] = -eye; //mat = mat.Translate(-eye.v.f[0], -eye.v.f[1], -eye.v.f[2]); mat[3] = ZVector(dot(right, -eye), dot(up, -eye), dot(-forward, -eye), 1.0); return mat; }
c++
10
0.614876
88
24.391304
23
inline
from templeplus.pymod import PythonModifier from toee import * import tpdp import math #Swift Ambusher: Complete Scoundrel, p. 81 print "Registering Swift Ambusher" def SkirmishBonusLevels(attachee, args, evt_obj): rogueLevel = attachee.stat_level_get(stat_level_rogue) evt_obj.return_val += rogueLevel return 0 daringOutlaw = PythonModifier("Swift Ambusher", 2) # args are just-in-case placeholders daringOutlaw.MapToFeat("Swift Ambusher") daringOutlaw.AddHook(ET_OnD20PythonQuery, "Skrimish Level Bonus", SkirmishBonusLevels, ())
python
7
0.785321
90
27.684211
19
starcoderdata
const Manager = require("../lib/Manager"); describe("Manager class", () => { describe("Constructors", () => { it("should pass office number through arguments", () => { const office = 22; const input = new Manager("greenTshirt", 33, " office); expect(input.office).toEqual(office); }) }) describe("Methods", () => { it("should getOffice() retrieves office", () => { const office = 56; const input = new Manager("greenTshirt", 33, " office); expect(input.getOfficeNumber()).toEqual(office); }) it("shoula getRole() retrieves 'Manager'", () => { const role = "Manager"; const input = new Manager("greenTshirt", 333, " 22); expect(input.getRole()).toEqual(role); }) }) })
javascript
19
0.58283
70
24.875
32
starcoderdata
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.spring.integration.servicebus.inbound; import com.azure.core.util.BinaryData; import com.azure.messaging.servicebus.ServiceBusErrorContext; import com.azure.messaging.servicebus.ServiceBusMessage; import com.azure.messaging.servicebus.ServiceBusProcessorClient; import com.azure.messaging.servicebus.ServiceBusReceivedMessage; import com.azure.messaging.servicebus.ServiceBusReceivedMessageContext; import com.azure.spring.cloud.service.listener.MessageListener; import com.azure.spring.cloud.service.servicebus.consumer.ServiceBusErrorHandler; import com.azure.spring.cloud.service.servicebus.consumer.ServiceBusRecordMessageListener; import com.azure.spring.integration.core.implementation.instrumentation.DefaultInstrumentationManager; import com.azure.spring.integration.core.instrumentation.Instrumentation; import com.azure.spring.integration.servicebus.implementation.health.ServiceBusProcessorInstrumentation; import com.azure.spring.messaging.ListenerMode; import com.azure.spring.messaging.converter.AbstractAzureMessageConverter; import com.azure.spring.messaging.servicebus.core.ServiceBusProcessorFactory; import com.azure.spring.messaging.servicebus.core.listener.ServiceBusMessageListenerContainer; import com.azure.spring.messaging.servicebus.core.properties.ServiceBusContainerProperties; import com.azure.spring.messaging.servicebus.support.converter.ServiceBusMessageConverter; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.Message; import java.time.Duration; import java.util.Arrays; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static com.azure.spring.integration.core.instrumentation.Instrumentation.Type.CONSUMER; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class ServiceBusInboundChannelAdapterTests { private ServiceBusInboundChannelAdapter adapter; private ServiceBusProcessorFactory processorFactory; private ServiceBusContainerProperties containerProperties; protected String subscription = "group"; protected String destination = "dest"; private String[] payloads = { "payload1", "payload2" }; private List messages = Arrays.stream(payloads) .map(p -> MessageBuilder.withPayload(p).build()) .collect(Collectors.toList()); @BeforeEach public void setUp() { this.processorFactory = mock(ServiceBusProcessorFactory.class); when(processorFactory.createProcessor(eq(destination), eq(subscription), isA(ServiceBusContainerProperties.class))).thenReturn(mock(ServiceBusProcessorClient.class)); this.containerProperties = new ServiceBusContainerProperties(); containerProperties.setEntityName(destination); containerProperties.setSubscriptionName(subscription); this.adapter = new ServiceBusInboundChannelAdapter( new ServiceBusMessageListenerContainer(processorFactory, containerProperties)); } @Test void defaultRecordListenerMode() { ServiceBusInboundChannelAdapter channelAdapter = new ServiceBusInboundChannelAdapter( new ServiceBusMessageListenerContainer(this.processorFactory, this.containerProperties)); assertThat(channelAdapter).hasFieldOrPropertyWithValue("listenerMode", ListenerMode.RECORD); } @Test void batchListenerModeDoesNotSupport() { ServiceBusInboundChannelAdapter channelAdapter = new ServiceBusInboundChannelAdapter( new ServiceBusMessageListenerContainer(this.processorFactory, this.containerProperties), ListenerMode.BATCH); assertThrows(IllegalStateException.class, channelAdapter::onInit, "Only record mode is supported!"); } @Test void setInstrumentationManager() { DefaultInstrumentationManager instrumentationManager = new DefaultInstrumentationManager(); this.adapter.setInstrumentationManager(instrumentationManager); assertThat(this.adapter).hasFieldOrPropertyWithValue("instrumentationManager", instrumentationManager); } @Test void setInstrumentationId() { String instrumentationId = "testId"; this.adapter.setInstrumentationId(instrumentationId); assertThat(this.adapter).hasFieldOrPropertyWithValue("instrumentationId", instrumentationId); } @Test void setMessageConverter() { AbstractAzureMessageConverter<ServiceBusReceivedMessage, ServiceBusMessage> converter = mock(ServiceBusMessageConverter.class); this.adapter.setMessageConverter(converter); assertThat(this.adapter).extracting("recordListener").extracting("messageConverter").isEqualTo(converter); } @Test void setPayloadType() { this.adapter.afterPropertiesSet(); assertThat(this.adapter).extracting("recordListener").extracting("payloadType").isEqualTo(byte[].class); this.adapter.setPayloadType(Long.class); this.adapter.afterPropertiesSet(); assertThat(this.adapter).extracting("recordListener").extracting("payloadType").isEqualTo(Long.class); } @Test void sendAndReceive() throws InterruptedException { ServiceBusMessageListenerContainer listenerContainer = new ServiceBusMessageListenerContainer(this.processorFactory, this.containerProperties); ServiceBusInboundChannelAdapter channelAdapter = new ServiceBusInboundChannelAdapter(listenerContainer); DirectChannel channel = new DirectChannel(); channel.setBeanName("output"); final CountDownLatch latch = new CountDownLatch(1); final List receivedMessages = new CopyOnWriteArrayList<>(); channel.subscribe(message -> { try { receivedMessages.add(new String((byte[]) message.getPayload())); } finally { latch.countDown(); } }); channelAdapter.setOutputChannel(channel); channelAdapter.onInit(); channelAdapter.doStart(); MessageListener messageListener = listenerContainer.getContainerProperties().getMessageListener(); assertTrue(messageListener instanceof ServiceBusRecordMessageListener); List payloads = Arrays.asList("a", "b", "c"); payloads.stream() .map(payload -> { ServiceBusReceivedMessageContext mock = mock(ServiceBusReceivedMessageContext.class); ServiceBusReceivedMessage message = mock(ServiceBusReceivedMessage.class); when(message.getBody()).thenReturn(BinaryData.fromString(payload)); when(mock.getMessage()).thenReturn(message); return mock; }) .forEach(context -> ((ServiceBusRecordMessageListener) messageListener).onMessage(context)); assertTrue(latch.await(5L, TimeUnit.SECONDS), "Failed to receive message"); for (int i = 0; i < receivedMessages.size(); i++) { Assertions.assertEquals(receivedMessages.get(i), payloads.get(i)); } } @Test void instrumentationErrorHandler() { DefaultInstrumentationManager instrumentationManager = new DefaultInstrumentationManager(); ServiceBusMessageListenerContainer listenerContainer = new ServiceBusMessageListenerContainer(this.processorFactory, this.containerProperties); ServiceBusInboundChannelAdapter channelAdapter = new ServiceBusInboundChannelAdapter(listenerContainer); String instrumentationId = CONSUMER + ":" + destination; ServiceBusProcessorInstrumentation processorInstrumentation = new ServiceBusProcessorInstrumentation( destination, CONSUMER, Duration.ofMinutes(1)); instrumentationManager.addHealthInstrumentation(processorInstrumentation); processorInstrumentation.setStatus(Instrumentation.Status.UP); assertEquals(Instrumentation.Status.UP, processorInstrumentation.getStatus()); channelAdapter.setInstrumentationId(instrumentationId); channelAdapter.setInstrumentationManager(instrumentationManager); channelAdapter.onInit(); channelAdapter.doStart(); ServiceBusErrorHandler errorHandler = listenerContainer.getContainerProperties().getErrorHandler(); ServiceBusErrorContext errorContext = mock(ServiceBusErrorContext.class); when(errorContext.getException()).thenReturn(new IllegalArgumentException("test")); when(errorContext.getEntityPath()).thenReturn("entity-path"); errorHandler.accept(errorContext); Instrumentation healthInstrumentation = instrumentationManager.getHealthInstrumentation(instrumentationId); assertEquals(Instrumentation.Status.DOWN, healthInstrumentation.getStatus()); assertEquals(healthInstrumentation.getException().getClass(), IllegalArgumentException.class); assertEquals(healthInstrumentation.getException().getMessage(), "test"); } }
java
20
0.75663
174
48.02
200
starcoderdata
using System; public class SimpleMathExam : Exam { private const int MinProblemsSolved = 0; private const int MaxProblemsSolved = 10; private const int AverageProblemsSolved = 5; private const int WorstGrade = 2; private const int AverageGrade = 4; private const int BestGrade = 6; private int problemsSolved; public SimpleMathExam(int problemsSolved) { this.ProblemsSolved = problemsSolved; } public int ProblemsSolved { get { return this.problemsSolved; } private set { if (value < SimpleMathExam.MinProblemsSolved || value > SimpleMathExam.MaxProblemsSolved) { throw new ArgumentOutOfRangeException(string.Format("problemsSolved must be in the range [{0}:{1}]", this.GetType(), MinProblemsSolved, MaxProblemsSolved)); } this.problemsSolved = value; } } public override ExamResult Check() { if (this.ProblemsSolved == SimpleMathExam.MinProblemsSolved) { return new ExamResult(SimpleMathExam.WorstGrade, SimpleMathExam.WorstGrade, SimpleMathExam.BestGrade, "Bad result: nothing done."); } else if (this.ProblemsSolved <= SimpleMathExam.AverageProblemsSolved) { return new ExamResult(SimpleMathExam.AverageGrade, SimpleMathExam.WorstGrade, SimpleMathExam.BestGrade, "Average result: good."); } else { return new ExamResult(SimpleMathExam.BestGrade, SimpleMathExam.WorstGrade, SimpleMathExam.BestGrade, "Very good result: well done."); } } }
c#
19
0.641487
172
31.076923
52
starcoderdata
/* * Licensed to the Sakai Foundation (SF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The SF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.sakaiproject.nakamura.workflow.persistence; import org.drools.KnowledgeBase; import org.drools.marshalling.Marshaller; import org.drools.marshalling.MarshallerFactory; import org.drools.marshalling.ObjectMarshallingStrategy; import org.drools.runtime.Environment; import org.drools.runtime.EnvironmentName; import org.drools.runtime.KnowledgeSessionConfiguration; import org.drools.runtime.StatefulKnowledgeSession; import org.sakaiproject.nakamura.api.workflow.WorkflowConstants; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Date; import javax.jcr.Binary; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.jcr.Session; public class SessionInfo extends AbstractIdBasedObject { private Date startDate; private Date lastModificationDate; private byte[] rulesByteArray; private byte[] rulesByteArrayShadow; private transient StatefulKnowledgeSession statefulKnowledgeSession; private boolean dirty; private KnowledgeBase kbase; private KnowledgeSessionConfiguration conf; private Environment env; private Marshaller marshaller; public SessionInfo(Session session, StatefulKnowledgeSession ksession, KnowledgeSessionConfiguration conf) throws PathNotFoundException, RepositoryException, IOException { super(session, ksession.getId()); this.statefulKnowledgeSession = ksession; this.kbase = ksession.getKnowledgeBase(); this.conf = conf; this.env = ksession.getEnvironment(); ObjectMarshallingStrategy[] strategies = (ObjectMarshallingStrategy[]) this.env .get(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES); if (strategies != null) { // use strategies if provided in the environment this.marshaller = MarshallerFactory.newMarshaller(kbase, strategies); } else { this.marshaller = MarshallerFactory.newMarshaller(kbase); } } public SessionInfo(Session session, KnowledgeBase kbase, KnowledgeSessionConfiguration conf, Environment env) throws RepositoryException, IOException { this(session, -1, kbase, conf, env); } public SessionInfo(Session session, int sessionId, KnowledgeBase kbase, KnowledgeSessionConfiguration conf, Environment env) throws RepositoryException, IOException { super(session, sessionId); this.kbase = kbase; this.conf = conf; this.env = env; ObjectMarshallingStrategy[] strategies = (ObjectMarshallingStrategy[]) env .get(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES); if (strategies != null) { // use strategies if provided in the environment this.marshaller = MarshallerFactory.newMarshaller(kbase, strategies); } else { this.marshaller = MarshallerFactory.newMarshaller(kbase); } this.startDate = new Date(); } public Date getStartDate() { return this.startDate; } public Date getLastModificationDate() { return this.lastModificationDate; } public StatefulKnowledgeSession getStatefulKnowledgeSession() throws IOException, ClassNotFoundException { if (dirty || statefulKnowledgeSession == null) { ByteArrayInputStream bais = new ByteArrayInputStream(rulesByteArray); if (statefulKnowledgeSession == null) { statefulKnowledgeSession = marshaller.unmarshall(bais, this.conf, this.env); } else { marshaller.unmarshall(bais, statefulKnowledgeSession); } dirty = false; } return statefulKnowledgeSession; } /** * Update the session info object from the session. * * @throws RepositoryException * @throws IOException */ public void update() throws RepositoryException, IOException { // we always increase the last modification date for each action, so we know there // will be an update ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { marshaller.marshall(baos, statefulKnowledgeSession); } catch (IOException e) { throw new RuntimeException("Unable to get session snapshot", e); } byte[] newByteArray = baos.toByteArray(); if (!Arrays.equals(newByteArray, this.rulesByteArray)) { lastModificationDate = new Date(); rulesByteArray = newByteArray; } rulesByteArrayShadow = this.rulesByteArray; } /** * Save the session info to jcr. * * @throws RepositoryException * @throws IOException * */ public void save() throws RepositoryException, IOException { update(); if (!Arrays.equals(this.rulesByteArrayShadow, this.rulesByteArray)) { setProperty(rulesByteArray); if (session.hasPendingChanges()) { session.save(); } lastModificationDate = new Date(); rulesByteArrayShadow = rulesByteArray; } } /** * {@inheritDoc} * * @see org.sakaiproject.nakamura.workflow.persistence.AbstractIdBasedObject#load() */ @Override public void load() throws RepositoryException, IOException { byte[] newByteArray = getByteArray(new byte[0]); if (!Arrays.equals(newByteArray, this.rulesByteArray)) { lastModificationDate = new Date(); rulesByteArray = newByteArray; } rulesByteArrayShadow = this.rulesByteArray; dirty = true; } /** * {@inheritDoc} * * @throws RepositoryException * @see org.sakaiproject.nakamura.workflow.persistence.AbstractIdBasedObject#createContentNode() */ @Override protected Node createContentNode(Node parentNode, String nodeName) throws RepositoryException { Node newObjectNode = parentNode.addNode(nodeName, "nt:file"); Node contentNode = newObjectNode.addNode("jcr:content", "nt:resource"); Binary value = contentNode.getSession().getValueFactory().createBinary( new ByteArrayInputStream(new byte[0])); contentNode.setProperty("jcr:data", value); return newObjectNode; } /** * {@inheritDoc} * * @see org.sakaiproject.nakamura.workflow.persistence.AbstractIdBasedObject#getStoragePrefix() */ @Override protected String getStoragePrefix() { return WorkflowConstants.SESSION_STORAGE_PREFIX; } }
java
14
0.732876
108
32.3
210
starcoderdata
#include "./render-batch.hpp" #include #include #include #include #include #include #include #include namespace bembel::gui { RenderBatch::RenderBatch() { } RenderBatch::~RenderBatch() { } void setupVertexAttribute(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei offset) { glEnableVertexAttribArray(index); glVertexAttribPointer(index, size, type, normalized, sizeof(InstanceData), (void*)(offset)); glVertexAttribDivisor(index, 1); } void RenderBatch::init() { glGenVertexArrays(1, &(this->vao)); glBindVertexArray(this->vao); glGenBuffers(1, &(this->vbo)); glBindBuffer(GL_ARRAY_BUFFER, this->vbo); // Positions 4*sizeof(GL_FLOAT) = 16 Byte setupVertexAttribute(0, 4, GL_FLOAT, GL_FALSE, 0); // TexCoords 4*sizeof(GL_UNSIGNED_SHORT) = 8 Byte setupVertexAttribute(1, 4, GL_UNSIGNED_SHORT, GL_TRUE, 16); // color 4*sizeof(GL_UNSIGNED_SHORT) = 4 Byte setupVertexAttribute(2, 4, GL_UNSIGNED_BYTE, GL_TRUE, 16 + 8); // additional data 4*sizeof(GL_UNSIGNED_SHORT) = 4 Byte setupVertexAttribute(3, 4, GL_UNSIGNED_BYTE, GL_FALSE, 16 + 8 + 4); } void RenderBatch::setPositionOffset(const glm::vec2& position_offset) { this->position_offset = position_offset; } void RenderBatch::setDrawArea(const glm::vec2& min, const glm::vec2& max) { this->draw_area_min = min; this->draw_area_max = max; } void RenderBatch::setColor(const glm::tvec4 color) { this->color = color; } void RenderBatch::draw() { if(this->instances.empty()) return; glBindBuffer(GL_ARRAY_BUFFER, this->vbo); // resize buffer if nececary std::size_t required_buffer_size = sizeof(InstanceData) * this->instances.size(); if(required_buffer_size > this->buffer_size) { this->buffer_size = std::max(2 * this->buffer_size, required_buffer_size * 3 / 2); glBufferData(GL_ARRAY_BUFFER, this->buffer_size, nullptr, GL_STREAM_DRAW); } // upload data glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(InstanceData) * this->instances.size(), &(this->instances[0])); glBindBuffer(GL_ARRAY_BUFFER, 0); // draw instances glBindVertexArray(this->vao); glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, this->instances.size()); // clear data this->instances.clear(); } void RenderBatch::drawRectangle(glm::vec2 min, glm::vec2 max) { min += this->position_offset; max += this->position_offset; min = glm::max(this->draw_area_min, min); max = glm::min(this->draw_area_max, max); if(max.x <= min.x || max.y <= min.y) { return; // outside of draw area } this->darwElement(min, max, {0.0f, 0.0f}, {1.0f, 1.0f}, InstanceType::RECTANGLE); } void RenderBatch::drawIcon(glm::vec2 min, glm::vec2 max, glm::vec2 tex_coords_min, glm::vec2 tex_coords_max) { min += this->position_offset; max += this->position_offset; if(!clampToViewArea(min, max, tex_coords_min, tex_coords_max)) { return; } this->darwElement(min, max, tex_coords_min, tex_coords_max, InstanceType::ICON); } /* void RenderBatch::drawText(const kernel::TextLayout& text, glm::vec2 pos, float scale) { auto font = text.getFont(); if(!font) return; for(const auto& glyph : text.getGlyphs()) { auto extends = font->getGlyphExtents(glyph.id); auto tex_coords = font->getGlyphTexCoord(glyph.id); glm::vec2 p = pos + scale * glyph.pos; drawGlyph( {p.x + scale * extends.x, p.y + scale * extends.z}, {p.x + scale * extends.y, p.y + scale * extends.w}, {tex_coords.x, tex_coords.z}, {tex_coords.y, tex_coords.w}); } } //*/ void RenderBatch::drawGlyph( const kernel::Font::Glyph& glyph, const glm::vec2& pos, float scale, float threshold_min, float threshold_max) { glm::vec2 min = glyph.extents_min * scale + pos + this->position_offset; glm::vec2 max = glyph.extents_max * scale + pos + this->position_offset; glm::vec2 tc_min = glyph.tex_coords_min; glm::vec2 tc_max = glyph.tex_coords_max; if(!clampToViewArea(min, max, tc_min, tc_max)) return; this->darwElement( min, max, tc_min, tc_max, InstanceType::GLYPH, uint8_t(threshold_min * 0xff), uint8_t(threshold_max * 0xff)); } bool RenderBatch::clampToViewArea( glm::vec2& min, glm::vec2& max, glm::vec2& tex_coords_min, glm::vec2& tex_coords_max) { if(max.x <= this->draw_area_min.x || min.x >= this->draw_area_max.x || max.y <= this->draw_area_min.y || min.y >= this->draw_area_max.y) { return false; // outside of draw area } // clamp lower bounds auto scale = (tex_coords_max - tex_coords_min) / (max - min); if(min.x < this->draw_area_min.x) { tex_coords_min.x -= (min.x - this->draw_area_min.x) * scale.x; min.x = this->draw_area_min.x; } if(min.y < this->draw_area_min.y) { tex_coords_min.y -= (min.y - this->draw_area_min.y) * scale.y; min.y = this->draw_area_min.y; } // upper if(max.x > this->draw_area_max.x) { tex_coords_max.x -= (max.x - this->draw_area_max.x) * scale.x; max.x = this->draw_area_max.x; } if(max.y > this->draw_area_max.y) { tex_coords_max.y -= (max.y - this->draw_area_max.y) * scale.y; max.y = this->draw_area_max.y; } return true; } } // namespace bembel::gui
c++
14
0.634976
117
34.801242
161
starcoderdata
package eBayPrep; public class _079WordSearch { public static void main(String[] args) { System.out.println(exist(new char[][]{ {'A','B','C','E'}, {'S','F','C','S'}, {'A','D','E','E'}},"ABCCED")); System.out.println(exist(new char[][]{ {'A','B','C','E'}, {'S','F','C','S'}, {'A','D','E','E'}},"SEE")); System.out.println(exist(new char[][]{ {'A','B','C','E'}, {'S','F','C','S'}, {'A','D','E','E'}},"ABCB")); System.out.println(exist(new char[][]{ {'A','A'}},"AA")); System.out.println(exist(new char[][]{ {'A','B','C','E'}, {'S','F','E','S'}, {'A','D','E','E'}},"ABCESEEEFS")); } public static boolean exist(char[][] board, String word) { for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if(board[i][j]==word.charAt(0)) { if(wordExists(i,j,board,word,0)) return true; } } } return false; } private static boolean wordExists(int i, int j, char[][] board, String word,int stringIndex) { if(i ||word.charAt(stringIndex)!=board[i][j]) { return false; } if(word.charAt(stringIndex)==board[i][j] && stringIndex==word.length()-1) return true; char temp=board[i][j]; board[i][j]='#'; if (wordExists(i+1, j, board, word,stringIndex+1)||wordExists(i-1, j, board, word,stringIndex+1) ||wordExists(i, j+1, board, word,stringIndex+1)||wordExists(i, j-1, board, word,stringIndex+1)) return true; board[i][j]=temp; return false; } }
java
15
0.550464
99
25.916667
60
starcoderdata
package springdemo; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component("theTennisCoach") @Scope("singleton") public class TennisCoach implements Coach { @Override public String getDailyWorkout() { return "Practice your backhand"; } @PostConstruct void atCreation() { System.out.println("At the time of creation!!!"); } @PreDestroy void atDestruction() { System.out.println("At the time of Destruction!!!"); } }
java
9
0.762324
54
21.72
25
starcoderdata
Image/ImagemFX/src/imagemfx/FXMLDocumentController.java /* * 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 imagemfx; import java.awt.image.BufferedImage; import java.awt.image.WritableRaster; import java.io.File; import java.net.URL; import java.util.ResourceBundle; import javafx.embed.swing.SwingFXUtils; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.stage.FileChooser; /** * * @author irineualmeidajunior */ public class FXMLDocumentController implements Initializable { @FXML private ImageView imageView; private Image image; private BufferedImage bimage; @Override public void initialize(URL url, ResourceBundle rb) { // TODO } @FXML private void evtAbrir(ActionEvent event) { FileChooser fileChooser = new FileChooser(); fileChooser.setInitialDirectory(new File("/Users/irineualmeidajunior")); fileChooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("JPEG Files", "*.jpg"), new FileChooser.ExtensionFilter("PNG Files", "*.png")); File file = fileChooser.showOpenDialog(null); if(file != null) { image = new Image(file.toURI().toString()); imageView.setFitHeight(image.getHeight()); imageView.setFitWidth(image.getWidth()); imageView.setImage(image); } } @FXML private void evtSalvar(ActionEvent event) { } @FXML private void evtSalvarComo(ActionEvent event) { } @FXML private void evtFechar(ActionEvent event) { } @FXML private void evtSair(ActionEvent event) { } @FXML private void evtTonsCinza(ActionEvent event) { int media; if(image != null) { bimage = SwingFXUtils.fromFXImage(image, bimage); int pixel[] = {0, 0 ,0 ,0}; WritableRaster raster = bimage.getRaster(); for(int y=0; y < image.getHeight(); y++) { for(int x=0; x < image.getWidth(); x++) { raster.getPixel(x, y, pixel); // As posições do vetor é RGB, R[0], G[1], B[2], ai multiplico, só que ele sai //em valor floar, mas como eu uso inteiro, faço um casting para inteiro. media = (int)(pixel[0] * 0.3 + pixel[1] *0.59 + pixel[2] * 0.11) / 3; pixel[0] = pixel[1] = pixel[2] = media; raster.setPixel(x, y, pixel); } } image = SwingFXUtils.toFXImage(bimage, null); imageView.setImage(image); } } @FXML private void evtSobre(ActionEvent event) { } @FXML private void evtPretoBranco(ActionEvent event) { // Fazer aqui como no converter para Tons de Cinza só que em Preto e Branco, para //isso fazer uma média, ao exemplo, maior que 150 coloco Preto, menor que esse valor //eu coloco Branco. // Então eu posso utilizar essa média para definir se será preto ou branco pixel } }
java
18
0.61312
99
30.181818
110
starcoderdata
import sys, os import numpy as np from Config import Configuration class PairwiseAAindex(Configuration): ''' This class deals with AAIndex pairwise potentials and makes easy to get the aaIndex potential involving 2 amino acids by giving their one letter code ''' badValue= 1024 def __init__(self, data_path= None): ''' @param data_path: str: Path where AAIndex files are located ''' Configuration.__init__(self) # Load configuration parameters such as path to programs self.protein_proteinIndexes=["KESO980101","KESO980102","MOOG990101"] if data_path is None: self.data_path= self.AAindexPath else: self.data_path=data_path self.data=self.load() def load(self): ''' loads all aaIndex potentials contained in self.protein_proteinIndexes and returns them as a dictionary return res: Dict. res[aaCodeL][aaCodeR]= [pot0, pot1 ...] ''' res={} for indexName in self.protein_proteinIndexes: fname=os.path.join(self.data_path,indexName) fname= os.path.realpath(fname) f=open(fname) aaTypes=f.readline() aaTypes=aaTypes.split()[1] aaTypes=list(aaTypes) for iLetter,line in zip(aaTypes,f): lineArray= line.split() if iLetter not in res: res[iLetter]={} for jLetter,score in zip(aaTypes,lineArray): if jLetter not in res[iLetter]: res[iLetter][jLetter]=[] res[iLetter][jLetter].append(float(score)) f.close() return res def getScore(self,aa1,aa2): ''' given aa1 and aa2, that are one letter amino acid codes, return the associated aaIndex values. @param aa1: str. one letter amino acid code @param aa2: str. one letter amino acid code @return self.data[aa1][aa2]: list containing the associated values ''' try: values = self.data[aa1][aa2] except KeyError: # print ("Non standard aa") values= [PairwiseAAindex.BadValue for i in xrange(len(self.protein_proteinIndexes))] return values def addAAIndexToDF(self, df): ''' adds to a pandas.DataFrame that represents amino acid pairs codification, new columns added using the aaIndex values. @param df: pandas.DataFrame. A pandas.Dataframe in which each row represents a pair of amino acids in direct form (L to R). Column names are: 'chainIdL', 'structResIdL', 'resNameL', 'chainIdR', 'structResIdR', 'resNameR', 'categ' ... [propertiesP .... propertiesL .... propertiesR] #no defined order for properties @return df: pandas.DataFrame. The same pandas.DataFrame given as input but with new columns added whose name is "aaIndex%d"%i ''' getScore= self.getScore nPots= len(self.protein_proteinIndexes) resNames= zip(df["resNameL"],df["resNameR"]) scoresNp= np.zeros((df.shape[0], 3)) for i in range(df.shape[0]): scoresNp[i,:]= getScore( *resNames[i]) for i in range(nPots): df.loc[:,"aaIndex%d_P"%i]= scoresNp[:, i] return df if __name__== "__main__": mapa=PairwiseAAindex().data print mapa["F"]["S"]
python
17
0.629573
107
33.606383
94
starcoderdata
describe('Redirect', function () { it('visit', function () { cy.visit('http://0.0.0.0:4000/foo') cy.location().should((loc) => { expect(loc.toString()).to.eq('http://0.0.0.0:4000/') }) cy.get('#app').should('have.length', 1) cy.get('#foo').should('have.length', 1) cy.get('.p1').should('contain', 'Foo') cy.get('.go-to-bar').should('contain', 'Go to bar') // Go to bar and redirect to baz cy.get('.go-to-bar').click() cy.location().should((loc) => { expect(loc.toString()).to.eq('http://0.0.0.0:4000/baz') }) cy.get('.p3').should('contain', 'Baz') }) })
javascript
24
0.541063
61
28.571429
21
starcoderdata
<?php namespace App\Http\Livewire; use App\Models\Product; use App\Models\ProductCategory; use Livewire\Component; class ProductList extends Component { use TracksCurrency, TracksSearch, InteractsWithCurrentCart; public bool $productWasAdded = false; public ?Product $productThatWasAdded = null; public ?string $category = null; protected $listeners = [ SearchSelect::EVENT_SELECTED => 'selectCategory' ]; public function getCategoriesProperty() { return ProductCategory::query() ->pluck('name') ->all(); } public function selectCategory($category) { $this->category = $category; } public function addProductToCart(int $productId) { $product = $this->addToCart($productId); $this->productWasAdded = true; $this->productThatWasAdded = $product; } public function indexQuery() { return Product::with('latestPrice') ->where('stock', '>', 0) ->when( filled($this->category), fn ($query) => $query->whereHas( 'category', fn ($category) => $category->where('name', $this->category) ) ); } public function searchQuery() { return Product::with('latestPrice') ->search($this->search); } public function render() { return view( 'livewire.product-list', [ 'products' => filled($this->search) ? $this->searchQuery()->paginate() : $this->indexQuery()->paginate(), ] ) ->layout('layouts.guest'); } }
php
19
0.545149
79
23.094595
74
starcoderdata
<?php $page_title = 'View the Current Users'; include('includes/header.html'); ?> <div class = "col-sm-10"> Users protect user privacy, we no longer display user information <?php include('includes/footer.html'); exit(); require('includes/pagination_functions.inc.php'); // Get pagination functions echo "<div class = 'search-container'>"; echo "<input placeholder = \"Search...\" type=\"search\" id=\"site-search\" name=\"q\" aria-label=\"Search through site content\" onkeydown = \"loadUserSearch(this.value)\">"; // echo "<button onclick = \"appendViewUsersQuery()\" type=\"submit\">Search echo "<button onclick = \"window.location.reload()\">X echo " define('DISPLAY', 20); // Number of records to show per page $pages = getPagesValue('id', 'users'); $start = getStartValue(); list($sort, $order_by, $direction, $order_in) = getSortValue('users'); define('UPARR', '<a href = "../view_users?sort='. $sort . '&dirtn=do">&#x25B2; define('DOWNARR', '<a href = "../view_users?sort=' . $sort . '&dirtn=up">&#x25BC; define('ARR', $direction == 'do' ? DOWNARR : UPARR); define('LNARR', isset($_GET['sort']) && $_GET['sort'] == 'ln' ? ARR : ''); define('FNARR', isset($_GET['sort']) && $_GET['sort'] == 'fn' ? ARR : ''); define('RDARR', isset($_GET['sort']) && $_GET['sort'] == 'rd' ? ARR : ''); $q = 'SELECT last_name, first_name, DATE_FORMAT(registration_date, \'%M %d, %Y\') AS dr, id FROM users'; $result = performPaginationQuery($dbc, $q, $order_by, $start); // Table header $adminControls = ISADMIN ? '<th align = "left"> <th align = "left"> : ''; echo '<table id = "users-table" width = "100%"> $adminControls . ' <th align = "left"> Profile <th align = "left"> href = "view_users?sort=ln">Last Name <th align = "left"> href = "view_users?sort=fn">First Name <th align = "left"> href = "view_users?sort=rd">Date Registered <tbody id = "users-body"> '; // Fetch and print all the records $bg = 'one'; // Set the initial background color while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { // Loop through the records in an associative array $bg = ($bg == 'one' ? 'two' : 'one'); // Switch the background color every row $adminControls = ISADMIN ? ' <td class = "links ' . $bg . '" align = "left"><a href = "pages/edit_user.php?id=' . $row['id'] . '">Edit <td class = "links ' . $bg . '" align = "left"><a href = "pages/delete_user.php?id=' . $row['id'] . '">Delete : ''; echo ' . $adminControls . ' <td class = "links ' . $bg . '" align = "left"><a href = "users/' . $row['id'] . '">View Profile <td class = "output ' . $bg . '" align = "left">' . $row['last_name'] . ' <td class = "output ' . $bg . '" align = "left">' . $row['first_name'] . ' <td class = "output ' . $bg . '" align = "left">' . $row['dr'] . ' '; } echo ' mysqli_free_result ($result); mysqli_close($dbc); // Make the links to other pages, if necessary setPreviousAndNextLinks('view_users'); include('includes/footer.html'); ?>
php
23
0.6035
126
36.235955
89
starcoderdata
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Diagnostics.Monitoring.TestCommon; using Microsoft.Diagnostics.Monitoring.TestCommon.Runners; using Microsoft.Diagnostics.Tools.Monitor; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Microsoft.Diagnostics.Monitoring.Tool.FunctionalTests.Runners { partial class MonitorCollectRunner { private readonly ConcurrentDictionary<CollectionRuleKey, List _collectionRuleCallbacks = new(); private readonly ConcurrentDictionary<int, List _eventCallbacks = new(); public Task WaitForCollectionRuleActionsCompletedAsync(string ruleName, CancellationToken token) { return WaitForCollectionRuleEventAsync(LoggingEventIds.CollectionRuleActionsCompleted.Id(), ruleName, token); } public Task WaitForCollectionRuleCompleteAsync(string ruleName, CancellationToken token) { return WaitForCollectionRuleEventAsync(LoggingEventIds.CollectionRuleCompleted.Id(), ruleName, token); } public Task WaitForCollectionRuleUnmatchedFiltersAsync(string ruleName, CancellationToken token) { return WaitForCollectionRuleEventAsync(LoggingEventIds.CollectionRuleUnmatchedFilters.Id(), ruleName, token); } public Task WaitForCollectionRuleStartedAsync(string ruleName, CancellationToken token) { return WaitForCollectionRuleEventAsync(LoggingEventIds.CollectionRuleStarted.Id(), ruleName, token); } public Task WaitForCollectionRulesStoppedAsync(CancellationToken token) { return WaitForEventAsync(LoggingEventIds.CollectionRulesStopped.Id(), token); } private async Task WaitForCollectionRuleEventAsync(int eventId, string ruleName, CancellationToken token) { TaskCompletionSource tcs = new(TaskCreationOptions.RunContinuationsAsynchronously); CollectionRuleKey eventKey = new(eventId, ruleName); CollectionRuleKey failedKey = new(LoggingEventIds.CollectionRuleFailed.Id(), ruleName); AddCollectionRuleCallback(eventKey, tcs); AddCollectionRuleCallback(failedKey, tcs); try { await tcs.WithCancellation(token); } finally { RemoveCollectionRuleCallback(eventKey, tcs); RemoveCollectionRuleCallback(failedKey, tcs); } } private async Task WaitForEventAsync(int eventId, CancellationToken token) { TaskCompletionSource tcs = new(TaskCreationOptions.RunContinuationsAsynchronously); AddEventCallback(eventId, tcs); try { await tcs.WithCancellation(token); } finally { RemoveEventCallback(eventId, tcs); } } private void HandleCollectionRuleEvent(ConsoleLogEvent logEvent) { if (logEvent.State.TryGetValue("ruleName", out string ruleName)) { CollectionRuleKey key = new(logEvent.EventId, ruleName); switch ((LoggingEventIds)logEvent.EventId) { case LoggingEventIds.CollectionRuleActionsCompleted: case LoggingEventIds.CollectionRuleCompleted: case LoggingEventIds.CollectionRuleUnmatchedFilters: case LoggingEventIds.CollectionRuleStarted: CompleteCollectionRuleCallbacks(key); break; case LoggingEventIds.CollectionRuleFailed: FailCollectionRuleCallbacks(key, logEvent.Exception); break; } } else { switch ((LoggingEventIds)logEvent.EventId) { case LoggingEventIds.CollectionRulesStopped: CompleteEventCallbacks(logEvent.EventId); break; } } } private List GetCollectionRuleCompletionSources(CollectionRuleKey key) { return _collectionRuleCallbacks.GetOrAdd(key, _ => new List } private List GetEventCompletionSources(int eventId) { return _eventCallbacks.GetOrAdd(eventId, _ => new List } private void AddCollectionRuleCallback(CollectionRuleKey key, TaskCompletionSource completionSource) { List completionSources = GetCollectionRuleCompletionSources(key); lock (completionSources) { completionSources.Add(completionSource); } } private void AddEventCallback(int eventId, TaskCompletionSource completionSource) { List completionSources = GetEventCompletionSources(eventId); lock (completionSources) { completionSources.Add(completionSource); } } private void RemoveCollectionRuleCallback(CollectionRuleKey key, TaskCompletionSource completionSource) { List completionSources = GetCollectionRuleCompletionSources(key); lock (completionSources) { completionSources.Remove(completionSource); } } private void RemoveEventCallback(int eventId, TaskCompletionSource completionSource) { List completionSources = GetEventCompletionSources(eventId); lock (completionSources) { completionSources.Remove(completionSource); } } private void CompleteCollectionRuleCallbacks(CollectionRuleKey key) { List completionSources = GetCollectionRuleCompletionSources(key); lock (completionSources) { foreach (TaskCompletionSource completionSource in completionSources) { completionSource.TrySetResult(null); } } } private void CompleteEventCallbacks(int eventId) { List completionSources = GetEventCompletionSources(eventId); lock (completionSources) { foreach (TaskCompletionSource completionSource in completionSources) { completionSource.TrySetResult(null); } } } private void FailCollectionRuleCallbacks(CollectionRuleKey key, string message) { List completionSources = GetCollectionRuleCompletionSources(key); InvalidOperationException ex = new InvalidOperationException(message); lock (completionSources) { foreach (TaskCompletionSource completionSource in completionSources) { completionSource.TrySetException(ex); } } } private struct CollectionRuleKey : IEquatable { private readonly int _eventId; private readonly string _ruleName; public CollectionRuleKey(int eventId, string ruleName) { _eventId = eventId; _ruleName = ruleName; } public bool Equals(CollectionRuleKey other) { return _eventId == other._eventId && string.Equals(_ruleName, other._ruleName, StringComparison.Ordinal); } public override bool Equals(object obj) { return obj is CollectionRuleKey key && Equals(key); } public override int GetHashCode() { HashCode code = new(); code.Add(_eventId); code.Add(_ruleName); return code.ToHashCode(); } } } }
c#
17
0.620812
134
37.69469
226
starcoderdata
package com.teammetallurgy.metallurgyclassic.machines.crusher; import com.teammetallurgy.metallurgyclassic.machines.abstractmachine.AbstractMachineBlock; import com.teammetallurgy.metallurgyclassic.machines.abstractmachine.AbstractMachineEntity; import com.teammetallurgy.metallurgyclassic.machines.furnace.MetalFurnaceBlockEntity; import com.teammetallurgy.metallurgyclassic.machines.furnace.MetalFurnaceComponent; import net.minecraft.block.*; import net.minecraft.block.entity.BlockEntity; import net.minecraft.block.entity.BlockEntityTicker; import net.minecraft.block.entity.BlockEntityType; import net.minecraft.block.enums.ChestType; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.particle.BlockStateParticleEffect; import net.minecraft.particle.ParticleTypes; import net.minecraft.screen.NamedScreenHandlerFactory; import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundEvents; import net.minecraft.stat.Stats; import net.minecraft.state.StateManager; import net.minecraft.state.property.BooleanProperty; import net.minecraft.state.property.DirectionProperty; import net.minecraft.state.property.Properties; import net.minecraft.util.BlockMirror; import net.minecraft.util.BlockRotation; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.util.shape.VoxelShape; import net.minecraft.world.BlockView; import net.minecraft.world.World; import org.jetbrains.annotations.Nullable; import java.util.Random; public class CrusherBlock extends AbstractMachineBlock { public static final DirectionProperty FACING; public static final BooleanProperty LIT; protected static final VoxelShape SINGLE_SHAPE; static { FACING = HorizontalFacingBlock.FACING; LIT = Properties.LIT; SINGLE_SHAPE = Block.createCuboidShape(0.0D, 0.0D, 0.0D, 16.0D, 13.0D, 16.0D); } protected CrusherBlock(Settings settings) { super(settings); this.setDefaultState(this.stateManager.getDefaultState().with(FACING, Direction.NORTH).with(LIT, false)); } public BlockEntity createBlockEntity(BlockPos pos, BlockState state) { return new CrusherBlockEntity(pos, state); } @Override public BlockRenderType getRenderType(BlockState state) { return BlockRenderType.ENTITYBLOCK_ANIMATED; } @Override public VoxelShape getOutlineShape(BlockState state, BlockView world, BlockPos pos, ShapeContext context) { return SINGLE_SHAPE; } @Override public BlockState rotate(BlockState state, BlockRotation rotation) { return state.with(FACING, rotation.rotate(state.get(FACING))); } @Override public BlockState mirror(BlockState state, BlockMirror mirror) { return state.rotate(mirror.getRotation(state.get(FACING))); } @Nullable public <T extends BlockEntity> BlockEntityTicker getTicker(World world, BlockState state, BlockEntityType type) { return checkType(type, CrusherComponent.getEntityType(state.getBlock()), AbstractMachineEntity::tick); } protected void appendProperties(StateManager.Builder<Block, BlockState> builder) { builder.add(FACING, LIT); } protected void openScreen(World world, BlockPos pos, PlayerEntity player) { BlockEntity blockEntity = world.getBlockEntity(pos); if (blockEntity instanceof CrusherBlockEntity) { player.openHandledScreen((NamedScreenHandlerFactory)blockEntity); } } public void randomDisplayTick(BlockState state, World world, BlockPos pos, Random random) { if (state.get(LIT)) { double d = (double) pos.getX() + 0.5D; double e = (double) pos.getY() + 1.0D; double f = (double) pos.getZ() + 0.5D; if (random.nextDouble() < 0.1D) { world.playSound(d, e, f, SoundEvents.BLOCK_FURNACE_FIRE_CRACKLE, SoundCategory.BLOCKS, 1.0F, 1.0F, false); } Direction direction = state.get(FACING); Direction.Axis axis = direction.getAxis(); double g = 0.52D; double h = random.nextDouble() * 0.8D - 0.4D; double minRandom = random.nextDouble() * 0.3D - 0.15D; double i = axis == Direction.Axis.X ? minRandom : h; double j = 0; //random.nextDouble() * 6.0D / 16.0D; double k = axis == Direction.Axis.Z ? minRandom : h; world.addParticle(ParticleTypes.SMOKE, d + i, e + j, f + k, 0.0D, 0.0D, 0.0D); if (random.nextDouble() < 0.9f) world.addParticle(ParticleTypes.FLAME, d + i, e + j - 0.1f, f + k, 0.0D, 0.0D, 0.0D); //entity.getCrushingBlock(); world.addParticle(new BlockStateParticleEffect(ParticleTypes.BLOCK, Blocks.IRON_ORE.getDefaultState()), d + i, e + j, f + k, 0.0D, 0.0D, 0.0D); } } }
java
14
0.712388
155
41.912281
114
starcoderdata
/* * Copyright 2014 Apereo Foundation (AF) Licensed under the * Educational Community 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://opensource.org/licenses/ECL-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. */ import assert from 'assert'; import * as tz from 'oae-util/lib/tz'; describe('TZ', () => { describe('#getTimeZoneFromRails()', () => { /** * Verifies that given a rails timezone, a "standard" timezone is returned. */ it('verify proper rails conversion', () => { assert.strictEqual(tz.getTimezoneFromRails('Brussels'), 'Europe/Brussels'); assert.strictEqual(tz.getTimezoneFromRails('Pacific Time (US & Canada)'), 'America/Los_Angeles'); }); }); describe('#getRailsTimeZoneFromTZInfo()', () => { /** * Verifies that given a rails timezone, a "standard" timezone is returned. */ it('verify proper rails conversion', () => { // Check a zone that exists in both rails and tzinfo assert.strictEqual(tz.getClosestSupportedTimezone('Europe/Brussels'), 'Europe/Brussels'); // Canada/Yukon is an obsolete zone replaced by America/Whitehorse // which has DST start on the second Sunday in March (UTC -7) and // end on the first Sunday in November (UTC -8) at 2am in both // cases adjusting the clock by 1 hour, those are the same rules // as America/Los_Angeles and America/Tijuana so L.A. comes first // in alphabetic order. assert.strictEqual(tz.getClosestSupportedTimezone('Canada/Yukon'), 'America/Los_Angeles'); // Africa/Bujumbura does not observe DST and is at UTC +2 that's // the same rules as Europe/Bucharest, Africa/Cairo, // Europe/Helsinki, Europe/Kiev, Europe/Riga, Europe/Sofia, // Europe/Tallinn, Europe/Vilnius, Europe/Athens, Europe/Istanbul, // Asia/Jerusalem, Africa/Harare, and Africa/Johannesburg so Cairo // is first in alphabetic order. assert.strictEqual(tz.getClosestSupportedTimezone('Africa/Bujumbura'), 'Africa/Cairo'); }); }); });
javascript
22
0.687371
103
42.410714
56
starcoderdata
import json, requests, sys, getpass, os def Init(): print("+===== Weaved CLI - (c) =====+") print("") print("") try: username = input("Enter your email address: ") password = getpass.getpass() url = "https://api.weaved.com/v22/api/user/login/" + username + "/" + password print("Connecting...") loginData = requests.get(url, headers={"apikey":"WeavedDemoKey$2015"}, timeout=10); loginJson = json.loads(loginData.text) if loginJson['status'] == "true": clearScreen() token = loginJson['token'] getDevices(token) else: print("Error 1: Unable to connect to api.weaved.com. Check your credentials.") sys.exit() except SyntaxError: print("Wrap your email address in double quotes.") Init() def getDevices(token): url = "https://api.weaved.com/v22/api/device/list/all" print("Retrieving devices using token " + token) deviceData = requests.get(url, headers={"apikey":"WeavedDemoKey$2015","token":token}, timeout=10); deviceJson = json.loads(deviceData.text) if deviceJson['status'] == "true": listDevices(deviceJson, token) else: print("Error 2: There was a problem retrieving the device list"); sys.exit() def listDevices(json, token): print("Listing devices...") print("") print("+===== Devices =====+") for i in json['devices']: print(i['devicealias'] + " || " + i['devicestate']) print("") picked = int(input("Select a device (enter 0 for the first): ")) clearScreen() try: deviceAddress = json['devices'][picked]['deviceaddress'] deviceIp = json['devices'][picked]['devicelastip'] print("Getting connection info for " + json['devices'][picked]['devicealias']) getConnectionInfo(deviceAddress, deviceIp, token) except: print("Your selection is out of range.") print("") listDevices(json, token) def getConnectionInfo(deviceAddress, hostIp, token): url = "https://api.weaved.com/v22/api/device/connect" connectionData = requests.post(url, headers={"apikey":"WeavedDemoKey$2015","token":token}, json={"deviceaddress":deviceAddress,"hostip":hostIp,"wait":"true"}, timeout=20); connectionJson = json.loads(connectionData.text) if connectionJson['status'] == "true": print("") print("Connection: " + connectionJson['connection']['proxy']) else: print("Error 3: There was a problem getting the connection details.") def clearScreen(): if (os.name in ('ce', 'nt', 'dos')): os.system('cls') else: os.system('clear') Init()
python
13
0.64817
172
24.46875
96
starcoderdata
/* * Copyright 2015 Collective, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.collective.celos; import org.apache.commons.lang.builder.CompareToBuilder; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; /** * Time of a workflow run in UTC. */ public class ScheduledTime extends ValueObject implements Comparable { public static final ScheduledTimeFormatter FORMATTER = new ScheduledTimeFormatter(); protected final DateTime dateTime; public ScheduledTime(String formattedDate) { this(DateTime.parse(formattedDate)); } public ScheduledTime(DateTime dateTime) { this.dateTime = Util.requireNonNull(dateTime); if (!dateTime.getZone().equals(DateTimeZone.UTC)) { throw new IllegalArgumentException( "Scheduled time must be in UTC, but isn't: " + dateTime); } } public DateTime getDateTime() { return dateTime; } @Override public int compareTo(ScheduledTime t) { return CompareToBuilder.reflectionCompare(this, t); } public int getYear() { return dateTime.getYear(); } public int getMonth() { return dateTime.getMonthOfYear(); } public int getDay() { return dateTime.getDayOfMonth(); } public int getHour() { return dateTime.getHourOfDay(); } public int getMinute() { return dateTime.getMinuteOfHour(); } public int getSecond() { return dateTime.getSecondOfMinute(); } public int getMillisecond() { return dateTime.getMillisOfSecond(); } public String toString() { return dateTime.toString(); } public ScheduledTime minusYears(int i) { return new ScheduledTime(getDateTime().minusYears(i)); } public ScheduledTime plusYears(int i) { return new ScheduledTime(getDateTime().plusYears(i)); } public ScheduledTime minusMonths(int i) { return new ScheduledTime(getDateTime().minusMonths(i)); } public ScheduledTime plusMonths(int i) { return new ScheduledTime(getDateTime().plusMonths(i)); } public ScheduledTime minusDays(int i) { return new ScheduledTime(getDateTime().minusDays(i)); } public ScheduledTime plusDays(int i) { return new ScheduledTime(getDateTime().plusDays(i)); } public ScheduledTime minusHours(int i) { return new ScheduledTime(getDateTime().minusHours(i)); } public ScheduledTime plusHours(int i) { return new ScheduledTime(getDateTime().plusHours(i)); } public ScheduledTime minusMinutes(int i) { return new ScheduledTime(getDateTime().minusMinutes(i)); } public ScheduledTime plusMinutes(int i) { return new ScheduledTime(getDateTime().plusMinutes(i)); } public ScheduledTime minusSeconds(int i) { return new ScheduledTime(getDateTime().minusSeconds(i)); } public ScheduledTime plusSeconds(int i) { return new ScheduledTime(getDateTime().plusSeconds(i)); } public String year() { return FORMATTER.formatYear(this); } public String month() { return FORMATTER.formatMonth(this); } public String day() { return FORMATTER.formatDay(this); } public String hour() { return FORMATTER.formatHour(this); } public String minute() { return FORMATTER.formatMinute(this); } public String second() { return FORMATTER.formatSecond(this); } public static ScheduledTime now() { return new ScheduledTime(DateTime.now(DateTimeZone.UTC)); } }
java
12
0.663805
88
25.2125
160
starcoderdata
/* Copyright 2019 Open End AB 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. */ Ext.define('Bokf.view.Main', { extend: 'Ext.panel.Panel', requires: [ 'Bokf.lib.LinkButton', 'Bokf.view.AccountsPayable', 'Bokf.view.Admin', 'Bokf.view.Expense', 'Bokf.view.Import', 'Bokf.view.Reports', 'Bokf.view.Verification', 'Bokf.view.members.Invoices', 'Bokf.view.members.Payments', 'Bokf.view.members.Products', 'Bokf.view.members.Purchases', 'Bokf.view.members.SalesReports' ], xtype: 'main', autoScroll: 'true', layout: 'border', dockedItems: [ {xtype: 'toolbar', cls: 'acc-top-toolbar', dock: 'top', height: 24, padding: '2 6 2 2', items: [ '->', {xtype: 'linkbutton', action: 'logout', href: '/logout'} ] } ], items: [ {xtype: 'orglist', region: 'west', width: 300, split: true, collapsible: true}, {xtype: 'tabpanel', name: 'main-tab-panel', region: 'center', tabBar: { cls: 'main-tab-bar' }, items: [ {xtype: 'admin', name: 'admin'}, {xtype: 'verification', name: 'accounting', hidden: true}, {xtype: 'reports', name: 'reports', hidden: true}, {xtype: 'products', name: 'products', hidden: true}, {xtype: 'payments', name: 'payments', hidden: true}, {xtype: 'purchases', name: 'purchases', hidden: true}, {xtype: 'invoices', name: 'invoices', hidden: true}, {xtype: 'expense', name: 'expenses', hidden: true}, {xtype: 'import', name: 'import', hidden: true}, {xtype: 'salesreports', name: 'salesreports', hidden: true}, {xtype: 'accountspayable', name: 'accountspayable', hidden: true} ], stateful: true, stateId: 'main-tab-bar', stateEvents: ['tabchange'], applyState: function(state) { if (state.index != null) { var tab = this.items.getAt(state.index) if (tab != null) { this.setActiveTab(tab) } } }, getState: function() { var tab = this.getActiveTab() var index = this.items.indexOf(tab) return {'index': index} } } ], l10n: { tabNames: { admin: 'Administration', accounting: 'Accounting', reports: 'Reports', products: 'Shop', payments: 'Payments', purchases: 'Purchases', invoices: 'Invoices', expenses: 'Expenses', 'import': 'Import', salesreports: 'Sales reports', accountspayable: 'Accounts payable' }, logout: 'Log out' }, listeners: { beforerender: { fn: function() { var tabPanel = this.down('[name=main-tab-panel]') var tabs = tabPanel.getTabBar().items tabPanel.items.each(function(item, i) { tabs.getAt(i).setText(this.l10n.tabNames[item.name]) }, this); this.down('button[action=logout]').setText(this.l10n.logout) } } } })
javascript
20
0.531636
78
30.354839
124
starcoderdata
/* * Copyright 2014 and others. * * 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.sourcepit.osgifier.core.bundle; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.sourcepit.common.manifest.osgi.BundleHeaderName.BUNDLE_REQUIREDEXECUTIONENVIRONMENT; import static org.sourcepit.common.manifest.osgi.BundleHeaderName.EXPORT_PACKAGE; import static org.sourcepit.osgifier.core.bundle.TestContextHelper.appendType; import static org.sourcepit.osgifier.core.bundle.TestContextHelper.appendTypeReference; import static org.sourcepit.osgifier.core.bundle.TestContextHelper.newBundleCandidate; import java.util.List; import java.util.Set; import javax.inject.Inject; import org.eclipse.sisu.launch.InjectedTest; import org.hamcrest.core.IsEqual; import org.junit.Test; import org.sourcepit.common.manifest.osgi.BundleManifest; import org.sourcepit.common.manifest.osgi.Version; import org.sourcepit.common.utils.props.LinkedPropertiesMap; import org.sourcepit.common.utils.props.PropertiesMap; import org.sourcepit.osgifier.core.model.context.BundleCandidate; import org.sourcepit.osgifier.core.model.context.BundleReference; import org.sourcepit.osgifier.core.model.context.ContextModelFactory; import org.sourcepit.osgifier.core.model.java.JavaArchive; import org.sourcepit.osgifier.core.model.java.JavaModelFactory; import org.sourcepit.osgifier.core.model.java.JavaType; /** * @author */ public class RequiredExecutionEnvironmentAppenderTest extends InjectedTest { @Inject private RequiredExecutionEnvironmentAppender execEnvAppender; @Test public void testGetExcludedExecutionEnvironments() throws Exception { PropertiesMap options = new LinkedPropertiesMap(); Set excludes = RequiredExecutionEnvironmentAppender.getExcludedExecutionEnvironments(options); assertTrue(excludes.isEmpty()); options.put("osgifier.excludedExecutionEnvironments", "OSGi/Minimum-1.0, JavaSE/compact1-1.8"); excludes = RequiredExecutionEnvironmentAppender.getExcludedExecutionEnvironments(options); assertEquals(2, excludes.size()); assertTrue(excludes.contains("OSGi/Minimum-1.0")); assertTrue(excludes.contains("JavaSE/compact1-1.8")); } @Test public void test() { PropertiesMap options = new LinkedPropertiesMap(); JavaArchive jArchive = JavaModelFactory.eINSTANCE.createJavaArchive(); appendType(jArchive, "org.sourcepit.Foo", 47); BundleCandidate bundle = newBundleCandidate(jArchive); execEnvAppender.append(bundle, options); BundleManifest manifest = bundle.getManifest(); assertThat(manifest.getHeaderValue(BUNDLE_REQUIREDEXECUTIONENVIRONMENT), IsEqual.equalTo("J2SE-1.3, JavaSE/compact1-1.8")); jArchive = JavaModelFactory.eINSTANCE.createJavaArchive(); appendType(jArchive, "org.sourcepit.Foo", 46); bundle = newBundleCandidate(jArchive); execEnvAppender.append(bundle, options); manifest = bundle.getManifest(); assertThat(manifest.getHeaderValue(BUNDLE_REQUIREDEXECUTIONENVIRONMENT), IsEqual.equalTo("OSGi/Minimum-1.1")); jArchive = JavaModelFactory.eINSTANCE.createJavaArchive(); appendType(jArchive, "org.sourcepit.Foo", 51); bundle = newBundleCandidate(jArchive); execEnvAppender.append(bundle, options); manifest = bundle.getManifest(); assertThat(manifest.getHeaderValue(BUNDLE_REQUIREDEXECUTIONENVIRONMENT), IsEqual.equalTo("JavaSE-1.7, JavaSE/compact1-1.8")); jArchive = JavaModelFactory.eINSTANCE.createJavaArchive(); JavaType jType = appendType(jArchive, "org.sourcepit.Foo", 47); appendTypeReference(jType, "java.nio.file.Foo"); bundle = newBundleCandidate(jArchive); execEnvAppender.append(bundle, options); manifest = bundle.getManifest(); assertThat(manifest.getHeaderValue(BUNDLE_REQUIREDEXECUTIONENVIRONMENT), IsEqual.equalTo("JavaSE-1.7, JavaSE/compact1-1.8")); // no perfect match jArchive = JavaModelFactory.eINSTANCE.createJavaArchive(); jType = appendType(jArchive, "org.sourcepit.Foo", 51); appendTypeReference(jType, "javax.microedition.io.Foo"); bundle = newBundleCandidate(jArchive); execEnvAppender.append(bundle, options); manifest = bundle.getManifest(); assertNull(manifest.getHeaderValue(BUNDLE_REQUIREDEXECUTIONENVIRONMENT)); jArchive = JavaModelFactory.eINSTANCE.createJavaArchive(); jType = appendType(jArchive, "org.sourcepit.Foo", 48); appendTypeReference(jType, "java.lang.Object"); bundle = newBundleCandidate(jArchive); execEnvAppender.append(bundle, options); manifest = bundle.getManifest(); assertThat(manifest.getHeaderValue(BUNDLE_REQUIREDEXECUTIONENVIRONMENT), IsEqual.equalTo("J2SE-1.4, JavaSE/compact1-1.8")); jArchive = JavaModelFactory.eINSTANCE.createJavaArchive(); jType = appendType(jArchive, "org.sourcepit.Foo", 47); appendTypeReference(jType, "java.text.Foo"); bundle = newBundleCandidate(jArchive); execEnvAppender.append(bundle, options); manifest = bundle.getManifest(); assertThat(manifest.getHeaderValue(BUNDLE_REQUIREDEXECUTIONENVIRONMENT), IsEqual.equalTo("J2SE-1.3, JavaSE/compact1-1.8")); jArchive = JavaModelFactory.eINSTANCE.createJavaArchive(); jType = appendType(jArchive, "org.sourcepit.Foo", 49); appendTypeReference(jType, "java.lang.Object"); bundle = newBundleCandidate(jArchive); execEnvAppender.append(bundle, options); manifest = bundle.getManifest(); assertThat(manifest.getHeaderValue(BUNDLE_REQUIREDEXECUTIONENVIRONMENT), IsEqual.equalTo("J2SE-1.5, JavaSE/compact1-1.8")); jArchive = JavaModelFactory.eINSTANCE.createJavaArchive(); jType = appendType(jArchive, "org.sourcepit.Foo", 45); appendTypeReference(jType, "java.lang.Object"); appendTypeReference(jType, "java.applet.Foo"); bundle = newBundleCandidate(jArchive); execEnvAppender.append(bundle, options); manifest = bundle.getManifest(); assertThat(manifest.getHeaderValue(BUNDLE_REQUIREDEXECUTIONENVIRONMENT), IsEqual.equalTo("JRE-1.1")); } @Test public void testBeAwareOfPackagesFromDependencies() throws Exception { PropertiesMap options = new LinkedPropertiesMap(); final BundleCandidate activation; { JavaArchive jArchive = JavaModelFactory.eINSTANCE.createJavaArchive(); appendType(jArchive, "javax.activation.MimeType", 48); activation = newBundleCandidate(jArchive); activation.getManifest().setHeader(EXPORT_PACKAGE, "javax.activation"); } final BundleCandidate mail; { JavaArchive jArchive = JavaModelFactory.eINSTANCE.createJavaArchive(); JavaType jType = appendType(jArchive, "javax.mail.Service", 48); appendTypeReference(jType, "javax.activation.MimeType"); mail = newBundleCandidate(jArchive); } execEnvAppender.append(mail, options); BundleManifest manifest = mail.getManifest(); assertThat(manifest.getHeaderValue(BUNDLE_REQUIREDEXECUTIONENVIRONMENT), IsEqual.equalTo("JavaSE-1.6")); BundleReference ref = ContextModelFactory.eINSTANCE.createBundleReference(); ref.setTarget(activation); mail.getDependencies().add(ref); manifest.setHeader(BUNDLE_REQUIREDEXECUTIONENVIRONMENT, null); execEnvAppender.append(mail, options); assertThat(manifest.getHeaderValue(BUNDLE_REQUIREDEXECUTIONENVIRONMENT), IsEqual.equalTo("J2SE-1.4, JavaSE/compact1-1.8")); } @Test public void testGetMappedEEIds() throws Exception { PropertiesMap options = new LinkedPropertiesMap(); List mappedEEs; mappedEEs = RequiredExecutionEnvironmentAppender.getMappedEEIds(options, "foo", Version.parse("1.0.0")); assertEquals("[]", mappedEEs.toString()); options.put("osgifier.executionEnvironmentMappings", "foo=JavaSE-1.6"); mappedEEs = RequiredExecutionEnvironmentAppender.getMappedEEIds(options, "foo", Version.parse("1.0.0")); assertEquals("[JavaSE-1.6]", mappedEEs.toString()); options.put("osgifier.executionEnvironmentMappings", "foo_1.0.0=JavaSE-1.5"); mappedEEs = RequiredExecutionEnvironmentAppender.getMappedEEIds(options, "foo", Version.parse("1.0.0")); assertEquals("[JavaSE-1.5]", mappedEEs.toString()); options.put("osgifier.executionEnvironmentMappings", "foo_1.0.0 = J2SE-1.4| | | | JavaSE/compact1-1.8"); mappedEEs = RequiredExecutionEnvironmentAppender.getMappedEEIds(options, "foo", Version.parse("1.0.0")); assertEquals("[J2SE-1.4, JavaSE/compact1-1.8]", mappedEEs.toString()); options.put("osgifier.executionEnvironmentMappings", "foo_1.0.0 = J2SE-1.4| | | | JavaSE/compact1-1.8, bar = J2SE-1.3"); mappedEEs = RequiredExecutionEnvironmentAppender.getMappedEEIds(options, "foo", Version.parse("1.0.0")); assertEquals("[J2SE-1.4, JavaSE/compact1-1.8]", mappedEEs.toString()); mappedEEs = RequiredExecutionEnvironmentAppender.getMappedEEIds(options, "bar", Version.parse("1.0.0")); assertEquals("[J2SE-1.3]", mappedEEs.toString()); } @Test public void testExecutionEnvironmentMappings() throws Exception { JavaArchive jArchive = JavaModelFactory.eINSTANCE.createJavaArchive(); appendType(jArchive, "org.sourcepit.Foo", 47); BundleCandidate bundle = newBundleCandidate(jArchive); bundle.setSymbolicName("foo"); bundle.setVersion(Version.parse("1")); // without mapping PropertiesMap options = new LinkedPropertiesMap(); execEnvAppender.append(bundle, options); BundleManifest manifest = bundle.getManifest(); assertEquals("J2SE-1.3, JavaSE/compact1-1.8", manifest.getHeaderValue(BUNDLE_REQUIREDEXECUTIONENVIRONMENT)); // with mapping manifest.setHeader(BUNDLE_REQUIREDEXECUTIONENVIRONMENT, null); options.put("osgifier.executionEnvironmentMappings", "foo = OSGi/Minimum-1.0 | J2SE-1.3"); execEnvAppender.append(bundle, options); manifest = bundle.getManifest(); assertEquals("OSGi/Minimum-1.0, J2SE-1.3", manifest.getHeaderValue(BUNDLE_REQUIREDEXECUTIONENVIRONMENT)); } }
java
12
0.734476
116
40.160448
268
starcoderdata
<T, B> void nextAccumulator(final Accumulator<T, B> nextAccumulator, final Subscriber<? super B> target, final Subscription bSubscription, final Subscription tSubscription) { requireNonNull(nextAccumulator); for (;;) { final Object cMaybeAccumulator = maybeAccumulator; if (cMaybeAccumulator == TERMINATED) { return; } if (cMaybeAccumulator == null) { // This is the first received accumulator (first boundary start); so we just store the accumulator // to accumulate and request items from tSubscription. if (maybeAccumulatorUpdater.compareAndSet(this, null, toCounting(nextAccumulator))) { tSubscription.request(itemsRequestN); // Since we did not emit the accumulator we request one more to observe the next boundary: bSubscription.request(1); return; } } else if (ItemsTerminated.class.equals(cMaybeAccumulator.getClass())) { // ItemsTerminated with outstanding accumulated data while there was no demand, waiting to demand // to finish termination. return; } else if (cMaybeAccumulator == ADDING) { // Hand-off emission of nextAccumulator to the thread that is ADDING if (maybeAccumulatorUpdater.compareAndSet(this, ADDING, new NextAccumulatorHolder<>(nextAccumulator))) { // Thread that is ADDING will observe the change and emit the current accumulator return; } } else if (NextAccumulatorHolder.class.equals(cMaybeAccumulator.getClass())) { // One more boundary is received when we already have a "queued" next boundary (we are in ADDING // state or delivering the previous boundary), discarding it. // Since we did not emit the accumulator we request one more to observe the next boundary: bSubscription.request(1); return; } else { assert cMaybeAccumulator instanceof CountingAccumulator; final NextAccumulatorHolder<T, B> holder = new NextAccumulatorHolder<>(nextAccumulator); if (maybeAccumulatorUpdater.compareAndSet(this, cMaybeAccumulator, holder)) { @SuppressWarnings("unchecked") Accumulator<T, B> oldAccumulator = (Accumulator<T, B>) cMaybeAccumulator; final Object nextState; try { deliverOnNext(oldAccumulator, target); } finally { nextState = unwrapHolderState(holder); } if (ItemsTerminated.class.equals(nextState.getClass())) { @SuppressWarnings("unchecked") final ItemsTerminated<T, B> it = (ItemsTerminated<T, B>) nextState; terminateIfPossible(it.accumulator, target, it.terminalNotification); } return; } } } }
java
19
0.528805
118
61.321429
56
inline
Component({ props: { className: '', show: false, position: 'bottom', mask: true, animation: true, disableScroll: true }, methods: { onMaskTap: function onMaskTap() { var onClose = this.props.onClose; if (onClose) { onClose(); } } } });
javascript
15
0.524752
39
14.2
20
starcoderdata
<?php namespace MediaWiki\Tests\Rest\HeaderParser; use MediaWiki\Rest\HeaderParser\HttpDate; /** * @covers \MediaWiki\Rest\HeaderParser\HttpDate */ class HttpDateTest extends \MediaWikiUnitTestCase { public static function provideParse() { return [ 'RFC 7231 example 1' => [ 'Sun, 06 Nov 1994 08:49:37 GMT', 784111777 ], 'RFC 7231 example 2' => [ 'Sunday, 06-Nov-94 08:49:37 GMT', 784111777 ], 'RFC 7231 example 3' => [ 'Sun Nov 6 08:49:37 1994', 784111777 ], 'asctime whitespace nitpick' => [ 'Sun Nov 6 08:49:37 1994', null ], 'PHP "r" format' => [ 'Sun, 06 Nov 1994 08:49:37 +0000', null ], 'RFC 7231 example 1 with trail' => [ 'Sun, 06 Nov 1994 08:49:37 GMT.', null ], 'RFC 7231 example 2 with trail' => [ 'Sunday, 06-Nov-94 08:49:37 GMT.', null ], 'RFC 7231 example 3 with trail' => [ 'Sun Nov 6 08:49:37 1994.', null ], ]; } /** * @dataProvider provideParse * @param string $input * @param string|null $expected */ public function testParse( $input, $expected ) { $result = HttpDate::parse( $input ); $this->assertSame( $expected, $result ); } public static function provideFormatRoundtrip() { for ( $ts = 1000000000; $ts < 2000000000; $ts += 100000000 ) { yield [ $ts ]; } } /** * @dataProvider provideFormatRoundtrip */ public function testFormatRoundtrip( $ts ) { $this->assertSame( $ts, HttpDate::parse( HttpDate::format( $ts ) ) ); } }
php
16
0.625987
138
22.197183
71
starcoderdata
#include "formleadparams.h" #include "ui_formleadparams.h" FormLeadParams::FormLeadParams(unsigned int _id,QWidget *parent) : QWidget(parent), ui(new Ui::FormLeadParams) { ui->setupUi(this); id = _id; ui->label->setText(QString::number(id+1)+"."); connect(ui->pushButtonShowHide,SIGNAL(toggled(bool)),this,SLOT(toggleShowHide(bool))); connect(ui->pushButtonShowArea,SIGNAL(toggled(bool)),this,SLOT(toggleShowLeadArea(bool))); } FormLeadParams::~FormLeadParams() { delete ui; } void FormLeadParams::toggleShowHide(bool toggle){ emit emitToggleShowHide(id,toggle); } void FormLeadParams::toggleShowLeadArea(bool toggle){ emit emittoggleShowLeadArea(id,toggle); }
c++
11
0.716438
94
24.172414
29
starcoderdata
// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: get.proto package workload import ( fmt "fmt" _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" _ "github.com/mwitkow/go-proto-validators" container "github.com/easyopsapis/easyops-api-go/protorepo-models/easyops/model/container" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // //Get请求 type GetRequest struct { // //获取指定的 workload id InstanceId string `protobuf:"bytes,1,opt,name=instanceId,proto3" json:"instanceId" form:"instanceId"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *GetRequest) Reset() { *m = GetRequest{} } func (m *GetRequest) String() string { return proto.CompactTextString(m) } func (*GetRequest) ProtoMessage() {} func (*GetRequest) Descriptor() ([]byte, []int) { return fileDescriptor_21b2a6be0e6d8388, []int{0} } func (m *GetRequest) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_GetRequest.Unmarshal(m, b) } func (m *GetRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_GetRequest.Marshal(b, m, deterministic) } func (m *GetRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_GetRequest.Merge(m, src) } func (m *GetRequest) XXX_Size() int { return xxx_messageInfo_GetRequest.Size(m) } func (m *GetRequest) XXX_DiscardUnknown() { xxx_messageInfo_GetRequest.DiscardUnknown(m) } var xxx_messageInfo_GetRequest proto.InternalMessageInfo func (m *GetRequest) GetInstanceId() string { if m != nil { return m.InstanceId } return "" } // //Get返回 type GetResponse struct { // //关联的部署资源组 (resource group) ResourceGroup *container.ResourceGroup `protobuf:"bytes,1,opt,name=resourceGroup,proto3" json:"resourceGroup" form:"resourceGroup"` // //workload 信息 Workload *container.Workload `protobuf:"bytes,2,opt,name=workload,proto3" json:"workload" form:"workload"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *GetResponse) Reset() { *m = GetResponse{} } func (m *GetResponse) String() string { return proto.CompactTextString(m) } func (*GetResponse) ProtoMessage() {} func (*GetResponse) Descriptor() ([]byte, []int) { return fileDescriptor_21b2a6be0e6d8388, []int{1} } func (m *GetResponse) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_GetResponse.Unmarshal(m, b) } func (m *GetResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_GetResponse.Marshal(b, m, deterministic) } func (m *GetResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_GetResponse.Merge(m, src) } func (m *GetResponse) XXX_Size() int { return xxx_messageInfo_GetResponse.Size(m) } func (m *GetResponse) XXX_DiscardUnknown() { xxx_messageInfo_GetResponse.DiscardUnknown(m) } var xxx_messageInfo_GetResponse proto.InternalMessageInfo func (m *GetResponse) GetResourceGroup() *container.ResourceGroup { if m != nil { return m.ResourceGroup } return nil } func (m *GetResponse) GetWorkload() *container.Workload { if m != nil { return m.Workload } return nil } // //GetApi返回 type GetResponseWrapper struct { // //返回码 Code int32 `protobuf:"varint,1,opt,name=code,proto3" json:"code" form:"code"` // //返回码解释 CodeExplain string `protobuf:"bytes,2,opt,name=codeExplain,proto3" json:"codeExplain" form:"codeExplain"` // //错误详情 Error string `protobuf:"bytes,3,opt,name=error,proto3" json:"error" form:"error"` // //返回数据 Data *GetResponse `protobuf:"bytes,4,opt,name=data,proto3" json:"data" form:"data"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *GetResponseWrapper) Reset() { *m = GetResponseWrapper{} } func (m *GetResponseWrapper) String() string { return proto.CompactTextString(m) } func (*GetResponseWrapper) ProtoMessage() {} func (*GetResponseWrapper) Descriptor() ([]byte, []int) { return fileDescriptor_21b2a6be0e6d8388, []int{2} } func (m *GetResponseWrapper) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_GetResponseWrapper.Unmarshal(m, b) } func (m *GetResponseWrapper) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_GetResponseWrapper.Marshal(b, m, deterministic) } func (m *GetResponseWrapper) XXX_Merge(src proto.Message) { xxx_messageInfo_GetResponseWrapper.Merge(m, src) } func (m *GetResponseWrapper) XXX_Size() int { return xxx_messageInfo_GetResponseWrapper.Size(m) } func (m *GetResponseWrapper) XXX_DiscardUnknown() { xxx_messageInfo_GetResponseWrapper.DiscardUnknown(m) } var xxx_messageInfo_GetResponseWrapper proto.InternalMessageInfo func (m *GetResponseWrapper) GetCode() int32 { if m != nil { return m.Code } return 0 } func (m *GetResponseWrapper) GetCodeExplain() string { if m != nil { return m.CodeExplain } return "" } func (m *GetResponseWrapper) GetError() string { if m != nil { return m.Error } return "" } func (m *GetResponseWrapper) GetData() *GetResponse { if m != nil { return m.Data } return nil } func init() { proto.RegisterType((*GetRequest)(nil), "workload.GetRequest") proto.RegisterType((*GetResponse)(nil), "workload.GetResponse") proto.RegisterType((*GetResponseWrapper)(nil), "workload.GetResponseWrapper") } func init() { proto.RegisterFile("get.proto", fileDescriptor_21b2a6be0e6d8388) } var fileDescriptor_21b2a6be0e6d8388 = []byte{ // 435 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x91, 0xcf, 0x6e, 0xd4, 0x30, 0x10, 0xc6, 0xb5, 0xb0, 0x45, 0xac, 0x17, 0x68, 0x71, 0x01, 0x45, 0xbd, 0x04, 0x19, 0x84, 0xe0, 0x90, 0x18, 0xa8, 0x84, 0xa0, 0xc7, 0x08, 0x54, 0xf5, 0xea, 0xcb, 0x56, 0x42, 0x80, 0xbc, 0x89, 0x1b, 0xa2, 0x66, 0x33, 0xc6, 0x76, 0x58, 0xfe, 0x88, 0x47, 0xe2, 0x79, 0xb8, 0x05, 0x89, 0x47, 0xc8, 0x13, 0xa0, 0x1d, 0x67, 0x53, 0xf7, 0xde, 0x53, 0x3c, 0xfe, 0xbe, 0xef, 0x97, 0x19, 0x0f, 0x99, 0x95, 0xca, 0xa5, 0xda, 0x80, 0x03, 0x7a, 0x73, 0x0d, 0xe6, 0xbc, 0x06, 0x59, 0x1c, 0x24, 0x65, 0xe5, 0x3e, 0xb7, 0xcb, 0x34, 0x87, 0x15, 0x2f, 0xa1, 0x04, 0x8e, 0x86, 0x65, 0x7b, 0x86, 0x15, 0x16, 0x78, 0xf2, 0xc1, 0x83, 0xd3, 0x12, 0x52, 0x25, 0xed, 0x77, 0xd0, 0x36, 0xad, 0x21, 0x97, 0x35, 0xcf, 0xa1, 0x71, 0x46, 0xe6, 0xce, 0xfa, 0xa4, 0x51, 0x1a, 0x92, 0x15, 0x14, 0xaa, 0xb6, 0x7c, 0x30, 0x72, 0x2c, 0xd1, 0x28, 0xab, 0x46, 0x19, 0x6e, 0x94, 0x85, 0xd6, 0xe4, 0xea, 0x53, 0x69, 0xa0, 0xd5, 0x03, 0x59, 0x5c, 0x05, 0x79, 0x3b, 0xd6, 0xc0, 0x7c, 0x15, 0x0c, 0xb7, 0x5a, 0x57, 0xee, 0x1c, 0xd6, 0xbc, 0x84, 0x04, 0xc5, 0xe4, 0xab, 0xac, 0xab, 0x42, 0x3a, 0x30, 0x96, 0x8f, 0x47, 0x9f, 0x63, 0x0b, 0x42, 0x8e, 0x95, 0x13, 0xea, 0x4b, 0xab, 0xac, 0xa3, 0x27, 0x84, 0x54, 0x8d, 0x75, 0xb2, 0xc9, 0xd5, 0x49, 0x11, 0x4d, 0x1e, 0x4e, 0x9e, 0xce, 0xb2, 0x67, 0x7d, 0x17, 0xdf, 0x3d, 0x03, 0xb3, 0x3a, 0x62, 0x17, 0x1a, 0xfb, 0xf7, 0x37, 0xde, 0x23, 0x77, 0x3e, 0xbe, 0x7f, 0x9e, 0xbc, 0x91, 0xc9, 0x8f, 0x0f, 0x3f, 0x5f, 0x1c, 0xfe, 0x7a, 0x2c, 0x82, 0x30, 0xfb, 0x3d, 0x21, 0x73, 0x24, 0x5b, 0x0d, 0x8d, 0x55, 0xf4, 0x94, 0xdc, 0xde, 0x3e, 0xc6, 0xf1, 0xe6, 0x2d, 0x90, 0x3e, 0x7f, 0x19, 0xa5, 0xe3, 0x48, 0xa9, 0x08, 0xf5, 0x2c, 0xea, 0xbb, 0xf8, 0x9e, 0xff, 0xef, 0xa5, 0x20, 0x13, 0x97, 0x41, 0xf4, 0x2d, 0x19, 0x77, 0x1c, 0x5d, 0x43, 0xe8, 0x7e, 0x00, 0x5d, 0x0c, 0x52, 0xb6, 0xdf, 0x77, 0xf1, 0xae, 0xe7, 0x6d, 0xed, 0x4c, 0x8c, 0x49, 0xf6, 0x67, 0x42, 0x68, 0xd0, 0xef, 0xc2, 0x48, 0xad, 0x95, 0xa1, 0x8f, 0xc8, 0x34, 0x87, 0x42, 0x61, 0xb7, 0x3b, 0xd9, 0x6e, 0xdf, 0xc5, 0x73, 0xcf, 0xd8, 0xdc, 0x32, 0x81, 0x22, 0x7d, 0x4d, 0xe6, 0x9b, 0xef, 0xbb, 0x6f, 0xba, 0x96, 0x55, 0x83, 0x4d, 0xcc, 0xb2, 0x07, 0x7d, 0x17, 0xd3, 0x0b, 0xef, 0x20, 0x32, 0x11, 0x5a, 0xe9, 0x13, 0xb2, 0xa3, 0x8c, 0x01, 0x13, 0x5d, 0xc7, 0xcc, 0x5e, 0xdf, 0xc5, 0xb7, 0x7c, 0x06, 0xaf, 0x99, 0xf0, 0x32, 0x3d, 0x22, 0xd3, 0x42, 0x3a, 0x19, 0x4d, 0x71, 0xbe, 0xfb, 0xe9, 0xb8, 0xfd, 0xa0, 0xe5, 0xb0, 0xbb, 0x8d, 0x99, 0x09, 0xcc, 0x2c, 0x6f, 0xe0, 0xa6, 0x0f, 0xff, 0x07, 0x00, 0x00, 0xff, 0xff, 0x49, 0x92, 0x43, 0x34, 0x15, 0x03, 0x00, 0x00, }
go
9
0.694995
132
36.796537
231
starcoderdata
var dir_439034b806e131c0cd19f2ce624559a9 = [ [ "backend.cpp", "backend_8cpp.html", null ], [ "backend.h", "backend_8h.html", [ [ "Backend", "class_backend.html", "class_backend" ] ] ], [ "controller.cpp", "controller_8cpp.html", "controller_8cpp" ], [ "controller.h", "controller_8h.html", [ [ "Controller", "class_controller.html", "class_controller" ] ] ], [ "main.cpp", "main_8cpp.html", "main_8cpp" ], [ "model.cpp", "model_8cpp.html", null ], [ "model.h", "model_8h.html", [ [ "Model", "class_model.html", "class_model" ] ] ] ];
javascript
8
0.57022
68
36
16
starcoderdata
import subprocess, os import dolfin as df from xii import EmbeddedMesh def convert(msh_file, h5_file): '''Convert from msh to h5''' root, _ = os.path.splitext(msh_file) assert os.path.splitext(msh_file)[1] == '.msh' assert os.path.splitext(h5_file)[1] == '.h5' # Get the xml mesh xml_file = '.'.join([root, 'xml']) subprocess.call(['dolfin-convert %s %s' % (msh_file, xml_file)], shell=True) # Success? assert os.path.exists(xml_file) cmd = '''from dolfin import Mesh, HDF5File;\ mesh=Mesh('%(xml_file)s');\ assert mesh.topology().dim() == 3;\ out=HDF5File(mesh.mpi_comm(), '%(h5_file)s', 'w');\ out.write(mesh, 'mesh');''' % {'xml_file': xml_file, 'h5_file': h5_file} for region in ('facet_region.xml', 'physical_region.xml'): name, _ = region.split('_') r_xml_file = '_'.join([root, region]) if os.path.exists(r_xml_file): cmd_r = '''from dolfin import MeshFunction;\ f = MeshFunction('size_t', mesh, '%(r_xml_file)s');\ out.write(f, '%(name)s');\ ''' % {'r_xml_file': r_xml_file, 'name': name} cmd = ''.join([cmd, cmd_r]) cmd = 'python -c "%s"' % cmd status = subprocess.call([cmd], shell=True) assert status == 0 # Sucess? assert os.path.exists(h5_file) # Cleanup list(map(os.remove, [f for f in os.listdir('.') if f.endswith('.xml') and f.startswith('domain')])) list(map(os.remove, [f for f in os.listdir('.') if f.endswith('.msh') and f.startswith('domain')])) return True def h5_file_name(scale, inner_size): return 'mesh_%g_%g.h5' % (scale, inner_size) def generate(scale=1, inner_size=1): '''Generate mesh from geo file storing it as H5File''' h5_file = h5_file_name(scale, inner_size) # Reuse if os.path.exists(h5_file): return h5_file # New cmd = 'gmsh -3 -setnumber inner %g -clscale %g domain.geo' % (inner_size, scale) status = subprocess.call([cmd], shell=True) assert status == 0 assert os.path.exists('domain.msh') # xml assert convert('domain.msh', h5_file) return h5_file def load(scale, inner_size, curve_gen): '''Load meshes for 3d-2d-1d problems''' h5_file = generate(scale, inner_size) comm = df.mpi_comm_world() h5 = df.HDF5File(comm, h5_file, 'r') mesh = df.Mesh() h5.read(mesh, 'mesh', False) surfaces = df.MeshFunction('size_t', mesh, mesh.topology().dim()-1) h5.read(surfaces, 'facet') volumes = df.MeshFunction('size_t', mesh, mesh.topology().dim()) h5.read(volumes, 'physical') # The 3d mesh is just mesh mesh_3d = mesh # Mesh for 2d is EmbeddedMesh using tags (1, 2, 3, 4) mesh_2d = EmbeddedMesh(surfaces, (1, 2, 3, 4)) # 1d mesh from tagged facets of 2d facet_f = curve_gen(mesh_2d) mesh_1d = EmbeddedMesh(facet_f, 1) return mesh_3d, mesh_2d, mesh_1d def boring(mesh_2d, inner_size): ''' A mesh2d is assumed to be be a cube [-inner_size, inner_size]^2. The curve is mostly a collection of boundary edges. ''' facet_f = df.MeshFunction('size_t', mesh_2d, 1, 0) mesh_2d.init(2, 1) # Mesh for the curve is tricky as we need to find the line in the faces def union(domains, A=inner_size, tol=1E-10): def body(domains): if isinstance(domains, str): if domains: return '( %s )' % domains else: return '' else: return ' || '.join(map(body, domains)) return df.CompiledSubDomain(body(domains), A=A, tol=tol) lines = {4: union('near(x[1], A, tol) && near(x[2], A, tol)'), 3: union('near(x[2], -x[0], tol)'), 2: union('near(x[2], x[1], tol)'), 1: union(['near(x[0], -A, tol) && near(x[2], -A, tol)', 'near(x[1], A, tol) && near(x[0], -A, tol)', 'near(x[1], -A, tol) && near(x[0], -A, tol)'])} for tag, line in lines.items(): # Get candidates facets = set(sum((cell.entities(1).tolist() for cell in df.SubsetIterator(mesh_2d.marking_function, tag)) , [])) for facet in facets: if line.inside(df.Facet(mesh_2d, facet).midpoint().array(), True): facet_f[int(facet)] = 1 return facet_f def fun(mesh2d, nselects): '''A random curve from the edges''' import networkx as nx import random facet_f = df.MeshFunction('size_t', mesh2d, 1, 0) mesh2d.init(1, 0) # Init the graph G = nx.Graph() edge_indices = {tuple(sorted(facet.entities(0).tolist())): f_index for f_index, facet in enumerate(df.facets(mesh2d))} G.add_edges_from(iter(edge_indices.keys())) vertices = list(range(mesh2d.num_vertices())) for _ in range(nselects): v0, v1 = random.sample(vertices, 2) if v0 == v1: continue # THe path is a shortest path between 2 random vertices path = nx.shortest_path(G, source=v0, target=v1) for v0, v1 in zip(path[:-1], path[1:]): edge = (v0, v1) if v0 < v1 else (v1, v0) facet_f[edge_indices[edge]] = 1 return facet_f # -------------------------------------------------------------------- if __name__ == '__main__': load(0.5, 0.5, lambda mesh: fun(mesh, 20))
python
16
0.535171
87
31.517241
174
starcoderdata
public double getAvgLinkDistance() { getOutLinks(); getWordMap(); double linkPairs = 0; double distance = 0; // Loop all link pairs for (Map.Entry<String, Integer> outLink1 : outLinks) { for (Map.Entry<String, Integer> outLink2 : outLinks) { int order = outLink1.getKey().compareTo(outLink2.getKey()); if (order > 0) { int w1 = wordMap.floorEntry(outLink1.getValue()).getValue(); int w2 = wordMap.floorEntry(outLink2.getValue()).getValue(); distance += max(abs(w1 - w2), 1); linkPairs++; } } } return distance / linkPairs; }
java
16
0.5
80
31.565217
23
inline
package io.github.toquery.framework.common.constant; import com.google.common.collect.Sets; import java.util.Set; /** * @author toquery * @version 1 */ public class AppDomainTreeFieldConstant { public static final String DOMAIN_TREE_FIELD_ID = "id"; public static final String DOMAIN_TREE_FIELD_PARENTID = "parentId"; public static final String DOMAIN_TREE_FIELD_LEVEL = "level"; public static final String DOMAIN_TREE_FIELD_PARENTIDS = "parentIds"; public static final String DOMAIN_TREE_FIELD_HAS_CHILDREN = "hasChildren"; public static final String DOMAIN_TREE_FIELD_CHILDREN = "children"; public static final Set ENTITY_TREE_FIELD = Sets.newHashSet( DOMAIN_TREE_FIELD_ID, DOMAIN_TREE_FIELD_PARENTID, DOMAIN_TREE_FIELD_LEVEL, DOMAIN_TREE_FIELD_PARENTIDS, DOMAIN_TREE_FIELD_HAS_CHILDREN, DOMAIN_TREE_FIELD_CHILDREN); }
java
7
0.693531
78
27.575758
33
starcoderdata
DoubleMatrix SBMLSolver::getReducedJacobian(double h) { get_self(); check_model(); if (h <= 0) { h = self.roadRunnerOptions.jacobianStepSize; } int nIndSpecies = self.model->getNumIndFloatingSpecies(); // result matrix DoubleMatrix jac(nIndSpecies, nIndSpecies); // get the row/column ids, independent floating species std::list<std::string> list; self.model->getIds(SelectionRecord::INDEPENDENT_FLOATING_AMOUNT, list); std::vector<std::string> ids(list.begin(), list.end()); assert(ids.size() == nIndSpecies && "independent species ids length != getNumIndFloatingSpecies"); jac.setColNames(ids); jac.setRowNames(ids); // need 2 buffers for rate central difference. std::vector<double> dy0v(nIndSpecies); std::vector<double> dy1v(nIndSpecies); double* dy0 = &dy0v[0]; double* dy1 = &dy1v[0]; // function pointers to the model get values and get init values based on // if we are doing amounts or concentrations. typedef int (ExecutableModel::*GetValueFuncPtr)(int len, int const *indx, double *values); typedef int (ExecutableModel::*SetValueFuncPtr)(int len, int const *indx, double const *values); GetValueFuncPtr getValuePtr = 0; GetValueFuncPtr getRateValuePtr = 0; SetValueFuncPtr setValuePtr = 0; if (Config::getValue(Config::SBMLSOLVER_JACOBIAN_MODE).convert<unsigned>() == Config::SBMLSOLVER_JACOBIAN_MODE_AMOUNTS) { Log(Logger::LOG_DEBUG) << "getReducedJacobian in AMOUNT mode"; getValuePtr = &ExecutableModel::getFloatingSpeciesAmounts; getRateValuePtr = &ExecutableModel::getFloatingSpeciesAmountRates; setValuePtr = &ExecutableModel::setFloatingSpeciesAmounts; } else { Log(Logger::LOG_DEBUG) << "getReducedJacobian in CONCENTRATION mode"; getValuePtr = &ExecutableModel::getFloatingSpeciesConcentrations; getRateValuePtr = &ExecutableModel::getFloatingSpeciesAmountRates; setValuePtr = &ExecutableModel::setFloatingSpeciesConcentrations; } for (int i = 0; i < nIndSpecies; ++i) { double savedVal = 0; double y = 0; // current value of species i (self.model->*getValuePtr)(1, &i, &savedVal); // get the entire rate of change for all the species with // species i being value(i) + h; y = savedVal + h; (self.model->*setValuePtr)(1, &i, &y); (self.model->*getRateValuePtr)(nIndSpecies, 0, dy0); // get the entire rate of change for all the species with // species i being value(i) - h; y = savedVal - h; (self.model->*setValuePtr)(1, &i, &y); (self.model->*getRateValuePtr)(nIndSpecies, 0, dy1); // restore original value (self.model->*setValuePtr)(1, &i, &savedVal); // matrix is row-major, so have to copy by elements for (int j = 0; j < nIndSpecies; ++j) { jac(j, i) = (dy0[j] - dy1[j]) / (2.0*h) ; } } return jac; }
c++
14
0.631868
102
33.388889
90
inline
<?php namespace Marketredesign\MrdAuth0Laravel\Facades; use Illuminate\Http\Resources\Json\ResourceCollection; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Facade; use Marketredesign\MrdAuth0Laravel\Contracts\DatasetRepository; use Marketredesign\MrdAuth0Laravel\Repository\Fakes\FakeDatasetRepository; /** * @method static Collection getUserDatasetIds() * @method static ResourceCollection getUserDatasets() * @method static int fakeCount() * @method static void fakeClear() * @method static void fakeAddDatasets(Collection $ids) * * @see DatasetRepository * @see FakeDatasetRepository */ class Datasets extends Facade { public static function fake() { self::$app->singleton(DatasetRepository::class, FakeDatasetRepository::class); } /** * @inheritDocs */ protected static function getFacadeAccessor() { return DatasetRepository::class; } }
php
10
0.749471
86
24.567568
37
starcoderdata
using System.Collections.Generic; using GameFramework; namespace GameMain { public class ActorBuff : IActorBuff { private readonly List m_DelBuffList = new List private readonly Map<int, BuffBase> m_BuffMap = new Map<int, BuffBase>(); private ActorBase m_Owner; public ActorBuff(ActorBase owner) { this.m_Owner = owner; } public void AddBuff(int id, ActorBase caster) { if (m_Owner.IsDead) { return; } DRBuff db = GameEntry.DataTable.GetDataTable if (db == null) { return; } BuffBase commonBuff = FindBuff(id); if (commonBuff != null) { switch ((BuffOverlayType)commonBuff.Data.OverlayType) { case BuffOverlayType.Overlay: commonBuff.Overlay(); break; case BuffOverlayType.Reset: commonBuff.Refresh(); break; case BuffOverlayType.Cancle: m_DelBuffList.Add(commonBuff.Id); break; } return; } CommandReplyType reply = CommandReplyType.NO; switch ((BattleActType)db.Result) { case BattleActType.Addattr: case BattleActType.Subattr: case BattleActType.Lddattr: case BattleActType.Lubattr: { reply = CommandReplyType.YES; } break; case BattleActType.Super: { reply = CommandReplyType.YES; } break; case BattleActType.Variation: { reply = m_Owner.ExecuteCommand(new VariationCommand(db.LifeTime, db.ChangeModelID)); } break; case BattleActType.Hitfly: { reply = m_Owner.ExecuteCommand(new BeatFlyCommand()); } break; case BattleActType.Hitdown: { reply = m_Owner.ExecuteCommand(new BeatDownCommand()); } break; case BattleActType.Hitback: { reply = m_Owner.ExecuteCommand(new BeatBackCommand()); } break; case BattleActType.Stun: { reply = m_Owner.ExecuteCommand(new StunCommand(db.LifeTime)); } break; case BattleActType.Fixbody: { reply = m_Owner.ExecuteCommand(new FixBodyCommand(db.LifeTime)); } break; case BattleActType.Stealth: { reply = m_Owner.ExecuteCommand(new StealthCommand(db.LifeTime)); } break; case BattleActType.Frozen: { reply = m_Owner.ExecuteCommand(new FrostCommand(db.LifeTime)); } break; case BattleActType.Blind: { reply = m_Owner.ExecuteCommand(new BlindCommand(db.LifeTime)); } break; case BattleActType.Silent: { reply = m_Owner.ExecuteCommand(new SilentCommand(db.LifeTime)); } break; case BattleActType.Sleep: { reply = m_Owner.ExecuteCommand(new SleepCommand(db.LifeTime)); } break; case BattleActType.Absorb: { reply = CommandReplyType.YES; } break; case BattleActType.Wild: { reply = CommandReplyType.YES; } break; case BattleActType.Divive: { RemoveAllDebuff(); reply = CommandReplyType.YES; } break; case BattleActType.Paraly: { reply = CommandReplyType.YES; } break; case BattleActType.Fear: { reply = CommandReplyType.YES; } break; case BattleActType.Reflex: { reply = CommandReplyType.YES; } break; case BattleActType.Dead: { reply = CommandReplyType.YES; } break; } if (reply == CommandReplyType.YES) { BuffBase buff = new BuffBase(id, m_Owner, caster); m_BuffMap.Add(id, buff); } m_Owner.UpdateCurAttribute(); } public void Step() { if(m_Owner.IsDead) return; if (m_BuffMap.Count > 0) { for (m_BuffMap.Begin(); m_BuffMap.Next();) { BuffBase buff = m_BuffMap.Value; buff.Update(); if (buff.IsDead) { m_DelBuffList.Add(buff.Id); } } } for (int i = 0; i < m_DelBuffList.Count; i++) { int id = m_DelBuffList[i]; if (m_BuffMap.ContainsKey(id)) { m_BuffMap[id].Exit(); m_BuffMap.Remove(id); } } if (m_DelBuffList.Count > 0) { m_Owner.UpdateCurAttribute(); m_DelBuffList.Clear(); } } public Map<int, BuffBase> GetAllBuff() { return m_BuffMap; } public void SetAllEffectEnable(bool enabled) { Map<int, BuffBase>.Enumerator em = m_BuffMap.GetEnumerator(); while (em.MoveNext()) { BuffBase buff = em.Current.Value; buff.SetEffectEnable(enabled); } em.Dispose(); } public void Clear() { RemoveAllBuff(); } public BuffBase FindBuff(int id) { BuffBase buff = null; m_BuffMap.TryGetValue(id, out buff); return buff; } public void RemoveBuff(int id) { m_DelBuffList.Add(id); } public void RemoveAllDot() { for (m_BuffMap.Begin(); m_BuffMap.Next();) { if ((BattleActType) m_BuffMap.Value.Data.Result == BattleActType.Lubattr) { m_DelBuffList.Add(m_BuffMap.Key); } } } public void RemoveAllDebuff() { for (m_BuffMap.Begin(); m_BuffMap.Next();) { if ((BuffType) m_BuffMap.Value.Data.BuffType == BuffType.Debuff) { m_DelBuffList.Add(m_BuffMap.Key); } } } public void RemoveAllControl() { for (m_BuffMap.Begin(); m_BuffMap.Next();) { if (IsControlBuff(m_BuffMap.Value)) { m_DelBuffList.Add(m_BuffMap.Key); } } } public void RemoveAllBuff() { for (m_BuffMap.Begin(); m_BuffMap.Next();) { m_DelBuffList.Add(m_BuffMap.Value.Id); } } private bool IsControlBuff(BuffBase buff) { switch ((BattleActType)buff.Data.Result) { case BattleActType.Blind: case BattleActType.Fear: case BattleActType.Fixbody: case BattleActType.Frozen: case BattleActType.Paraly: case BattleActType.Sleep: case BattleActType.Stun: case BattleActType.Variation: return true; } return false; } } }
c#
20
0.399556
108
29.945017
291
starcoderdata
def _collect_experiment_results(self, ec): LOG.info("Collecting experiment results ...") # generate result paths dst_path = os.path.join(self.args.result_dir, ec.name) # for each container collect files from containers for c in self.emudocker.list_emu_containers(): c_dst_path = os.path.join(dst_path, c.name) self.emudocker.copy_folder(c.name, PATH_SHARE, c_dst_path) # for each container collect log outputs and write to files for c in self.emudocker.list_emu_containers(): c_dst_path = os.path.join(dst_path, c.name) self.emudocker.store_logs( c.name, os.path.join(c_dst_path, PATH_CONTAINER_LOG)) # colelct and store continous monitoring data # self.emudocker_mon.store_stats( # os.path.join(dst_path, PATH_CONTAINER_MON)) # collect and store vim-emu metrics (e.g. instantiation times) self.llcmc.store_stats( os.path.join(dst_path, PATH_LLCM_STATS)) # store experiment timestamps to do mapping to Prometheus data self._store_times( os.path.join(dst_path, PATH_EXPERIMENT_TIMES))
python
11
0.632378
70
52.954545
22
inline
[Test] public void TestSplitGONoEndLine() { string[] scripts = null; scripts = BatchSqlParser.SplitBatch(@" 1:1 1:2 GO"); //should be 1 script with no 'GO' Assert.AreEqual(1, scripts.Length); Assert.IsFalse(scripts[0].Contains("GO")); }
c#
13
0.666667
45
22.272727
11
inline
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Assimp; using Assimp.Configs; using RayTracing.Materials; using RayTracing.Maths; namespace RayTracing.Models { public class ModelLoader { private const string ModelsPath = "RayTracer.Resources.Models."; public static CustomModel Load(string path, bool loadFromExe = false) { return Load(path, PostProcessSteps.Triangulate | PostProcessSteps.GenerateNormals | PostProcessSteps.JoinIdenticalVertices | PostProcessSteps.FixInFacingNormals, loadFromExe); } public static CustomModel Load(string path, PostProcessSteps ppSteps, bool loadFromExe = false, params PropertyConfig[] configs) { Log.Info($"Loading model: {path}"); var model = new CustomModel(); if (!File.Exists(path) && !loadFromExe) { Log.Error($"Model {path} does not exist."); return model; } var importer = new AssimpContext(); if (configs != null) { foreach (var config in configs) importer.SetConfig(config); } try { Scene scene; if (loadFromExe) { var assembly = Assembly.GetAssembly(typeof(ModelLoader)); Stream stream = assembly.GetManifestResourceStream(ModelsPath + path); scene = importer.ImportFileFromStream(stream, ppSteps, Path.GetExtension(path)); stream.Dispose(); } else { scene = importer.ImportFile(path, ppSteps); } if (scene == null) { Log.Error($"Error loading model {path}. Scene was null."); return model; } if (scene.Meshes.Count == 0) { Log.Error($"Error loading model {path}. No meshes found."); return model; } if (scene.Meshes.Count > 1) { Log.Warn($"Model {path} containing more than one mesh. Using first mesh."); } var mesh = new Mesh(new List new List new List new List for (int i = 0; i < scene.MeshCount; i++) { mesh += ProcessMesh(scene.Meshes[i]); } var material = ProcessMaterial(scene.Materials[scene.Meshes[0].MaterialIndex], loadFromExe ? "" : Path.GetDirectoryName(Path.GetFullPath(path))); model.Mesh = mesh; model.Material = material; return model; } catch (AssimpException e) { Log.Error("Assimp has thrown an exception.", e); Console.WriteLine(e.Message); return model; } } private static IMaterial ProcessMaterial(Assimp.Material material, string dir) { Log.Info($"Processing material:: {material.Name}"); return new MasterMaterial { Emissive = { Albedo = ProcessTexture(material.HasTextureAmbient, material.ColorAmbient, material.TextureAmbient, dir) }, Diffuse = { Albedo = ProcessTexture(material.HasTextureDiffuse, material.ColorDiffuse, material.TextureDiffuse, dir) }, Reflective = { Albedo = ProcessTexture(material.HasTextureSpecular, material.ColorSpecular, material.TextureSpecular, dir), Disturbance = Math.Min(Math.Max(1 - material.ShininessStrength / 100, 0), 1) }, Parts = ProcessMaterialParts(material.ColorAmbient, material.ColorDiffuse, material.ColorSpecular) }; } private static ITexture ProcessTexture(bool hasTexture, Color4D color4, TextureSlot textureSlot, string dir) { Log.Info($"Processing texture:: hasTex:{hasTexture}, Color: {color4}, Texture:{textureSlot.FilePath}"); return hasTexture ? (ITexture) new Texture(Path.Combine(dir, textureSlot.FilePath)) : new SolidColor(Color.FromAssimpColor4(color4)); } private static (float emissive, float diffuse, float reflective, float refractive) ProcessMaterialParts( Color4D ambient, Color4D diffuse, Color4D specular) { (float emissive, float diffuse, float reflective, float refractive) parts = (Color.FromAssimpColor4(ambient).GetBrightness(), Color.FromAssimpColor4(diffuse).GetBrightness(), Color.FromAssimpColor4(specular).GetBrightness(), 0); return parts; } private static Mesh ProcessMesh(Assimp.Mesh mesh) { var positions = ProcessVertices(mesh); var textures = ProcessTextCoord(mesh); var normals = ProcessNormals(mesh); var indices = ProcessIndices(mesh); return new Mesh(positions, normals, textures, indices); } private static List ProcessVertices(Assimp.Mesh mesh) { List vertices = new List foreach (var v in mesh.Vertices) { vertices.Add(v.X); vertices.Add(v.Y); vertices.Add(v.Z); } return vertices; } private static List ProcessTextCoord(Assimp.Mesh mesh) { List textCoord = new List if (mesh.HasTextureCoords(0)) foreach (var tc in mesh.TextureCoordinateChannels[0]) { textCoord.Add(tc.X); textCoord.Add(1 - tc.Y); } return textCoord; } private static List ProcessNormals(Assimp.Mesh mesh) { List normals = new List foreach (var n in mesh.Normals) { normals.Add(n.X); normals.Add(n.Y); normals.Add(n.Z); } return normals; } private static List ProcessIndices(Assimp.Mesh mesh) { List indices = new List foreach (var f in mesh.Faces) { foreach (var ind in f.Indices) { indices.Add(ind); } } return indices; } } }
c#
23
0.50896
136
33.745098
204
starcoderdata
import tweepy import fileOp consumer_key = '' consumer_secret = '' access_token = '' access_token_secret = '' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) def login(): print(auth.get_authorization_url()) verifier = input('Verifier:').strip() acc = auth.get_access_token(verifier) print(acc) auth.set_access_token(acc[0], acc[1]) # self.auth = tweepy.OAuthHandler(acc[0], acc[1]) # self.auth.set_access_token(acc[0], acc[1]) fileOp.writeFile(auth.get_username(), str(acc[0]), str(acc[1])) return auth
python
10
0.681607
67
22.107143
28
starcoderdata
#!/Users/RobbyMiller/opt/anaconda3/bin/python """ A basic script to filter a fasta file of sequences by size - a useful step to remove partial sequences or sequences that would potentially introduce a large number of gaps in the alignment. This script reads in the alignment, computes the average sequence length, and outputs a new alignment that keeps sequences of length mean +/- tolerance (tolerance default = 50) :Arguments: Input_MSA.fasta (the alignment to be processed) :Keyword Arguments: --tolerance, -t allowable sequence length variation (in number of amino acids), default: 50 --output output file name, default: FilteredAln.fa :By: :On: 6.5.2015 Copyright (C) 2015 This program is free software distributed under the BSD 3-clause license, please see the file LICENSE for details. """ import scaTools as sca import numpy as np import argparse if __name__ =='__main__': #parse inputs parser = argparse.ArgumentParser() parser.add_argument("alignment", help='Input Sequence Alignment') parser.add_argument("-t","--tolerance", dest = "tol", type = int, default = 50, help="allowable sequence length variation in number of amino acids (alignment will be trimmed to mean +/- tolerance, default = 50)") parser.add_argument("--output", dest="outputfile", default = 'FilteredAln.fa', help="specify an outputfile name") options = parser.parse_args() headers, seqs = sca.readAlg(options.alignment) seqLen = np.zeros((len(seqs),1)).astype(int) for i,k in enumerate(seqs): seqLen[i] = len(k) avgLen = seqLen.mean() print ("Average sequence length: %i" % avgLen) print ("Min: %i, Max %i" % (seqLen.min(), seqLen.max())) minsz = avgLen - options.tol; maxsz = avgLen + options.tol; print ("Keeping sequences in the range: %i - %i" % (minsz, maxsz)) keepSeqs = list() keepHeaders = list() for i,k in enumerate(seqLen): if (k > minsz) & (k < maxsz): keepSeqs.append(seqs[i]) keepHeaders.append(headers[i]) print ("Keeping %i of %i total sequences" % (len(keepSeqs), len(seqLen))) f = open(options.outputfile, 'w') for i,k in enumerate(keepSeqs): f.write('>%s\n' % keepHeaders[i]) f.write('%s\n' % keepSeqs[i]) f.close()
python
12
0.631684
366
40.766667
60
starcoderdata
import glamorous from 'glamorous'; import image from '../assets/image.jpg'; const imageUrl = `url('${image}')`; export const PresentationContainer = glamorous.div({ display: 'flex', justifyContent: 'center', alignItems: 'center', textAlign: 'center', fontSize: 'x-large', backgroundColor: '#FCFBF9', '@media (max-height : 480px)': { paddingTop: '20%', paddingBottom: '20%', }, '@media (min-height : 481px)': { '@media (max-width : 500px)': { paddingTop: '40%', paddingBottom: '40%', }, '@media (min-width : 500px)': { paddingTop: 170, paddingBottom: 170, } } }); export const Name = glamorous.h1({ '@media (max-width: 600px)': { fontSize: '1.5em', } }); export const Role = glamorous.h4({ fontWeight: 'normal' }); export const AboutMeContainer = glamorous.div({ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', backgroundColor: '#547980', color: 'white', '@media (max-width: 1024px)': { paddingTop: 20, paddingBottom: 20, }, }); export const AboutMeTitle = glamorous.h1({ fontWeight: 'normal' }); export const AboutMeContent = glamorous.div({ fontSize: 'large', display: 'flex', '@media (max-width: 1024px)': { alignItems: 'center', flexDirection: 'column', width: '80%', }, '@media (min-width: 1024px)': { width: '60%', }, }); export const AvatarWrapper = glamorous.div({ height: 'inherit', display: 'flex', alignItems: 'center' }); export const Avatar = glamorous.div({ '@media (max-width: 599px)': { height: 150, width: 150, margin: 10, }, '@media (min-width: 600px)': { height: 150, width: 150, margin: '20px 40px 20px 20px', }, flex: '1 0 auto', textAlign: 'center', backgroundImage: imageUrl, backgroundPosition: 'center', color: 'rgba(0, 0, 0, 0.87)', backgroundColor: 'rgb(255, 255, 255)', transition: 'all 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms', boxSizing: 'border-box', boxShadow: 'rgba(0, 0, 0, 0.19) 0px 10px 30px, rgba(0, 0, 0, 0.23) 0px 6px 10px', borderRadius: '50%' });
javascript
8
0.612933
83
21.329897
97
starcoderdata
@Test public void testFoo() throws SQLException, RichSQLException { List<Integer> ints = Arrays.asList(5963, 4649); List<String> strings = Arrays.asList("John", "Manjiro"); Foo foo = this.orm.insert(Foo.class).value("csvInt", ints) .value("csvString", strings).executeSelect(); assertEquals(foo.getCsvInt().size(), 2); assertEquals(foo.getCsvInt().get(0), (Integer)5963); assertEquals(foo.getCsvInt().get(1), (Integer)4649); assertEquals(foo.getCsvString().size(), 2); assertEquals(foo.getCsvString().get(0), "John"); assertEquals(foo.getCsvString().get(1), "Manjiro"); // updateByBean { FooUpdateForm fooUpdateForm = new FooUpdateForm(); List<Integer> ints2 = Arrays.asList(123, 456); fooUpdateForm.setCsvInt(ints2); foo.update() .setBean(fooUpdateForm) .execute(); assertEquals(foo.refetch().get().getCsvInt().get(0).intValue(), 123); } // updateByBean(no UPDATE query required. Because the data set is same) { FooUpdateForm fooUpdateForm = new FooUpdateForm(); List<Integer> ints2 = Arrays.asList(123, 456); // same as previous fooUpdateForm.setCsvInt(ints2); foo.update() .setBean(fooUpdateForm) .execute(); assertEquals(foo.refetch().get().getCsvInt().get(0).intValue(), 123); } }
java
13
0.68652
73
33.513514
37
inline
package org.miss.redis.client; /** * @project: miss-redis-plugin * @package: org.miss.redis.client * @author: miss * @since: 2020/7/27 18:26 * @history: 1.2020/7/27 created by miss */ public class KeyTask { private String key; private String keyType; public KeyTask() {} }
java
5
0.654237
40
16.352941
17
starcoderdata
public void clearErrorMode(){ //Clear the flag. this.errorMode = false; //Clear the text field. settfResult(""); //Empty the BigDecimal container. clearResult(); }
java
7
0.681818
35
21.125
8
inline
const VERSION = "6.00.5" function isFirstTime () { if (Keywords.get()) { return false } else { /* for in-game text search, visit: https://strings.wakingsands.com/ */ let defaultWords = [ "招募队员结束,队员已经集齐", "成功完成了探险", "招募队员结束,招募期限已过", ] for (let word of defaultWords) { Keywords.add(word) } return true } } function i18n () { // default $(".chinese").hide() $(".english").show() // translate callOverlayHandler({call: "getLanguage"}).then((lang) => { if (lang.language == 'Chinese') { $(".chinese").show() $(".english").hide() } }) } const Config = { get: function (key) { return window.localStorage.getItem(`keywordnotif:config:${key}`) }, set: function (key, value) { return window.localStorage.setItem(`keywordnotif:config:${key}`, value) }, } const Keywords = { get: function () { let keywords = Config.get('keyword') return keywords ? keywords.split(',') : null }, updateHtml: function () { $("#keyword-div .keyword").remove() let keywords = Keywords.get() || [] for (let kw of keywords) { if (kw) { $("#keyword-div").append(`<span class="mr-1 keyword btn btn-outline-dark text-white btn-sm bg-opacity-dark" onclick="Keywords.remove('${kw}')">${kw} } } }, add: function (kw) { let keywords = Keywords.get() let newKeywords = keywords ? keywords.concat(kw) : [].concat(kw) Config.set('keyword', newKeywords.join(',')) Keywords.updateHtml() }, remove: function (kw) { let keywords = Keywords.get() keywords.splice(keywords.indexOf(kw), 1) Config.set('keyword', keywords.join(',')) Keywords.updateHtml() }, toggle: function (kw) { if (Keywords.get().indexOf(kw) >= 0) { // keyword already exists. Keywords.remove(kw) } else { Keywords.add(kw) } } } const PartySay = { checkbox: () => document.querySelector("input[name='partysay']"), updateHtml: () => PartySay.load(), ready: () => PartySay.checkbox().checked ? true : false, save: () => Config.set("partysay:on", PartySay.checkbox().checked ? "on" : "off"), load: () => PartySay.checkbox().checked = Config.get("partysay:on") === "on" ? true : false, } const NpcSay = { checkbox: () => document.querySelector("input[name='npcsay']"), updateHtml: () => NpcSay.load(), ready: () => NpcSay.checkbox().checked ? true : false, save: () => Config.set("npcsay:on", NpcSay.checkbox().checked ? "on" : "off"), load: () => NpcSay.checkbox().checked = Config.get("npcsay:on") === "on" ? true : false, } const Tts = { checkbox: () => document.querySelector("input[name='tts']"), updateHtml: () => Tts.load(), ready: () => Tts.checkbox().checked ? true : false, save: () => Config.set("tts:on", Tts.checkbox().checked ? "on" : "off"), load: () => Tts.checkbox().checked = Config.get("tts:on") === "on" ? true : false, send: (data) => { // text to speech if (Tts.ready()) { callOverlayHandler({ call: 'say', text: data }) } } } const Webhook = { checkbox: () => document.querySelector("input[name='webhook']"), get: () => { let url = Config.get('webhook:url') let key = Config.get('webhook:key') if (url && key) { return { url: url, key: key } } return null }, set: ({url, key} = {}) => { Config.set("webhook:url", url ? url : "") Config.set("webhook:key", key ? key : "text") Webhook.updateHtml() }, updateHtml: () => { let webhook = Webhook.get() if (webhook) { $("#webhook-btn").show() $("#webhook-info > code").text(webhook.url + ` :` + webhook.key) } else { $("#webhook-btn").hide() $("#webhook-info > code").text("") Webhook.checkbox().checked = false } Webhook.load() }, ready: () => (Webhook.get() && Webhook.checkbox().checked) ? true : false, save: () => Config.set("webhook:on", Webhook.checkbox().checked ? "on" : "off"), load: () => Webhook.checkbox().checked = Config.get("webhook:on") === "on" ? true : false, send: (data) => { // text to webhook if (Webhook.ready()) { if (Webhook.get().url.search("discord.com") >= 0) { // discord.com need application/json with preflight $.ajax({ url: Webhook.get().url, type: "POST", data: JSON.stringify({"content": data}), contentType: "application/json; charset=utf-8", }) } else { // slack.com does not support preflight, so let param = {} param[Webhook.get().key] = data $.post(Webhook.get().url, JSON.stringify(param)) } } }, hello: () => { // send a message when checkbox is checked. if (Webhook.checkbox().checked) { Webhook.send("Webhook: ON") } }, } function toggleHelp () { $('#help-div').slideToggle('fast') $('#webhook-info').slideToggle('fast') } function update (data) { if (!data.line) { return null } let [logType, logTime, ...logProperties] = data.line /* for more log types, visit: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#00-logline */ // console.debug(`logtype:${logType} -> ${logProperties}`) if (logType === '00') { let [logSubtype, logChar, logText, logId] = logProperties logSubtype = logSubtype.toLowerCase() // Both '003D' and '003d' works. for (let kw of Keywords.get()) { if (kw && logText && logText.includes(kw)) { Tts.send(logText) Webhook.send(logText) } } if (logText.startsWith("关键字 ") || logText.startsWith("keyword ")) { let kw = logText.split(' ')[1] return Keywords.toggle(kw) } if (logText.startsWith("webhook")) { let [ignore, url=null, key='text'] = logText.split(' ') if (url) { Webhook.set({ url: url, key: key }) } else { Webhook.set() } } if (logSubtype == '003d') { // Npc conversation. if (NpcSay.ready()) { Tts.send(logText) // logText contains only the content. logChar for NPC name. } //console.debug(`logSubtype:${logSubtype} -> ${logProperties}`) } if (logSubtype == '000e') { // Party Member Conversation. if (PartySay.ready()) { Webhook.send("/p " + logChar + ": " + logText) Tts.send(logChar + ": " + logText) } } if (logSubtype == '2239') { // Party Makeup Change. if (PartySay.ready()) { Webhook.send("/p " + logText) Tts.send(logText) } } if (logSubtype == '001b') { // Newbie Channel. // "/n " + logChar + ": " + logText } if (logSubtype == '001c') { // Emotion Channel. // logChar + ": " + logText } if (logSubtype == '0039') { // System Channel. // logText } } } /* for more event types, visit: https://ngld.github.io/OverlayPlugin/devs/event_types */ addOverlayListener("LogLine", (e) => update(e)) startOverlayEvents() $(function () { if (!isFirstTime()) { $('.hidable').hide() } i18n() Keywords.updateHtml() Webhook.updateHtml() Tts.updateHtml() NpcSay.updateHtml() PartySay.updateHtml() console.log(`[LOADED] FFXIV Keyword Notif: Version ${VERSION}`) })
javascript
21
0.509767
173
32.210744
242
starcoderdata
using System.Collections.Generic; using System.Text; using EcmaScript.NET; using Yahoo.Yui.Compressor; using WebMarkupMin.Core; using WebMarkupMin.Yui.Reporters; namespace WebMarkupMin.Yui { /// /// Minifier, which produces minifiction of JS-code by using the YUI JS Compressor for .NET /// public sealed class YuiJsMinifier : YuiMinifierBase, IJsMinifier { /// /// Settings of the YUI JS Minifier /// private readonly YuiJsMinificationSettings _settings; /// /// Error reporter /// private YuiJsErrorReporter _errorReporter; /// /// Original JS minifier /// private JavaScriptCompressor _originalJsMinifier; /// /// Synchronizer of minification /// private readonly object _minificationSynchronizer = new object(); /// /// Constructs an instance of the YUI JS Minifier /// public YuiJsMinifier() : this(new YuiJsMinificationSettings()) { } /// /// Constructs an instance of the YUI JS Minifier /// /// <param name="settings">Settings of the YUI JS Minifier public YuiJsMinifier(YuiJsMinificationSettings settings) { _settings = settings; } /// /// Creates a instance of original JS minifier /// /// <param name="settings">JS minifier settings /// of original JS minifier private static JavaScriptCompressor CreateOriginalJsMinifierInstance( YuiJsMinificationSettings settings) { var originalMinifier = new JavaScriptCompressor(); ApplyCommonSettingsToOriginalMinifier(originalMinifier, settings); originalMinifier.ObfuscateJavascript = settings.ObfuscateJavascript; originalMinifier.PreserveAllSemicolons = settings.PreserveAllSemicolons; originalMinifier.DisableOptimizations = settings.DisableOptimizations; originalMinifier.IgnoreEval = settings.IgnoreEval; return originalMinifier; } #region IJsMinifier implementation /// /// Gets a value indicating the minifier supports inline code minification /// public bool IsInlineCodeMinificationSupported { get { return false; } } /// /// Produces a code minifiction of JS content by using the YUI JS Compressor for .NET /// /// <param name="content">JS content /// <param name="isInlineCode">Flag whether the content is inline code /// JS content public CodeMinificationResult Minify(string content, bool isInlineCode) { return Minify(content, isInlineCode, TextEncodingShortcuts.Default); } /// /// Produces a code minifiction of JS content by using the YUI JS Compressor for .NET /// /// <param name="content">JS content /// <param name="isInlineCode">Flag whether the content is inline code /// <param name="encoding">Text encoding /// JS content public CodeMinificationResult Minify(string content, bool isInlineCode, Encoding encoding) { if (string.IsNullOrWhiteSpace(content)) { return new CodeMinificationResult(string.Empty); } string newContent = string.Empty; var errors = new List var warnings = new List lock (_minificationSynchronizer) { if (_errorReporter == null) { _errorReporter = new YuiJsErrorReporter(_settings.WarningLevel); } if (_originalJsMinifier == null) { _originalJsMinifier = CreateOriginalJsMinifierInstance(_settings); } _originalJsMinifier.ErrorReporter = _errorReporter; _originalJsMinifier.Encoding = encoding; try { newContent = _originalJsMinifier.Compress(content); } catch (EcmaScriptRuntimeException e) { errors.Add(new MinificationErrorInfo(e.Message, e.LineNumber, e.ColumnNumber, e.LineSource)); } catch (EcmaScriptException e) { errors.Add(new MinificationErrorInfo(e.Message, e.LineNumber, e.ColumnNumber, e.LineSource)); } finally { _originalJsMinifier.ErrorReporter = null; _originalJsMinifier.Encoding = TextEncodingShortcuts.Default; errors.AddRange(_errorReporter.Errors); warnings.AddRange(_errorReporter.Warnings); _errorReporter.Clear(); } } return new CodeMinificationResult(newContent, errors, warnings); } #endregion } }
c#
20
0.715775
98
27.531646
158
starcoderdata
<?php declare(strict_types=1); namespace Helpers\DataTables; use KikCMS\Classes\DataTable\SelectDataTable; class TestSelectDataTable extends SelectDataTable { public function getModel(): string { return ''; } public function getAlias(): ?string { return 'a'; } protected function initialize() { // nothing here... } }
php
7
0.629243
49
14.36
25
starcoderdata
package org.wso2.patchvalidator.revertor; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.wso2.patchvalidator.client.PmtClient; import org.wso2.patchvalidator.enums.PatchType; import org.wso2.patchvalidator.enums.ValidationType; import org.wso2.patchvalidator.exceptions.ServiceException; import org.wso2.patchvalidator.util.Util; import java.util.Collections; import java.util.List; /** * Revert PMT state when reverting patch. * Pre validate and Post validate to check whether particular patch can be reverted in PMT */ class PmtReverter { private static List overviewProducts = Collections.emptyList(); private static List overviewCompatibleProducts = Collections.emptyList(); private static String wumProductsJson = ""; private static String lifeCycleState = ""; /** * Revert PMT LC state. * * @param version carbon version * @param patchId 4 digit patch id * @param patchType patch type (patch, update, patch and update) * @return is PMT reverted for the given patch */ static boolean revertPmt(String version, String patchId, PatchType patchType) { boolean isPreValidated = false; boolean isPmtReverted = false; boolean isPostValidated = false; //pre validation, validate pmt json //pre validation does not apply for patches if (!(patchType == PatchType.PATCH)) { try { JSONObject pmtJson = PmtClient.getPatchInfo(version, patchId); isPreValidated = validatePatchInfo(pmtJson, ValidationType.PRE_VALIDATION); } catch (ServiceException ex) { throw new ServiceException("Pre validation failed, patch:" + version + "-" + patchId, ex.getDeveloperMessage(), ex); } } //revert pmt state if (isPreValidated || patchType == PatchType.PATCH) { try { isPmtReverted = PmtClient.revertPmtLcState(patchId, version); } catch (ServiceException ex) { throw new ServiceException("Exception occurred when reverting pmt state, patch:" + version + "-" + patchId, ex.getDeveloperMessage(), ex); } } //post validation, check pmt json whether patch is reverted //post validation does not apply for patches if (!(patchType == PatchType.PATCH)) { if (isPmtReverted) { JSONObject pmtJsonReverted = PmtClient.getPatchInfo(version, patchId); try { isPostValidated = validatePatchInfo(pmtJsonReverted, ValidationType.POST_VALIDATION); } catch (ServiceException ex) { throw new ServiceException("Exception occurred when post validating pmt json, patch:" + version + "-" + patchId, ex.getDeveloperMessage(), ex); } } } if (isPostValidated || patchType == PatchType.PATCH) { return true; } else if (isPmtReverted) { throw new ServiceException("pre validation successful, reverting pmt lc state successful," + " post validation failed," + " patch:" + version + "-" + patchId, "Pre validation successful, Reverting pmt lc state successful, Post validation failed," + " for the" + " patch \"" + version + "-" + patchId + "\", Please contact admin."); } else if (isPreValidated) { throw new ServiceException("pre validation successful, reverting pmt lc state failed," + " patch:" + version + "-" + patchId, "Pre validation successful, reverting pmt lc state failed, for the patch \"" + version + "-" + patchId + "\", Please contact admin."); } else { throw new ServiceException("pre validation failed" + " patch:" + version + "-" + patchId, "Pre validation failed for the" + " patch \"" + version + "-" + patchId + "\", " + "Please contact admin."); } } /** * Check patch info is valid. * * @param pmtJson patch info json * @param validationType validation type (pre, post) * @return is patch info validated */ private static boolean validatePatchInfo(JSONObject pmtJson, ValidationType validationType) { JSONArray pmtArray = (JSONArray) pmtJson.get("pmtResult"); for (Object aJsonArray : pmtArray) { JSONObject element = (JSONObject) aJsonArray; try { if (element.get("name").equals("overview_products")) { overviewProducts = Util.createListFromJsonArray((JSONArray) element.get("value")); } else if (element.get("name").equals("overview_compatibleProducts")) { overviewCompatibleProducts = Util.createListFromJsonArray((JSONArray) element.get("value")); } else if (element.get("name").equals("wum_productsJSON")) { wumProductsJson = Util.createListFromJsonArray((JSONArray) element.get("value")).get(0); } else if (element.get("name").equals("registry.lifecycle.PatchLifeCycle.state")) { lifeCycleState = Util.createListFromJsonArray((JSONArray) element.get("value")).get(0); } } catch (Exception ex) { throw new ServiceException("Exception occurred, pmt patch info is not valid", "Invalid patch information.", ex); } } if (validationType == ValidationType.PRE_VALIDATION) { if (overviewProducts.size() < 1) { throw new ServiceException("products list is empty", "Invalid patch information, " + "products list is empty. Please amend and re-submit."); } else if (overviewCompatibleProducts.size() < 1) { throw new ServiceException("compatible products list is empty", "Invalid patch information" + ", compatible products list is empty. Please amend and re-submit."); } else if (wumProductsJson.equals("")) { throw new ServiceException("products json is empty", "Invalid patch information" + ", compatible products list is empty. Please amend and re-submit."); } else if (!(lifeCycleState.equals("Staging"))) { throw new ServiceException("life cycle state should be Staging, lifeCycleState:" + lifeCycleState, "Invalid life cycle state \"" + lifeCycleState + "\". Please change life cycle " + "stage to \"Staging\" and re-submit."); } else { return true; } } else { //post validation if (overviewProducts.size() < 1) { throw new ServiceException("products list is empty", "Products list is empty after reverting" + " PMT, Please contact admin."); } else if (!(Util.listEqualsIgnoreOrder(overviewProducts, overviewCompatibleProducts))) { throw new ServiceException("products and compatible products lists are not having same products, " + "products:" + overviewProducts.toString() + " compatibleProducts:" + overviewCompatibleProducts.toString(), "products list and compatible products list is different after reverting PMT," + " Please contact admin."); } else if (!(wumProductsJson.equals(""))) { throw new ServiceException("products json should be empty, productsJson:" + wumProductsJson, "Products json is not empty after reverting PMT, Please contact admin."); } else if (!(lifeCycleState.equals("Testing"))) { throw new ServiceException("life cycle state should be Testing, state:" + lifeCycleState, "Life cycle state is \"" + lifeCycleState + "\" after reverting PMT, It should be" + "\"Testing\", Please contact admin"); } else { return true; } } } }
java
23
0.588053
121
50.140244
164
starcoderdata
using GameLogics.Shared.Command; using GameLogics.Shared.Model.State; using GameLogics.Shared.Model.Config; using Xunit; namespace UnitTests { public sealed class TakeOffItemCommandTest : BaseCommandTest { ulong _unitId; ulong _itemId; public TakeOffItemCommandTest() { _unitId = NewId(); _itemId = NewId(); _config.AddItem("item_desc", new WeaponConfig()); _state.AddUnit(new UnitState("unit_desc", 1).WithId(_unitId)); _state.Units[_unitId].Items.Add(new ItemState("item_desc").WithId(_itemId)); } [Fact] void CantTakeoffUnknownItem() { IsInvalid(new TakeOffItemCommand(InvalidId, _unitId)); } [Fact] void CantTakeoffFromUnknownUnit() { IsInvalid(new TakeOffItemCommand(_itemId, InvalidId)); } [Fact] void ItemWasRemovedFromUnit() { Execute(new TakeOffItemCommand(_itemId, _unitId)); Assert.DoesNotContain(_state.Units[_unitId].Items, it => (it.Id == _itemId)); } [Fact] void ItemWasAddedToInventory() { Execute(new TakeOffItemCommand(_itemId, _unitId)); Assert.True(_state.Items.ContainsKey(_itemId)); } } }
c#
17
0.700441
83
24.818182
44
starcoderdata
<?php use Illuminate\Database\Seeder; use App\Maskapai; class MaskapaiSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $kode = Maskapai::gen_kode(); Maskapai::create([ 'kode_maskapai' => $kode, 'kode_penerbangan' => '888', 'nama_maskapai' => 'Citilink', 'alias' => 'QG', 'status' => 'aktif' ]); $kode = Maskapai::gen_kode(); Maskapai::create([ 'kode_maskapai' => $kode, 'kode_penerbangan' => '990', 'nama_maskapai' => 'Lion Air', 'alias' => 'JT', 'status' => 'aktif' ]); $kode = Maskapai::gen_kode(); Maskapai::create([ 'kode_maskapai' => $kode, 'kode_penerbangan' => '938', 'nama_maskapai' => 'Batik', 'alias' => 'BTK', 'status' => 'aktif' ]); $kode = Maskapai::gen_kode(); Maskapai::create([ 'kode_maskapai' => $kode, 'kode_penerbangan' => '513', 'nama_maskapai' => 'Wings Air', 'alias' => 'WA', 'status' => 'aktif' ]); $kode = Maskapai::gen_kode(); Maskapai::create([ 'kode_maskapai' => $kode, 'kode_penerbangan' => '977', 'nama_maskapai' => 'Sriwijaya', 'alias' => 'SR', 'status' => 'aktif' ]); $kode = Maskapai::gen_kode(); Maskapai::create([ 'kode_maskapai' => $kode, 'kode_penerbangan' => '274', 'nama_maskapai' => 'Nam air', 'alias' => 'NA', 'status' => 'aktif' ]); } }
php
12
0.421171
43
24.014085
71
starcoderdata
'use strict'; var xhr = require('xhr'); var Promise = require('promise'); function mount() { console.log('Tollan app is mounting'); var React = this.React; var Router = this.Router; var appElement = document.getElementById('tollanApp'); Router.run(this.routes, Router.HistoryLocation, function(Handler) { console.time('render'); React.render(React.createElement(Handler), appElement, function() { console.timeEnd('render'); }); }); } function loadBundle(name) { // based on loadscript.js by epeli // https://gist.github.com/epeli/5384178 return new Promise((resolve, reject) => { if (this.SERVER) { return resolve(); } if (this.loadedBundles.indexOf(name) > -1) { return resolve(); } var src = '/' + name + '.js'; var script = document.createElement('script'); script.async = true; script.src = src; script.onerror = () => { reject(new Error("Failed to load" + src)); }; script.onload = () => { console.log('Loaded bundle: ' + name); this.loadedBundles.push(name); resolve(); }; document.getElementsByTagName("head")[0].appendChild(script); }); } var Tollan = require('./tollan'); Tollan.prototype.mount = mount; //Tollan.prototype.get = get; //Tollan.prototype.getModel = getModel; //Tollan.prototype.post = post; //Tollan.prototype.postAction = postAction; Tollan.prototype.SERVER = false; Tollan.prototype.loadBundle = loadBundle; module.exports = Tollan;
javascript
18
0.678937
69
23.04918
61
starcoderdata
package jdrivesync; import com.google.api.services.drive.model.File; import jdrivesync.exception.JDriveSyncException; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.Optional; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class ITRemoteRootDir extends BaseClass { private static final String TESTDATA = ITRemoteRootDir.class.getSimpleName(); @BeforeClass public static void beforeClass() { BaseClass.beforeClass(); } @Before public void before() throws IOException { super.beforeEachTest(TESTDATA, driveFactory); createTestData(TESTDATA); } private void createTestData(String name) throws IOException { deleteDirectorySubtree(Paths.get(basePathTestData(), name)); Files.createDirectory(Paths.get(basePathTestData(), name)); Files.write(Paths.get(basePathTestData(), name, "test1.txt"), Arrays.asList("test1"), Charset.defaultCharset(), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE); Files.createDirectory(Paths.get(basePathTestData(), name, "folder")); Files.write(Paths.get(basePathTestData(), name, "folder", "test2.txt"), Arrays.asList("test2"), Charset.defaultCharset(), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE); } @Test public void testRemoteDirDoesNotExist() { options.setRemoteRootDir(Optional.of("DoesNotExist")); App app = new App(); boolean exceptionThrown = false; try { app.sync(options); } catch (Exception e) { exceptionThrown = true; assertThat(e instanceof JDriveSyncException, is(true)); assertThat(((JDriveSyncException) e).getReason(), is(JDriveSyncException.Reason.InvalidRemoteRootDirectory)); } assertThat(exceptionThrown, is(true)); } @Test public void testRemoteDirExists() { File rootRemoteDir = googleDriveAdapter.getFile("root"); googleDriveAdapter.createDirectory(rootRemoteDir, "backup"); sleep(); assertThat(googleDriveAdapter.listAll().size(), is(1)); options.setRemoteRootDir(Optional.of("backup")); App app = new App(); app.sync(options); sleep(); assertThat(googleDriveAdapter.listAll().size(), is(4)); } @Test public void testRemoteDirWithSubDirs() { File rootRemoteDir = googleDriveAdapter.getFile("root"); File backupDir = googleDriveAdapter.createDirectory(rootRemoteDir, "backup"); googleDriveAdapter.createDirectory(backupDir, "2014-10-05"); sleep(); assertThat(googleDriveAdapter.listAll().size(), is(2)); options.setRemoteRootDir(Optional.of("/backup/2014-10-05")); App app = new App(); app.sync(options); sleep(); assertThat(googleDriveAdapter.listAll().size(), is(5)); } @Test public void testRemoteDirAfterBasicSync() { App app = new App(); app.sync(options); sleep(); assertThat(googleDriveAdapter.listAll().size(), is(3)); options.setRemoteRootDir(Optional.of("/folder")); options.setLocalRootDir(Optional.of(Paths.get(options.getLocalRootDir().get().getAbsolutePath(), "folder").toFile())); app.sync(options); sleep(); assertThat(googleDriveAdapter.listAll().size(), is(3)); } }
java
17
0.677919
187
36.645833
96
starcoderdata
<?php namespace TikTokRESTAPI; use LazyJsonMapper\LazyJsonMapper; /** * Automatically maps JSON data onto PHP objects with virtual functions. * * Configures important core settings for the property mapping process. */ class AutoPropertyMapper extends LazyJsonMapper { /** @var bool */ const ALLOW_VIRTUAL_PROPERTIES = false; /** @var bool */ const ALLOW_VIRTUAL_FUNCTIONS = true; /** @var bool */ const USE_MAGIC_LOOKUP_CACHE = true; }
php
6
0.701493
72
20.318182
22
starcoderdata
import unittest from calculator import sum class TestCalculator(unittest.TestCase): def test_sum_5_and_5_should_return_10(self): self.assertEqual(sum(5, 5), 10) def test_sum_5_negative_and_5_should_return_0(self): self.assertEqual(sum(-5, 5), 0) def test_sum_many_entries(self): x_y_outputs = ( (10, 10, 20), (1.5, 3.5, 5), (-6, 10, 4), (-5, 5, 0), (-9, -6, -15), # (-9, -6, -90) # Error ) for x_y_output in x_y_outputs: with self.subTest(x_y_output=x_y_output): x, y, output = x_y_output self.assertEqual(sum(x, y), output) def test_sum_x_not_int_or_float_should_return_assertionerror(self): with self.assertRaises(AssertionError): sum('a', 11) def test_sum_y_not_int_or_float_should_return_assertionerror(self): with self.assertRaises(AssertionError): sum(11, 'a') unittest.main(verbosity=2)
python
14
0.670213
83
25.111111
36
starcoderdata
import { ADMIN_LICENSES_REFRESH_REQUEST, ADMIN_LICENSES_REFRESH_SUCCESS, ADMIN_LICENSES_REFRESH_FAIL, ADMIN_LICENSE_DELETE_REQUEST, ADMIN_LICENSE_DELETE_SUCCESS, ADMIN_LICENSE_DELETE_FAIL, ADMIN_LICENSE_ADD_REQUEST, ADMIN_LICENSE_ADD_SUCCESS, ADMIN_LICENSE_ADD_FAIL, } from 'src/actions/admin_licenses'; import { Map, fromJS } from 'immutable'; function normalizeLicenses(state, licenseList) { return state.set('licenses', fromJS(licenseList)); } function deleteLicense(state, licenseId) { let newState = []; state.get('licenses').map((license) => { if (license.get('id') !== licenseId) { newState.push(license); } }); return state.set('licenses', fromJS(newState)); } function addLicense(state, license) { let newState = state.get('licenses').toJS(); newState.push(license); return state.set('licenses', fromJS(newState)); } const initialState = Map({ licenses: null, }); export default function admin_licenses(state = initialState, action) { switch (action.type) { case ADMIN_LICENSES_REFRESH_SUCCESS: return normalizeLicenses(state, action.licenseList); case ADMIN_LICENSE_DELETE_SUCCESS: return deleteLicense(state, action.deletedLicenseId); case ADMIN_LICENSE_ADD_SUCCESS: return addLicense(state, action.addedLicense); case ADMIN_LICENSE_ADD_REQUEST: case ADMIN_LICENSE_ADD_FAIL: case ADMIN_LICENSE_DELETE_REQUEST: case ADMIN_LICENSE_DELETE_FAIL: case ADMIN_LICENSES_REFRESH_REQUEST: case ADMIN_LICENSES_REFRESH_FAIL: default: return state; } }
javascript
14
0.6854
70
28.232143
56
starcoderdata
/* * Copyright 2018 herd-mdl 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.tsi.mdlt.test.herd; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import io.restassured.response.Response; import org.apache.http.HttpStatus; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.tsi.mdlt.pojos.User; import org.tsi.mdlt.test.BaseTest; import org.tsi.mdlt.util.HerdRestUtil; import org.finra.herd.model.api.xml.BusinessObjectData; import org.finra.herd.model.api.xml.NamespacePermissionEnum; @Tag("authTest") public class HerdAuthorizationTest extends BaseTest { private static final User SEC_APP_USER = User.getLdapSecAppUser(); private static final User MDL_APP_USER = User.getLdapMdlAppUser(); private static final User HERD_RO_USER = User.getHerdRoUser(); private static final User HERD_ADMIN_USER = User.getHerdAdminUser(); private static final String NAMESPACE_MDL = "MDL"; private static final String NAMESPACE_SEC = "SEC_MARKET_DATA"; @Test public void readWriteNamespaceWithPermission() { String dataProvider = "MDLT_DP1"; LogStep("Call Write and Read non-namespace restricted endpoints with write permission"); assertEquals(HttpStatus.SC_OK, HerdRestUtil.postDataProvider(SEC_APP_USER, dataProvider).statusCode()); assertEquals(HttpStatus.SC_OK, HerdRestUtil.getDataProvider(SEC_APP_USER, dataProvider).statusCode()); assertEquals(HttpStatus.SC_OK, HerdRestUtil.deleteDataProvider(SEC_APP_USER, dataProvider).statusCode()); LogStep("Read business object data with namespace permission"); assertEquals(HttpStatus.SC_OK, HerdRestUtil.getBusinessObjectData(SEC_APP_USER, getSecBusinessObjectData()).statusCode()); LogStep("Read business object format with namespace permission"); assertEquals(HttpStatus.SC_OK, HerdRestUtil.getBusinessObjectFormat(SEC_APP_USER, getSecBusinessObjectData()).statusCode()); LogStep("Write with namespace permission"); BusinessObjectData secBusinessObjectData = getSecBusinessObjectData(); secBusinessObjectData.setBusinessObjectDefinitionName("InvalidValue"); assertTrue(HerdRestUtil.deleteBusinessObjectData(SEC_APP_USER, secBusinessObjectData).statusCode() != HttpStatus.SC_FORBIDDEN); } @Test public void readWriteToNamespaceWithoutPermission() { LogStep("Read business object data without namespace permission"); assertEquals(HttpStatus.SC_FORBIDDEN, HerdRestUtil.getBusinessObjectData(MDL_APP_USER, getSecBusinessObjectData()).statusCode()); LogStep("Read business object format without namespace permission"); assertEquals(HttpStatus.SC_FORBIDDEN, HerdRestUtil.getBusinessObjectFormat(MDL_APP_USER, getSecBusinessObjectData()).statusCode()); LogStep("Write without namespace permission"); assertEquals(HttpStatus.SC_FORBIDDEN, HerdRestUtil.deleteBusinessObjectData(MDL_APP_USER, getSecBusinessObjectData()).statusCode()); } @Test public void testHerdReadOnlyUser() { LogStep("Call Read endpoints using ReadOnly User"); assertEquals(HttpStatus.SC_OK, HerdRestUtil.getBuildInfo(HERD_RO_USER).statusCode()); assertEquals(HttpStatus.SC_OK, HerdRestUtil.getNamespace(HERD_RO_USER, NAMESPACE_MDL).statusCode()); LogStep("Call Read endpoints with various endpoints using ReadOnly User"); assertEquals(HttpStatus.SC_OK, HerdRestUtil.getBusinessObjectData(SEC_APP_USER, getSecBusinessObjectData()).statusCode()); assertEquals(HttpStatus.SC_OK, HerdRestUtil.getBusinessObjectData(HERD_RO_USER, getMdlBusinessObjectData()).statusCode()); LogStep("Call Write endpoint using ReadOnly User"); Response writeResponse = HerdRestUtil.postDataProvider(HERD_RO_USER, "unAuthorizedDataProvider"); LogVerification("Verify Readonly user cannot write"); assertEquals(HttpStatus.SC_FORBIDDEN, writeResponse.statusCode(), "ReadOnly user should not have permission to write"); } @Test public void testHerdAdminUser() { LogStep("Call Read endpoints with Admin User"); assertEquals(HttpStatus.SC_OK, HerdRestUtil.getBuildInfo(HERD_ADMIN_USER).statusCode()); assertEquals(HttpStatus.SC_OK, HerdRestUtil.getNamespace(HERD_ADMIN_USER, NAMESPACE_MDL).statusCode()); assertEquals(HttpStatus.SC_OK, HerdRestUtil.getBusinessObjectData(HERD_ADMIN_USER, getMdlBusinessObjectData()).statusCode()); assertEquals(HttpStatus.SC_OK, HerdRestUtil.getBusinessObjectData(HERD_ADMIN_USER, getSecBusinessObjectData()).statusCode()); LogStep("Call Write endpoints with Admin User"); String namespace = "MDLT_ADMIN_NM"; assertEquals(HttpStatus.SC_OK, HerdRestUtil.postNamespace(HERD_ADMIN_USER, namespace).statusCode()); assertEquals(HttpStatus.SC_OK, HerdRestUtil.getNamespace(HERD_ADMIN_USER, namespace).statusCode()); assertEquals(HttpStatus.SC_OK, HerdRestUtil.deleteNamespace(HERD_ADMIN_USER, namespace).statusCode()); LogStep("Write namespace restricted endpoint with Admin User"); BusinessObjectData secBusinessObjectData = getSecBusinessObjectData(); secBusinessObjectData.setBusinessObjectDefinitionName("InvalidValue"); BusinessObjectData mdlBusinessObjectData = getSecBusinessObjectData(); mdlBusinessObjectData.setBusinessObjectDefinitionName("InvalidValue"); assertTrue(HerdRestUtil.deleteBusinessObjectData(HERD_ADMIN_USER, secBusinessObjectData).statusCode() != HttpStatus.SC_FORBIDDEN); assertTrue(HerdRestUtil.deleteBusinessObjectData(HERD_ADMIN_USER, mdlBusinessObjectData).statusCode() != HttpStatus.SC_FORBIDDEN); LogStep("verify user get access denied read without permission"); assertEquals(HttpStatus.SC_FORBIDDEN, HerdRestUtil.getBusinessObjectData(MDL_APP_USER, getSecBusinessObjectData()).statusCode()); LogStep("grant permission to user"); HerdRestUtil.grantNamespacePermission(HERD_ADMIN_USER, MDL_APP_USER.getUsername(), NAMESPACE_SEC, NamespacePermissionEnum.READ); assertTrue(HerdRestUtil.getBusinessObjectData(MDL_APP_USER, getSecBusinessObjectData()).statusCode() != HttpStatus.SC_FORBIDDEN); LogStep("revoke permission from user"); HerdRestUtil.deleteNamespacePermission(HERD_ADMIN_USER, MDL_APP_USER.getUsername(), NAMESPACE_SEC); assertEquals(HttpStatus.SC_FORBIDDEN, HerdRestUtil.getBusinessObjectData(MDL_APP_USER, getSecBusinessObjectData()).statusCode()); } private BusinessObjectData getSecBusinessObjectData() { BusinessObjectData secBuzObjData = new BusinessObjectData(); secBuzObjData.setNamespace(NAMESPACE_SEC); secBuzObjData.setBusinessObjectDefinitionName("TradeData"); secBuzObjData.setBusinessObjectFormatUsage("MDL"); secBuzObjData.setBusinessObjectFormatFileType("TXT"); secBuzObjData.setPartitionKey("TDATE"); secBuzObjData.setPartitionValue("2017-08-01"); secBuzObjData.setBusinessObjectFormatVersion(0); secBuzObjData.setVersion(0); return secBuzObjData; } private BusinessObjectData getMdlBusinessObjectData() { BusinessObjectData secBuzObjData = new BusinessObjectData(); secBuzObjData.setNamespace(NAMESPACE_MDL); secBuzObjData.setBusinessObjectDefinitionName("MDL_OBJECT"); secBuzObjData.setBusinessObjectFormatUsage("MDL"); secBuzObjData.setBusinessObjectFormatFileType("TXT"); secBuzObjData.setPartitionKey("TDATE"); secBuzObjData.setPartitionValue("2017-01-02"); secBuzObjData.setBusinessObjectFormatVersion(0); secBuzObjData.setVersion(0); return secBuzObjData; } }
java
14
0.755213
140
54.526316
152
starcoderdata
MaEspHandlerService::MaEspHandlerService() : MaHandlerService("espHandler") { serviceFlags = 0; espControl.createSession = createSession; espControl.destroySession = destroySession; espControl.getSessionId = getSessionId; espControl.maxScriptSize = maGetHttp()->getLimits()->maxScriptSize; espControl.mapToStorage = mapToStorage; espControl.readFile = readFile; espControl.redirect = redirect; espControl.setCookie = setCookie; espControl.setHeader = setHeader; espControl.setResponseCode = setResponseCode; espControl.writeBlock = writeBlock; espControl.writeFmt = writeFmt; #if BLD_FEATURE_MULTITHREAD // // This mutex is used very sparingly and must be an application global // lock. // mutex = new MprMutex(); espControl.lock = espLock; espControl.unlock = espUnlock; espControl.lockData = mutex; #endif espOpen(&espControl); }
c++
10
0.779206
75
27.566667
30
inline
// // HZViewController.h // HZHelloWorld // // Created by juejianghuazi on 03/08/2022. // Copyright (c) 2022 juejianghuazi. All rights reserved. // @import UIKit; @interface HZViewController : UIViewController @end
c
6
0.765677
80
20.642857
14
starcoderdata
package com.myapp.backend.repository; import com.myapp.backend.domain.entity.Attend; import com.myapp.backend.domain.entity.key.AttendKey; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Date; import java.util.List; public interface AttendRepository extends JpaRepository<Attend, AttendKey> { Attend findByUserIdAndDate(String userId, Date date); List userId); List userId, Date start, Date end); }
java
8
0.807273
99
29.555556
18
starcoderdata
/******************************************************************************* * 命名空间: SF.Core.EFCore.UoW * * 功 能: N/A * 类 名: IEFCoreAsyncQueryable * * Ver 变更日期 负责人 变更内容 * ─────────────────────────────────── * V0.01 2016/11/11 10:53:10 疯狂蚂蚁 初版 * * Copyright (c) 2016 SF 版权所有 * Description: SF快速开发平台 * Website:http://www.mayisite.com *********************************************************************************/ using SF.Core.Abstraction.UoW; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SF.Core.EFCore.UoW { /// /// Specialized <see cref="IQueryable{T}"/> for async executions using the Entity Framework Core. /// /// <typeparam name="T">The entity type public interface IEFCoreAsyncQueryable : IAsyncQueryable { } }
c#
6
0.55082
101
27.59375
32
starcoderdata
@Override protected void onCreate(Bundle savedInstanceState) { Log.d(LOG_TAG, "onCreate"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialize view objects from your layout mPublisherViewContainer = (FrameLayout)findViewById(R.id.publisher_container); mSubscriberViewContainer = (FrameLayout)findViewById(R.id.subscriber_container); requestPermissions(); }
java
10
0.701299
88
32.071429
14
inline
// //#define GC_DEBUG // //#include // //#include "gc_cpp.h" #include "gc.h" void GC_ADD_ROOT_SINGLE(void* ptr) { GC_add_roots(ptr, (void *)((uintptr_t)ptr + sizeof(uintptr_t))); } void GC_init_main_thread() { GC_init(); //GC_allow_register_threads(); } void GC_init_pre_thread() { //GC_init(); } void GC_init_thread() { //int a = 0; GC_register_my_thread(&a); GC_init(); } void GC_finish_thread() { }
c++
11
0.602299
65
15.769231
26
starcoderdata
from nipype.interfaces.base import ( BaseInterface, BaseInterfaceInputSpec, TraitedSpec, Directory, File, traits) import os import shutil import pydicom import numpy as np import glob class PrepareFIXInputSpec(BaseInterfaceInputSpec): melodic_dir = Directory() filtered_epi = File(exists=True) t1_brain = File(exists=True) mc_par = File(exists=True) epi_brain_mask = File(exists=True) epi_preproc = File(exists=True) epi2t1_mat = File(exists=True) t12epi_mat = File(exists=True) t12MNI_mat = File(exists=True) MNI2t1_mat = File(exists=True) epi_mean = File(exists=True) class PrepareFIXOutputSpec(TraitedSpec): fix_dir = Directory() hand_label_file = File(exists=True) class PrepareFIX(BaseInterface): input_spec = PrepareFIXInputSpec output_spec = PrepareFIXOutputSpec def _run_interface(self, runtime): melodic_dir = self.inputs.melodic_dir filtered_epi = self.inputs.filtered_epi t1_brain = self.inputs.t1_brain mc_par = self.inputs.mc_par epi_brain_mask = self.inputs.epi_brain_mask epi_preproc = self.inputs.epi_preproc epi2t1_mat = self.inputs.epi2t1_mat t12epi_mat = self.inputs.t12epi_mat t12MNI_mat = self.inputs.t12MNI_mat MNI2t1_mat = self.inputs.MNI2t1_mat epi_mean = self.inputs.epi_mean shutil.copytree(melodic_dir, 'melodic_ica') os.mkdir('melodic_ica/reg') shutil.copy2(t12MNI_mat, 'melodic_ica/reg/highres2std.mat') shutil.copy2(MNI2t1_mat, 'melodic_ica/reg/std2highres.mat') shutil.copy2(epi2t1_mat, 'melodic_ica/reg/example_func2highres.mat') shutil.copy2(t1_brain, 'melodic_ica/reg/highres.nii.gz') shutil.copy2(epi_preproc, 'melodic_ica/reg/example_func.nii.gz') shutil.copy2(t12epi_mat, 'melodic_ica/reg/highres2example_func.mat') os.mkdir('melodic_ica/mc') shutil.copy2(mc_par, 'melodic_ica/mc/prefiltered_func_data_mcf.par') shutil.copy2(epi_brain_mask, 'melodic_ica/mask.nii.gz') shutil.copy2(epi_mean, 'melodic_ica/mean_func.nii.gz') shutil.copytree(melodic_dir, 'melodic_ica/filtered_func_data.ica') shutil.copy2(filtered_epi, 'melodic_ica/filtered_func_data.nii.gz') with open('hand_label_file.txt', 'w') as f: f.write('not_provided') return runtime def _list_outputs(self): outputs = self._outputs().get() outputs["fix_dir"] = os.getcwd()+'/melodic_ica' outputs["hand_label_file"] = os.getcwd()+'/hand_label_file.txt' return outputs class FieldMapTimeInfoInputSpec(BaseInterfaceInputSpec): fm_mag = Directory() class FieldMapTimeInfoOutputSpec(TraitedSpec): delta_te = traits.Float() class FieldMapTimeInfo(BaseInterface): input_spec = FieldMapTimeInfoInputSpec output_spec = FieldMapTimeInfoOutputSpec def _run_interface(self, runtime): fm_mag = sorted(glob.glob(self.inputs.fm_mag+'/*')) tes = [pydicom.read_file(x).EchoTime for x in fm_mag] tes = list(set(tes)) if len(tes) != 2: print('Something went wrong when trying to estimate ' 'the delta TE between the two echos field map ' 'images. delta_TE will be set equal to 2.46, ' 'but please check if this is correct.') self.delta_te = 2.46 else: self.delta_te = float(np.abs(tes[1]-tes[0])) print('delta_TE: {}'.format(self.delta_te)) return runtime def _list_outputs(self): outputs = self._outputs().get() outputs["delta_te"] = self.delta_te return outputs
python
16
0.646853
76
30.243697
119
starcoderdata
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by // #import #import "MMViewerWindowDelegate-Protocol.h" @class MMAvatarImageView, MMFriendRequestData, MMView, NSButton, NSString, NSTextField, NSTextView; @interface MMFriendRequestCellView : NSTableCellView { BOOL _isLastCell; BOOL _friendAdded; MMAvatarImageView *_avatarImgView; NSTextField *_nickNameField; NSTextView *_requestContentsView; NSButton *_acceptButton; NSButton *_deleteButton; NSTextField *_friendAddedField; MMFriendRequestData *_friendRequestData; MMView *_seperator; struct CGSize _requestContentsViewSize; } + (id)defaultParagraphStyle; + (id)attributedStringWithRequestContents:(id)arg1; + (double)availableWidthForDescriptionWithCellWidth:(double)arg1; + (double)cellHeightWithFriendRequestData:(id)arg1 width:(double)arg2; @property(nonatomic) struct CGSize requestContentsViewSize; // @synthesize requestContentsViewSize=_requestContentsViewSize; @property(nonatomic) BOOL friendAdded; // @synthesize friendAdded=_friendAdded; @property(nonatomic) BOOL isLastCell; // @synthesize isLastCell=_isLastCell; @property(retain, nonatomic) MMView *seperator; // @synthesize seperator=_seperator; @property(retain, nonatomic) MMFriendRequestData *friendRequestData; // @synthesize friendRequestData=_friendRequestData; @property(retain, nonatomic) NSTextField *friendAddedField; // @synthesize friendAddedField=_friendAddedField; @property(retain, nonatomic) NSButton *deleteButton; // @synthesize deleteButton=_deleteButton; @property(retain, nonatomic) NSButton *acceptButton; // @synthesize acceptButton=_acceptButton; @property(retain, nonatomic) NSTextView *requestContentsView; // @synthesize requestContentsView=_requestContentsView; @property(retain, nonatomic) NSTextField *nickNameField; // @synthesize nickNameField=_nickNameField; @property(retain, nonatomic) MMAvatarImageView *avatarImgView; // @synthesize avatarImgView=_avatarImgView; - (void).cxx_destruct; - (void)showUIDebugGuidesChanged:(id)arg1; - (struct CGRect)originScreenRectForAnimationForWindow:(id)arg1; - (void)enlargeAvatarImage:(id)arg1; - (void)deleteRequest:(id)arg1; - (void)acceptFriend:(id)arg1; - (void)populateWithFriendRequestData:(id)arg1 isLastCell:(BOOL)arg2 width:(double)arg3; - (void)prepareForReuse; - (void)drawRect:(struct CGRect)arg1; - (void)layoutSubViews; - (void)dealloc; - (id)initWithFrame:(struct CGRect)arg1; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
c
6
0.788395
124
43.96875
64
starcoderdata
from requests_html import HTMLSession import json import requests class UsernameError(Exception): pass class PlatformError(Exception): pass class User: def __init__(self,username=None,platform=None): self.__username = username self.__platform = platform def codechef(self): url = "https://codechef.com/users/{}".format(self.__username) session = HTMLSession() r = session.get(url,timeout=10) if r.status_code!=200: raise UsernameError("User not found") try: rating_header = r.html.find(".rating-header",first=True) except: raise UsernameError('User not found') try: rating = rating_header.find(".rating-number",first=True).text except: raise UsernameError('User not found') max_rating = rating_header.find('small')[0].text[1:-1].split()[2] rating_star = len(r.html.find(".rating-star",first=True).find('span')) ranks = r.html.find('.rating-ranks',first=True).find('strong') global_rank = ranks[0].text country_rank = ranks[1].text def get_contests_details(): rating_table = r.html.find('.rating-table',first=True) data_rows = rating_table.find('tr')[1:] data = list() for row in data_rows: td = row.find('td') d = dict() d['name'] = td[0].text.replace("\n", " ") d['rating'] = td[1].text d['global_rank'] = td[2].text d['country_rank'] = td[3].text data.append(d) return data def get_problems_solved(): div = r.html.find('.problems-solved',first=True) problems_solved = dict() fully_solved=dict() partial_solved =dict() articles = div.find('article') h5s = div.find('h5') for a,h in zip(articles,h5s): ps = a.find('p') prob_data = dict() for p in ps: txt = p.text.split() type = txt[0][:-1] txt = txt[1:] prob_data[type] =list() for t in txt: if t==txt[len(txt)-1]: prob_data[type].append(t) else: prob_data[type].append(t[:-1]) if h.text.split()[0]=='Fully': fully_solved['count'] = h.text.split()[2][1:-1] fully_solved['problems'] = prob_data elif h.text.split()[0]=='Partially': partial_solved['count'] = h.text.split()[2][1:-1] partial_solved['problems'] = prob_data problems_solved['fully_solved'] = fully_solved problems_solved['partial_solved'] = partial_solved return problems_solved return {'status':'OK','rating':rating,'max_rating':max_rating, 'global_rank':global_rank,'country_rank':country_rank, 'contests':get_contests_details(),'problems_solved':get_problems_solved()} def codeforces(self): url = 'https://codeforces.com/api/user.info?handles={}'.format(self.__username) r = requests.get(url,timeout=10) if r.status_code !=200: raise UsernameError('User not found') r_data = r.json() if r_data['status']!='OK': raise UsernameError('User not found') data = dict() data['status'] = 'OK' data.update(r_data['result'][0]) return data def atcoder(self): url = "https://atcoder.jp/users/{}".format(self.__username) session = HTMLSession() r = session.get(url,timeout=10) if r.status_code != 200: raise UsernameError('User not found') data_tables = r.html.find('.dl-table') if not len(data_tables): raise UsernameError('User not found') data = dict() data['status']='OK' for table in data_tables: data_rows = table.find('tr') for row in data_rows: attr = row.find('th',first=True).text val = row.find('td',first=True).text data[attr]=val if attr == 'Highest Rating': val = val.split()[0] data[attr]=val return data def spoj(self): url = "https://www.spoj.com/users/{}/".format(self.__username) session = HTMLSession() r = session.get(url,timeout=10) if r.status_code !=200: raise UsernameError("User not found") user_profile_left = r.html.find("#user-profile-left") if not len(user_profile_left): raise UsernameError user_profile_left = user_profile_left[0] data = dict() data['status'] = 'OK' data['full_name'] = user_profile_left.find('h3',first=True).text data['img_src'] = user_profile_left.find('img')[0].attrs['src'] p_data = user_profile_left.find('p') data['location'] = p_data[0].text data['joined'] = p_data[1].text.replace("Joined ","") data['world_rank'] = p_data[2].text.split()[2][1:] data['institution'] = p_data[3].text.replace("Institution: ","") data_stats = r.html.find('.profile-info-data-stats',first=True) dts = data_stats.find('dt') dds = data_stats.find('dd') for dt,dd in zip(dts,dds): data[dt.text] =dd.text return data def leetcode(self): session = HTMLSession() url = "https://leetcode.com/{}/".format(self.__username) r = session.get(url,timeout=10) if r.status_code!=200: raise UsernameError('User not found') check = r.html.find('.username') if not len(check): raise UsernameError('User not found') target = r.html.find('.list-group-item') basic_profile = dict() contest = dict() progress = dict() contribution = dict() for li in target: text = li.text.split() if len(text)<6: if len(text)>=2 and text[0]=='Location': basic_profile['location'] = li.text.replace("Location ","") elif len(text)>=1 and text[0]=='School': basic_profile['school'] = li.text.replace("School ","") elif len(text)>=2 and text[1]=='Rating': contest['rating']=text[0] elif len(text)>=3 and text[1]+text[2]=='FinishedContests': contest['finished_contests']=text[0] elif len(text)>=5 and text[len(text)-2]+text[len(text)-1]=='GlobalRanking': contest['global_ranking'] = text[0] contest['total_participants'] = text[2] elif len(text)>=5 and text[len(text)-2]+text[len(text)-1]=='SolvedQuestion': progress['solved_question'] = text[0] progress['total_question'] = text[2] elif len(text)>=5 and text[len(text)-2]+text[len(text)-1]=='AcceptedSubmission': progress['accepted_submission'] = text[0] progress['total_submission'] = text[2] elif len(text)>=4 and text[len(text)-2]+text[len(text)-1]=='AcceptanceRate': progress['acceptance_rate'] = text[0]+ " %" elif len(text)>=2 and text[1]=="Problems": contribution['problems'] = text[0] elif len(text)>=2 and text[1]=="Points": contribution['points']=text[0] elif len(text)>=3 and text[len(text)-2]+text[len(text)-1]=='TestCases': contribution['test_cases'] = text[0] elif len(text)>=2 and text[0] == 'Website': basic_profile['website'] = text[1] elif len(text)>=2 and text[0]=='Company': basic_profile['company'] = text[1] data = {'status':'OK','basic_profile':basic_profile,'contest':contest,'progress':progress,'contribution':contribution,} return data def get_info(self): if self.__platform=='codechef': return self.codechef() if self.__platform=='codeforces': return self.codeforces() if self.__platform == 'atcoder': return self.atcoder() if self.__platform == 'spoj': return self.spoj() if self.__platform =='leetcode': return self.leetcode() raise PlatformError('Platform not Found') if __name__ == '__main__': platform = input("Enter platform: ") username = input("Enter username: ") obj = User(username,platform) print(obj.get_info())
python
22
0.512155
127
43.80198
202
starcoderdata
from PIL import Image, ImageDraw import sys import requests import os def scaleTuple(tuple, scale): return (int(tuple[0]*scale), int(tuple[1]*scale)) def pasteAlphaComposite(background, foreground): fw, fh = foreground.size bw, bh = background.size offset = ((bw - fw) // 2, (bh - fh) // 2) background.alpha_composite(foreground, offset) def drawBorders(img): draw = ImageDraw.Draw(img) w, h = img.size draw.rectangle((0, 0, w-1, h-1), outline="grey", width=4) def drawBack(img): draw = ImageDraw.Draw(img) w, h = img.size polygons = [ # Outer trapeze ( (0, 0), (w*0.6, h*0.25), (w*0.6, h*0.75), (0, h-1), ), # Upper line ( (w-1, 0), (w*0.49, h*0.2) ), # Lower line ( (w-1, h-1), (w*0.49, h*0.8) ), ] for polygon in polygons: draw.line(polygon, fill="grey", width=4, joint="curve") def createFront(cover): size = (290, 386) cover = cover.rotate(90, expand = True) cover = cover.resize(size, Image.LANCZOS) return cover def createPlaceholderFront(logo): size = (290, 386) logoSize = scaleTuple(size, 0.8) logo = logo.rotate(90, expand = True) logo.thumbnail(logoSize, Image.LANCZOS) front = Image.new("RGBA", size, "black") pasteAlphaComposite(front, logo) drawBorders(front) return front def addTop(img): top = Image.new("RGBA", (290, 194), "black") drawBorders(top) img.paste(top, (215, 7)) def addBottom(img): bottom = Image.new("RGBA", (290, 194), "black") drawBorders(bottom) img.paste(bottom, (727, 7)) def addLeft(img, logo): size = (194, 386) logoSize = scaleTuple(size, 0.8) left = Image.new("RGBA", size, "black") logo = logo.rotate(-90, expand = True) logo.thumbnail(logoSize) pasteAlphaComposite(left, logo) drawBorders(left) img.paste(left, (7, 215)) def addRight(img, logo): size = (194, 386) logoSize = scaleTuple(size, 0.8) right = Image.new("RGBA", size, "black") logo = logo.rotate(90, expand = True) logo.thumbnail(logoSize) pasteAlphaComposite(right, logo) drawBorders(right) img.paste(right, (519, 215)) def addFront(img, front): img.paste(front, (215, 215)) def addBack(img): back = Image.new("RGBA", (290, 386), "black") drawBorders(back) drawBack(back) img.paste(back, (727, 215)) def create(path): logo = os.path.join(os.path.dirname(__file__), 'logo.png') logo = Image.open(logo) img = Image.new("RGBA", (1024, 768), None) front = None if path == None: print("No front image specified, creating placeholder") front = createPlaceholderFront(logo) else: cover = path # if true -> url, otherwise local file if cover.startswith("http"): cover = requests.get(cover, stream=True).raw cover = Image.open(cover) front = createFront(cover) addTop(img) addBottom(img) addLeft(img, logo) addRight(img, logo) addFront(img, front) addBack(img) img.save("box.png", "PNG")
python
14
0.580846
63
23.930233
129
starcoderdata
package mathTag func Fraction(cont []int) []int { //a为分子,b为分母 //但是最后一次转换不用交换分子分母,所以最后a为分母,b为分子 a, b := 0, 1 for i := len(cont) - 1; i >= 0; i-- { a += cont[i]*b a, b = b, a } g := gcd(a, b) return []int{b/g, a/g} } func gcd(a, b int) int { for b != 0 { a, b = b, a%b } return a }
go
10
0.513423
38
13.238095
21
starcoderdata
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Diagnostics; namespace Interactipy.Engine { public class PyExecutable { public string Path { get; set; } private string versioncache = ""; public string Version { get { if (versioncache != "") { versioncache = GetVersionString(); } return versioncache; } } public bool IsValid { get { string verstr; if (!File.Exists(Path)) { return false; } try { verstr = GetVersionString(); if (!verstr.StartsWith("Python")) { return false; } } catch { return false; } versioncache = verstr; return true; } } public PyExecutable(string path) { Path = path; } public string GetVersionString(int timeout = 500) { Process proc = new Process(); ProcessStartInfo info = new ProcessStartInfo(); info.FileName = Path; info.Arguments = @"Python\vercheck.py"; info.WorkingDirectory = Environment.CurrentDirectory; info.UseShellExecute = false; info.CreateNoWindow = true; info.RedirectStandardOutput = true; info.RedirectStandardError = true; proc.StartInfo = info; proc.Start(); DateTime stamp = DateTime.Now; string result = ""; while (true) { if (proc.StandardOutput.Peek() > -1) { char ch = (char)proc.StandardOutput.Read(); if (ch == '\r' || ch == '\n') { break; } result += ch; } if (DateTime.Now - stamp > new TimeSpan(0,0,0,0,timeout)) { throw new ExcutableNotRespondingException("not responding"); } } return result; } public PyProcess Run(string args, string workingDirectory, IEnumerable pythonPath) { PyProcess proc = PyProcess.Create(Path, args, workingDirectory, pythonPath); return proc; } public PyProcess Run(string args, string workingDirectory) { List pythonPathes = new List { System.IO.Path.GetDirectoryName(Path) }; return Run(args, workingDirectory, pythonPathes); } } }
c#
19
0.446231
98
24.780488
123
starcoderdata
def forward(self, ebd): ''' @param data dictionary @param weights placeholder used for maml @return output: batch_size * embedding_dim ''' ebd = self.ebd(data) # count length excluding <pad> and <unk>. is_zero = (torch.sum(torch.abs(ebd), dim=2) > 1e-8).float() soft_len = torch.sum(is_zero, dim=1, keepdim=True) soft_len[soft_len < 1] = 1 # # don't need to mask out the <pad> tokens, as the embeddings are zero ebd = torch.sum(ebd, dim=1) ebd = ebd / soft_len return ebd
python
13
0.543333
79
29.05
20
inline
define([ 'jquery', 'model-engine/js/enum' ], function($, enu) { var ModelType = enu.ModelType, FormfieldPrefix = enu.FormfieldPrefix; /** * 创建单选按钮列表表单项。 * @param o {ModelForm} 模型表单对象的实例。 * o.containers {Array} 表单项的容器的队列。 * o.controls {Object} 表单项的字典。 * @param container {Element} 表单项的容器。 * @param settings {Object} 表单项的配置数据。 * @param ext {Object} 扩展配置。 * @param def {String} 表单对象的默认值。 */ function create(o, container, settings, ext, def){ var util = require('model-engine/js/plugs/plugutil'), attributes = settings.attributes, list = settings.list, form_name = o.getControlName(settings), controls = util.createHorizontalContainer(o.containers, container, settings, form_name, attributes.label); o.controls[form_name] = {'id': form_name, 'name': settings.name, 'type': ModelType.RADIOLISTINPUT, 'field': attributes.field}; if (list && ext.hasOwnProperty('list_service')) { var options = { 'type': list['type'], 'id': list['id'], /*宿主模型的用途主要是在特定情况下获取模型字段的列表*/ 'parasitifer': ext['parasitifer'] }; $.getJSON(ext['list_service'], options, function(items){ for(var i = 0; i < items.length; i++){ var lbl_rdl = $('<label class="radio inline">'); controls.append(lbl_rdl); var input = $('<input type="radio" />'); lbl_rdl.append(input); input.attr('name', form_name); input.attr('value', items[i]['value']); lbl_rdl.append(items[i]['text']); } if (def) { $('input[name=' + form_name + ']').attr("checked", def); }; }); }; } return { 'create': create }; });
javascript
25
0.47642
134
36.481481
54
starcoderdata
const set1 = [1, 2, 3, 9]; const set2 = [1, 2, 4, 4]; const sumTotal = 8; const hasPairSum = (set, sum) => { const dictionary = {}; let i = 0; let hasPair; while (i < set.length && !hasPair) { if (dictionary[set[i] - sum]) { hasPair = true; break; } dictionary[set[i] - sum] = true; i++; } return hasPair; }; console.log(`has sum in set1`, hasPairSum(set1, sumTotal)); console.log(`has sum in set2`, hasPairSum(set2, sumTotal)); console.log("Time complexty: O(n) =D");
javascript
12
0.577821
59
19.56
25
starcoderdata
func (g *ProviderDingTalk) Exchange(ctx context.Context, code string, opts ...oauth2.AuthCodeOption) (*oauth2.Token, error) { conf, err := g.OAuth2(ctx) if err != nil { return nil, errors.WithStack(herodot.ErrInternalServerError.WithReasonf("%s", err)) } pTokenParams := &struct { ClientId string `json:"clientId"` ClientSecret string `json:"clientSecret"` Code string `json:"code"` GrantType string `json:"grantType"` }{conf.ClientID, conf.ClientSecret, code, "authorization_code"} bs, err := json.Marshal(pTokenParams) if err != nil { return nil, errors.WithStack(herodot.ErrInternalServerError.WithReasonf("%s", err)) } r := strings.NewReader(string(bs)) client := g.reg.HTTPClient(ctx, httpx.ResilientClientDisallowInternalIPs()) req, err := retryablehttp.NewRequest("POST", conf.Endpoint.TokenURL, r) if err != nil { return nil, errors.WithStack(herodot.ErrInternalServerError.WithReasonf("%s", err)) } req.Header.Add("Content-Type", "application/json;charset=UTF-8") resp, err := client.Do(req) if err != nil { return nil, errors.WithStack(herodot.ErrInternalServerError.WithReasonf("%s", err)) } defer resp.Body.Close() var dToken struct { ErrCode int `json:"code"` ErrMsg string `json:"message"` AccessToken string `json:"accessToken"` // Interface call credentials ExpiresIn int64 `json:"expireIn"` // access_token interface call credential timeout time, unit (seconds) } if err := json.NewDecoder(resp.Body).Decode(&dToken); err != nil { return nil, errors.WithStack(herodot.ErrInternalServerError.WithReasonf("%s", err)) } if dToken.ErrCode != 0 { return nil, errors.WithStack(herodot.ErrInternalServerError.WithReasonf("dToken.ErrCode = %d, dToken.ErrMsg = %s", dToken.ErrCode, dToken.ErrMsg)) } token := &oauth2.Token{ AccessToken: dToken.AccessToken, Expiry: time.Unix(time.Now().Unix()+int64(dToken.ExpiresIn), 0), } return token, nil }
go
17
0.709463
148
36.615385
52
inline
/** * 用户模块接口列表 */ import axios from '@/libs/http'; // 导入http中创建的axios实例 import qs from "qs"; const mine = { // ==============用户信息============== // 获取用户信息 getUserInfo () { return axios.get(`/api/user/info`) }, // 更新用户信息 updateUserInfo (params) { return axios.post(`/api/user/update`, params) }, // 更新密码 changePassword (params) { return axios.post(`/api/user/changePassword`, qs.stringify(params)) }, // ==============地址管理============== // 获取用户地址列表 getAddressList (params) { return axios.get(`/api/user/address/page`, { params: params }) }, // 获取地址详情 getAddressObj (addressId) { return axios.get(`/api/user/address/${addressId}`) }, // 新增地址 addressAdd (params) { return axios.post(`/api/user/address/add`, params) }, // 编辑地址 addressEdit (params) { return axios.post(`/api/user/address/update`, params) }, // 删除地址 addressDelete (addressId) { return axios.get(`/api/user/address/delete/${addressId}`) }, // ==============收藏管理============== // 获取用户收藏商品列表 getFavoriteList (params) { return axios.get(`/api/user/favorite/page`, { params: params }) }, // 新增收藏 favoriteAdd (productId) { return axios.get(`/api/user/favorite/favorite/${productId}`) }, // 取消收藏 favoriteCancel (favoriteId) { return axios.get(`/api/user/favorite/unfavorite/${favoriteId}`) }, } export default mine;
javascript
11
0.531792
75
21.57971
69
starcoderdata
/* -*- C++ -*- */ /** * @file DSRT_Dispatch_Item_T.h * * $Id: DSRT_Dispatch_Item_T.h 80826 2008-03-04 14:51:23Z wotte $ * * @author ( * */ #ifndef DSRT_DISPATCH_ITEM_H #define DSRT_DISPATCH_ITEM_H #include /**/ "ace/pre.h" #include "ace/Bound_Ptr.h" #include "ace/Copy_Disabled.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ #include "Kokyu_dsrt.h" namespace Kokyu { /** * @class DSRT_Dispatch_Item * * @brief This stores information about a schedulable thread. */ template <class DSRT_Scheduler_Traits> class DSRT_Dispatch_Item : private ACE_Copy_Disabled { typedef typename DSRT_Scheduler_Traits::Guid_t Guid_t; typedef typename DSRT_Scheduler_Traits::QoSDescriptor_t DSRT_QoSDescriptor; protected: ACE_hthread_t thr_handle_; Guid_t guid_; DSRT_QoSDescriptor qos_; ACE_Time_Value insertion_time_; public: DSRT_Dispatch_Item (Guid_t guid, const DSRT_QoSDescriptor&); /// Get the guid. Guid_t guid (); /// Get the associated qos value. DSRT_QoSDescriptor qos (); /// Get the thread handle. ACE_hthread_t thread_handle (); /// Set the thread handle. void thread_handle (ACE_hthread_t &handle); /// Get the insertion time. ACE_Time_Value insertion_time (); /// Set the insertion time. void insertion_time (const ACE_Time_Value&); }; /** * @class DSRT_Dispatch_Item_var * * @brief Smart pointer to dynamically allocated * DSRT_Dispatch_Item objects. */ template <class DSRT_Scheduler_Traits> class DSRT_Dispatch_Item_var : public ACE_Strong_Bound_Ptr< DSRT_Dispatch_Item ACE_SYNCH_MUTEX> { public: explicit DSRT_Dispatch_Item_var (DSRT_Dispatch_Item *p = 0); DSRT_Dispatch_Item_var ( const DSRT_Dispatch_Item_var &r); }; } #if defined (__ACE_INLINE__) #include "DSRT_Dispatch_Item_T.inl" #endif /* __ACE_INLINE__ */ #if defined (ACE_TEMPLATES_REQUIRE_SOURCE) #include "DSRT_Dispatch_Item_T.cpp" #endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ #if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) #pragma implementation ("DSRT_Dispatch_Item_T.cpp") #endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ #include /**/ "ace/post.h" #endif /* DSRT_DISPATCH_ITEM_H */
c
13
0.611024
72
22.834951
103
starcoderdata
public override Dictionary<string, string> GetPhysicalDiskInfo(string path, bool sizeStatsOnly) { // DiskUtil will return disk statistics in xml format ProcessResult processResult = ProcessHelper.Run("diskutil", "info -plist /", true); Dictionary<string, string> result = new Dictionary<string, string>(); if (string.IsNullOrEmpty(processResult.Output)) { result.Add("DiskUtilError", processResult.Errors); return result; } try { // Parse the XML looking for FilesystemType XDocument xmlDoc = XDocument.Parse(processResult.Output); XElement filesystemTypeValue = xmlDoc.XPathSelectElement("plist/dict/key[text()=\"FilesystemType\"]")?.NextNode as XElement; result.Add("FileSystemType", filesystemTypeValue != null ? filesystemTypeValue.Value: "Not Found"); } catch (XmlException ex) { result.Add("DiskUtilError", ex.ToString()); } return result; }
c#
16
0.570441
140
44.36
25
inline
from accelerate import Accelerator accelerator = Accelerator() class Config: seed = 42, model ='swin_small_patch4_window7_224', size = 224, inp_channels = 1, device = accelerator.device, lr = 1e-4, weight_decay = 1e-6, batch_size = 32, num_workers = 0, epochs = 5, out_features = 1, name = 'CosineAnnealingLR', T_max = 10, min_lr = 1e-6, num_tta = 1, train_dir = '../input/seti-breakthrough-listen/train' test_dir = '../input/seti-breakthrough-listen/test'
python
7
0.635889
57
25.136364
22
starcoderdata
package http.model.interfaces; import java.security.Principal; import java.util.Collection; public interface Authentication extends Principal { Long getId(); Collection getRoles(); }
java
6
0.763547
51
17.454545
11
starcoderdata
const CustomError = require("../extensions/custom-error"); module.exports = function createDreamTeam(array) { if(!Array.isArray(array)){ return false; } if(array.length==0){ return 'FAIL'; } let str=''; array.forEach(element => { if(typeof element=="string"){ element=element.trim(); str+=element[0]; }});; return str.toUpperCase().split('').sort().join(''); };
javascript
10
0.662338
58
20.388889
18
starcoderdata
<?php namespace Example\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class JobsQueueCommand extends BaseCommand { protected function configure() { $this ->setName('jobs:queue') ->setDescription('Start queueing randomly generated jobs') ->addArgument( 'number', InputArgument::REQUIRED, 'The number of jobs to queue' ) ->addOption( 'no-router', null, InputOption::VALUE_NONE, 'Do not use the router to decide which queues jobs go to' ) ->addOption( 'no-unique', null, InputOption::VALUE_NONE, 'Allow identical jobs to being active at the same time' ) ->addOption( 'delay', null, InputOption::VALUE_REQUIRED, 'Delay the queueing of the jobs by the specified number of seconds' ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $queued = 0; while ($queued++ < $input->getArgument('number')) { $queue = 'queue'.mt_rand(1, 4); $job = json_encode([ 'queue' => $queue, 'runtime' => mt_rand(1, 3), 'expedited' => mt_rand(1, 100) == 100 ? true : false, ]); if (!$input->getOption('no-router')) { $queue = $this->getRocket()->getPlugin('router')->applyRulesToJob($job); } if (!$input->getOption('no-unique')) { if ($this->getRocket()->getPlugin('unique')->getJobIdIfActive($job)) { $output->writeln('Job was already queued'); continue; } } if ($delay = $input->getOption('delay')) { $start = new \DateTime(); $start->add(new \DateInterval(sprintf('PT%dS', $delay))); $this->getRocket()->getQueue($queue)->scheduleJob($start, $job); } else { $this->getRocket()->getQueue($queue)->queueJob($job); } sleep(1); } } }
php
20
0.498024
88
31.025316
79
starcoderdata
def main(): # IO file name filename = 'config_file' in_file = './work/Cap_TrainingSet_*.txt' # Translate data into an array for file in glob.glob(in_file): assert os.path.exists(file), '{} file does not exist'.format(file) start_time = time.time() dataset=np.genfromtxt(file, delimiter=" ", skip_header=2) #reads file # Get corner type corner_type = get_corner_type(file) print('\n# Start Training Regression Model for: {}'.format(corner_type)) # Compute the # of layers total_layer = int(len(dataset)/SAMPLE_CAP) cap_storage = [] for metal_layer in range (1, total_layer+1): run_regression(metal_layer, dataset, cap_storage) outFile = filename + '_' + corner_type # Writing the data to the config file write_toFile(cap_storage, outFile, cap_storage) print('\n# Completed - Total Elapsed Time: {} seconds'.format(time.time() - start_time))
python
12
0.558226
92
35.37931
29
inline
import collections class Stats: def __init__(self): self.men = 0 self.women = 0 def __repr__(self): return f"men: {self.men}, women: {self.women}" stats = collections.defaultdict(lambda: Stats()) print("Accessing an object first time:") print(f"{stats['Russia']}\n") print("Add count of men in Russia:") stats["Russia"].men = 100 print(f"{stats['Russia']}\n") print("Add count of women in England:") stats["England"].women = 100 print(f"{stats['England']}\n") print("Whole dict:") for key, value in stats.items(): print(f"{key}: {value}")
python
9
0.625
54
19.857143
28
starcoderdata
void Initialize() { //When initialising the program, it is important to set the current months data (lastMonth = current month) after initialisation, all initialisation variables have to be commented out. //writeFile(SPIFFS, "/lastMonth.txt", "10"); //writeFile(SPIFFS, "/lastDay.txt", "01"); //writeFile(SPIFFS, "/yearToLastMonthEnergy.txt", "101"); //correctManualStart = 17.57; // prduktion this month until yesterday //char Last12Months[] = R"raw({"last12":{"Jan":"101","Feb":"192","Mar":"540","Apr":"808","Maj":"903","Jun":"903","Jul":"756","Aug":"762","Sep":"452","Okt":"309","Nov":"120","Dec":"30","lastTwelve":"0"}})raw"; //writeFile(SPIFFS, "/last12.txt", Last12Months); //char AllYears[] = R"raw({"lastYears":{"2013":"5160","2014":"5668","2015":"5830","2016":"5820","2017":"5410","2018":"6150","2019":"5790","2020":"5940","2021":"0","2022":"0","2023":"0","2024":"0","2025":"0"}})raw"; //writeFile(SPIFFS, "/allYears.txt", AllYears); Serial.println("DID YOU REMEMBER TO UNCOMMENT / COMMENT THE VARIABLES YOU WANT TO USE / NOT USE ---- IMPORTANT!!!!!!!!!!!"); // END Initialisation }
c
7
0.636687
216
52.47619
21
starcoderdata
// Copyright (c) 2021 Artyom " Volkov ( #include "Objects/EntityResource.h" #include "TimerManager.h" void UEntityResource::SetResourceData(const FResourceData& NewResourceData) { ResourceData = NewResourceData; ResourceData.Value = ResourceData.bUseCustomInitialValue ? ResourceData.ValueInitial : ResourceData.ValueMax; ResourceData.AutoIncreaseData.Time = 1 / ResourceData.AutoIncreaseData.Frequency; ResourceData.AutoDecreaseData.Time = 1 / ResourceData.AutoDecreaseData.Frequency; if (ResourceData.ValueMax <= 0) { if (ResourceData.AutoIncreaseData.bIsEnabled) { ResourceData.AutoIncreaseData.bIsEnabled = false; } if (ResourceData.AutoDecreaseData.bIsEnabled) { ResourceData.AutoDecreaseData.bIsEnabled = false; } StartAutoIncrease(); StartAutoDecrease(); } } void UEntityResource::SetValue(const float NewValue) { if (NewValue < 0.f || ResourceData.Value <= 0.f) return; ResourceData.Value = NewValue; OnValueChanged.Broadcast(ResourceData.Value, ResourceData.Value - NewValue); } void UEntityResource::DecreaseValue(const float DeltaValue) { if (DeltaValue <= 0.f || GetValue() <= 0.f) return; ResourceData.Value = FMath::Max(ResourceData.Value - DeltaValue, 0.f); OnValueChanged.Broadcast(ResourceData.Value, DeltaValue); StartAutoIncrease(); } void UEntityResource::IncreaseValue(const float DeltaValue, const bool bClampToMax) { if (DeltaValue <= 0.f) return; ResourceData.Value += DeltaValue; if (bClampToMax) { ResourceData.Value = FMath::Min(ResourceData.Value, ResourceData.ValueMax); } OnValueChanged.Broadcast(ResourceData.Value, DeltaValue); StartAutoDecrease(); } void UEntityResource::SetValueMax(const float NewValue, const bool bClampValue) { if (NewValue <= 0.f) return; ResourceData.ValueMax = NewValue; if (bClampValue) { SetValue(FMath::Clamp(ResourceData.Value, 0.f, GetValueMax())); } OnValueMaxChanged.Broadcast(ResourceData.ValueMax); } void UEntityResource::DecreaseValueMax(const float DeltaValue, const bool bClampValue) { if (DeltaValue <= 0.f) return; ResourceData.ValueMax -= DeltaValue; if (bClampValue) { SetValue(FMath::Clamp(ResourceData.Value, 0.f, GetValueMax())); } OnValueMaxChanged.Broadcast(ResourceData.ValueMax); } void UEntityResource::IncreaseValueMax(const float DeltaValue, const bool bClampValue) { if (DeltaValue <= 0.f) return; ResourceData.ValueMax += DeltaValue; if (bClampValue) { SetValue(ResourceData.ValueMax); } OnValueMaxChanged.Broadcast(ResourceData.ValueMax); } void UEntityResource::StopTimer(FTimerHandle& TimerHandle) const { if (!GetWorld()) return; FTimerManager& TimerManager = GetWorld()->GetTimerManager(); if (TimerManager.IsTimerActive(TimerHandle)) { TimerManager.ClearTimer(TimerHandle); } } void UEntityResource::ProcessAutoIncrease() { IncreaseValue(ResourceData.AutoIncreaseData.TickValue, false); if (GetNormalizedValue() >= ResourceData.AutoIncreaseData.Threshold) { StopTimer(AutoIncreaseTimerHandle); } } void UEntityResource::StartAutoIncrease() { if (!ResourceData.AutoIncreaseData.bIsEnabled || GetNormalizedValue() >= ResourceData.AutoIncreaseData.Threshold || !GetWorld()) return; StopTimer(AutoIncreaseTimerHandle); GetWorld()->GetTimerManager().SetTimer(AutoIncreaseTimerHandle, this, &UEntityResource::ProcessAutoIncrease, ResourceData.AutoIncreaseData.Time, true, ResourceData.AutoIncreaseData.StartDelay); } void UEntityResource::StopAutoIncrease() { if (!ResourceData.AutoIncreaseData.bIsEnabled) return; StopTimer(AutoIncreaseTimerHandle); } void UEntityResource::SetAutoIncreaseEnabled(const bool bIsEnabled) { if (ResourceData.AutoIncreaseData.bIsEnabled == bIsEnabled) return; ResourceData.AutoIncreaseData.bIsEnabled = bIsEnabled; bIsEnabled ? StartAutoIncrease() : StopAutoIncrease(); } void UEntityResource::SetAutoIncreaseFrequency(const float NewFrequency) { if (NewFrequency <= 0.f) return; ResourceData.AutoIncreaseData.Frequency = NewFrequency; ResourceData.AutoIncreaseData.Time = 1.f / NewFrequency; StartAutoIncrease(); } void UEntityResource::SetAutoIncreaseValue(const float NewValue) { if (NewValue <= 0.f) return; ResourceData.AutoIncreaseData.TickValue = NewValue; StartAutoIncrease(); } void UEntityResource::SetAutoIncreaseThreshold(const float NewThreshold) { if (NewThreshold < 0.f) return; ResourceData.AutoIncreaseData.Threshold = NewThreshold; StartAutoIncrease(); } void UEntityResource::SetAutoIncreaseStartDelay(const float NewDelay) { if (NewDelay <= 0.f) return; ResourceData.AutoIncreaseData.StartDelay = NewDelay; } void UEntityResource::ProcessAutoDecrease() { DecreaseValue(ResourceData.AutoDecreaseData.TickValue); if (GetNormalizedValue() <= ResourceData.AutoDecreaseData.Threshold) { StopTimer(AutoDecreaseTimerHandle); } } void UEntityResource::StartAutoDecrease() { if (!ResourceData.AutoDecreaseData.bIsEnabled || GetNormalizedValue() <= ResourceData.AutoDecreaseData.Threshold || !GetWorld()) return; StopTimer(AutoDecreaseTimerHandle); GetWorld()->GetTimerManager().SetTimer(AutoDecreaseTimerHandle, this, &UEntityResource::ProcessAutoDecrease, ResourceData.AutoDecreaseData.Time, true, ResourceData.AutoDecreaseData.StartDelay); } void UEntityResource::StopAutoDecrease() { if (!ResourceData.AutoDecreaseData.bIsEnabled) return; StopTimer(AutoDecreaseTimerHandle); } void UEntityResource::SetAutoDecreaseEnabled(const bool bIsEnabled) { if (ResourceData.AutoDecreaseData.bIsEnabled == bIsEnabled) return; ResourceData.AutoDecreaseData.bIsEnabled = bIsEnabled; bIsEnabled ? StartAutoDecrease() : StopAutoDecrease(); } void UEntityResource::SetAutoDecreaseFrequency(const float NewFrequency) { if (NewFrequency <= 0.f) return; ResourceData.AutoDecreaseData.Frequency = NewFrequency; ResourceData.AutoDecreaseData.Time = 1.f / NewFrequency; StartAutoDecrease(); } void UEntityResource::SetAutoDecreaseValue(const float NewValue) { if (NewValue <= 0.f) return; ResourceData.AutoDecreaseData.TickValue = NewValue; StartAutoDecrease(); } void UEntityResource::SetAutoDecreaseThreshold(const float NewThreshold) { if (NewThreshold < 0.f) return; ResourceData.AutoDecreaseData.Threshold = NewThreshold; StartAutoDecrease(); } void UEntityResource::SetAutoDecreaseStartDelay(const float NewDelay) { if (NewDelay < 0.f) return; ResourceData.AutoDecreaseData.StartDelay = NewDelay; }
c++
12
0.740949
116
25.872093
258
starcoderdata
import Vue from 'vue' import Router from 'vue-router' import Home from '@/views/Home.vue' import Problems from '@/views/Problems.vue' import Submissions from '@/views/Submissions.vue' import Login from '@/views/Login.vue' import Admin from '@/views/Admin.vue' import Problem from '@/views/Problem.vue' import Submit from '@/views/Submit.vue' import Settings from '@/views/Settings.vue' import Scoreboard from '@/views/Scoreboard.vue' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'home', component: Home }, { path: '/problems', name: 'problems', component: Problems }, { path: '/login', name: 'login', component: Login }, { path: '/submissions', name: 'submissions', component: Submissions }, { path: '/problem/:idx', name: 'problem', component: Problem }, { path: '/submit', name: 'submit', component: Submit }, { path: '/submit/:idx', name: 'submit_idx', component: Submit }, { path: '/admin', name: 'admin', component: Admin }, { path: '/settings', name: 'settings', component: Settings }, { path: '/scoreboard', name: 'scoreboard', component: Scoreboard }, { path: '*', redirect: '/' } ] })
javascript
17
0.550694
49
18.459459
74
starcoderdata
# Copyright (C) 2020 Arm Limited or its affiliates. All rights reserved. # # SPDX-License-Identifier: Apache-2.0 # # 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 # # 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. # Description: # Contains unit tests for npu_encode_bias API for an external consumer import random import numpy as np from ethosu.vela.api import npu_encode_bias def test_encode_bias(): bias_lower_limit = -(1 << (40 - 1)) bias_upper_limit = (1 << (40 - 1)) - 1 scale_lower_limit = 0 scale_upper_limit = (1 << 32) - 1 shift_lower_limit = 0 shift_upper_limit = (1 << 6) - 1 for _ in range(30): bias = np.int64(random.randint(bias_lower_limit, bias_upper_limit)) scale = int(random.randint(scale_lower_limit, scale_upper_limit)) shift = int(random.randint(shift_lower_limit, shift_upper_limit)) biases_enc = npu_encode_bias(bias, scale, shift) assert isinstance(biases_enc, bytearray) assert len(biases_enc) == 10
python
11
0.700765
75
35.846154
39
starcoderdata
def partition(X, y): """ Partitions data. Args: X: features y: labels Returns: X_train, X_val, y_train, y_val """ # partition into validation set X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2) return X_train, X_val, y_train, y_val
python
8
0.502907
78
25.538462
13
inline
#ifndef BABYLON_MESHES_BUILDERS_TILED_PLANE_BUILDER_H #define BABYLON_MESHES_BUILDERS_TILED_PLANE_BUILDER_H #include #include #include #include namespace BABYLON { class Scene; class TiledPlaneOptions; FWD_CLASS_SPTR(Mesh) /** * @brief Class containing static functions to help procedurally build meshes. */ struct BABYLON_SHARED_EXPORT TiledPlaneBuilder { // clang-format off /** * @brief Creates a tiled plane mesh. * * The parameter `pattern` will, depending on value, do nothing or * * * flip (reflect about central vertical) alternate tiles across and up * * * flip every tile on alternate rows * * * rotate (180 degs) alternate tiles across and up * * * rotate every tile on alternate rows * * * flip and rotate alternate tiles across and up * * * flip and rotate every tile on alternate rows * * The parameter `tileSize` sets the size (float) of each tile side (default 1) * * You can set some different tile dimensions by using the parameters `tileWidth` and `tileHeight` (both by default have the same value of `tileSize`) * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * @see https://doc.babylonjs.com/how_to/set_shapes#box * @param name defines the name of the mesh * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns the box mesh */ // clang-format on static MeshPtr CreateTiledPlane(const std::string& name, TiledPlaneOptions& options, Scene* scene = nullptr); }; // end of struct TiledPlaneBuilder } // end of namespace BABYLON #endif // end of BABYLON_MESHES_BUILDERS_TILED_PLANE_BUILDER_H
c
12
0.731216
299
48.653846
52
starcoderdata