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
public String senseJewelColor() { while (opModeIsActive()) { int red = af.colorSensor.red(); int blue = af.colorSensor.blue(); int green = af.colorSensor.green(); // sense color blue if (blue >= 4 && red <= 1 && green <= 1) { return "BLUE"; } // sense color red if (red >= 4 && blue <= 1 && green <= 1) { return "RED"; } telemetry.addData("values ", blue); telemetry.update(); } return "NOTHING"; }
java
10
0.42
54
20.464286
28
inline
using System.Collections.Generic; using Addiscode.SudokuCore.Models; namespace Addiscode.SudokuGenerator.Models { public class ConnectedLocations { public ConnectedLocations() { ColoumnConnections = new List RowConnections = new List InnerBlockConnections = new List } public List ColoumnConnections { get; set; } public List RowConnections { get; set; } public List InnerBlockConnections { get; set; } } }
c#
12
0.630363
65
28.35
20
starcoderdata
from unittest.mock import MagicMock from django import forms from django.template import TemplateSyntaxError from ralph.admin.mixins import RalphAdminFormMixin from ralph.deployment.models import PrebootConfiguration, PrebootItemType from ralph.deployment.utils import _render_configuration class PrebootConfigurationForm(RalphAdminFormMixin, forms.ModelForm): class Meta: model = PrebootConfiguration fields = ('name', 'type', 'configuration') def is_valid(self): is_valid = super().is_valid() try: _render_configuration( self.cleaned_data.get('configuration', ''), MagicMock(), disable_reverse=True ) except TemplateSyntaxError as error: self.add_error('configuration', error) is_valid = False return is_valid def clean_configuration(self): configuration_type = self.cleaned_data.get('type') configuration = self.cleaned_data.get('configuration') if configuration_type in ( PrebootItemType.kickstart.id, PrebootItemType.preseed.id ): if 'done_url' not in configuration: raise forms.ValidationError( 'Please specify {{ done_url }} (e.g. curl {{ done_url }})' ) return configuration
python
13
0.650281
78
35.512821
39
starcoderdata
public static void main(String... args) throws IOException, InterruptedException, ExecutionException { // Replace these with your client id and secret final String clientId = "your client id"; final String clientSecret = "your client secret"; final OAuth20Service service = new ServiceBuilder(clientId) .apiSecret(clientSecret) .scope("wall,offline") // replace with desired scope .callback("http://your.site.com/callback") .build(VkontakteApi.instance()); System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ==="); System.out.println(); final OAuth2AccessToken accessToken = service.getAccessTokenClientCredentialsGrant(); System.out.println("Got the Access Token!"); System.out.println(accessToken.getRawResponse()); System.out.println(); System.out.println("Thats it man! Go and build something awesome with ScribeJava! :)"); }
java
11
0.648649
102
49
20
inline
/* * Copyright 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package main import ( "fmt" "io/ioutil" "os" "os/exec" "os/signal" "path/filepath" "sync" "syscall" // "syscall" flag "github.com/spf13/pflag" coreapiv1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" coreclientv1 "k8s.io/client-go/kubernetes/typed/core/v1" "github.com/jimmidyson/kubernetes-run-and-reflect/pkg/kubernetes" "github.com/jimmidyson/kubernetes-run-and-reflect/pkg/version" ) var ( kubeconfig string command []string targetResourceKind string targetResourceName string targetResourceNamespace string files []string ) func main() { flag.StringVar(&kubeconfig, "kubeconfig", "", "Path to kubeconfig file with authorization and master location information.") flag.StringVar(&targetResourceName, "target-resource-name", "", "Name of the target resource to reflect the file contents to.") flag.StringVar(&targetResourceNamespace, "target-resource-namespace", "", "Namespace of the target resource to reflect the file contents to.") flag.Var(newResourceKindValue("secret", &targetResourceKind), "target-resource-kind", "Kind of the target resource to reflect the file contents to.") flag.StringArrayVar(&files, "file", nil, "Files to reflect to the target resource.") versionFlag := flag.Bool("version", false, "Print version information and quit") flag.Parse() if *versionFlag { fmt.Fprintln(os.Stderr, version.Get().GitVersion) os.Exit(0) } if targetResourceName == "" { fmt.Fprintln(os.Stderr, "Missing required flag: --target-resource-name") flag.Usage() os.Exit(1) } if targetResourceNamespace == "" { fmt.Fprintln(os.Stderr, "Missing required flag: --target-resource-namespace") flag.Usage() os.Exit(1) } if len(files) == 0 { fmt.Fprintln(os.Stderr, "Missing required flag: --file") flag.Usage() os.Exit(1) } argsLenAtDash := flag.CommandLine.ArgsLenAtDash() if flag.CommandLine.ArgsLenAtDash() == -1 { fmt.Fprintln(os.Stderr, "Missing command: specify after --") flag.Usage() os.Exit(1) } commandArgs := flag.CommandLine.Args()[argsLenAtDash:] if len(commandArgs) == 0 { fmt.Fprintln(os.Stderr, "Missing command: specify after --") flag.Usage() os.Exit(1) } kubernetesClient, err := kubernetes.CoreClient(kubeconfig) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create Kubernetes client: %v\n", err) os.Exit(1) } var ( cmd *exec.Cmd pLock sync.RWMutex ) sigc := make(chan os.Signal, 1) signal.Notify(sigc, os.Interrupt, syscall.SIGTERM) go func() { s := <-sigc fmt.Fprintf(os.Stderr, "Caught signal: %s\n", s) pLock.Lock() defer pLock.Unlock() if cmd != nil && cmd.Process != nil{ // Signal child process, if it succeeds then use normal wait, otherwise handle // the signal in this process. err := cmd.Process.Signal(s) if err == nil { return } fmt.Fprintf(os.Stderr, "Failed to signal child process: %v\n", err) } os.Exit(1) }() fmt.Fprintf(os.Stderr, "Starting: %v\n", commandArgs) pLock.Lock() cmd = exec.Command(commandArgs[0], commandArgs[1:]...) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.SysProcAttr = &syscall.SysProcAttr{ Setpgid: true, Pgid: 0, } if err := cmd.Start(); err != nil { fmt.Fprintf(os.Stderr, "Failed to start command: %v\n", err) os.Exit(1) } done := make(chan error, 1) go func() { done <- cmd.Wait() }() pLock.Unlock() exitCode := 1 err = <- done if err != nil { if exitError, ok := err.(*exec.ExitError); ok { if status, ok := cmd.ProcessState.Sys().(syscall.WaitStatus); ok && status.Signaled(){ fmt.Fprintf(os.Stderr, "Command exited with with signal: %v\n", status.Signal()) os.Exit(1) } fmt.Fprintf(os.Stderr, "Command exited with error: %v\n", exitError.ExitCode()) exitCode = exitError.ExitCode() } } else { fmt.Fprintf(os.Stderr, "Command exited with exit code: %d\n", cmd.ProcessState.ExitCode()) exitCode = cmd.ProcessState.ExitCode() } if exitCode == 0 { fileContentsMap := make(map[string][]byte, len(files)) for _, f := range files { contents, err := ioutil.ReadFile(f) if err != nil { fmt.Fprintf(os.Stderr, "Failed to read file: %s\n", f) os.Exit(1) } fileContentsMap[filepath.Base(f)] = contents } switch targetResourceKind { case "configmap": err = createOrUpdateConfigMap( targetResourceNamespace, targetResourceName, fileContentsMap, kubernetesClient, ) case "secret": err = createOrUpdateSecret( targetResourceNamespace, targetResourceName, fileContentsMap, kubernetesClient, ) } if err != nil { fmt.Fprintf(os.Stderr, "%v\n", err) os.Exit(1) } fmt.Fprintf(os.Stderr, "Successfully created/updated %s %s/%s", targetResourceKind, targetResourceNamespace, targetResourceName) } os.Exit(exitCode) } func createOrUpdateSecret(namespace, name string, newContents map[string][]byte, client coreclientv1.CoreV1Interface) error { secretsClient := client.Secrets(namespace) secret, err := secretsClient.Get(name, metav1.GetOptions{}) isNewSecret := false if err != nil { if !errors.IsNotFound(err) { return fmt.Errorf("failed to get secret %s/%s: %v", namespace, name, err) } isNewSecret = true secret = &coreapiv1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: name, }, } } if secret.Data == nil { secret.Data = make(map[string][]byte, len(newContents)) } for k, v := range newContents { secret.Data[k] = v } if isNewSecret { if _, err := secretsClient.Create(secret); err != nil { return fmt.Errorf("failed to create new secret %s/%s: %v", namespace, name, err) } return nil } if _, err := secretsClient.Update(secret); err != nil { return fmt.Errorf("failed to update secret %s/%s: %v", namespace, name, err) } return nil } func createOrUpdateConfigMap(namespace, name string, newContents map[string][]byte, client coreclientv1.CoreV1Interface) error { configmapClient := client.ConfigMaps(namespace) configmap, err := configmapClient.Get(name, metav1.GetOptions{}) isNewSecret := false if err != nil { if !errors.IsNotFound(err) { return fmt.Errorf("failed to get secret %s/%s: %v", namespace, name, err) } isNewSecret = true configmap = &coreapiv1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: name, }, } } if configmap.Data == nil { configmap.Data = make(map[string]string, len(newContents)) } for k, v := range newContents { configmap.Data[k] = string(v) } if isNewSecret { if _, err := configmapClient.Create(configmap); err != nil { return fmt.Errorf("failed to create new configmap %s/%s: %v", namespace, name, err) } return nil } if _, err := configmapClient.Update(configmap); err != nil { return fmt.Errorf("failed to update configmap %s/%s: %v", namespace, name, err) } return nil } // -- resourceKindValue Value type resourceKindValue string func newResourceKindValue(val string, p *string) *resourceKindValue { *p = val return (*resourceKindValue)(p) } func (s *resourceKindValue) Set(val string) error { if val == "secret" || val == "configmap" { *s = resourceKindValue(val) return nil } return fmt.Errorf("invalid resource kind, must be one of %v", []string{"secret", "configmap"}) } func (s *resourceKindValue) Type() string { return "resourcekind" } func (s *resourceKindValue) String() string { return string(*s) }
go
16
0.686826
150
26.445578
294
starcoderdata
func TestReceiveContextCancelled(t *testing.T) { q, cleanup := newQ(t) defer cleanup() ctx, cancel := context.WithCancel(context.Background()) done := make(chan struct{}) go func() { defer close(done) q.Receive(ctx) }() cancel() <-done // blocks forever if the Receive never gets cancelled }
go
10
0.688525
61
20.857143
14
inline
package strings; // BEGIN main public class ForEachChar { public static void main(String[] args) { String s = "Hello world"; // for (char ch : s) {...} Does not work, in Java 7 for (char ch : s.toCharArray()) { System.out.println(ch); } } } // END main
java
10
0.602041
85
27
14
starcoderdata
package packed.internal.hooks.var2; import java.lang.reflect.AnnotatedType; public class TmpExecutable { AnnotatedType[] annotatedParameterTypes; AnnotatedType annotatationOf(int index) { return annotatedParameterTypes[index]; } }
java
7
0.727599
46
18.928571
14
starcoderdata
<?php error_reporting(E_ALL | E_STRICT); ini_set('display_errors', 1); $root = realpath(dirname(dirname(__FILE__))); $library = "$root/library"; $path = array($library, get_include_path()); set_include_path(implode(PATH_SEPARATOR, $path)); require_once $root . '/vendor/autoload.php'; use ReceiptValidator\GooglePlay\Validator as PlayValidator; // google authencation $client_id = 'xxxxxxx'; $client_secret = 'xxxx'; $refresh_token = 'xxxx'; // receipt data $package_name = 'com.example'; $product_id = 'coins_10000'; $purchase_token = 'xxxxxx'; $validator = new PlayValidator(['client_id' => $client_id, 'client_secret' => $client_secret, 'refresh_token' => $refresh_token]); try { $response = $validator->setPackageName($package_name)->setProductId($product_id)->setPurchaseToken($purchase_token)->validate(); } catch (Exception $e) { echo 'got error = ' . $e->getMessage() . PHP_EOL; } print_R($response);
php
12
0.700099
130
27
36
starcoderdata
import React, { useState, useEffect } from "react"; import PropTypes from "prop-types"; import { gql } from "apollo-boost"; import Form from "react-bootstrap/Form"; import { useLazyQuery, useMutation } from "@apollo/react-hooks"; import ContentLoading from "../common/ContentLoading"; import FormField from "../common/FormField"; import { COMPONENT_TYPE } from "./choices"; const COMPONENT = gql` query getComponent($filters: ComponentFilter) { components(filters: $filters) { objects { component_type model serial_number catalog_number } } } `; const ADD_COMPONENT = gql` mutation AddComponent($data: ComponentInput!) { addComponent(data: $data) { status errors { field message } object { id get_component_type_display model serial_number catalog_number } } } `; const UPDATE_COMPONENT = gql` mutation UpdateComponent($id: ID!, $data: ComponentInput!) { updateComponent(id: $id, data: $data) { status errors { field message } object { id get_component_type_display model serial_number catalog_number } } } `; const ComponentForm = (props) => { const [component, setComponent] = useState({ component_type: props.initial ? props.initial.component_type : null, model: props.initial ? props.initial.model : null, serial_number: props.initial ? props.initial.serial_number : null, catalog_number: props.initial ? props.initial.catalog_number : null, }); const [errors, setErrors] = useState({ component_type: [], model: [], serial_number: [], catalog_number: [], }); const [isLoading, setIsLoading] = useState(true); const [getComponent, { loading }] = useLazyQuery(COMPONENT, { variables: { filters: { id: props.componentId } }, fetchPolicy: "no-cache", onCompleted: (data) => { const object = data.components.objects[0]; setComponent({ component_type: object.component_type, model: object.model, serial_number: object.serial_number, catalog_number: object.catalog_number, }); }, }); const [addComponent] = useMutation(ADD_COMPONENT, { onCompleted: (data) => { if (data.addComponent.status === true) props.onSaved(data.addComponent.object); else { let newErrors = {}; data.addComponent.errors.forEach((error) => { if (newErrors[error.field]) newErrors[error.field].push(error.message); else newErrors[error.field] = [error.message]; }); setErrors(newErrors); } }, }); const [updateComponent] = useMutation(UPDATE_COMPONENT, { onCompleted: (data) => { if (data.updateComponent.status === true) props.onSaved(data.updateComponent.object); else { let newErrors = {}; data.updateComponent.errors.forEach((error) => { if (newErrors[error.field]) newErrors[error.field].push(error.message); else newErrors[error.field] = [error.message]; }); setErrors(newErrors); } }, }); useEffect(() => { if (props.componentId) getComponent(); setIsLoading(false); }, [props.componentId]); const handleChanges = (e) => { setComponent({ ...component, [e.target.name]: e.target.type === "number" ? (e.target.value ? Number(e.target.value) : null) : e.target.value, }); }; const onSubmit = (e) => { e.preventDefault(); if (props.componentId) updateComponent({ variables: { id: props.componentId, data: component } }); else addComponent({ variables: { data: component } }); }; if (isLoading || loading) return <ContentLoading />; return ( <Form id="component-form" onSubmit={onSubmit} noValidate> <Form.Group controlId="formType"> <FormField label="Rodzaj podzespłu:" name="component_type" value={component.component_type} onChange={handleChanges} errors={errors.component_type} type="select" options={COMPONENT_TYPE} /> <Form.Group controlId="formModel"> <FormField label="Model:" name="model" value={component.model} onChange={handleChanges} errors={errors.model} /> <Form.Group controlId="formSerial"> <FormField label="Numer seryjny:" name="serial_number" value={component.serial_number} onChange={handleChanges} errors={errors.serial_number} /> <Form.Group controlId="formCatalog"> <FormField label="Numer katalogowy:" name="catalog_number" value={component.catalog_number} onChange={handleChanges} errors={errors.catalog_number} /> ); }; ComponentForm.propTypes = { componentId: PropTypes.string, initial: PropTypes.object, onSaved: PropTypes.func, }; export default ComponentForm;
javascript
27
0.507632
111
30.906736
193
starcoderdata
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // User/transparent types for RunClassConstructor tests using System; using System.Security; public class Watcher { public static bool f_hasRun = false; public static string lastTypeParameter = ""; } public class GenericWithCctor { //public static string myTypeName = // typeof(T).FullName; static GenericWithCctor() { Watcher.lastTypeParameter = typeof(T).FullName; Watcher.f_hasRun = true; } } public class NoCctor { } public class NestedContainer { // "nested public" public class NestedPublicHasCctor { static NestedPublicHasCctor() { Watcher.f_hasRun = true; } } // "nested private" private class NestedPrivateHasCctor { static NestedPrivateHasCctor() { Watcher.f_hasRun = true; } } // "nested assembly" internal class NestedAssemHasCctor { static NestedAssemHasCctor() { Watcher.f_hasRun = true; } } // "nested famorassem" internal protected class NestedFamOrAssemHasCctor { static NestedFamOrAssemHasCctor() { Watcher.f_hasRun = true; } } } class PrivateHasCctor { static PrivateHasCctor() { Watcher.f_hasRun = true; } } public class HasCctor { static HasCctor() { Watcher.f_hasRun = true; } } public class CriticalCctor { [System.Security.SecurityCritical] static CriticalCctor() { Watcher.f_hasRun = true; } } // base-class of (...); duplicate of HasCctor so we guarantee that it hasn't // been initialized when we call its subclass cctor. public class BaseWithCctor { static BaseWithCctor() { Watcher.f_hasRun = true; } } public class CctorInBase : BaseWithCctor { } public class ThrowingCctor { static ThrowingCctor() { throw new ArgumentException("I have an argument."); } }
c#
10
0.62968
76
18.389381
113
starcoderdata
/** Copyright 2017-2020 CNRS-AIST JRL and CNRS-UM LIRMM */ #include #include #include #include using namespace Eigen; namespace { /** max value of two sorted vectors, where the second one can be empty*/ DenseIndex optionalMax(const std::vector & v1, const std::vector & v2) { assert(v1.size() > 0); if(v2.empty()) { return v1.back(); } else { return std::max(v1.back(), v2.back()); } } } // namespace namespace tvm { namespace hint { namespace internal { DiagonalCalculator::DiagonalCalculator(DenseIndex first, DenseIndex size) : first_(first), size_(size) { if(first < 0) { throw std::runtime_error("first must be non-negative."); } if(size < -1) { throw std::runtime_error("Invalid size."); } } DiagonalCalculator::DiagonalCalculator(const std::vector & nnzRows, const std::vector & zeroRows) : first_(-1), size_(-1), nnz_(nnzRows), zeros_(zeroRows) { if(nnz_.empty()) { throw std::runtime_error("There should be at least one non-zero row."); } std::sort(nnz_.begin(), nnz_.end()); std::sort(zeros_.begin(), zeros_.end()); std::vector appear(optionalMax(nnz_, zeros_) + 1, false); for(auto i : nnz_) { if(i < 0) { throw std::runtime_error("Indices must be non-negative."); } if(appear[static_cast { throw std::runtime_error("Each index must be unique."); } else { appear[i] = true; } } for(auto i : zeros_) { if(i < 0) { throw std::runtime_error("Indices must be non-negative."); } if(appear[static_cast { throw std::runtime_error("Each index of nnzRows and zeroRows must be unique."); } else { appear[i] = true; } } } std::unique_ptr DiagonalCalculator::impl_( const std::vector & cstr, const std::vector & x, int rank) const { if(first_ >= 0) { return std::unique_ptr Impl(cstr, x, rank, first_, size_)); } else { return std::unique_ptr Impl(cstr, x, rank, nnz_, zeros_)); } } DiagonalCalculator::Impl::Impl(const std::vector & cstr, const std::vector & x, int rank, DenseIndex first, DenseIndex size) : SubstitutionCalculatorImpl(cstr, x, rank), first_(first), size_(size) { if(!isSimple()) { throw std::runtime_error( "This calculator is only for the substitution of a single variable through a single constraint."); } if(size == -1) { size_ = x.front()->size() - first; } if(size_ != rank) { throw std::runtime_error("The number of non-zero rows is not consistent with the rank."); } DenseIndex i = 0; for(; i < first; ++i) { cnnz_.push_back(i); } for(DenseIndex j = 0; j < size_; ++i, ++j) { nnz_.push_back(i); } for(; i < n(); ++i) { cnnz_.push_back(i); } build(); } DiagonalCalculator::Impl::Impl(const std::vector & cstr, const std::vector & x, int rank, const std::vector & nnzRows, const std::vector & zeroRows) : SubstitutionCalculatorImpl(cstr, x, rank), first_(-1), size_(0), nnz_(nnzRows), cnnz_(), zeros_(zeroRows) { if(!isSimple()) { throw std::runtime_error( "This calculator is only for the substitution of a single variable through a single constraint."); } if(static_cast zeroRows)) >= n()) { throw std::runtime_error("Some indices are too large for the substitution considered"); } if(static_cast != rank) { throw std::runtime_error("The number of non-zero rows is not consistent with the rank."); } // build cnnz_ for(DenseIndex i = 0; i < nnz_.front(); ++i) { cnnz_.push_back(i); } for(size_t j = 0; j < nnz_.size() - 1; ++j) { for(auto i = nnz_[j] + 1; i < nnz_[j + 1]; ++i) { cnnz_.push_back(i); } } for(auto i = nnz_.back() + 1; i < n(); ++i) { cnnz_.push_back(i); } build(); } void DiagonalCalculator::Impl::update_() { auto A = constraints_[0]->jacobian(*variables_[0]); for(size_t i = 0; i < nnz_.size(); ++i) { inverse_[static_cast = 1. / A(innz_[i], nnz_[i]); } } void DiagonalCalculator::Impl::premultiplyByASharpAndSTranspose_(MatrixRef outA, MatrixRef outS, const MatrixConstRef & in, bool minus) const { // FIXME: optimized version for identity/minus identity // multiplying by A^# if(minus) { for(size_t i = 0; i < nnz_.size(); ++i) { outA.row(nnz_[i]) = -inverse_[static_cast * in.row(innz_[i]); } } else { for(size_t i = 0; i < nnz_.size(); ++i) { outA.row(nnz_[i]) = inverse_[static_cast * in.row(innz_[i]); } } for(auto i : cnnz_) { outA.row(i).setZero(); } // multiplying by S^T for(size_t i = 0; i < zeros_.size(); ++i) { outS.row(static_cast = in.row(zeros_[i]); } } void DiagonalCalculator::Impl::postMultiplyByN_(MatrixRef out, const MatrixConstRef & in, bool add) const { if(add) { for(size_t i = 0; i < cnnz_.size(); ++i) { out.col(static_cast += in.col(cnnz_[i]); } } else { for(size_t i = 0; i < cnnz_.size(); ++i) { out.col(static_cast = in.col(cnnz_[i]); } } } void DiagonalCalculator::Impl::build() { N_.setZero(); for(size_t i = 0; i < cnnz_.size(); ++i) { N_(cnnz_[i], static_cast = 1; } std::vector appearnnz(static_cast false); std::vector appearZero(static_cast false); for(auto i : nnz_) { appearnnz[i] = true; } for(auto i : zeros_) { appearZero[i] = true; } DenseIndex k = 0; for(size_t i = 0; i < static_cast ++i) { if(appearnnz[i]) { innz_.push_back(k); ++k; } else if(appearZero[i]) { ++k; } } inverse_.resize(static_cast } } // namespace internal } // namespace hint } // namespace tvm
c++
23
0.560773
107
22.965157
287
starcoderdata
package services; import models.MatchingInfo; import models.UIScreen; import nlu.SimpleTextInterpreter; import nlu.TextInterpreter; import storage.NavigationGraphStore; import storage.SemanticActionStore; import util.ResultFunction; import util.Utils; import javax.inject.Inject; import javax.inject.Singleton; import java.util.*; import static config.BackendConfiguration.MIN_MATCH_PERCENTAGE_FOR_FUZZY_SCREEN_TITLE_MATCH; @Singleton public class UIScreenManager { private Map<String, UIScreen> uiScreenMap; private Map<String, Set packageNameToScreenIdMap; private Map<String, Set screenTitleToScreenIdMap; private TextInterpreter textInterpreter; private DatabaseBackend databaseBackend; private NavigationGraphStore navigationGraphStore; private SemanticActionStore semanticActionStore; private List uiScreensToDelete; @Inject public UIScreenManager(DatabaseBackend databaseBackend, NavigationGraphStore navigationGraphStore, SemanticActionStore semanticActionStore) { uiScreenMap = new HashMap<>(); packageNameToScreenIdMap = new HashMap<>(); screenTitleToScreenIdMap = new HashMap<>(); textInterpreter = new SimpleTextInterpreter(); this.databaseBackend = databaseBackend; this.navigationGraphStore = navigationGraphStore; this.semanticActionStore = semanticActionStore; this.uiScreensToDelete = new ArrayList<>(); //Start fetch of screens from database and update the hash map here startLoading(); } private void startLoading() { databaseBackend.loadAllScreens((ResultFunction uiScreenList -> { UIScreenManager.this.updateScreenMap(uiScreenList); return null; }); } public void writeScreenToBackend(UIScreen uiScreen) { List screenList = Collections.singletonList(uiScreen); databaseBackend.saveScreensAsync(screenList); } public void commitScreensToBackendAsync() { List screenList = new ArrayList<>(uiScreenMap.values()); databaseBackend.saveScreensAsync(screenList); databaseBackend.deleteScreensAsync(uiScreensToDelete); } private void updateScreenMap(List uiScreenList) { if (uiScreenList == null) { return; } for (UIScreen uiScreen: uiScreenList) { addScreenAdvanced(uiScreen); } } public UIScreen addScreenAdvanced(UIScreen uiScreen) { String screenId = uiScreen.getId(); UIScreen screenInMap = uiScreenMap.get(screenId); if (screenInMap == null) { screenInMap = uiScreen; uiScreenMap.put(screenId, uiScreen); } else { boolean mergeResult = screenInMap.mergeScreen(uiScreen, true); if (!mergeResult) { System.err.print("Screen merge failed for screen getId: " + screenId); } } //Check if a screen exists with same title and empty subtitle -- remove it and merge String screenIdWithEmptySubtitle = UIScreen.getScreenId( uiScreen.getPackageName(), uiScreen.getTitle(), Utils.EMPTY_STRING, uiScreen.getScreenType(), uiScreen.getMatchingInfo().toString()); UIScreen emptySubtitleScreen = uiScreenMap.get(screenIdWithEmptySubtitle); if (emptySubtitleScreen != null && !emptySubtitleScreen.getId().equalsIgnoreCase(screenInMap.getId())) { //Remove the empty subtitle screen screenInMap.mergeScreen(emptySubtitleScreen, false); uiScreenMap.remove(emptySubtitleScreen.getId()); uiScreensToDelete.add(emptySubtitleScreen); } addScreenToPackageMap(screenInMap); addScreenToTitleMap(screenInMap); navigationGraphStore.updateNavigationGraph(screenInMap); semanticActionStore.updateSemanticActionStore(screenInMap); return screenInMap; } public UIScreen getScreen(String packageName, String title, String subTitle, String screenType, MatchingInfo matchingInfo) { if (Utils.nullOrEmpty(matchingInfo.toString())) { return getScreen(packageName, title); } Set screenIdListForTitleAndPackage = screenTitleToScreenIdMap.get(getKeyForTitleMap(title, packageName, screenType)); if (screenIdListForTitleAndPackage != null) { ArrayList screenIdList = new ArrayList<>(screenIdListForTitleAndPackage); if (screenIdList.size() == 1) { //One match only -- bingo return uiScreenMap.get(screenIdList.get(0)); } else { return uiScreenMap.get(UIScreen.getScreenId(packageName, title, subTitle, screenType, matchingInfo.toString())); } } return null; } private UIScreen getScreen(String packageName, String title) { Set uiScreens = new HashSet<>(uiScreenMap.values()); for (UIScreen uiScreen: uiScreens) { if (uiScreen.getPackageName().equalsIgnoreCase(packageName) && uiScreen.getTitle().equalsIgnoreCase(title)) { return uiScreen; } } return null; } public UIScreen getScreen(String id) { return uiScreenMap.get(id); } public Set getAllScreens() { return new HashSet<>(uiScreenMap.values()); } public Set getAllScreensFromDatabase() { return new HashSet<>(databaseBackend.getAllScreens()); } public Set getAllScreensWithoutPaths() { HashSet screenHashSet = new HashSet<>(); for (UIScreen uiScreen: uiScreenMap.values()) { if (uiScreen.getLastStepToCurrentScreen().size() == 0) { screenHashSet.add(uiScreen); } } return screenHashSet; } public UIScreen updateScreen(UIScreen uiScreen) { String id = uiScreen.getId(); if (uiScreenMap.containsKey(id)) { uiScreenMap.put(id, uiScreen); return uiScreen; } return null; } public boolean deleteScreen(String id) { return uiScreenMap.remove(id) != null; } private void addScreenToPackageMap(UIScreen uiScreen) { Set screenList = packageNameToScreenIdMap.get(uiScreen.getPackageName()); if (screenList == null) { screenList = new HashSet<>(); screenList.add(uiScreen.getId()); packageNameToScreenIdMap.put(uiScreen.getPackageName(), screenList); } else if (!screenList.contains(uiScreen.getId())) { screenList.add(uiScreen.getId()); } } private String getKeyForTitleMap(String title, String packageName, String screenType) { String key = title + " " + packageName + " " + screenType; return Utils.sanitizeText(key); } private void addScreenToTitleMap(UIScreen uiScreen) { String keyForTitleMap = getKeyForTitleMap(uiScreen.getTitle(), uiScreen.getPackageName(), uiScreen.getScreenType()); Set screenList = screenTitleToScreenIdMap.get(keyForTitleMap); if (screenList == null) { screenList = new HashSet<>(); screenList.add(uiScreen.getId()); screenTitleToScreenIdMap.put(keyForTitleMap, screenList); } else if (!screenList.contains(uiScreen.getId())) { screenList.add(uiScreen.getId()); } } public UIScreen fuzzyFindTopMatchingScreenId(String keyWords, String packageName, String screenType, MatchingInfo matchingInfo) { final double MAX_GAP_FOR_CONFIDENCE = 0.2; Map<String, Double> confidenceScores = fuzzyFindScreenIds(keyWords, packageName, matchingInfo, MAX_GAP_FOR_CONFIDENCE); for (HashMap.Entry<String, Double> entry : confidenceScores.entrySet()) { UIScreen matchingScreen = uiScreenMap.get(entry.getKey()); if (matchingScreen != null && matchingScreen.getScreenType().equalsIgnoreCase(screenType)) { return matchingScreen; } } return null; } private LinkedHashMap<String, Double> fuzzyFindScreenIds(String keyWords, String packageName, MatchingInfo matchingInfo, double maxGapFromBest) { LinkedHashMap<String, Double> screenIdsToReturn = new LinkedHashMap<>(); HashMap<String, Double> screenIdToConfidenceHashMap = new HashMap<>(); //Search in all screens for this match in a given packageName Set screenIdSet = packageNameToScreenIdMap.get(packageName); if (screenIdSet == null) { return screenIdsToReturn; } double bestMetric = 0; for (String screenId: screenIdSet) { UIScreen uiScreen = uiScreenMap.get(screenId); if (uiScreen == null) { continue; } double totalMetric = textInterpreter.getMatchMetric(keyWords, uiScreen.getTitle(), MIN_MATCH_PERCENTAGE_FOR_FUZZY_SCREEN_TITLE_MATCH); double matchingScore = Utils.getMatchingScore( uiScreen.getMatchingInfo(), matchingInfo, true, matchingInfo.checkIfSystemPackage()); totalMetric = totalMetric * matchingScore; //double matchMetric = textInterpreter.getMatchMetric(keyWords, uiScreen.getTitle()); //double navigationMetric = findBestNavigationStepMetricByKeyWords(keyWords, uiScreen); //double totalMetric = navigationMetric >= 0 ? (navigationMetric + matchMetric) / 2 : matchMetric; if (bestMetric < totalMetric) { bestMetric = totalMetric; } screenIdToConfidenceHashMap.put(screenId, totalMetric); } //Search in all screens navigational elements for this match Map<String, Double> sortedConfidenceHashMap = Utils.sortHashMapByValueDescending(screenIdToConfidenceHashMap); for (HashMap.Entry<String, Double> entry : sortedConfidenceHashMap.entrySet()) { if (entry.getValue() > bestMetric - maxGapFromBest && entry.getValue() > 0) { screenIdsToReturn.put(entry.getKey(), entry.getValue()); } } return screenIdsToReturn; } }
java
16
0.650194
146
40.83004
253
starcoderdata
<?php /* * This file is part of the Jiannei/lumen-api-starter. * * (c) Jiannei * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace App\Providers; use App\Repositories\Enums\CacheEnum; use Illuminate\Auth\EloquentUserProvider as BaseEloquentUserProvider; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Str; class EloquentUserProvider extends BaseEloquentUserProvider { /** * Retrieve a user by their unique identifier. * * @param mixed $identifier * @return \Illuminate\Contracts\Auth\Authenticatable|null */ public function retrieveById($identifier) { $cacheKey = CacheEnum::getCacheKey(CacheEnum::AUTHORIZATION_USER, $identifier); $cacheExpireTime = CacheEnum::getCacheExpireTime(CacheEnum::AUTHORIZATION_USER); return Cache::remember($cacheKey, $cacheExpireTime, function () use ($identifier) { $model = $this->createModel(); return $this->newModelQuery($model) ->where($model->getAuthIdentifierName(), $identifier) ->first(); }); } /** * Retrieve a user by the given credentials. * * @param array $credentials * @return \Illuminate\Contracts\Auth\Authenticatable|null */ public function retrieveByCredentials(array $credentials) { if (empty($credentials) || (count($credentials) === 1 && Str::contains($this->firstCredentialKey($credentials), 'password'))) { return; } // First we will add each credential element to the query as a where clause. // Then we can execute the query and, if we found a user, return it in a // Eloquent User "model" that will be utilized by the Guard instances. $query = $this->newModelQuery(); foreach ($credentials as $key => $value) { if (Str::contains($key, 'password')) { continue; } if (is_array($value) || $value instanceof Arrayable) { $query->whereIn($key, $value); } else { $query->where($key, $value); } } return $query->first(); } }
php
18
0.617746
91
30.289474
76
starcoderdata
/* rand( void ) This file is part of the Public Domain C Library (PDCLib). Permission is granted to use, modify, and / or redistribute at will. */ #include #ifndef REGTEST int rand( void ) { _PDCLIB_seed = _PDCLIB_seed * 1103515245 + 12345; return ( int )( _PDCLIB_seed / 65536 ) % 32768; } #endif #ifdef TEST #include "_PDCLIB_test.h" int main( void ) { int rnd1, rnd2; TESTCASE( ( rnd1 = rand() ) < RAND_MAX ); TESTCASE( ( rnd2 = rand() ) < RAND_MAX ); srand( 1 ); TESTCASE( rand() == rnd1 ); TESTCASE( rand() == rnd2 ); return TEST_RESULTS; } #endif
c
12
0.602524
71
17.114286
35
starcoderdata
'use strict'; let express = require('express'), bodyParser = require('body-parser'), passport = require('passport'), setUpPassport = require('./init/passport'), setUpRoutes = require('./routes'), app = express(); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(passport.initialize()); setUpPassport(passport); setUpRoutes(app,passport); app.listen(8080, () => { console.log('App on 8080'); });
javascript
6
0.693446
44
18.75
24
starcoderdata
# pylint:disable=unused-argument,redefined-outer-name import multiprocessing from collections import Counter import pytest from simcore_service_sidecar import mpi_lock pytest_simcore_core_services_selection = ["redis"] @pytest.fixture def redis_service_config(redis_service) -> None: old_config = mpi_lock.config.CELERY_CONFIG.redis mpi_lock.config.CELERY_CONFIG.redis = redis_service yield mpi_lock.config.CELERY_CONFIG.redis = old_config async def test_mpi_locking(loop, simcore_services, redis_service_config) -> None: cpu_count = 2 assert mpi_lock.acquire_mpi_lock(cpu_count) is True assert mpi_lock.acquire_mpi_lock(cpu_count) is False @pytest.mark.parametrize("process_count, cpu_count", [(1, 3), (32, 4)]) async def test_multiple_parallel_locking( loop, simcore_services, redis_service_config, process_count, cpu_count ) -> None: def worker(reply_queue: multiprocessing.Queue, cpu_count: int) -> None: mpi_lock_acquisition = mpi_lock.acquire_mpi_lock(cpu_count) reply_queue.put(mpi_lock_acquisition) reply_queue = multiprocessing.Queue() for _ in range(process_count): multiprocessing.Process(target=worker, args=(reply_queue, cpu_count)).start() results = [] for _ in range(process_count): results.append(reply_queue.get()) assert len(results) == process_count results = Counter(results) assert results[True] == 1 assert results[False] == process_count - 1
python
13
0.710526
85
28.64
50
starcoderdata
export const FULL_WIDTH = 256 * 16 export const SCREEN_WIDTH = 32 * 16 export const FULL_HEIGHT = 16 * 16 export const SCREEN_HEIGHT = 16 * 16 export const MAIN_BACKGROUND = 'main-background' export const MAP_KEY = 'map' export const LEVEL_2_MAP_KEY = 'level-2-map' export const LEVEL_3_MAP_KEY = 'level-3-map' export const CEMETERY_OBJECTS_KEY = 'cemetery-objects' export const CEMETERY_TILES_KEY = 'cemetery-tiles' export const ENV_TILES_KEY = 'env-tiles' export const CHURCH_TILES_KEY = 'church-tileset' export const TWILIGHT_BW_TILES = 'twilight-bw-tiles' export const TWILIGHT_TILES = 'twilight-tiles' export const STONE_ANGEL_KEY = 'stone-angel' export const CASTLE_EXTERIOR_KEY = 'castle_tileset_part1' export const MAIN_CASTLE = 'main-castle' export const MAIN_CASTLE_DECORATIVE = 'decorative' export const MAIN_CASTLE_ENVIRONMENT = 'environment-objects' export const MAIN_CASTLE_WOOD = 'wood' export const PLAYER_KEY = 'player' export const DEATH_ANIM_KEY = 'please-die' export const ENEMY_KEYS = { HELLCAT: 'hellcat', SKELETON: 'skeleton', SKELETON_BOSS: 'skeleton-boss', BAT: 'bat-flat', WOLF: 'wolf', DIE: 'death', FLAMING_SKULL: 'flaming-skull', SKELETON_WARRIOR: 'skeleton-sword', BANDIT: 'bandit', } export const ENEMY_HP = { [ENEMY_KEYS.SKELETON_BOSS]: 5, [ENEMY_KEYS.SKELETON]: 1, [ENEMY_KEYS.HELLCAT]: 2, [ENEMY_KEYS.FLAMING_SKULL]: 2, [ENEMY_KEYS.BANDIT]: 3, [ENEMY_KEYS.SKELETON_WARRIOR]: 4, } export const MUSIC_SCENES = { INTRO: 'intro-audio', LEVEL1: 'level-1-audio', LEVEL2: 'level-2-audio', LEVEL3: 'level-3-audio', ENDING: 'ending-audio', } export const SCENES = { LEVEL1: 'level-1', LEVEL2: 'level-2', LEVEL3: 'level-3', }
javascript
8
0.708824
60
28.824561
57
starcoderdata
// Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace DaydreamElements.Common { using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class DynamicWindColorEffector { public Transform source; public float targetGrowthSpeed = 0.5f; [HideInInspector] public float growthSpeed = 0.0f; public float decaySpeed = 1.0f; public float maxRadius; float targetRadius = 0.0f; [HideInInspector] public float radius = 0.0f; public float growthSpeedPrewarm = 0.1f; [HideInInspector] public Vector3 position; Vector3 lastPosition; Vector3 posDelta; float velocity; //Values read by global effect system [HideInInspector] public Vector4 effectorProperties; public void DrawGizmos(){ if(source != null) { Gizmos.color = Color.blue; Gizmos.DrawWireSphere(source.position,maxRadius); } } public void Initialize() { lastPosition = position = source.position; velocity = 0.0f; growthSpeed = 0.0f + growthSpeedPrewarm; } public void UpdateEffector() { float dt = Time.deltaTime; //Calculate velocity position = source.position; posDelta = lastPosition - position; velocity = posDelta.magnitude; //Update effector radius velocity = Mathf.Clamp(velocity, 0.0f, 1.0f); targetRadius -= decaySpeed * velocity; growthSpeed -= decaySpeed * dt; growthSpeed = Mathf.Clamp(growthSpeed, 0.0f, targetGrowthSpeed); growthSpeed = Mathf.Lerp(growthSpeed, targetGrowthSpeed, dt); targetRadius += growthSpeed * dt; targetRadius = Mathf.Clamp(targetRadius, 0.001f, maxRadius); radius = Mathf.Lerp(radius, targetRadius, dt); //Save values to be passed to global shader value effectorProperties = new Vector4(position.x, position.y, position.z, radius); //Record position for velocity calculation next frame lastPosition = position; } } }
c#
19
0.694818
83
31.575
80
starcoderdata
func (nice *Nicenshtein) ContainsWord(word string) bool { currentNode := nice.root numRunes := utf8.RuneCountInString(word) runeIndex := 0 for _, runeValue := range word { if numRunes-runeIndex > currentNode.length { return false } childNode, ok := currentNode.children[runeValue] //Current rune not indexed, dead end. if !ok { return false } currentNode = childNode runeIndex++ } //Does this node terminate with the given word? return currentNode.word == word }
go
9
0.701613
57
19.708333
24
inline
/******************************************************************************** ** Form generated from reading UI file 'personaldetails.ui' ** ** Created by: Qt User Interface Compiler version 5.8.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_PERSONALDETAILS_H #define UI_PERSONALDETAILS_H #include #include #include #include #include #include #include #include #include #include #include #include QT_BEGIN_NAMESPACE class Ui_personalDetails { public: QLabel *label; QLabel *label_3; QTextBrowser *textBrowser; QTextBrowser *textBrowser_2; QFrame *line; QLabel *label_2; QFrame *line_2; QFrame *line_3; QLabel *label_4; QTableWidget *tableWidget; QPushButton *pushButton; QPushButton *pushButton_2; QLabel *label_5; QLabel *label_6; QLabel *label_7; QLabel *label_8; QLabel *label_9; QLabel *label_10; QLabel *label_11; QLabel *label_12; QPushButton *pushButton_3; QLabel *label_13; QLineEdit *lineEdit; QLabel *label_14; QLabel *label_15; void setupUi(QDialog *personalDetails) { if (personalDetails->objectName().isEmpty()) personalDetails->setObjectName(QStringLiteral("personalDetails")); personalDetails->resize(1200, 480); label = new QLabel(personalDetails); label->setObjectName(QStringLiteral("label")); label->setGeometry(QRect(30, 50, 81, 21)); label->setStyleSheet(QString::fromUtf8("font: 14pt \"\345\215\216\346\226\207\346\226\260\351\255\217\";")); label_3 = new QLabel(personalDetails); label_3->setObjectName(QStringLiteral("label_3")); label_3->setGeometry(QRect(820, 50, 81, 21)); label_3->setStyleSheet(QString::fromUtf8("font: 14pt \"\345\215\216\346\226\207\346\226\260\351\255\217\";")); textBrowser = new QTextBrowser(personalDetails); textBrowser->setObjectName(QStringLiteral("textBrowser")); textBrowser->setGeometry(QRect(940, 40, 231, 41)); textBrowser->setStyleSheet(QStringLiteral("background-color: rgb(220, 220, 220);")); textBrowser_2 = new QTextBrowser(personalDetails); textBrowser_2->setObjectName(QStringLiteral("textBrowser_2")); textBrowser_2->setGeometry(QRect(150, 40, 111, 41)); textBrowser_2->setStyleSheet(QString::fromUtf8("background-color: rgb(220, 220, 220);\n" "font: 14pt \"\345\256\213\344\275\223\";")); line = new QFrame(personalDetails); line->setObjectName(QStringLiteral("line")); line->setGeometry(QRect(580, 0, 16, 481)); line->setFrameShape(QFrame::VLine); line->setFrameShadow(QFrame::Sunken); label_2 = new QLabel(personalDetails); label_2->setObjectName(QStringLiteral("label_2")); label_2->setGeometry(QRect(30, 130, 121, 31)); label_2->setStyleSheet(QString::fromUtf8("font: 16pt \"\345\215\216\346\226\207\346\226\260\351\255\217\";")); line_2 = new QFrame(personalDetails); line_2->setObjectName(QStringLiteral("line_2")); line_2->setGeometry(QRect(20, 90, 551, 20)); line_2->setFrameShape(QFrame::HLine); line_2->setFrameShadow(QFrame::Sunken); line_3 = new QFrame(personalDetails); line_3->setObjectName(QStringLiteral("line_3")); line_3->setGeometry(QRect(600, 90, 581, 20)); line_3->setFrameShape(QFrame::HLine); line_3->setFrameShadow(QFrame::Sunken); label_4 = new QLabel(personalDetails); label_4->setObjectName(QStringLiteral("label_4")); label_4->setGeometry(QRect(1040, 130, 121, 31)); label_4->setStyleSheet(QString::fromUtf8("font: 16pt \"\345\215\216\346\226\207\346\226\260\351\255\217\";")); tableWidget = new QTableWidget(personalDetails); tableWidget->setObjectName(QStringLiteral("tableWidget")); tableWidget->setGeometry(QRect(930, 170, 250, 200)); tableWidget->setStyleSheet(QString::fromUtf8("font: 14pt \"\346\245\267\344\275\223\";")); pushButton = new QPushButton(personalDetails); pushButton->setObjectName(QStringLiteral("pushButton")); pushButton->setGeometry(QRect(480, 40, 93, 31)); pushButton->setStyleSheet(QString::fromUtf8("font: 75 12pt \"\345\276\256\350\275\257\351\233\205\351\273\221\";")); pushButton_2 = new QPushButton(personalDetails); pushButton_2->setObjectName(QStringLiteral("pushButton_2")); pushButton_2->setGeometry(QRect(1090, 417, 93, 31)); pushButton_2->setStyleSheet(QString::fromUtf8("font: 75 12pt \"\345\276\256\350\275\257\351\233\205\351\273\221\";")); label_5 = new QLabel(personalDetails); label_5->setObjectName(QStringLiteral("label_5")); label_5->setGeometry(QRect(20, 200, 221, 151)); label_5->setStyleSheet(QStringLiteral("border-image: url(:/new/prefix1/Image/58ece79b36818.png);")); label_6 = new QLabel(personalDetails); label_6->setObjectName(QStringLiteral("label_6")); label_6->setGeometry(QRect(310, 200, 221, 151)); label_6->setStyleSheet(QStringLiteral("border-image: url(:/new/prefix1/Image/58ece79b36818.png);")); label_7 = new QLabel(personalDetails); label_7->setObjectName(QStringLiteral("label_7")); label_7->setGeometry(QRect(80, 380, 131, 21)); label_7->setStyleSheet(QString::fromUtf8("font: 12pt \"\345\271\274\345\234\206\";")); label_8 = new QLabel(personalDetails); label_8->setObjectName(QStringLiteral("label_8")); label_8->setGeometry(QRect(350, 380, 151, 21)); label_8->setStyleSheet(QString::fromUtf8("font: 12pt \"\345\271\274\345\234\206\";")); label_9 = new QLabel(personalDetails); label_9->setObjectName(QStringLiteral("label_9")); label_9->setGeometry(QRect(10, 430, 211, 31)); label_9->setStyleSheet(QString::fromUtf8("font: 16pt \"\351\273\221\344\275\223\";")); label_10 = new QLabel(personalDetails); label_10->setObjectName(QStringLiteral("label_10")); label_10->setGeometry(QRect(340, 430, 131, 31)); label_10->setStyleSheet(QString::fromUtf8("font: 16pt \"\351\273\221\344\275\223\";")); label_11 = new QLabel(personalDetails); label_11->setObjectName(QStringLiteral("label_11")); label_11->setGeometry(QRect(230, 430, 51, 31)); label_11->setStyleSheet(QStringLiteral("font: 16pt \"Verdana\";")); label_12 = new QLabel(personalDetails); label_12->setObjectName(QStringLiteral("label_12")); label_12->setGeometry(QRect(470, 430, 72, 31)); label_12->setStyleSheet(QStringLiteral("font: 16pt \"Verdana\";")); pushButton_3 = new QPushButton(personalDetails); pushButton_3->setObjectName(QStringLiteral("pushButton_3")); pushButton_3->setGeometry(QRect(800, 330, 191, 61)); pushButton_3->setStyleSheet(QString::fromUtf8("font: 75 24pt \"\345\276\256\350\275\257\351\233\205\351\273\221\";")); label_13 = new QLabel(personalDetails); label_13->setObjectName(QStringLiteral("label_13")); label_13->setGeometry(QRect(690, 260, 91, 31)); label_13->setStyleSheet(QString::fromUtf8("font: 16pt \"\346\245\267\344\275\223\";")); lineEdit = new QLineEdit(personalDetails); lineEdit->setObjectName(QStringLiteral("lineEdit")); lineEdit->setGeometry(QRect(800, 260, 311, 31)); lineEdit->setStyleSheet(QStringLiteral("font: 14pt \"Verdana\";")); label_14 = new QLabel(personalDetails); label_14->setObjectName(QStringLiteral("label_14")); label_14->setGeometry(QRect(760, 120, 291, 41)); label_14->setStyleSheet(QString::fromUtf8("font: 18pt \"\345\256\213\344\275\223\";")); label_15 = new QLabel(personalDetails); label_15->setObjectName(QStringLiteral("label_15")); label_15->setGeometry(QRect(780, 170, 261, 31)); label_15->setStyleSheet(QString::fromUtf8("font: 18pt \"\345\256\213\344\275\223\";")); retranslateUi(personalDetails); QMetaObject::connectSlotsByName(personalDetails); } // setupUi void retranslateUi(QDialog *personalDetails) { personalDetails->setWindowTitle(QApplication::translate("personalDetails", "Dialog", Q_NULLPTR)); label->setText(QApplication::translate("personalDetails", "\347\224\250\346\210\267\345\220\215\357\274\232", Q_NULLPTR)); label_3->setText(QApplication::translate("personalDetails", "\345\233\242\351\230\237\345\220\215\357\274\232", Q_NULLPTR)); textBrowser->setHtml(QApplication::translate("personalDetails", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" " name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" " style=\" font-family:'SimSun'; font-size:9pt; font-weight:400; font-style:normal;\">\n" "<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:14pt;\">\350\277\205\346\215\267\345\246\202\351\243\216\347\232\204\350\257\276\350\256\276\345\260\217\347\273\204 Q_NULLPTR)); textBrowser_2->setHtml(QApplication::translate("personalDetails", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" " name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" " style=\" font-family:'\345\256\213\344\275\223'; font-size:14pt; font-weight:400; font-style:normal;\">\n" "<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">\351\231\210\351\225\224\346\273\250 Q_NULLPTR)); label_2->setText(QApplication::translate("personalDetails", "\346\225\260\346\215\256\347\273\237\350\256\241\357\274\232", Q_NULLPTR)); label_4->setText(QApplication::translate("personalDetails", "\345\233\242\351\230\237\346\210\220\345\221\230\357\274\232", Q_NULLPTR)); pushButton->setText(QApplication::translate("personalDetails", "\346\263\250\351\224\200", Q_NULLPTR)); pushButton_2->setText(QApplication::translate("personalDetails", "\351\200\200\345\207\272\345\233\242\351\230\237", Q_NULLPTR)); label_5->setText(QString()); label_6->setText(QString()); label_7->setText(QApplication::translate("personalDetails", "\347\225\252\350\214\204\351\222\237\350\265\260\345\212\277\345\233\276", Q_NULLPTR)); label_8->setText(QApplication::translate("personalDetails", "\346\257\217\345\221\250\346\227\245\345\277\227\347\273\237\350\256\241\345\233\276", Q_NULLPTR)); label_9->setText(QApplication::translate("personalDetails", "\346\200\273\350\256\241\344\275\277\347\224\250\347\225\252\350\214\204\351\222\237\357\274\232", Q_NULLPTR)); label_10->setText(QApplication::translate("personalDetails", "\346\200\273\350\256\241\346\227\245\345\277\227\357\274\232", Q_NULLPTR)); label_11->setText(QApplication::translate("personalDetails", "100", Q_NULLPTR)); label_12->setText(QApplication::translate("personalDetails", "10", Q_NULLPTR)); pushButton_3->setText(QApplication::translate("personalDetails", "\347\224\263\350\257\267\345\212\240\345\205\245", Q_NULLPTR)); label_13->setText(QApplication::translate("personalDetails", "\345\233\242\351\230\237\345\217\267\357\274\232", Q_NULLPTR)); label_14->setText(QApplication::translate("personalDetails", "\346\202\250\350\277\230\346\234\252\345\212\240\345\205\245\344\273\273\344\275\225\345\233\242\351\230\237\357\274\201", Q_NULLPTR)); label_15->setText(QApplication::translate("personalDetails", "\345\277\253\346\211\276\344\270\252\345\233\242\351\230\237\345\212\240\345\205\245\345\220\247\357\274\201", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class personalDetails: public Ui_personalDetails {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_PERSONALDETAILS_H
c
13
0.661488
320
58.514151
212
starcoderdata
import unittest from paginaysitioweb import PaginaWeb,SitioWeb class TestClases(unittest.TestCase): def test_SiteWeb(self): self.paginaA = PaginaWeb("www.facebook.com/LuFlores","/Facebook/Users/LuFlores","HTML"," Facebook","lu-flores-facebook",('red social','facebook')) self.paginaB = PaginaWeb("www.facebook.com/LuFlores","/Facebook/Users/LuFlores","HTML"," Facebook","lu-flores-facebook",('red social','facebook')) self.paginaC = PaginaWeb("www.facebook.com/LuFlores","/Facebook/Users/LuFlores","HTML"," Facebook","lu-flores-facebook",('red social','facebook')) self.paginaD = PaginaWeb("www.facebook.com/LuFlores","/Facebook/Users/LuFlores","HTML"," Facebook","lu-flores-facebook",('red social','facebook')) self.paginaE = PaginaWeb("www.facebook.com/LuFlores","/Facebook/Users/LuFlores","HTML"," Facebook","lu-flores-facebook",('red social','facebook')) self.paginaF = PaginaWeb("www.facebook.com/LuFlores","/Facebook/Users/LuFlores","HTML"," Facebook","lu-flores-facebook",('red social','facebook')) self.paginas=(self.paginaA,self.paginaB,self.paginaC,self.paginaD,self.paginaE,self.paginaF) self.sitio = SitioWeb("facebook.com","red social",self.paginas) self.resultado=f"dominio: facebook.com" self.resultado+=f"\ncategoria: red social" self.resultado+=f"\npaginas:\n" self.resultado+=f"\n" self.resultado+=f"{self.paginaA}\n" self.resultado+=f"\n" self.resultado+=f"{self.paginaB}\n" self.resultado+=f"\n" self.resultado+=f"{self.paginaC}\n" self.resultado+=f"\n" self.resultado+=f"{self.paginaD}\n" self.resultado+=f"\n" self.resultado+=f"{self.paginaE}\n" self.resultado+=f"\n" self.resultado+=f"{self.paginaF}\n" self.assertEqual(str(self.sitio),self.resultado) if __name__ == '__main__': unittest.main()
python
11
0.659696
185
66.903226
31
starcoderdata
<?php class Controller_Message extends Controller_Page { public $data; public function before() { parent::before(); // この行がないと、テンプレートが動作しません! } public function action_cartempty(){ global $data; $data['title'] = 'カートに商品がありません'; $data['messagein'] = View::forge('message/cartempty'); } public function action_newmember(){ global $data; $data['title'] = '登録完了'; $data['messagein'] = View::forge('message/newmember'); } public function action_commit(){ global $data; $data['title'] = '注文完了'; $data['messagein'] = View::forge('message/commit'); } public function action_pizzadoko(){ global $data; $data['title'] = '私のピザは今どこ?'; $data['messagein'] = View::forge('message/pizzadoko'); } public function after($response) { global $data; $this->template->content = View::forge('content/message',$data); $response = parent::after($response); // あなた自身のレスポンスオブジェクトを作成する場合は必要ありません。 // do stuff return $response; // after() は確実に Response オブジェクトを返すように } }
php
11
0.641618
82
20.625
48
starcoderdata
/** * Step 5 */ public class Longhand { public static void main(String[] args) { String inDollars = args[0].substring(1,args[0].length()); String cents; int dollars; if(inDollars.contains(".")) { String[] dollarsCents = inDollars.split("\\."); cents = dollarsCents[1]; dollars = Integer.valueOf(dollarsCents[0]); }else{ cents = "00"; dollars = Integer.valueOf(inDollars); } String outDollars = " and " + cents + "/100 dollars."; if (dollars % 100 != 0){ outDollars = numToWord((dollars % 100)) + outDollars; dollars -= dollars%100; } if(dollars % 1000 != 0){ outDollars = numToWord((dollars % 1000)/100) + " hundred " + outDollars; dollars -= dollars%1000; } if (dollars % 100000 != 0) { outDollars = numToWord((dollars % 100000)/1000) + " thousand " + outDollars; dollars -= dollars%100000; }else if(dollars % 1000000 != 0){ outDollars = "thousand " + outDollars; } if (dollars % 1000000 != 0){ outDollars = numToWord((dollars % 1000000)/100000) + " hundred " + outDollars; dollars -= dollars%1000000; } if (dollars % 10000000 != 0){ outDollars = numToWord((dollars%10000000)/1000000) + " million " + outDollars; } System.out.println(outDollars); } public static String numToWord(int n){ String strVal; if (n < 20){ switch(n) { case 1: strVal = "one"; break; case 2: strVal = "two"; break; case 3: strVal = "three"; break; case 4: strVal = "four"; break; case 5: strVal = "five"; break; case 6: strVal = "six"; break; case 7: strVal = "seven"; break; case 8: strVal = "eight"; break; case 9: strVal = "nine"; break; case 10: strVal = "ten"; break; case 11: strVal = "eleven"; break; case 12: strVal = "twelve"; break; case 13: strVal = "thirteen"; break; case 14: strVal = "fourteen"; break; case 15: strVal = "fifteen"; break; case 16: strVal = "sixteen"; break; case 17: strVal = "seventeen"; break; case 18: strVal = "eighteen"; break; case 19: strVal = "nineteen"; break; default: strVal = ""; break; } return strVal; }else{ switch(n/10){ case 2: strVal = "twenty"; break; case 3: strVal = "thirty"; break; case 4: strVal = "forty"; break; case 5: strVal = "fifty"; break; case 6: strVal = "sixty"; break; case 7: strVal = "seventy"; break; case 8: strVal = "eighty"; break; case 9: strVal = "ninety"; break; default: strVal = ""; break; } return strVal+" "+numToWord(n%10); } } }
java
16
0.359193
90
28.475524
143
starcoderdata
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright [2018] [ # # 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 Scopuli.Interfaces.MySQL.SQLAlchemy import String, TypeDecorator, type_coerce, func class PasswordType(TypeDecorator): impl = String(40) def bind_expression(self, bindvalue): """Apply a SQL expression to an incoming cleartext value being rendered as a bound parameter. For this example, this handler is intended only for the INSERT and UPDATE statements. Comparison operations within a SELECT are handled below by the Comparator. """ return func.crypt(bindvalue, func.gen_salt('md5')) class comparator_factory(String.comparator_factory): def __eq__(self, other): """Compare the local password column to an incoming cleartext password. This handler is invoked when a PasswordType column is used in conjunction with the == operator in a SQL expression, replacing the usage of the "bind_expression()" handler. """ # we coerce our own "expression" down to String, # so that invoking == doesn't cause an endless loop # back into __eq__() here local_pw = type_coerce(self.expr, String) return local_pw == func.crypt(other, local_pw)
python
12
0.663861
88
34.867925
53
starcoderdata
CObjectKeyContainer::CObjectKeyContainer(CObjectKeyContainer *object_key, PGCCError pRetCode) : CRefCount(MAKE_STAMP_ID('O','b','j','K')), m_fValidObjectKeyPDU(FALSE), m_cbDataSize(0) { GCCError rc = GCC_NO_ERROR; UINT object_id_size; m_InternalObjectKey.object_id_key = NULL; m_InternalObjectKey.poszNonStandardIDKey = NULL; /* * If an object ID "key" exists for the CObjectKeyContainer to be copied, * allocate memory to hold the object ID "key" information internally. * Check to make sure construction of the object is successful. */ if (object_key->m_InternalObjectKey.object_id_key != NULL) { /* * The key is of type Object ID. */ m_InternalObjectKey.object_id_length = object_key->m_InternalObjectKey.object_id_length; object_id_size = m_InternalObjectKey.object_id_length * sizeof(UINT); DBG_SAVE_FILE_LINE m_InternalObjectKey.object_id_key = new BYTE[object_id_size]; if (m_InternalObjectKey.object_id_key != NULL) { ::CopyMemory(m_InternalObjectKey.object_id_key, object_key->m_InternalObjectKey.object_id_key, object_id_size); } else { ERROR_OUT(("CObjectKeyContainer::CObjectKeyContainer: Error allocating memory")); rc = GCC_ALLOCATION_FAILURE; } } else if (object_key->m_InternalObjectKey.poszNonStandardIDKey != NULL) { /* * If a non-standard ID "key" exists for the CObjectKeyContainer to be copied, * create a new Rogue Wave string to hold the non-standard "key" * information internally. Check to make sure construction of the * object is successful. */ if (NULL == (m_InternalObjectKey.poszNonStandardIDKey = ::My_strdupO( object_key->m_InternalObjectKey.poszNonStandardIDKey))) { ERROR_OUT(("CObjectKeyContainer::CObjectKeyContainer: Error creating new non standard id key")); rc = GCC_ALLOCATION_FAILURE; } } else { /* * At least one of the internal pointers for the passed in object key * must be valid. */ ERROR_OUT(("CObjectKeyContainer::CObjectKeyContainer: Bad input parameters")); rc = GCC_BAD_OBJECT_KEY; } *pRetCode = rc; }
c++
15
0.669071
99
31.134328
67
inline
function partitionArray(array, startIdx, endIdx, steps){ // pivot (Element to be placed at right position) also the last element let pivotValue = array[endIdx]; let pivotIdx = startIdx; // Index of smaller element for (let i=startIdx; i<endIdx; i++){ // If current element is smaller than the pivot if (array[i] < pivotValue){ steps.push([i, pivotIdx, true]); steps.push([i, pivotIdx, false]); swap(array, i, pivotIdx); pivotIdx++; // increment index of smaller element } } steps.push([pivotIdx, endIdx, true]); steps.push([pivotIdx, endIdx, false]); swap(array, pivotIdx, endIdx); return(pivotIdx); }
javascript
11
0.665649
73
35.444444
18
inline
// // UIViewController+TDKit.h // tinyDict // // Created by guangbool on 2017/7/14. // Copyright © 2017年 bool. All rights reserved. // #import #import @interface UIViewController (TDKit) - (void)openURL:(NSURL *)url; @end
c
7
0.730114
79
19.705882
17
starcoderdata
class Jlab25 // Student Name : // Student Id Number : C00137009 // Date : 19/09/14 // Purpose : Write a program which ask the user for 2 numbers, it then indicates whether the first number is The first number is exactly divisible by both numbers.. ////// start on 25 part 2 { public static void main(String[] args) { int num1; int num2; int num3; System.out.print("Enter number One -> "); num1 = EasyIn.getInt(); System.out.print("Enter number Two -> "); num2 = EasyIn.getInt(); System.out.print("Enter number Three -> "); num3 = EasyIn.getInt(); if ( num1 % num2 == 0 && num1 % num3 == 0 ) { System.out.println("Number One is exactly divisible by number Two and Three"); } else { System.out.println("Number One is NOT exactly divisible by number Two and Three"); } } }
java
11
0.604938
167
21.846154
39
starcoderdata
# Import libraries import matplotlib.pyplot as plt import numpy as np import pandas as pd #%matplotlib notebook # First dataset City_A=[36,37,36,34,39,33,30,30,32,31,31,32,32,33,35] # Second dataset City_B=[41,35,28,29,25,36,36,32,38,40,40,34,31,28,30] # Caluclate the mean of datasets Mean_City_A=np.mean(City_A) Mean_City_B=np.mean(City_B) # Caluclate the standard deviation of datasets STDV_City_A=np.std(City_A) STDV_City_B=np.std(City_B) # Create a figure with customized size fig = plt.figure(figsize=(10, 8)) ax = fig.add_subplot(111) # Set the axis lables ax.set_xlabel('Day', fontsize = 18) ax.set_ylabel('Temperature', fontsize = 18) # X axis is day numbers from 1 to 15 xaxis = np.array(range(1,16)) # Line color for error bar color_City_A = 'red' color_City_B = 'darkgreen' # Line style for each dataset lineStyle_City_A={"linestyle":"--", "linewidth":2, "markeredgewidth":2, "elinewidth":2, "capsize":3} lineStyle_City_B={"linestyle":"-", "linewidth":2, "markeredgewidth":2, "elinewidth":2, "capsize":3} # Create an error bar for each dataset line_City_A=ax.errorbar(xaxis, City_A, yerr=STDV_City_A, **lineStyle_City_A, color=color_City_A, label='City A') line_City_B=ax.errorbar(xaxis, City_B, yerr=STDV_City_B, **lineStyle_City_B, color=color_City_B, label='City B') # Label each dataset on the graph, xytext is the label's position for i, txt in enumerate(City_A): ax.annotate(txt, xy=(xaxis[i], City_A[i]), xytext=(xaxis[i]+0.03, City_A[i]+0.3),color=color_City_A) for i, txt in enumerate(City_B): ax.annotate(txt, xy=(xaxis[i], City_B[i]), xytext=(xaxis[i]+0.03, City_B[i]+0.3),color=color_City_B) # Draw a legend bar plt.legend(handles=[line_City_A, line_City_B], loc='upper right') # Customize the tickes on the graph plt.xticks(xaxis) plt.yticks(np.arange(20, 47, 2)) # Customize the legend font and handle length params = {'legend.fontsize': 13, 'legend.handlelength': 2} plt.rcParams.update(params) # Customize the font font = {'family' : 'Arial', 'weight':'bold', 'size' : 12} #matplotlib.rc('font', **font) # Draw a grid for the graph ax.grid(color='lightgrey', linestyle='-') ax.set_facecolor('w') plt.show()
python
10
0.680162
112
29.054054
74
starcoderdata
package com.asyncapi.v2.binding.ws; import com.asyncapi.v2.binding.ChannelBinding; import lombok.*; import javax.annotation.CheckForNull; import javax.annotation.Nullable; /** * Describes WebSockets channel binding. * * When using WebSockets, the channel represents the connection. Unlike other protocols that support multiple virtual * channels (topics, routing keys, etc.) per connection, WebSockets doesn't support virtual channels or, put it another * way, there's only one channel and its characteristics are strongly related to the protocol used for the handshake, * i.e., HTTP. * * @version 0.1.0 * @see <a href="https://github.com/asyncapi/bindings/tree/master/websockets#channel-binding-object">WebSockets channel binding * @author */ @Data @Builder @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(callSuper = true) public class WebSocketsChannelBinding extends ChannelBinding { /** * The HTTP method to use when establishing the connection. Its value MUST be either GET or POST. */ @Nullable @CheckForNull private String method; /** * A Schema object containing the definitions for each query parameter. This schema MUST be of type * object and have a properties key. * * @see <a href="https://www.asyncapi.com/docs/specifications/2.0.0/#schemaObject">Schema object */ @Nullable @CheckForNull private Object query; /** * A Schema object containing the definitions of the HTTP headers to use when establishing the connection. * This schema MUST be of type object and have a properties key. * * @see <a href="https://www.asyncapi.com/docs/specifications/2.0.0/#schemaObject">Schema object */ @Nullable @CheckForNull private Object headers; /** * The version of this binding. If omitted, "latest" MUST be assumed. */ @Nullable @CheckForNull private String bindingVersion; }
java
6
0.714213
131
30.66129
62
starcoderdata
// license:BSD-3-Clause // copyright-holders: #ifndef MAME_AUDIO_DECOBSMT_H #define MAME_AUDIO_DECOBSMT_H #pragma once #include "cpu/m6809/m6809.h" #include "sound/bsmt2000.h" #define DECOBSMT_TAG "decobsmt" //************************************************************************** // TYPE DEFINITIONS //************************************************************************** class decobsmt_device : public device_t { public: // construction/destruction decobsmt_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock); void bsmt_reset_w(u8 data); u8 bsmt_status_r(); void bsmt0_w(u8 data); void bsmt1_w(offs_t offset, u8 data); u8 bsmt_comms_r(); void bsmt_comms_w(u8 data); DECLARE_WRITE_LINE_MEMBER(bsmt_reset_line); void bsmt_map(address_map &map); void decobsmt_map(address_map &map); protected: // device-level overrides virtual void device_start() override; virtual void device_reset() override; virtual void device_add_mconfig(machine_config &config) override; private: required_device m_ourcpu; required_device m_bsmt; uint8_t m_bsmt_latch; uint8_t m_bsmt_reset; uint8_t m_bsmt_comms; INTERRUPT_GEN_MEMBER(decobsmt_firq_interrupt); void bsmt_ready_callback(); }; // device type definition DECLARE_DEVICE_TYPE(DECOBSMT, decobsmt_device) #endif // MAME_AUDIO_DECOBSMT_H
c
9
0.656006
98
22.847458
59
starcoderdata
import colors from 'vuetify/es5/util/colors' const path = require('path') const fs = require('fs') import FMMode from "frontmatter-markdown-loader/mode"; import MarkdownIt from 'markdown-it' import mip from 'markdown-it-prism' function getMDPaths(type) { const directories = fs.readdirSync(path.resolve(__dirname, 'contents')); const res = [] directories.forEach(directoryName => { const files = fs.readdirSync(path.resolve(__dirname, 'contents', directoryName)); res.push(directoryName) files.forEach(fileName => res.push(`${directoryName}/${path.parse(fileName).name}`)) }) return res } const md = new MarkdownIt({ html: true, typographer: true }) md.use(mip) export default { /* ** Nuxt rendering mode ** See https://nuxtjs.org/api/configuration-mode */ mode: 'universal', /* ** Headers of the page ** See https://nuxtjs.org/api/configuration-head */ head: { titleTemplate: '%s - ' + process.env.npm_package_name, title: process.env.npm_package_name || '', meta: [ { charset: 'utf-8' }, { name: 'viewport', content: 'width=device-width, initial-scale=1' }, { name: "description", property: "og:description", content: 'Área de aprendizaje colaborativo de informática', hid: "description" }, { property: 'og:image', content:'/icon.png', hid: "og:image" }, { name: 'twitter:site', content: '@donEber98', hid: "twitter:site" }, ], link: [ { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' } ] }, /* PWA*/ pwa: { meta: { title: 'Enfocate', author: 'donEber', }, manifest: { name: 'Enfocate', short_name: 'Enfocate', lang: 'es', }, }, /* ** Global CSS */ css: [ '@/assets/css/prism-material-light.css', '@/assets/css/md-styles.css', ], /* ** Plugins to load before mounting the App ** https://nuxtjs.org/guide/plugins */ plugins: [ ], /* ** Nuxt.js dev-modules */ buildModules: [ '@nuxtjs/vuetify', ], /* ** Nuxt.js modules */ modules: [ '@nuxtjs/pwa', ], /* ** vuetify module configuration ** https://github.com/nuxt-community/vuetify-module */ vuetify: { customVariables: ['~/assets/variables.scss'], theme: { options: { customProperties: true }, themes: { blue: { primary: colors.blueGrey.darken1, primaryMiddle: colors.blueGrey.darken4, primaryDark: colors.blueGrey.darken3, primaryLight: colors.blueGrey.darken4, background: '#263238', }, dark: { primary: '#BDBDBD', primaryMiddle: '#272829', primaryDark: colors.grey.darken4, primaryLight: '#2f2f2f', background: '#212121', }, light: { primary: '#212121', primaryMiddle: colors.blueGrey.lighten5, primaryDark: colors.blueGrey.darken2, primaryLight: '#475b65', } } } }, /* ** Build configuration ** See https://nuxtjs.org/api/configuration-build/ */ build: { extend (config){ config.module.rules.push( { test: /\.md$/, loader: 'frontmatter-markdown-loader', include: path.resolve(__dirname, 'contents'), options: { mode: [FMMode.VUE_RENDER_FUNCTIONS, FMMode.VUE_COMPONENT], vue: { root: "dynamicMarkdown" }, markdown(body) { return md.render(body) } } } ) }, }, generate: { routes: ['404'] .concat(getMDPaths()) } }
javascript
21
0.568499
138
23.877551
147
starcoderdata
package org.kuali.ole.deliver.bo; import org.kuali.rice.krad.bo.PersistableBusinessObjectBase; /** * The OleLoanTermUnit is a BO class that defines the loan term unit fields with getters and setters which * is used for interacting the loan data with the persistence layer in OLE. */ public class OleLoanTermUnit extends PersistableBusinessObjectBase { private String loanTermUnitId; private String loanTermUnitCode; private String loanTermUnitName; /** * Gets the loanTermUnitId attribute. * * @return Returns the loanTermUnitId */ public String getLoanTermUnitId() { return loanTermUnitId; } /** * Sets the loanTermUnitId attribute value. * * @param loanTermUnitId The loanTermUnitId to set. */ public void setLoanTermUnitId(String loanTermUnitId) { this.loanTermUnitId = loanTermUnitId; } /** * Gets the loanTermUnitCode attribute. * * @return Returns the loanTermUnitCode */ public String getLoanTermUnitCode() { return loanTermUnitCode; } /** * Sets the loanTermUnitCode attribute value. * * @param loanTermUnitCode The loanTermUnitCode to set. */ public void setLoanTermUnitCode(String loanTermUnitCode) { this.loanTermUnitCode = loanTermUnitCode; } /** * Gets the loanTermUnitName attribute. * * @return Returns the loanTermUnitName */ public String getLoanTermUnitName() { return loanTermUnitName; } /** * Sets the loanTermUnitName attribute value. * * @param loanTermUnitName The loanTermUnitName to set. */ public void setLoanTermUnitName(String loanTermUnitName) { this.loanTermUnitName = loanTermUnitName; } }
java
8
0.676751
106
25.25
68
starcoderdata
// Copyright (c) 2018, the R8 project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package classmerging; import classmerging.pkg.SimpleInterfaceImplRetriever; public class SimpleInterfaceAccessTest { public static void main(String[] args) { // Without access modifications, it is not possible to merge the interface SimpleInterface into // SimpleInterfaceImpl, since this would lead to an illegal class access here. SimpleInterface x = SimpleInterfaceImplRetriever.getSimpleInterfaceImpl(); x.foo(); // Without access modifications, it is not possible to merge the interface OtherSimpleInterface // into OtherSimpleInterfaceImpl, since this could lead to an illegal class access if another // package references OtherSimpleInterface. OtherSimpleInterface y = new OtherSimpleInterfaceImpl(); y.bar(); } // Should only be merged into OtherSimpleInterfaceImpl if access modifications are allowed. public interface SimpleInterface { void foo(); } // Should only be merged into OtherSimpleInterfaceImpl if access modifications are allowed. public interface OtherSimpleInterface { void bar(); } private static class OtherSimpleInterfaceImpl implements OtherSimpleInterface { @Override public void bar() { System.out.println("In bar on OtherSimpleInterfaceImpl"); } } }
java
11
0.757576
99
34.357143
42
starcoderdata
def get_individual_data(cursor, firstname, lastname, batch): ''' Function that gets experience of a student from a particular batch for individual_page.html in templates folder. ## ABOUT THE ARGS ## cursor : To establish connection with tables firstname : To query in db with firstname lastname : To query in db with lastname batch : To query in database with batch Returns experience of the students whose firstname, lastname and batch match. ''' #print("SELECT exp from temp where (fname='" + firstname + "', lname='" + lastname + "', batch=" + batch + ");") rollno = get_rollno(cursor, firstname, lastname, batch) data_temp = cursor.execute("SELECT experiance from Exp where Rollno=" + rollno + ";") #change to batch instead of branch data = cursor.fetchall() print(data) return data
python
10
0.724566
121
37.428571
21
inline
// IDDN FR.001.250001.004.S.X.2019.000.00000 // ULIS is subject to copyright laws and is the legal and intellectual property of Praxinos,Inc /* * ULIS *__________________ * @file DualBuffer.h * @author * @brief This file provides the declaration for the DualBuffer arguments and scheduling functions. * @copyright Copyright 2018-2021 Praxinos, Inc. All Rights Reserved. * @license Please refer to LICENSE.md */ #pragma once #include "Core/Core.h" #include "Image/Block.h" #include "Math/Geometry/Rectangle.h" #include "Scheduling/RangeBasedPolicyScheduler.h" #include "Scheduling/ScheduleArgs.h" #include "Scheduling/SimpleBufferArgs.h" ULIS_NAMESPACE_BEGIN ///////////////////////////////////////////////////// /// @class FDualBufferCommandArgs /// @brief The FDualBufferCommandArgs class provides a class to implement /// the arguments objects for operations, used on simple buffers. /// @details FDualBufferCommandArgs is usually used for simple operations on a /// single buffer, such as Clear or Fill, for instance. class FDualBufferCommandArgs : public FSimpleBufferCommandArgs { public: virtual ~FDualBufferCommandArgs() override {} FDualBufferCommandArgs( const FBlock& iSrc , FBlock& iDst , const FRectI& iSrcRect , const FRectI& iDstRect ) : FSimpleBufferCommandArgs( iDst, iDstRect ) , src( iSrc ) , srcRect( iSrcRect ) {} const FBlock& src; const FRectI srcRect; }; ///////////////////////////////////////////////////// /// @class FDualBufferJobArgs /// @brief The FDualBufferJobArgs class provides a class to implement /// the arguments objects for operations, used on simple buffers. /// @details FDualBufferJobArgs is usually used for simple operations on a /// single buffer, such as Clear or Fill, for instance. class FDualBufferJobArgs final : public IJobArgs { public: ~FDualBufferJobArgs() override {} const uint8* ULIS_RESTRICT src; uint8* ULIS_RESTRICT dst; int64 size; uint32 line; }; ///////////////////////////////////////////////////// // Job Building static void BuildDualBufferJob_Scanlines( const FDualBufferCommandArgs* iCargs , const int64 iNumJobs , const int64 iNumTasksPerJob , const int64 iIndex , FDualBufferJobArgs& oJargs ) { const FFormatMetrics& src_fmt = iCargs->src.FormatMetrics(); const FFormatMetrics& dst_fmt = iCargs->dst.FormatMetrics(); const uint8* const ULIS_RESTRICT src = iCargs->src.Bits() + static_cast< uint64 >( iCargs->srcRect.x ) * src_fmt.BPP; uint8* const ULIS_RESTRICT dst = iCargs->dst.Bits() + static_cast< uint64 >( iCargs->dstRect.x ) * dst_fmt.BPP; const int64 src_bps = static_cast< int64 >( iCargs->src.BytesPerScanLine() ); const int64 dst_bps = static_cast< int64 >( iCargs->dst.BytesPerScanLine() ); const int64 size = static_cast< uint64 >( iCargs->dstRect.w ) * src_fmt.BPP; oJargs.src = src + ( iCargs->srcRect.y + iIndex ) * src_bps; oJargs.dst = dst + ( iCargs->dstRect.y + iIndex ) * dst_bps; oJargs.size = size; oJargs.line = static_cast< uint32 >( iIndex ); } static void BuildDualBufferJob_Chunks( const FDualBufferCommandArgs* iCargs , const int64 iSize , const int64 iCount , const int64 iOffset , const int64 iIndex , FDualBufferJobArgs& oJargs ) { const uint8* const ULIS_RESTRICT src = iCargs->src.Bits(); uint8* const ULIS_RESTRICT dst = iCargs->dst.Bits(); const int64 btt = static_cast< int64 >( iCargs->src.BytesTotal() ); oJargs.src = src + iOffset; // Changed from xxx + iIndex to xxx + iOffset to solve Copy on Chunk CacheEfficient, might trigger a new bug later on. oJargs.dst = dst + iOffset; // Changed from xxx + iIndex to xxx + iOffset to solve Copy on Chunk CacheEfficient, might trigger a new bug later on. oJargs.size = FMath::Min( iOffset + iSize, btt ) - iOffset; oJargs.line = ULIS_UINT16_MAX; // N/A for chunks } template< typename TJobArgs , typename TCommandArgs , void (*TDelegateInvoke)( const TJobArgs* , const TCommandArgs* ) , typename TDelegateBuildJobScanlines , typename TDelegateBuildJobChunks > void ScheduleDualBufferJobs( FCommand* iCommand , const FSchedulePolicy& iPolicy , bool iContiguous , bool iForceMonoChunk , TDelegateBuildJobScanlines iDelegateBuildJobScanlines , TDelegateBuildJobChunks iDelegateBuildJobChunks ) { const FDualBufferCommandArgs* cargs = dynamic_cast< const FDualBufferCommandArgs* >( iCommand->Args() ); RangeBasedSchedulingBuildJobs< TJobArgs , TCommandArgs , TDelegateInvoke > ( iCommand , iPolicy , static_cast< int64 >( cargs->src.BytesTotal() ) , cargs->dstRect.h , iContiguous , iForceMonoChunk , iDelegateBuildJobScanlines , iDelegateBuildJobChunks ); } #define ULIS_DEFINE_COMMAND_SCHEDULER_FORWARD_DUAL_CUSTOM( iName, iJobArgs, iCommandArgs, iDelegateInvocation, iDelegateBuildJobScanlines, iDelegateBuildJobChunks ) \ void \ iName( \ FCommand* iCommand \ , const FSchedulePolicy& iPolicy \ , bool iContiguous \ , bool iForceMonoChunk \ ) \ { \ ScheduleDualBufferJobs< \ iJobArgs \ , iCommandArgs \ , iDelegateInvocation \ > \ ( \ iCommand \ , iPolicy \ , iContiguous \ , iForceMonoChunk \ , iDelegateBuildJobScanlines \ , iDelegateBuildJobChunks \ ); \ } #define ULIS_DEFINE_COMMAND_SCHEDULER_FORWARD_DUAL( iName, iJobArgs, iCommandArgs, iDelegateInvocation ) \ ULIS_DEFINE_COMMAND_SCHEDULER_FORWARD_DUAL_CUSTOM( \ iName \ , iJobArgs \ , iCommandArgs \ , iDelegateInvocation \ , BuildDualBufferJob_Scanlines \ , BuildDualBufferJob_Chunks \ ) #define ULIS_DEFINE_GENERIC_COMMAND_SCHEDULER_FORWARD_DUAL_CUSTOM( iName, iJobArgs, iCommandArgs, iDelegateInvocation, iDelegateBuildJobScanlines, iDelegateBuildJobChunks ) \ template< typename T > ULIS_DEFINE_COMMAND_SCHEDULER_FORWARD_DUAL_CUSTOM( iName, iJobArgs, iCommandArgs, iDelegateInvocation, iDelegateBuildJobScanlines, iDelegateBuildJobChunks ) #define ULIS_DEFINE_GENERIC_COMMAND_SCHEDULER_FORWARD_DUAL( iName, iJobArgs, iCommandArgs, iDelegateInvocation ) \ template< typename T > ULIS_DEFINE_COMMAND_SCHEDULER_FORWARD_DUAL( iName, iJobArgs, iCommandArgs, iDelegateInvocation ) ULIS_NAMESPACE_END
c
18
0.41409
185
55.47619
189
starcoderdata
/* * This file contains generic tests that are run against every rule. Early on, * we found some common rule patterns that would cause errors under certain * conditions. Instead of tracking them down individually, this file runs * the same tests on every defined rule to track down these patterns. * * When run in addition to the other tests, this causes the Rhino CLI test * to fail due to Java stack overflow. This must be run separate from other tests. */ (function() { "use strict"; var Assert = YUITest.Assert, suite = new YUITest.TestSuite("General Tests for all Rules"), rules = CSSLint.getRules(), len = rules.length, i; function testAll(i, rules) { suite.add(new YUITest.TestCase({ name: "General Tests for " + rules[i].id, setUp: function() { this.options = {}; this.options[rules[i].id] = 1; }, "Using @viewport should not result in an error": function() { var result = CSSLint.verify("@viewport { width: auto; }", this.options); Assert.areEqual(0, result.messages.length); }, "Using @keyframes should not result in an error": function() { var result = CSSLint.verify("@keyframes resize { 0% {padding: 0;} 50% {padding: 0;} 100% {padding: 0;}}", this.options); Assert.areEqual(0, result.messages.length); }, "Using @page should not result in an error": function() { var result = CSSLint.verify("@page { width: 100px; }", this.options); Assert.areEqual(0, result.messages.length); }, "Using @page @top-left should not result in an error": function() { var result = CSSLint.verify("@page { @top-left { content: ''; } }", this.options); Assert.areEqual(0, result.messages.length); }, "Using a regular rule should not result in an error": function() { var result = CSSLint.verify("body { margin: 0; }", this.options); Assert.areEqual(0, result.messages.length); } })); } for (i = 0; i < len; i++) { testAll(i, rules); } YUITest.TestRunner.add(suite); })();
javascript
24
0.568819
136
34.134328
67
starcoderdata
public <V> Future<V> submit(Callable<V> task, CallableAfterExecuteHandler<V> callableAfterExecuteHandler) { if (task == null) throw new NullPointerException(); RunnableFuture<V> futureTask = newTaskFor(task); afterExecuteHandlers.put(futureTask, throwable -> { try { callableAfterExecuteHandler.handle(futureTask.get(), null); } catch (ExecutionException executionException) { callableAfterExecuteHandler.handle(null, executionException.getCause()); } catch (InterruptedException interruptedException) // if the get() above gets interrupted; expected to never happen { callableAfterExecuteHandler.handle(null, interruptedException); } catch (CancellationException cancellationException) { throw new RuntimeException("This should not be possible. If the future was cancelled it wouldn't get to afterExecute()"); } }); execute(futureTask); return futureTask; }
java
16
0.650659
133
39.884615
26
inline
import os from pyramid.view import view_config import pyramid.httpexceptions as exc from waxe.core.views.base import BaseUserView from waxe.core import browser from . import elastic class SearchView(BaseUserView): @view_config(route_name='search_json') def search(self): user_index_name = self.get_search_dirname() if not user_index_name: raise exc.HTTPInternalServerError('The search is not available') search = self.req_get.get('search') if not search: raise exc.HTTPClientError('Nothing to search') filetype = self.req_get.get('filetype') tag = self.req_get.get('tag') path = self.req_get.get('path') or '' page_num = self.req_get.get('page') or 1 try: page_num = int(page_num) except ValueError: page_num = 1 abspath = None if path: abspath = browser.absolute_path(path, self.root_path) url = self._get_search_url() index_name = self._get_search_index() res, nb_hits = elastic.do_search( url, index_name, search, abspath=abspath, ext=filetype, tag=tag, page=page_num) lis = [] if res: for dic in res: newdic = {} newdic['path'] = dic['_source']['relpath'] newdic['name'] = os.path.basename(newdic['path']) highlight = dic['highlight'] newdic['excerpts'] = [] for k, v in highlight.iteritems(): key = ' > '.join(k.split('.')[1:]) newdic['excerpts'].append((key, v)) lis += [newdic] return { 'results': lis, 'nb_items': nb_hits, 'items_per_page': elastic.HITS_PER_PAGE, } @view_config(route_name='search_path_complete_json') def search_path_complete(self): dirname = self.get_search_dirname() if not dirname: raise exc.HTTPInternalServerError('The search is not available') search = self.req_get.get('search') or '' if not search: raise exc.HTTPClientError('Nothing to search') url = self._get_search_url() index_name = self._get_search_index() return elastic.path_completion(url, index_name, search) def includeme(config): # TODO: remove this hardcoded prefix prefix = '/api/1/account/{login}/' config.add_route('search_json', prefix + 'search/search.json') config.add_route('search_path_complete_json', prefix + 'search/path-complete.json') config.scan(__name__)
python
20
0.565348
76
31.777778
81
starcoderdata
export { default as Button } from './Button'; export { default as Container } from './Container'; export { default as Form } from './Form'; export { default as FormWrapper } from './FormWrapper'; export { default as TextInput } from './TextInput'; export { default as Title } from './Title';
javascript
4
0.707246
55
48.285714
7
starcoderdata
#ifndef SCOPERATOR_H #define SCOPERATOR_H #include "sctokenrepresentable.h" class SCOperator : public SCTokenRepresentable { public: SCOperator(const QString &tk, const SCTokenTypes::TokenType &tt, const QString &rep, const SCTokenTypes::OperatorPrecedence &prec, const SCTokenTypes::OperatorAssociativity &assoc); SCOperator(const SCOperator &other); void setPrecedence(const SCTokenTypes::OperatorPrecedence &prec); void setAssociativity(const SCTokenTypes::OperatorAssociativity &assoc); SCTokenTypes::OperatorPrecedence getPrecedence() const; SCTokenTypes::OperatorAssociativity getAssociativity() const; protected: SCTokenTypes::OperatorPrecedence precedence; SCTokenTypes::OperatorAssociativity associativity; }; #endif // SCOPERATOR_H
c
9
0.780691
111
31.269231
26
starcoderdata
/* * Copyright (c) 2004, 2009, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 4984908 5058132 6653154 * @summary Basic test of valueOf(String) * @author * * @compile ValueOf.java * @run main ValueOf * @key randomness */ import java.util.*; import java.lang.reflect.Method; public class ValueOf { static Random rnd = new Random(); public static void main(String[] args) throws Exception { test(Silly0.class); test(Silly1.class); test(Silly31.class); test(Silly32.class); test(Silly33.class); test(Silly63.class); test(Silly64.class); test(Silly65.class); test(Silly127.class); test(Silly128.class); test(Silly129.class); test(Silly500.class); test(Specialized.class); testMissingException(); } static <T extends Enum void test(Class enumClass) throws Exception { Set s = EnumSet.allOf(enumClass); test(enumClass, s); // Delete half the elements from set at random for (Iterator i = s.iterator(); i.hasNext(); ) { i.next(); if (rnd.nextBoolean()) i.remove(); } test(enumClass, s); } static <T extends Enum void test(Class enumClass, Set s) throws Exception { Method valueOf = enumClass.getDeclaredMethod("valueOf", String.class); Set copy = EnumSet.noneOf(enumClass); for (T e : s) copy.add((T) valueOf.invoke(null, e.name())); if (!copy.equals(s)) throw new Exception(copy + " != " + s); } static void testMissingException() { try { Enum.valueOf(Specialized.class, "BAZ"); throw new RuntimeException("Expected IllegalArgumentException not thrown."); } catch(IllegalArgumentException iae) { String message = iae.getMessage(); if (! "No enum constant ValueOf.Specialized.BAZ".equals(message)) throw new RuntimeException("Unexpected detail message: ``" + message + "''."); } } enum Silly0 { }; enum Silly1 { e1 } enum Silly31 { e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30 } enum Silly32 { e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31 } enum Silly33 { e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32 } enum Silly63 { e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, e50, e51, e52, e53, e54, e55, e56, e57, e58, e59, e60, e61, e62 } enum Silly64 { e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, e50, e51, e52, e53, e54, e55, e56, e57, e58, e59, e60, e61, e62, e63 } enum Silly65 { e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, e50, e51, e52, e53, e54, e55, e56, e57, e58, e59, e60, e61, e62, e63, e64 } enum Silly127 { e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, e50, e51, e52, e53, e54, e55, e56, e57, e58, e59, e60, e61, e62, e63, e64, e65, e66, e67, e68, e69, e70, e71, e72, e73, e74, e75, e76, e77, e78, e79, e80, e81, e82, e83, e84, e85, e86, e87, e88, e89, e90, e91, e92, e93, e94, e95, e96, e97, e98, e99, e100, e101, e102, e103, e104, e105, e106, e107, e108, e109, e110, e111, e112, e113, e114, e115, e116, e117, e118, e119, e120, e121, e122, e123, e124, e125, e126 } enum Silly128 { e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, e50, e51, e52, e53, e54, e55, e56, e57, e58, e59, e60, e61, e62, e63, e64, e65, e66, e67, e68, e69, e70, e71, e72, e73, e74, e75, e76, e77, e78, e79, e80, e81, e82, e83, e84, e85, e86, e87, e88, e89, e90, e91, e92, e93, e94, e95, e96, e97, e98, e99, e100, e101, e102, e103, e104, e105, e106, e107, e108, e109, e110, e111, e112, e113, e114, e115, e116, e117, e118, e119, e120, e121, e122, e123, e124, e125, e126, e127 } enum Silly129 { e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, e50, e51, e52, e53, e54, e55, e56, e57, e58, e59, e60, e61, e62, e63, e64, e65, e66, e67, e68, e69, e70, e71, e72, e73, e74, e75, e76, e77, e78, e79, e80, e81, e82, e83, e84, e85, e86, e87, e88, e89, e90, e91, e92, e93, e94, e95, e96, e97, e98, e99, e100, e101, e102, e103, e104, e105, e106, e107, e108, e109, e110, e111, e112, e113, e114, e115, e116, e117, e118, e119, e120, e121, e122, e123, e124, e125, e126, e127, e128 } enum Silly500 { e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, e50, e51, e52, e53, e54, e55, e56, e57, e58, e59, e60, e61, e62, e63, e64, e65, e66, e67, e68, e69, e70, e71, e72, e73, e74, e75, e76, e77, e78, e79, e80, e81, e82, e83, e84, e85, e86, e87, e88, e89, e90, e91, e92, e93, e94, e95, e96, e97, e98, e99, e100, e101, e102, e103, e104, e105, e106, e107, e108, e109, e110, e111, e112, e113, e114, e115, e116, e117, e118, e119, e120, e121, e122, e123, e124, e125, e126, e127, e128, e129, e130, e131, e132, e133, e134, e135, e136, e137, e138, e139, e140, e141, e142, e143, e144, e145, e146, e147, e148, e149, e150, e151, e152, e153, e154, e155, e156, e157, e158, e159, e160, e161, e162, e163, e164, e165, e166, e167, e168, e169, e170, e171, e172, e173, e174, e175, e176, e177, e178, e179, e180, e181, e182, e183, e184, e185, e186, e187, e188, e189, e190, e191, e192, e193, e194, e195, e196, e197, e198, e199, e200, e201, e202, e203, e204, e205, e206, e207, e208, e209, e210, e211, e212, e213, e214, e215, e216, e217, e218, e219, e220, e221, e222, e223, e224, e225, e226, e227, e228, e229, e230, e231, e232, e233, e234, e235, e236, e237, e238, e239, e240, e241, e242, e243, e244, e245, e246, e247, e248, e249, e250, e251, e252, e253, e254, e255, e256, e257, e258, e259, e260, e261, e262, e263, e264, e265, e266, e267, e268, e269, e270, e271, e272, e273, e274, e275, e276, e277, e278, e279, e280, e281, e282, e283, e284, e285, e286, e287, e288, e289, e290, e291, e292, e293, e294, e295, e296, e297, e298, e299, e300, e301, e302, e303, e304, e305, e306, e307, e308, e309, e310, e311, e312, e313, e314, e315, e316, e317, e318, e319, e320, e321, e322, e323, e324, e325, e326, e327, e328, e329, e330, e331, e332, e333, e334, e335, e336, e337, e338, e339, e340, e341, e342, e343, e344, e345, e346, e347, e348, e349, e350, e351, e352, e353, e354, e355, e356, e357, e358, e359, e360, e361, e362, e363, e364, e365, e366, e367, e368, e369, e370, e371, e372, e373, e374, e375, e376, e377, e378, e379, e380, e381, e382, e383, e384, e385, e386, e387, e388, e389, e390, e391, e392, e393, e394, e395, e396, e397, e398, e399, e400, e401, e402, e403, e404, e405, e406, e407, e408, e409, e410, e411, e412, e413, e414, e415, e416, e417, e418, e419, e420, e421, e422, e423, e424, e425, e426, e427, e428, e429, e430, e431, e432, e433, e434, e435, e436, e437, e438, e439, e440, e441, e442, e443, e444, e445, e446, e447, e448, e449, e450, e451, e452, e453, e454, e455, e456, e457, e458, e459, e460, e461, e462, e463, e464, e465, e466, e467, e468, e469, e470, e471, e472, e473, e474, e475, e476, e477, e478, e479, e480, e481, e482, e483, e484, e485, e486, e487, e488, e489, e490, e491, e492, e493, e494, e495, e496, e497, e498, e499 } enum Specialized { FOO { public void foo() {} }; public abstract void foo(); }; }
java
13
0.578523
94
45.60177
226
starcoderdata
from django import forms class QueryFlightForm(forms.Form): origination = forms.CharField(max_length=30, label="始发地", widget=forms.TextInput(attrs={'class': 'form-control'})) destination = forms.CharField(max_length=30, label="目的地", widget=forms.TextInput(attrs={'class': 'form-control'})) date = forms.CharField(max_length=30, label="目的地", widget=forms.TextInput(attrs={'class': 'form-control'})) class BookTicketForm(forms.Form): date = forms.CharField(max_length=30, label="日期", widget=forms.TextInput(attrs={'class': 'form-control'})) real_name = forms.CharField(max_length=30, label="真实姓名", widget=forms.TextInput(attrs={'class': 'form-control'})) Id_number = forms.CharField(max_length=30, label="身份证号", widget=forms.TextInput(attrs={'class': 'form-control'})) flight_number = forms.CharField(max_length=30, label="航班号", widget=forms.TextInput(attrs={'class': 'form-control'})) money = forms.FloatField() class pay_form(forms.Form): username = forms.CharField(label="用户名", max_length=128, widget=forms.TextInput(attrs={'class': 'form-control'})) money = forms.FloatField() order_id = forms.IntegerField() class cancel_ticket_form(forms.Form): order_number = forms.CharField(max_length=30, label="日期", widget=forms.TextInput(attrs={'class': 'form-control'})) username = forms.CharField(label="用户名", max_length=128, widget=forms.TextInput(attrs={'class': 'form-control'}))
python
14
0.711297
120
61.391304
23
starcoderdata
/** * Copyright 2013 Canada Health Infoway, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: $LastChangedBy: tmcgrady $ * Last modified: $LastChangedDate: 2011-05-04 16:47:15 -0300 (Wed, 04 May 2011) $ * Revision: $LastChangedRevision: 2623 $ */ package ca.infoway.messagebuilder.marshalling.hl7; import static ca.infoway.messagebuilder.datatype.StandardDataType.PQ_BASIC; import static ca.infoway.messagebuilder.datatype.StandardDataType.PQ_DISTANCE; import static ca.infoway.messagebuilder.datatype.StandardDataType.PQ_DRUG; import static ca.infoway.messagebuilder.datatype.StandardDataType.PQ_HEIGHTWEIGHT; import static ca.infoway.messagebuilder.datatype.StandardDataType.PQ_LAB; import static ca.infoway.messagebuilder.datatype.StandardDataType.PQ_TIME; import java.math.BigDecimal; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.w3c.dom.Element; import ca.infoway.messagebuilder.Hl7BaseVersion; import ca.infoway.messagebuilder.SpecificationVersion; import ca.infoway.messagebuilder.VersionNumber; import ca.infoway.messagebuilder.datatype.StandardDataType; import ca.infoway.messagebuilder.domainvalue.UnitsOfMeasureCaseSensitive; import ca.infoway.messagebuilder.domainvalue.x_BasicUnitsOfMeasure; import ca.infoway.messagebuilder.domainvalue.x_DistanceObservationUnitsOfMeasure; import ca.infoway.messagebuilder.domainvalue.x_DrugUnitsOfMeasure; import ca.infoway.messagebuilder.domainvalue.x_HeightOrWeightObservationUnitsOfMeasure; import ca.infoway.messagebuilder.domainvalue.x_LabUnitsOfMeasure; import ca.infoway.messagebuilder.domainvalue.x_TimeUnitsOfMeasure; import ca.infoway.messagebuilder.error.ErrorLevel; import ca.infoway.messagebuilder.error.Hl7Error; import ca.infoway.messagebuilder.error.Hl7ErrorCode; import ca.infoway.messagebuilder.error.Hl7Errors; import ca.infoway.messagebuilder.lang.NumberUtil; import ca.infoway.messagebuilder.resolver.CodeResolverRegistry; import ca.infoway.messagebuilder.util.xml.XmlDescriber; public class PqValidationUtils { public static final int MAXIMUM_INTEGER_DIGITS = 11; public static final int MAXIMUM_FRACTION_DIGITS = 2; public static final int MAXIMUM_FRACTION_DIGITS_DRUG_LAB = 4; private static final int MAX_ORIGINAL_TEXT_LENGTH = 150; public static final Map<String, Integer> maximum_fraction_digits_exceptions = new HashMap<String, Integer>(); public static final Map<String, Integer> maximum_integer_digits_exceptions = new HashMap<String, Integer>(); static { maximum_fraction_digits_exceptions.put(Hl7BaseVersion.MR2007 + "_PQ.DRUG", 2); maximum_fraction_digits_exceptions.put(Hl7BaseVersion.MR2007 + "_PQ.LAB", 2); maximum_fraction_digits_exceptions.put(Hl7BaseVersion.CERX + "_PQ.DRUG", 2); maximum_fraction_digits_exceptions.put(Hl7BaseVersion.CERX + "_PQ.LAB", 2); maximum_integer_digits_exceptions.put(Hl7BaseVersion.CERX + "_PQ.BASIC", 8); maximum_integer_digits_exceptions.put(Hl7BaseVersion.CERX + "_PQ.DRUG", 8); maximum_integer_digits_exceptions.put(Hl7BaseVersion.CERX + "_PQ.TIME", 8); maximum_integer_digits_exceptions.put(Hl7BaseVersion.CERX + "_PQ.HEIGHTWEIGHT", 8); // CeRx does not specify PQ.LAB or PQ.DISTANCE } public int getMaxFractionDigits(VersionNumber version, String typeAsString) { int maxFractionDigits = MAXIMUM_FRACTION_DIGITS; StandardDataType type = StandardDataType.getByTypeName(typeAsString); if (PQ_DRUG.equals(type) || PQ_LAB.equals(type)) { maxFractionDigits = MAXIMUM_FRACTION_DIGITS_DRUG_LAB; } Integer exceptionValue = maximum_fraction_digits_exceptions.get(version.getBaseVersion() + "_" + type); return (int) (exceptionValue == null ? maxFractionDigits : exceptionValue); } public int getMaxIntDigits(VersionNumber version, String type) { Integer exceptionValue = maximum_integer_digits_exceptions.get(version.getBaseVersion() + "_" + type); return (int) (exceptionValue == null ? MAXIMUM_INTEGER_DIGITS : exceptionValue); } private Class<? extends UnitsOfMeasureCaseSensitive> getUnitTypeByHl7Type(String typeAsString, Element element, String propertyPath, Hl7Errors errors, boolean isR2) { StandardDataType type = StandardDataType.getByTypeName(typeAsString); if (PQ_BASIC.equals(type)) { return x_BasicUnitsOfMeasure.class; } else if (PQ_DRUG.equals(type)) { return x_DrugUnitsOfMeasure.class; } else if (PQ_TIME.equals(type)) { return x_TimeUnitsOfMeasure.class; } else if (PQ_LAB.equals(type)) { return x_LabUnitsOfMeasure.class; } else if (PQ_HEIGHTWEIGHT.equals(type)) { return x_HeightOrWeightObservationUnitsOfMeasure.class; } else if (PQ_DISTANCE.equals(type)) { return x_DistanceObservationUnitsOfMeasure.class; } else { if (!isR2) { createWarning(MessageFormat.format("Type \"{0}\" is not a valid PQ type", typeAsString), element, propertyPath, errors); } return UnitsOfMeasureCaseSensitive.class; } } public BigDecimal validateValue(String value, VersionNumber version, String type, boolean hasNullFlavor, Element element, String propertyPath, Hl7Errors errors) { int maxIntDigits = this.getMaxIntDigits(version, type); int maxFractionDigits = this.getMaxFractionDigits(version, type); boolean alreadyWarnedAboutValue = false; BigDecimal result = null; if (StringUtils.isBlank(value)) { if (!hasNullFlavor) { createWarning("No value provided for physical quantity", element, propertyPath, errors); } } else { if (NumberUtil.isNumber(value)) { String integerPart = value.contains(".") ? StringUtils.substringBefore(value, ".") : value; String decimalPart = value.contains(".") ? StringUtils.substringAfter(value, ".") : ""; String errorMessage = "PhysicalQuantity for {0}/{1} can contain a maximum of {2} {3} places"; if (StringUtils.length(decimalPart) > maxFractionDigits) { createWarning(MessageFormat.format(errorMessage, version.getBaseVersion(), type, maxFractionDigits, "decimal"), element, propertyPath, errors); } if (StringUtils.length(integerPart) > maxIntDigits) { createWarning(MessageFormat.format(errorMessage, version.getBaseVersion(), type, maxIntDigits, "integer"), element, propertyPath, errors); } if (!StringUtils.isNumeric(integerPart) || !StringUtils.isNumeric(decimalPart)) { alreadyWarnedAboutValue = true; createWarning(MessageFormat.format("value \"{0}\" must contain digits only", value), element, propertyPath, errors); } } try { result = new BigDecimal(value); } catch (NumberFormatException e) { if (!alreadyWarnedAboutValue) { createWarning(MessageFormat.format("value \"{0}\" is not a valid decimal value", value), element, propertyPath, errors); } } } return result; } public BigDecimal validateValueR2(String value, VersionNumber version, String type, boolean hasNullFlavor, Element element, String propertyPath, Hl7Errors errors) { BigDecimal result = null; if (!StringUtils.isBlank(value)) { try { result = new BigDecimal(value); } catch (NumberFormatException e) { createWarning(MessageFormat.format("value \"{0}\" is not a valid decimal value", value), element, propertyPath, errors); } } return result; } public UnitsOfMeasureCaseSensitive validateUnits(String type, String unitsAsString, Element element, String propertyPath, Hl7Errors errors, boolean isR2) { UnitsOfMeasureCaseSensitive units = null; if (StringUtils.isNotBlank(unitsAsString)) { units = (UnitsOfMeasureCaseSensitive) CodeResolverRegistry.lookup(this.getUnitTypeByHl7Type(type, element, propertyPath, errors, isR2), unitsAsString); if (units == null) { createWarning(MessageFormat.format("Unit \"{0}\" is not valid for type {1}", unitsAsString, type), element, propertyPath, errors); } } return units; } public void validateOriginalText(String typeAsString, String originalText, boolean hasAnyValues, boolean hasNullFlavor, VersionNumber version, Element element, String propertyPath, Hl7Errors errors) { StandardDataType type = StandardDataType.getByTypeName(typeAsString); boolean hasOriginalText = StringUtils.isNotBlank(originalText); if (hasOriginalText) { // only PQ.LAB is allowed to have originalText if (!PQ_LAB.equals(type)) { createWarning(MessageFormat.format("Type {0} not allowed to have originalText. For physical quantity types, originalText is only allowed for PQ.LAB.", typeAsString), element, propertyPath, errors); } else { // no more than 150 characters int length = originalText.length(); if (length > MAX_ORIGINAL_TEXT_LENGTH) { createWarning(MessageFormat.format("PQ.LAB originalText has {0} characters, but only {1} are allowed.", length, MAX_ORIGINAL_TEXT_LENGTH), element, propertyPath, errors); } } } // TM - HACK: these restrictions don't seem to apply to the R2 datatype version of PQ.LAB; currently only BC using this (refactor when implementing R2 datatypes) if (PQ_LAB.equals(type) && hasNullFlavor && !SpecificationVersion.isExactVersion(version, SpecificationVersion.V02R04_BC)) { if (!hasOriginalText) { createWarning("For PQ.LAB values, originalText is mandatory when set to a NullFlavor.", element, propertyPath, errors); } if (hasAnyValues) { createWarning("PQ.LAB can not have quantity or units specified when set to a NullFlavor.", element, propertyPath, errors); } } } private void createWarning(String errorMessage, Element element, String propertyPath, Hl7Errors errors) { Hl7Error error = null; if (element != null) { error = new Hl7Error( Hl7ErrorCode.DATA_TYPE_ERROR, ErrorLevel.ERROR, errorMessage + " (" + XmlDescriber.describeSingleElement(element) + ")", element); } else { // assuming this has a property path error = new Hl7Error( Hl7ErrorCode.DATA_TYPE_ERROR, ErrorLevel.ERROR, errorMessage, propertyPath); } errors.addHl7Error(error); } }
java
20
0.73598
201
44.982609
230
starcoderdata
const yup = require('yup'); function TransactionsController(database) { async function update(request, response) { const { amount, description } = request.body; if (!amount && !description) { return response.status(400).json({ message: 'Validation failed!' }); } const { id } = request.params; const transaction = await database('transaction') .where({ id }) .select('*') .first(); if (!transaction) { return response.status(404).json({ message: 'Transaction not found' }); } const [updatedTransaction] = await database('transaction') .where({ id }) .update({ amount, description, }) .returning('*'); return response.status(200).json({ ...updatedTransaction }); } async function index(request, response) { function validateDate(date) { const matches = /(\d{4})[-.\/](\d{1,2})[-.\/](\d{1,2})$/.exec(date); if (!matches) { return false; } const [year, month, day] = date.split('-'); month == '12' ? (month = '11') : null; const dateObject = new Date(year, month, day); if ( Number(year) != dateObject.getFullYear() || Number(month) != dateObject.getMonth() || Number(day) != dateObject.getDate() ) { return false; } } const querySchema = yup.object().shape({ date: yup.string().transform(validateDate), page: yup.number().positive(), timezoneOffset: yup.number().integer(), }); if (!(await querySchema.isValid(request.query))) { return response.status(400).json({ message: 'Validation failed!' }); } const { id: userId } = request.userData; const { date, page = 1, timezoneOffset = 0 } = request.query; const limitElementsForPage = 10; const transactionsQuery = database('transaction') .limit(limitElementsForPage) .offset((page - 1) * limitElementsForPage) .leftJoin('wallet', 'wallet.id', '=', 'transaction.wallet_id') .innerJoin('user', 'user.id', '=', 'wallet.user_id') .where('user.id', `${userId}`) .orderBy('created_at', 'desc') .select('transaction.*', 'wallet.name as wallet_name'); if (date) { let [year, month, day] = date.split('-'); month == '12' ? (month = '11') : null; const formattedDate = new Date( year, month, day, 23 + timezoneOffset, 59, 59 ); transactionsQuery.andWhere('created_at', '<=', formattedDate); } const transactions = await transactionsQuery; if (transactions.length == 0) { return response.status(404).json({ message: "you don't have transactions in date", }); } return response.status(200).json({ transactions }); } async function getExpensesAndIncomes(request, response) { const querySchema = yup.object().shape({ year: yup.number().min(2021).required(), month: yup.number().min(1).max(12).required(), timezoneOffset: yup.number().integer(), }); if (!(await querySchema.isValid(request.query))) { return response.status(400).json({ message: 'Validation failed!' }); } const { year, month, timezoneOffset = 0 } = request.query; const { id: userId } = request.userData; const walletsUsersIds = await database('wallet') .where({ user_id: userId }) .select('id') .then(data => data.map(a => a.id)); const monthIndex = month - 1; const from = new Date(year, monthIndex, 1); const to = new Date( year, monthIndex + 1, 0, 23 + timezoneOffset / 60, 59, 59 ); const transactions = await database('transaction') .whereIn('wallet_id', walletsUsersIds) .whereBetween('created_at', [from, to]) .select('*'); let data = {}; walletsUsersIds.forEach(id => { if (!(id in data)) { data[id] = { expenses: 0, incomes: 0, }; } }); data = transactions.reduce((acc, transaction, _) => { if (transaction.amount < 0) { acc[`${transaction.wallet_id}`].expenses += transaction.amount; } else { acc[`${transaction.wallet_id}`].incomes += transaction.amount; } return acc; }, data); return response.status(200).json({ expensesAndIncome: data }); } return { update, index, getExpensesAndIncomes, }; } module.exports = TransactionsController;
javascript
18
0.57484
77
25.922619
168
starcoderdata
@Override public void onReceive(Context context, Intent intent) { if (intent == null || intent.getAction() == null) { return; } if (AudioRecorder.BROADCAST_SAMPLE_ACTION.equals(intent.getAction())) { AudioRecorder.AverageSampleHolder sampleHolder = AudioRecorder.getAverageSample(intent); if (sampleHolder != null) { if (audioGraphView == null) { // graph not ready yet return; } audioGraphView.setMaxSampleValue(sampleHolder.getMaxVolume()); audioGraphView.addSample(sampleHolder.getAverageSampleVolume()); } } }
java
12
0.461717
88
44.421053
19
inline
package com.embrio.test.phonepe.config; import com.google.common.collect.BiMap; import com.google.common.collect.ImmutableBiMap; import java.util.*; public class Limit extends HashMap }
java
4
0.801724
48
20.090909
11
starcoderdata
#include "PCH.h" #include "RenderTarget.h" #include "Renderer.h" #include "Platform\OpenGL\OpenGLTexture.h" #include "Platform\OpenGL\OpenGLRenderTarget.h" namespace Evoke { TSharedPtr RenderTarget2D::Create(u32 inWidth, u32 inHeight, const std::initializer_list inFormats) { switch (Renderer::API()) { case ERenderAPI::OpenGL: return MakeShared inHeight, inFormats); default: EV_CORE_ASSERT(false, "Unknown render API."); return nullptr; } } }
c++
13
0.750473
133
25.5
20
starcoderdata
static int netvsc_probe(struct hv_device *dev, const struct hv_vmbus_device_id *dev_id) { struct net_device *net = NULL; struct net_device_context *net_device_ctx; struct netvsc_device_info *device_info = NULL; struct netvsc_device *nvdev; int ret = -ENOMEM; net = alloc_etherdev_mq(sizeof(struct net_device_context), VRSS_CHANNEL_MAX); if (!net) goto no_net; netif_carrier_off(net); netvsc_init_settings(net); net_device_ctx = netdev_priv(net); net_device_ctx->device_ctx = dev; net_device_ctx->msg_enable = netif_msg_init(debug, default_msg); if (netif_msg_probe(net_device_ctx)) netdev_dbg(net, "netvsc msg_enable: %d\n", net_device_ctx->msg_enable); hv_set_drvdata(dev, net); INIT_DELAYED_WORK(&net_device_ctx->dwork, netvsc_link_change); spin_lock_init(&net_device_ctx->lock); INIT_LIST_HEAD(&net_device_ctx->reconfig_events); INIT_DELAYED_WORK(&net_device_ctx->vf_takeover, netvsc_vf_setup); net_device_ctx->vf_stats = netdev_alloc_pcpu_stats(struct netvsc_vf_pcpu_stats); if (!net_device_ctx->vf_stats) goto no_stats; net->netdev_ops = &device_ops; net->ethtool_ops = &ethtool_ops; SET_NETDEV_DEV(net, &dev->device); /* We always need headroom for rndis header */ net->needed_headroom = RNDIS_AND_PPI_SIZE; /* Initialize the number of queues to be 1, we may change it if more * channels are offered later. */ netif_set_real_num_tx_queues(net, 1); netif_set_real_num_rx_queues(net, 1); /* Notify the netvsc driver of the new device */ device_info = netvsc_devinfo_get(NULL); if (!device_info) { ret = -ENOMEM; goto devinfo_failed; } nvdev = rndis_filter_device_add(dev, device_info); if (IS_ERR(nvdev)) { ret = PTR_ERR(nvdev); netdev_err(net, "unable to add netvsc device (ret %d)\n", ret); goto rndis_failed; } memcpy(net->dev_addr, device_info->mac_adr, ETH_ALEN); /* We must get rtnl lock before scheduling nvdev->subchan_work, * otherwise netvsc_subchan_work() can get rtnl lock first and wait * all subchannels to show up, but that may not happen because * netvsc_probe() can't get rtnl lock and as a result vmbus_onoffer() * -> ... -> device_add() -> ... -> __device_attach() can't get * the device lock, so all the subchannels can't be processed -- * finally netvsc_subchan_work() hangs forever. */ rtnl_lock(); if (nvdev->num_chn > 1) schedule_work(&nvdev->subchan_work); /* hw_features computed in rndis_netdev_set_hwcaps() */ net->features = net->hw_features | NETIF_F_HIGHDMA | NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX; net->vlan_features = net->features; /* MTU range: 68 - 1500 or 65521 */ net->min_mtu = NETVSC_MTU_MIN; if (nvdev->nvsp_version >= NVSP_PROTOCOL_VERSION_2) net->max_mtu = NETVSC_MTU - ETH_HLEN; else net->max_mtu = ETH_DATA_LEN; ret = register_netdevice(net); if (ret != 0) { pr_err("Unable to register netdev.\n"); goto register_failed; } list_add(&net_device_ctx->list, &netvsc_dev_list); rtnl_unlock(); kfree(device_info); return 0; register_failed: rtnl_unlock(); rndis_filter_device_remove(dev, nvdev); rndis_failed: kfree(device_info); devinfo_failed: free_percpu(net_device_ctx->vf_stats); no_stats: hv_set_drvdata(dev, NULL); free_netdev(net); no_net: return ret; }
c
10
0.68342
70
26.428571
119
inline
package com.gbr.nyan.web.support; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import static java.util.Collections.list; /** * lifted from : http://stackoverflow.com/questions/28723425/logging-controller-requests-spring-boot */ public class FullRequestLogFilter implements Filter { private final static Logger logger = LoggerFactory.getLogger(FullRequestLogFilter.class); @Override public void init(FilterConfig filterConfig) { logger.info("Init logger Request Filter"); } private void logRequest(HttpServletRequest request) { logger.debug("### Request Headers:"); for (String header : list(request.getHeaderNames())) { logger.debug("\t* {}: {}", new Object[]{header, request.getHeader(header)}); } logger.debug("### Request Parameters:"); for (String paramName : list(request.getParameterNames())) { logger.debug("\t* {}: {}", new Object[]{paramName, request.getParameter(paramName)}); } } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (logger.isDebugEnabled()) { logRequest((HttpServletRequest) request); } chain.doFilter(request, response); } @Override public void destroy() { logger.debug("Destroy logger Request Filter"); } }
java
14
0.679605
132
31.340426
47
starcoderdata
/*----------------------------------------------------------------------------------------------Gravador*/ var tituloNotas = []; var textoNotas = []; var querJaFav = []; var nota = [] function gravarNota() { const titulo = document.querySelector("#titulo").value; const texto = document.querySelector("#texto").value; const querJa = document.querySelector("#querJa").value; const notaJogo = document.querySelector("#nota").value; querJaFav.push(querJa); tituloNotas.push(titulo); textoNotas.push(texto); nota.push(notaJogo); atualizarListaNotas(); } function atualizarListaNotas() { const elements = document.querySelectorAll(".item-show"); for (let i = 0; i < elements.length; i++) { elements[i].parentNode.removeChild(elements[i]); } for (let i = 0; i < tituloNotas.length; i++) { const cloneItem = document.querySelector("#base-item").cloneNode(true); const parent = document.querySelector("#content"); parent.appendChild(cloneItem); cloneItem.className = "item-show"; cloneItem.querySelector('#excluir').onclick = function() { if (confirm("Tem Certeza ?")) { tituloNotas.splice(i,1); textoNotas.splice(i, 1); querJaFav.splice(i,1); nota.splice(i,1); atualizarListaNotas(); } else { return false; } } cloneItem.querySelector('#editar').onclick = function() { var editarJogo = prompt ('Edite o jogo') ; var editarEstilo = prompt ('Edite o Estilo'); var editarQuer = prompt ('Edite o Status'); var editarNota = prompt ('Edite a Nota'); nota[i] = editarNota; tituloNotas[i] = editarJogo; textoNotas[i] = editarEstilo; querJaFav[i] = editarQuer; atualizarListaNotas(); } cloneItem.querySelector(".item-title").textContent ="Jogo: " + tituloNotas[i] + " | " + nota[i]; cloneItem.querySelector(".item-text").textContent ="Estilo: " + textoNotas[i]; cloneItem.querySelector(".item-querJaFav").textContent ="Status: " + querJaFav[i]; } } /*----------------------------------------------------------------------------------------------*/
javascript
14
0.509541
106
32.208333
72
starcoderdata
package com.airmap.airmapsdk.networking.callbacks; import com.airmap.airmapsdk.AirMapException; import com.airmap.airmapsdk.models.pilot.AirMapPilot; public interface LoginCallback { void onSuccess(AirMapPilot pilot); void onError(AirMapException e); }
java
7
0.809886
53
28.222222
9
starcoderdata
[TestMethod] public void MembershipRole_GetUsersInRoleTests() { string roleName; string[] results; //------------------------------------------------------- // existing role no users //------------------------------------------------------- roleName = TestUtils.ProviderRoles[10]; results = _provider.GetUsersInRole(roleName); Assert.IsNotNull(results); Assert.AreEqual<int>(0, results.Length); //------------------------------------------------------- // existing role with users //------------------------------------------------------- roleName = TestUtils.ProviderRoles[0]; results = _provider.GetUsersInRole(roleName); Assert.IsNotNull(roleName); Assert.AreEqual<int>(3, results.Length); Assert.AreEqual<string>(TestUtils.Users[0].Username, results[0]); Assert.AreEqual<string>(TestUtils.Users[2].Username, results[1]); Assert.AreEqual<string>(TestUtils.Users[4].Username, results[2]); //------------------------------------------------------- // nonexisting role //------------------------------------------------------- roleName = Guid.NewGuid().ToString(); try { results = _provider.GetUsersInRole(roleName); Assert.Fail("Provider did not throw expected ProviderException"); } catch(ProviderException) { //ignore expected exception } //------------------------------------------------------- // null role //------------------------------------------------------- roleName = null; try { results = _provider.GetUsersInRole(roleName); Assert.Fail("Provider did not throw expected ArgumentNullException"); } catch (ArgumentNullException) { //ignore expected exception } //------------------------------------------------------- // empty role //------------------------------------------------------- roleName = string.Empty; try { results = _provider.GetUsersInRole(roleName); Assert.Fail("Provider did not throw expected ArgumentException"); } catch (ArgumentException) { //ignore expected exception } }
c#
12
0.386807
85
40.703125
64
inline
package de.quinscape.exceed.runtime.domain; import de.quinscape.exceed.runtime.RuntimeContext; import de.quinscape.exceed.runtime.component.DataGraph; import de.quinscape.exceed.runtime.expression.query.QueryDefinition; public class SystemStorageOperations implements DomainOperations { @Override public DataGraph query(RuntimeContext runtimeContext, DomainService domainService, QueryDefinition queryDefinition) { throw new UnsupportedOperationException("System storage does not support query()"); } @Override public DomainObject create(RuntimeContext runtimeContext, DomainService domainService, String type, String id, Class<? extends DomainObject> implClass) { final GenericDomainObject genericDomainObject = new GenericDomainObject(); genericDomainObject.setDomainType(type); genericDomainObject.setDomainService(domainService); genericDomainObject.setId(id); return genericDomainObject; } @Override public DomainObject read(RuntimeContext runtimeContext, DomainService domainService, String type, String id) { throw new UnsupportedOperationException("System storage does not support read()"); } @Override public boolean delete(RuntimeContext runtimeContext, DomainService domainService, DomainObject genericDomainObject) { throw new UnsupportedOperationException("System storage does not support delete()"); } @Override public void insert(RuntimeContext runtimeContext, DomainService domainService, DomainObject genericDomainObject) { throw new UnsupportedOperationException("System storage does not support insert()"); } @Override public void insertOrUpdate(RuntimeContext runtimeContext, DomainService domainService, DomainObject genericDomainObject) { throw new UnsupportedOperationException("System storage does not support insertOrUpdate()"); } @Override public boolean update(RuntimeContext runtimeContext, DomainService domainService, DomainObject genericDomainObject) { throw new UnsupportedOperationException("System storage does not support update()"); } }
java
9
0.746768
144
33.507692
65
starcoderdata
/* * Artifactory is a binaries repository manager. * Copyright (C) 2012 JFrog Ltd. * * Artifactory is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Artifactory is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Artifactory. If not, see */ package org.artifactory.factory.xstream; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.HierarchicalStreamDriver; import com.thoughtworks.xstream.io.xml.QNameMap; import com.thoughtworks.xstream.io.xml.StaxDriver; import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder; import com.thoughtworks.xstream.mapper.MapperWrapper; import com.thoughtworks.xstream.security.ArrayTypePermission; import com.thoughtworks.xstream.security.NoTypePermission; import com.thoughtworks.xstream.security.NullPermission; import com.thoughtworks.xstream.security.PrimitiveTypePermission; import org.artifactory.model.common.RepoPathImpl; import org.artifactory.repo.RepoPath; import org.artifactory.util.PrettyStaxDriver; import javax.annotation.Nullable; import java.util.Collection; /** * @author */ public abstract class XStreamFactory { private XStreamFactory() { // utility class } public static XStream create(Class... annotatedClassesToProcess) { return createXStream(null, false, annotatedClassesToProcess); } public static XStream create(@Nullable QNameMap qNameMap, Class... annotatedClassesToProcess) { return createXStream(qNameMap, false, annotatedClassesToProcess); } /** * Creates a missing field tolerating instance of XStream * * @param annotatedClassesToProcess Classes to process * @return XStream instance */ public static XStream createMissingFieldTolerating(Class... annotatedClassesToProcess) { return createXStream(null, true, annotatedClassesToProcess); } /** * Creates XStream not escaping single underscores */ public static XStream createWithUnderscoreFriendly(Class... annotatedClassesToProcess) { return createXStream1(true, new PrettyStaxDriver(null, new XmlFriendlyNameCoder("_-", "_")), annotatedClassesToProcess); } /** * Creates an XStream instance * * @param qNameMap Optional map * @param ignoreMissingMembers True if missing fields should be ignored * @param annotatedClassesToProcess Classes to process * @return XStream instance */ private static XStream createXStream(@Nullable QNameMap qNameMap, boolean ignoreMissingMembers, Class... annotatedClassesToProcess) { return createXStream1(ignoreMissingMembers, new PrettyStaxDriver(qNameMap), annotatedClassesToProcess); } private static XStream createXStream1(boolean ignoreMissingMembers, StaxDriver staxDriver, Class... annotatedClassesToProcess) { XStream xstream = new ResilientXStream(ignoreMissingMembers, staxDriver); xstream.registerConverter(new RepoPathConverter()); xstream.registerConverter(new PropertiesConverter()); xstream.registerConverter(new ChecksumsInfoConverter()); xstream.registerConverter(new UserGroupInfoConverter()); for (Class annotatedClass : annotatedClassesToProcess) { xstream.processAnnotations(annotatedClass); } xstream.alias("repoPath", RepoPath.class, RepoPathImpl.class); // clear out existing permissions and set own ones xstream.addPermission(NoTypePermission.NONE); // allow some basics xstream.addPermission(NullPermission.NULL); xstream.addPermission(PrimitiveTypePermission.PRIMITIVES); xstream.addPermission(ArrayTypePermission.ARRAYS); xstream.allowTypeHierarchy(Collection.class); xstream.allowTypeHierarchy(String.class); // allow any type from the same package xstream.allowTypesByWildcard(new String[]{"org.artifactory.**", "org.jfrog.**"}); return xstream; } /** * XStream instance that can optionally ignore missing fields */ private static class ResilientXStream extends XStream { private boolean ignoreMissingMembers; private ResilientXStream(boolean ignoreMissingMembers, HierarchicalStreamDriver driver) { super(driver); this.ignoreMissingMembers = ignoreMissingMembers; } @Override protected MapperWrapper wrapMapper(MapperWrapper next) { return new MapperWrapper(next) { @Override public boolean shouldSerializeMember(Class definedIn, String fieldName) { return (!ignoreMissingMembers || (definedIn != Object.class)) ? super.shouldSerializeMember(definedIn, fieldName) : false; } }; } } }
java
19
0.718085
111
38.79562
137
starcoderdata
protected void assertEquals(RandomDocument doc, Fields fields) throws IOException { // compare field names assertEquals(doc == null, fields == null); assertEquals(doc.fieldNames.length, fields.size()); final Set<String> fields1 = new HashSet<>(); final Set<String> fields2 = new HashSet<>(); for (int i = 0; i < doc.fieldNames.length; ++i) { fields1.add(doc.fieldNames[i]); } for (String field : fields) { fields2.add(field); } assertEquals(fields1, fields2); for (int i = 0; i < doc.fieldNames.length; ++i) { assertEquals(doc.tokenStreams[i], doc.fieldTypes[i], fields.terms(doc.fieldNames[i])); } }
java
12
0.64275
92
36.222222
18
inline
module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), sass: { options: { includePaths: [ 'node_modules/foundation-sites/scss', 'node_modules/font-awesome/scss', 'node_modules/sass-flex-mixin/', 'node_modules/angularjs-datepicker/src/css/' ] }, dist: { options: { outputStyle: 'compressed' }, files: { 'web/assets/css/app.css': 'src/scss/app.scss' } } }, concat: { dist: { src: [ "src/**/*.module.js", "src/**/**!(.module).js" ], dest: "web/assets/js/app.js" } }, uglify: { dist: { files: { "web/assets/js/app.min.js": ["web/assets/js/app.js"] } } }, copy: { main: { files: [ { flatten: false, expand: true, cwd: 'node_modules/twemoji/svg/', src: ['**/*.svg'], dest: 'web/images/twemoji/svg/', filter: 'isFile' }, { flatten: true, src: ['node_modules/twemoji/twemoji.npm.js'], dest: 'web/assets/js/twemoji.min.js', filter: 'isFile' }, { flatten: true, src: ['node_modules/markdown-it-emoji/dist/markdown-it-emoji.min.js'], dest: 'web/assets/js/markdown-it-emoji.min.js', filter: 'isFile' }, { flatten: true, src: ['node_modules/markdown-it/dist/markdown-it.js'], dest: 'web/assets/js/markdown-it.js', filter: 'isFile' }, { flatten: true, src: ['node_modules/angular-storage/dist/angular-storage.js'], dest: 'web/assets/js/angular-storage.js', filter: 'isFile' }, { flatten: true, src: ['node_modules/angular-lodash/angular-lodash.js'], dest: 'web/assets/js/angular-lodash.js', filter: 'isFile' }, { flatten: true, src: ['node_modules/lodash/lodash.js'], dest: 'web/assets/js/lodash.js', filter: 'isFile' }, { flatten: true, src: ['node_modules/angular-mm-foundation/src/topbar/topbar.js'], dest: 'web/assets/js/topbar.js', filter: 'isFile' }, { flatten: true, src: ['node_modules/angular-mm-foundation/src/dropdownToggle/dropdownToggle.js'], dest: 'web/assets/js/dropdownToggle.js', filter: 'isFile' }, { flatten: true, src: ['node_modules/angular-file-upload/dist/angular-file-upload.js'], dest: 'web/assets/js/angular-file-upload.js', filter: 'isFile' }, { flatten: true, src: ['node_modules/angular-mm-foundation/src/position/position.js'], dest: 'web/assets/js/position.js', filter: 'isFile' }, { flatten: true, src: ['node_modules/angular-mm-foundation/src/typeahead/typeahead.js'], dest: 'web/assets/js/typeahead.js', filter: 'isFile' }, { flatten: true, src: ['node_modules/angular-mm-foundation/src/bindHtml/bindHtml.js'], dest: 'web/assets/js/bindHtml.js', filter: 'isFile' }, { flatten: true, src: ['node_modules/angular-mm-foundation/src/mediaQueries/mediaQueries.js'], dest: 'web/assets/js/mediaQueries.js', filter: 'isFile' }, { flatten: true, src: ['node_modules/angular-mm-foundation/src/tabs/tabs.js'], dest: 'web/assets/js/tabs.js', filter: 'isFile' }, { flatten: true, src: ['node_modules/angular-loading-bar/build/loading-bar.js'], dest: 'web/assets/js/loading-bar.js', filter: 'isFile' }, { flatten: true, src: ['node_modules/angular-loading-bar/build/loading-bar.css'], dest: 'web/assets/css/loading-bar.css', filter: 'isFile' }, { flatten: true, src: ['node_modules/angular-mm-foundation/src/transition/transition.js'], dest: 'web/assets/js/transition.js', filter: 'isFile' }, { flatten: true, src: ['node_modules/ng-sortable/dist/ng-sortable.js'], dest: 'web/assets/js/ng-sortable.js', filter: 'isFile' }, { flatten: true, src: ['node_modules/angular/angular.js'], dest: 'web/assets/js/angular.js', filter: 'isFile' }, { flatten: true, src: ['node_modules/angular-ui-router/release/angular-ui-router.min.js'], dest: 'web/assets/js/angular-ui-router.js', filter: 'isFile' }, { flatten: true, src: ['node_modules/ng-sortable/dist/ng-sortable.min.css'], dest: 'web/assets/css/ng-sortable.min.css', filter: 'isFile' }, { flatten: true, src: ['node_modules/angularjs-datepicker/dist/angular-datepicker.min.js'], dest: 'web/assets/js/angularjs-datepicker.min.js', filter: 'isFile' }, { flatten: false, expand: true, cwd: 'node_modules/angular-mm-foundation/template', src: '**', dest: 'web/template/', filter: 'isFile' }, { flatten: true, expand: true, cwd: 'node_modules/foundation-sites/js/foundation/', src: '**', dest: 'web/assets/js', filter: 'isFile' }, { flatten: true, expand: true, cwd: 'node_modules/font-awesome/fonts/', src: '**', dest: 'web/assets/fonts/', filter: 'isFile' }, { flatten: false, expand: true, cwd: 'src/', src: ['**/*.js'], dest: 'web/assets/js/', filter: 'isFile' }, { flatten: false, expand: true, cwd: 'src/', src: ['**/*.html'], dest: 'web/assets/html/', filter: 'isFile' }, { flatten: true, src: ['src/user/views/oauth.html'], dest: 'web/assets/html/user/views/oauth.html', filter: 'isFile' }, { flatten: false, expand: true, cwd: 'src/static/images/', src: ['**/*.svg', '**/*.png'], dest: 'web/images/', filter: 'isFile' } ] } }, watch: { grunt: { files: ['Gruntfile.js'], tasks: ['sass', 'copy'] }, sass: { files: 'src/scss/*.scss', tasks: ['sass'] }, copy: { files: ['src/**/*.js', 'src/**/*.html'], tasks: ['copy'] }, concat: { files: ['src/**/*.js'], tasks: ['concat'] }, uglify: { files: ['web/assets/js/app.js'], tasks: ['uglify'] } } }); grunt.loadNpmTasks('grunt-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.registerTask('build', ['sass', 'copy', 'concat', 'uglify']); grunt.registerTask('default', ['build', 'watch']); };
javascript
30
0.345659
105
36.629893
281
starcoderdata
s=input() N=len(s) ans='' for i in range(0, N, 2): ans+=s[i] print(ans)
python
6
0.539474
24
10
7
codenet
USING_CHPSIM_DLFUNCTION_PROLOGUE // bogus function, with wrong argument type static int_value_type bad_gcd(const bool_value_type a, const bool_value_type b) { return 7; }
c++
6
0.763006
59
18.333333
9
inline
def download_official_wheels(): """ Download the official wheels for each platform """ assert AZURE_STORAGE_CONNECTION_STRING, \ 'Set AZURE_STORAGE_CONNECTION_STRING environment variable' # Clear previous downloads utility.clean_up(utility.MSSQLCLI_DIST_DIRECTORY) os.mkdir(utility.MSSQLCLI_DIST_DIRECTORY) print('Downloading official wheels and sdist with version: {}'.format(latest_version)) blob_names = [ 'mssql_cli-{}-py2.py3-none-macosx_10_11_intel.whl'.format(latest_version), 'mssql_cli-{}-py2.py3-none-manylinux1_x86_64.whl'.format(latest_version), 'mssql_cli-{}-py2.py3-none-win_amd64.whl'.format(latest_version), 'mssql_cli-{}-py2.py3-none-win32.whl'.format(latest_version) ] blob_service = BlockBlobService(connection_string=AZURE_STORAGE_CONNECTION_STRING) for blob in blob_names: print('Downloading file:{}'.format(blob)) if not blob_service.exists(BLOB_MSSQL_CLI_DAILY_CONTAINER_NAME, blob): print('Error: blob: {} does not exist in container: {}'\ .format(blob, BLOB_MSSQL_CLI_DAILY_CONTAINER_NAME)) sys.exit(1) blob_service.get_blob_to_path(BLOB_MSSQL_CLI_DAILY_CONTAINER_NAME, blob, os.path.join(utility.MSSQLCLI_DIST_DIRECTORY, blob))
python
13
0.654385
90
44.266667
30
inline
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var getTreeLeafDataByIndexArray = function getTreeLeafDataByIndexArray(data, indexArray) { var childrenName = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'children'; var length = indexArray.length; var p = 0; var r = data; while (p < length) { r = r[childrenName][indexArray[p]]; p += 1; } return r; }; var withChildrenName = function withChildrenName(childrenName) { return function (data, indexArray) { return getTreeLeafDataByIndexArray(data, indexArray, childrenName); }; }; exports.withChildrenName = withChildrenName; exports.default = getTreeLeafDataByIndexArray;
javascript
13
0.714882
100
25.666667
27
starcoderdata
package br.usp.each.saeg.baduino.xml; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import java.util.Arrays; import java.util.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class XMLPackageTests { private static XMLPackage pkg; @BeforeClass public static void setUpBeforeClass() throws Exception { pkg = new XMLPackage(); pkg.setName("imc/usp/IMC"); } @AfterClass public static void tearDownAfterClass() throws Exception { pkg = null; } @Test public final void testProperties() { assertThat(pkg, hasProperty("name")); assertThat(pkg, hasProperty("classes")); } @Test public final void testGetName() { assertThat(pkg.getName(), is("imc.usp")); } @Test public final void testGetClasses() { final XMLClass clazz1 = new XMLClass(); clazz1.setName("imc/usp/IMC1"); final XMLClass clazz2 = new XMLClass(); clazz2.setName("imc/usp/IMC2"); final XMLClass clazz3 = new XMLClass(); clazz3.setName("imc/usp/calc/Calc"); final List classes = Arrays.asList(clazz1, clazz2, clazz3); pkg.setClasses(classes); assertThat(pkg.getClasses(), hasSize(3)); assertThat(pkg.getClasses(), containsInAnyOrder(clazz1, clazz2, clazz3)); } @Test public final void testToString() { assertThat(pkg.toString(), is("imc.usp")); } }
java
9
0.724801
123
22.936508
63
starcoderdata
private < R extends RealType<R>> double padOperation( RandomAccess< R > access, int dimension, double last, double z, double Ci ) { access.fwd( dimension ); padding[ 0 ] = access.get().getRealDouble() + z * last; // do paddingWidth more causal operations for( int i = 1; i < paddingWidth; i++ ) { access.fwd( dimension ); padding[ i ] = access.get().getRealDouble() + z * padding[ i - 1 ]; } // initialize anticausal // coefs[ N-1 ] = Ci * ( coefs[ N-1 ] + z * coefs[ N-2 ] ); padding [ paddingWidth - 1 ] += z * padding [ paddingWidth - 2 ]; padding [ paddingWidth - 1 ] *= Ci; // do paddingWith anticausal operations for( int i = paddingWidth - 2; i >=0; i-- ) { padding[ i ] = z * ( padding[ i + 1 ] - padding[ i ] ); } return padding[ 0 ]; }
java
12
0.590909
129
30.72
25
inline
import unittest import numpy as np def self_test(): import EggNetExtension img = np.random.rand(100, 28, 28, 4).astype(np.float32) K = np.random.rand(3, 3, 4, 8).astype(np.float32) o = EggNetExtension.conv2d(img, K, 1) print("o.shape = ", o.shape) o2 = EggNetExtension.maxPool2D(o) EggNetExtension.relu4D(o2) print("o2.shape = ", o2.shape) # Try to trigger exception by prividing bad kernel K = np.random.rand(4, 4, 4, 8).astype( np.float32) # only odd numbers are allowed o = EggNetExtension.conv2d(img, K, 1) def get_uniform_test_image_and_kernel(shape_image, shape_kernel): K = np.random.rand(*shape_kernel).astype(np.float32) - 0.5 I = np.random.rand(*shape_image).astype(np.float32) - 0.5 return I, K class NNExtensionTestCase(unittest.TestCase): NUMERIC_EPS = 1e-4 def test_generic(self): from EggNetExtension import conv2d, maxPool2D, relu4D I, K = get_uniform_test_image_and_kernel( (10, 28, 28, 10), (3, 3, 10, 20)) o = conv2d(I, K, 1) print("o.shape = ", o.shape) o2 = maxPool2D(o) relu4D(o2) print("o2.shape = ", o2.shape) def test_conv(self): from EggNet import conv2d from EggNetExtension import conv2d as conv2d_ext from EggNetExtension import conv2d_3x3 # Get images and kernel and keep workload small I, K = get_uniform_test_image_and_kernel((5, 14, 14, 3), (3, 3, 3, 6)) Y_ext = conv2d_ext(I, K, 1) Y_ext2 = conv2d_3x3(I, K) Y = conv2d(I, K, stride=1) self.assertEqual(Y.shape, Y_ext.shape) for (di_1, di_2) in zip(Y.shape, Y_ext.shape): self.assertEqual(di_1, di_2) self.assertTrue(np.allclose(Y, Y_ext2, atol=self.NUMERIC_EPS)) def test_conv_speed(self): import time from EggNetExtension import conv2d_3x3 from EggNetExtension import conv2d as conv2d_ext from EggNet import conv2d n_runs = 10 # Get large image data set I, K = get_uniform_test_image_and_kernel( (10, 28, 28, 6), (3, 3, 6, 12)) print("Code Time") t_start = time.time() for i in range(n_runs): _ = conv2d_3x3(I, K) t_end = time.time() t_cext = (t_end - t_start) / n_runs print("C-Ext ", t_cext) t_start = time.time() for i in range(n_runs): _ = conv2d_ext(I, K, 1) t_end = time.time() t_cext2 = (t_end - t_start) / n_runs print("C-Ext2 ", t_cext2) t_start = time.time() for i in range(n_runs): _ = conv2d(I, K) t_end = time.time() t_py = (t_end - t_start) / n_runs print("Python ", t_py) # Speedup is >100 print("Speedup: ", t_py / t_cext) def test_relu_speed(self): import time from EggNetExtension import relu4D from EggNet import relu n_runs = 100 # Get large image data set I, _ = get_uniform_test_image_and_kernel( (10, 28, 28, 6), (3, 3, 6, 12)) print("Code Time") t_start = time.time() for i in range(n_runs): _ = relu4D(I) t_end = time.time() t_cext = (t_end - t_start) / n_runs print("C-Ext ", t_cext) t_start = time.time() for i in range(n_runs): _ = relu(I) t_end = time.time() t_py = (t_end - t_start) / n_runs print("Python ", t_py) # Speedup is ~2 print("Speedup: ", t_py / t_cext) def test_pool_speed(self): import time from EggNetExtension import maxPool2D from EggNet import pooling_max n_runs = 100 # Get large image data set I, _ = get_uniform_test_image_and_kernel( (10, 28, 28, 6), (3, 3, 6, 12)) print("Code Time") t_start = time.time() for i in range(n_runs): _ = maxPool2D(I) t_end = time.time() t_cext = (t_end - t_start) / n_runs print("C-Ext ", t_cext) t_start = time.time() for i in range(n_runs): _ = pooling_max(I, pool_size=2) t_end = time.time() t_py = (t_end - t_start) / n_runs print("Python ", t_py) # Speedup is ~2 print("Speedup: ", t_py / t_cext) def test_relu_1(self): from EggNetExtension import relu1D negatives = np.random.rand(1000).astype(np.float32) - 10 self.assertTrue(np.all(negatives < 0)) relu1D(negatives) self.assertTrue(np.all(negatives < 0.00000001)) self.assertTrue(np.all(negatives > -0.00000001)) def test_relu_ndim(self): from EggNet import relu import EggNetExtension sizes_to_test = [ (100, 100), (10, 100, 100), (10, 100, 100, 10), ] for size in sizes_to_test: x = np.random.rand(*size).astype(np.float32) x_relu1 = x.copy() x_relu2 = relu(x) if x.ndim == 2: EggNetExtension.relu2D(x_relu1) elif x.ndim == 3: EggNetExtension.relu3D(x_relu1) elif x.ndim == 4: EggNetExtension.relu4D(x_relu1) else: raise ValueError() self.assertTrue(np.allclose( x_relu1, x_relu2, atol=self.NUMERIC_EPS)) def test_int(self): from EggNet import relu import EggNetExtension x1 = np.random.rand(100).astype(dtype=np.int16) * 10 - 5 x2 = x1.copy() EggNetExtension.relu_int16_t_inplace(x1) x2 = relu(x2) np.allclose(x1, x2, atol=self.NUMERIC_EPS) if __name__ == '__main__': self_test() unittest.main()
python
14
0.531968
78
28.795
200
starcoderdata
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.lib.editor.util; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.AbstractList; import java.util.ArrayList; import java.util.EventListener; import java.util.Iterator; import java.util.List; /** * Listener list storing listeners of a single type. * * @author * @since 1.11 */ public final class ListenerList<T extends EventListener> implements Serializable { static final long serialVersionUID = 0L; /** A null array to be shared by all empty listener lists */ private static final EventListener[] EMPTY_LISTENER_ARRAY = new EventListener[0]; /* The array of listeners. */ private transient ImmutableList listenersList; public ListenerList() { listenersList = new ImmutableList } /** * Returns a list of listeners. * * listeners are returned in exactly the same order * as they were added to this list. Use the following code * for firing events to all the listeners you get from this * method. * * * List listeners = listenerList.getListeners(); * for (MyListener l : listeners) { * l.notify(evt); * } * * * @return An immutable list of listeners contained in this listener list. */ public synchronized List getListeners() { return listenersList; } /** * Returns the total number of listeners for this listener list. */ public synchronized int getListenerCount() { return listenersList.size(); } /** * Adds the given listener to this listener list. * * @param listener the listener to be added. If null is passed it is ignored (nothing gets added). */ public synchronized void add(T listener) { if (listener == null) return; EventListener [] arr = new EventListener[listenersList.getArray().length + 1]; if (arr.length > 1) { System.arraycopy(listenersList.getArray(), 0, arr, 0, arr.length - 1); } arr[arr.length - 1] = listener; listenersList = new ImmutableList } /** * Removes the given listener from this listener list. * * @param listener the listener to be removed. If null is passed it is ignored (nothing gets removed). */ public synchronized void remove(T listener) { if (listener == null) return; int idx = listenersList.indexOf(listener); if (idx == -1) { return; } EventListener [] arr = new EventListener[listenersList.getArray().length - 1]; if (arr.length > 0) { System.arraycopy(listenersList.getArray(), 0, arr, 0, idx); } if (arr.length > idx) { System.arraycopy(listenersList.getArray(), idx + 1, arr, idx, listenersList.getArray().length - idx - 1); } listenersList = new ImmutableList } // Serialization support. private void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); // Write in opposite order of adding for (Iterator i = listenersList.iterator(); i.hasNext(); ) { T l = i.next(); // Save only the serializable listeners if (l instanceof Serializable) { s.writeObject(l); } } s.writeObject(null); } private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); List lList = new ArrayList Object listenerOrNull; while (null != (listenerOrNull = s.readObject())) { @SuppressWarnings("unchecked") T l = (T)listenerOrNull; lList.add(l); } this.listenersList = new ImmutableList [])lList.toArray(new EventListener[lList.size()])); } public String toString() { return listenersList.toString(); } private static final class ImmutableList<E extends EventListener> extends AbstractList { private EventListener[] array; public ImmutableList(EventListener[] array) { super(); assert array != null : "The array can't be null"; //NOI18N this.array = array; } public E get(int index) { if (index >= 0 && index < array.length) { @SuppressWarnings("unchecked") E element = (E) array[index]; return element; } else { throw new IndexOutOfBoundsException("index = " + index + ", size = " + array.length); //NOI18N } } public int size() { return array.length; } public EventListener[] getArray() { return array; } } // End of ImmutableList class }
java
16
0.605162
117
31.254054
185
starcoderdata
const glob = require('glob') glob('**/*.js', { ignore: [ '**/node_modules/**' ] }, function (er, files) { console.log(files) })
javascript
9
0.544776
28
13.888889
9
starcoderdata
import os, os.path from io import BytesIO from adaguc.CGIRunner import CGIRunner import unittest import shutil import subprocess import json from lxml import etree from lxml import objectify import re from .AdagucTestTools import AdagucTestTools # import sys # sys.path.insert(0, '/nobackup/users/bennekom/adaguc-webmapjs-sld-server/env/lib/python3.6/site-packages/flask/__init__.py') # from flask import Flask ADAGUC_PATH = os.environ['ADAGUC_PATH'] DEFAULT_REQUEST_PARAMS = "SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS=radar&WIDTH=512&HEIGHT=512&CRS=EPSG%3A4326&BBOX=30,-30,75,30&FORMAT=image/png&TRANSPARENT=TRUE"; class TestWMSSLD(unittest.TestCase): testresultspath = "testresults/TestWMSSLD/" expectedoutputsspath = "expectedoutputs/TestWMSSLD/" env={'ADAGUC_CONFIG' : ADAGUC_PATH + "/data/config/adaguc.sld.xml"} AdagucTestTools().mkdir_p(testresultspath); def compareXML(self,xml,expectedxml): obj1 = objectify.fromstring(re.sub(' xmlns="[^"]+"', '', expectedxml, count=1)) obj2 = objectify.fromstring(re.sub(' xmlns="[^"]+"', '', xml, count=1)) # Remove ADAGUC build date and version from keywordlists for child in obj1.findall("Service/KeywordList")[0]:child.getparent().remove(child) for child in obj2.findall("Service/KeywordList")[0]:child.getparent().remove(child) # Boundingbox extent values are too varying by different Proj libraries def removeBBOX(root): if (root.tag.title() == "Boundingbox"): #root.getparent().remove(root) try: del root.attrib["minx"] del root.attrib["miny"] del root.attrib["maxx"] del root.attrib["maxy"] except: pass for elem in root.getchildren(): removeBBOX(elem) removeBBOX(obj1); removeBBOX(obj2); result = etree.tostring(obj1) expect = etree.tostring(obj2) self.assertEquals(expect, result) def checkReport(self, reportFilename="", expectedReportFilename=""): self.assertTrue(os.path.exists(reportFilename)) self.assertEqual(AdagucTestTools().readfromfile(reportFilename), AdagucTestTools().readfromfile(self.expectedoutputsspath + expectedReportFilename)) os.remove(reportFilename) def test_WMSGetMap_testdatanc_NOSLD(self): AdagucTestTools().cleanTempDir() filename="test_WMSGetMap_testdatanc_NOSLD.png" status,data,headers = AdagucTestTools().runADAGUCServer(args = ['--updatedb', '--config', ADAGUC_PATH + '/data/config/adaguc.sld.xml'], env = self.env, isCGI = False, showLogOnError = True) self.assertEqual(status, 0) status,data,headers = AdagucTestTools().runADAGUCServer(DEFAULT_REQUEST_PARAMS, env = self.env) AdagucTestTools().writetofile(self.testresultspath + filename,data.getvalue()) self.assertEqual(status, 0) self.assertEqual(data.getvalue(), AdagucTestTools().readfromfile(self.expectedoutputsspath + filename)) def test_WMSGetMap_testdatanc_NOSLDURL(self): AdagucTestTools().cleanTempDir() filename="test_WMSGetMap_testdatanc_NOSLDURL.xml" status,data,headers = AdagucTestTools().runADAGUCServer(DEFAULT_REQUEST_PARAMS + "&SLD=", env = self.env, showLogOnError = False) AdagucTestTools().writetofile(self.testresultspath + filename,data.getvalue()) self.assertEqual(status, 1) # def test_WMSGetMap_WITHSLD_testdatanc(self): # AdagucTestTools().cleanTempDir() # Start flask server # filename="test_WMSGetMap_testdatanc_WITHSLD.png" # # status,data,headers = AdagucTestTools().runADAGUCServer(args = ['--updatedb', '--config', ADAGUC_PATH + '/data/config/adaguc.sld.xml'], env = self.env, isCGI = False, showLogOnError = True) # self.assertEqual(status, 0) # # status,data,headers = AdagucTestTools().runADAGUCServer("SERVICE=WMS&SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS=radar&WIDTH=512&HEIGHT=512&CRS=EPSG%3A4326&BBOX=30,-30,75,30&FORMAT=image/png&TRANSPARENT=FALSE&SHOWLEGEND=TRUE&SLD=http://0.0.0.0:5000/sldFiles/radar.xml", # env = self.env) # AdagucTestTools().writetofile(self.testresultspath + filename,data.getvalue()) # self.assertEqual(status, 0) # self.assertEqual(data.getvalue(), AdagucTestTools().readfromfile(self.expectedoutputsspath + filename))
python
14
0.652535
283
47.895833
96
starcoderdata
FN_INTERNAL int fnusb_list_device_attributes(fnusb_ctx *ctx, struct freenect_device_attributes** attribute_list) { // todo: figure out how to log without freenect_context *attribute_list = NULL; // initialize some return value in case the user is careless. libusb_device **devs; // pointer to pointer of device, used to retrieve a list of devices ssize_t count = libusb_get_device_list (ctx->ctx, &devs); if (count < 0) { return -1; } struct freenect_device_attributes** next_attr = attribute_list; // Pass over the list. For each camera seen, if we already have a camera // for the newest_camera device, allocate a new one and append it to the list, // incrementing num_cams. int num_cams = 0; int i; for (i = 0; i < count; i++) { libusb_device* camera_device = devs[i]; struct libusb_device_descriptor desc; int res = libusb_get_device_descriptor (camera_device, &desc); if (res < 0) { continue; } if (desc.idVendor == VID_MICROSOFT && (desc.idProduct == PID_NUI_CAMERA || desc.idProduct == PID_K4W_CAMERA)) { // Verify that a serial number exists to query. If not, don't touch the device. if (desc.iSerialNumber == 0) { continue; } libusb_device_handle *camera_handle; res = libusb_open(camera_device, &camera_handle); if (res != 0) { continue; } // Read string descriptor referring to serial number. unsigned char serial[256]; // String descriptors are at most 256 bytes. res = libusb_get_string_descriptor_ascii(camera_handle, desc.iSerialNumber, serial, 256); libusb_close(camera_handle); if (res < 0) { continue; } // K4W and 1473 don't provide a camera serial; use audio serial instead. const char* const K4W_1473_SERIAL = "0000000000000000"; if (strncmp((const char*)serial, K4W_1473_SERIAL, 16) == 0) { libusb_device* audio_device = fnusb_find_connected_audio_device(camera_device, devs, count); if (audio_device != NULL) { struct libusb_device_descriptor audio_desc; res = libusb_get_device_descriptor(audio_device, &audio_desc); if (res != 0) { //FN_ERROR("Failed to get audio serial descriptors of K4W or 1473 device: %d\n", res); } else { libusb_device_handle * audio_handle = NULL; res = libusb_open(audio_device, &audio_handle); if (res != 0) { //FN_ERROR("Failed to open audio device for serial of K4W or 1473 device: %d\n", res); } else { res = libusb_get_string_descriptor_ascii(audio_handle, audio_desc.iSerialNumber, serial, 256); libusb_close(audio_handle); if (res != 0) { //FN_ERROR("Failed to get audio serial of K4W or 1473 device: %d\n", res); } } } } } // Add item to linked list. struct freenect_device_attributes* current_attr = (struct freenect_device_attributes*)malloc(sizeof(struct freenect_device_attributes)); memset(current_attr, 0, sizeof(*current_attr)); current_attr->camera_serial = strdup((char*)serial); *next_attr = current_attr; next_attr = &(current_attr->next); num_cams++; } } libusb_free_device_list(devs, 1); return num_cams; }
c
22
0.650784
139
29.980583
103
inline
<?php Route::group([ 'prefix' => LaravelLocalization::setLocale(), 'middleware' => [ 'localeSessionRedirect', 'localizationRedirect', 'localeViewPath' ,'auth'] ], function () { Route::group(['prefix' => 'profile'], function () { Route::get('/', 'ProfileController@getIndex')->name('profile.index'); Route::get('/edit', 'ProfileController@getEdit')->name('profile.edit'); Route::post('/edit', 'ProfileController@postEdit')->name('profile.edit'); Route::post('/change-password', 'ProfileController@changePassword')->name('profile.changePassword'); Route::get('/money-requests', 'ProfileController@getMoneyRequests'); Route::get('/orders', 'ProfileController@getOrders'); Route::get('/order/{order_id}', 'ProfileController@getOrderDetails'); }); });
php
19
0.669967
108
46.842105
19
starcoderdata
package com.tryfit.qrcode; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.Toast; import com.google.zxing.Result; import com.tryfit.MainActivity; import com.tryfit.R; import com.tryfit.common.OnFragmentInteractionListener; import me.dm7.barcodescanner.zxing.ZXingScannerView; public class QRCodeFragment extends Fragment implements ZXingScannerView.ResultHandler { private static final String TAG = QRCodeFragment.class.getSimpleName(); private static final int MY_PERMISSIONS_REQUEST_CAMERA = 0; private OnFragmentInteractionListener mListener; private ZXingScannerView mScannerView; public QRCodeFragment() { } public static QRCodeFragment newInstance() { return new QRCodeFragment(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.fragment_qrcode, container, false); mScannerView = new ZXingScannerView(getActivity()); FrameLayout viewContainer = rootView.findViewById(R.id.scanner_view_container); viewContainer.addView(mScannerView, 0); return rootView; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (checkCameraPermission()) { mScannerView.setResultHandler(this); mScannerView.startCamera(); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onResume() { super.onResume(); ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); if (actionBar != null) actionBar.setTitle(getString(R.string.qr_code)); ((MainActivity) getActivity()).selectTab(MainActivity.TABS.QRCode); } @Override public void onPause() { super.onPause(); mScannerView.stopCamera(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { Log.d(TAG, "onRequestPermissionsResult"); switch (requestCode) { case MY_PERMISSIONS_REQUEST_CAMERA: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { mScannerView.setResultHandler(this); mScannerView.startCamera(); } else { Toast.makeText(getActivity(), "Permission to use camera denied!", Toast.LENGTH_SHORT).show(); } break; } } } private boolean checkCameraPermission() { if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA); return false; } else { return true; } } @Override public void handleResult(Result result) { if (result != null) { mListener.onFragmentInteraction(R.id.scanner_view_container, result.getText()); } mScannerView.startCamera(); } }
java
17
0.659393
113
32.210145
138
starcoderdata
var Cryo = require('../lib/cryo'); var obj = { name: 'Hunter', created: new Date(), hello: function() { console.log(this.name + ' said hello in ' + this.created.getFullYear() + '!'); } }; var frozen = Cryo.stringify(obj); var hydrated = Cryo.parse(frozen); hydrated.hello(); // Hunter says hello in 2013!
javascript
15
0.60241
82
21.857143
14
starcoderdata
""" Created on March 18th, 2021 Predicting trajectories using a simple constant velocity model """ import numpy as np import torch from models.utils.utils import relative_traj_to_abs def predict_const_vel(obs_traj, pred_len=1, multi_modal=False, first_multi_modal=False): """ predict trajectories assuming a constant velocity :param obs_traj: observed trajectory (assumed to be in absolute coordinates). Expected to be a tensor of shape (obs_len, batch, 2) :param pred_len: for how many instants to perform prediction :param multi_modal: if True, generate based on average and standard deviation of velocities in module. This generates just one prediction, but it can be called more than once, and results will be different. :param first_multi_modal: if True, will not use standard deviation, just average value. This may improve the results :return: the predicted trajectories. Tensor of shape (pred_len, batch, 2) """ # this actually doesn't use velocity, uses relative displacement, but this is because one assumes a constant spacing # in time between the positions last_pos = obs_traj[-1] obs_rel = torch.zeros(obs_traj.shape, device=obs_traj.device) obs_rel[1:, :, :] = obs_traj[1:, :, :] - obs_traj[:-1, :, :] if multi_modal: vel = __cv_multimodal_direction__(obs_rel) else: vel = last_pos - obs_traj[-2] pred_traj_rel = vel.repeat(pred_len, 1, 1) pred_traj = relative_traj_to_abs(pred_traj_rel, last_pos) return pred_traj def __cv_multimodal_direction__(obs_rel, angle_std=25): """ Credits for this implementation goes to https://github.com/cschoeller/constant_velocity_pedestrian_motion From the paper entitled "What the Constant Velocity Model Can Teach Us About Pedestrian Motion Prediction" To cite, use: @article{article, author = {Schöller, Aravantinos, Lay, Knoll, Alois}, year = {2020}, month = {01}, pages = {1-1}, title = {What the Constant Velocity Model Can Teach Us About Pedestrian Motion Prediction}, volume = {PP}, journal = {IEEE Robotics and Automation Letters}, doi = {10.1109/LRA.2020.2969925} } :param obs_rel: Tensor of shape [obs_traj_len, num_peds, 2]. The relative displacements (simulating velocity) for each of the pedestrians. :param angle_std: Standard deviation of the rotation angle for the velocity direction, in degrees. By default will use 25 degrees, which is the value used in the original implementation :return: """ last_vel = obs_rel[-1] sampled_angle_deg = np.random.normal(0, angle_std, last_vel.shape[0]) theta = (sampled_angle_deg * np.pi) / 180. # convert from degrees to radians c, s = np.cos(theta), np.sin(theta) rotation_mat = torch.tensor([[c, s], [-s, c]], dtype=last_vel.dtype) # i j n new_vel = torch.einsum('ijn,jn->in', rotation_mat, last_vel.T).T return new_vel def __cv_multimodal_speed__(obs_traj, obs_rel, last_pos, first_multi_modal): num_peds = obs_rel.shape[1] dims_pos = obs_rel.shape[2] # Use the entire observed length and the absolute velocity across instants to weight the constant velocities to # use. If the velocity is 0 then it will not be used. vel_obs_std_mean = torch.std_mean(torch.abs(obs_rel), dim=0) # weight_vel_obs = torch.mean(torch.abs(obs_rel), dim=0) vel = last_pos - obs_traj[-2] for idx in range(num_peds): for pos in range(dims_pos): if torch.is_nonzero(vel[idx][pos]): if first_multi_modal: weight = vel_obs_std_mean[1][idx][pos] else: weight = torch.normal(mean=vel_obs_std_mean[1][idx][pos], std=vel_obs_std_mean[0][idx][pos]) vel[idx][pos] *= weight / torch.abs(vel[idx][pos]) return vel
python
20
0.666838
120
45.285714
84
starcoderdata
/* Example of how to handle stdin redirect * * The problem is non-trivial since Linux epoll, which libuEv uses, does * not support I/O watchers for regular files or directories. * * This works: * echo foo | redirect * This doesn't: * redirect < foo.txt * * However, with a little bit of hacking libuEv can be made to handle * reading from stdin as a special case. */ #include #include #include #include #include #include "src/uev.h" void process_stdin(uev_t *w, void *arg, int events) { char buf[256]; int len; if (UEV_ERROR == events) { warnx("Spurious problem with the stdin watcher, restarting."); uev_io_start(w); } len = read(w->fd, buf, sizeof(buf)); if (len == -1) { warn("Error reading from stdin"); return; } if (len == 0 || UEV_HUP == events) { warnx("Connection closed."); return; } printf("Read %d bytes\n", len); if (write(STDOUT_FILENO, buf, len) != len) warn("Failed writing to stdout"); } int main(int argc, char **argv) { int ret; uev_t watcher; uev_ctx_t ctx; uev_init(&ctx); ret = uev_io_init(&ctx, &watcher, process_stdin, NULL, STDIN_FILENO, UEV_READ); if (ret) err(errno, "Failed setting up STDIN watcher"); return uev_run(&ctx, 0); } /** * Local Variables: * compile-command: "make redirect; echo hej > hej.txt; ./redirect < hej.txt" * indent-tabs-mode: t * c-file-style: "linux" * End: */
c
9
0.631579
80
20.202899
69
starcoderdata
private void highlightMarker(Graphics2D g) { // Change to red, and redraw the currently highlighted one if (mrkrIndex >= 0 && mrkrIndex < canvas.view.markerCount()) { g.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON); g.setColor(Color.red); int xS = canvas.pX1 / canvas.boxW; renderMarker(g, mrkrIndex, xS, true); } }
java
9
0.675978
62
28
12
inline
def __init__(self, graph, quantized=False): self._graph = graph self._quantized = quantized # All entities translated from ops. self._entities = [] # Node name -> index in self._entities self._name_to_entity = {} # Op type -> count self._op_count = {} #for node in graph.nodes: # entities = self.translate_op_to_entities(node.op) # self._entities.extend(entities) # # Post-order traversing in `self.translate_op_to_entities`, # # the last element in returned list is the entity converted from node.op. # self._name_to_entity[node.name] = len(self._entities) - 1 # node_entity = self.get_entity(node.name) # for i, tensor in enumerate(node.out_tensors): # # Use node entity's name as prefix # tensor_entity = Entity('%s_%d' % (node_entity.name, i), # EntityTypes.Tensor) # self._add_entity(tensor.name, tensor_entity) # node_entity.outputs.append(tensor_entity) #for node in graph.nodes: # entity = self.get_entity(node.name) # for i, tensor in enumerate(node.in_tensors): # entity.inputs.append(self.get_entity(tensor.name))
python
6
0.622034
80
35.90625
32
inline
def cpg_island_prediction(): """ function to perform CpG island prediction (bed format) by newcpgreport in EMBOSS & format it to BED :return: X """ cgi_embl_file_s = os.path.join(species_fasta_dir_s, "%s.newcpgreport" % ref_s) out_bed_file_s = os.path.join(species_fasta_dir_s, "%s.newcpgreport.bed" % ref_s) # (1) Performing CGI prediction by newcpgreport if file_check(cgi_embl_file_s) is False: os.system("%s -sequence %s -outfile %s" % (newcpgreport_command_s, ref_fasta_file_s, cgi_embl_file_s)) # (2) Reformat EMBL file to BED manually with open(cgi_embl_file_s) as cgi_embl_file_f, open(out_bed_file_s, "w") as out_bed_file_f: embl_contents_l = cgi_embl_file_f.read().split("\n//\n") for cpgreport_s in embl_contents_l: cpgreport_l = cpgreport_s.split("\nXX\n") try: assert cpgreport_l[0].startswith("ID") chrom_s = cpgreport_l[0].split(" ")[3] print(chrom_s) except AssertionError: assert len(cpgreport_l) == 1 continue assert cpgreport_l[1].startswith("DE") assert cpgreport_l[2].startswith("CC") assert cpgreport_l[3].startswith("FH") assert len(cpgreport_l) == 4 cpg_infos_l = cpgreport_l[3].split("\nFT CpG island ")[1:] count_i = 0 for cpg_info_s in cpg_infos_l: count_i += 1 cpg_info_line_l = cpg_info_s.split("\nFT /") print(cpg_info_line_l) assert ".." in cpg_info_line_l[0] start_i, end_i = [int(x) for x in cpg_info_line_l[0].split("..")] assert start_i <= end_i assert "size=" in cpg_info_line_l[1] size_i = int(cpg_info_line_l[1].split("=")[-1]) assert size_i == end_i-start_i+1 assert "Sum C+G=" in cpg_info_line_l[2] sum_c_g_i = int(cpg_info_line_l[2].split("=")[-1]) assert "Percent CG=" in cpg_info_line_l[3] percent_gc_fl = float(cpg_info_line_l[3].split("=")[-1]) assert "ObsExp=" in cpg_info_line_l[4] # for last line if "numislands" in cpg_info_line_l[4]: obs_exp_s = cpg_info_line_l[4].split("\nFT numislands ")[0] num_islands_i = int(cpg_info_line_l[4].split("\nFT numislands ")[-1]) assert len(cpg_infos_l) == num_islands_i else: obs_exp_s = cpg_info_line_l[4] obs_exp_fl = float(obs_exp_s.split("=")[-1]) out_bed_file_f.write("\t".join(map(str,[chrom_s, start_i-1, end_i, "CpGIsland_%s_%i|size=%i|Sum C+G=%i|Percent CG=%f|ObsExp=%s" % (chrom_s, count_i, size_i, sum_c_g_i, percent_gc_fl, obs_exp_fl), 0, "+"]))+"\n")
python
20
0.495569
145
55.528302
53
inline
int SurveyDroidMenuComponent::handleObjectMenuSelect(SceneObject* droidObject, CreatureObject* player, byte selectedID) const { if (!droidObject->isTangibleObject()) { return 0; } if (!player->isPlayerCreature()) { return 0; } TangibleObject* tano = cast<TangibleObject*>( droidObject); if (selectedID == 20) { // Use radial menu // check for inventory ManagedReference<SceneObject*> inventory = player->getSlottedObject("inventory"); if (inventory == nullptr) return 0; PlayerObject* playerObject = player->getPlayerObject(); // Check for appropiate skill (survey) if (!playerObject->hasAbility("survey")) { player->sendSystemMessage("@pet/droid_modules:survey_no_survey_skill"); return 0; } if (player->containsActiveSession(SessionFacadeType::INTERPLANETARYSURVEYDROID)) { return 0; } ManagedReference<InterplanetarySurveyDroidSession*> session = new InterplanetarySurveyDroidSession(player); player->addActiveSession(SessionFacadeType::INTERPLANETARYSURVEYDROID,session); session->initalizeDroid(tano); return 0; } else { return TangibleObjectMenuComponent::handleObjectMenuSelect(droidObject, player, selectedID); } }
c++
11
0.757653
127
35.78125
32
inline
@Override protected void configureOutputFormat(Job job, String tableName, String tableClassName) throws ClassNotFoundException, IOException { super.configureOutputFormat(job, tableName, tableClassName); job.getConfiguration().set( MainframeConfiguration.MAINFRAME_FTP_TRANSFER_MODE, options.getMainframeFtpTransferMode()); // use the default outputformat LazyOutputFormat.setOutputFormatClass(job, getOutputFormatClass()); }
java
8
0.779221
73
45.3
10
inline
<?php namespace Devtodev\StatApi\ApiActions; use Devtodev\StatApi\ApiClient; /** * Class TrackingAvailabilityAction * @package Devtodev\StatApi\ApiActions */ class TrackingAvailabilityAction extends BaseApiAction { /** * @var boolean */ protected $isTrackingAllowed = null; /** * @return boolean */ public function getIsTrackingAllowed() { return $this->isTrackingAllowed; } /** * @param string $isTrackingAllowed */ public function setIsTrackingAllowed($isTrackingAllowed) { $this->isTrackingAllowed = $isTrackingAllowed; } /** * @return string */ protected function getActionCode() { return 'ts'; } /** * @return boolean * @throws ApiException */ protected function validateParams() { $isValidate = true; if($this->getIsTrackingAllowed() === null){ ApiClient::appendToErrors("Tracking status is empty"); $isValidate = false; } return $isValidate; } /** * @return void */ protected function buildRequestData() { $mainUserId = $this->getMainUserId(); $actionCode = $this->getActionCode(); $actionData= [ 'isTrackingAllowed' => $this->getIsTrackingAllowed(), 'timestamp' => $this->getTime() ]; $this->requestData = [ $mainUserId => array_merge($this->buildBaseRequestData(), [ $actionCode => [$actionData] ]), ]; } }
php
17
0.572258
71
22.5
66
starcoderdata
const moment = require('../../utils/moment.min.js'); const app = getApp() Page({ data: { navigate_data: { name: "任务" }, is_show_checkin: 'false', is_show_invite: 'false', is_show_read: 'false', is_show_collect: 'false', is_show_dailytask: true, is_show_invitetask: false, checkin_process: 0, reading_process: 0, invite_reading_process: 0, collect_process: 0, info_process: 0, invite_friend_process: 0, checkin_credits: [], artical_items: {}, show_credits_checkin: 0, show_credits_read: 0, show_credits_invite_read: 0, show_credits_collect: 0, show_credits_person_info: 0, show_credits_invite_person: [] }, onLoad: function() { const _that = this; this.getCheckinHistory(); this.getReadingHistory(); this.getInviteReadingHistory(); this.getCollectHistory(); this.getInfoHistory(); this.getInviteFriendHistory(); this.getRecommend(); }, getRecommend: function() { const _that = this; app.xpm.api('/xpmsns/pages/Recommend/getContents')() .get({ perpage: 5, slugs: 'weekly_hotnews' }) .then((data) => { _that.setData({ artical_items: data.data }) }) .catch(function(error) { console.log(error); }); }, getCheckinHistory: function() { const _that = this; app.xpm.api('/xpmsns/user//Task/gettasks')() .get({ slug: 'checkin' }) .then((data) => { _that.setData({ show_credits_checkin: data.data[0].quantity[0], checkin_credits: data.data[0].quantity, checkin_process: data.data[0].usertask !== null ? data.data[0].usertask.process : 0, }) }) .catch(function(error) { console.log(error); }); }, getReadingHistory: function() { const _that = this; app.xpm.api('/xpmsns/user//Task/gettasks')() .get({ slug: 'article-reading' }) .then((data) => { _that.setData({ reading_process: data.data[0].usertask !== null ? data.data[0].usertask.process : 0, show_credits_read: data.data[0].quantity[0] }) }) .catch(function(error) { console.log(error); }); }, getInviteReadingHistory: function() { const _that = this; app.xpm.api('/xpmsns/user//Task/gettasks')() .get({ slug: 'article-invitee-reading' }) .then((data) => { _that.setData({ invite_reading_process: data.data[0].usertask !== null ? data.data[0].usertask.process : 0, show_credits_invite_read: data.data[0].quantity[0] }) }) .catch(function(error) { console.log(error); }); }, getCollectHistory: function() { const _that = this; app.xpm.api('/xpmsns/user//Task/gettasks')() .get({ slug: 'favorite' }) .then((data) => { _that.setData({ collect_process: data.data[0].usertask !== null ? data.data[0].usertask.process : 0, show_credits_collect: data.data[0].quantity[0] }) }) .catch(function(error) { console.log(error); }); }, getInfoHistory: function() { const _that = this; app.xpm.api('/xpmsns/user//Task/gettasks')() .get({ slug: 'profile' }) .then((data) => { _that.setData({ info_process: data.data[0].usertask !== null ? data.data[0].usertask.process : 0, show_credits_person_info: data.data[0].quantity[0] }) }) .catch(function(error) { console.log(error); }); }, getInviteFriendHistory: function() { const _that = this; app.xpm.api('/xpmsns/user//Task/gettasks')() .get({ slug: 'invite' }) .then((data) => { _that.setData({ invite_friend_process: data.data[0].usertask !== null ? data.data[0].usertask.process : 0, show_credits_invite_person: data.data[0].quantity }) }) .catch(function(error) { console.log(error); }); }, handleTapComplete: function(e) { const _that = this; switch (e.target.dataset.type) { case 'checkin': _that.setData({ is_show_checkin: 'true' }); this.setTaskAccept('checkin'); break; case 'read': _that.setData({ is_show_read: 'true' }); this.setTaskAccept('article-reading'); break; case 'invite': _that.setData({ is_show_invite: 'true' }); this.setTaskAccept('article-invitee-reading'); break; case 'collect': _that.setData({ is_show_collect: 'true' }); this.setTaskAccept('favorite'); break; } }, onShareAppMessage: function(e) { const _that = this; let invite_type = ''; wx.showShareMenu({ withShareTicket: true }) if (e.target.dataset.type === 'invite_article') { invite_type = 'invite_article'; app.xpm.api('/xpmsns/user/Invite/create')() .post({ slug: 'invite_article' }) .then((data) => { console.log(data); }) .catch(function(error) { console.log(error); }); } else { this.setTaskAccept('invite'); invite_type = 'invite_signup'; app.xpm.api('/xpmsns/user/Invite/create')() .post({ slug: 'invite_signup' }) .then((data) => { console.log(data); }) .catch(function(error) { console.log(error); }); } return { title: e.target.dataset.title ? e.target.dataset.title : '看好文,获积分,换豪礼', path: `/pages/invitereading/invitereading?article_id=${e.target.dataset.id}&user_id=${app.global_data.user_info.user_id}&invite_type=${invite_type}`, imageUrl: e.target.dataset.coverurl ? e.target.dataset.coverurl : '../../images/pictrue_goods_eg.jpg' } }, setTaskAccept: function(slug) { app.xpm.api('/xpmsns/user/Task/accept')() .post({ slug: slug }) .then((data) => { console.log(data); }) .catch(function(error) { console.log(error); }); }, handleTapArticle: function(e) { wx.navigateTo({ url: `/pages/artical/artical?article_id=${e.target.dataset.articleid}` }) }, toggleTab: function(e) { if (e.target.dataset.type === 'dailytask') { this.setData({ is_show_dailytask: true, is_show_invitetask: false }) } else { this.setData({ is_show_dailytask: false, is_show_invitetask: true }) } } })
javascript
25
0.426441
161
29.770677
266
starcoderdata
package com.rei.stats.gsampler.graphite; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class EchoServer { public static void main(String[] args) throws IOException { new EchoServer().start(Integer.parseInt(args[0])); } private Appendable out = System.out; private boolean shutdown; EchoServer setOutput(Appendable out) { this.out = out; return this; } void start(int port) throws IOException { try(ServerSocket serverSocket = new ServerSocket(port)) { serverSocket.setReuseAddress(true); Socket socket = serverSocket.accept(); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); String line = null; while (!shutdown && (line = reader.readLine()) != null) { out.append(line + '\n'); } } } void destroy() { shutdown = true; } }
java
13
0.636364
103
29.105263
38
starcoderdata
# -*- coding: utf-8 -*- ########################################################################## # 2010-2017 Webkul. # # NOTICE OF LICENSE # # All right is reserved, # Please go through this link for complete license : https://store.webkul.com/license.html # # DISCLAIMER # # Do not edit or add to this file if you wish to upgrade this module to newer # versions in the future. If you wish to customize this module for your # needs please refer to https://store.webkul.com/customisation-guidelines/ for more information. # # @Author : Webkul Software Pvt. Ltd. ( # @Copyright (c) : 2010-2017 Present Webkul Software Pvt. Ltd. ( # @License : https://store.webkul.com/license.html # ########################################################################## from odoo import api, fields, models import odoo.addons.decimal_precision as dp class MarketplaceMembershipInvoice(models.TransientModel): _name = "mp.membership.invoice" _description = "Marketplace Membership Invoice" product_id = fields.Many2one('product.product', string='Membership', required=True, domain="[('wk_mp_membership', '=', True)]") membership_fee = fields.Float(string='Membership Price', digits= dp.get_precision('Product Price'), required=True) @api.onchange('product_id') def onchange_product(self): """Return value of product's membership fee based on product id.""" price_dict = self.product_id.price_compute('list_price') self.membership_fee = price_dict.get(self.product_id.id) or False @api.multi def create_seller_membership_invoice(self): if self: datas = { 'membership_product_id': self.product_id.id, 'amount': self.membership_fee } invoice_list = self.env['res.partner'].browse(self._context.get('active_ids')).create_mp_membership_invoice(datas=datas) search_view_ref = self.env.ref('account.view_account_invoice_filter', False) form_view_ref = self.env.ref('account.invoice_form', False) return { 'domain': [('id', 'in', invoice_list)], 'name': 'Membership Invoices', 'res_model': 'account.invoice', 'type': 'ir.actions.act_window', 'views': [(False, 'tree'), (form_view_ref and form_view_ref.id, 'form')], 'search_view_id': search_view_ref and search_view_ref.id, }
python
15
0.613021
131
40.915254
59
starcoderdata
func (c cryptVolume) WriteAt(buf []byte, off int64) (int, error) { length := uint64(len(buf)) offset := uint64(off) if length%c.sectorSize != 0 { return 0, fmt.Errorf("size of the buffer must be multiple of CryptTable.SectorSize") } if offset%c.sectorSize != 0 { return 0, fmt.Errorf("offset must be multiple of CryptTable.SectorSize") } sectorSize := int(c.sectorSize) counter := uint64(off) / uint64(SectorSize) cryptBuf := make([]byte, length) for i := 0; i < int(length); i += sectorSize { ciphertext := cryptBuf[i : i+sectorSize] plaintext := buf[i : i+sectorSize] c.cipher.Encrypt(ciphertext, plaintext, counter) counter += c.sectorSize / SectorSize // if iv_large_sectors flag set then it should be counter+=1 } return c.f.WriteAt(cryptBuf, off+int64(c.offset)) }
go
11
0.693852
99
33.695652
23
inline
<?php namespace App\Http\Controllers; use App\Services\DomainsService; use App\Services\ImportKayakoService; use App\Services\KayakoService; use App\Services\ParsService; use Carbon\Carbon; use Illuminate\Http\Request; class TestController extends AuthBaseController { public function index() { return view('test'); } public function test(Request $request) { $test_text = $request->test_text?? ''; $result = [ ['name' => 'domain', 'pars' => ParsService::domain($test_text)], ['name' => 'ip', 'pars' => ParsService::ip($test_text)], ['name' => 'prohibited schemes', 'pars' => [ParsService::prohibitedSchemes($test_text)? 'true': 'false']], ]; return view('test', compact('result', 'test_text')); } public function zendesk($api_id) { $api = \App\Services\ImportZendeskService::getApi((int)$api_id); ddd($api); $api->allTickets(1, 100); } public function zendesk_tickets(Request $request, $api_id) { $api = \App\Services\ImportZendeskService::getApi((int)$api_id); /* if ($api->allTickets($request->get('page', 1), $request->get('per_page', 100))) { ddd($api->tickets()); } */ // ddd($api->errors_api); ddd($api->getLastActivity('-16 day')); } public function zendesk_tickets_comments(Request $request, $api_id, $tickets_id) { $api = \App\Services\ImportZendeskService::getApi((int)$api_id); if ($api->allTicketComments($tickets_id, $request->get('page', 1), $request->get('per_page', 100))) { ddd([ 'comments' => (array)$api->comments(), 'users' => (array)$api->users(), 'nextPage' => $api->nextPage(), 'raw' => $api->api_result ]); } ddd($api->errors_api); } public function zendesk_update_tickets(Request $request) { $api = \App\Services\UpdateZendeskService::getApiUpdateToDay($request->get('day', '-1')); if (empty($api)) { ddd('empty api'); } if ($api->allTickets($request->get('page', 1), $request->get('per_page', 100))) { ddd([ 'tickets' => $api->tickets(), 'nextPage' => $api->nextPage(), 'raw' => $api->api_result ]); } ddd($api->errors_api); } public function domains_update_ranks(Request $request) { ddd( DomainsService::update_day($request->get('days', -1), $request->get('limit', 5)) ); } public function kayako(Request $request) { /* $this->service_id = 2; $ImportKayakoService = ImportKayakoService::getApi($this->service_id); if (empty($ImportKayakoService)) { dd('empty($ImportKayakoService)'); return; } $ImportKayakoService->getDepartment(); */ /* $there_is_tickets = $ImportKayakoService->allTickets(1, 20); if (!$there_is_tickets) { dd(['!$there_is_tickets' => 'false', ]); return; } */ /* if (!empty($page_params = $ImportKayakoService->nextPage())) { // dispatch(new ImportZendeskTicketsJob($this->service_id, $page_params['page'], $this->per_page)); } */ //dd($ImportKayakoService->tickets()); /** * @var \App\Services\ImportKayakoService */ $kayako = ImportKayakoService::getApi(2); $kayako->getDepartment(); /* $default_status_id = kyTicketStatus::getAll()->filterByTitle("Open")->first()->getId(); $default_priority_id = kyTicketPriority::getAll()->filterByTitle("Normal")->first()->getId(); $default_type_id = kyTicketType::getAll()->filterByTitle("Issue")->first()->getId(); */ // kyTicket::setDefaults($default_status_id, $default_priority_id, $default_type_id); // $import_at = (Carbon::today()->modify('-1 day'))->getTimestamp(); $kayako->getLastActivity('-1 day'); //$general_department = \App\KayakoApi\kyDepartment::getAll(); // ->filterByTitle("General") // $general_department = $general_department->filterByModule(\App\KayakoApi\kyDepartment::MODULE_TICKETS)->collectId(); /* ->first() ;*/ // $kayako->getDepartment(); // $ticket = $kayako->getPage(5, 10); //$tickets = \App\KayakoApi\kyTicket::getListAll($general_department, [], [], [], 1000, 1, 'lastactivity', 'desc'); // ->filterByLastActivity(['>', $import_at]); ddd([ // $import_at, $kayako->tickets(), // \App\KayakoApi\kyTicket::getStatistics(), //$kayako->errors_api // //\App\KayakoApi\kyTicket::getAll($general_department, [], [], [], 20, 300), //$general_department // $ticket->getPage(3, 20), //$ticket->offsetGet(100), /* $ticket->getPageCount(100) */ //$ticket->_data, // $general_department, // $kayako->getTicketComments(337368), /* $kayako->getTicket(318155), $kayako->getTicketPost(318155, 1640562), $kayako->getUser(75732) */ // $kayako->getTicketPost(318155, 1640562)->getUser(true), // $kayako->allAttachments(318155) // $kayako->getAttachment(318155, 943341) // \App\KayakoApi\kyTicketPost::getAll(344711)->getPage(2, 20) //kyTicketStatus::getAll() //$ticket, // /* $ticket->getCustomField('notes'), $ticket->getDepartment(true), $ticket->getStatus(true), $ticket->getSubject(), $ticket->getTags(), $ticket->getTimeTracks(true), $ticket->getType(true), $ticket->getUser()->buildData(false), $ticket->getNotes(true) */ // kyDepartment::getAll() // $general_department ]); } }
php
18
0.536982
126
34.578947
171
starcoderdata
#include #include char* echomsg(char* msg) { printf("Hello %s\n", msg); char* some = "HiHiHi"; return some; }
c
7
0.643939
27
15.625
8
starcoderdata
/* * This file is part of ELKI: * Environment for Developing KDD-Applications Supported by Index-Structures * * Copyright (C) 2019 * ELKI Development Team * * 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 this program. If not, see */ package de.lmu.ifi.dbs.elki.utilities.datastructures.heap; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; import java.util.Random; import org.junit.Ignore; import org.junit.Test; /** * Unit test to ensure that our heap is not significantly worse than SUN javas * regular PriorityQueue. * * @author * @since 0.7.0 */ public class HeapPerformanceTest { final private int queueSize = 200000; final private int preiterations = 20; final private int iterations = 200; final private long seed = 123456L; @Ignore @Test public void testRuntime() throws Exception { // prepare the data set final List elements = new ArrayList<>(queueSize); { final Random random = new Random(seed); for(int i = 0; i < queueSize; i++) { elements.add(i); } Collections.shuffle(elements, random); } // Pretest, to trigger hotspot compiler, hopefully. { for(int j = 0; j < preiterations; j++) { ComparableMinHeap pq = new ComparableMinHeap<>(); testHeap(elements, pq); } for(int j = 0; j < preiterations; j++) { PriorityQueue pq = new PriorityQueue<>(); testQueue(elements, pq); } } long pqstart = System.nanoTime(); { for(int j = 0; j < iterations; j++) { PriorityQueue pq = new PriorityQueue<>(); testQueue(elements, pq); } } long pqtime = System.nanoTime() - pqstart; long hstart = System.nanoTime(); { for(int j = 0; j < iterations; j++) { ComparableMinHeap pq = new ComparableMinHeap<>(); testHeap(elements, pq); } } long htime = System.nanoTime() - hstart; // System.err.println("Heap performance test: us: " + htime*1E-9 + " java: " + pqtime*1E-9); assertTrue("Heap performance regression - run test individually, since the hotspot optimizations may make the difference! " + htime + " >>= " + pqtime, htime < 1.1 * pqtime); // 1.1 allows some difference in measuring, which can occur e.g. due to Jacoco instrumentation } private void testHeap(final List elements, ComparableMinHeap pq) { // Insert all for(int i = 0; i < elements.size(); i++) { pq.add(elements.get(i)); } // Poll first half. final int half = elements.size() >> 1; for(int i = 0; i < half; i++) { assertEquals((int) pq.poll(), i); // assertEquals((int) pq.poll(), queueSize - 1 - i); } assertEquals("Heap not half-empty?", elements.size() - half, pq.size()); pq.clear(); } private void testQueue(final List elements, Queue pq) { // Insert all for(int i = 0; i < elements.size(); i++) { pq.add(elements.get(i)); } // Poll first half. final int half = elements.size() >> 1; for(int i = 0; i < half; i++) { assertEquals((int) pq.poll(), i); // assertEquals((int) pq.poll(), queueSize - 1 - i); } assertEquals("Heap not half-empty?", elements.size() - half, pq.size()); pq.clear(); } }
java
13
0.646699
178
30.713178
129
starcoderdata
namespace Fonet.Layout { using Fonet.Fo.Properties; using Fonet.Render.Pdf; internal class SpanArea : AreaContainer { private int columnCount; private int currentColumn = 1; private int columnGap = 0; private bool _isBalanced = false; public SpanArea(FontState fontState, int xPosition, int yPosition, int allocationWidth, int maxHeight, int columnCount, int columnGap) : base(fontState, xPosition, yPosition, allocationWidth, maxHeight, Position.ABSOLUTE) { this.contentRectangleWidth = allocationWidth; this.columnCount = columnCount; this.columnGap = columnGap; int columnWidth = (allocationWidth - columnGap * (columnCount - 1)) / columnCount; for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) { int colXPosition = (xPosition + columnIndex * (columnWidth + columnGap)); int colYPosition = yPosition; ColumnArea colArea = new ColumnArea(fontState, colXPosition, colYPosition, columnWidth, maxHeight, columnCount); addChild(colArea); colArea.setColumnIndex(columnIndex + 1); } } public override void render(PdfRenderer renderer) { renderer.RenderSpanArea(this); } public override void end() { } public override void start() { } public override int spaceLeft() { return maxHeight - currentHeight; } public int getColumnCount() { return columnCount; } public int getCurrentColumn() { return currentColumn; } public void setCurrentColumn(int currentColumn) { if (currentColumn <= columnCount) { this.currentColumn = currentColumn; } else { this.currentColumn = columnCount; } } public AreaContainer getCurrentColumnArea() { return (AreaContainer)getChildren()[currentColumn - 1]; } public bool isBalanced() { return _isBalanced; } public void setIsBalanced() { _isBalanced = true; } public int getTotalContentHeight() { int totalContentHeight = 0; foreach (AreaContainer ac in getChildren()) { totalContentHeight += ac.getContentHeight(); } return totalContentHeight; } public int getMaxContentHeight() { int maxContentHeight = 0; foreach (AreaContainer nextElm in getChildren()) { if (nextElm.getContentHeight() > maxContentHeight) { maxContentHeight = nextElm.getContentHeight(); } } return maxContentHeight; } public override void setPage(Page page) { this.page = page; foreach (AreaContainer ac in getChildren()) { ac.setPage(page); } } public bool isLastColumn() { return (currentColumn == columnCount); } } }
c#
16
0.501914
79
26.931298
131
starcoderdata
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.CloudWatchLogs; using Amazon.CloudWatchLogs.Model; namespace TestServerlessApp.IntegrationTests.Helpers { public class CloudWatchHelper { private readonly IAmazonCloudWatchLogs _cloudWatchlogsClient; public CloudWatchHelper(IAmazonCloudWatchLogs cloudWatchlogsClient) { _cloudWatchlogsClient = cloudWatchlogsClient; } public string GetLogGroupName(string lambdaFunctionName) => $"/aws/lambda/{lambdaFunctionName}"; public async Task MessageExistsInRecentLogEventsAsync(string message, string logGroupName, string logGroupNamePrefix) { var attemptCount = 0; const int maxAttempts = 5; while (attemptCount < maxAttempts) { attemptCount += 1; var recentLogEvents = await GetRecentLogEventsAsync(logGroupName, logGroupNamePrefix); if (recentLogEvents.Any(x => x.Message.Contains(message))) return true; await Task.Delay(StaticHelpers.GetWaitTime(attemptCount)); } return false; } private async Task GetRecentLogEventsAsync(string logGroupName, string logGroupNamePrefix) { var latestLogStreamName = await GetLatestLogStreamNameAsync(logGroupName, logGroupNamePrefix); var logEvents = await GetLogEventsAsync(logGroupName, latestLogStreamName); return logEvents; } private async Task GetLatestLogStreamNameAsync(string logGroupName, string logGroupNamePrefix) { var attemptCount = 0; const int maxAttempts = 5; while (attemptCount < maxAttempts) { attemptCount += 1; if (await LogGroupExistsAsync(logGroupName, logGroupNamePrefix)) break; await Task.Delay(StaticHelpers.GetWaitTime(attemptCount)); } var response = await _cloudWatchlogsClient.DescribeLogStreamsAsync( new DescribeLogStreamsRequest { LogGroupName = logGroupName, Descending = true, Limit = 1 }); return response.LogStreams.FirstOrDefault()?.LogStreamName; } private async Task GetLogEventsAsync(string logGroupName, string logStreamName) { var response = await _cloudWatchlogsClient.GetLogEventsAsync( new GetLogEventsRequest { LogGroupName = logGroupName, LogStreamName = logStreamName, Limit = 10 }); return response.Events; } private async Task LogGroupExistsAsync(string logGroupName, string logGroupNamePrefix) { var response = await _cloudWatchlogsClient.DescribeLogGroupsAsync(new DescribeLogGroupsRequest{LogGroupNamePrefix = logGroupNamePrefix}); return response.LogGroups.Any(x => string.Equals(x.LogGroupName, logGroupName)); } } }
c#
19
0.624885
149
36.609195
87
starcoderdata
func (h *Handler) createStorageClusterIfAbsent(ds *appsv1.DaemonSet) (*corev1.StorageCluster, error) { clusterName := getPortworxClusterName(ds) stc := &corev1.StorageCluster{} err := h.client.Get( context.TODO(), types.NamespacedName{ Name: clusterName, Namespace: ds.Namespace, }, stc, ) if err == nil { return stc, nil } else if err != nil && !errors.IsNotFound(err) { return nil, err } stc, err = h.createStorageCluster(ds) // TODO: Create dry run specs return stc, err }
go
12
0.679764
102
23.285714
21
inline
from collections import OrderedDict import torch from torch import nn from clinicadl.utils.network.network import Network from clinicadl.utils.network.network_utils import ( CropMaxUnpool2d, CropMaxUnpool3d, PadMaxPool2d, PadMaxPool3d, ) class AutoEncoder(Network): def __init__(self, encoder, decoder, use_cpu=False): super().__init__(use_cpu=use_cpu) self.encoder = encoder.to(self.device) self.decoder = decoder.to(self.device) @property def layers(self): return nn.Sequential(self.encoder, self.decoder) def transfer_weights(self, state_dict, transfer_class): if issubclass(transfer_class, AutoEncoder): self.load_state_dict(state_dict) elif issubclass(transfer_class, CNN): encoder_dict = OrderedDict( [ (k.replace("convolutions.", ""), v) for k, v in state_dict.items() if "convolutions" in k ] ) self.encoder.load_state_dict(encoder_dict) else: raise ValueError( f"Cannot transfer weights from {transfer_class} " f"to Autoencoder." ) def predict(self, x): _, output = self.forward(x) return output def forward(self, x): indices_list = [] pad_list = [] for layer in self.encoder: if ( (isinstance(layer, PadMaxPool3d) or isinstance(layer, PadMaxPool2d)) and layer.return_indices and layer.return_pad ): x, indices, pad = layer(x) indices_list.append(indices) pad_list.append(pad) elif ( isinstance(layer, nn.MaxPool3d) or isinstance(layer, nn.MaxPool2d) ) and layer.return_indices: x, indices = layer(x) indices_list.append(indices) else: x = layer(x) code = x.clone() for layer in self.decoder: if isinstance(layer, CropMaxUnpool3d) or isinstance(layer, CropMaxUnpool2d): x = layer(x, indices_list.pop(), pad_list.pop()) elif isinstance(layer, nn.MaxUnpool3d) or isinstance(layer, nn.MaxUnpool2d): x = layer(x, indices_list.pop()) else: x = layer(x) return code, x def compute_outputs_and_loss(self, input_dict, criterion, use_labels=True): images = input_dict["image"].to(self.device) train_output = self.predict(images) loss = criterion(train_output, images) return train_output, loss class CNN(Network): def __init__(self, convolutions, fc, n_classes, use_cpu=False): super().__init__(use_cpu=use_cpu) self.convolutions = convolutions.to(self.device) self.fc = fc.to(self.device) self.n_classes = n_classes @property def layers(self): return nn.Sequential(self.convolutions, self.fc) def transfer_weights(self, state_dict, transfer_class): if issubclass(transfer_class, CNN): self.load_state_dict(state_dict) elif issubclass(transfer_class, AutoEncoder): convolutions_dict = OrderedDict( [ (k.replace("encoder.", ""), v) for k, v in state_dict.items() if "encoder" in k ] ) self.convolutions.load_state_dict(convolutions_dict) else: raise ValueError( f"Cannot transfer weights from {transfer_class} " f"to CNN." ) def forward(self, x): x = self.convolutions(x) return self.fc(x) def predict(self, x): return self.forward(x) def compute_outputs_and_loss(self, input_dict, criterion, use_labels=True): images, labels = input_dict["image"].to(self.device), input_dict["label"].to( self.device ) train_output = self.forward(images) if use_labels: loss = criterion(train_output, labels) else: loss = torch.Tensor([0]) return train_output, loss
python
17
0.558435
88
30.671642
134
starcoderdata
def test_recv_one_retry(self): sock = "carState" sock_timeout = 0.1 pub_sock = messaging.pub_sock(sock) sub_sock = messaging.sub_sock(sock, timeout=sock_timeout*1000) zmq_sleep() # this test doesn't work with ZMQ since multiprocessing interrupts it if "ZMQ" not in os.environ: # wait 15 socket timeouts and make sure it's still retrying p = multiprocessing.Process(target=messaging.recv_one_retry, args=(sub_sock,)) p.start() time.sleep(sock_timeout*15) self.assertTrue(p.is_alive()) p.terminate() # wait 15 socket timeouts before sending msg = random_carstate() delayed_send(sock_timeout*15, pub_sock, msg.to_bytes()) start_time = time.monotonic() recvd = messaging.recv_one_retry(sub_sock) self.assertGreaterEqual(time.monotonic() - start_time, sock_timeout*15) self.assertIsInstance(recvd, capnp._DynamicStructReader) assert_carstate(msg.carState, recvd.carState)
python
11
0.690871
84
39.208333
24
inline
module.exports = [ { "name": " "type": "thi-tran", "slug": "nui-doi", "name_with_type": " "path": "Núi Đối, Kiến Thuỵ, Hải Phòng", "path_with_type": "Thị trấn Núi Đối, Huyện Kiến Thuỵ, Thành phố Hải Phòng", "code": "11680", "parent_code": "314" }, { "name": " "type": "xa", "slug": "dong-phuong", "name_with_type": " "path": "Đông Phương, Kiến Thuỵ, Hải Phòng", "path_with_type": "Xã Đông Phương, Huyện Kiến Thuỵ, Thành phố Hải Phòng", "code": "11695", "parent_code": "314" }, { "name": " "type": "xa", "slug": "thuan-thien", "name_with_type": " "path": "Thuận Thiên, Kiến Thuỵ, Hải Phòng", "path_with_type": "Xã Thuận Thiên, Huyện Kiến Thuỵ, Thành phố Hải Phòng", "code": "11698", "parent_code": "314" }, { "name": " "type": "xa", "slug": "huu-bang", "name_with_type": " "path": "Hữu Bằng, Kiến Thuỵ, Hải Phòng", "path_with_type": "Xã Hữu Bằng, Huyện Kiến Thuỵ, Thành phố Hải Phòng", "code": "11701", "parent_code": "314" }, { "name": " "type": "xa", "slug": "dai-dong", "name_with_type": " "path": "Đại Đồng, Kiến Thuỵ, Hải Phòng", "path_with_type": "Xã Đại Đồng, Huyện Kiến Thuỵ, Thành phố Hải Phòng", "code": "11704", "parent_code": "314" }, { "name": " "type": "xa", "slug": "ngu-phuc", "name_with_type": " "path": "Ngũ Phúc, Kiến Thuỵ, Hải Phòng", "path_with_type": "Xã Ngũ Phúc, Huyện Kiến Thuỵ, Thành phố Hải Phòng", "code": "11710", "parent_code": "314" }, { "name": " "type": "xa", "slug": "kien-quoc", "name_with_type": " "path": "Kiến Quốc, Kiến Thuỵ, Hải Phòng", "path_with_type": "Xã Kiến Quốc, Huyện Kiến Thuỵ, Thành phố Hải Phòng", "code": "11713", "parent_code": "314" }, { "name": " "type": "xa", "slug": "du-le", "name_with_type": " "path": "Du Lễ, Kiến Thuỵ, Hải Phòng", "path_with_type": "Xã Du Lễ, Huyện Kiến Thuỵ, Thành phố Hải Phòng", "code": "11716", "parent_code": "314" }, { "name": " "type": "xa", "slug": "thuy-huong", "name_with_type": " "path": "Thuỵ Hương, Kiến Thuỵ, Hải Phòng", "path_with_type": "Xã Thuỵ Hương, Huyện Kiến Thuỵ, Thành phố Hải Phòng", "code": "11719", "parent_code": "314" }, { "name": " "type": "xa", "slug": "thanh-son", "name_with_type": " "path": "Thanh Sơn, Kiến Thuỵ, Hải Phòng", "path_with_type": "Xã Thanh Sơn, Huyện Kiến Thuỵ, Thành phố Hải Phòng", "code": "11722", "parent_code": "314" }, { "name": " "type": "xa", "slug": "minh-tan", "name_with_type": " "path": "Minh Tân, Kiến Thuỵ, Hải Phòng", "path_with_type": "Xã Minh Tân, Huyện Kiến Thuỵ, Thành phố Hải Phòng", "code": "11725", "parent_code": "314" }, { "name": " "type": "xa", "slug": "dai-ha", "name_with_type": " "path": "Đại Hà, Kiến Thuỵ, Hải Phòng", "path_with_type": "Xã Đại Hà, Huyện Kiến Thuỵ, Thành phố Hải Phòng", "code": "11728", "parent_code": "314" }, { "name": " "type": "xa", "slug": "ngu-doan", "name_with_type": " "path": "Ngũ Đoan, Kiến Thuỵ, Hải Phòng", "path_with_type": "Xã Ngũ Đoan, Huyện Kiến Thuỵ, Thành phố Hải Phòng", "code": "11731", "parent_code": "314" }, { "name": " "type": "xa", "slug": "tan-phong", "name_with_type": " "path": "Tân Phong, Kiến Thuỵ, Hải Phòng", "path_with_type": "Xã Tân Phong, Huyện Kiến Thuỵ, Thành phố Hải Phòng", "code": "11734", "parent_code": "314" }, { "name": " "type": "xa", "slug": "tan-trao", "name_with_type": " "path": "Tân Trào, Kiến Thuỵ, Hải Phòng", "path_with_type": "Xã Tân Trào, Huyện Kiến Thuỵ, Thành phố Hải Phòng", "code": "11743", "parent_code": "314" }, { "name": " "type": "xa", "slug": "doan-xa", "name_with_type": " "path": "Đoàn Xá, Kiến Thuỵ, Hải Phòng", "path_with_type": "Xã Huyện Kiến Thuỵ, Thành phố Hải Phòng", "code": "11746", "parent_code": "314" }, { "name": " "type": "xa", "slug": "tu-son", "name_with_type": " "path": "Tú Sơn, Kiến Thuỵ, Hải Phòng", "path_with_type": "Xã Tú Sơn, Huyện Kiến Thuỵ, Thành phố Hải Phòng", "code": "11749", "parent_code": "314" }, { "name": " "type": "xa", "slug": "dai-hop", "name_with_type": " "path": "Đại Hợp, Kiến Thuỵ, Hải Phòng", "path_with_type": "Xã Đại Hợp, Huyện Kiến Thuỵ, Thành phố Hải Phòng", "code": "11752", "parent_code": "314" } ]
javascript
7
0.515998
79
25.983607
183
starcoderdata
'use strict'; var BaseService = require('./BaseService.js'); var Model = appGlobals.dbModels; var modelName = "orders"; const _ = require('lodash'); const PromiseB = require('bluebird'); const ProductServiceInst = require('./ProductDetailsService').getInst(); function OrderDetailsService() { BaseService.call(this); } var model = Model.getModel(modelName); OrderDetailsService.prototype.getOrderDetailsByUserName = async function(userName) { try{ let orderDetails = await model.find({"username": userName}, {hash: 0}); if(orderDetails){ return orderDetails }else{ throw {message:"User data not found."} } }catch(error){ return Promise.reject(error) } }; OrderDetailsService.prototype.getAllOrderDetails = async function() { let orderDetails = await model.find({}, {hash: 0}); if(orderDetails){ return orderDetails }else{ throw {message:"User data not found."} } }; OrderDetailsService.prototype.insertOrderDetails = async function(userName, order) { console.log("userName", userName) try{ var model = Model.getModel(modelName); let orderDetails = await model.create({"username":userName, ...order}); console.log("orderDetails", orderDetails) if(!_.isEmpty(orderDetails)){ return orderDetails; }else{ throw {"message":`orderDetails not added`}; } }catch(error){ return Promise.reject(error); } }; OrderDetailsService.prototype.updateOrder = async function(orderId,data){ try{ let {order, productDetails, availableQuantities} = data; console.log("productDetails", productDetails) productDetails.map(eachProduct =>{ if(eachProduct.quantity > availableQuantities[eachProduct._id]){ throw {message: `Quantity mismatch for ${eachProduct.productName}`} } }) var model = Model.getModel(modelName); let productsUpdateP = ProductServiceInst.updateProductsQuantity(productDetails) let orderDetailsP = model.update({"orderId":orderId},{$set:{...order}}); let [orderDetails] = await PromiseB.all([orderDetailsP,productsUpdateP]); if(!_.isEmpty(orderDetails)){ return orderDetails; }else{ throw {"message":`orderDetails not added`}; } }catch(error){ console.log("error", error) return Promise.reject(error); } } module.exports = { getInst : function() { return new OrderDetailsService(); } };
javascript
20
0.636994
87
31.037037
81
starcoderdata
// Copyright 2020 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package de.rngcntr.gremlin.optimize.query; import de.rngcntr.gremlin.optimize.retrieval.dependent.DependentRetrieval; import de.rngcntr.gremlin.optimize.structure.PatternElement; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; import java.util.HashSet; import java.util.Map; import java.util.Set; public class JoinAttribute { private PatternElement leftElement, rightElement; private MatchOn leftMatch, rightMatch; public enum MatchOn { ELEMENT, IN, OUT; } public enum JoinPosition { LEFT, RIGHT; } public JoinAttribute(PatternElement leftElement, MatchOn leftMatch, PatternElement rightElement, MatchOn rightMatch) { this.leftElement = leftElement; this.rightElement = rightElement; this.leftMatch = leftMatch; this.rightMatch = rightMatch; } public JoinAttribute(PatternElement bothElements) { this(bothElements, MatchOn.ELEMENT, bothElements, MatchOn.ELEMENT); } public Set getElements() { Set s = new HashSet(); s.add(leftElement); s.add(rightElement); return s; } public String toString() { return String.format("%s.%s=%s.%s", leftElement.getId(), leftMatch, rightElement.getId(), rightMatch); } public boolean doMatch(Map<String, Object> left, Map<String, Object> right) { Object leftCandidate = left.get(String.valueOf(leftElement.getId())); Object rightCandidate = right.get(String.valueOf(rightElement.getId())); if (leftCandidate == null || rightCandidate == null) { return true; } return resolve(leftCandidate, leftMatch) == resolve(rightCandidate, rightMatch); } public void reformat(DependentRetrieval reorderedRetrieval, JoinPosition pos) { final PatternElement oldElement = reorderedRetrieval.getElement(); final PatternElement newElement = reorderedRetrieval.getSource(); MatchOn newMatch = reorderedRetrieval.getDirection() == Direction.IN ? MatchOn.IN : MatchOn.OUT; switch(pos) { case LEFT: if (leftElement == oldElement) { leftElement = newElement; leftMatch = newMatch; } break; case RIGHT: if (rightElement == oldElement) { rightElement = newElement; rightMatch = newMatch; } break; } } private Object resolve(Object candidate, MatchOn matchOn) { if (matchOn == MatchOn.ELEMENT) { return candidate; } if (!(candidate instanceof Edge)) { throw new IllegalArgumentException( String.format("%s can only be used on Edges but was used on %s", matchOn, candidate)); } Edge e = (Edge) candidate; switch (matchOn) { case IN: return e.inVertex(); case OUT: return e.outVertex(); default: throw new IllegalArgumentException(String.format("Unhandled match type: %s", matchOn)); } } @Override public boolean equals(Object other) { if (!(other instanceof JoinAttribute)) return false; JoinAttribute otherAttribute = (JoinAttribute) other; return leftElement == otherAttribute.leftElement && rightElement == otherAttribute.rightElement && leftMatch == otherAttribute.leftMatch && rightMatch == otherAttribute.rightMatch; } }
java
14
0.639906
128
34.5
120
starcoderdata
import { vec3 } from 'gl-matrix'; import { FORCE } from '../constants'; class Force { constructor(x = 0, y = 0, z = 0) { this.type = FORCE; this.data = vec3.fromValues(x, y, z); } } export default Force;
javascript
7
0.596154
45
20.666667
12
starcoderdata
import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines W,H,x,y = map(int,read().split()) W,H,x,y bl = (W == 2*x and H == 2*y) area = W*H/2 print(area,1 if bl else 0)
python
9
0.668122
38
18.166667
12
codenet
void loop() { // Split time parts of last time into low/high DWORDS uint32_t time_l = _time.uptime >> 32; uint32_t time_h = _time.uptime; // Get current time uint32_t ctime = millis(); // Handle rollover/overflow if (ctime < time_h) time_l++; // Increase low DWORD // Reassemble time _time.uptime = ((uint64_t)time_l << 32) | ctime; // Store current time in seconds since epoch _time.time = NTPClock::Now(); // Main loop OTA::Handle(); // Effects: // Animation::Handle(_time); // SolidColor::Handle(_time); // Rainbow::Handle(_time); // Gradient::Handle(_time); // Actual time Clock::Handle(_time); // Temperature::Handle(_time); Display::Refresh(_time); // Determine at what time the next frame should be ready and how long we should // wait and then delay for that time. Note that we're working in the 32bit domain // here. We're calling millis() here again because we want to take into account // the actual duration of the time the last frame took since last time we called // millis() at the top of this function. uint32_t t_wait = (ctime + _frameduration) - millis(); delay(t_wait <= _frameduration ? t_wait : 0); }
c++
10
0.618859
85
30.575
40
inline
using UnityEngine; public class TestSpawner : MonoBehaviour { public GameObject player; private Vector3 spawnPos = new Vector3(0, 1, 0); private bool isSpawned = false; void Update() { if (!isSpawned && !GetComponent { Instantiate(player, spawnPos, Quaternion.identity); isSpawned = true; } } }
c#
13
0.649652
73
24.352941
17
starcoderdata
(function(tocify) { // ECMAScript 5 Strict Mode "use strict"; // Calls the second IIFE and locally passes in the global jQuery, window, and document objects tocify(window.jQuery, window, document); } (function($, window, document, undefined) { // ECMAScript 5 Strict Mode "use strict"; var tocClassName = "tocify", tocClass = "." + tocClassName, tocFocusClassName = "tocify-focus", tocHoverClassName = "tocify-hover", hideTocClassName = "tocify-hide", hideTocClass = "." + hideTocClassName, headerClassName = "tocify-header", headerClass = "." + headerClassName, subheaderClassName = "tocify-subheader", subheaderClass = "." + subheaderClassName, itemClassName = "tocify-item", itemClass = "." + itemClassName, extendPageClassName = "tocify-extend-page", extendPageClass = "." + extendPageClassName; // Calling the jQueryUI Widget Factory Method $.widget("toc.tocify", { version: "1.9.0", // These options will be used as defaults options: { context: "body", ignoreSelector: null, selectors: "h1, h2, h3", showAndHide: true, showEffect: "slideDown", showEffectSpeed: "medium", hideEffect: "slideUp", hideEffectSpeed: "medium", smoothScroll: true, smoothScrollSpeed: "medium", scrollTo: 0, showAndHideOnScroll: true, highlightOnScroll: true, highlightOffset: 40, theme: "bootstrap", extendPage: true, extendPageOffset: 100, history: true, scrollHistory: false, hashGenerator: "compact", highlightDefault: true }, // _Create _create: function() { var self = this; self.extendPageScroll = true; // Internal array that keeps track of all TOC items (Helps to recognize if there are duplicate TOC item strings) self.items = []; // Generates the HTML for the dynamic table of contents self._generateToc(); // Adds CSS classes to the newly generated table of contents HTML self._addCSSClasses(); self.webkit = (function() { for(var prop in window) { if(prop) { if(prop.toLowerCase().indexOf("webkit") !== -1) { return true; } } } return false; }()); // Adds jQuery event handlers to the newly generated table of contents self._setEventHandlers(); // Binding to the Window load event to make sure the correct scrollTop is calculated $(window).load(function() { // Sets the active TOC item self._setActiveElement(true); // Once all animations on the page are complete, this callback function will be called $("html, body").promise().done(function() { setTimeout(function() { self.extendPageScroll = false; },0); }); }); }, // _generateToc _generateToc: function() { // Stores the plugin context in the self variable var self = this, firstElem, ul, ignoreSelector = self.options.ignoreSelector; if(this.options.selectors.indexOf(",") !== -1) { // Grabs the first selector from the string firstElem = $(this.options.context).find(this.options.selectors.replace(/ /g,"").substr(0, this.options.selectors.indexOf(","))); } else { firstElem = $(this.options.context).find(this.options.selectors.replace(/ /g,"")); } if(!firstElem.length) { self.element.addClass(hideTocClassName); return; } self.element.addClass(tocClassName); // Loops through each top level selector firstElem.each(function(index) { if($(this).is(ignoreSelector)) { return; } ul = $(" { "id": headerClassName + index, "class": headerClassName }). // Appends a top level list item HTML element to the previously created HTML header append(self._nestElements($(this), index)); // Add the created unordered list element to the HTML element calling the plugin self.element.append(ul); // Finds all of the HTML tags between the header and subheader elements $(this).nextUntil(this.nodeName.toLowerCase()).each(function() { // If there are no nested subheader elemements if($(this).find(self.options.selectors).length === 0) { // Loops through all of the subheader elements $(this).filter(self.options.selectors).each(function() { //If the element matches the ignoreSelector then we skip it if($(this).is(ignoreSelector)) { return; } self._appendSubheaders.call(this, self, ul); }); } // If there are nested subheader elements else { // Loops through all of the subheader elements $(this).find(self.options.selectors).each(function() { //If the element matches the ignoreSelector then we skip it if($(this).is(ignoreSelector)) { return; } self._appendSubheaders.call(this, self, ul); }); } }); }); },
javascript
28
0.493386
146
30.75
200
starcoderdata