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
function test(chart) { $('#outer').scrollTop(100); // Set hoverPoint chart.series[0].points[0].onMouseOver(); // Move it chart.pointer.onContainerMouseMove({ type: 'mousemove', pageX: 200, pageY: 200 }); // Don't go through the export server chart.getSVG = function () { return this.container.innerHTML; } }
javascript
10
0.713969
122
21.6
20
starcoderdata
using SQLite; namespace QuickMeds.Models { public class Medication { [PrimaryKey, AutoIncrement] public int MedicationID { get; set; } public string GenericName { get; set; } public string BrandName { get; set; } public string ActionClass { get; set; } public int ControlClass { get; set; } public int BTFlag { get; set; } public string SideEffects { get; set; } public string Interactions { get; set; } public string Warnings { get; set; } } }
c#
8
0.605607
48
32.4375
16
starcoderdata
@Test public void testEtagForDirectContainerIsMemberOfPatch() throws Exception { final var membershipRescId = createBasicContainer(); final var membershipRescURI = serverAddress + membershipRescId; final var directId = createDirectContainer(membershipRescURI, EX_IS_MEMBER_PROP, true); final var memberId = createBasicContainer(directId, "member1"); final var memberUri = serverAddress + memberId; final String committedMemberEtag = getEtag(memberUri); assertNotNull("Member resource must have etag", committedMemberEtag); // Update the member resource using the etags addTitleWithEtag(memberUri, "title1", deweakify("W/\"fake\""), Status.PRECONDITION_FAILED); addTitleWithEtag(memberUri, "title2", deweakify(committedMemberEtag), Status.NO_CONTENT); assertNotEquals("Etag must update after modification", committedMemberEtag, getEtag(membershipRescURI)); }
java
9
0.731733
112
49.473684
19
inline
import logging from flask import Flask _logger: logging.Logger # Registers the blueprints for the given Flask app. def init_app(app: Flask): from project.routes.errors import blueprint as errors_bp from project.routes.auth import blueprint as auth_bp from project.routes.api import blueprint as api_bp from project.routes.main import blueprint as main_bp from project.routes.user import blueprint as user_bp app.register_blueprint(errors_bp) app.register_blueprint(auth_bp) app.register_blueprint(main_bp) app.register_blueprint(user_bp, url_prefix="/user") app.register_blueprint(api_bp, url_prefix="/api") global _logger _logger = app.logger _logger.info("Routes initialised.")
python
8
0.739305
60
34.666667
21
starcoderdata
<?php Conexion::abrir_conexion(); $task = TaskRepository::get_one(Conexion::obtener_conexion(), $id_task); $users = RepositorioUsuario::get_enable_users(Conexion::obtener_conexion()); $comments = TaskCommentRepository::get_all(Conexion::obtener_conexion(), $id_task); Conexion::cerrar_conexion(); ?> <input type="hidden" name="id_task" value="<?php echo $id_task;?>"> <div class="modal-body"> <div class="row"> <div class="col-md-12"> <div class="form-group"> <input type="hidden" name="old_status" value="<?php echo $task-> get_status(); ?>"> <div class="btn-group btn-block btn-group-toggle" data-toggle="buttons"> <label class="btn bg-olive <?php echo $task-> get_status() == 'todo' ? 'active' : ''; ?>"> <input type="radio" name="status" id="option_b1" autocomplete="off" value="todo" <?php echo $task-> get_status() == 'todo' ? 'checked' : ''; ?>> To Do <label class="btn bg-olive <?php echo $task-> get_status() == 'in_progress' ? 'active' : ''; ?>"> <input type="radio" name="status" id="option_b2" autocomplete="off" value="in_progress" <?php echo $task-> get_status() == 'in_progress' ? 'checked' : ''; ?>> In Progress <label class="btn bg-olive <?php echo $task-> get_status() == 'done' ? 'active' : ''; ?>"> <input type="radio" name="status" id="option_b3" autocomplete="off" value="done" <?php echo $task-> get_status() == 'done' ? 'checked' : ''; ?>> Done <?php echo $task-> get_title(); ?> <div class="form-group"> <label for="assigned_user">Assigned user: <?php if($task-> get_status() == 'done'){ ?> <input type="hidden" name="assigned_user" value="<?php echo $task-> get_assigned_user(); ?>"> echo $task-> get_assigned_user_name(); ?> <?php }else{ ?> <select id="assigned_user" class="form-control form-control-sm" name="assigned_user"> <?php foreach ($users as $user) { ?> <option value="<?php echo $user-> obtener_id(); ?>" <?php echo $user-> obtener_id() == $task-> get_assigned_user() ? 'selected' : ''; ?>><?php echo $user-> obtener_nombre_usuario(); ?> <?php } ?> <?php } ?> <div class="form-group"> echo $task-> get_message(); ?> <div class="form-group"> <label for="task_comment">Comment: <textarea id="task_comment" class="form-control form-control-sm" name="comment" rows="3" cols="80"> <div class="timeline"> <i class="fa fa-bookmark"> <div class="timeline-item"> <h3 class="timeline-header">Comments <?php if(count($comments)){ foreach ($comments as $comment) { $created_at = RepositorioComment::mysql_datetime_to_english_format($comment-> get_created_at()); ?> <i class="fa fa-user"> <div class="timeline-item"> <span class="time"><i class="far fa-clock"> <?php echo $created_at; ?> <h3 class="timeline-header"> <span class="text-primary"><?php echo $comment-> get_id_user_name(); ?> <div class="timeline-body"> <?php echo $comment-> get_comment(); ?> <?php } } ?> <i class="fa fa-infinity"> <div class="modal-footer"> <button type="submit" name="save" form="edit_task_form" class="btn btn-success">Save
php
12
0.512846
207
42.06383
94
starcoderdata
package com.secuconnect.client.model; import com.google.gson.annotations.SerializedName; import java.util.Objects; /** * Bank details for withdrawals */ public class PaymentInformation { @SerializedName("iban") private String iban = null; @SerializedName("bic") private String bic = null; @SerializedName("owner") private String owner = null; @SerializedName("bankname") private String bankname = null; public PaymentInformation iban(String iban) { this.iban = iban; return this; } /** * International Bank Account Number (IBAN) * @return iban **/ public String getIban() { return iban; } public void setIban(String iban) { this.iban = iban; } public PaymentInformation bic(String bic) { this.bic = bic; return this; } /** * Bank Identifier Code (BIC), or formerly SWIFT code * @return bic **/ public String getBic() { return bic; } public void setBic(String bic) { this.bic = bic; } public PaymentInformation owner(String owner) { this.owner = owner; return this; } /** * Account owner name * @return owner **/ public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public PaymentInformation bankname(String bankname) { this.bankname = bankname; return this; } /** * Bank name * @return bankname **/ public String getBankname() { return bankname; } public void setBankname(String bankname) { this.bankname = bankname; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PaymentInformation paymentInformation = (PaymentInformation) o; return Objects.equals(this.iban, paymentInformation.iban) && Objects.equals(this.bic, paymentInformation.bic) && Objects.equals(this.owner, paymentInformation.owner) && Objects.equals(this.bankname, paymentInformation.bankname); } @Override public int hashCode() { return Objects.hash(iban, bic, owner, bankname); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PaymentInformation {\n"); sb.append(" iban: ").append(toIndentedString(iban)).append("\n"); sb.append(" bic: ").append(toIndentedString(bic)).append("\n"); sb.append(" owner: ").append(toIndentedString(owner)).append("\n"); sb.append(" bankname: ").append(toIndentedString(bankname)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
java
12
0.63865
100
20.992424
132
starcoderdata
<?php namespace App\Providers; use DebugBar\Bridge\DoctrineCollector; use Illuminate\Support\ServiceProvider; class AppProvider extends ServiceProvider { private $controllerServices = [ 'View' => 'Illuminate\View\Factory', 'Response' => 'Illuminate\Support\Facades\Response', ]; private $composers = [ 'App\LayoutComposer' => 'layout', ]; private $controllers = [ 'BaseController' => '', 'HomeController' => '', ]; public function register() { $this->setupControllers(); $this->setupViews(); } public function boot() { $this->view = $this->app->make('view'); $this->router = $this->app->make('router'); $this->blade = $this->app->make('blade.compiler'); $frontPath = app_path('Frontend/'); $backPath = app_path('Backend/'); // $this->view->addLocation(__DIR__.'/Frontend/views'); $this->view->addNamespace('backend', $backPath . 'views'); $this->view->addNamespace('frontend', $frontPath . 'views'); require $backPath . 'routes.php'; require $backPath . 'filters.php'; require $frontPath . 'routes.php'; require $frontPath . 'filters.php'; require app_path('blade_extensions.php'); } private function setupControllers() { $services = $this->controllerServices; $this->app->resolvingAny(function ($object) use ($services) { if (!is_string($object) && isset($this->controllers[get_class($object)]) ) { foreach ($services as $service => $class) { call_user_func([$object, 'set' . $service], $this->app->make($class)); } } }); } private function setupViews() { $this->app->view->composers($this->composers); } }
php
23
0.561895
90
28.046875
64
starcoderdata
import React from 'react'; import styles from './Footer.module.css'; import NewsLetterInput from '../NewsLetterInput/NewsLetterInput'; import SocialMediaLinks from '../SocialMediaLinks/SocialMediaLinks'; const Footer = () => { return ( <div className={styles.footer} data-testid="Footer"> <div className={styles.footerBody}> <div className={styles.newsLetter}> Hi, sign up for my newsletter to get game development and technology related content. <NewsLetterInput /> <SocialMediaLinks style={{fontSize: "3em"}} /> ); } Footer.propTypes = {}; Footer.defaultProps = {}; export default Footer;
javascript
13
0.651042
97
27.444444
27
starcoderdata
<?php sleep(5); // wait 5 seconds before processing data $results = [ 'total_count' => 6, 'items' => [ [ 'id' => 0, 'text' => 'France', ], [ 'id' => 1, 'text' => 'Spain', ], [ 'id' => 2, 'text' => 'England', ], [ 'id' => 3, 'text' => 'Belgium', ], [ 'id' => 4, 'text' => 'Germany', ], [ 'id' => 5, 'text' => 'Canada', ], ], ]; header('Content-Type: application/json'); echo json_encode($results, JSON_PRETTY_PRINT);
php
10
0.315946
50
17.638889
36
starcoderdata
""" Helper methods and public API Copyright (C) 2020 nocturn9x 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. """ import inspect import threading from giambio.core import AsyncScheduler from giambio.exceptions import GiambioError from giambio.context import TaskManager from timeit import default_timer from giambio.util.debug import BaseDebugger from types import FunctionType thread_local = threading.local() def get_event_loop(): """ Returns the event loop associated to the current thread """ try: return thread_local.loop except AttributeError: raise GiambioError("giambio is not running") from None def new_event_loop(debugger: BaseDebugger, clock: FunctionType): """ Associates a new event loop to the current thread and deactivates the old one. This should not be called explicitly unless you know what you're doing. If an event loop is currently set and it is running, a GiambioError exception is raised """ try: loop = get_event_loop() except GiambioError: thread_local.loop = AsyncScheduler(clock, debugger) else: if not loop.done(): raise GiambioError("cannot change event loop while running") else: loop.close() thread_local.loop = AsyncScheduler(clock, debugger) def run(func: FunctionType, *args, **kwargs): """ Starts the event loop from a synchronous entry point """ if inspect.iscoroutine(func): raise GiambioError( "Looks like you tried to call giambio.run(your_func(arg1, arg2, ...)), that is wrong!" "\nWhat you wanna do, instead, is this: giambio.run(your_func, arg1, arg2, ...)" ) elif not inspect.iscoroutinefunction(func): raise GiambioError("giambio.run() requires an async function as parameter!") new_event_loop(kwargs.get("debugger", None), kwargs.get("clock", default_timer)) get_event_loop().start(func, *args) def clock(): """ Returns the current clock time of the thread-local event loop """ return get_event_loop().clock() def create_pool(): """ Creates an async pool """ return TaskManager() def with_timeout(timeout: int or float): """ Creates an async pool with an associated timeout """ assert timeout > 0, "The timeout must be greater than 0" mgr = TaskManager(timeout) loop = get_event_loop() if loop.current_task.pool is None: loop.current_pool = mgr loop.current_task.pool = mgr loop.current_task.next_deadline = mgr.timeout or 0.0 loop.deadlines.put(mgr) return mgr def skip_after(timeout: int or float): """ Creates an async pool with an associated timeout, but without raising a TooSlowError exception. The pool is simply cancelled and code execution moves on """ assert timeout > 0, "The timeout must be greater than 0" mgr = TaskManager(timeout, False) loop = get_event_loop() if loop.current_task.pool is None: loop.current_pool = mgr loop.current_task.pool = mgr loop.current_task.next_deadline = mgr.timeout or 0.0 loop.deadlines.put(mgr) return mgr
python
13
0.658606
98
27.366412
131
starcoderdata
import qs from "query-string"; const INDIVIDUAL_AUTHOR_TYPE = "Individual"; export const authorProfileLink = (post) => `/${ post.author.type === INDIVIDUAL_AUTHOR_TYPE ? "profile" : "organisation" }/${post.author.id}`; export const buildLocationString = ({ city = "", country }) => { const MAX_LENGTH = 26; if (city.length >= MAX_LENGTH) return `${city.substring(0, MAX_LENGTH - 3)}..., ${country}`; return city ? `${city}, ${country}` : country; }; export const getOptionText = (filterOptions, filterLabel, option) => filterOptions .filter(({ label }) => label === filterLabel)[0] .options.filter(({ value }) => value === option)[0].text; export const highlightSearchRegex = (text) => { let cleanKeywords = text .replace(/[.*+?^${}()|[\]\\\.]/g, "\\$&") .replace(/\\./g, " "); let isLatin = /^[a-zA-Z .*+?^${}()|[\]\\\.]+$/.test(cleanKeywords); const regex = new RegExp( `(${ cleanKeywords .split(/[ \/,=$%#()-]/gi) .filter((key) => key && key.length > 1) .map((key) => isLatin && key.length <= 3 ? "\\b" + key + "\\b" : isLatin ? "\\b" + key : key, ) .join("|") || "\\b\\B" })`, "ig", ); return regex; }; export const setQueryKeysValue = (history, newQuery) => { const query = qs.parse(history.location.search); for (const key in newQuery) { if (!newQuery[key] || newQuery[key] === -1) delete query[key]; else query[key] = newQuery[key]; } const stringifiedQuery = qs.stringify(query); const oldQuery = history.location.search.replace("?", ""); if (stringifiedQuery === oldQuery) return; history.push({ pathname: history.location.pathname, search: stringifiedQuery, }); };
javascript
23
0.557497
76
29.586207
58
starcoderdata
def moveTo(self, x, y, z): # Create pose data target_pose = PoseStamped() target_pose.header.frame_id = self.reference_frame target_pose.header.stamp = rospy.Time.now() target_pose.pose.position.x = x target_pose.pose.position.y = y target_pose.pose.position.z = z target_pose.pose.orientation.x = 0 target_pose.pose.orientation.y = 0 target_pose.pose.orientation.z = 0 target_pose.pose.orientation.w = 1 # Set pick position self.arm.set_start_state_to_current_state() self.arm.set_pose_target(target_pose, self.end_effector_link) traj = self.arm.plan() if len(traj.joint_trajectory.points) == 0: return False self.arm.execute(traj) return True
python
9
0.576151
69
32.92
25
inline
package dap4.test; import junit.framework.TestResult; import junit.framework.TestSuite; import org.junit.Ignore; import org.junit.Test; @Ignore public class TestDap4All extends DapTestCommon { ////////////////////////////////////////////////// static String getClassName(Class c) { String[] pieces = c.getName().split("[.]"); return pieces[pieces.length - 1]; } ////////////////////////////////////////////////// // Instance variables protected Class[] testclasses = new Class[]{ TestParserDMR.class, TestParserCE.class, TestServletConstraints.class, TestFilters.class, TestCDMClient.class, TestDSR.class, /* not yet testable TestH5Iosp.class, TestFrontPage.java TestHyrax.java TestSerial.java */ }; protected int testmax = testclasses.length; protected TestSuite[] tests = new TestSuite[testmax]; protected TestResult[] results = new TestResult[testmax]; ////////////////////////////////////////////////// // Constructor(s) public TestDap4All() throws Exception { this("TestDap4All"); } public TestDap4All(String name) throws Exception { super(name); } ////////////////////////////////////////////////// @Test public void testAll() { org.junit.Assume.assumeTrue(usingIntellij); for(int i = 0; i < testmax; i++) { tests[i] = new TestSuite(testclasses[i]); results[i] = new TestResult(); } boolean pass = true; int nfailures = 0; for(int i = 0; i < testmax; i++) { setTitle(getClassName(testclasses[i])); System.out.println("Test Case: " + getTitle()); tests[i].run(results[i]); if(results[i].failureCount() > 0) { pass = false; nfailures++; System.out.println("***Fail: " + getTitle()); } else { System.out.println("***Pass: " + getTitle()); } } assertTrue(nfailures + " Tests Failed", pass); } }
java
15
0.505322
61
23.83908
87
starcoderdata
/** * Logs debug data to the console when in development mode * @param {*} data The data to Logs * @returns {boolean} */ const debug = (data) => { if (Boolean(process.env.DEBUG) !== true) return false; console.debug(data); return true; }; /** * @param {hex} hex The hex to convert to a string * @returns {string}; */ const hexToString = (hex) => { return Buffer.from(hex.toString('utf-8')); }; /** * @param {hex} hex The hex to pad * @param {number} bytes The number of bytes to add * @returns {string} */ const padHex = (hex, bytes) => { return ('00'.repeat(bytes) + hex).substr(-(bytes * 2)); }; /** * @param {hex} hex The hex to pad * @param {number} bytes The number of bytes to add * @returns {string} */ const padHexEnd = (hex, bytes) => { return (hex + '00'.repeat(bytes)).substring(0, bytes * 2); }; /** * @param {number} number The number to convert * @returns {hex} */ const int64ToHex = (int) => { return padHex(int.toString(16), 8); }; /** * @param {number} number The number to convert * @returns {hex} */ const int32ToHex = (int) => { return padHex(int.toString(16), 4); }; /** * @param {number} number The number to convert * @returns {hex} */ const int16ToHex = (int) => { return padHex(int.toString(16), 2); }; /** * @param {number} number The number to convert * @returns {hex} */ const int8ToHex = (int) => { return padHex(int.toString(16), 1); } /** * I legit can't be fucked to work this out * @param {string} str The string * @param {number} n The amount of characters * @returns {array} */ const eachCharsFromString = (str, n) => { const chrs = Number(n); const arr = []; for (let i = 0; i < (str.length / chrs); i++) { arr.push(str.substring(i * chrs, (i + 1) * chrs)); } return arr; }; module.exports = { debug, hexToString, int8ToHex, int16ToHex, int32ToHex, int64ToHex, padHex, padHexEnd, };
javascript
14
0.624147
59
20.896552
87
starcoderdata
using System; using System.Threading; using System.Threading.Tasks; using NUnit.Framework; using Rebus.Activation; using Rebus.Config; using Rebus.Tests.Contracts; using Rebus.Tests.Contracts.Extensions; using Rebus.Tests.Extensions; using Rebus.Transport.InMem; namespace Rebus.Tests.Integration { [TestFixture] public class TestShutdownWithPendingTasks : FixtureBase { [Test] public async Task DoIt() { var builtinHandlerActivator = new BuiltinHandlerActivator(); var allDone = false; var gotMessage = new ManualResetEvent(false); builtinHandlerActivator.Handle _ => { gotMessage.Set(); await Task.Delay(2000); allDone = true; }); var bus = Configure.With(builtinHandlerActivator) .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "shutdown with pending tasks")) .Start(); using (bus) { await bus.SendLocal("hej"); gotMessage.WaitOrDie(TimeSpan.FromSeconds(2)); // make bus shut down here } Assert.That(allDone, Is.True, "The message was apparently not handled all the way to the end!!!"); } } }
c#
22
0.593423
110
26.326531
49
starcoderdata
package son.vu.jdk8; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; public class CheckJdk8 { public static void check(String... args) { if(args.length == 0) return; // for(String value: args) { // System.out.println(value); // } List list = Arrays.asList(args); list.forEach(x -> { try { int value = Integer.parseInt(x); System.out.println(value + " is integer"); } catch (Exception e) { System.out.println("Value is not integer"); } }); } public static void main(String[] args) { Consumer c1 = s -> System.out.println(s + " Khanh"); Consumer c2 = s -> System.out.println(s + " c1.andThen(c2).accept("Hello"); } }
java
17
0.631225
63
21.515152
33
starcoderdata
package org.cnt.tss.innerbeandef; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; /** * @author lixinjie * @since 2019-08-29 */ @Configuration @ConditionalOnBean(name = "haha") public class OutterWithImport { //该内部类的外部类是通过@Import引入的 //所以受到外部类上的@Configuration影响 //因为源码中判断只有标了这个注解才会去 //处理内部类 //肯定也受条件的影响 @Configuration public static class InnerClass4 { } @Component public static class InnerClass5 { } public static class InnerClass6 { } //外部类是通过@Import引入的 //bean方法只是外部类上的条件影响 //不受外部类上的@Configuration影响 //即使外部类上没有注解,外部类也会 //被注册bean定义 @Bean public InnerClass6 innerClass6() { return new InnerClass6(); } }
java
6
0.737119
74
19.155556
45
starcoderdata
def launch(self): """Make the script file and return the newly created job id""" # Make script file # self.make_script() # Do it # sbatch_out = sh.sbatch(self.script_path) jobs.expire() # Message # print Color.i_blu + "SLURM:" + Color.end + " " + str(sbatch_out), # Return id # self.id = int(re.findall("Submitted batch job ([0-9]+)", str(sbatch_out))[0]) return self.id
python
12
0.541485
85
37.25
12
inline
def _setup_ui(self): """Initialize user interface.""" main_layout = QtWidgets.QGridLayout(self) main_layout.setContentsMargins(0, 0, 0, 0) main_layout.setSpacing(8) pattern_path_lbl = QtWidgets.QLabel("Pattern Path", self) main_layout.addWidget(pattern_path_lbl, 0, 0, 1, 1) self._pattern_path = QtWidgets.QLineEdit(self) main_layout.addWidget(self._pattern_path, 0, 1, 1, 1) pattern_base_lbl = QtWidgets.QLabel("Pattern Base Name", self) main_layout.addWidget(pattern_base_lbl, 1, 0, 1, 1) self._pattern_base = QtWidgets.QLineEdit(self) main_layout.addWidget(self._pattern_base, 1, 1, 1, 1) self._append_username_to_name = QtWidgets.QCheckBox( "Append username to name", self ) main_layout.addWidget(self._append_username_to_name, 2, 1, 1, 1) self._append_colorspace_to_name = QtWidgets.QCheckBox( "Append colorspace to name", self ) main_layout.addWidget(self._append_colorspace_to_name, 3, 1, 1, 1) self._append_passname_to_name = QtWidgets.QCheckBox( "Append passname to name", self ) main_layout.addWidget(self._append_passname_to_name, 4, 1, 1, 1) self._append_passname_to_subfolder = QtWidgets.QCheckBox( "Append passname to subfolder", self ) main_layout.addWidget(self._append_passname_to_subfolder, 5, 1, 1, 1)
python
8
0.621935
77
38.702703
37
inline
/** * \file main.c * * \copyright (C) 2021 "piscilus" * * Distributed under MIT license. * See file LICENSE for details or copy at https://opensource.org/licenses/MIT * * \brief Main program for advent of code 2021 day 5. */ /*---- Includes --------------------------------------------------------------*/ #include #include #include #include /*---- Local macro definitions -----------------------------------------------*/ #define MAX_LINES (500) #define DIAGRAM_SIZE (1000) /*---- Local type definitions ------------------------------------------------*/ typedef struct coords { int x1; int y1; int x2; int y2; } coords_t; /*---- Local function prototypes ---------------------------------------------*/ /*---- Global constants ------------------------------------------------------*/ /*---- Global data -----------------------------------------------------------*/ /*---- Local constants -------------------------------------------------------*/ /*---- Local data ------------------------------------------------------------*/ /*---- Exported functions ----------------------------------------------------*/ int main ( int argc, char *argv[] ) { coords_t lines[MAX_LINES] = {0}; static int diagram[DIAGRAM_SIZE][DIAGRAM_SIZE] = {0}; int result = 0; printf("Advent of Code 2021 - Day 5: Hydrothermal Venture\n\n"); if ( argc != 2 ) { fprintf(stderr, "Please provide data record file name and part selection."); exit(EXIT_FAILURE); } FILE* fp = fopen(argv[1], "r"); if ( !fp ) { fprintf(stderr, "Could not open file!"); exit(EXIT_FAILURE); } int i = 0; while ( EOF != fscanf(fp, "%d,%d -> %d,%d\n", &lines[i].x1, &lines[i].y1, &lines[i].x2, &lines[i].y2) ) { if ( i >= MAX_LINES ) { fprintf(stderr, "Buffer overflow, too much data!"); exit(EXIT_FAILURE); } i++; } for ( int n = 0; n < i; n++ ) { // printf("%d: %d,%d -> %d,%d\n", n, lines[n].x1, lines[n].y1, lines[n].x2, lines[n].y2); if ( lines[n].x1 == lines[n].x2 ) { // printf("vertical\n"); if ( lines[n].y1 > lines[n].y2 ) { // printf("y1>y2\n"); for ( int j=lines[n].y2; j<=lines[n].y1; j++ ) diagram[j][lines[n].x1]++; } else { // printf("y1<=y2\n"); for ( int j=lines[n].y1; j<=lines[n].y2; j++ ) diagram[j][lines[n].x1]++; } } else if ( lines[n].y1 == lines[n].y2 ) { // printf("horizontal\n"); if ( lines[n].x1 > lines[n].x2 ) { // printf("x1>x2\n"); for ( int j=lines[n].x2; j<=lines[n].x1; j++ ) diagram[lines[n].y1][j]++; } else { // printf("x1<=x2\n"); for ( int j=lines[n].x1; j<=lines[n].x2; j++ ) diagram[lines[n].y1][j]++; } } else { // nop ; } } for ( int y = 0; y < DIAGRAM_SIZE; y++ ) //rows { for ( int x = 0; x < DIAGRAM_SIZE; x++ ) //cols { // printf("%d", diagram[y][x]); if ( diagram[y][x] >= 2 ) result++; } // printf("\n"); } printf("result: %d\n", result); return EXIT_SUCCESS; } /*---- Local functions -------------------------------------------------------*/ /*----------------------------------------------------------- END OF FILE ----*/
c
19
0.368155
107
24.767123
146
starcoderdata
<?php namespace Omnestek\Phpeav\Dto; /** * User: @fabianjuarezmx * Date: 30/01/2017 * Time: 11:47 PM */ abstract class AttributeValueAbstract { /** * @var int */ protected $value_id; /** * @var int */ protected $entity_id; /** * @var int */ protected $entity_type_id; /** * @var int */ protected $attribute_id; /** * @var int */ protected $attributes_set_id; /** * @var int */ protected $order; /** * @var int */ protected $active; /** * @return int */ public function getValueId() { return $this->value_id; } /** * @param int $value_id * @return AttributeValueAbstract */ public function setValueId($value_id) { $this->value_id = $value_id; return $this; } /** * @return int */ public function getEntityId() { return $this->entity_id; } /** * @param int $entity_id * @return AttributeValueAbstract */ public function setEntityId($entity_id) { $this->entity_id = $entity_id; return $this; } /** * @return int */ public function getEntityTypeId() { return $this->entity_type_id; } /** * @param int $entity_type_id * @return AttributeValueAbstract */ public function setEntityTypeId($entity_type_id) { $this->entity_type_id = $entity_type_id; return $this; } /** * @return int */ public function getAttributeId() { return $this->attribute_id; } /** * @param int $attribute_id * @return AttributeValueAbstract */ public function setAttributeId($attribute_id) { $this->attribute_id = $attribute_id; return $this; } /** * @return int */ public function getAttributesSetId() { return $this->attributes_set_id; } /** * @param int $attributes_set_id * @return AttributeValueAbstract */ public function setAttributesSetId($attributes_set_id) { $this->attributes_set_id = $attributes_set_id; return $this; } /** * @return int */ public function getOrder() { return $this->order; } /** * @param int $order * @return AttributeValueAbstract */ public function setOrder($order) { $this->order = $order; return $this; } /** * @return int */ public function getActive() { return $this->active; } /** * @param int $active * @return AttributeValueAbstract */ public function setActive($active) { $this->active = $active; return $this; } }
php
9
0.508415
58
15.485549
173
starcoderdata
def draw_piechart(self): cash =int(static.account.cash + static.account.locked_cash) sum = cash datas = [[cash, 'KRW']] for i in static.account.coins: datas.append([int(static.account.coins[i]['evaluate']), i]) sum += int(static.account.coins[i]['evaluate']) # Sort Coin and KRW datas.sort(reverse=True) remain = [0,'Other Coins'] labels = [] frequency = [] if sum != 0: # Data Screening for i in datas: if len(labels) < 7 or i[1] == 'KRW': labels.append(i[1] + " : " + str(round(i[0]/sum * 100)) + "%") frequency.append(i[0]) else: remain[0] += i[0] # If there are any remaining coins if remain[0] != 0: labels.append(remain[1] + " : " + str(round(remain[0]/sum * 100)) + "%") frequency.append(remain[0]) self.canvas.axes.clear() self.canvas.axes2.clear() else: labels.append("KRW : 100%") frequency.append(100) # Donut Chart pie = self.canvas.axes.pie(frequency, ## 파이차트 출력 startangle=90, ## 시작점을 90도(degree)로 지정 counterclock=False, ## 시계 방향으로 그린다. #autopct=lambda p : str(round(p)) + "%", ## 퍼센티지 출력 wedgeprops=dict(width=0.5) ## 중간의 반지름 0.5만큼 구멍을 뚫어준다. ) # Pie Chart # pie = self.axes.pie(frequency, startangle=260, counterclock=False, explode=explode) # Set Chart Percentage text # for t in pie[2]: # t.set_color("white") # t.set_fontweight('bold') # Set Legend self.canvas.axes2.legend(pie[0],labels, loc = 'center',labelcolor='white', borderpad=1, fontsize = 12) self.canvas.axes2.axis('off') self.canvas.draw_idle()
python
21
0.487633
111
35.036364
55
inline
def _build_network_interfaces(params, key, value): # Build up the NetworkInterfaces data structure if 'NetworkInterfaces' not in params: params['NetworkInterfaces'] = [{'DeviceIndex': 0}] if key == 'PrivateIpAddresses': if 'PrivateIpAddresses' not in params['NetworkInterfaces'][0]: params['NetworkInterfaces'][0]['PrivateIpAddresses'] = value else: params['NetworkInterfaces'][0][key] = value
python
13
0.670404
72
43.7
10
inline
package com.lechner.demo.termin; import java.time.LocalDate; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.lechner.demo.termin.Termin.*; /** * The Class TerminDataInit. */ @Configuration class TerminDataInit { /** The Constant log. */ private static final org.slf4j.Logger log = LoggerFactory.getLogger(TerminDataInit.class); /** * Inits the database. * * @param repository the repository * @return the command line runner */ @Bean CommandLineRunner initDatabase(TerminRepository repository) { return args -> { log.info("Preloading " + repository.save(new Termin("1", "introduction", LocalDate.now()))); log.info("Preloading " + repository.save(new Termin("2", "cont", LocalDate.now()))); }; } }
java
18
0.735008
98
28.9
40
starcoderdata
void saveItems(List<String> itemIds) { List<String> notEmptyOfferIds = itemIds.stream() .filter(itemId -> !itemId.isEmpty()) .collect(Collectors.toList()); // save in database notEmptyOfferIds.forEach(eventPublisher::publish); }
java
12
0.607639
58
40.285714
7
inline
<?php class BBM_Protection_Helper_ContentProtection { /************************************** This class is used to protect the content of the Bbm BbCodes with view permissions. The general idea is to listen the controller and protect these Bb Codes > Two XenForo listerners are extended here: the preView & postView Controller The Controller preView listerner is used to get some key settings and to modify some Json responses The Controller postView listerner is used to modify the other kind of responses (=> it might need to be modified next) > Some parts of XenForo can't be protected with only listening the controller: # Search > Reason: XenForo_ViewPublic_Search_Results has this function "XenForo_ViewPublic_Helper_Search::renderSearchResults" which modifies the parameters of the Controller Response > Solution: BBM_Protection_Model_Search # NewsFeed > Reason: XenForo_ViewPublic_NewsFeed_View has this function "XenForo_ViewPublic_Helper_NewsFeed::getTemplates" which modifies the parameters of the Controller Response > Solution: See here: BBM_Protection_Model_NewsFeed # ThreadWatch > Reason: The mail is sent inside the datawritter (no controller here) > Solution: See here: BBM_Protection_Model_ThreadWatch > There are two tools to protect the Bb Content Content: These two tools are some stand-alone functions easy to use. 1) The parsing protection - this is the cleanest way to do this. Arguments: > $string The string to process > $checkVisitorPerms Optional. Default is true. This will protect the Bb Code Content only if the user doesn't have the permission to see it. In some case the parameter must be set on false. For example with email or alerts => even if the visitor has the permission to see the content it doesn't mean the one who will receive the email or the alert has also this permission 2) The mini parser protection - An alternative to the XenForo parser/formatter Reason: with an incomplete closing tag, the XenForo parser will eat all the remaining text... if you apply this to the html output, it's really a problem Arguments are the same than the two above **************************************/ /**** * Debug tool ***/ protected static $_debug; /**** * XenForo Listeners Hooks ***/ protected static $_isControllerAdmin = false; protected static $_responseType = NULL; protected static $_isJson = false; //Double check protected static $_controllerName = NULL; protected static $_controllerAction = NULL; protected static $_viewName = NULL; protected static $_processMiniParser = false; protected static $_processParsing = true; public static function controllerPreDispatch(XenForo_FrontController $fc, XenForo_RouteMatch &$routeMatch) { /* Listener - Execution order: #1 */ self::$_responseType = $routeMatch->getResponseType(); } public static function controllerPreView(XenForo_FrontController $fc, XenForo_ControllerResponse_Abstract &$controllerResponse, XenForo_ViewRenderer_Abstract &$viewRenderer, array &$containerParams ) { /* Listener - Execution order: #2 */ self::$_isControllerAdmin = (strstr($controllerResponse->controllerName, 'ControllerAdmin')) ? true : false; self::$_controllerName = (isset($controllerResponse->controllerName)) ? $controllerResponse->controllerName : NULL; self::$_controllerAction = (isset($controllerResponse->controllerAction)) ? $controllerResponse->controllerAction : NULL; self::$_viewName = (isset($controllerResponse->viewName)) ? $controllerResponse->viewName : NULL; self::$_isJson = ($viewRenderer instanceof XenForo_ViewRenderer_Json) ? true : false; if(XenForo_Application::get('options')->get('Bbm_ContentProtection') && self::$_isControllerAdmin === false) { if(self::$_isJson == true) { /*** * Protect Json Response here. It will not work with the controllerPostView listener (will generate an error) **/ if(isset($controllerResponse->params['post']['message'])) { /*** * Use for: - Edit inline * - Thread fast preview (small popup when mouse over title) * - Thread/post/conversation edit preview **/ $controllerResponse->params['post']['message'] = self::parsingProtection($controllerResponse->params['post']['message']); } if(isset($controllerResponse->params['quote'])) { /*** * Use for: - Quotes **/ $controllerResponse->params['quote'] = self::parsingProtection($controllerResponse->params['quote'], true, 'quotes'); } } } if(self::$_debug == 'pre' && self::$_isControllerAdmin === false) { $visitor = XenForo_Visitor::getInstance(); if($visitor['is_admin']) { Zend_Debug::dump($controllerResponse); } } /*Extra function to hide tags in Thread fast preview*/ if(self::$_isJson == true && self::$_viewName == 'XenForo_ViewPublic_Thread_Preview' && XenForo_Application::get('options')->get('Bbm_HideTagsInFastPreview')) { if(isset($controllerResponse->params['post']['message'])) { if(XenForo_Application::get('options')->get('Bbm_HideTagsInFastPreviewInvisible')) { $formatter = XenForo_BbCode_Formatter_Base::create('BBM_Protection_BbCode_Formatter_BbCode_Eradicator', false); $formatter->setAllTagsAsProtected(); $formatter->invisibleMode(); } else { $formatter = XenForo_BbCode_Formatter_Base::create('BBM_Protection_BbCode_Formatter_BbCode_Lupin', false); } $parser = XenForo_BbCode_Parser::create($formatter); $extraStates = array( 'bbmContentProtection' => true ); $controllerResponse->params['post']['message'] = $parser->render($controllerResponse->params['post']['message'], $extraStates); } } } public static function controllerPostView($fc, &$output) { /* Listener - Execution order: #3 */ if(XenForo_Application::get('options')->get('Bbm_ContentProtection') && self::$_isControllerAdmin === false && is_string($output)) { if(self::$_responseType == 'html' && self::$_isJson != true && self::$_processParsing == true) { //Don't use the parser method, if it finds an opening tag it will "eat" all the page. Use instead the regex method //$output = self::parsingProtection($output); $output = self::miniParserProtection($output, true); } elseif(self::$_processMiniParser == true) { $output = self::miniParserProtection($output, true); } } if(self::$_debug == 'post' && self::$_isControllerAdmin === false) { $visitor = XenForo_Visitor::getInstance(); if($visitor['is_admin']) { Zend_Debug::dump($output); } } } /**** * Bbm Bb Codes Content Protection tools ***/ public static function parsingProtection($string, $checkVisitorPerms = true, $src = null) { if(XenForo_Application::get('options')->get('Bbm_ContentProtection')) { $formatter = XenForo_BbCode_Formatter_Base::create('BBM_Protection_BbCode_Formatter_BbCode_Eradicator', false); $formatter->setCheckVisitorPerms($checkVisitorPerms); $parser = XenForo_BbCode_Parser::create($formatter); $extraStates = array( 'bbmContentProtection' => true ); $string = $parser->render($string, $extraStates); if($src == 'quotes') { $string.= "\r\n"; } } return $string; } public static function miniParserProtection($string, $checkVisitorPerms = true) { $visitor = XenForo_Visitor::getInstance(); $options = XenForo_Application::get('options'); if(!$options->Bbm_ContentProtection) { return $string; } $bbmCached = XenForo_Application::getSimpleCacheData('bbm_active'); if( !is_array($bbmCached) || !isset($bbmCached['protected']) || !is_array($bbmCached['protected']) || empty($bbmCached['protected']) ) { return $string; } if($checkVisitorPerms === true) { $visitorUserGroupIds = array_merge(array((string)$visitor['user_group_id']), (explode(',', $visitor['secondary_group_ids']))); } $protectedTags = $bbmCached['protected']; $replace = new XenForo_Phrase('bbm_viewer_content_protected'); $openTags = array(); $xenProtectedTags = array('attach', 'email', 'img', 'media', 'url'); $xenProtectedTagsNoPermsDisplay = false;//make another phrase inviting the user to log to see the content? foreach($xenProtectedTags as $tagName) { $permKey = "bbm_hide_{$tagName}"; $permsVal = $visitorUserGroupIds; if($checkVisitorPerms === true) { if($visitor->hasPermission('bbm_bbcodes_grp', $permKey)) { $permsVal = array(); } } else { //ie: for alerts, mails if($xenProtectedTagsNoPermsDisplay) { $permsVal = array(); } } $protectedTags[$tagName] = $permsVal; } foreach($protectedTags AS $tag => $perms) { if($checkVisitorPerms === true && array_intersect($visitorUserGroupIds, $perms)) { continue; } $openTags[] = $tag; } $tagRules = array(); foreach($openTags as $tag) { $tagRules[$tag] = array( 'stringReplace' => new XenForo_Phrase('bbm_viewer_content_protected') ); } $parserOptions = array( 'parserOpeningCharacter' => '[', 'parserClosingCharacter' => ']', 'htmlspecialcharsForContent' => false, 'htmlspecialcharsForOptions' => false, 'nl2br' => false, 'checkClosingTag' => true, 'preventHtmlBreak' => true ); if(!preg_match('# $string)) { $miniParser = new BBM_Protection_Helper_MiniParser($string, $tagRules, array(), $parserOptions); $string = $miniParser->render(); } return $string; } } //Zend_Debug::dump($string);
php
20
0.66369
160
32.07047
298
starcoderdata
namespace Z.Dapper.Plus { public partial class DapperPlusEntityMapper { /// the retry count. /// retry count. public int? RetryCount() { return _retryCount ?? (!_isMasterConfig ? _masterConfig._retryCount : null); } /// the retry interval. /// retry interval. public int? RetryInterval() { return _retryInterval ?? (!_isMasterConfig ? _masterConfig._retryInterval : null); } /// the retry count. /// <param name="retryCount">The retry count. /// DapperPlusActionSet. public DapperPlusEntityMapper RetryCount(int retryCount) { _retryCount = retryCount; return this; } /// the retry interval. /// <param name="retryInterval">The retry interval. /// DapperPlusActionSet. public DapperPlusEntityMapper RetryInterval(int retryInterval) { _retryInterval = retryInterval; return this; } } }
c#
10
0.586098
94
32.342105
38
starcoderdata
import { createApp } from './app' import Vue from 'vue' import api from '~api' import 'toastr/build/toastr.css' import {Utils} from '@/util/index.js' let util = new Utils() const { app, router, store } = createApp(util.getCookie('uid')) import theme from 'muse-ui/lib/theme'; if(util.isMobile()){ console.log("是移动端喔") // theme.use('ltlight'); store.isMobile = store.state.isMobile = true }else { // theme.use('ltdark'); console.log("不是移动端喔") } Vue.use(theme); Vue.mixin({ beforeRouteUpdate(to, from, next) { const { asyncData } = this.$options if (asyncData) { asyncData({ store: this.$store, route: to }).then(next).catch(next) } else { next() } } }) // 将服务端渲染时候的状态写入vuex中 if (window.__INITIAL_STATE__) { store.replaceState(window.__INITIAL_STATE__) store.$api = store.state.$api = api // 可做其他操作 -- 例如初始化 } router.onReady(() => { router.beforeResolve((to, from, next) => { const matched = router.getMatchedComponents(to) const prevMatched = router.getMatchedComponents(from) // 我们只关心之前没有渲染的组件 // 所以我们对比它们,找出两个匹配列表的差异组件 let diffed = false const activated = matched.filter((c, i) => { return diffed || (diffed = (prevMatched[i] !== c)) }) if (!activated.length) { return next() } // 这里如果有加载指示器(loading indicator),就触发 Promise.all(activated.map(c => { /** * 两种情况下执行asyncData: * 1. 非keep-alive组件每次都需要执行 * 2. keep-alive组件首次执行,执行后添加标志 */ if (c.asyncData) { return c.asyncData({ store, route: to, isServer: false, isClient: true, isMobile: store.state.isMobile }) } })).then(() => { // 停止加载指示器(loading indicator) next() }).catch(next) }) app.$mount('#app') }) // service worker // if ('serviceWorker' in navigator) { // navigator.serviceWorker.register('/service-worker.js'); // } if ('serviceWorker' in navigator) { console.log("SW present !!! "); navigator.serviceWorker.register('/service-worker.js', { //scope: '/toto/' }).then(function (registration) { console.log('Service worker registered : ', registration.scope); }) .catch(function (err) { console.log("Service worker registration failed : ", err); }); }
javascript
29
0.523827
72
23.227273
110
starcoderdata
#include #include "ScreenDebugger.h" #ifdef USE_SCREENDEBUGGER ScreenDebugger::ScreenDebugger(U8G2* pTheScreen, uint16_t linesBeforeDelay, uint16_t delayAfterLineMS, bool showLineNumber) : _pTheScreen(pTheScreen) , _TheDelay(delayAfterLineMS) , _LinesBeforeWait(linesBeforeDelay) , _LinesAddedNoWait(0) , _ShowLineNumber(showLineNumber) , _LinesAdded(0) { } void ScreenDebugger::SetFont(FONTS theFont) { if(!_pTheScreen) { return; } switch(theFont) { case FONTS::MINSIZE: _pTheScreen->setFont(u8g2_font_tom_thumb_4x6_mf); break; case FONTS::SIZE1: _pTheScreen->setFont(u8g2_font_5x8_mf); break; case FONTS::SIZE2: _pTheScreen->setFont(u8g2_font_6x12_mf); break; case FONTS::SIZE3: _pTheScreen->setFont(u8g2_font_7x13_mf); break; case FONTS::SIZE4: _pTheScreen->setFont(u8g2_font_9x15_mf); break; case FONTS::SIZE5: _pTheScreen->setFont(u8g2_font_10x20_mf); break; case FONTS::MAXSIZE: _pTheScreen->setFont(u8g2_font_inr16_mf); break; } } void ScreenDebugger::NewLine(const char* pTheLine, bool repaint) { std::string theLine(pTheLine); NewLine(theLine, repaint); } void ScreenDebugger::NewLine(std::string& theLine, bool repaint) { uint16_t charH = _pTheScreen->getMaxCharHeight() == 0 ? 1 : _pTheScreen->getMaxCharHeight(); uint16_t h = _pTheScreen->getHeight(); uint16_t maxLines=h/charH; _LinesAdded++; char buff[10]; snprintf(buff, sizeof(buff), "%03d.", _LinesAdded); std::string line(buff+theLine); if(_ThePhrases.size()<maxLines) { _ThePhrases.push_back(line); } else if(_ThePhrases.size() > maxLines) { do { if(_FirstLine>0) { _ThePhrases.erase(_ThePhrases.begin()); _FirstLine--; } else { _ThePhrases.pop_back(); } } while(_ThePhrases.size()>maxLines); } else { //_ThePhrases.size() == maxLines _ThePhrases[_FirstLine]=line; _FirstLine = (_FirstLine + 1) % maxLines; } if(repaint) { DrawLines(); } if(_TheDelay > 0) { _LinesAddedNoWait++; if(_LinesAddedNoWait >= _LinesBeforeWait) { delay(_TheDelay); _LinesAddedNoWait=0; } } } void ScreenDebugger::NewLines(std::list lines, bool repaint) { auto iter=lines.begin(); int i=0; while(iter != lines.end()) { NewLine(*iter, i == (lines.size()-1)?repaint:false); //only repaint on the last line i++; iter++; } } void ScreenDebugger::DrawLines() { if(!_pTheScreen) { return; } uint16_t charH = _pTheScreen->getMaxCharHeight() == 0 ? 10 : _pTheScreen->getMaxCharHeight(); uint16_t maxHeight = _pTheScreen->getHeight(); uint16_t j = charH; auto iter = _ThePhrases.begin(); _pTheScreen->firstPage(); do { j=charH; iter = _ThePhrases.begin(); while(iter != _ThePhrases.end() && j <= maxHeight) { _pTheScreen->setCursor(0, j); _pTheScreen->print((*iter).c_str()); j+=charH; iter++; } } while(_pTheScreen->nextPage()); } #endif
c++
17
0.669442
123
20.840909
132
starcoderdata
def data_upgrades(): """Add optional data upgrade migrations here""" conn = op.get_bind() projs = conn.execute(sa.select([ t_project.c.id, t_project.c.graph ])).fetchall() def process_node(n): """ Reformat node data structure (1) Adds the hyperlinks key (2) Adds the sources key """ node_data = n['data'] # Add the hyperlinks key and transfer any existing hyperlink over if it exists if 'hyperlinks' not in node_data: # Reformat existing hyperlink if it exists if node_data.get('hyperlink'): node_data['hyperlinks'] = [dict(domain='', url=node_data['hyperlink'])] else: node_data['hyperlinks'] = [] # Add the sources key and transfer any existing source over if it exists if 'sources' not in node_data: # Reformat existing source if it exists if node_data.get('source'): node_data['sources'] = [dict(type='', domain='', url=node_data['source'])] else: node_data['sources'] = [] return n def process_edge(e): """ Reformat edge data structure (1) Adds the hyperlinks key (2) Adds the sources key """ if 'data' in e: edge_data = e['data'] if 'hyperlinks' not in e['data']: if edge_data.get('hyperlink'): edge_data['hyperlinks'] = [dict(domain='', url=edge_data['hyperlink'])] else: edge_data['hyperlinks'] = [] if 'sources' not in e['data']: if edge_data.get('source'): edge_data['sources'] = [dict(type='', domain='', url=edge_data['source'])] else: edge_data['sources'] = [] else: # If no data attribute, add one e['data'] = dict(hyperlinks=[], sources=[]) return e for proj_id, graph in projs: nodes_copy = copy.deepcopy(graph['nodes']) edges_copy = copy.deepcopy(graph['edges']) graph['nodes'] = [process_node(n) for n in nodes_copy] graph['edges'] = [process_edge(e) for e in edges_copy] conn.execute(t_project.update().where(t_project.c.id == proj_id).values(graph=graph))
python
19
0.525416
94
37.393443
61
inline
using System.Threading; using System.Threading.Tasks; using AutoMapper; using NetLearningGuide.Message.Commands.Demo; using NetLearningGuide.Message.Dtos.Demo; namespace NetLearningGuide.Core.Services.Demo.AutoMapper { public class DemoAutoMapperService : IDemoAutoMapperService { private readonly IMapper _mapper; public DemoAutoMapperService(IMapper mapper) { _mapper = mapper; } public async Task AutoMapperTest(DemoMappingServiceCommand demoMappingCommand, CancellationToken cancellationToken) { return await Task.Run(() => { return _mapper.Map }).ConfigureAwait(false); } } }
c#
21
0.679172
139
29.92
25
starcoderdata
void RasterizerSceneRD::_allocate_blur_textures(RenderBuffers *rb) { ERR_FAIL_COND(!rb->blur[0].texture.is_null()); uint32_t mipmaps_required = Image::get_image_required_mipmaps(rb->width, rb->height, Image::FORMAT_RGBAH); RD::TextureFormat tf; tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT; tf.width = rb->width; tf.height = rb->height; tf.type = RD::TEXTURE_TYPE_2D; tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_COPY_TO_BIT; tf.mipmaps = mipmaps_required; rb->blur[0].texture = RD::get_singleton()->texture_create(tf, RD::TextureView()); //the second one is smaller (only used for separatable part of blur) tf.width >>= 1; tf.height >>= 1; tf.mipmaps--; rb->blur[1].texture = RD::get_singleton()->texture_create(tf, RD::TextureView()); int base_width = rb->width; int base_height = rb->height; for (uint32_t i = 0; i < mipmaps_required; i++) { RenderBuffers::Blur::Mipmap mm; mm.texture = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), rb->blur[0].texture, 0, i); { Vector<RID> fbs; fbs.push_back(mm.texture); mm.framebuffer = RD::get_singleton()->framebuffer_create(fbs); } mm.width = base_width; mm.height = base_height; rb->blur[0].mipmaps.push_back(mm); if (i > 0) { mm.texture = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), rb->blur[1].texture, 0, i - 1); { Vector<RID> fbs; fbs.push_back(mm.texture); mm.framebuffer = RD::get_singleton()->framebuffer_create(fbs); } rb->blur[1].mipmaps.push_back(mm); } base_width = MAX(1, base_width >> 1); base_height = MAX(1, base_height >> 1); } }
c++
14
0.665897
157
31.111111
54
inline
int parseXmlTag( void **inPtr, packItem_t *myPackedItem, int flag, int *skipLen ) { char *inStrPtr, *tmpPtr; int nameLen; int myLen = 0; inStrPtr = ( char * ) * inPtr; nameLen = strlen( myPackedItem->name ); if ( flag & END_TAG_FL ) { /* end tag */ char endTag[MAX_NAME_LEN]; snprintf( endTag, MAX_NAME_LEN, "</%s>", myPackedItem->name ); if ( ( tmpPtr = strstr( inStrPtr, endTag ) ) == NULL ) { rodsLog( LOG_ERROR, "parseXmlTag: XML end tag error for %s, expect </%s>", *inPtr, myPackedItem->name ); return SYS_PACK_INSTRUCT_FORMAT_ERR; } *skipLen = tmpPtr - inStrPtr; myLen = nameLen + 3; inStrPtr = tmpPtr + nameLen + 3; if ( *inStrPtr == '\n' ) { myLen++; } } else { /* start tag */ if ( ( tmpPtr = strstr( inStrPtr, "<" ) ) == NULL ) { return SYS_PACK_INSTRUCT_FORMAT_ERR; } *skipLen = tmpPtr - inStrPtr; inStrPtr = tmpPtr + 1; myLen++; if ( strncmp( inStrPtr, myPackedItem->name, nameLen ) != 0 ) { /* this can be normal */ rodsLog( LOG_DEBUG1, "parseXmlValue: XML start tag error for %s, expect <%s>", *inPtr, myPackedItem->name ); return SYS_PACK_INSTRUCT_FORMAT_ERR; } inStrPtr += nameLen; myLen += nameLen; if ( *inStrPtr != '>' ) { rodsLog( LOG_DEBUG1, "parseXmlValue: XML start tag error for %s, expect <%s>", *inPtr, myPackedItem->name ); return SYS_PACK_INSTRUCT_FORMAT_ERR; } myLen++; inStrPtr ++; if ( ( flag & LF_FL ) && *inStrPtr == '\n' ) { myLen++; } } return myLen; }
c++
13
0.472545
79
27.283582
67
inline
# This module contains the shaders used to region-select objects. # The following vertex shader is used to region-select top-level objects VERT_SHADER = """ #version 420 uniform mat4 p3d_ModelViewProjectionMatrix; in vec4 p3d_Vertex; uniform int index; flat out int oindex; void main() { gl_Position = p3d_ModelViewProjectionMatrix * p3d_Vertex; oindex = index; } """ # The following fragment shader is used to determine which objects lie # within a rectangular region FRAG_SHADER = """ #version 420 layout(r32i) uniform iimageBuffer selections; flat in int oindex; void main() { // Write 1 to the location corresponding to the custom index imageAtomicOr(selections, (oindex >> 5), 1 << (oindex & 31)); } """ # The following fragment shader is used to constrain the selection to an # elliptic region FRAG_SHADER_ELLIPSE = """ #version 420 uniform vec4 ellipse_data; layout(r32i) uniform iimageBuffer selections; flat in int oindex; void main() { float radius, aspect_ratio, offset_x, offset_y, x, y, dist; radius = ellipse_data.x; aspect_ratio = ellipse_data.y; // the ellipse might be clipped by the viewport border, so it is // necessary to know the left and bottom offsets of this clipped // portion offset_x = ellipse_data.z; offset_y = ellipse_data.w; ivec2 coord = ivec2(gl_FragCoord.xy); x = offset_x + coord.x - radius; y = (offset_y + coord.y) * aspect_ratio - radius; dist = sqrt((x * x) + (y * y)); // only consider pixels that are inside of the ellipse if (dist > radius) { discard; } // Write 1 to the location corresponding to the custom index imageAtomicOr(selections, (oindex >> 5), 1 << (oindex & 31)); } """ # The following fragment shader is used to constrain the selection to a # free-form (point-to-point "fence", lasso or painted) region FRAG_SHADER_FREE = """ #version 420 uniform sampler2D mask_tex; layout(r32i) uniform iimageBuffer selections; flat in int oindex; void main() { vec4 texelValue = texelFetch(mask_tex, ivec2(gl_FragCoord.xy), 0); // discard pixels whose corresponding mask texels are (0., 0., 0., 0.) if (texelValue == vec4(0., 0., 0., 0.)) { discard; } // Write 1 to the location corresponding to the custom index imageAtomicOr(selections, (oindex >> 5), 1 << (oindex & 31)); } """ # The following fragment shader is used to determine which objects are # not completely enclosed within a rectangular region FRAG_SHADER_INV = """ #version 420 uniform vec2 buffer_size; layout(r32i) uniform iimageBuffer selections; flat in int oindex; void main() { int w, h, x, y; w = int(buffer_size.x); h = int(buffer_size.y); x = int(gl_FragCoord.x); y = int(gl_FragCoord.y); // only consider border pixels if ((x > 1) && (x < w) && (y > 1) && (y < h)) { discard; } // Write 1 to the location corresponding to the custom index imageAtomicOr(selections, (oindex >> 5), 1 << (oindex & 31)); } """ # The following fragment shader is used to determine which objects are # not completely enclosed within an elliptic region FRAG_SHADER_ELLIPSE_INV = """ #version 420 uniform vec4 ellipse_data; layout(r32i) uniform iimageBuffer selections; flat in int oindex; void main() { float radius, aspect_ratio, offset_x, offset_y, x, y, dist; radius = ellipse_data.x; aspect_ratio = ellipse_data.y; // the ellipse might be clipped by the viewport border, so it is // necessary to know the left and bottom offsets of this clipped // portion offset_x = ellipse_data.z; offset_y = ellipse_data.w; ivec2 coord = ivec2(gl_FragCoord.xy); x = offset_x + coord.x - 2 - radius; y = (offset_y + coord.y - 2) * aspect_ratio - radius; dist = sqrt((x * x) + (y * y)); // only consider pixels that are outside of the ellipse if (dist <= radius) { discard; } // Write 1 to the location corresponding to the custom index imageAtomicOr(selections, (oindex >> 5), 1 << (oindex & 31)); } """ # The following fragment shader is used to determine which objects are not # completely enclosed within a free-form (fence, lasso or painted) region FRAG_SHADER_FREE_INV = """ #version 420 uniform sampler2D mask_tex; layout(r32i) uniform iimageBuffer selections; flat in int oindex; void main() { vec4 texelValue = texelFetch(mask_tex, ivec2(gl_FragCoord.xy), 0); // only consider pixels whose corresponding mask texels are (0., 0., 0., 0.) if (texelValue != vec4(0., 0., 0., 0.)) { discard; } // Write 1 to the location corresponding to the custom index imageAtomicOr(selections, (oindex >> 5), 1 << (oindex & 31)); } """ # The following shaders are used to gradually create a mask texture that can # in turn be used as input for the free-form region-selection fragment shaders. VERT_SHADER_MASK = """ #version 420 uniform mat4 p3d_ModelViewProjectionMatrix; in vec4 p3d_Vertex; void main() { gl_Position = p3d_ModelViewProjectionMatrix * p3d_Vertex; } """ FRAG_SHADER_MASK = """ #version 420 uniform sampler2D prev_tex; uniform vec4 fill_color; layout(location = 0) out vec4 out_color; void main() { vec4 texelValue = texelFetch(prev_tex, ivec2(gl_FragCoord.xy), 0); if (texelValue == vec4(0., 0., 0., 0.)) { out_color = fill_color; } else { out_color = vec4(0., 0., 0., 0.); } } """
python
4
0.608097
84
26.43318
217
starcoderdata
using System; using System.Linq; using System.Linq.Expressions; using AutoMapper; using AutoMapper.QueryableExtensions; namespace DigitalReceipt.Common.Mappings { public static class MappingExtensions { public static IQueryable To this IQueryable source, params Expression<Func<TDestination, object>>[] membersToExpand) { if (source == null) { throw new ArgumentNullException(nameof(source)); } return source.ProjectTo(AutoMapperConfig.MapperInstance.ConfigurationProvider, null, membersToExpand); } public static IQueryable To this IQueryable source, object parameters) { if (source == null) { throw new ArgumentNullException(nameof(source)); } return source.ProjectTo parameters); } public static Destination To object source) => AutoMapperConfig.MapperInstance.Map public static Destination To object source, object destination) => (Destination)AutoMapperConfig.MapperInstance.Map(source, destination, source.GetType(), destination.GetType()); public static Destination To<Source, Destination>(this Source source, Destination destination, Action<IMappingOperationOptions<Source, Destination>> options) => AutoMapperConfig.MapperInstance.Map(source, destination, options); } }
c#
16
0.677536
168
36.636364
44
starcoderdata
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Utilities; using System.Collections.Generic; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Input { /// /// Configuration profile settings for setting up and consuming Input Actions. /// [CreateAssetMenu(menuName = "Mixed Reality Toolkit/Profiles/Mixed Reality Input Actions Profile", fileName = "MixedRealityInputActionsProfile", order = (int)CreateProfileMenuItemIndices.InputActions)] [DocLink("https://microsoft.github.io/MixedRealityToolkit-Unity/Documentation/Input/InputActions.html")] public class MixedRealityInputActionsProfile : BaseMixedRealityProfile { private readonly string[] defaultInputActions = { "Select", "Menu", "Grip", "Pointer", "Walk", "Look", "Interact", "Pickup", "Inventory", "ConversationSelect" }; // Examples only, to be refined later. private readonly AxisType[] defaultInputActionsAxis = { AxisType.Digital, AxisType.Digital, AxisType.SixDof, AxisType.SixDof, AxisType.DualAxis, AxisType.DualAxis, AxisType.DualAxis, AxisType.Digital, AxisType.DualAxis, AxisType.DualAxis }; // Examples only, to be refined later [SerializeField] [Tooltip("The list of actions users can do in your application.")] private MixedRealityInputAction[] inputActions = { // 0 is reserved for "None" new MixedRealityInputAction(1, "Select"), new MixedRealityInputAction(2, "Menu"), new MixedRealityInputAction(3, "Grip") }; // Examples only, to be refined later /// /// The list of actions users can do in your application. /// /// Actions are device agnostic and can be paired with any number of device inputs across all platforms. public MixedRealityInputAction[] InputActions => inputActions; /// /// Reset the current InputActions definitions to the Mixed Reality Toolkit defaults /// If existing mappings exist, they will be preserved and pushed to the end of the array /// /// MRTK Actions plus any custom actions (if already configured) public MixedRealityInputAction[] LoadMixedRealityToolKitDefaults() { var defaultActions = new List bool exists = false; for (uint i = 0; i < defaultInputActions.Length; i++) { defaultActions.Add(new MixedRealityInputAction(i, defaultInputActions[i], defaultInputActionsAxis[i])); } for (int i = 0; i < inputActions.Length; i++) { if (defaultActions.Contains(inputActions[i])) { exists = true; } if (!exists) { defaultActions.Add(inputActions[i]); } exists = false; } return inputActions = defaultActions.ToArray(); } } }
c#
19
0.582503
204
36.446809
94
starcoderdata
/* This file is part of VoltDB. * Copyright (C) 2019 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see */ #include "common/TupleSchema.h" #include "indexes/tableindexfactory.h" #include "topics/TableFactory.h" #include "storage/tablefactory.h" #include "storage/SystemTableFactory.h" using namespace voltdb; PersistentTable* SystemTableFactory::createTable(char const *name, TupleSchema *schema, const std::vector &columnNames, const int partitionColumn) const { vassert(partitionColumn >= 0 && partitionColumn < columnNames.size()); Table *table = TableFactory::getPersistentTable(0, name, schema, columnNames, nullptr, false, partitionColumn, TableType::PERSISTENT, 0, m_compactionThreshold, false, false); return dynamic_cast } void SystemTableFactory::addIndex(PersistentTable *table, const std::string name, const std::vector &columns, bool unique, bool primary, AbstractExpression* predicate) const { auto indexedExpressions = TableIndex::simplyIndexColumns(); TableIndexScheme scheme(name, BALANCED_TREE_INDEX, columns, indexedExpressions, predicate, unique, false, false, "", "", table->schema()); TableIndex *index = TableIndexFactory::getInstance(scheme); table->addIndex(index); if (unique && primary) { table->setPrimaryKeyIndex(index); } } PersistentTable* SystemTableFactory::create(const SystemTableId id) { switch (id) { case SystemTableId::TOPICS_GROUP: return topics::TableFactory::createGroup(*this); case SystemTableId::TOPICS_GROUP_MEMBER: return topics::TableFactory::createGroupMember(*this); case SystemTableId::TOPICS_GROUP_OFFSET: return topics::TableFactory::createGroupOffset(*this); default: std::string errorMessage = "Unknown system table ID: " + std::to_string(static_cast throw SerializableEEException(VoltEEExceptionType::VOLT_EE_EXCEPTION_TYPE_GENERIC, errorMessage); } }
c++
15
0.730494
118
43.216667
60
starcoderdata
void DeregisterInterfaceWorker( PDEVICE_OBJECT DevObj, // Unused. Wish they passed the WorkItem instead. PVOID Context) // A DeregisterInterfaceContext struct. { DeregisterInterfaceContext *MyContext = Context; Interface *IF = MyContext->IF; NTSTATUS Status; UNREFERENCED_PARAMETER(DevObj); IoFreeWorkItem(MyContext->WorkItem); ExFreePool(MyContext); // // Deregister the interface with TDI, if it was registered. // The loopback interface is not registered. // if (IF->TdiRegistrationHandle != NULL) { Status = TdiDeregisterDeviceObject(IF->TdiRegistrationHandle); if (Status != STATUS_SUCCESS) KdPrintEx((DPFLTR_TCPIP6_ID, DPFLTR_NTOS_ERROR, "DeregisterInterfaceContext: " "TdiDeregisterDeviceObject: %x\n", Status)); } KdPrintEx((DPFLTR_TCPIP6_ID, DPFLTR_INFO_STATE, "DeregisterInterfaceWorker(IF %u/%p) -> freed\n", IF->Index, IF)); // // Perform final cleanup of the link-layer data structures. // if (IF->Cleanup != NULL) (*IF->Cleanup)(IF->LinkContext); ExFreePool(IF); // // Note that we've finished our cleanup. // InterlockedDecrement((PLONG)&OutstandingDeregisterInterfaceCount); }
c
15
0.622024
81
30.047619
42
inline
export function ThemeMe(theme) { return ( { background : theme.tertiary, color: theme.secondary } ) } export function ThemeFormation(theme) { return ( { background : theme.quaternary, color: theme.secondary } ) } export function ThemeSkill(theme) { return ( { background : theme.five, color: theme.secondary } ) } export function ThemeProject(theme) { return ( { background : theme.six, color: theme.secondary } ) } export function ThemeNetwork(theme) { return ( { background : theme.seven, color: theme.secondary } ) }
javascript
8
0.500645
42
16.244444
45
starcoderdata
void vtkQtChartLegend::calculateSize() { QSize bounds; if(this->Internal->Entries.size() > 0) { // Get the font height for the entries. For now, all the entries // use the same font. QFontMetrics fm = this->fontMetrics(); this->Internal->EntryHeight = fm.height(); if(this->Internal->EntryHeight < this->IconSize) { this->Internal->EntryHeight = this->IconSize; } // Find the width needed for each entry. Use the width to determine // the necessary space. int total = 0; int maxWidth = 0; int visibleCount = 0; QList<vtkQtChartLegendEntry *>::Iterator iter = this->Internal->Entries.begin(); for(int i = 0; iter != this->Internal->Entries.end(); ++iter, ++i) { if(this->Model && (this->Internal->FontChanged || (*iter)->Width == 0)) { QString text = this->Model->getText(i); (*iter)->Width = fm.width(text); QPixmap icon = this->Model->getIcon(i); if(!icon.isNull()) { (*iter)->Width += this->IconSize + this->TextSpacing; } } // Sum up the entry widths for left-to-right. In top-to-bottom // mode, find the max width. if((*iter)->Visible) { visibleCount++; if(this->Flow == vtkQtChartLegend::LeftToRight) { total += (*iter)->Width; if(i > 0) { total += this->TextSpacing; } } else if((*iter)->Width > maxWidth) { maxWidth = (*iter)->Width; } } } if(visibleCount > 0) { // Add space around the entries for the outline. int padding = 2 * this->Margin; if(this->Flow == vtkQtChartLegend::LeftToRight) { bounds.setHeight(total + padding); bounds.setWidth(this->Internal->EntryHeight + padding); if(this->Location == vtkQtChartLegend::Top || this->Location == vtkQtChartLegend::Bottom) { bounds.transpose(); } } else { total = this->Internal->EntryHeight * visibleCount; total += padding; if(visibleCount > 1) { total += (visibleCount - 1) * this->TextSpacing; } bounds.setWidth(maxWidth + padding); bounds.setHeight(total); if(this->Location == vtkQtChartLegend::Top || this->Location == vtkQtChartLegend::Bottom) { bounds.transpose(); } } } } if(bounds != this->Bounds) { this->Bounds = bounds; this->updateMaximum(); this->updateGeometry(); } }
c++
18
0.527674
77
27.157895
95
inline
import os from pathlib import Path import numpy as np from PIL import Image import cv2 import matplotlib.pyplot as plt root = str(Path(__file__).resolve().parent.parent) def main(): path = os.path.join(root, 'label_generator', 'data') path2 = os.path.join(root, 'data_generation', 'data') gt_path = os.path.join(root, 'experiments', 'data', 'gt_test') classes = [d for d in list(os.listdir(gt_path)) if os.path.isdir(os.path.join(gt_path, d))] print('classes', classes) gt_path = os.path.join(root, 'experiments', 'data', 'gt_test') plot_labels = False c0 = 0.7 c1 = 1.0 - c0 ch1 = 2 # color pred ch2 = 0 # color new pred and gen ious_gt_vs_new_pred = [] ious_gt_vs_pred = [] ious_pred_vs_new_pred = [] ious_gt_vs_gen = [] ious_gen_vs_pred = [] ious_1 = 0 ious_2 = 0 ious_3 = 0 ious_4 = 0 ious_5 = 0 total_samples = 0 rotations = ['foreground', 'foreground180'] for i, cls in enumerate(classes): #if cls != 'Joint': # continue for j, rot in enumerate(rotations): print('cls {}/{}, rot {}/{}'.format(i+1, len(classes), j+1, len(rotations))) rot_path = os.path.join(path, cls, rot) rot_path2 = os.path.join(path2, cls, rot) gt_rot_path = os.path.join(gt_path, cls, rot) tag = '.color.mask.0.png' samples = [s[:-len(tag)] for s in list(os.listdir(gt_rot_path)) if tag in s] for sample in samples: gt_sample_path = os.path.join(gt_rot_path, '{}{}'.format(sample, tag)) new_pred_path = os.path.join(rot_path, '{}.new_pred.label.png'.format(sample)) pred_path = os.path.join(rot_path, '{}.pred.label.png'.format(sample)) gen_path = os.path.join(rot_path, '{}.gen.label.png'.format(sample)) image_path = os.path.join(rot_path2, '{}.color.png'.format(sample)) gt_label = np.array(Image.open(gt_sample_path).convert('RGB'), dtype=np.uint8)[:, :, 0] new_pred_label = np.array(Image.open(new_pred_path).convert('RGB'), dtype=np.uint8)[:, :, 0] pred_label = np.array(Image.open(pred_path).convert('RGB'), dtype=np.uint8)[:, :, 0] gen_label = np.array(Image.open(gen_path).convert('RGB'), dtype=np.uint8)[:, :, 0] image = np.array(Image.open(image_path).convert('RGB'), dtype=np.uint8) if plot_labels: plt.subplot(2, 2, 1) plt.imshow(image) plt.axis('off') plt.title('RGB Image') plt.subplot(2, 2, 2) plt.imshow(gt_label) plt.axis('off') plt.title('Human Hand annotation') plt.subplot(2, 2, 3) plt.imshow(pred_label) plt.axis('off') plt.title('Background Subtraction') plt.subplot(2, 2, 4) plt.imshow(new_pred_label) plt.axis('off') plt.title('Segmentation Model') plt.show() if plot_labels: plt.subplot(2, 2, 1) plt.imshow(image) plt.axis('off') plt.title('RGB Image') plt.subplot(2, 2, 2) plt.imshow(gt_label) plt.axis('off') plt.title('Human Hand annotation') plt.subplot(2, 2, 3) plt.imshow(gen_label) plt.axis('off') plt.title('Classical Approach') plt.subplot(2, 2, 4) plt.imshow(pred_label) plt.axis('off') plt.title('Deep Learning Approach') plt.show() if plot_labels: added = image.copy() added[:, :, ch1][pred_label != 0] = added[:, :, ch1][pred_label != 0] * c0 + pred_label[pred_label != 0] * c1 added[:, :, ch2][new_pred_label != 0] = added[:, :, ch2][new_pred_label != 0] * c0 + new_pred_label[new_pred_label != 0] * c1 plt.imshow(added) plt.axis('off') plt.title('Background Subtraction vs Segmentation Model') plt.show() added = image.copy() added[:, :, ch1][pred_label != 0] = added[:, :, ch1][pred_label != 0] * c0 + pred_label[pred_label != 0] * c1 added[:, :, ch2][gen_label != 0] = added[:, :, ch2][gen_label != 0] * c0 + gen_label[gen_label != 0] * c1 plt.imshow(added) plt.axis('off') plt.title('Deep Learning vs Classical') plt.show() ious_gt_vs_new_pred.append(compute_IoU(gt_label, new_pred_label)) ious_gt_vs_pred.append(compute_IoU(gt_label, pred_label)) ious_pred_vs_new_pred.append(compute_IoU(pred_label, new_pred_label)) ious_gt_vs_gen.append(compute_IoU(gt_label, gen_label)) ious_gen_vs_pred.append(compute_IoU(gen_label, pred_label)) if ious_gt_vs_new_pred[-1][0] >= 0.5: ious_1 += 1 if ious_gt_vs_pred[-1][0] >= 0.5: ious_2 += 1 if ious_pred_vs_new_pred[-1][0] >= 0.5: ious_3 += 1 if ious_gt_vs_gen[-1][0] >= 0.5: ious_4 += 1 if ious_gen_vs_pred[-1][0] >= 0.5: ious_5 += 1 total_samples += 1 iou_gt_vs_new_pred = np.round(np.mean(np.array(ious_gt_vs_new_pred), axis=0), 4) iou_gt_vs_pred = np.round(np.mean(np.array(ious_gt_vs_pred), axis=0), 4) iou_pred_vs_new_pred = np.round(np.mean(np.array(ious_pred_vs_new_pred), axis=0), 4) iou_gt_vs_gen = np.round(np.mean(np.array(ious_gt_vs_gen), axis=0), 4) iou_gen_vs_pred = np.round(np.mean(np.array(ious_gen_vs_pred), axis=0), 4) ious_1_out = np.round(ious_1/total_samples, 4) ious_2_out = np.round(ious_2/total_samples, 4) ious_3_out = np.round(ious_3/total_samples, 4) ious_4_out = np.round(ious_4/total_samples, 4) ious_5_out = np.round(ious_5/total_samples, 4) print('gt_vs_new_pred: iou = {}, accuracy = {}, precision = {}, recall = {}, iou >= 0.5: {}'.format(*iou_gt_vs_new_pred, ious_1_out)) print('gt_vs_pred: iou = {}, accuracy = {}, precision = {}, recall = {}, iou >= 0.5: {} '.format(*iou_gt_vs_pred, ious_2_out)) print('pred_vs_new_pred: iou = {}, accuracy = {}, precision = {}, recall = {}, iou >= 0.5: {} '.format(*iou_pred_vs_new_pred, ious_3_out)) print('gt_vs_gen: iou = {}, accuracy = {}, precision = {}, recall = {}, iou >= 0.5: {} '.format(*iou_gt_vs_gen, ious_4_out)) print('gen_vs_pred: iou = {}, accuracy = {}, precision = {}, recall = {}, iou >= 0.5: {} '.format(*iou_gen_vs_pred, ious_5_out)) def compute_IoU(ground_truth, label): # flatten image, set 255 to 1 and background to 3 such that we can count tp, fp, fn, tn ground_truth_flat = np.ndarray.flatten(ground_truth) ground_truth_flat[ground_truth_flat != 0] = 1 ground_truth_flat[ground_truth_flat == 0] = 3 # flatten label as well label_flat = np.ndarray.flatten(label) label_flat[label_flat != 0] = 1 # compute difference, and get uniques and their counts diff = ground_truth_flat - label_flat unique, counts = np.unique(diff, return_counts=True) # count tp, fp and fn tp = 0 tn = 0 fp = 0 fn = 0 for j, i in enumerate(unique): if i == 0: tp = counts[j] elif i == 1: fp = counts[j] elif i == 2: fn = counts[j] elif i == 3: tn = counts[j] iou = float(float(tp) / float(tp + fp + fn)) accuracy = (tp + tn) / (tp + tn + fp + fn) precision = float(float(tp) / float(tp + fp)) recall = float(float(tp) / float(tp + fn)) return [iou, accuracy, precision, recall] def change_contrast(image): #print('change contrast') #cv2.imshow('input', np.array(image, dtype=np.uint8)) lab = cv2.cvtColor(np.array(image, dtype=np.uint8), cv2.COLOR_BGR2LAB) #cv2.imshow("lab", lab) l, a, b = cv2.split(lab) #cv2.imshow('l_channel', l) #cv2.imshow('a_channel', a) #cv2.imshow('b_channel', b) clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8)) cl = clahe.apply(l) #cv2.imshow('CLAHE output', cl) limg = cv2.merge((cl, a, b)) #cv2.imshow('limg', limg) image = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR) #cv2.imshow('final', image) return np.array(image, dtype=np.uint8) if __name__ == '__main__': main()
python
18
0.503905
153
39.589286
224
starcoderdata
package com.dynamsoft.dwt; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import javax.imageio.ImageIO; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; public class PDFUtil { public static byte[] createPDFFromImage(byte[] byteArray) throws IOException { InputStream input = null; byte[] ret = null; // the document PDDocument doc = null; PDPageContentStream contents = null; try { doc = new PDDocument(); // a valid PDF document requires at least one page PDPage page = new PDPage(); doc.addPage(page); input = new ByteArrayInputStream(byteArray); BufferedImage img = ImageIO.read(input); PDImageXObject pdImage = LosslessFactory.createFromImage(doc, img); input.close(); input=null; contents = new PDPageContentStream(doc, page); contents.drawImage(pdImage, 0, 0); contents.close(); ByteArrayOutputStream output = new ByteArrayOutputStream(); doc.save(output); doc.close(); doc = null; ret = output.toByteArray(); } finally { if(null != input) { input.close(); } if(null != contents) { contents.close(); } if( doc != null ) { doc.close(); } } return ret; } public static void saveToFile(byte[] binary, String filePath) { try { File f = new File(filePath); FileOutputStream fs = new FileOutputStream(f); fs.write(binary); fs.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassCastException e) { e.printStackTrace(); } finally { } } public static byte[] createPDFFromURL(URL url) throws IOException { InputStream input = null; byte[] ret = null; // the document PDDocument doc = null; PDPageContentStream contents = null; try { doc = new PDDocument(); // a valid PDF document requires at least one page PDPage page = new PDPage(); doc.addPage(page); BufferedImage image = ImageIO.read(url); PDImageXObject pdImage = LosslessFactory.createFromImage(doc, image); contents = new PDPageContentStream(doc, page); contents.drawImage(pdImage, 0, 0, 600, 800); contents.close(); ByteArrayOutputStream output = new ByteArrayOutputStream(); doc.save(output); ret = output.toByteArray(); } finally { if(null != input) { input.close(); } if(null != contents) { contents.close(); } if( doc != null ) { doc.close(); } } return ret; } }
java
13
0.559954
78
23.556338
142
starcoderdata
TEST(StatsTest, PerNodeTimeSeriesSingleThread) { StatsHolder holder( StatsParams().setIsServer(false).setNodeStatsRetentionTimeOnClients( DEFAULT_TEST_TIMEOUT)); NodeID id1{1}, id2{2}; StatsHolder* holder_ptr = &holder; PER_NODE_STAT_ADD(holder_ptr, id1, AppendSuccess); PER_NODE_STAT_ADD(holder_ptr, id1, AppendSuccess); PER_NODE_STAT_ADD(holder_ptr, id1, AppendFail); PER_NODE_STAT_ADD(holder_ptr, id2, AppendFail); std::unordered_map<NodeID, size_t, NodeID::Hash> append_success; std::unordered_map<NodeID, size_t, NodeID::Hash> append_fail; const auto now = std::chrono::steady_clock::now(); // the only thread is this one though, so it'll only loop once holder.runForEach([&](Stats& stats) { for (auto& thread_node_stats : stats.synchronizedCopy(&Stats::per_node_stats)) { thread_node_stats.second->updateCurrentTime(now); append_success[thread_node_stats.first] += thread_node_stats.second->sumAppendSuccess( now - DEFAULT_TEST_TIMEOUT, now); append_fail[thread_node_stats.first] += thread_node_stats.second->sumAppendFail( now - DEFAULT_TEST_TIMEOUT, now); } }); EXPECT_EQ(2, append_success[id1]); EXPECT_EQ(1, append_fail[id1]); EXPECT_EQ(0, append_success[id2]); EXPECT_EQ(1, append_fail[id2]); }
c++
15
0.673348
74
32.7
40
inline
@Test public void getEffectiveDomainConfig_returnsCorrectConfig() { Map<String, Set<String>> clusters = new HashMap(); clusters.put(CLUSTER1, getServers(SERVER1)); clusters.put(CLUSTER2, getServers(SERVER2)); Set<String> servers = getServers(SERVER3); DomainSpec domainSpec = new DomainSpec(); Domain domain = newDomainV1Dot1().withSpec(domainSpec); DomainConfig actual = getHelper().getEffectiveDomainConfig(domain, servers, clusters); // Just spot check that the expected servers and clusters got created assertThat(actual.getServers().keySet(), contains(SERVER3)); assertThat(actual.getClusters().keySet(), contains(CLUSTER1, CLUSTER2)); assertThat(actual.getClusters().get(CLUSTER1).getServers().keySet(), contains(SERVER1)); assertThat(actual.getClusters().get(CLUSTER2).getServers().keySet(), contains(SERVER2)); }
java
11
0.739429
92
47.666667
18
inline
from __future__ import annotations import copy import json import random from pathlib import Path from typing import Any, Optional, Union from .dicttree import flattenDict as _flattenDict from .dicttree import flattenDictIter as _flattenDictIter from .dicttree import foldDict as _foldDict from .dicttree import update_tree as _update def _query(q, dct): return { k.removeprefix(q + '.'): v for k, v in dct.items() if k.startswith(q + '.') } def randomStr(n): s = ('abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' '0123456789') return ''.join(random.choices(s, k=n)) def mixin(o: object, *traits: type) -> object: bases = (o.__class__, *traits) name = '_'.join([cls.__name__ for cls in bases]) name = '_'.join([name, randomStr(6)]) cls = type(name, bases, {}) o.__class__ = cls return o class TraitMeta(type): _traits = {} def __new__(cls, name, bases, namespace): cls = super().__new__(cls, name, bases, namespace) if name != 'Trait': TraitMeta._traits[name] = cls return cls class Trait(metaclass=TraitMeta): pass def queryKey(q, dct, prefix=None): if prefix is None: prefix = [] keys = q.split('.', maxsplit=1) if not isinstance(dct, dict): k = '.'.join(prefix) raise KeyError( f"Query {k}.{q} error, type '{k}' is {type(dct)}, not dict.") try: sub = dct[keys[0]] except KeyError: k = '.'.join([*prefix, keys[0]]) raise KeyError( f"Query {'.'.join([*prefix, q])} error, key '{k}' not found.") if len(keys) == 1: return sub else: return queryKey(keys[1], sub, [*prefix, keys[0]]) def query(q, dct, prefix=None): if isinstance(q, str): return queryKey(q, dct, prefix) elif isinstance(q, list): return [query(sub_q, dct, prefix) for sub_q in q] elif isinstance(q, tuple): return tuple([query(sub_q, dct, prefix) for sub_q in q]) elif isinstance(q, set): return {sub_q: query(sub_q, dct, prefix) for sub_q in q} elif isinstance(q, dict): if prefix is None: prefix = [] ret = {} for k, sub_q in q.items(): if sub_q is None: ret[k] = queryKey(k, dct, prefix) else: ret[k] = query(sub_q, queryKey(k, dct, prefix), [*prefix, k]) return ret else: raise TypeError def setKey(q, value, dct, prefix=None): if prefix is None: prefix = [] keys = q.split('.', maxsplit=1) if len(keys) == 1: if keys[0] in dct and isinstance(dct[keys[0]], dict) and not isinstance(value, dict): k = '.'.join([*prefix, keys[0]]) raise ValueError(f'try to set a dict {k} to {type(value)}') else: dct[keys[0]] = value else: if keys[0] in dct and isinstance(dct[keys[0]], dict): sub = dct[keys[0]] elif keys[0] in dct and not isinstance(dct[keys[0]], dict): k = '.'.join([*prefix, keys[0]]) raise ValueError(f'try to set a dict {k} to {type(value)}') else: sub = {} dct[keys[0]] = sub setKey(keys[1], sub, [*prefix, keys[0]]) class ConfigSection(dict): def __init__(self, cfg: BaseConfig, key: str): self._cfg_ = cfg self._key_ = key def __setitem__(self, key: str, value: Any) -> None: if self._cfg_ is None: self._modified_ = True else: self._cfg_._modified_ = True if isinstance(value, dict) and not isinstance(value, ConfigSection): key, *traits = key.split(':') if self._cfg_ is None: cfg = self k = key else: cfg = self._cfg_ k = '.'.join([self._key_, key]) d = ConfigSection(cfg, k) d.update(value) value = d elif isinstance(value, ConfigSection): value.__class__ = ConfigSection super().__setitem__(key, value) def __getitem__(self, key: str) -> ValueType: key, *traits = key.split(':') if self._cfg_ is not None: d = self._cfg_.query(self._key_) if self is not d: self.update(d) ret = super().__getitem__(key) if isinstance(ret, ConfigSection) and len(traits) > 0: traits = [ TraitMeta._traits[n] for n in traits if n in TraitMeta._traits ] mixin(ret, *traits) return ret def __delitem__(self, key: str) -> None: if self._cfg_ is None: self._modified_ = True else: self._cfg_._modified_ = True return super().__delitem__(key) def __delattr__(self, name: str) -> None: if name in self: return self.__delitem__(name) else: return super().__delattr__(name) def __getattr__(self, name: str) -> Any: try: return self.__getattribute__(name) except: try: return self.__getitem__(name) except: raise AttributeError(f'Not Find Attr: {name}') def __setattr__(self, name: str, value: Any) -> None: if name in self: self.__setitem__(name, value) else: super().__setattr__(name, value) def __deepcopy__(self, memo): dct = {k: copy.deepcopy(v) for k, v in self.items()} return dct def query(self, q: Union[str, set, tuple, list, dict]) -> Union[dict, ValueType]: if self._key_ is None: prefix = [] else: prefix = self._key_.split('.') return query(q, self, prefix=prefix) def set(self, q, value): if self._key_ is None: prefix = [] else: prefix = self._key_.split('.') setKey(q, value, self, prefix=prefix) def update(self, other): _update(self, other) ValueType = Union[str, int, float, list, ConfigSection] class BaseConfig(ConfigSection): def __init__(self, path: Optional[Union[str, Path]] = None, backup: bool = False): super().__init__(None, None) if isinstance(path, str): path = Path(path) self._path_ = path self._backup_ = backup self._modified_ = False if self._path_ is None: return if self._path_.exists(): self.reload() if '__version__' not in self: self['__version__'] = 1 else: self._path_.parent.mkdir(parents=True, exist_ok=True) self['__version__'] = 1 self._modified_ = True self.commit() def commit(self): if not self._modified_ or self._path_ is None: return if self._backup_ and self._path_.exists(): v = self['__version__'] bk = self._path_.with_stem(self._path_.stem + f"_{v}") self._path_.rename(bk) with self._path_.open('w') as f: self['__version__'] = self['__version__'] + 1 json.dump(self, f, indent=4) self._modified_ = False def rollback(self): if not self._modified_ or self._path_ is None: return self.reload() def reload(self): with self._path_.open('r') as f: dct = json.load(f) self.clear() self.update(dct) self._modified_ = False @classmethod def fromdict(cls, d: dict) -> BaseConfig: ret = cls() ret.update(d) return ret
python
17
0.510334
79
28.137546
269
starcoderdata
import GameObject from './GameObject.js'; import * as Helper from './helper.js'; //Food definition //This class represents Food objects in the game. It inherits GameObject export default class Food extends GameObject { constructor(x,y) { super(x, y, true, document.getElementById('apple')); this.color = 'red'; } //Specific update method for all instances of Food class. If destroyed, // food disappears and appears on different spot update() { if (this.isDestroyed) { this.position.X = Helper.getRandomPositionX(0, Helper.FieldSize.WIDTH - this.size.WIDTH); this.position.Y = Helper.getRandomPositionY(0, Helper.FieldSize.HEIGHT - this.size.HEIGHT); this.isDestroyed = false; } } }
javascript
15
0.663239
103
34.409091
22
starcoderdata
import os import pytest from astropy.tests.helper import remote_data import numpy as np from hendrics.base import deorbit_events from stingray.events import EventList from hendrics.tests import _dummy_par from hendrics.fold import HAS_PINT def test_deorbit_badpar(): ev = np.asarray(1) with pytest.warns(UserWarning) as record: ev_deor = deorbit_events(ev, None) assert np.any( ["No parameter file specified" in r.message.args[0] for r in record] ) assert ev_deor == ev def test_deorbit_non_existing_par(): ev = np.asarray(1) with pytest.raises(FileNotFoundError) as excinfo: ev_deor = deorbit_events(ev, "warjladsfjqpeifjsdk.par") assert "Parameter file warjladsfjqpeifjsdk.par does not exist" in str( excinfo.value ) @remote_data @pytest.mark.skipif("not HAS_PINT") def test_deorbit_bad_mjdref(): from hendrics.base import deorbit_events ev = EventList(np.arange(100), gti=np.asarray([[0, 2]])) ev.mjdref = 2 par = _dummy_par("bububu.par") with pytest.raises(ValueError) as excinfo: _ = deorbit_events(ev, par) assert "MJDREF is very low (<01-01-1950), " in str(excinfo.value) os.remove("bububu.par") @remote_data @pytest.mark.skipif("not HAS_PINT") def test_deorbit_inverse(): from hendrics.base import deorbit_events ev = EventList( np.sort(np.random.uniform(0, 1000, 10)), gti=np.asarray([[0, 1000]]), mjdref=55000, ) par = _dummy_par("bububu.par", pb=1.0, a1=30) ev2 = deorbit_events(ev, par) ev3 = deorbit_events(ev, par, invert=True) assert np.allclose(ev.time - ev2.time, -(ev.time - ev3.time), atol=1e-6) os.remove("bububu.par") @remote_data @pytest.mark.skipif("not HAS_PINT") def test_deorbit_run(): from hendrics.base import deorbit_events ev = EventList(np.arange(0, 210000, 1000), gti=np.asarray([[0.0, 210000]])) ev.mjdref = 56000.0 ev.ephem = "de200" par = _dummy_par("bububu.par") _ = deorbit_events(ev, par) os.remove("bububu.par")
python
13
0.66587
79
27.27027
74
starcoderdata
import urllib import sys class Controller(object): def write_from_file(self, handler, code, path): handler.send_response(code) handler.send_headers('') f = open(path, 'r') handler.send_body(f) f.close() class CssController(Controller): def index(self, handler): self.main(handler) def main(self, handler): self.write_from_file(handler, 200, 'templates/css/moxy.css') class ConfigController(Controller): def index(self, handler): self.main(handler) def main(self, handler): self.write_from_file(handler, 200, 'templates/config.html') def show(self, handler): self.write_from_file(handler, 200, handler.config.FILE_PATH) def showMeTheFile(self, handler): self.show(handler) def refresh(self, handler): try: handler.config.load() self.write_from_file(handler, 200, 'templates/config_success.html') except: print sys.exc_info()[0] self.write_from_file(handler, 200, 'templates/config_error.html') def conditions(self, handler): cond_table = handler.config.cond_table conditions = handler.config.conditions if handler.postvars and 'id' in handler.postvars: cond = urllib.unquote(handler.postvars['id'][0]) if not cond in cond_table: handler.send_response(400) return cond_table[cond] = not cond_table[cond] handler.send_response(200) handler.send_headers('') f = open('templates/conditions.html', 'r') html = f.read() f.close() html_body = '' for c in conditions: safe_c = urllib.quote(c) html_body += """ <a href='#' onclick=\"setItem('%s');\">%s %s """ % (safe_c, safe_c, cond_table[c] and 'True' or 'False') handler.wfile.write(html.replace('$rows', html_body, 1))
python
14
0.667049
70
23.885714
70
starcoderdata
<?php declare(strict_types=1); $finder = PhpCsFixer\Finder::create() ->in(['src', 'tests']); $config = new PhpCsFixer\Config(); return $config ->setRules([ '@PSR2' => true, 'no_empty_phpdoc' => true, 'single_blank_line_before_namespace' => true, 'array_syntax' => ['syntax' => 'short'], 'ordered_imports' => ['sortAlgorithm' => 'length'], 'no_spaces_after_function_name' => true, 'no_whitespace_in_blank_line' => true, 'no_whitespace_before_comma_in_array' => true, 'no_useless_return' => true, 'no_useless_else' => true, 'no_unused_imports' => true, 'standardize_not_equals' => true, 'declare_strict_types' => true, 'is_null' => true, 'yoda_style' => false, 'no_empty_statement' => true, 'void_return' => true, 'list_syntax' => ['syntax' => 'short'], 'class_attributes_separation' => [ 'elements' => [ 'const', 'method', 'property', ] ], 'blank_line_before_statement' => [ 'statements' => [ 'return', ] ], ]) ->setRiskyAllowed(true) ->setFinder($finder);
php
14
0.485782
59
29.878049
41
starcoderdata
class MemoryDirectory : public Directory { // Use a vector instead of a map to save code size. struct ChildEntry { std::string name; std::shared_ptr<File> child; }; std::vector<ChildEntry> entries; std::vector<ChildEntry>::iterator findEntry(const std::string& name); std::shared_ptr<File> getChild(const std::string& name) override; bool removeChild(const std::string& name) override; std::shared_ptr<File> insertChild(const std::string& name, std::shared_ptr<File> file) override; std::string getName(std::shared_ptr<File> file) override; size_t getNumEntries() override { return entries.size(); } std::vector<Directory::Entry> getEntries() override; public: MemoryDirectory(mode_t mode, backend_t backend) : Directory(mode, backend) {} }
c
10
0.688424
79
35.954545
22
inline
func (d *workloadDeployer) pushEnvFilesToS3Bucket(in *pushEnvFilesToS3BucketInput) (string, error) { path := envFile(d.mft) if path == "" { return "", nil } content, err := in.fs.ReadFile(filepath.Join(d.workspacePath, path)) if err != nil { return "", fmt.Errorf("read env file %s: %w", path, err) } reader := bytes.NewReader(content) url, err := in.uploader.Upload(d.s3Bucket, s3.MkdirSHA256(path, content), reader) if err != nil { return "", fmt.Errorf("put env file %s artifact to bucket %s: %w", path, d.s3Bucket, err) } bucket, key, err := s3.ParseURL(url) if err != nil { return "", fmt.Errorf("parse s3 url: %w", err) } // The app and environment are always within the same partition. partition, err := partitions.Region(d.env.Region).Partition() if err != nil { return "", err } envFileARN := s3.FormatARN(partition.ID(), fmt.Sprintf("%s/%s", bucket, key)) return envFileARN, nil }
go
11
0.667029
100
34.384615
26
inline
def __init__(self, data, feature_data=None, thresh=EXPRESSION_THRESH, feature_rename_col=None, feature_ignore_subset_cols=None, outliers=None, log_base=None, pooled=None, plus_one=False, minimum_samples=0, technical_outliers=None, predictor_config_manager=None): """Object for holding and operating on expression data """ sys.stdout.write("{}\tInitializing expression\n".format(timestamp())) super(ExpressionData, self).__init__( data, feature_data=feature_data, feature_rename_col=feature_rename_col, feature_ignore_subset_cols=feature_ignore_subset_cols, thresh=thresh, outliers=outliers, pooled=pooled, minimum_samples=minimum_samples, predictor_config_manager=predictor_config_manager, technical_outliers=technical_outliers, data_type='expression') self.thresh_original = thresh self.plus_one = plus_one if plus_one: self.data += 1 self.thresh = self.thresh_original + 1 # self.original_data = self.data # import pdb; pdb.set_trace() # self.data = self._threshold(data, thresh) self.log_base = log_base if self.log_base is not None: self.thresh = np.divide(np.log(self.thresh), np.log(self.log_base)) # data = np.self.data_original if not self.singles.empty: self.data = self._threshold(self.data, self.singles) else: self.data = self._threshold(self.data) self.data = np.divide(np.log(self.data), np.log(self.log_base)) self.feature_data = feature_data sys.stdout.write("{}\tDone initializing expression\n".format( timestamp()))
python
13
0.592212
79
41.045455
44
inline
package com.Ultra_Nerd.CodeLyokoLegacy.items.tools; import com.Ultra_Nerd.CodeLyokoLegacy.Entity.EntityLaser; import com.Ultra_Nerd.CodeLyokoLegacy.init.ModItems; import com.Ultra_Nerd.CodeLyokoLegacy.init.ModSounds; import net.minecraft.entity.EquipmentSlot; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.BowItem; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.sound.SoundCategory; import net.minecraft.stat.Stat; import net.minecraft.stat.Stats; import net.minecraft.util.Arm; import net.minecraft.util.Hand; import net.minecraft.util.TypedActionResult; import net.minecraft.util.UseAction; import net.minecraft.world.World; import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; import java.util.Random; import java.util.function.Predicate; public final class ForceFieldEmitter extends BowItem{ public ForceFieldEmitter(final Settings settings) { super(settings); } @Override public int getMaxUseTime(final ItemStack stack) { return 72000; } @Override public Predicate getProjectiles() { return (itemStack) -> itemStack.equals(ItemStack.EMPTY); } @Override public Predicate getHeldProjectiles() { return itemStack -> itemStack.equals(ItemStack.EMPTY); } @Override public void usageTick(final World world, final LivingEntity user, final ItemStack stack, final int remainingUseTicks) { super.usageTick(world, user, stack, remainingUseTicks); publicUseTicks = remainingUseTicks; } public int publicUseTicks = 0; @Override public void onStoppedUsing(final ItemStack stack, final World world, final LivingEntity user, final int remainingUseTicks) { if (user instanceof PlayerEntity playerentity) { final int i = this.getMaxUseTime(stack) - remainingUseTicks; //i = (stack, worldIn, playerentity, i, true); publicUseTicks = getMaxUseTime(stack) - 1; final float f = getPullProgress(i); if (!((double) f < 0.1D)) { if (!world.isClient()) { final EntityLaser las = new EntityLaser(world,user,20); las.setDamage(40); las.setPos(playerentity.getBlockPos().getX(), playerentity.getEyeY(), playerentity.getBlockPos().getZ()); las.setNoGravity(true); las.shake = 0; las.setVelocity(playerentity,playerentity.getPitch() ,playerentity.getYaw(), 0.0F, f * 3.0F, 0.1F); if (f == 1.0F) { las.setCritical(true); } world.spawnEntity(las); } world.playSound( playerentity, playerentity.getBlockPos(), ModSounds.LASERARROW, SoundCategory.PLAYERS, 1.0F, 1.0F / (new Random().nextFloat() * 0.4F + 1.2F) + f * 0.5F); playerentity.incrementStat(Stats.USED.getOrCreateStat(this)); } } } @Override public UseAction getUseAction(final ItemStack stack) { return UseAction.BOW; } @Override public TypedActionResult use(final World world, final PlayerEntity user, final Hand hand) { final ItemStack heldItem = user.getStackInHand(hand); if (user.getInventory().armor.get(EquipmentSlot.CHEST.getEntitySlotId()).getItem() != ModItems.AELITA_CHESTPLATE && user.getInventory().armor.get(EquipmentSlot.LEGS.getEntitySlotId()).getItem() != ModItems.AELITA_LEGGINGS && user.getInventory().armor.get(EquipmentSlot.FEET.getEntitySlotId()).getItem() != ModItems.AELITA_BOOTS) { return TypedActionResult.fail(heldItem); } else { user.setCurrentHand(hand); return TypedActionResult.consume(heldItem); } //boolean flag = !playerIn.findAmmo(itemstack).isEmpty(); //TypedActionResult ret = EventFactory.createArrayBacked(heldItem, world, user, hand, true); //if (ret != null) { // return ret; //} } }
java
18
0.658
186
33.427419
124
starcoderdata
var dots = null; var mousePositions = []; function initializeDots() { dots = []; for (var i = 0; i < 5; i++) { var dot = document.createElement("div") dot.className = "trail"; dot.style.left = (event.pageX - 4) + "px"; dot.style.top = (event.pageY - 4) + "px"; dots.push(dot); } dots.forEach(function(dot) { document.body.appendChild(dot); }); } function updateDots() { dots.forEach(function(dot, i) { if (mousePositions[i]) { dot.style.left = mousePositions[i][0]; dot.style.top = mousePositions[i][1]; } }); } addEventListener("mousemove", function(event) { if (dots == null) initializeDots(); mousePositions.push([(event.pageX - 4) + "px", (event.pageY - 4) + "px"]); if (mousePositions.length > 5) mousePositions = mousePositions.slice(mousePositions.length - 5); updateDots(); });
javascript
14
0.608092
76
23.027778
36
starcoderdata
namespace Windows.UI.Xaml.Controls { /// /// Defines constants that specify the different orientations that a control or layout can have. /// public enum Orientation { /// /// The control or layout should be vertically oriented. /// Vertical, /// /// The control or layout should be horizontally oriented. /// Horizontal, } }
c#
6
0.678832
97
23.176471
17
starcoderdata
/* * Copyright (C) 2017 B3Partners B.V. * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the “Software”), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of * the Software. * * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ package nl.b3p.jdbc.util.converter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.Point; import org.locationtech.jts.io.ParseException; import org.locationtech.jts.io.WKTReader; import java.math.BigDecimal; import java.sql.SQLException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeParseException; import java.util.Date; /** * * @author * @author * @author mprins */ public abstract class GeometryJdbcConverter { private static final Log LOG = LogFactory.getLog(GeometryJdbcConverter.class); static public Object convertToSQLObject(String stringValue, ColumnMetadata cm, String tableName, String column) { Object param; stringValue = stringValue.trim(); switch (cm.getDataType()) { case java.sql.Types.DECIMAL: case java.sql.Types.NUMERIC: case java.sql.Types.INTEGER: try { param = new BigDecimal(stringValue); } catch (NumberFormatException nfe) { throw new NumberFormatException( String.format("Conversie van waarde \"%s\" naar type %s voor %s.%s niet mogelijk", stringValue, cm.getTypeName(), tableName, cm.getName())); } break; case java.sql.Types.CHAR: case java.sql.Types.VARCHAR: case java.sql.Types.NVARCHAR: case java.sql.Types.LONGNVARCHAR: case java.sql.Types.LONGVARCHAR: param = stringValue; break; case java.sql.Types.DATE: case java.sql.Types.TIMESTAMP: try { param = LocalDateTime.parse(stringValue); } catch (DateTimeParseException e) { LOG.debug( "Parsen van waarde " + stringValue + " als LocalDateTime is mislukt, probeer als " + "LocalDate."); try { param = LocalDate.parse(stringValue).atTime(0, 0); } catch (DateTimeParseException e2) { LOG.error("Fout tijdens parsen van waarde " + stringValue + " als LocalDate", e2); param = null; } } if (param != null) { param = new java.sql.Date( Date.from(((LocalDateTime) param).atZone(ZoneId.systemDefault()).toInstant()).getTime() ); } break; default: throw new UnsupportedOperationException( String.format("Data type %s (#%d) van kolom \"%s\" wordt niet ondersteund.", cm.getTypeName(), cm.getDataType(), cm.getName()) ); } return param; } protected GeometryFactory gf = new GeometryFactory(); protected final WKTReader wkt = new WKTReader(); //definieer placeholder als ? wanneer object naar native geometry wordt //geconverteerd //defineer placeholder via native wkt-import functie als geometry als //wkt-string wordt doorgegeven public abstract Object convertToNativeGeometryObject(Geometry param) throws SQLException, ParseException; public abstract Object convertToNativeGeometryObject(Geometry param, int srid) throws SQLException, ParseException; public abstract Geometry convertToJTSGeometryObject(Object nativeObj); public abstract String createPSGeometryPlaceholder() throws SQLException; public abstract String getSchema(); public abstract String getGeomTypeName(); public abstract boolean isDuplicateKeyViolationMessage(String message); /** * bepaal of een melding een constraint violation betreft. * * @param message de melding uit de database * @return {@code true} als de melding een contraint violation betreft */ public abstract boolean isFKConstraintViolationMessage(String message); public abstract String buildPaginationSql(String sql, int offset, int limit); public abstract StringBuilder buildLimitSql(StringBuilder sql, int limit); public abstract boolean useSavepoints(); public abstract boolean isPmdKnownBroken(); public abstract String getMViewsSQL(); public abstract String getMViewRefreshSQL(String mview); /** * Gets a statement to use in a {@link java.sql.PreparedStatement } to restart a sequence. * * @param seqName name of sequence * @param nextVal the value to restart the sequence, some systems * require this to be larger than the next value of the sequence. * @return SQL statement specific for the flavour of database */ public String getUpdateSequenceSQL(String seqName, long nextVal) { // supported for postgres, ms sql, hsqldb, NB return values vary // https://www.postgresql.org/docs/11/sql-altersequence.html // https://docs.microsoft.com/en-us/sql/t-sql/statements/alter-sequence-transact-sql?view=sql-server-ver15 return String.format("ALTER SEQUENCE %s RESTART WITH %d", seqName , nextVal); } /** * get the database flavour specific SQL statement to get the next value from a sequence. * * @param seqName name of sequence * @return SQL statement specific for the flavour of database */ public abstract String getSelectNextValueFromSequenceSQL(String seqName); public abstract String getGeotoolsDBTypeName(); public Object convertToNativeGeometryObject(String param) throws ParseException, SQLException { Geometry o = null; if (param != null && param.trim().length() > 0) { o = wkt.read(param); } return convertToNativeGeometryObject(o); } public Object createNativePoint(double lat, double lon, int srid) throws SQLException, ParseException { if (lat == 0 || lon == 0) { return null; } Point p = gf.createPoint(new Coordinate(lon, lat)); return convertToNativeGeometryObject(p, srid); } }
java
22
0.64309
119
40.497297
185
starcoderdata
import React, { Component, PropTypes } from 'react'; import shallowCompare from 'react-addons-shallow-compare'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { aboutActions } from '../../../actions'; import CoverImg from '../../../components/coverImg/index'; import InstaSection from '../../../components/AboutInstaSection/index'; import TweeterSection from '../../../components/AboutTweeterSection/index'; import PosterImg from '../../../common/coverVideo/cover.jpg'; import messages from './messages'; class AboutMe extends Component { constructor(props) { super(props); this.state = { instaImages: props.instaImages, tweets: props.tweets }; } componentWillMount() { this .props .actions .loadInstaImages(); this .props .actions .loadTweets(); } componentWillReceiveProps(nextProps) { this.setState({ instaImages: nextProps.instaImages, tweets: nextProps.tweets }); } shouldComponentUpdate(nextProps, nextState) { return shallowCompare(this, nextProps, nextState); } render() { return ( <CoverImg PosterImg={PosterImg} headerText={messages.headerText} subHeaderText={messages.subHeaderText} /> < InstaSection instaImages={this.state.instaImages} /> <TweeterSection tweets={this.state.tweets} /> ); } } AboutMe.propTypes = { pathname: PropTypes.string.isRequired, instaImages: PropTypes.array.isRequired, tweets: PropTypes.array.isRequired, actions: PropTypes.object.isRequired }; const mapStateToProps = (state, ownProps) => ({ pathname: ownProps.location.pathname, instaImages: state.instaImages, tweets: state.tweets }); const mapDispatchToProps = (dispatch) => ({ actions: bindActionCreators(aboutActions, dispatch) }); export default connect(mapStateToProps, mapDispatchToProps)(AboutMe);
javascript
13
0.685861
142
29.390625
64
starcoderdata
/** * Created by schwarzkopfb on 15/9/12. */ var http = require('http'), router = require('./router').prototype, app = module.exports app.prototype = app.__proto__ = router Object.defineProperties(app, { listen: { enumerable: true, value: function listen() { var server = http.createServer(this.handle.bind(this)) return server.listen.apply(server, arguments) } } })
javascript
17
0.590498
66
21.1
20
starcoderdata
package sorts import ( "testing" ) func TestSimpleSelectionSort(t *testing.T) { s := []int{5, 4, 3, 2, 1} SimpleSelectionSort(s) ln(s) s = []int{1, 2, 3, 4, 5} SimpleSelectionSort(s) ln(s) s = []int{4, 5, 3, 2, 1} SimpleSelectionSort(s) ln(s) s = []int{3, 5, 1, 4, 2} SimpleSelectionSort(s) ln(s) s = []int{5, 1} SimpleSelectionSort(s) ln(s) s = []int{5} SimpleSelectionSort(s) ln(s) s = []int{} SimpleSelectionSort(s) ln(s) } func BenchmarkSimpleSelectionSort(b *testing.B) { c := 100 for i := 0; i < b.N; i++ { s := make([]int, c) for i, j := c, 0; i > 0; i-- { s[j] = i j++ } SimpleSelectionSort(s) } }
go
10
0.56231
49
12.708333
48
starcoderdata
import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns sns.set() def show_histograms(Y, X, title=''): ax = sns.distplot(X[Y==-1], hist=False, kde_kws = {'shade': True, 'linewidth': 2}, label='$Y=-1$') sns.distplot(X[Y==1], hist=False, kde_kws = {'shade': True, 'linewidth': 2}, label='$Y=+1$') ax.set_xlabel("$X_2$") ax.set_ylabel("density") ax.set_title(title) ax.legend() plt.show() return ax n_samples = 10000 scm_class = 'fair-IMF-LIN' # scm_class = 'fair-CAU-LIN' # scm_class = 'fair-CAU-ANM' # classifier_type = 'linear' classifier_type = 'radial' U_A = np.random.uniform(0, 1, n_samples) A = 2 * (U_A > 0.5) - 1 # needs to be +1 or -1 U_X_1 = np.random.normal(0, 1, n_samples) X_1 = 0.5 * A + U_X_1 U_X_2 = np.random.normal(0, 1, n_samples) X_2 = 0 + U_X_2 U_X_3 = np.random.normal(0, 1, n_samples) if scm_class == 'fair-IMF-LIN': X_3 = 0.5 * A + U_X_3 elif scm_class == 'fair-CAU-LIN': X_3 = 0.5 * (A + X_1 - X_2) + U_X_3 elif scm_class == 'fair-CAU-ANM': X_3 = 0.5 * A + 0.1 * (X_1**3 - X_2**3) + U_X_3 else: print('SCM type not recognised') if classifier_type == 'linear': h = (1 + np.exp(-2*(X_1 + X_2 - X_3))) ** (-1) elif classifier_type == 'radial': h = (1 + np.exp(4-(X_1 + 2 * X_2 + X_3)**2)) ** (-1) else: print('Classifier type not recognised') noise = np.random.uniform(0, 1, n_samples) Y = 2 * (noise < h) - 1 # needs to be +1 or -1 print('SCM:', scm_class) print('Classifier:', classifier_type) print("The following 4 numbers should be roughly equal for a balanced dataset") print("Class +1:", sum((Y == 1))) print("Class -1:", sum((Y == -1))) print("Attribute +1:", sum((A == 1))) print("Attribute -1:", sum((A == -1))) title_string = scm_class+' with '+classifier_type+' classifier ' label_dist_x2 = show_histograms(Y, X_2, title_string) fig = label_dist_x2.get_figure() fig.savefig(title_string+'.pdf') # synth_data = np.stack([Y, A, X_1, X_2, X_3], axis=1) # synth_data_frame = pd.DataFrame(synth_data) # sns.pairplot(synth_data_frame) # # fig = plt.figure() # ax = fig.add_subplot(111, projection='3d') # ax.set_xlabel("X_1") # ax.set_ylabel("X_2") # ax.set_zlabel("X_3") # ax.scatter(X_1[(Y == 1) & (A == 1)], X_2[(Y == 1) & (A == 1)], X_3[(Y == 1) & (A == 1)], color='green', marker='o') # ax.scatter(X_1[(Y == -1) & (A == 1)], X_2[(Y == -1) & (A == 1)], X_3[(Y == -1) & (A == 1)], color='red', marker='o') # ax.scatter(X_1[(Y == 1) & (A == -1)], X_2[(Y == 1) & (A == -1)], X_3[(Y == 1) & (A == -1)], color='blue', marker='x') # ax.scatter(X_1[(Y == -1) & (A == -1)], X_2[(Y == -1) & (A == -1)], X_3[(Y == -1) & (A == -1)], color='orange', marker='x') # plt.show()
python
17
0.552272
124
32.012195
82
starcoderdata
from django.urls import path, re_path from publicApi import views urlpatterns = [ <<<<<<< HEAD re_path('contacts',views.getContacts), ======= re_path(r'create',views.createQueue), #根据表单数据创建生产者队列 #re_path(r'^re$',views.index2), >>>>>>> 114e55319ca78933fd9c53c3e31ef4c67a9f0c2b ]
python
8
0.691803
56
24.5
12
starcoderdata
// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/ads/googleads/v3/errors/campaign_feed_error.proto package errors import ( fmt "fmt" math "math" proto "github.com/catper/protobuf/proto" _ "google.golang.org/genproto/googleapis/api/annotations" ) // 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.ProtoPackageIsVersion3 // please upgrade the proto package // Enum describing possible campaign feed errors. type CampaignFeedErrorEnum_CampaignFeedError int32 const ( // Enum unspecified. CampaignFeedErrorEnum_UNSPECIFIED CampaignFeedErrorEnum_CampaignFeedError = 0 // The received error code is not known in this version. CampaignFeedErrorEnum_UNKNOWN CampaignFeedErrorEnum_CampaignFeedError = 1 // An active feed already exists for this campaign and placeholder type. CampaignFeedErrorEnum_FEED_ALREADY_EXISTS_FOR_PLACEHOLDER_TYPE CampaignFeedErrorEnum_CampaignFeedError = 2 // The specified feed is removed. CampaignFeedErrorEnum_CANNOT_CREATE_FOR_REMOVED_FEED CampaignFeedErrorEnum_CampaignFeedError = 4 // The CampaignFeed already exists. UPDATE should be used to modify the // existing CampaignFeed. CampaignFeedErrorEnum_CANNOT_CREATE_ALREADY_EXISTING_CAMPAIGN_FEED CampaignFeedErrorEnum_CampaignFeedError = 5 // Cannot update removed campaign feed. CampaignFeedErrorEnum_CANNOT_MODIFY_REMOVED_CAMPAIGN_FEED CampaignFeedErrorEnum_CampaignFeedError = 6 // Invalid placeholder type. CampaignFeedErrorEnum_INVALID_PLACEHOLDER_TYPE CampaignFeedErrorEnum_CampaignFeedError = 7 // Feed mapping for this placeholder type does not exist. CampaignFeedErrorEnum_MISSING_FEEDMAPPING_FOR_PLACEHOLDER_TYPE CampaignFeedErrorEnum_CampaignFeedError = 8 // Location CampaignFeeds cannot be created unless there is a location // CustomerFeed for the specified feed. CampaignFeedErrorEnum_NO_EXISTING_LOCATION_CUSTOMER_FEED CampaignFeedErrorEnum_CampaignFeedError = 9 ) var CampaignFeedErrorEnum_CampaignFeedError_name = map[int32]string{ 0: "UNSPECIFIED", 1: "UNKNOWN", 2: "FEED_ALREADY_EXISTS_FOR_PLACEHOLDER_TYPE", 4: "CANNOT_CREATE_FOR_REMOVED_FEED", 5: "CANNOT_CREATE_ALREADY_EXISTING_CAMPAIGN_FEED", 6: "CANNOT_MODIFY_REMOVED_CAMPAIGN_FEED", 7: "INVALID_PLACEHOLDER_TYPE", 8: "MISSING_FEEDMAPPING_FOR_PLACEHOLDER_TYPE", 9: "NO_EXISTING_LOCATION_CUSTOMER_FEED", } var CampaignFeedErrorEnum_CampaignFeedError_value = map[string]int32{ "UNSPECIFIED": 0, "UNKNOWN": 1, "FEED_ALREADY_EXISTS_FOR_PLACEHOLDER_TYPE": 2, "CANNOT_CREATE_FOR_REMOVED_FEED": 4, "CANNOT_CREATE_ALREADY_EXISTING_CAMPAIGN_FEED": 5, "CANNOT_MODIFY_REMOVED_CAMPAIGN_FEED": 6, "INVALID_PLACEHOLDER_TYPE": 7, "MISSING_FEEDMAPPING_FOR_PLACEHOLDER_TYPE": 8, "NO_EXISTING_LOCATION_CUSTOMER_FEED": 9, } func (x CampaignFeedErrorEnum_CampaignFeedError) String() string { return proto.EnumName(CampaignFeedErrorEnum_CampaignFeedError_name, int32(x)) } func (CampaignFeedErrorEnum_CampaignFeedError) EnumDescriptor() ([]byte, []int) { return fileDescriptor_a4307471cace193a, []int{0, 0} } // Container for enum describing possible campaign feed errors. type CampaignFeedErrorEnum struct { XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *CampaignFeedErrorEnum) Reset() { *m = CampaignFeedErrorEnum{} } func (m *CampaignFeedErrorEnum) String() string { return proto.CompactTextString(m) } func (*CampaignFeedErrorEnum) ProtoMessage() {} func (*CampaignFeedErrorEnum) Descriptor() ([]byte, []int) { return fileDescriptor_a4307471cace193a, []int{0} } func (m *CampaignFeedErrorEnum) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_CampaignFeedErrorEnum.Unmarshal(m, b) } func (m *CampaignFeedErrorEnum) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_CampaignFeedErrorEnum.Marshal(b, m, deterministic) } func (m *CampaignFeedErrorEnum) XXX_Merge(src proto.Message) { xxx_messageInfo_CampaignFeedErrorEnum.Merge(m, src) } func (m *CampaignFeedErrorEnum) XXX_Size() int { return xxx_messageInfo_CampaignFeedErrorEnum.Size(m) } func (m *CampaignFeedErrorEnum) XXX_DiscardUnknown() { xxx_messageInfo_CampaignFeedErrorEnum.DiscardUnknown(m) } var xxx_messageInfo_CampaignFeedErrorEnum proto.InternalMessageInfo func init() { proto.RegisterEnum("google.ads.googleads.v3.errors.CampaignFeedErrorEnum_CampaignFeedError", CampaignFeedErrorEnum_CampaignFeedError_name, CampaignFeedErrorEnum_CampaignFeedError_value) proto.RegisterType((*CampaignFeedErrorEnum)(nil), "google.ads.googleads.v3.errors.CampaignFeedErrorEnum") } func init() { proto.RegisterFile("google/ads/googleads/v3/errors/campaign_feed_error.proto", fileDescriptor_a4307471cace193a) } var fileDescriptor_a4307471cace193a = []byte{ // 445 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x92, 0x41, 0x8e, 0xd3, 0x30, 0x14, 0x86, 0x69, 0x80, 0x19, 0xf0, 0x2c, 0x28, 0x96, 0x40, 0x08, 0x8d, 0xba, 0x08, 0x12, 0xb0, 0x18, 0x39, 0x48, 0xd9, 0xa0, 0xb0, 0xf2, 0x24, 0x4e, 0xb1, 0x48, 0xec, 0x28, 0x49, 0x03, 0x45, 0x95, 0xac, 0x30, 0x09, 0x51, 0xa5, 0x69, 0x5c, 0xc5, 0xa5, 0x07, 0x62, 0xc9, 0x51, 0x58, 0x72, 0x0c, 0xc4, 0x86, 0x1b, 0x20, 0xc7, 0x6d, 0x50, 0x55, 0x98, 0x55, 0x7e, 0x39, 0xdf, 0xff, 0xbf, 0x67, 0xbf, 0x07, 0x5e, 0x37, 0x52, 0x36, 0xd7, 0xb5, 0x53, 0x56, 0xca, 0x31, 0x52, 0xab, 0xad, 0xeb, 0xd4, 0x5d, 0x27, 0x3b, 0xe5, 0x5c, 0x95, 0xab, 0x75, 0xb9, 0x6c, 0x5a, 0xf1, 0xb9, 0xae, 0x2b, 0xd1, 0x1f, 0xa2, 0x75, 0x27, 0x37, 0x12, 0x4e, 0x0c, 0x8e, 0xca, 0x4a, 0xa1, 0xc1, 0x89, 0xb6, 0x2e, 0x32, 0xce, 0xa7, 0xe7, 0xfb, 0xe4, 0xf5, 0xd2, 0x29, 0xdb, 0x56, 0x6e, 0xca, 0xcd, 0x52, 0xb6, 0xca, 0xb8, 0xed, 0x5f, 0x16, 0x78, 0xe4, 0xef, 0xb2, 0xc3, 0xba, 0xae, 0x88, 0x36, 0x91, 0xf6, 0xcb, 0xca, 0xfe, 0x61, 0x81, 0x87, 0x47, 0x7f, 0xe0, 0x03, 0x70, 0x36, 0x63, 0x59, 0x42, 0x7c, 0x1a, 0x52, 0x12, 0x8c, 0x6f, 0xc1, 0x33, 0x70, 0x3a, 0x63, 0xef, 0x18, 0x7f, 0xcf, 0xc6, 0x23, 0x78, 0x01, 0x5e, 0x86, 0x84, 0x04, 0x02, 0x47, 0x29, 0xc1, 0xc1, 0x5c, 0x90, 0x0f, 0x34, 0xcb, 0x33, 0x11, 0xf2, 0x54, 0x24, 0x11, 0xf6, 0xc9, 0x5b, 0x1e, 0x05, 0x24, 0x15, 0xf9, 0x3c, 0x21, 0x63, 0x0b, 0xda, 0x60, 0xe2, 0x63, 0xc6, 0x78, 0x2e, 0xfc, 0x94, 0xe0, 0x9c, 0xf4, 0x5c, 0x4a, 0x62, 0x5e, 0x90, 0x40, 0xe8, 0x9c, 0xf1, 0x1d, 0xf8, 0x0a, 0x5c, 0x1c, 0x32, 0x07, 0xd1, 0x94, 0x4d, 0x85, 0x8f, 0xe3, 0x04, 0xd3, 0x29, 0x33, 0x8e, 0xbb, 0xf0, 0x05, 0x78, 0xb6, 0x73, 0xc4, 0x3c, 0xa0, 0xe1, 0x7c, 0x48, 0x3c, 0x04, 0x4f, 0xe0, 0x39, 0x78, 0x42, 0x59, 0x81, 0x23, 0x1a, 0x1c, 0x37, 0x77, 0xaa, 0xaf, 0x12, 0xd3, 0x2c, 0xd3, 0x15, 0x34, 0x1f, 0xe3, 0x24, 0xe9, 0xf5, 0xbf, 0xae, 0x72, 0x0f, 0x3e, 0x07, 0x36, 0xe3, 0x7f, 0x7b, 0x8a, 0xb8, 0x8f, 0x73, 0xca, 0x99, 0xf0, 0x67, 0x59, 0xce, 0x63, 0x92, 0x9a, 0x9a, 0xf7, 0x2f, 0x7f, 0x8f, 0x80, 0x7d, 0x25, 0x57, 0xe8, 0xe6, 0x99, 0x5d, 0x3e, 0x3e, 0x7a, 0xf8, 0x44, 0x4f, 0x2b, 0x19, 0x7d, 0x0c, 0x76, 0xce, 0x46, 0x5e, 0x97, 0x6d, 0x83, 0x64, 0xd7, 0x38, 0x4d, 0xdd, 0xf6, 0xb3, 0xdc, 0xef, 0xcd, 0x7a, 0xa9, 0xfe, 0xb7, 0x46, 0x6f, 0xcc, 0xe7, 0xab, 0x75, 0x7b, 0x8a, 0xf1, 0x37, 0x6b, 0x32, 0x35, 0x61, 0xb8, 0x52, 0xc8, 0x48, 0xad, 0x0a, 0x17, 0xf5, 0x25, 0xd5, 0xf7, 0x3d, 0xb0, 0xc0, 0x95, 0x5a, 0x0c, 0xc0, 0xa2, 0x70, 0x17, 0x06, 0xf8, 0x69, 0xd9, 0xe6, 0xd4, 0xf3, 0x70, 0xa5, 0x3c, 0x6f, 0x40, 0x3c, 0xaf, 0x70, 0x3d, 0xcf, 0x40, 0x9f, 0x4e, 0xfa, 0xee, 0xdc, 0x3f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x6c, 0x14, 0x3d, 0x9c, 0xe3, 0x02, 0x00, 0x00, }
go
9
0.736941
186
50.258065
155
starcoderdata
/*global define*/ define(function() { "use strict"; function MockProperty(value) { this.value = value; } MockProperty.prototype.getValue = function() { return this.value; }; MockProperty.prototype.getValueCartesian = function() { return this.value; }; MockProperty.prototype.getValueSpherical = function() { return this.value; }; MockProperty.prototype.getValueRangeCartesian = function(start, stop, currentTime, result) { this.lastStart = start; this.lastStop = stop; this.lastCurrentTime = currentTime; return this.value; }; return MockProperty; });
javascript
13
0.630792
96
22.103448
29
starcoderdata
<?php namespace Sirius\Validation\Rule; abstract class AbstractStringRule extends AbstractRule { protected function getStringLength($str) { if (function_exists('mb_strlen')) { return mb_strlen( $str, (isset($this->options['encoding']) && $this->options['encoding']) ? $this->options['encoding'] : mb_internal_encoding() ); } return strlen($str); } }
php
20
0.591337
83
25.55
20
starcoderdata
def test_handle_notify_request_payment_failed(provider_base_config, order): """Test request notify helper returns http 204 and order status is correct when payment fails""" order.order_number = "abc123" order.status = OrderStatus.PAID order.save() refund = OrderRefundFactory( order=order, refund_id="1234567", amount=order.total_price ) params = { "AUTHCODE": "8CF2D0EA9947D09B707E3C2953EF3014F1AD12D2BB0DCDBAC3ABD4601B50462B", "RETURN_CODE": "1", "REFUND_ID": "1234567", } rf = RequestFactory() request = rf.get("/payments/notify_refund/", params) payment_provider = create_bambora_provider(provider_base_config, request) assert refund.status == OrderRefundStatus.PENDING lease_status = refund.order.lease.status returned = payment_provider.handle_notify_refund_request() refund = OrderRefund.objects.get(refund_id=params.get("REFUND_ID")) order = refund.order assert refund.status == OrderRefundStatus.REJECTED # The order status shouldn't change assert order.status == OrderStatus.PAID assert order.lease.status == lease_status assert isinstance(returned, HttpResponse) assert returned.status_code == 204
python
11
0.707692
100
35.352941
34
inline
using Newtonsoft.Json; namespace Compos.Coreforce.Models.Authorization { public class AuthorizationResult { [JsonProperty("access_token")] public string AccessToken { get; set; } [JsonProperty("instance_url")] public string InstanceUrl { get; set; } [JsonProperty("id")] public string Id { get; set; } [JsonProperty("token_type")] public string TokenType { get; set; } [JsonProperty("issued_at")] public string IssuedAt { get; set; } [JsonProperty("signature")] public string Signature { get; set; } } }
c#
11
0.619414
47
29.904762
21
starcoderdata
import pandas as pd import numpy as np from lib.config import * import lib meta = pd.read_csv(data_directory + 'metadata-britanova.txt', sep='\t') mask = meta['age']>0 print(meta[mask].shape[0], meta.shape[0]-meta[mask].shape[0], meta[mask]['age'].min(), meta['age'].max()) Nsample = 5e5 count_dict = {} for file_name in meta['file_name']: print(file_name) counts = pd.read_csv(britanova_rawdata_directory + file_name +'.gz', sep='\t', usecols=(0,))['count'] counts = np.sort(counts) count_dict[file_name] = counts meta['totcount'] = meta.apply(lambda s: count_dict[s['file_name']].sum(), axis=1) meta['singletons'] = meta.apply(lambda s: np.sum(count_dict[s['file_name']]==1), axis=1) meta['largest'] = meta.apply(lambda s: count_dict[s['file_name']][-1], axis=1) meta['10thlargest'] = meta.apply(lambda s: count_dict[s['file_name']][-10], axis=1) meta['100thlargest'] = meta.apply(lambda s: count_dict[s['file_name']][-100], axis=1) meta['1000thlargest'] = meta.apply(lambda s: count_dict[s['file_name']][-1000], axis=1) meta['10000thlargest'] = meta.apply(lambda s: count_dict[s['file_name']][-10000], axis=1) meta['sub_singletons'] = meta.apply(lambda s: np.sum(lib.subsample(count_dict[s['file_name']], Nsample)==1) if s['totcount'] > Nsample else np.nan, axis=1) meta.to_csv(data_directory + '/britanova-counts.csv', index=False)
python
15
0.675847
155
46.2
30
starcoderdata
#include "bits/stdc++.h" using namespace std; int cnt(const vector<int> &A){ int foo=A.size(); vector<int> a=A; sort(a.begin(), a.end()); long long presum=a[0]*1LL; for(size_t i=1; i<a.size(); i++){ if(presum*2LL<a[i]*1LL){ foo=a.size()-i; } presum+=a[i]*1LL; } return foo; } int main(){ int n; while(scanf("%d", &n)!=EOF){ vector<int> a(n, 0); for(int i=0; i<n; i++){ scanf("%d", &a[i]); } printf("%d\n", cnt(a)); } return 0; }
c++
13
0.445848
37
18.821429
28
codenet
Analysis /build_csv.py %matplotlib inline import json import requests import pandas as pd import numpy as np import matplotlib.pyplot as plt pd.set_option('display.width', 500) pd.set_option('display.max_columns', 30) # set some nicer defaults for matplotlib from matplotlib import rcParams #these colors come from colorbrewer2.org. Each is an RGB triplet dark2_colors = [(0.10588235294117647, 0.6196078431372549, 0.4666666666666667), (0.8509803921568627, 0.37254901960784315, 0.00784313725490196), (0.4588235294117647, 0.4392156862745098, 0.7019607843137254), (0.9058823529411765, 0.1607843137254902, 0.5411764705882353), (0.4, 0.6509803921568628, 0.11764705882352941), (0.9019607843137255, 0.6705882352941176, 0.00784313725490196), (0.6509803921568628, 0.4627450980392157, 0.11372549019607843), (0.4, 0.4, 0.4)] rcParams['figure.figsize'] = (10, 6) rcParams['figure.dpi'] = 150 rcParams['axes.color_cycle'] = dark2_colors rcParams['lines.linewidth'] = 2 rcParams['axes.grid'] = False rcParams['axes.facecolor'] = 'white' rcParams['font.size'] = 14 rcParams['patch.edgecolor'] = 'none' def remove_border(axes=None, top=False, right=False, left=True, bottom=True): """ Minimize chartjunk by stripping out unnecesary plot borders and axis ticks The top/right/left/bottom keywords toggle whether the corresponding plot border is drawn """ ax = axes or plt.gca() ax.spines['top'].set_visible(top) ax.spines['right'].set_visible(right) ax.spines['left'].set_visible(left) ax.spines['bottom'].set_visible(bottom) #turn off all ticks ax.yaxis.set_ticks_position('none') ax.xaxis.set_ticks_position('none') #now re-enable visibles if top: ax.xaxis.tick_top() if bottom: ax.xaxis.tick_bottom() if left: ax.yaxis.tick_left() if right: ax.yaxis.tick_right() api_key = 'YOUR KEY HERE' movie_id = '770672122' # toy story 3 url = 'http://api.rottentomatoes.com/api/public/v1.0/movies/%s/reviews.json' % movie_id #these are "get parameters" options = {'review_type': 'top_critic', 'page_limit': 20, 'page': 1, 'apikey': api_key} data = requests.get(url, params=options).text data = json.loads(data) # load a json string into a collection of lists and dicts from io import StringIO movie_txt = requests.get('https://raw.github.com/cs109/cs109_data/master/movies.dat').text movie_file = StringIO(movie_txt) # treat a string like a file movies = pd.read_csv(movie_file, delimiter='\t') def base_url(): return 'http://api.rottentomatoes.com/api/public/v1.0/' def rt_id_by_imdb(imdb): """ Queries the RT movie_alias API. Returns the RT id associated with an IMDB ID, or raises a KeyError if no match was found """ url = base_url() + 'movie_alias.json' imdb = "%7.7i" % imdb params = dict(id=imdb, type='imdb', apikey=api_key) r = requests.get(url, params=params).text r = json.loads(r) return r['id'] def _imdb_review(imdb): """ Query the RT reviews API, to return the first page of reviews for a movie specified by its IMDB ID Returns a list of dicts """ rtid = rt_id_by_imdb(imdb) url = base_url() + 'movies/{0}/reviews.json'.format(rtid) params = dict(review_type='top_critic', page_limit=20, page=1, country='us', apikey=api_key) data = json.loads(requests.get(url, params=params).text) data = data['reviews'] data = [dict(fresh=r['freshness'], quote=r['quote'], critic=r['critic'], publication=r['publication'], review_date=r['date'], imdb=imdb, rtid=rtid ) for r in data] return data def fetch_reviews(movies, row): m = movies.irow(row) try: result = pd.DataFrame(_imdb_review(m['imdbID'])) result['title'] = m['title'] except KeyError: return None return result def build_table(movies, rows): dfs = [fetch_reviews(movies, r) for r in range(rows)] dfs = [d for d in dfs if d is not None] return pd.concat(dfs, ignore_index=True) critics = build_table(movies, 3000) critics.to_csv('critics.csv', index=False) critics = pd.read_csv('critics.csv') #let's drop rows with missing quotes critics = critics[~critics.quote.isnull()] n_reviews = len(critics) n_movies = critics.rtid.unique().size n_critics = critics.critic.unique().size print "Number of reviews: %i" % n_reviews print "Number of critics: %i" % n_critics print "Number of movies: %i" % n_movies
python
13
0.640864
92
29.754839
155
starcoderdata
class Solution: def diagonalSum(self, mat: List[List[int]]) -> int: res = 0 right = len(mat) - 1 for i in range(len(mat)): res += mat[i][i] res += mat[i][right] right -= 1 if len(mat) % 2 == 1: half = int(len(mat)/2) return res - mat[half][half] else: return res
python
14
0.367713
55
21.35
20
starcoderdata
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) class Stepper: # adjust if different def __init__(self, pin1=17, pin2=18, pin3=22, pin4=23): self.StepState = 0; # 8 per full step self.Position = 0; # 400 per revolution self.StepCount = 8 self.Seq = range(0, self.StepCount) self.Seq[0] = [0,1,0,0] self.Seq[1] = [0,1,0,1] self.Seq[2] = [0,0,0,1] self.Seq[3] = [1,0,0,1] self.Seq[4] = [1,0,0,0] self.Seq[5] = [1,0,1,0] self.Seq[6] = [0,0,1,0] self.Seq[7] = [0,1,1,0] self.coil_A_1_pin = pin1 self.coil_A_2_pin = pin2 self.coil_B_1_pin = pin3 self.coil_B_2_pin = pin4 GPIO.setup(self.coil_A_1_pin, GPIO.OUT) GPIO.setup(self.coil_A_2_pin, GPIO.OUT) GPIO.setup(self.coil_B_1_pin, GPIO.OUT) GPIO.setup(self.coil_B_2_pin, GPIO.OUT) #self.setStep(self.Seq[self.StepState][0], self.Seq[self.StepState][1], self.Seq[self.StepState][2], self.Seq[self.StepState][3]) def setStep(self, w1, w2, w3, w4): GPIO.output(self.coil_A_1_pin, w1) GPIO.output(self.coil_A_2_pin, w2) GPIO.output(self.coil_B_1_pin, w3) GPIO.output(self.coil_B_2_pin, w4) def forward(self, delay, steps): for i in range(steps): self.StepState = self.StepState + 1 self.Position = self.Position + 1 if self.StepState == self.StepCount: self.StepState = 0 self.setStep(self.Seq[self.StepState][0], self.Seq[self.StepState][1], self.Seq[self.StepState][2], self.Seq[self.StepState][3]) time.sleep(delay) def backwards(self, delay, steps): for i in range(steps): self.StepState = self.StepState - 1 self.Position = self.Position - 1 if self.StepState < 0: self.StepState = self.StepCount - 1 self.setStep(self.Seq[self.StepState][0], self.Seq[self.StepState][1], self.Seq[self.StepState][2], self.Seq[self.StepState][3]) time.sleep(delay) def setPosition(self, pos): if pos < self.Position: self.backwards(.002, self.Position - pos) elif pos > self.Position: self.forward(.002, pos - self.Position) print "Current Position: ", self.Position if __name__ == '__main__': motor = Stepper(); while True: steps = raw_input("How many steps forward? ") motor.setPosition(int(steps));
python
13
0.555135
140
33.723684
76
starcoderdata
var test = require("test"); require("a"); try { require("A"); test.assert(false, "should fail to require alternate spelling"); } catch (error) { } test.print("DONE", "info");
javascript
7
0.628415
68
21.875
8
starcoderdata
#include #include #include #include #include using namespace urchin; void FileUtilTest::getDirectoryUnix() { std::string filenamePath = "/home/jean/binaryFile"; std::string result = FileUtil::getDirectory(filenamePath); AssertHelper::assertTrue(result == "/home/jean/"); } void FileUtilTest::getDirectoryWindows() { std::string filenamePath = R"(C:\home\jean\binaryFile)"; std::string result = FileUtil::getDirectory(filenamePath); AssertHelper::assertTrue(result == R"(C:\home\jean\)"); } void FileUtilTest::getFilesRecursiveWithSpecialChar() { std::vector files = FileUtil::getFilesRecursive(FileSystem::instance().getResourcesDirectory() + "files/"); AssertHelper::assertUnsignedIntEquals(files.size(), 1); AssertHelper::assertTrue(FileUtil::isFileExist(files[0])); AssertHelper::assertStringEquals(FileUtil::getFileName(files[0]), "file.txt"); } CppUnit::Test* FileUtilTest::suite() { auto* suite = new CppUnit::TestSuite("FileUtilTest"); suite->addTest(new CppUnit::TestCaller &FileUtilTest::getDirectoryUnix)); suite->addTest(new CppUnit::TestCaller &FileUtilTest::getDirectoryWindows)); suite->addTest(new CppUnit::TestCaller &FileUtilTest::getFilesRecursiveWithSpecialChar)); return suite; }
c++
12
0.747921
143
35.348837
43
starcoderdata
// // Luna+Position.h // Luna // // Created by 李夙璃 on 2018/4/25. // Copyright © 2018年 李夙璃. All rights reserved. // #import "Luna+PreGenerate.h" // MARK: - LCBitChess typedef UInt32 LCBitChess; LC_INLINE void LCBitChessAddChess(LCBitChess *bitchess, const LCChess chess) { *bitchess |= 1 << (chess - 16); } LC_INLINE void LCBitChessRemoveChess(LCBitChess *bitchess, const LCChess chess) { *bitchess &= ~(1 << (chess - 16)); } // MARK: - LCPosition typedef struct { LCLocation board[LCBoardLength]; LCLocation chess[LCChessLength]; LCRowColumn row[LCBoardRowsColumnsLength]; LCRowColumn column[LCBoardRowsColumnsLength]; LCSide side; LCBitChess bitchess; LCZobristHash hash; LCZobristKey key; } LCPosition; typedef const LCPosition *const LCPositionRef; typedef LCPosition *const LCMutablePositionRef; // MARK: - LCPosition Life Cycle extern LCMutablePositionRef LCPositionCreateMutable(void); @class NSString; extern void LCPositionInit(LCMutablePositionRef position, NSString *FEN, const LCSide side); extern void LCPositionRelease(LCPositionRef position);
c
10
0.733333
92
23.456522
46
starcoderdata
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //instantiate the Broadcast Receiver here. receiver = new ConnectivityChangeReceiver(); //register the Broadcast Receiver on application onCreate. registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); Toast.makeText(this, "Broadcast Receiver registered!", Toast.LENGTH_LONG).show(); Log.i("BROADCAST", "Broadcast Receiver registered!"); }
java
9
0.714041
94
44
13
inline
import os; import re; import numpy as np; statistics = { "tabu_search":[], "hill_climb_rnd":[] } for method_name in statistics: for problem_size in range(5, 30): for repeat in range(1,15): cmndName = "./a.out --size " + str(problem_size) + " --method " + method_name + " --iterations 1000 --tabu_size 200" print(cmndName) result = os.popen(cmndName) output = result.read() calcTime = re.findall("dt.*", output) if (len(calcTime) > 0): calcTime = re.findall("[0-9.]+",calcTime[0]) result_val = re.findall("[0-9.]+",re.findall("result.*", output)[0]) statistics[method_name].append([problem_size,float(result_val[0]), float(calcTime[0])]) #print(statistics) with open("result.plt", "a") as gnuplotfile: gnuplotfile.write("set term png\n") gnuplotfile.write("set output \"result.png\"\n") gnuplotfile.write("plot ") for method_name in statistics: print(method_name) summary = statistics[method_name] # print(summary) per_size = {} for values in summary: if (per_size.get(values[0]) is None): per_size[values[0]] = [[values[1], values[2]]] else: per_size[values[0]].append([values[1], values[2]]) #print(per_size) for s in per_size: combined = np.mean(per_size[s], axis=0) with open("result_" + method_name + ".txt", "a") as myfile: myfile.write(str(s) + " " + str(combined[0]) + " "+ str(combined[1]) + "\n") gnuplotfile.write("'result_" + method_name + ".txt' u 1:2 w lines, ") gnuplotfile.write("\n") result = os.popen("gnuplot result.plt") output = result.read()
python
19
0.548369
129
33.788462
52
starcoderdata
void CSArc::compress_index() { uint64_t index_size = 0; char *index_buf = PackIndex(index_, abindex_, index_size); FileWriter file_writer; MemReader mem_reader; Mutex arc_lock; mem_reader.ptr = index_buf; mem_reader.size = index_size; mem_reader.pos = 0; mem_reader.is.Read = mem_read_proc; // begin to compress index, and write to end of file init_mutex(arc_lock); ArchiveBlocks ab; uint64_t arc_index_pos = 0; { InputFile f; f.open(arcname_.c_str()); f.seek(0, SEEK_END); arc_index_pos = f.tell(); f.close(); ab.filename = arcname_; ab.blocks.clear(); } file_writer.obj = new AsyncArchiveWriter(ab, 1 * 1048576, arc_lock); file_writer.os.Write = file_write_proc; { CSCProps p; CSCEncProps_Init(&p, 256 * 1024, 2); CSCEncHandle h = CSCEnc_Create(&p, (ISeqOutStream*)&file_writer); uint8_t buf[CSC_PROP_SIZE]; CSCEnc_WriteProperties(&p, buf, 0); file_writer.obj->Run(); file_writer.obj->Write(buf, CSC_PROP_SIZE); CSCEnc_Encode(h, (ISeqInStream*)&mem_reader, NULL); CSCEnc_Encode_Flush(h); CSCEnc_Destroy(h); file_writer.obj->Finish(); delete file_writer.obj; } destroy_mutex(arc_lock); delete[] index_buf; // Write pos of compressed index and its size on header pos { OutputFile f; f.open(arcname_.c_str()); f.seek(0, SEEK_END); uint32_t idx_compressed = f.tell() - arc_index_pos; char fs_buf[16]; //printf("llu compressed_size %lu\n", arc_index_pos, idx_compressed); Put8(arc_index_pos, fs_buf); Put4(idx_compressed, fs_buf + 8); Put4(index_size, fs_buf + 12); f.write(fs_buf, 8, 16); fs_buf[0] = 'C'; fs_buf[1] = 'S'; fs_buf[2] = 'A'; fs_buf[7] = '1'; Put4(0x20130331, fs_buf + 3); f.write(fs_buf, 0, 8); f.close(); } }
c++
11
0.561025
77
28.294118
68
inline
using System.Web.Http; using CustomerOrders.Data.Interfaces; using CustomerOrders.WebAPI.Services; namespace CustomerOrders.WebAPI.Controllers { [RoutePrefix("api/customer")] public class CustomerController : ApiController { private IRepository _repository; private IMapperService _mapperService; public CustomerController(IRepository repository, IMapperService mapperService) { _repository = repository; _mapperService = mapperService; } [Route("~/api/customers")] public IHttpActionResult GetAll() { var customers = _repository.GetAllCustomers(); var customerDtos = _mapperService.Map(customers); return Ok(customerDtos); } [Route("{id:alpha}")] public IHttpActionResult Get(string id) { var customer = _repository.GetCustomer(id); if (customer == null) { return NotFound(); } var customerDto = _mapperService.Map(customer); return Ok(customerDto); } [Route("{customerId}/orders")] public IHttpActionResult GetOrdersByCustomerId(string customerId) { var orders = _repository.GetOrdersByCustomerId(customerId); var orderDtos = _mapperService.Map(orders); return Ok(orderDtos); } } }
c#
14
0.608163
87
27.269231
52
starcoderdata
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using ProtoBuf.Meta; namespace Zaabee.Protobuf { public static class SerializerBuilder { private const BindingFlags Flags = BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; private static readonly ConcurrentDictionary<Type, HashSet SubTypes = new ConcurrentDictionary<Type, HashSet private static readonly ConcurrentBag BuiltTypes = new ConcurrentBag private static readonly Type ObjectType = typeof(object); /// /// Build the ProtoBuf serializer from the generic <see cref="Type">type /// /// <typeparam name="T">The type of build the serializer for. public static void Build runtimeTypeModel) { var type = typeof(T); Build(runtimeTypeModel, type); } /// /// Build the ProtoBuf serializer for the <see cref="Type">type /// /// <param name="runtimeTypeModel"> /// <param name="type">The type of build the serializer for. public static void Build(RuntimeTypeModel runtimeTypeModel, Type type) { if (BuiltTypes.Contains(type)) return; lock (type) { if (BuiltTypes.Contains(type)) return; if (runtimeTypeModel.CanSerialize(type)) { if (type.IsGenericType) BuildGenerics(runtimeTypeModel,type); return; } var meta = runtimeTypeModel.Add(type, false); var fields = type.GetFields(Flags); meta.Add(fields.Select(m => m.Name).ToArray()); meta.UseConstructor = false; BuildBaseClasses(runtimeTypeModel, type); BuildGenerics(runtimeTypeModel, type); foreach (var memberType in fields.Select(f => f.FieldType).Where(t => !t.IsPrimitive)) Build(runtimeTypeModel, memberType); BuiltTypes.Add(type); } } /// /// Builds the base class serializers for a type. /// /// <param name="runtimeTypeModel"> /// <param name="type">The type. private static void BuildBaseClasses(RuntimeTypeModel runtimeTypeModel, Type type) { var baseType = type.BaseType; var inheritingType = type; while (baseType != null && baseType != ObjectType) { if (!SubTypes.TryGetValue(baseType, out var baseTypeEntry)) SubTypes.TryAdd(baseType, baseTypeEntry = new HashSet if (!baseTypeEntry.Contains(inheritingType)) { Build(runtimeTypeModel, baseType); runtimeTypeModel[baseType].AddSubType(baseTypeEntry.Count + 500, inheritingType); baseTypeEntry.Add(inheritingType); } inheritingType = baseType; baseType = baseType.BaseType; } } /// /// Builds the serializers for the generic parameters for a given type. /// /// <param name="runtimeTypeModel"> /// <param name="type">The type. private static void BuildGenerics(RuntimeTypeModel runtimeTypeModel, Type type) { if (!type.IsGenericType && (type.BaseType is null || !type.BaseType.IsGenericType)) return; var generics = type.IsGenericType ? type.GetGenericArguments() : type.BaseType.GetGenericArguments(); foreach (var generic in generics) Build(runtimeTypeModel, generic); } } }
c#
21
0.57575
113
37.126126
111
starcoderdata
# =============================================================================== # Copyright 2015 # # 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. # =============================================================================== from enable.component_editor import ComponentEditor from pyface.tasks.traits_dock_pane import TraitsDockPane from pyface.tasks.traits_task_pane import TraitsTaskPane from traits.api import Button, Bool, Int, Float from traitsui.api import View, Item, UItem, VGroup, HGroup, spring, Tabbed from pychron.core.ui.lcd_editor import LCDEditor from pychron.envisage.icon_button_editor import icon_button_editor class ControlPane(TraitsDockPane): name = "Controls" id = "pychron.ldeofurnace.controls" extract_value = Float extract_button = Button("Extract") dump_sample_number = Int dump_sample_button = Button("Dump") # jitter_button = Button # jitter_label = Str('Start') # jittering = Bool # configure_jitter_button = Button # refresh_states_button = Button('Refresh') set_home_button = Button("Set Home") toggle_advanced_view_button = Button _advanced_view_state = Bool(False) disable_button = Button motor_stop_button = Button clear_sample_states_button = Button("Clear Dumped Samples") def _motor_stop_button_fired(self): self.model.stop_motors() def _set_home_button_fired(self): self.model.furnace_maset_home() def _disable_button_fired(self): self.model.stop_motors() # just refers to motor stop function for now def _dump_sample_button_fired(self): self.model.drop_sample(self.dump_sample_number) def _extract_button_fired(self): self.model.extract(self.extract_value, "percent") # def _jitter_button_fired(self): # if not self.jittering: # self.model.start_jitter_feeder() # self.jitter_label = 'Stop' # else: # self.model.stop_jitter_feeder() # self.jitter_label = 'Start' # self.jittering = not self.jittering # # def _configure_jitter_button_fired(self): # self.model.configure_jitter_feeder() def _toggle_advanced_view_button_fired(self): self._advanced_view_state = not self._advanced_view_state def _refresh_states_button_fired(self): self.model.refresh_states() def _clear_sample_states_button_fired(self): self.model.clear_sample_states() def trait_context(self): return {"object": self.model, "pane": self, "manager": self.model} def traits_view(self): c_grp = VGroup( # HGroup(Item('setpoint'), # UItem('water_flow_state', editor=LEDEditor(label='H2O Flow')), # spring, icon_button_editor('pane.disable_button', 'cancel')), VGroup(UItem("output_percent_readback", editor=LCDEditor())), icon_button_editor( "start_record_button", "media-record", tooltip="Start recording", enabled_when="not _recording", ), icon_button_editor( "stop_record_button", "media-playback-stop", tooltip="Stop recording", enabled_when="_recording", ), label="Controller", show_border=True, ) power_grp = HGroup( UItem( "pane.extract_value", width=50, enabled_when="furnace_enabled", tooltip="Power setting for furnace (0-100%)", ), UItem( "pane.extract_button", enabled_when="furnace_enabled", tooltip="Send the value to the furnace", ), show_border=True, label="Furnace Power", ) # jitter_grp = HGroup(UItem('pane.jitter_button', editor=ButtonEditor(label_value='pane.jitter_label')), # icon_button_editor('pane.configure_jitter_button', 'cog', tooltip='Configure Jitter'), # show_border=True, label='Jitter') dump_grp = HGroup( UItem( "pane.dump_sample_number", width=50, enabled_when="dump_sample_enabled", tooltip="Sample number to dump", ), UItem( "pane.dump_sample_button", enabled_when="dump_sample_enabled", tooltip="Execute the complete sample loading procedure", ), UItem("pane.clear_sample_states_button"), show_border=True, label="Dump", ) # status_grp = HGroup(CustomLabel('status_txt', size=14)) d1 = VGroup(power_grp, dump_grp) d2 = VGroup( # UItem('pane.refresh_states_button'), UItem("dumper_canvas", editor=ComponentEditor()) ) d_grp = HGroup(d1, d2, label="Dumper", show_border=True) # v_grp = VGroup(UItem('video_canvas', editor=VideoComponentEditor()), # visible_when='video_enabled', # label='Camera') g_grp = VGroup( Item("graph_scan_width", label="Scan Width (mins)"), HGroup( Item("graph_scale", label="Scale"), Item("graph_y_auto", label="Autoscale Y"), Item( "graph_ymax", label="Max", format_str="%0.3f", enabled_when="not graph_y_auto", ), Item( "graph_ymin", label="Min", format_str="%0.3f", enabled_when="not graph_y_auto", ), ), HGroup( icon_button_editor( "clear_button", "clear", tooltip="Clear and reset graph" ), spring, ), HGroup( icon_button_editor( "start_record_button", "media-record", tooltip="Start recording", enabled_when="not _recording", ), icon_button_editor( "stop_record_button", "media-playback-stop", tooltip="Stop recording", enabled_when="_recording", ), icon_button_editor( "add_marker_button", "flag", enabled_when="_recording" ), show_border=True, label="Record Scan", ), label="Graph", ) v = View(VGroup(c_grp, HGroup(Tabbed(d_grp, g_grp)))) return v class FurnacePane(TraitsTaskPane): def trait_context(self): return {"object": self.model, "pane": self, "manager": self.model} def traits_view(self): canvas_grp = VGroup( # HGroup(UItem('stage_manager.stage_map_name', editor=EnumEditor(name='stage_manager.stage_map_names')), # spring), UItem("canvas", style="custom", editor=ComponentEditor()) ) v = View(VGroup(UItem("graph", style="custom"), canvas_grp)) return v # ============= EOF =============================================
python
16
0.528463
116
34.132743
226
starcoderdata
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getAuthenticatedOctokitForEvent = void 0; const auth_unauthenticated_1 = require("@octokit/auth-unauthenticated"); const get_authenticated_octokit_1 = require("./get-authenticated-octokit"); function getAuthenticatedOctokitForEvent(state, event) { if (state.githubToken) return get_authenticated_octokit_1.getAuthenticatedOctokit(state); if (isUnauthenticatedEvent(event)) { return new state.Octokit({ authStrategy: auth_unauthenticated_1.createUnauthenticatedAuth, auth: { reason: "`context.github` is unauthenticated. See https://probot.github.io/docs/github-api/#unauthenticated-events", }, }); } return get_authenticated_octokit_1.getAuthenticatedOctokit(state, event.payload.installation.id); } exports.getAuthenticatedOctokitForEvent = getAuthenticatedOctokitForEvent; // Some events can't get an authenticated client (#382): function isUnauthenticatedEvent(event) { return (!event.payload.installation || (event.name === "installation" && event.payload.action === "deleted")); } //# sourceMappingURL=get-authenticated-octokit-for-event.js.map
javascript
13
0.725363
132
48.56
25
starcoderdata
<?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; class UpdateBalance implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; protected $address; protected $asset; /** * Create a new job instance. * * @return void */ public function __construct($address, $asset) { $this->address = $address; $this->asset = $asset; } /** * Execute the job. * * @return void */ public function handle() { // Block of Last Saved Balance $last_block = $this->getLastBlockIndex(); // Blocks w/ Changes Since Then $blocks = $this->getBalanceChanges($last_block); $unique_blocks = $blocks->unique('block_index')->sortBy('block_index'); // Crunch and Save Balances foreach($unique_blocks as $unique_block) { // Expire Prior Balances $this->expireBalances($unique_block['block_index']); // Get Balance Quantity $quantity = $this->getQuantity($unique_block['block_index']); // Get Block as a Model $block = \App\Block::find($unique_block['block_index']); // Save Current Balance $this->createBalance($quantity, $block); } \Cache::tags([$this->address . '_balances'])->flush(); } /** * Get Last Block Index */ private function getLastBlockIndex() { $last_balance = $this->getLastBalance(); return $last_balance ? $last_balance->block_index : 0; } /** * Get Last Balance */ private function getLastBalance() { return \App\Balance::where('address', '=', $this->address) ->where('asset', '=', $this->asset) ->orderBy('block_index', 'desc') ->first(); } /** * Get Balance Changes */ private function getBalanceChanges($block_index) { $credit_blocks = $this->getCreditBlocks($block_index); $debit_blocks = $this->getDebitBlocks($block_index); return collect(array_merge($credit_blocks, $debit_blocks)); } /** * Get Blocks w/ Credits */ private function getCreditBlocks($block_index) { return \App\Credit::where('address', '=', $this->address) ->where('asset', '=', $this->asset) ->where('block_index', '>', $block_index) ->select('block_index') ->groupBy('block_index') ->get() ->toArray(); } /** * Get Blocks w/ Debits */ private function getDebitBlocks($block_index) { return \App\Debit::where('address', '=', $this->address) ->where('asset', '=', $this->asset) ->where('block_index', '>', $block_index) ->select('block_index') ->groupBy('block_index') ->get() ->toArray(); } /** * Create Balance */ private function createBalance($quantity, $block) { return \App\Balance::firstOrCreate([ 'address' => $this->address, 'asset' => $this->asset, 'block_index' => $block->block_index, ],[ 'current' => 1, 'quantity' => $quantity, 'confirmed_at' => $block->confirmed_at, ]); } /** * Get Quantity */ private function getQuantity($block_index) { $credits = $this->getCredits($block_index); $debits = $this->getDebits($block_index); $quantity = $credits - $debits; if($quantity < 0) $quantity = 0; return $quantity; } /** * Get Credits */ private function getCredits($block_index) { return \App\Credit::where('address', '=', $this->address) ->where('asset', '=', $this->asset) ->where('block_index', '<=', $block_index) ->sum('quantity'); } /** * Get Debits */ private function getDebits($block_index) { return \App\Debit::where('address', '=', $this->address) ->where('asset', '=', $this->asset) ->where('block_index', '<=', $block_index) ->sum('quantity'); } /** * Expire Balances */ private function expireBalances($block_index) { return \App\Balance::where('address', '=', $this->address) ->where('asset', '=', $this->asset) ->where('block_index', '<', $block_index) ->update(['current' => 0]); } }
php
17
0.523642
79
24.930108
186
starcoderdata
package ru.job4j; import org.junit.Test; import java.util.*; import static org.hamcrest.core.Is.is; import static org.junit.Assert.*; /** * class DepartamentTest * project lesson Collection plus * * @author ( * project job4j * @version 1.0 * @since 08.12.2018 */ public class DepartamentTest { @Test public void whenSortRightAndAddThenOk() { Departament departament = new Departament(); Collection departs = departament.addDepartInit(departament.departInit); departs = departament.sortRightPlus(departs); assertThat(departs.toString(), is("[" + "K1, " + "K1\\SK1, " + "K1\\SK1\\SSK1, " + "K1\\SK1\\SSK2, " + "K1\\SK2, " + "K2, " + "K2\\SK1, " + "K2\\SK1\\SSK1, " + "K2\\SK1\\SSK2" + "]")); } @Test public void whenSortReversAndAddThenOk() { Departament departament = new Departament(); Collection departs = departament.addDepartInit(departament.departInit); departs = departament.sortReversPlus(departs); assertThat(departs.toString(), is("[" + "K2, " + "K2\\SK1, " + "K2\\SK1\\SSK2, " + "K2\\SK1\\SSK1, " + "K1, " + "K1\\SK2, " + "K1\\SK1, " + "K1\\SK1\\SSK2, " + "K1\\SK1\\SSK1" + "]")); } }
java
21
0.5
87
25.933333
60
starcoderdata
'use strict'; export class Field { constructor(name, title) { this.isRef = false; this.key = name; this.name = name; this.title = title; this.isRequired = false; } } export class IntegerField extends Field { static get typeName() { return 'integer'; } constructor(name, title) { super(name, title); this.currentType = IntegerField.typeName; } } export class FloatField extends Field { static get typeName() { return 'number'; } constructor(name, title) { super(name, title); this.currentType = FloatField.typeName; } } export class StringField extends Field { static get typeName() { return 'string'; } constructor(name, title) { super(name, title); this.currentType = StringField.typeName; } } export class BoolField extends Field { static get typeName() { return 'boolean'; } constructor(name, title) { super(name, title); this.currentType = BoolField.typeName; } } export class ArrayField extends Field { static get typeName() { return 'array'; } constructor(name, title, itemField) { super(name, title); this.isRef = true; this.itemField = itemField; this.currentType = ArrayField.typeName; } } export class ObjectField extends Field { static get typeName() { return 'object'; } constructor(name, title, typeInfo) { super(name, title); this.isRef = true; this.typeInfo = typeInfo; this.currentType = ObjectField.typeName; } } export class EnumField extends Field { static get typeName() { return 'enum'; } constructor(name, title, valueType, values) { super(name, title); this.isRef = true; this.valueType = valueType; this.values = values; this.currentType = EnumField.typeName; this.typeInfo = name; } }
javascript
9
0.649891
47
16.747573
103
starcoderdata
import sys input = sys.stdin.readline N = 26 D = int(input()) Cs = list(map(int, input().split())) Sss = [tuple(map(int, input().split())) for _ in range(D)] Ts = [int(input())-1 for _ in range(D)] anss = [] score = 0 dayLasts = [-1] * N for day, T in enumerate(Ts): score += Sss[day][T] dayLasts[T] = day for C, dayLast in zip(Cs, dayLasts): score -= C * (day-dayLast) anss.append(score) print('\n'.join(map(str, anss)))
python
12
0.582222
58
20.428571
21
codenet
#include "g3/multivector.h" #include "g3/add_into.h" #include "g3/multiply.h" #include "g3/multivector_layout.h" #include "g3/quaternion.h" #include "g3/quaternion_layout.h" #include "g3/vector.h" #include "g3/vector_layout.h" namespace g3 { } // namespace g3
c++
4
0.718412
34
20.307692
13
starcoderdata
using System; namespace StockCommonLib { [Serializable] public class StockQueryResultMessage { public string StockCode { get; set; } public int ReservedStockCount { get; set; } public int TotalStockCount { get; set; } } }
c#
8
0.703812
76
25.230769
13
starcoderdata
package net.minecraft.network.protocol.game; import java.util.UUID; import java.util.function.Function; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.network.protocol.Packet; import net.minecraft.world.BossEvent; public class ClientboundBossEventPacket implements Packet { private static final int FLAG_DARKEN = 1; private static final int FLAG_MUSIC = 2; private static final int FLAG_FOG = 4; private final UUID id; private final ClientboundBossEventPacket.Operation operation; static final ClientboundBossEventPacket.Operation REMOVE_OPERATION = new ClientboundBossEventPacket.Operation() { public ClientboundBossEventPacket.OperationType getType() { return ClientboundBossEventPacket.OperationType.REMOVE; } public void dispatch(UUID p_178660_, ClientboundBossEventPacket.Handler p_178661_) { p_178661_.remove(p_178660_); } public void write(FriendlyByteBuf p_178663_) { } }; private ClientboundBossEventPacket(UUID pId, ClientboundBossEventPacket.Operation pOperation) { this.id = pId; this.operation = pOperation; } public ClientboundBossEventPacket(FriendlyByteBuf pBuffer) { this.id = pBuffer.readUUID(); ClientboundBossEventPacket.OperationType clientboundbosseventpacket$operationtype = pBuffer.readEnum(ClientboundBossEventPacket.OperationType.class); this.operation = clientboundbosseventpacket$operationtype.reader.apply(pBuffer); } public static ClientboundBossEventPacket createAddPacket(BossEvent pEvent) { return new ClientboundBossEventPacket(pEvent.getId(), new ClientboundBossEventPacket.AddOperation(pEvent)); } public static ClientboundBossEventPacket createRemovePacket(UUID pId) { return new ClientboundBossEventPacket(pId, REMOVE_OPERATION); } public static ClientboundBossEventPacket createUpdateProgressPacket(BossEvent pEvent) { return new ClientboundBossEventPacket(pEvent.getId(), new ClientboundBossEventPacket.UpdateProgressOperation(pEvent.getProgress())); } public static ClientboundBossEventPacket createUpdateNamePacket(BossEvent pEvent) { return new ClientboundBossEventPacket(pEvent.getId(), new ClientboundBossEventPacket.UpdateNameOperation(pEvent.getName())); } public static ClientboundBossEventPacket createUpdateStylePacket(BossEvent pEvent) { return new ClientboundBossEventPacket(pEvent.getId(), new ClientboundBossEventPacket.UpdateStyleOperation(pEvent.getColor(), pEvent.getOverlay())); } public static ClientboundBossEventPacket createUpdatePropertiesPacket(BossEvent pEvent) { return new ClientboundBossEventPacket(pEvent.getId(), new ClientboundBossEventPacket.UpdatePropertiesOperation(pEvent.shouldDarkenScreen(), pEvent.shouldPlayBossMusic(), pEvent.shouldCreateWorldFog())); } /** * Writes the raw packet data to the data stream. */ public void write(FriendlyByteBuf pBuffer) { pBuffer.writeUUID(this.id); pBuffer.writeEnum(this.operation.getType()); this.operation.write(pBuffer); } static int encodeProperties(boolean pDarkenScreen, boolean pPlayMusic, boolean pCreateWorldFog) { int i = 0; if (pDarkenScreen) { i |= 1; } if (pPlayMusic) { i |= 2; } if (pCreateWorldFog) { i |= 4; } return i; } /** * Passes this Packet on to the NetHandler for processing. */ public void handle(ClientGamePacketListener pHandler) { pHandler.handleBossUpdate(this); } public void dispatch(ClientboundBossEventPacket.Handler pHandler) { this.operation.dispatch(this.id, pHandler); } static class AddOperation implements ClientboundBossEventPacket.Operation { private final Component name; private final float progress; private final BossEvent.BossBarColor color; private final BossEvent.BossBarOverlay overlay; private final boolean darkenScreen; private final boolean playMusic; private final boolean createWorldFog; AddOperation(BossEvent pEvent) { this.name = pEvent.getName(); this.progress = pEvent.getProgress(); this.color = pEvent.getColor(); this.overlay = pEvent.getOverlay(); this.darkenScreen = pEvent.shouldDarkenScreen(); this.playMusic = pEvent.shouldPlayBossMusic(); this.createWorldFog = pEvent.shouldCreateWorldFog(); } private AddOperation(FriendlyByteBuf pBuffer) { this.name = pBuffer.readComponent(); this.progress = pBuffer.readFloat(); this.color = pBuffer.readEnum(BossEvent.BossBarColor.class); this.overlay = pBuffer.readEnum(BossEvent.BossBarOverlay.class); int i = pBuffer.readUnsignedByte(); this.darkenScreen = (i & 1) > 0; this.playMusic = (i & 2) > 0; this.createWorldFog = (i & 4) > 0; } public ClientboundBossEventPacket.OperationType getType() { return ClientboundBossEventPacket.OperationType.ADD; } public void dispatch(UUID pId, ClientboundBossEventPacket.Handler pHandler) { pHandler.add(pId, this.name, this.progress, this.color, this.overlay, this.darkenScreen, this.playMusic, this.createWorldFog); } public void write(FriendlyByteBuf pBuffer) { pBuffer.writeComponent(this.name); pBuffer.writeFloat(this.progress); pBuffer.writeEnum(this.color); pBuffer.writeEnum(this.overlay); pBuffer.writeByte(ClientboundBossEventPacket.encodeProperties(this.darkenScreen, this.playMusic, this.createWorldFog)); } } public interface Handler { default void add(UUID pId, Component pName, float pProgress, BossEvent.BossBarColor pColor, BossEvent.BossBarOverlay pOverlay, boolean pDarkenScreen, boolean pPlayMusic, boolean pCreateWorldFog) { } default void remove(UUID pId) { } default void updateProgress(UUID pId, float pProgress) { } default void updateName(UUID pId, Component pName) { } default void updateStyle(UUID pId, BossEvent.BossBarColor pColor, BossEvent.BossBarOverlay pOverlay) { } default void updateProperties(UUID pId, boolean pDarkenScreen, boolean pPlayMusic, boolean pCreateWorldFog) { } } interface Operation { ClientboundBossEventPacket.OperationType getType(); void dispatch(UUID pId, ClientboundBossEventPacket.Handler pHandler); void write(FriendlyByteBuf pBuffer); } static enum OperationType { ADD(ClientboundBossEventPacket.AddOperation::new), REMOVE((p_178719_) -> { return ClientboundBossEventPacket.REMOVE_OPERATION; }), UPDATE_PROGRESS(ClientboundBossEventPacket.UpdateProgressOperation::new), UPDATE_NAME(ClientboundBossEventPacket.UpdateNameOperation::new), UPDATE_STYLE(ClientboundBossEventPacket.UpdateStyleOperation::new), UPDATE_PROPERTIES(ClientboundBossEventPacket.UpdatePropertiesOperation::new); final Function<FriendlyByteBuf, ClientboundBossEventPacket.Operation> reader; private OperationType(Function<FriendlyByteBuf, ClientboundBossEventPacket.Operation> p_178716_) { this.reader = p_178716_; } } static class UpdateNameOperation implements ClientboundBossEventPacket.Operation { private final Component name; UpdateNameOperation(Component pName) { this.name = pName; } private UpdateNameOperation(FriendlyByteBuf pBuffer) { this.name = pBuffer.readComponent(); } public ClientboundBossEventPacket.OperationType getType() { return ClientboundBossEventPacket.OperationType.UPDATE_NAME; } public void dispatch(UUID pId, ClientboundBossEventPacket.Handler pHandler) { pHandler.updateName(pId, this.name); } public void write(FriendlyByteBuf pBuffer) { pBuffer.writeComponent(this.name); } } static class UpdateProgressOperation implements ClientboundBossEventPacket.Operation { private final float progress; UpdateProgressOperation(float pProgress) { this.progress = pProgress; } private UpdateProgressOperation(FriendlyByteBuf pBuffer) { this.progress = pBuffer.readFloat(); } public ClientboundBossEventPacket.OperationType getType() { return ClientboundBossEventPacket.OperationType.UPDATE_PROGRESS; } public void dispatch(UUID pId, ClientboundBossEventPacket.Handler pHandler) { pHandler.updateProgress(pId, this.progress); } public void write(FriendlyByteBuf pBuffer) { pBuffer.writeFloat(this.progress); } } static class UpdatePropertiesOperation implements ClientboundBossEventPacket.Operation { private final boolean darkenScreen; private final boolean playMusic; private final boolean createWorldFog; UpdatePropertiesOperation(boolean pDarkenScreen, boolean pPlayMusic, boolean pCreateWorldFog) { this.darkenScreen = pDarkenScreen; this.playMusic = pPlayMusic; this.createWorldFog = pCreateWorldFog; } private UpdatePropertiesOperation(FriendlyByteBuf pBuffer) { int i = pBuffer.readUnsignedByte(); this.darkenScreen = (i & 1) > 0; this.playMusic = (i & 2) > 0; this.createWorldFog = (i & 4) > 0; } public ClientboundBossEventPacket.OperationType getType() { return ClientboundBossEventPacket.OperationType.UPDATE_PROPERTIES; } public void dispatch(UUID pId, ClientboundBossEventPacket.Handler pHandler) { pHandler.updateProperties(pId, this.darkenScreen, this.playMusic, this.createWorldFog); } public void write(FriendlyByteBuf pBuffer) { pBuffer.writeByte(ClientboundBossEventPacket.encodeProperties(this.darkenScreen, this.playMusic, this.createWorldFog)); } } static class UpdateStyleOperation implements ClientboundBossEventPacket.Operation { private final BossEvent.BossBarColor color; private final BossEvent.BossBarOverlay overlay; UpdateStyleOperation(BossEvent.BossBarColor pColor, BossEvent.BossBarOverlay pOverlay) { this.color = pColor; this.overlay = pOverlay; } private UpdateStyleOperation(FriendlyByteBuf pBuffer) { this.color = pBuffer.readEnum(BossEvent.BossBarColor.class); this.overlay = pBuffer.readEnum(BossEvent.BossBarOverlay.class); } public ClientboundBossEventPacket.OperationType getType() { return ClientboundBossEventPacket.OperationType.UPDATE_STYLE; } public void dispatch(UUID pId, ClientboundBossEventPacket.Handler pHandler) { pHandler.updateStyle(pId, this.color, this.overlay); } public void write(FriendlyByteBuf pBuffer) { pBuffer.writeEnum(this.color); pBuffer.writeEnum(this.overlay); } } }
java
13
0.718533
208
36.123746
299
starcoderdata
public static IEnumerable<MemberInfo> GetMembersInHierarchy(this Type type, string name) { // Do the whole hierarchy for properties first since looking for fields is slower. var currentType = type; do { var typeInfo = currentType.GetTypeInfo(); var propertyInfo = typeInfo.GetDeclaredProperty(name); if (propertyInfo != null && !(propertyInfo.GetMethod ?? propertyInfo.SetMethod).IsStatic) { yield return propertyInfo; } currentType = typeInfo.BaseType; } while (currentType != null); currentType = type; do { var fieldInfo = currentType.GetRuntimeFields().FirstOrDefault(f => f.Name == name && !f.IsStatic); if (fieldInfo != null) { yield return fieldInfo; } currentType = currentType.GetTypeInfo().BaseType; } while (currentType != null); }
c#
17
0.500444
114
37.896552
29
inline
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; using TMPro; public class UIDragableItem : MonoBehaviour { private RectTransform rectTransform; private CanvasGroup canvasGroup; public Item item; public int amount; private Image image; private TextMeshProUGUI itemLevel; private TextMeshProUGUI itemCount; public void SetItem(Item item, int amount = 1) { this.item = item; this.amount = amount; image = transform.Find("ItemBackground").gameObject.GetComponent itemLevel = transform.Find("ItemLevel").GetComponent itemCount = transform.Find("ItemCount").GetComponent image.sprite = item.image; itemLevel.SetText(item.level.ToString()); if (amount > 1) { itemCount.SetText(amount.ToString()); } else { itemCount.SetText(""); } } void Awake() { rectTransform = GetComponent canvasGroup = GetComponent } public void OnDrag(PointerEventData eventData) { rectTransform.position = eventData.position; } public void OnPointerDown(PointerEventData eventData) { } public void OnBeginDrag(PointerEventData eventData) { canvasGroup.blocksRaycasts = false; canvasGroup.alpha = .6f; } public void OnEndDrag(PointerEventData eventData) { canvasGroup.blocksRaycasts = true; canvasGroup.alpha = 1f; } public void OnPlacementConfirm(UIDropReciver reciver) { } }
c#
14
0.651568
82
25.492308
65
starcoderdata
bool karte_t::can_flood_to_depth( koord k, sint8 new_water_height, sint8 *stage, sint8 *our_stage, sint16 x_min, sint16 x_max, sint16 y_min, sint16 y_max ) const { bool succeeded = true; if( k == koord::invalid ) { return false; } if( new_water_height < get_groundwater() - 3 ) { return false; } // make a list of tiles to change // cannot use a recursive method as stack is not large enough! sint8 *from_dir = new sint8[get_size().x * get_size().y]; bool local_stage = (our_stage==NULL); if( local_stage ) { our_stage = new sint8[get_size().x * get_size().y]; } memset( from_dir + sizeof(sint8) * array_koord(0,y_min), -1, sizeof(sint8) * get_size().x * (y_max-y_min) ); memset( our_stage + sizeof(sint8) * array_koord(0,y_min), -1, sizeof(sint8) * get_size().x * (y_max-y_min) ); uint32 offset = array_koord(k.x,k.y); stage[offset]=0; our_stage[offset]=0; do { for( int i = our_stage[offset]; i < 8; i++ ) { koord k_neighbour = k + koord::neighbours[i]; if( k_neighbour.x >= x_min && k_neighbour.x<x_max && k_neighbour.y >= y_min && k_neighbour.y<y_max ) { const uint32 neighbour_offset = array_koord(k_neighbour.x,k_neighbour.y); // already visited if(our_stage[neighbour_offset] != -1) goto next_neighbour; // water height above if(water_hgts[neighbour_offset] >= new_water_height) goto next_neighbour; grund_t *gr2 = lookup_kartenboden_nocheck(k_neighbour); if( !gr2 ) goto next_neighbour; sint8 neighbour_height = gr2->get_hoehe(); // land height above if(neighbour_height >= new_water_height) goto next_neighbour; //move on to next tile from_dir[neighbour_offset] = i; stage[neighbour_offset] = 0; our_stage[neighbour_offset] = 0; our_stage[offset] = i; k = k_neighbour; offset = array_koord(k.x,k.y); break; } else { // edge of map - we keep iterating so we can mark all connected tiles as failing succeeded = false; } next_neighbour: //return back to previous tile if( i==7 ) { k = k - koord::neighbours[from_dir[offset]]; } } offset = array_koord(k.x,k.y); } while( from_dir[offset] != -1 ); delete [] from_dir; if( local_stage ) { delete [] our_stage; } return succeeded; }
c++
17
0.621812
163
28.545455
77
inline
'use strict'; // Generate image link var SERVICE_INSTAGRAM = /(((instagr\.am)|(instagram\.com))\/\w\/\w+)/i; exports.process = function(media, remix) { if (!remix.isMatched && media.url.match(SERVICE_INSTAGRAM)) { var parts = media.url.split('/'); var shortcode = parts[parts.length - 2]; remix.isMatched = true; remix.result = '<div class="image-wrapper"><a href="' + media.url + '">' + '<img src="http://instagr.am/p/' + shortcode + '/media/"/> href="' + media.url + '" target="_blank" class="media-off">' + media.text + ' } return remix; };
javascript
19
0.589018
98
30.631579
19
starcoderdata
def cli(): """Capture a todo/idea quickly into notion""" application = setup_editor(COMPLETION_WORDS) result: CapturedText = application.run() if result.save: save(result.text) return console.log("[red]Quited without saving :x:")
python
9
0.650376
49
28.666667
9
inline
/* * 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 ar.com.scvst.server.bean; import java.io.IOException; import org.apache.commons.lang3.StringUtils; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.internal.storage.file.FileRepository; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.transport.CredentialsProvider; import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider; /** * * @author */ public class Configuracion { public enum TipoRepositorio { BitBucket, GitHub, GitLab, GoogleDrive, DropBox } private String ubicacionLocal; private transient Repository repositorioLocal; private String ubicacionRemota; private transient TipoRepositorio tipoRepositorioRemoto; private transient Git git; private transient CredentialsProvider credenciales; private String usuario; private String clave; public Configuracion() { } public Configuracion(String ubicacionLocal, String ubicacionRemota) throws IOException { this.ubicacionLocal = ubicacionLocal; this.ubicacionRemota = ubicacionRemota; this.repositorioLocal = new FileRepository(ubicacionLocal + "/.git"); git = new Git(repositorioLocal); } public Configuracion(String ubicacionLocal, String ubicacionRemota, TipoRepositorio tipoRepositorioRemoto) throws IOException { this.ubicacionLocal = ubicacionLocal; this.ubicacionRemota = ubicacionRemota; this.tipoRepositorioRemoto = tipoRepositorioRemoto; this.repositorioLocal = new FileRepository(ubicacionLocal + "/.git"); git = new Git(repositorioLocal); } public Configuracion(String ubicacionLocal, String ubicacionRemota, String usuario, String clave, TipoRepositorio tipoRepositorioRemoto) throws IOException { this.ubicacionLocal = ubicacionLocal; this.ubicacionRemota = ubicacionRemota; this.tipoRepositorioRemoto = tipoRepositorioRemoto; this.repositorioLocal = new FileRepository(ubicacionLocal + "/.git"); if (StringUtils.isNotBlank(clave) && StringUtils.isNoneBlank(usuario)) { this.usuario = usuario; this.clave = clave; credenciales = new UsernamePasswordCredentialsProvider(this.usuario, this.clave); } git = new Git(repositorioLocal); } public String getUbicacionLocal() { return ubicacionLocal; } public void setUbicacionLocal(String ubicacionLocal) { this.ubicacionLocal = ubicacionLocal; } public Repository getRepositorioLocal() { return repositorioLocal; } public void setRepositorioLocal(Repository repositorioLocal) { this.repositorioLocal = repositorioLocal; } public String getUbicacionRemota() { return ubicacionRemota; } public void setUbicacionRemota(String ubicacionRemota) { this.ubicacionRemota = ubicacionRemota; } public TipoRepositorio getTipoRepositorioRemoto() { return tipoRepositorioRemoto; } public void setTipoRepositorioRemoto(TipoRepositorio tipoRepositorioRemoto) { this.tipoRepositorioRemoto = tipoRepositorioRemoto; } public Git getGit() { return git; } public void setGit(Git git) { this.git = git; } public CredentialsProvider getCredenciales() { return credenciales; } public void setCredenciales(CredentialsProvider credenciales) { this.credenciales = credenciales; } public String getUsuario() { return usuario; } public void setUsuario(String usuario) { this.usuario = usuario; } public String getClave() { return clave; } public void setClave(String clave) { this.clave = clave; } @Override public String toString() { return "Configuracion{" + "ubicacionLocal=" + ubicacionLocal + ", repositorioLocal=" + repositorioLocal + ", ubicacionRemota=" + ubicacionRemota + ", tipoRepositorioRemoto=" + tipoRepositorioRemoto + ", git=" + git + ", credenciales=" + credenciales + ", usuario=" + usuario + ", clave=" + clave + '}'; } }
java
24
0.69377
310
30.185714
140
starcoderdata
/* Copyright © 2015 */ using System; using System.IO; using System.Text; using Bam.Net.Presentation; using Bam.Net.ServiceProxy; using Bam.Net.Web; namespace Bam.Net.Server.Renderers { public class HtmlRenderer: ContentRenderer { public HtmlRenderer(ExecutionRequest request, ContentResponder contentResponder) : base(request, contentResponder, "text/html", ".htm", ".html") { this.AppName = UriApplicationNameResolver.ResolveApplicationName(request.Request.Url); this.ContentResponder = contentResponder; this.ExecutionRequest = request; } public string AppName { get; set; } HttpArgs _args; protected internal HttpArgs HttpArgs { get { if (_args == null) { _args = new HttpArgs(ExecutionRequest.Request.Url.Query); } return _args; } } public string GetTemplateName(object toRender) { HttpArgs args = HttpArgs;//new HttpArgs(ExecutionRequest.Request.Url.Query); args.Has("view", out string result); if (string.IsNullOrEmpty(result)) { string prefix = string.Empty; if (toRender != null) { Type typeToRender = toRender.GetType(); prefix = "{0}_"._Format(typeToRender.Name); ITemplateManager dustRenderer = ContentResponder.AppContentResponders[AppName].AppTemplateManager; dustRenderer.EnsureDefaultTemplate(typeToRender); } AppContentResponder appContentResponder = ContentResponder.AppContentResponders[AppName]; string domAppName = AppConf.DomApplicationIdFromAppName(appContentResponder.AppConf.Name); result = "{0}.{1}default"._Format(domAppName, prefix); } return result; } /// /// Render the response to the output stream of ExecutionRequest.Response /// public void Render() { Render(ExecutionRequest.Result, ExecutionRequest.Response.OutputStream); } public override void Render(object toRender, Stream output) { AppContentResponder appContentResponder = ContentResponder.AppContentResponders[AppName]; ITemplateManager templateManager = appContentResponder.AppTemplateManager; string templateName = GetTemplateName(toRender); string templates = string.Empty; if(templateManager is IHasCompiledTemplates hasCompiledTemplates) { templates = hasCompiledTemplates.CombinedCompiledTemplates; } string renderedContent = DustScript.Render(templates, templateName, toRender); byte[] data; if (HttpArgs.Has("layout", out string layout)) { string absolutePath = ExecutionRequest.Request.Url.AbsolutePath; string extension = Path.GetExtension(absolutePath); string path = absolutePath.Truncate(extension.Length); LayoutModel layoutModel = appContentResponder.GetLayoutModelForPath(path); layoutModel.LayoutName = layout; layoutModel.PageContent = renderedContent; MemoryStream ms = new MemoryStream(); appContentResponder.CommonTemplateManager.RenderLayout(layoutModel, ms); ms.Seek(0, SeekOrigin.Begin); data = ms.GetBuffer(); } else { data = Encoding.UTF8.GetBytes(renderedContent); } output.Write(data, 0, data.Length); } } }
c#
19
0.590897
118
36.038095
105
starcoderdata
/** * @author * @created 25.07.17 * @description User configuration for viaduct-ui. */ // Import Adapters for data requests import datasetService from '../src/viaduct-ui-adapter-vhub/datasets'; import catalogueService from '../src/viaduct-ui-adapter-vhub/catalogues'; import distributionService from '../src/viaduct-ui-adapter-vhub/distributions'; import datastoreService from '../src/viaduct-ui-adapter-vhub/datastore'; import gazetteerService from '../src/viaduct-ui-adapter-vhub/gazetteer'; import uploadService from '../src/services/uploads'; import authService from '../src/auth/authService'; // Export Config-Object export default { title: 'Piveau', api: { baseUrl: 'http://localhost:8081/', gazetteerBaseUrl: 'http://localhost:8081/gazetteer/', uploadBaseUrl: 'http://localhost:8080', matomoUrl: 'https://matomo', authToken: '', }, keycloak: { enableLogin: true, realm: 'edp', url: 'https://www.keycloak.com', 'ssl-required': 'external', clientId: 'edp-ui', 'public-client': true, 'verify-token-audience': true, 'use-resource-role-mappings': true, 'confidential-port': 0, }, rtp: { grand_type: 'urn:ietf:params:oauth:grant-type:uma-ticket', audience: 'piveau-hub', }, images: { headerLogos: [ { src: 'https://i.imgur.com/lgtG4zB.png', // href: 'https://my-url.de'(optional) // target: '_blank'(optional) description: 'Logo', height: '60px', width: 'auto', }, ], footerLogos: [], }, locale: 'en', fallbackLocale: 'en', services: { catalogueService, datasetService, distributionService, datastoreService, gazetteerService, uploadService, authService, }, themes: { header: 'dark', }, routerOptions: { base: '', mode: 'history', }, navigation: { topnav: { main: { home: { // href: 'https://link-to-external-url.com' (optional) // target: '_self', show: true, }, data: { show: true, }, maps: { show: false, }, about: { show: false, }, append: [ { href: 'https://www.fokus.fraunhofer.de/datenschutz', // icon: 'rowing', target: '_self', title: 'Privacy Policy', }, { href: 'https://www.fokus.fraunhofer.de/9663f8cb2d267d4b', // icon: 'rowing', target: '_self', title: 'Imprint', }, ], icons: false, }, sub: { privacyPolicy: { show: false, href: 'https://www.fokus.fraunhofer.de/datenschutz', target: '_self', }, imprint: { show: false, href: 'https://www.fokus.fraunhofer.de/9663f8cb2d267d4b', target: '_self', }, }, }, }, };
javascript
14
0.546253
79
23.890756
119
starcoderdata
#pragma once #include #include #include namespace cuda { struct launchInfo { dim3 blocks, threads; int width, height; }; launchInfo optimumLaunch(void* kernel, int width, int height, int datasetSize); template<typename K, typename... Args> cudaError_t start(K kernel, launchInfo& launch, Args&&... args) { kernel<<<launch.blocks, launch.threads>>>(launch, std::forward return cudaDeviceSynchronize(); } }
c
11
0.640152
87
21.041667
24
starcoderdata
#include "Pipeline.h" #include #include #include namespace SnekVk { Pipeline::Pipeline( VulkanDevice& device, const char* vertFilePath, const char* fragFilePath, const PipelineConfigInfo& configInfo) : device{device} { CreateGraphicsPipeline(vertFilePath, fragFilePath, configInfo); } Pipeline::~Pipeline() { vkDestroyShaderModule(device.Device(), vertShader, nullptr); vkDestroyShaderModule(device.Device(), fragShader, nullptr); vkDestroyPipeline(device.Device(), graphicsPipeline, nullptr); } FileData Pipeline::ReadFile(const char* filePath) { std::ifstream file { filePath, std::ios::ate | std::ios::binary }; SNEK_ASSERT(file.is_open(), std::string("Could not find file: ") + filePath); u32 size = static_cast char* buffer = new char[size]; file.seekg(0); file.read(buffer, size); file.close(); return { buffer, size }; } void Pipeline::CreateGraphicsPipeline( char const* vertFilePath, char const* fragFilePath, const PipelineConfigInfo& configInfo) { SNEK_ASSERT(configInfo.pipelineLayout != VK_NULL_HANDLE, "Cannot create graphics pipeline: no pipeline config provided in configInfo"); SNEK_ASSERT(configInfo.renderPass != VK_NULL_HANDLE, "Cannot create graphics pipeline: no renderpass config provided in configInfo"); auto vertCode = ReadFile(vertFilePath); auto fragCode = ReadFile(fragFilePath); std::cout << "Vert Size: " << vertCode.bufferSize << std::endl; std::cout << "Frag Size: " << fragCode.bufferSize << std::endl; CreateShaderModule(vertCode, OUT &vertShader); CreateShaderModule(fragCode, OUT &fragShader); std::cout << "create shader module" << std::endl; VkPipelineViewportStateCreateInfo viewportCreateInfo{}; viewportCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewportCreateInfo.viewportCount = 1; viewportCreateInfo.pViewports = &configInfo.viewport; viewportCreateInfo.scissorCount = 1; viewportCreateInfo.pScissors = &configInfo.scissor; VkPipelineShaderStageCreateInfo shaderStages[2]; shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; shaderStages[0].module = vertShader; shaderStages[0].pName = "main"; shaderStages[0].flags = 0; shaderStages[0].pNext = nullptr; shaderStages[0].pSpecializationInfo = nullptr; shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; shaderStages[1].module = fragShader; shaderStages[1].pName = "main"; shaderStages[1].flags = 0; shaderStages[1].pNext = nullptr; shaderStages[0].pSpecializationInfo = nullptr; VkPipelineVertexInputStateCreateInfo vertexInputCreateInfo{}; vertexInputCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vertexInputCreateInfo.vertexAttributeDescriptionCount = 0; vertexInputCreateInfo.vertexBindingDescriptionCount = 0; vertexInputCreateInfo.pVertexAttributeDescriptions = nullptr; vertexInputCreateInfo.pVertexBindingDescriptions = nullptr; VkGraphicsPipelineCreateInfo pipelineCreateInfo{}; pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipelineCreateInfo.stageCount = 2; pipelineCreateInfo.pStages = shaderStages; pipelineCreateInfo.pVertexInputState = &vertexInputCreateInfo; pipelineCreateInfo.pInputAssemblyState = &configInfo.inputAssemblyInfo; pipelineCreateInfo.pViewportState = &viewportCreateInfo; pipelineCreateInfo.pRasterizationState = &configInfo.rasterizationInfo; pipelineCreateInfo.pMultisampleState = &configInfo.multisampleInfo; pipelineCreateInfo.pColorBlendState = &configInfo.colorBlendInfo; pipelineCreateInfo.pDynamicState = nullptr; pipelineCreateInfo.layout = configInfo.pipelineLayout; pipelineCreateInfo.renderPass = configInfo.renderPass; pipelineCreateInfo.subpass = configInfo.subPass; pipelineCreateInfo.basePipelineHandle = VK_NULL_HANDLE; pipelineCreateInfo.basePipelineIndex = -1; SNEK_ASSERT(vkCreateGraphicsPipelines(device.Device(), VK_NULL_HANDLE, 1, &pipelineCreateInfo, nullptr, OUT &graphicsPipeline) == VK_SUCCESS, "Failed to create graphics pipeline!") std::cout << "CREATED" << std::endl; DestroyFileData(vertCode); DestroyFileData(fragCode); std::cout << "CREATED" << std::endl; } void Pipeline::CreateShaderModule(struct FileData fileData, VkShaderModule* shaderModule) { VkShaderModuleCreateInfo createInfo {}; createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; createInfo.codeSize = fileData.bufferSize; createInfo.pCode = reinterpret_cast<const u32*>(fileData.buffer); SNEK_ASSERT(vkCreateShaderModule(device.Device(), &createInfo, nullptr, OUT shaderModule) == VK_SUCCESS, "Failed to create shader module!"); } PipelineConfigInfo Pipeline::DefaultPipelineConfig(u32 width, u32 height) { PipelineConfigInfo configInfo {}; configInfo.inputAssemblyInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; configInfo.inputAssemblyInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; configInfo.inputAssemblyInfo.primitiveRestartEnable = VK_FALSE; configInfo.viewport.x = 0.0f; configInfo.viewport.y = 0.0f; configInfo.viewport.width = static_cast configInfo.viewport.height = static_cast configInfo.viewport.minDepth = 0.0f; configInfo.viewport.maxDepth = 1.0f; configInfo.scissor.offset = {0, 0}; configInfo.scissor.extent = {width, height}; configInfo.rasterizationInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; configInfo.rasterizationInfo.depthClampEnable = VK_FALSE; configInfo.rasterizationInfo.rasterizerDiscardEnable = VK_FALSE; configInfo.rasterizationInfo.polygonMode = VK_POLYGON_MODE_FILL; configInfo.rasterizationInfo.lineWidth = 1.0f; configInfo.rasterizationInfo.cullMode = VK_CULL_MODE_NONE; configInfo.rasterizationInfo.frontFace = VK_FRONT_FACE_CLOCKWISE; configInfo.rasterizationInfo.depthBiasEnable = VK_FALSE; configInfo.rasterizationInfo.depthBiasConstantFactor = 0.0f; configInfo.rasterizationInfo.depthBiasClamp = 0.0f; configInfo.rasterizationInfo.depthBiasSlopeFactor = 0.0f; configInfo.multisampleInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; configInfo.multisampleInfo.sampleShadingEnable = VK_FALSE; configInfo.multisampleInfo.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; configInfo.multisampleInfo.minSampleShading = 1.0f; configInfo.multisampleInfo.pSampleMask = nullptr; configInfo.multisampleInfo.alphaToCoverageEnable = VK_FALSE; configInfo.multisampleInfo.alphaToOneEnable = VK_FALSE; configInfo.colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; configInfo.colorBlendAttachment.blendEnable = VK_FALSE; configInfo.colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; configInfo.colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; configInfo.colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; configInfo.colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; configInfo.colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; configInfo.colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; configInfo.colorBlendInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; configInfo.colorBlendInfo.logicOpEnable = VK_FALSE; configInfo.colorBlendInfo.logicOp = VK_LOGIC_OP_COPY; configInfo.colorBlendInfo.attachmentCount = 1; configInfo.colorBlendInfo.pAttachments = &configInfo.colorBlendAttachment; configInfo.colorBlendInfo.blendConstants[0] = 0.0f; configInfo.colorBlendInfo.blendConstants[1] = 0.0f; configInfo.colorBlendInfo.blendConstants[2] = 0.0f; configInfo.colorBlendInfo.blendConstants[3] = 0.0f; configInfo.depthStencilInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; configInfo.depthStencilInfo.depthTestEnable = VK_TRUE; configInfo.depthStencilInfo.depthWriteEnable = VK_TRUE; configInfo.depthStencilInfo.depthCompareOp = VK_COMPARE_OP_LESS; configInfo.depthStencilInfo.depthBoundsTestEnable = VK_FALSE; configInfo.depthStencilInfo.minDepthBounds = 0.0f; configInfo.depthStencilInfo.maxDepthBounds = 1.0f; configInfo.depthStencilInfo.stencilTestEnable = VK_FALSE; configInfo.depthStencilInfo.front = {}; configInfo.depthStencilInfo.back = {}; return configInfo; } void DestroyFileData(FileData& data) { delete [] data.buffer; } }
c++
13
0.702191
135
44.009259
216
starcoderdata
namespace PdfCraft.Fonts.TrueType.Parsing.Tables.Os2 { public class Os2 { public ushort Version { get; set; } public short XAvgCharWidth { get; set; } public ushort UsWeightClass { get; set; } public ushort UsWidthClass { get; set; } public short FsType { get; set; } public short YSubscriptXSize { get; set; } public short YSubscriptYSize { get; set; } public short YSubscriptXOffset { get; set; } public short YSubscriptYOffset { get; set; } public short YSuperscriptXSize { get; set; } public short YSuperscriptYSize { get; set; } public short YSuperscriptXOffset { get; set; } public short YSuperscriptYOffset { get; set; } public short YStrikeoutSize { get; set; } public short YStrikeoutPosition { get; set; } public short SFamilyClass { get; set; } public byte[] Panose { get; set; } public byte[] UlCharRange { get; set; } public string AchVendID { get; set; } public ushort FsSelection { get; set; } public ushort FsFirstCharIndex { get; set; } public ushort FsLastCharIndex { get; set; } public short STypoAscender { get; set; } public short STypoDescender { get; set; } public short STypoLineGap { get; set; } public ushort UsWinAscent { get; set; } public ushort UsWinDescent { get; set; } public uint UlCodePageRange1 { get; set; } public uint UlCodePageRange2 { get; set; } public short SCapHeight { get; set; } } }
c#
8
0.618205
54
42.972222
36
starcoderdata
from __future__ import unicode_literals from django.db import models class analytics(models.Model): id = models.AutoField(primary_key=True) url_id = models.IntegerField() created_at = models.DateTimeField() os = models.CharField(max_length=64, blank=True, null=True) browser = models.CharField(max_length=256, blank=True, null=True) device = models.CharField(max_length=64, blank=True, null=True) referer = models.CharField(max_length=2048, blank=True, null=True) class Meta: managed = False db_table = 'analytics' class count(models.Model): id = models.AutoField(primary_key=True) count = models.IntegerField() url_id = models.IntegerField() created_at = models.DateTimeField() class Meta: managed = False db_table = 'count' class media(models.Model): id = models.AutoField(primary_key=True) shown_name = models.CharField(unique=True, max_length=64) name = models.CharField(unique=True, max_length=64) created_at = models.DateTimeField() class Meta: managed = False db_table = 'media' class url(models.Model): id = models.AutoField(primary_key=True) hash = models.CharField(max_length=32) long_url = models.CharField(db_column='longUrl', max_length=2048, blank=True, null=True) title = models.CharField(max_length=512, blank=True, null=True) type = models.IntegerField() description = models.TextField(blank=True, null=True) show_redirection = models.IntegerField(db_column='showRedirection', default=0) show_utm = models.IntegerField(db_column='showUtm', default=1) created_at = models.DateTimeField() tags = models.CharField(max_length=32, null=True) class Meta: managed = False db_table = 'url' def tags_to_bool_array(self): if self.tags is None: return [] str_arr = self.tags.split(',') return str_arr def all_tag_array(self): if self.tags is None: return [False] * 8 arr = [] str_arr = self.tags.split(',') for i in range(1, 9): arr.append(i in str_arr) return arr class url_link(models.Model): id = models.AutoField(primary_key=True) link = models.CharField(max_length=2048) created_at = models.DateTimeField() media_id = models.IntegerField() url_id = models.IntegerField() class Meta: managed = False db_table = 'url_link' unique_together = (('url_id', 'media_id'))
python
11
0.64454
92
28.616279
86
starcoderdata