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
const { describe, it, beforeEach, afterEach } = require("mocha") const { expect, assert } = require("chai") const { keys, pick, sortBy, merge, omit } = require("lodash") const { dbSync, dbDrop } = require("../helpers/db") const Zone = require("../../src/models/zone") const zones = require("../testData/zones.json") describe("Model Zone", () => { beforeEach(async () => { await dbSync() }) afterEach(async () => { await dbDrop() }) it("can create points", async () => { await Zone.bulkCreate(zones) const queryResults = await Zone.findAll() const storedZones = queryResults .map(queryResult => pick(queryResult, keys(zones[0]))) expect(sortBy(storedZones, ["name"])) .to.deep.equal(sortBy(zones, ["name"])) }) it("raises an error when the zone name already exists", async () => { try { await Zone.bulkCreate( [ zones[0], merge({ name: "zone1" }, omit(zones[1], "name")) ] ) assert.fail("", "Validation error", "No error was thrown") } catch (error) { expect(error.message).to.equal("Validation error") } }) })
javascript
19
0.591659
71
27.073171
41
starcoderdata
from datastream import Datastream, samplers from {{cookiecutter.package_name}} import datastream def evaluate_datastreams(): return { split_name: Datastream(dataset, samplers.SequentialSampler(len(dataset))) for split_name, dataset in datastream.datasets().items() }
python
12
0.724919
81
27.090909
11
starcoderdata
import fractions N=int(input()) out=1 for i in range(N): i=int(input()) a=fractions.gcd(out, i) out=out*i//a print(out)
python
9
0.656
25
14.75
8
codenet
/** * @license MIT */ /** * @fileoverview * Plugins for generating dist/ output with Rollup. */ import builtinModules from 'builtin-modules'; import { readPackageJson } from '../package.js'; const packageJson = readPackageJson(); const peerDeps = Object.keys(packageJson.peerDependencies || {}); const gnvDeps = Object.keys(packageJson.gnvDependencies || {}); export const disabledModules = [ 'fsevents', ]; export const distExternal = [ /** * Builtins and manually disabled packages. */ ...builtinModules, ...disabledModules, /** * Package.json dependencies. */ ...peerDeps, ]; export const devExternal = [ ...distExternal, ...gnvDeps, ];
javascript
3
0.678822
65
18.805556
36
starcoderdata
package common; import java.io.Serializable; import java.util.Map; import java.util.Stack; import sleep.runtime.SleepUtils; public class ProfilerEvent implements Serializable, Transcript, Scriptable { public String external; public String internal; public String useragent; public Map applications; public String id; public ProfilerEvent(String var1, String var2, String var3, Map var4, String var5) { this.external = var1; this.internal = var2; this.useragent = var3; this.applications = var4; this.id = var5; } public Stack eventArguments() { Stack var1 = new Stack(); var1.push(SleepUtils.getScalar(this.id)); var1.push(SleepUtils.getHashWrapper(this.applications)); var1.push(SleepUtils.getScalar(this.useragent)); var1.push(SleepUtils.getScalar(this.internal)); var1.push(SleepUtils.getScalar(this.external)); return var1; } public String eventName() { return "profiler_hit"; } }
java
11
0.695866
87
26.459459
37
starcoderdata
#!/usr/bin/env python3 import logging import bspump import bspump.common import bspump.file import bspump.trigger ### L = logging.getLogger(__name__) ### class SamplePipeline(bspump.Pipeline): def __init__(self, app, pipeline_id): super().__init__(app, pipeline_id) self.build( bspump.file.FileCSVSource(app, self, config={ 'path': 'data/sample.csv', 'delimiter': ';', 'post': 'noop' }).on(bspump.trigger.RunOnceTrigger(app)), bspump.common.StdDictToJsonParser(app, self), bspump.common.StdJsonToDictParser(app, self), bspump.common.NullSink(app, self) ) if __name__ == '__main__': app = bspump.BSPumpApplication() svc = app.get_service("bspump.PumpService") # Create and register all pipelines here pl = SamplePipeline(app, 'SamplePipeline') svc.add_pipeline(pl) pl.insert_before("DictToJsonParser", bspump.common.PPrintProcessor(app, pl)) pl.insert_after("JsonToDictParser", bspump.common.PPrintProcessor(app, pl)) app.run()
python
16
0.703954
77
19.74
50
starcoderdata
import { PropTypes } from "prop-types"; import { createElement } from "react"; import { Link } from "react-router"; import { makeClassName } from "../../utils/dom"; const ButtonPrimary = ({ children, onClick, small, to }) => { const className = makeClassName( "ButtonPrimary", small && "ButtonPrimary--small" ); return to ? createElement(Link, { className, to }, children) : createElement("a", { className, href: "#", onClick }, children); }; ButtonPrimary.propTypes = { children: PropTypes.string, onClick: PropTypes.func, small: PropTypes.bool, to: PropTypes.string, }; export default ButtonPrimary;
javascript
10
0.673313
70
26.166667
24
starcoderdata
define([ 'common/collections/dashboards' ], function (Collection) { describe('Filtered List Collection', function () { var collection; var data = [ { title: 'Sheep' }, { title: 'Cow' }, { title: 'Pig' }, { title: 'Chicken' }, { title: 'Duck' } ]; beforeEach(function () { collection = new Collection(data); }); it('sorts by title', function () { expect(collection.at(0).get('title')).toEqual('Chicken'); expect(collection.at(1).get('title')).toEqual('Cow'); expect(collection.at(2).get('title')).toEqual('Duck'); expect(collection.at(3).get('title')).toEqual('Pig'); expect(collection.at(4).get('title')).toEqual('Sheep'); }); describe('alphabetise', function () { it('groups by first letter', function () { var output = collection.alphabetise(); expect(_.keys(output)).toEqual(['count', 'C', 'D', 'P', 'S']); expect(output.C).toEqual([ { title: 'Chicken' }, { title: 'Cow' } ]); expect(output.D).toEqual([ { title: 'Duck' } ]); expect(output.P).toEqual([ { title: 'Pig' } ]); expect(output.S).toEqual([ { title: 'Sheep' } ]); }); it('keeps a count of total entries', function () { var output = collection.alphabetise(); expect(output.count).toEqual(5); }); it('filters input based on string matching of a single character', function () { var output = collection.alphabetise({'text': 'C'}); expect(output.count).toEqual(3); expect(output.C).toEqual([ { title: 'Chicken' }, { title: 'Cow' } ]); expect(output.D).toEqual([ { title: 'Duck' } ]); expect(output.P).toBeUndefined(); expect(output.S).toBeUndefined(); }); it('filters input based on string matching of multiple characters', function () { var output = collection.alphabetise({'text': 'ck'}); expect(output.count).toEqual(2); expect(output.C).toEqual([ { title: 'Chicken' }, ]); expect(output.D).toEqual([ { title: 'Duck' } ]); expect(output.P).toBeUndefined(); expect(output.S).toBeUndefined(); }); it('filters input based on string matching against department title', function () { collection.reset([ { title: 'Foo', department: { title: 'Department of Things', abbr: 'DoT' } }, { title: 'Bar', department: { title: 'Department of Other Stuff', abbr: 'DoOS' } } ]); var output = collection.alphabetise({'text': 'thing'}); expect(output.count).toEqual(1); expect(output.F).toEqual([ { title: 'Foo', department: { title: 'Department of Things', abbr: 'DoT' } } ]); }); it('filters input based on string matching against department abbreviation', function () { collection.reset([ { title: 'Foo', department: { title: 'Department of Things', abbr: 'DoT' } }, { title: 'Bar', department: { title: 'Department of Other Stuff', abbr: 'DoOS' } } ]); var output = collection.alphabetise({'text': 'doos'}); expect(output.count).toEqual(1); expect(output.B).toEqual([ { title: 'Bar', department: { title: 'Department of Other Stuff', abbr: 'DoOS' } } ]); }); it('filters based on explicit department filter', function () { collection.reset([ { title: 'Blood', department: { title: 'Department of Health', abbr: 'DH' } }, { title: 'Passport', department: { title: 'Home Office', abbr: 'Home Office' } } ]); var output = collection.alphabetise({'department': 'home-office'}); expect(output.count).toEqual(1); expect(output.P).toEqual([ { title: 'Passport', department: { title: 'Home Office', abbr: 'Home Office' } } ]); }); }); describe('getSlug', function () { it('lowercases the abbreviation if possible', function () { var department = { title: 'Cabinet Office', abbr: 'CO' }; expect(collection.getSlug(department)).toEqual('co'); }); it('turns spaces into hyphens', function () { var department = { title: 'Home Office', abbr: 'Home Office' }; expect(collection.getSlug(department)).toEqual('home-office'); }); it('uses the title if no abbreviation is provided', function () { var department = { title: 'Skills Funding Agency' }; expect(collection.getSlug(department)).toEqual('skills-funding-agency'); }); it('returns unknown-organisation if no useful information is provided', function () { var department = { foo: 'bar' }; expect(collection.getSlug(department)).toEqual('unknown-organisation'); }); }); describe('filterDashboards', function () { var data = [ { title: 'Sheep', 'dashboard-type': 'transaction' }, { title: 'Cow', 'dashboard-type': 'high-volume-transaction' }, { title: 'Pig', 'dashboard-type': 'service-group' }, { title: 'Chicken', 'dashboard-type': 'transaction' }, { title: 'Duck', 'dashboard-type': 'transaction' } ]; beforeEach(function () { collection.reset(data); }); it('filters the collection to only the dashboard types provided', function () { var output; output = collection.filterDashboards('service-group'); expect(output).toEqual([ { title: 'Pig', 'dashboard-type': 'service-group' } ]); output = collection.filterDashboards('transaction'); expect(output).toEqual([ { title: 'Chicken', 'dashboard-type': 'transaction' }, { title: 'Duck', 'dashboard-type': 'transaction' }, { title: 'Sheep', 'dashboard-type': 'transaction' } ]); }); it('handles multiple values', function () { var output; output = collection.filterDashboards('service-group'); expect(output).toEqual([ { title: 'Pig', 'dashboard-type': 'service-group' } ]); output = collection.filterDashboards('transaction', 'service-group'); expect(output).toEqual([ { title: 'Chicken', 'dashboard-type': 'transaction' }, { title: 'Duck', 'dashboard-type': 'transaction' }, { title: 'Pig', 'dashboard-type': 'service-group' }, { title: 'Sheep', 'dashboard-type': 'transaction' } ]); }); it('handles an array as the first argument', function () { var output; output = collection.filterDashboards(['service-group']); expect(output).toEqual([ { title: 'Pig', 'dashboard-type': 'service-group' } ]); }); }); }); });
javascript
30
0.551619
96
32.410628
207
starcoderdata
import os # get the oauth client's API token. # this could come from anywhere api_token = os.getenv("JUPYTERHUB_API_TOKEN") if not api_token: raise ValueError("Make sure to `export JUPYTERHUB_API_TOKEN=$(openssl rand -hex 32)`") # tell JupyterHub to register the service as an external oauth client c.JupyterHub.services = [ { 'name': 'external-oauth', 'oauth_client_id': "whoami-oauth-client-test", 'api_token': api_token, 'oauth_redirect_uri': 'http://127.0.0.1:5555/oauth_callback', }, ]
python
7
0.663636
90
27.947368
19
starcoderdata
using NUnit.Framework; using System.Linq; namespace Autoquit.Standard.Tests { public class StandardModuleTests { [Test] public void StandardModuleTests_CanLoadModules() { // Assign var module = new StandardModule(); // Act var result = module.Load(out var list); // Assert Assert.IsTrue(result); Assert.IsNotEmpty(list); CollectionAssert.AllItemsAreNotNull(list, "Loaded module must not contains null item"); } } }
c#
16
0.579965
99
23.782609
23
starcoderdata
private void run() { try { _latch.await(); if (_throwOnExit) { throw new RuntimeException(); } } catch (InterruptedException e) { // We do not use Thread.currentThread().interrupt() or rely on // _thread.isInterrupted() because querying a thread's interrupt // flag after it has exited is implementation-defined (the observed // behavior with the JDK I was using is that the interrupted flag is // reset on a thread's exit). _isInterrupted = true; } }
java
10
0.594595
76
36.066667
15
inline
package com.uok.se.thisara.smart.trackerapplication.dao; import android.arch.lifecycle.LiveData; import android.arch.persistence.room.Dao; import android.arch.persistence.room.Insert; import android.arch.persistence.room.Query; import com.uok.se.thisara.smart.trackerapplication.model.Bus; import java.util.List; import static android.arch.persistence.room.OnConflictStrategy.REPLACE; @Dao public interface BusDao { @Insert(onConflict = REPLACE) void save(Bus busList); /*@Query("SELECT * FROM bus") LiveData load(String userId);*/ }
java
9
0.770175
71
22.75
24
starcoderdata
using(console); using(ship); var currentCoordsEnemy; var anglerOfEnemy; var radToDegrerOfEnemy; var pointXOfEnemy; var pointYOfEnemy; var dirXOfEnemy; var dirYOfEnemy; var forwardOfEnemy; var veloEnemy; var speedEnemy; var eData; var SC_AI_Drone_Get_eData = { npcGetEnemyData: function (enemyID, veloSwitch) { //var max_structure = ship.GetFinalCacheValue(enemyID, "structure"); var current_structure = ship.GetCurrentValue(enemyID, "structure"); if(generator.ShipExists(enemyID) &&current_structure > 0) { currentCoordsEnemy = ship.GetCoordinates(enemyID); anglerOfEnemy = ship.GetRotation(enemyID); radToDegrerOfEnemy = anglerOfEnemy * (180.0 / Math.PI); pointXOfEnemy = (1 * Math.cos(radToDegrerOfEnemy * Math.PI / 180)) + currentCoordsEnemy.x; pointYOfEnemy = (1 * Math.sin(radToDegrerOfEnemy * Math.PI / 180)) + currentCoordsEnemy.y; dirXOfEnemy = pointXOfEnemy - currentCoordsEnemy.x; dirYOfEnemy = pointYOfEnemy - currentCoordsEnemy.y; forwardOfEnemy = { x: dirXOfEnemy, y: dirYOfEnemy }; if (veloSwitch == 1) { veloEnemy = ship.GetVelocity(enemyID); speedEnemy = Math.sqrt(veloEnemy.x * veloEnemy.x + veloEnemy.y * veloEnemy.y); veloEnemy.x /= speedEnemy; veloEnemy.y /= speedEnemy; eData = { eCoord: currentCoordsEnemy, eAngle: radToDegrerOfEnemy, eForward: forwardOfEnemy, eVelo: veloEnemy, eSpeed: speedEnemy }; return eData; } else { eData = { eCoord: currentCoordsEnemy, eAngle: radToDegrerOfEnemy, eForward: forwardOfEnemy, eVelo: null, eSpeed: null }; return eData; } } else{ return null; } } };
javascript
19
0.705417
135
27.327586
58
starcoderdata
import seaborn as sns import matplotlib.pyplot as plt from wordcloud import WordCloud class mv(): def __init__(self): ''' This class hosts several functions for data visualizations ''' pass def generate_hist(x, y): ''' This creates a function call that plots a histogram ''' plt.style.use('fivethirtyeight') plt.figure(figsize=(12, 5)) sns.barplot(x, y, palette="ch:s=.25,rot=-.25") def generate_wordcloud(text): ''' This creates a function call that creates the wordcloud ''' wordcloud = WordCloud(max_words=30, background_color='white', relative_scaling = 1 ).generate(text) plt.subplots(figsize=(10, 10)) plt.imshow(wordcloud) plt.axis("off") plt.show() def generate_pie(sizes, colors, explode, cities): ''' This creates a function call that plots a pie chart ''' # initializing the chart with the predefined variables plt.pie(sizes, colors=colors, labels=cities, autopct='%1.1f%%', startangle=90, pctdistance=0.85, explode=explode, shadow=True, radius=1) # drawing circle centre_circle = plt.Circle((0,0),0.60,fc='white') fig = plt.gcf() fig.gca().add_artist(centre_circle) # increasing aspect ration plt.tight_layout() plt.show()
python
13
0.537986
69
29.803922
51
starcoderdata
<? $MESS ['SALE_WIZARD_GROUP'] = " "; $MESS ['SALE_WIZARD_MAIL_A'] = "Snail mail"; $MESS ['SALE_WIZARD_MAIL_A_DESC'] = "Tariffs of mail and courier services depend on the order weight with an interval of 500 or 1000 gram."; $MESS ['SALE_WIZARD_COUR'] = "Courier"; $MESS ['SALE_WIZARD_COUR_DESCR'] = "Your order will be delivered within 3 to 10 business days."; $MESS ['SALE_WIZARD_COUR1'] = "Courier delivery"; $MESS ['SALE_WIZARD_SPSR'] = " "; $MESS ['SALE_WIZARD_SPSR_DESCR'] = " "; $MESS ['SALE_WIZARD_MAIL'] = " "; $MESS ['SALE_WIZARD_MAIL_DESCR'] = " "; $MESS ['SALE_WIZARD_UPS'] = "International delivery"; $MESS ['SALE_WIZARD_VAT'] = "VAT"; ?>
php
5
0.663923
140
47.6
15
starcoderdata
package main import ( "strconv" "strings" ) func formatString(str *string) string { if str == nil { return " } else if strings.TrimSpace(*str) == "" { return " } else { return *str } } func formatBool(b *bool) string { if b == nil { return " } else { bval := *b if bval { return "true" } else { return "false" } } } func parseBool(str *string, defaultVal bool) bool { if str == nil { return defaultVal } else if strings.TrimSpace(*str) == "" { return defaultVal } else { boolstr := strings.TrimSpace(*str) boolstr = strings.ToLower(boolstr) if boolstr == "true" || boolstr == "1" { return true } else if boolstr == "false" || boolstr == "0" { return false } else { val, err := strconv.ParseInt(boolstr, 10, 32) if err != nil && val != 0 { return true } else { return defaultVal } } } }
go
13
0.592391
51
16.358491
53
starcoderdata
package com.fillmore_labs.kafka.sensors.serde.confluent.json.serialization; import static io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG; import com.fillmore_labs.kafka.sensors.serde.confluent.common.Confluent; import com.fillmore_labs.kafka.sensors.serde.confluent.common.SchemaRegistryUrl; import com.fillmore_labs.kafka.sensors.serde.json.serialization.ReadingJson; import com.fillmore_labs.kafka.sensors.serde.json.serialization.SensorStateJson; import com.fillmore_labs.kafka.sensors.serde.json.serialization.StateWithDurationJson; import dagger.Module; import dagger.Provides; import io.confluent.kafka.serializers.json.KafkaJsonSchemaDeserializer; import io.confluent.kafka.serializers.json.KafkaJsonSchemaDeserializerConfig; import io.confluent.kafka.serializers.json.KafkaJsonSchemaSerializer; import java.util.Map; import org.apache.kafka.common.serialization.Deserializer; import org.apache.kafka.common.serialization.Serializer; @Module public abstract class SerializationModule { private SerializationModule() {} @Provides @Confluent /* package */ static Serializer readingSerializer( @SchemaRegistryUrl String registryUrl) { var config = Map.of(SCHEMA_REGISTRY_URL_CONFIG, registryUrl); var serializer = new KafkaJsonSchemaSerializer serializer.configure(config, /* isKey= */ false); return serializer; } @Provides @Confluent /* package */ static Deserializer readingDeserializer( @SchemaRegistryUrl String registryUrl) { var config = Map.of( SCHEMA_REGISTRY_URL_CONFIG, registryUrl, KafkaJsonSchemaDeserializerConfig.JSON_VALUE_TYPE, ReadingJson.class); var deserializer = new KafkaJsonSchemaDeserializer deserializer.configure(config, /* isKey= */ false); return deserializer; } @Provides @Confluent /* package */ static Serializer sensorStateSerializer( @SchemaRegistryUrl String registryUrl) { var config = Map.of(SCHEMA_REGISTRY_URL_CONFIG, registryUrl); var serializer = new KafkaJsonSchemaSerializer serializer.configure(config, /* isKey= */ false); return serializer; } @Provides @Confluent /* package */ static Deserializer sensorStateDeserializer( @SchemaRegistryUrl String registryUrl) { var config = Map.of( SCHEMA_REGISTRY_URL_CONFIG, registryUrl, KafkaJsonSchemaDeserializerConfig.JSON_VALUE_TYPE, SensorStateJson.class); var deserializer = new KafkaJsonSchemaDeserializer deserializer.configure(config, /* isKey= */ false); return deserializer; } @Provides @Confluent /* package */ static Serializer stateDurationSerializer( @SchemaRegistryUrl String registryUrl) { var config = Map.of(SCHEMA_REGISTRY_URL_CONFIG, registryUrl); var serializer = new KafkaJsonSchemaSerializer serializer.configure(config, /* isKey= */ false); return serializer; } @Provides @Confluent /* package */ static Deserializer stateDurationDeserializer( @SchemaRegistryUrl String registryUrl) { var config = Map.of( SCHEMA_REGISTRY_URL_CONFIG, registryUrl, KafkaJsonSchemaDeserializerConfig.JSON_VALUE_TYPE, StateWithDurationJson.class); var deserializer = new KafkaJsonSchemaDeserializer deserializer.configure(config, /* isKey= */ false); return deserializer; } }
java
8
0.74544
125
33.890909
110
starcoderdata
import { shallow } from 'enzyme'; import React from 'react'; import CounterApp from '../../CounterApp'; describe('CounterApp funciones del contador', () => { let wrapper = shallow(<CounterApp value={10} />); beforeEach(() => { wrapper = shallow(<CounterApp value={10} />); }); test('should be showing the component CounterApp', () => { expect(wrapper).toMatchSnapshot(); }); test('should be 100 at the counter show', () => { const contador = 100; const wrapper = shallow(<CounterApp value={contador} />); const contadorhtml = parseInt(wrapper.find('h2').text()); expect(contador).toBe(contadorhtml); }); test('should be increment counter in CounterApp', () => { wrapper.find('button').at(0).simulate('click'); const counterText = parseInt(wrapper.find('h2').text()); expect(counterText).toBe(11); }); test('should be decrement counter in CounterApp', () => { wrapper.find('button').at(2).simulate('click'); const counterText = parseInt(wrapper.find('h2').text()); expect(counterText).toBe(9); }); test('should be reset the counter in CounterApp', () => { wrapper.find('button').at(0).simulate('click'); wrapper.find('button').at(0).simulate('click'); wrapper.find('button').at(2).simulate('click'); wrapper.find('button').at(1).simulate('click'); const counterReset = parseInt(wrapper.find('h2').text()); expect(counterReset).toBe(10); }); });
javascript
20
0.657204
59
26.096154
52
starcoderdata
using DataTransferObjects; using FluentValidation; using Microsoft.Extensions.DependencyInjection; using TaskList.Application.Services; using TaskList.Application.Services.Interfaces; using TaskList.Application.Services.Validators; namespace TaskList.Application.Ioc { public static class IocService { public static void Register(IServiceCollection services) { services.AddScoped<ITaskService, TaskService>(); services.AddScoped TaskValidator>(); } } }
c#
14
0.750446
69
28.578947
19
starcoderdata
private void formResultAction(Transaction transaction, Exception exception) { FormResult formResult = null; if (transaction != null) { formResult = this.manageTransactionState(transaction); } else if (exception != null) { formResult = this.manageTransactionError(exception); } else { //no-op } if (formResult != null) { switch (formResult) { // this never happens for now case FormActionReset: { this.setLoadingMode(false, false); if (!isPaymentTokenizable()) { forceBackPressed(); } } break; case FormActionReload: { //this is made directly this.setLoadingMode(false, false); } break; case FormActionBackgroundReload: { //this.setLoadingMode(true); //it's on loading mode already this.transactionNeedsReload(transaction); } break; case FormActionForward: { this.setLoadingMode(false, true); //do not dismiss the loading thing now } break; case FormActionQuit: { //not need to stop the loading mode finish(); } break; default: { //nothing this.setLoadingMode(false, true); } } } }
java
14
0.453374
77
25.737705
61
inline
def __getitem__(self, index): ''' get data for feature and target hypothesis NOTE: For stock transactions are evaluated by the diff of today's price and the next day's, `y` labels are a little bit tricky ''' if (index > self.len - 1): raise IndexError() features = self.data[index] # the first row will be used to # generate `y` labels target = torch.Tensor([ self.data[index+1][0], # open price self.data[index+1][1], # highest self.data[index+1][2], # lowest self.data[index+1][3] # close price ]) return features, target
python
11
0.515994
74
39
18
inline
/* Copyright (c) 2018-2019 Uber Technologies, Inc. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. */ /* eslint-disable flowtype/require-valid-file-annotation */ import * as React from 'react'; import {useStyletron} from 'baseui'; function getPadding(componentType) { const multiplier = Number(componentType.replace('h', '')); return `${multiplier * 8}px`; } const TableOfContents = props => { const [useCss, theme] = useStyletron(); const TOC = []; const content = props.content[0].props.children; content && content.forEach && content.forEach(element => { if ( element.props.name && element.props.name.startsWith('h') && element.props.children.toLowerCase ) { TOC.push({ name: element.props.children, anchor: `#${element.props.children .toLowerCase() .replace(/\s+/g, '-')}`, component: element.props.name, }); } if (element.props.path && element.props.title) { TOC.push({ name: element.props.title, anchor: `#${element.props.title.toLowerCase().replace(/\s+/g, '-')}`, component: 'h3', }); } if (element.props.api && element.props.heading) { TOC.push({ name: element.props.heading, anchor: `#${element.props.heading .toLowerCase() .replace(/\s+/g, '-')}`, component: 'h3', }); } }); if (TOC.length === 1) { return null; } return ( <ul className={useCss({ [theme.direction === 'rtl' ? 'borderRight' : 'borderLeft']: `1px solid ${theme.colors.mono400}`, listStyle: 'none', [theme.direction === 'rtl' ? 'marginRight' : 'marginLeft']: theme.sizing .scale400, paddingLeft: 0, paddingRight: 0, // to make sure we align vertically with the edit on github button marginTop: '-10px', marginBottom: 0, // set predictable width to avoid page relayout when table of content changes width: '160px', position: 'fixed', top: '100px', })} > {TOC.map(header => ( <li key={header.name} className={useCss({ ...theme.typography.font100, [theme.direction === 'rtl' ? 'paddingRight' : 'paddingLeft']: getPadding(header.component), })} > <a className={useCss({color: theme.colors.foregroundAlt})} href={header.anchor} > {header.name} ))} ); }; export default TableOfContents;
javascript
26
0.539065
85
25.443396
106
starcoderdata
def rotate(self, degrees): times = int(degrees / 90) if times > 4 or times < -4: times = times / 4 if times < 0: times = times + 4 rotated_image_matrix = [ [0 for i in range(self.height)] for j in range(self.width) ] # criando a nova matriz for _ in range(times): # para cada vez no numero total de vezes for i in range(self.height): for j in range(self.width): rotated_image_matrix[j][self.height - 1 - i] = self.image_matrix[i][ j ] rotated_width = self.height rotated_height = self.width return rotated_image_matrix, rotated_width, rotated_height
python
15
0.5166
88
36.7
20
inline
/* JSON encoding for messages written to Kafka. * * The JSON format is defined by libavro's avro_value_to_json function, which * produces JSON as defined in the Avro spec: * https://avro.apache.org/docs/1.7.7/spec.html#json_encoding * * Examples: * * * {"id": {"int": 1}} // an integer key * * {"id": {"int": 3}, "title": {"string": "Man Bites Dog"}} // a row with two fields */ #include "json.h" #include #include int avro_bin_to_json(avro_schema_t schema, const void *val_bin, size_t val_len, char **val_out, size_t *val_len_out); int json_encode_msg(table_metadata_t table, const void *key_bin, size_t key_len, char **key_out, size_t *key_len_out, const void *row_bin, size_t row_len, char **row_out, size_t *row_len_out) { int err; err = avro_bin_to_json(table->key_schema, key_bin, key_len, key_out, key_len_out); if (err) { fprintf(stderr, "json: error encoding key\n"); return err; } err = avro_bin_to_json(table->row_schema, row_bin, row_len, row_out, row_len_out); if (err) { fprintf(stderr, "json: error encoding row\n"); return err; } return 0; } int avro_bin_to_json(avro_schema_t schema, const void *val_bin, size_t val_len, char **val_out, size_t *val_len_out) { if (!val_bin) { *val_out = NULL; return 0; } else if (!schema) { fprintf(stderr, "json: got a value where we didn't expect one, and no schema to decode it\n"); *val_out = NULL; return EINVAL; } avro_reader_t reader = avro_reader_memory(val_bin, val_len); avro_value_iface_t *iface = avro_generic_class_from_schema(schema); if (!iface) { fprintf(stderr, "json: error in avro_generic_class_from_schema: %s\n", avro_strerror()); avro_reader_free(reader); return EINVAL; } int err; avro_value_t value; err = avro_generic_value_new(iface, &value); if (err) { fprintf(stderr, "json: error in avro_generic_value_new: %s\n", avro_strerror()); avro_value_iface_decref(iface); avro_reader_free(reader); return err; } err = avro_value_read(reader, &value); if (err) { fprintf(stderr, "json: error decoding Avro value: %s\n", avro_strerror()); avro_value_decref(&value); avro_value_iface_decref(iface); avro_reader_free(reader); return err; } err = avro_value_to_json(&value, 1, val_out); if (err) { fprintf(stderr, "json: error converting Avro value to JSON: %s\n", avro_strerror()); avro_value_decref(&value); avro_value_iface_decref(iface); avro_reader_free(reader); return err; } *val_len_out = strlen(*val_out); // not including null terminator - to librdkafka it's just bytes avro_value_decref(&value); avro_value_iface_decref(iface); avro_reader_free(reader); return 0; }
c
11
0.593917
101
28.333333
102
starcoderdata
package com.machpay.api.user.verification; import com.machpay.api.common.enums.ContactType; import com.machpay.api.entity.ContactVerification; import com.machpay.api.entity.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface ContactVerificationRepository extends JpaRepository<ContactVerification, String> { ContactVerification findByToken(String token); ContactVerification findByUserIdAndType(Long id, Enum type); Boolean existsByUserAndType(User user, ContactType contactType); Optional findByUserAndType(User user, ContactType contactType); }
java
4
0.828534
99
32.26087
23
starcoderdata
<?php session_name(md5("www.r6club.com.br")); session_start(); if(isset($_SESSION['login_id']) and !empty($_SESSION['login_id']) and isset($_POST['motivo']) and isset($_POST['id_lobby'])){ require('connection.php'); $id = $_SESSION['login_id']; $id_lobby = $_POST['id_lobby']; $tempo_inclusao = date("Y-m-d H:i:s", strtotime("+3 seconds")); $motivo = trim(filter_var($_POST['motivo'], FILTER_SANITIZE_STRING)); $busca_report = mysqli_query($conexao, "SELECT id FROM lobby_reports WHERE id_quem_reportou = '$id' and id_lobby = '$id_lobby' "); $busca_lobby = mysqli_query($conexao, "SELECT cancelado, id, finalizado, time_azul, time_laranja FROM lobby WHERE id = '$id_lobby'"); $dado_lobby = mysqli_fetch_array($busca_lobby); $cancelado = $dado_lobby['cancelado']; $finalizado = $dado_lobby['finalizado']; $times = $dado_lobby['time_azul'].','.$dado_lobby['time_laranja']; if($cancelado == '0'){ if(mysqli_num_rows($busca_report) == 0){ $data = date("Y-m-d H:i:s"); $insere_report = mysqli_query($conexao, "INSERT INTO lobby_reports (id_quem_reportou, id_lobby, motivo, data) VALUES ('$id', '$id_lobby', '$motivo', '$data')"); $busca_reports = mysqli_query($conexao, "SELECT id FROM lobby_reports WHERE id_lobby = '$id_lobby'"); if(mysqli_num_rows($busca_reports) >= 7 and $finalizado == '0'){ $msg = "PARTIDA CANCELADA. Cancelamento ocorreu pois obteve 70% de denúncias dos jogadores. Leia nossas regras de criação de partidas e saiba mais. Você já pode sair desta página"; $insere_report .= mysqli_query($conexao, "INSERT INTO chat (id_user, content, id_lobby, timestamp, time, nick) VALUES ('0', '$msg', '$id_lobby', '$tempo_inclusao', 'ambos', 'SERVIDOR: ')"); $insere_report .= mysqli_query($conexao, "UPDATE lobby SET cancelado = '1', tempo_final = '$tempo_inclusao' WHERE id = '$id_lobby'"); $insere_report .= mysqli_query($conexao, "DELETE FROM users_buscando WHERE id_user IN ($times)"); if($insere_report == true){ echo "success"; }else{ echo "error"; } }else{ if($insere_report == true){ echo "success"; }else{ echo "error"; } } }else{ echo "try"; } }else{ echo "cancelado"; } }else{ echo "Erro [003]: Você não está logado ou falta dados para a denúncia."; } ?>
php
16
0.616709
197
43.846154
52
starcoderdata
using System; using System.Text.Json; using System.Text.Json.Serialization; using PlatformRacing3.Common.Level; namespace PlatformRacing3.Common.Json { public sealed class JsonLevelModeConverter : JsonConverter { public override LevelMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => throw new NotImplementedException(); public override void Write(Utf8JsonWriter writer, LevelMode value, JsonSerializerOptions options) { string mode = value.ToString(); writer.WriteStringValue(char.ToLowerInvariant(mode[0]) + mode[1..]); } } }
c#
18
0.798496
150
32.25
20
starcoderdata
private void printBALines(SourceFileCoverage sourceFile) throws IOException { for (BranchCoverage branch : sourceFile.getAllBranches()) { if (!branch.blockNumber().isEmpty() && !branch.branchNumber().isEmpty()) { // This branch was already printed with more information as a BRDA line. continue; } bufferedWriter.write(Constants.BA_MARKER); bufferedWriter.write(Integer.toString(branch.lineNumber())); bufferedWriter.write(Constants.DELIMITER); // 0 = branch was not executed // 1 = branch was executed but not taken // 2 = branch was executed and taken bufferedWriter.write(branch.wasExecuted() ? "2" : "0"); bufferedWriter.newLine(); } }
java
12
0.674483
80
44.375
16
inline
package com.bdoemu.gameserver.model.creature.player.itemPack; import com.bdoemu.commons.collection.ListSplitter; import com.bdoemu.commons.concurrent.CloseableReentrantLock; import com.bdoemu.commons.database.mongo.JSONable; import com.bdoemu.core.network.sendable.SMAddItemToInventory; import com.bdoemu.core.network.sendable.SMGetAllEquipSlot; import com.bdoemu.core.network.sendable.SMInventorySlotCount; import com.bdoemu.core.network.sendable.SMWarehouseSlotCount; import com.bdoemu.gameserver.model.creature.DropBag; import com.bdoemu.gameserver.model.creature.player.Player; import com.bdoemu.gameserver.model.creature.player.itemPack.events.IBagEvent; import com.bdoemu.gameserver.model.creature.servant.Servant; import com.bdoemu.gameserver.model.items.Item; import com.bdoemu.gameserver.model.items.ShopItem; import com.bdoemu.gameserver.model.items.enums.EItemStorageLocation; import com.bdoemu.gameserver.model.misc.enums.EPacketTaskType; import com.bdoemu.gameserver.model.stats.elements.Element; import com.bdoemu.gameserver.model.stats.elements.WeightElement; import com.bdoemu.gameserver.model.team.guild.Guild; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.BasicDBObjectBuilder; import com.mongodb.DBObject; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; public class PlayerBag extends JSONable { private final CloseableReentrantLock lock; private final ADBItemPack[] itemPacks; private final List repurchaseList; private final CashInventory cashInventory; private final HashMap<Integer, Warehouse> warehouses; private ShopItem randomShopItem; private Player owner; private DropBag dropBag; public PlayerBag(final Player player, final AccountBag accountBag) { this.lock = new CloseableReentrantLock(); this.repurchaseList = new ArrayList<>(); this.owner = player; (this.itemPacks = new ADBItemPack[2])[0] = new PlayerInventory(player); this.itemPacks[1] = new PlayerEquipments(player); this.cashInventory = accountBag.getCashInventory(); this.warehouses = accountBag.getWarehouses(); } public PlayerBag(final BasicDBObject dbObject, final Player player, final AccountBag accountBag) { this.lock = new CloseableReentrantLock(); this.repurchaseList = new ArrayList<>(); this.owner = player; this.itemPacks = new ADBItemPack[2]; final BasicDBObject invDB = (BasicDBObject) dbObject.get(EItemStorageLocation.Inventory.toString()); this.itemPacks[0] = new PlayerInventory(invDB, player); this.itemPacks[1] = new PlayerEquipments((BasicDBObject) dbObject.get(EItemStorageLocation.Equipments.toString()), player); this.cashInventory = accountBag.getCashInventory(); this.warehouses = accountBag.getWarehouses(); if (dbObject.containsField("weightExpands")) { final BasicDBList weightBasicDBList = (BasicDBList) dbObject.get("weightExpands"); for (final Object aWeightBasicDBList : weightBasicDBList) { this.owner.getGameStats().getWeight().addElement(new WeightElement((BasicDBObject) aWeightBasicDBList)); } } } public boolean onEvent(final IBagEvent event) { try (final CloseableReentrantLock tempLock = this.lock.open()) { if (event.canAct()) { event.onEvent(); return true; } } return false; } public long getAllMoney() { long allMoney = this.getInventory().getItemCount(0); for (final Warehouse warehouse : this.warehouses.values()) { allMoney += warehouse.getItemCount(0); } return allMoney; } public DropBag getDropBag() { return this.dropBag; } public void setDropBag(final DropBag dropBag) { this.dropBag = dropBag; } public ShopItem getRandomShopItem() { return this.randomShopItem; } public void setRandomShopItem(final ShopItem randomShopItem) { this.randomShopItem = randomShopItem; } public Warehouse getWarehouse(final int townId) { return this.warehouses.get(townId); } public Collection getWarehouses() { return this.warehouses.values(); } public List getRepurchaseList() { return this.repurchaseList; } public PlayerEquipments getEquipments() { return (PlayerEquipments) this.itemPacks[EItemStorageLocation.Equipments.ordinal()]; } public PlayerInventory getInventory() { return (PlayerInventory) this.itemPacks[EItemStorageLocation.Inventory.ordinal()]; } public CashInventory getCashInventory() { return this.cashInventory; } public ItemPack getItemPack(final EItemStorageLocation storageType) { return this.getItemPack(storageType, -1, 1); } public ItemPack getItemPack(final EItemStorageLocation storageType, final int servantSession, final int townId) { switch (storageType) { case Inventory: { return this.getInventory(); } case Equipments: { return this.getEquipments(); } case CashInventory: { return this.getCashInventory(); } case GuildWarehouse: { final Guild guild = this.owner.getGuild(); return (guild != null) ? guild.getGuildWarehouse() : null; } case Warehouse: { return this.warehouses.get(townId); } case ServantInventory: { final Servant servant = this.getOwner().getServantController().getServant(servantSession); if (servant != null) { return servant.getInventory(); } return null; } case ServantEquip: { final Servant servant = this.getOwner().getServantController().getServant(servantSession); if (servant != null) { return servant.getEquipments(); } break; } } return null; } public Player getOwner() { return this.owner; } public void onLogin() { final PlayerInventory inventory = this.owner.getPlayerBag().getInventory(); final ListSplitter inventorySplitter = new ListSplitter<>(inventory.getItemMap().values(), 150); while (inventorySplitter.hasNext()) { this.owner.sendPacket(new SMAddItemToInventory(this.owner.getGameObjectId(), inventorySplitter.getNext(), inventorySplitter.isFirst() ? EPacketTaskType.Add : EPacketTaskType.Update)); } final CashInventory cashInventory = this.owner.getPlayerBag().getCashInventory(); final ListSplitter cashInventorySplitter = new ListSplitter<>(cashInventory.getItemMap().values(), 150); while (cashInventorySplitter.hasNext()) { this.owner.sendPacket(new SMAddItemToInventory(this.owner.getGameObjectId(), cashInventorySplitter.getNext(), cashInventorySplitter.isFirst() ? EPacketTaskType.Add : EPacketTaskType.Update)); } this.owner.sendPacket(new SMGetAllEquipSlot(this.owner.getPlayerBag().getEquipments())); this.owner.sendPacket(new SMInventorySlotCount(inventory.getExpandSize())); for (final Warehouse warehouse : this.warehouses.values()) { this.owner.sendPacket(new SMWarehouseSlotCount(warehouse)); } } public DBObject toDBObject() { final BasicDBObjectBuilder builder = new BasicDBObjectBuilder(); final BasicDBList weightExpands = new BasicDBList(); for (final Element element : this.owner.getGameStats().getWeight().getElements()) { if (element instanceof WeightElement) { final WeightElement weightElement = (WeightElement) element; weightExpands.add(weightElement.toDBObject()); } } builder.append("weightExpands", weightExpands); for (final ADBItemPack itemPack : this.itemPacks) { builder.append(itemPack.getLocationType().toString(), itemPack.toDBObject()); } return builder.get(); } }
java
15
0.675182
203
40.063725
204
starcoderdata
using Furion.DatabaseAccessor; namespace Heavens.Core.Entities.Base; public interface IBaseEntity : IPrivateEntity { /// /// id主键 /// public TKey Id { get; set; } /// /// 创建者id /// public int? CreatedId { get; set; } /// /// 创建者 /// public string CreatedBy { get; set; } /// /// 创建时间 /// public DateTime? CreatedTime { get; set; } /// /// 更新者id /// public int? UpdatedId { get; set; } /// /// 更新者 /// public string UpdatedBy { get; set; } /// /// 更新时间 /// public DateTime? UpdatedTime { get; set; } /// /// 根据httpToken设置创建字段,如果没有token信息则只设置CreatedTime /// void SetCreateByHttpToken(); /// /// 根据httpToken设置更新字段,如果没有token信息则只设置UpdatedTime /// void SetUpdateByHttpToken(); } public interface IBaseEntity : IBaseEntity { }
c#
7
0.57397
52
21.723404
47
starcoderdata
public bool AddNewAppointment(AppointmentViewModel appointment) { try { var user = new User(); var workload = new WorkloadBacklog(); // Creating UserKanban object to save. user.UniqueName = appointment._AppointmentUserUniqueName; // Creating Workload object to save. workload.WBID = appointment._AppointmentWorkloadWBID; var appointmentToBeSaved = new Appointment() { AppointmentID = appointment._AppointmentID, AppointmentUser = user, AppointmentWorkload = workload, AppointmentDate = appointment._AppointmentDate, AppointmentHoursDispensed = appointment._AppointmentHoursDispensed, AppointmentTE = appointment._AppointmentTE, AppointmentComment = appointment._AppointmentComment }; _context.Appointments.Add(appointmentToBeSaved); var response = _context.SaveChanges(); if (response > 0) { return true; } else { return false; } } catch (Exception e) { return false; throw new Exception(e.StackTrace); } }
c#
14
0.488874
87
34.333333
42
inline
// // VCSqlite3Handler.c // Example // // Created by lihao10 on 2020/5/29. // Copyright © 2020 GodL. All rights reserved. // #include "VCSqlite3Handler.h" #include "VCRuntime.h" #include "VCBlockingQueue.h" typedef struct __VCSqlite3Handler{ VCRuntimeBase base; const char *path; VCIndex concurrentRead; VCBlockingQueueRef wQueue; VCBlockingQueueRef rQueue; } VCSqlite3Handler; static void __VCSqlite3HandlerDealloc(VCTypeRef ref) { if (VC_UNLIKELY(ref == NULL)) return; VCSqlite3HandlerRef handler = (VCSqlite3HandlerRef)ref; free((void *)handler->path); if (handler->rQueue) { VCRelease(handler->rQueue); handler->rQueue = NULL; } if (handler->wQueue) { VCRelease(handler->wQueue); handler->wQueue = NULL; } free(handler); handler = NULL; } static void __VCSqlite3HandlerSetupHandle(VCSqlite3HandlerRef ref) { VCSqlite3Ref sqlite3 = VCSqlite3Create(ref->path); VCBlockingQueueEnqueue(ref->wQueue, sqlite3); VCRelease(sqlite3); for (VCIndex i=0; i i++) { sqlite3 = VCSqlite3Create(ref->path); VCBlockingQueueEnqueue(ref->rQueue, sqlite3); VCRelease(sqlite3); } } const VCRuntimeClass __VCSqlite3HandlerClass = { "VCSqlite3Handler", NULL, NULL, NULL, NULL, __VCSqlite3HandlerDealloc }; static volatile VCTypeID __VCSqlite3HandlerTypeID = 0; VCTypeID VCSqlite3HandlerGetTypeID(void) { return VCRuntimeRegisterClass(__VCSqlite3HandlerTypeID, __VCSqlite3HandlerClass); } VCSqlite3HandlerRef VCSqlite3HandlerCreate(const char *path,VCIndex concurrentRead) { assert(path); if (VC_UNLIKELY(strlen(path) == 0)) return NULL; VCSqlite3HandlerRef ref = (VCSqlite3HandlerRef)VCRuntimeCreateInstance(VCSqlite3HandlerGetTypeID(), sizeof(VCSqlite3Handler) - sizeof(VCRuntimeBase)); if (VC_UNLIKELY(ref == NULL)) return NULL; ref->path = strdup(path); if (concurrentRead == 0) concurrentRead = 6; ref->concurrentRead = concurrentRead; VCBlockingQueueRef wQueue = VCBlockingQueueCreate(&kVCTypeBlockingQueueCallBack); ref->wQueue = wQueue; VCBlockingQueueRef rQueue = VCBlockingQueueCreate(&kVCTypeBlockingQueueCallBack); ref->rQueue = rQueue; __VCSqlite3HandlerSetupHandle(ref); return ref; } VCSqlite3Ref VCSqlite3HandlerGetWriteHandle(VCSqlite3HandlerRef ref) { assert(ref); VCSqlite3Ref sqlite3 = (VCSqlite3Ref)VCBlockingQueueDequeue(ref->wQueue); if (!VCSqlite3IsOpen(sqlite3)) { VCSqlite3OpenWal(sqlite3); } return sqlite3; } void VCSqlite3HandlerReturnWriteHandle(VCSqlite3HandlerRef ref,VCSqlite3Ref sqlite3) { assert(ref); VCBlockingQueueEnqueue(ref->wQueue, sqlite3); VCRelease(sqlite3); } VCSqlite3Ref VCSqlite3HandlerGetReadHandle(VCSqlite3HandlerRef ref) { assert(ref); VCSqlite3Ref sqlite3 = (VCSqlite3Ref)VCBlockingQueueDequeue(ref->rQueue); if (!VCSqlite3IsOpen(sqlite3)) { VCSqlite3OpenWal(sqlite3); } return sqlite3; }
c
11
0.716497
154
29.069307
101
starcoderdata
<?php namespace App\Http\Helpers; use App\Models\Role; class Helper { public static function getManagerRoleId() { $manager_id = Role::firstWhere('name', '=', 'Manager')->id; return $manager_id; } public static function getCustomerRoleId() { $cust_id = Role::firstWhere('name', '=', 'Customer')->id; return $cust_id; } }
php
12
0.601078
67
20.882353
17
starcoderdata
<?php namespace App\Notifications; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ trait ValidateMessage { /** * Get the password reset validation rules. * * @return array */ protected function rules() { return [ ]; } /** * Get the password reset validation error messages. * * @return array */ protected function validationErrorMessages() { return [ 'email.required' => 'email_empty', 'email.email' => 'email_format_invalid', 'password.required' => ' 'password.confirmed' => ' 'password.min' => ' 'id.required' => 'id_required', ]; } /** * Validate request * @param Request $request * @return JsonResponse */ public function validateRequest(Request $request, $rule = null, $errorMessage = null){ if(is_null($rule)){ $rule = $this->rules(); } if(is_null($errorMessage)){ $errorMessage = $this->validationErrorMessages(); } //check validator $data = $request->all(); $validator = Validator::make($data, $rule, $errorMessage); return $this->validateError($validator); } /** * Validate required * @param $data * @param null $rule * @param null $errorMessage * @return JsonResponse */ public function validateValues($data, $rule = null, $errorMessage = null){ if(is_null($rule)){ $rule = $this->rules(); } if(is_null($errorMessage)){ $errorMessage = $this->validationErrorMessages(); } //check validator $validator = Validator::make($data, $rule, $errorMessage); return $this->validateError($validator); } /** * * @param Validator $validator * @return JsonResponse */ public function validateError($validator){ if ($validator->fails()) { $messages = $validator->messages(); foreach ($messages->all() as $error) { return response()->json([ 'code' => $error, 'message' => trans("error_message." . $error), 'data' => null ]); } } return null; } }
php
20
0.534368
90
25.792079
101
starcoderdata
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.spring.integration.servicebus.queue; import com.azure.spring.integration.servicebus.factory.ServiceBusQueueClientFactory; import com.azure.spring.integration.servicebus.inbound.ServiceBusQueueInboundChannelAdapter; import com.azure.spring.integration.servicebus.queue.support.ServiceBusQueueTestOperation; import com.microsoft.azure.servicebus.IQueueClient; import com.azure.spring.integration.test.support.InboundChannelAdapterTest; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class ServiceBusQueueInboundAdapterTest extends InboundChannelAdapterTest { @Mock ServiceBusQueueClientFactory clientFactory; @Mock IQueueClient queueClient; @Override public void setUp() { when(this.clientFactory.getOrCreateClient(anyString())).thenReturn(queueClient); this.adapter = new ServiceBusQueueInboundChannelAdapter(destination, new ServiceBusQueueTestOperation(clientFactory)); } }
java
11
0.825793
198
42.558824
34
starcoderdata
package com.em.validation.rebind.generator.source; /* GWT Validation Framework - A JSR-303 validation framework for GWT (c) 2008 gwt-validation contributors (http://code.google.com/p/gwt-validation/) 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. */ import java.lang.annotation.ElementType; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import javax.validation.metadata.ConstraintDescriptor; import javax.validation.metadata.Scope; import com.em.validation.client.reflector.IReflector; import com.em.validation.client.reflector.ReflectorFactory; import com.em.validation.rebind.metadata.ClassDescriptor; import com.em.validation.rebind.metadata.PropertyMetadata; import com.em.validation.rebind.resolve.PropertyResolver; import com.em.validation.rebind.template.TemplateController; public enum ReflectorGenerator { INSTANCE; private final String BASE_PACKAGE = "com.em.validation.client"; private final String TARGET_PACKAGE = this.BASE_PACKAGE + ".generated.reflector"; public ClassDescriptor getReflectorDescirptions(Class targetClass) { //get the runtime reflector (usful for some metadata) IReflector runtimeReflector = ReflectorFactory.INSTANCE.getReflector(targetClass); //target of generation String targetPackage = this.TARGET_PACKAGE; UUID uuid = UUID.randomUUID(); String uuidString = uuid.toString(); uuidString = uuidString.replaceAll("\\-",""); //get the basic name of the target class and generate the reflector class name, add uuid to avoid colisions with //classes from different trees (and groups) that may have otherwise stomped on each other String concreteClassName = targetClass.getSimpleName() + "Reflector_" + uuidString; //the source listings ClassDescriptor reflectorDescriptor = new ClassDescriptor(); //set up imports List imports = new ArrayList String targetClassString = targetClass.getName(); if(targetClassString != null && !targetClassString.isEmpty()) { targetClassString = targetClassString.replaceAll("\\$", "."); } imports.add(targetClassString); //group sequence Class groupSequenceArray = runtimeReflector.getGroupSequence(); List groupSequences = new ArrayList for(Class group : groupSequenceArray) { groupSequences.add(group.getName() + ".class"); } //the list of properties Map metadataMap = PropertyResolver.INSTANCE.getPropertyMetadata(targetClass); //list of cascaded properties Set cascadedProperties = new LinkedHashSet //where properties are declared (for finder) Set declaredOnMethod = new LinkedHashSet Set declaredOnField = new LinkedHashSet //generate class descriptors for each metadata on each annotation for(PropertyMetadata propertyMetadata : metadataMap.values()) { for(ConstraintDescriptor constraint : runtimeReflector.getConstraintDescriptors(propertyMetadata.getName(), Scope.LOCAL_ELEMENT)) { //generate the class descriptor (the actual ascii data that makes up the class) from the annotation and property metadata ClassDescriptor descriptor = ConstraintDescriptionGenerator.INSTANCE.generateConstraintDescriptor(constraint.getAnnotation(),propertyMetadata.getReturnType()); //set up the dependencies in the property metadata and in the class descriptor propertyMetadata.getConstraintDescriptorClasses().add(descriptor.getClassName()); reflectorDescriptor.getDependencies().add(descriptor); //get declared on Set declaredOn = runtimeReflector.declaredOn(Scope.LOCAL_ELEMENT, propertyMetadata.getName(), constraint); //if the return list contains "field" then it has been declared on a field and we pass this info to the template if(declaredOn.contains(ElementType.FIELD)) { declaredOnField.add(descriptor.getClassName()); } //if the return list contains "method" then it has been declared on a method and we pass this info to the template if(declaredOn.contains(ElementType.METHOD)) { declaredOnMethod.add(descriptor.getClassName()); } } //save cascaded property if(runtimeReflector.isCascaded(propertyMetadata.getName())) { cascadedProperties.add(propertyMetadata.getName()); } } Set classLevelConstraints = new HashSet for(ConstraintDescriptor classLevel : runtimeReflector.getClassConstraintDescriptors(Scope.LOCAL_ELEMENT)) { //generate the class descriptor (the actual ascii data that makes up the class) from the annotation and property metadata ClassDescriptor descriptor = ConstraintDescriptionGenerator.INSTANCE.generateConstraintDescriptor(classLevel.getAnnotation(),targetClass); reflectorDescriptor.getDependencies().add(descriptor); classLevelConstraints.add(descriptor.getClassName()); } //create data model Map templateDataModel = new HashMap<String, Object>(); templateDataModel.put("concreteClassName", concreteClassName); templateDataModel.put("importList", imports); templateDataModel.put("properties", metadataMap.values()); templateDataModel.put("reflectionTargetName", targetClass.getSimpleName()); templateDataModel.put("targetPackage", targetPackage); templateDataModel.put("generatedConstraintPackage",ConstraintDescriptionGenerator.INSTANCE.getTargetPackage()); templateDataModel.put("cascades",cascadedProperties); templateDataModel.put("declaredOnMethod", declaredOnMethod); templateDataModel.put("declaredOnField", declaredOnField); templateDataModel.put("groupSequence",groupSequences); templateDataModel.put("classLevelConstraints",classLevelConstraints); //create class descriptor from generated code reflectorDescriptor.setClassContents(TemplateController.INSTANCE.processTemplate("templates/reflector/ReflectorImpl.ftl", templateDataModel)); reflectorDescriptor.setClassName(concreteClassName); reflectorDescriptor.setFullClassName(targetPackage + "." + concreteClassName); reflectorDescriptor.setPackageName(this.TARGET_PACKAGE); return reflectorDescriptor; } }
java
17
0.782267
163
44.113924
158
starcoderdata
def make_filter(my_request): """ Build a list of filters for each object """ query_attrs = dict() query_attrs['program'] = dict() query_attrs['project'] = dict() query_attrs['indicator'] = dict() query_attrs['collecteddata'] = dict() for param, val in my_request.iteritems(): if param == 'program': query_attrs['program']['id__in'] = val.split(',') query_attrs['project']['program__id__in'] = val.split(',') query_attrs['indicator']['program__id__in'] = val.split(',') query_attrs['collecteddata']['indicator__program__id__in'] = val.split( ',') elif param == 'sector': query_attrs['program']['sector__in'] = val.split(',') query_attrs['project']['sector__in'] = val.split(',') query_attrs['indicator']['sector__in'] = val.split(',') query_attrs['collecteddata']['indicator__sector__in'] = val.split( ',') elif param == 'country': query_attrs['program']['country__id__in'] = val.split(',') query_attrs['project']['program__country__id__in'] = val.split(',') query_attrs['indicator']['program__country__in'] = val.split(',') query_attrs['collecteddata']['program__country__in'] = val.split( ',') elif param == 'indicator__id': query_attrs['indicator']['id'] = val query_attrs['collecteddata']['indicator__id'] = val elif param == 'approval': if val == "new": query_attrs['project']['approval'] = "" else: query_attrs['project']['approval'] = val elif param == 'collecteddata__isnull': if val == "True": query_attrs['indicator']['collecteddata__isnull'] = True else: query_attrs['indicator']['collecteddata__isnull'] = False elif param == 'export': """ IGNORE EXPORT PARAM """ else: query_attrs['program'][param] = val query_attrs['project'][param] = val query_attrs['indicator'][param] = val query_attrs['collecteddata'][param] = val return query_attrs
python
16
0.510141
83
42.634615
52
inline
#include<cstdio> #include<cstring> #include<vector> #include<iostream> #include<algorithm> using namespace std; typedef long long ll; const ll mod= 998244353; int main(){ ll n; scanf("%lld",&n); vector<ll> items(n+5,0); bool sign=false; ll maxn=0; for(int i=0;i<n;i++){ ll t; scanf("%lld",&t); maxn=max(maxn,t); if((i==0&&t!=0)||(i>0&&t==0)) sign=true; items[t]++; } if(sign) printf("0"); else{ ll k=1; ll ans=1; for(ll i=1;i<=maxn;i++){ for(ll j=0;j<items[i];j++){ ans*=k ; ans%=mod; } k=items[i]; } printf("%lld",ans); } return 0; }
c++
12
0.547421
32
13.682927
41
codenet
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_SAFE_BROWSING_DOWNLOAD_FEEDBACK_H_ #define CHROME_BROWSER_SAFE_BROWSING_DOWNLOAD_FEEDBACK_H_ #include #include "base/callback_forward.h" #include "base/files/file_path.h" #include "base/memory/scoped_ptr.h" #include "base/threading/non_thread_safe.h" #include "chrome/browser/safe_browsing/two_phase_uploader.h" namespace content { class DownloadItem; } namespace safe_browsing { class DownloadFeedbackFactory; // Handles the uploading of a single downloaded binary to the safebrowsing // download feedback service. class DownloadFeedback : public base::NonThreadSafe { public: // Takes ownership of the file pointed to be |file_path|, it will be deleted // when the DownloadFeedback is destructed. static DownloadFeedback* Create( net::URLRequestContextGetter* request_context_getter, base::TaskRunner* file_task_runner, const base::FilePath& file_path, const std::string& ping_request, const std::string& ping_response); // The largest file size we support uploading. // Note: changing this will affect the max size of // SBDownloadFeedback.SizeSuccess and SizeFailure histograms. static const int64 kMaxUploadSize; // The URL where the browser sends download feedback requests. static const char kSbFeedbackURL[]; virtual ~DownloadFeedback() {} // Makes the passed |factory| the factory used to instantiate // a DownloadFeedback. Useful for tests. static void RegisterFactory(DownloadFeedbackFactory* factory) { factory_ = factory; } // Start uploading the file to the download feedback service. // |finish_callback| will be called when the upload completes or fails, but is // not called if the upload is cancelled by deleting the DownloadFeedback // while the upload is in progress. virtual void Start(const base::Closure& finish_callback) = 0; virtual const std::string& GetPingRequestForTesting() const = 0; virtual const std::string& GetPingResponseForTesting() const = 0; private: // The factory that controls the creation of DownloadFeedback objects. // This is used by tests. static DownloadFeedbackFactory* factory_; }; class DownloadFeedbackFactory { public: virtual ~DownloadFeedbackFactory() {} virtual DownloadFeedback* CreateDownloadFeedback( net::URLRequestContextGetter* request_context_getter, base::TaskRunner* file_task_runner, const base::FilePath& file_path, const std::string& ping_request, const std::string& ping_response) = 0; }; } // namespace safe_browsing #endif // CHROME_BROWSER_SAFE_BROWSING_DOWNLOAD_FEEDBACK_H_
c
12
0.7493
80
33.409639
83
starcoderdata
import requests api_key = 'acc_c300ad844f148f7' api_secret = ' image_url = 'https://upload.wikimedia.org/wikipedia/commons/a/a6/The_Rim_Fire_in_the_Stanislaus_National_Forest_near_in_California_began_on_Aug._17%2C_2013-0004.jpg' response = requests.get( 'https://api.imagga.com/v2/tags?image_url=%s' % image_url, auth=(api_key, api_secret)) print(response.json())
python
7
0.721785
165
33.636364
11
starcoderdata
(function() { 'use strict'; var _ = require('underscore'); /***************** Utility Wrappers ******************/ function Single(value) { this.value = value; } Single.prototype.toString = function() { return this.value ; }; function Double(first, second) { this.first = first; this.second = second; } Double.prototype.toString = function() { return '(' + this.first + ' ' + this.second + ')'; }; function Triple(first, second, third) { this.first = first; this.second = second; this.third = third; } Triple.prototype.toString = function() { return '(' + this.first + ' ' + this.second + ' ' + this.third + ')'; }; function Quad(first, second, third, fourth) { this.first = first; this.second = second; this.third = third; this.fourth = fourth; } Quad.prototype.toString = function() { return '(' + this.first + ' ' + this.second + ' ' + this.third + this.fourth + ')'; }; /************ Syntax Tree ****************/ function Sequence(seq) { if(seq) { this.seq = seq; } else { this.seq = []; } } Sequence.prototype.push = function(term) { this.seq.push(term); }; Sequence.prototype.toString = function() { return _(this.seq).map(function(expr) { return expr.toString(); }).join('\n'); }; function Unary(op, x) { Double.call(this, op, x); } Unary.prototype = Object.create(Double.prototype); Unary.prototype.constructor = Unary; function Binary(op, x, y) { Triple.call(this, op, x, y); } Binary.prototype = Object.create(Triple.prototype); Binary.prototype.constructor = Binary; function Trinary(op, x, y, z) { Quad.call(this, op, x, y, z); } Trinary.prototype = Object.create(Quad.prototype); Trinary.prototype.constructor = Trinary; function Ident(value) { Single.call(this, value); } Ident.prototype = Object.create(Single.prototype); Ident.prototype.constructor = Ident; /********************* Value Syntax **********************/ function Char(value) { Single.call(this, value); } Char.prototype = Object.create(Single.prototype); Char.prototype.constructor = Char; function Str(value) { Single.call(this, value); } Str.prototype = Object.create(Single.prototype); Str.prototype.constructor = Str; function UInt(value, hex) { Single.call(this, value); this.hex = hex ? true : false; } UInt.prototype = Object.create(Single.prototype); UInt.prototype.constructor = UInt; function MAC_Addr(value) { Single.call(this, value); } MAC_Addr.prototype = Object.create(Single.prototype); MAC_Addr.prototype.constructor = MAC_Addr; function IPv4_Addr(value) { Single.call(this, value); } IPv4_Addr.prototype = Object.create(Single.prototype); IPv4_Addr.prototype.constructor = IPv4_Addr; /* Syntax symbol exports */ exports.symbol = { SEQ : "seq", X : "x", DEF : "def", ASSIGN : "=", WHILE : "while", COMMA : ",", SWITCH : "switch", CASE : "case", RETURN : "return", BLOCK : "block", IF : "if", CONDITIONAL : "cond", LAND : "and", LOR : "or", AND : "&", OR : "|", XOR : "^", EQ : "==", NEQ : "!=", LT : "<", LTEQ : "<=", GT : ">", GTEQ : ">=", LSHIFT : "<<", RSHIFT : ">>", PLUS : "+", MINUS : "-", MULT : "*", DIV : "/", MOD : "%", TILDE : "~", BANG : "!", TERM : ":", TYPE : "::", KIND : ":::", RARROW : "->", PROJECTION : "proj", RANGE : "range", CALL : "call", BRACE : "brace", array : "array" }; function Term(name) { var i; this.name = name; this.t = []; this.t = Array.prototype.slice.call(arguments); this.t.splice(0, 1); } Term.prototype.push = function(_t) { this.t.push(_t); }; Term.prototype.toString = function () { return "(" + this.name + ' ' + _(this.t).map(function(_t) { return _t.toString(); }).join(", ") + ")"; }; function construct(constructor, args) { function F() { return constructor.apply(this, args); } F.prototype = constructor.prototype; return new F(); } exports.mkTerm = function(name) { var args = Array.prototype.slice.call(arguments); args.splice(0, 1, name); function K() { return Term.apply(this, args); } K.prototype = Term.prototype; return new K(); }; /* Syntax term factory exports */ exports.mkSequence = function mkSequence(seq) { return new Sequence(seq); }; exports.mkUnary = function mkUnary(op, x) { return new Unary(op, x); }; exports.mkBinary = function mkBinary(op, x, y) { return new Binary(op, x, y); }; exports.mkTrinary = function mkTrinary(op, x, y, z) { return new Trinary(op, x, y, z); }; exports.mkIdent = function mkIdent(v) { return new Ident(v); }; exports.mkChar = function mkChar(v) { return new Char(v); }; exports.mkStr = function mkStr(v) { return new Str(v); }; exports.mkUInt = function mkUInt(v, m) { return new UInt(v, m); }; exports.mkMAC_Addr = function mkMAC_Addr(v) { return new MAC_Addr(v); }; exports.mkIPv4_Addr = function mkIPv4_Addr(v) { return new IPv4_Addr(v); }; })();
javascript
23
0.586754
91
21.748899
227
starcoderdata
#!/usr/bin/env python import os import pathlib import sys from qgis.core import \ QgsApplication, QgsVectorLayer, \ QgsProjUtils, QgsCoordinateReferenceSystem fname = os.path.join(os.path.dirname(__file__), 'test_data', 'box.geojson') def testPROJ(): """ Tests if PROJ library can be found """ PROJ_LIB = pathlib.Path(os.environ.get('PROJ_LIB')) assert PROJ_LIB.is_dir(), f'PROJ_LIB does not exist: {PROJ_LIB}' PROJ_DB = PROJ_LIB / 'proj.db' assert PROJ_DB.is_file(), f'proj.db file does not exist: {PROJ_DB}' found = False for path in QgsProjUtils.searchPaths(): path = pathlib.Path(path) / 'proj.db' if path.is_file(): found = True break assert found, f'Unable to find proj.db in QgsProjUtils.searchPaths(): {QgsProjUtils.searchPaths()}' wkt = QgsCoordinateReferenceSystem.fromEpsgId(4326).toWkt() assert not wkt.startswith('GEOGCS["unknown"') def test(vector_file): vl = QgsVectorLayer(vector_file) valid = vl.isValid() print('Valid layer?: {valid}'.format(valid=valid)) if not valid: print('Could not even validate the vector file... ') print('Printing environment\n') for k, v in os.environ.items(): print('{k}: {v}'.format(k=k, v=v)) raise Exception("QGIS Python API not functional") else: nfeat = vl.featureCount() print('Feature count?: {nfeat}'.format(nfeat=nfeat)) assert nfeat == 1 if __name__ == '__main__': # Initialize QGIS API -- we shouldn't have to fuss with paths app = QgsApplication([], False) app.initQgis() print('Ran `app.initQgis`') try: test(fname) testPROJ() except Exception as e: print(e) print('QGIS prefixPath(): "{0}"'.format(app.prefixPath())) sys.exit(1) # Shut down app.exitQgis() print('Ran `app.exitQgis()`')
python
13
0.617119
103
27.691176
68
starcoderdata
import "../../../src/components/VResize/VResize.scss"; import { h, ref, computed, reactive, defineComponent, onMounted, onBeforeUnmount } from 'vue'; import { positionProps } from '../../effects/use-position'; import { useColors } from '../../effects/use-colors'; export const VResize = defineComponent({ name: 'v-resize', props: { emit: { type: Boolean, default: false }, customClass: { type: String }, minSize: { type: [String, Number], default: 50 }, color: { type: String, default: 'grey lighten-2' }, ...positionProps() }, emits: ['resize'], setup(props, { emit }) { const data = reactive({ parentNode: null, startOffset: null, offsetTop: 0, offsetLeft: 0, parentHeight: 0, parentWidth: 0, marginLeft: 0, marginTop: 0, left: 0, top: 0, isActive: false }); const resizeRef = ref(null); const { setBackground } = useColors(); const classes = computed(() => { return { 'v-resize': true, 'v-resize--active': data.isActive, 'v-resize--top': props.top, 'v-resize--bottom': props.bottom, 'v-resize--right': props.right, 'v-resize--left': props.left, [props.customClass]: !!props.customClass }; }); const isDirectY = computed(() => { return props.top || props.bottom; }); const isNeedReverse = computed(() => { return props.top || props.left; }); const currentSize = computed(() => { return isDirectY.value ? data.parentHeight : data.parentWidth; }); const sizeProp = computed(() => { return isDirectY.value ? 'height' : 'width'; }); const reverseDirection = computed(() => { return props.top ? 'top' : 'left'; }); const reverseOffsetKey = computed(() => { const side = reverseDirection.value; return 'offset' + side[0].toUpperCase() + side.slice(1); }); const offset = computed(() => { return isDirectY.value ? data.offsetTop : data.offsetLeft; }); const direction = computed(() => { return isDirectY.value ? 'clientY' : 'clientX'; }); function moveReverse(size) { const { parentNode, left, top } = data; const reverseTo = reverseDirection.value; const value = !isDirectY.value ? currentSize.value - size + left : currentSize.value - size + top; parentNode.style[reverseTo] = `${value}px`; } function setOrEmitSize(size) { if (props.emit) return emit('resize', size); data.parentNode.style[sizeProp.value] = `${size}px`; isNeedReverse.value && moveReverse(size); } function resize(e) { let size; if (isNeedReverse.value) { size = currentSize.value - (e[direction.value] - offset.value) + data.startOffset; } else { size = currentSize.value + (e[direction.value] - currentSize.value - offset.value - data.startOffset); } size > props.minSize && setOrEmitSize(size); } function resetMinMaxStyles() { if (isDirectY.value) { data.parentNode.style.maxHeight = ''; data.parentNode.style.minHeight = ''; } else { data.parentNode.style.maxWidth = ''; data.parentNode.style.minWidth = ''; } } function setParent() { const parent = resizeRef.value.parentNode; data.parentNode = parent; } function computeSizes() { const { top, left, height, width, marginLeft, marginTop } = getComputedStyle(data.parentNode); data.offsetTop = data.parentNode.offsetTop; data.offsetLeft = data.parentNode.offsetLeft; data.marginLeft = parseFloat(marginLeft); data.marginTop = parseFloat(marginTop); data.parentHeight = parseFloat(height); data.parentWidth = parseFloat(width); data.top = parseFloat(top); data.left = parseFloat(left); } function setStartPositions() { const side = reverseDirection.value; const offset = reverseOffsetKey.value; if (data[side] === data[offset]) { data.parentNode.style[side] = `${data[offset]}px`; } } function disableSelection(e) { e.preventDefault(); } function initResize(e) { if (!data.isActive) { data.isActive = true; computeSizes(); resetMinMaxStyles(); setStartPositions(); setStartOffset(e); } requestAnimationFrame(() => resize(e)); } function setStartOffset(e) { if (isNeedReverse.value) data.startOffset = e[direction.value];else data.startOffset = e[direction.value] - currentSize.value; data.startOffset -= offset.value; } function reset() { data.isActive = false; resetMinMaxStyles(); } function onMouseup() { reset(); removeHandlers(); } function onMousedown() { document.addEventListener('mousemove', initResize); document.addEventListener('mouseup', onMouseup); document.addEventListener('selectstart', disableSelection); } function removeHandlers() { document.removeEventListener('mousemove', initResize); document.removeEventListener('mouseup', onMouseup); document.removeEventListener('selectstart', disableSelection); } onMounted(() => { setParent(); }); onBeforeUnmount(() => { document.removeEventListener('mousedown', onMousedown); }); return () => { const propsData = { class: { ...classes.value }, key: 'resize', ref: resizeRef, onMousedown }; return h('div', setBackground(props.color, propsData)); }; } }); //# sourceMappingURL=VResize.js.map
javascript
23
0.585988
132
25.784404
218
starcoderdata
package uk.ac.cam.cl.ticking.ui.ticks; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.joda.time.DateTime; import uk.ac.cam.cl.ticking.ui.api.public_interfaces.beans.TickBean; import com.fasterxml.jackson.annotation.JsonProperty; /** * This class stores information regarding a tick. * * @author tl364 * */ public class Tick implements Comparable { // FORMAT: 'author','name' @JsonProperty("_id") private String tickId; private String name; private String author; private String stubRepo; private DateTime deadline; private List groups = new ArrayList<>(); private boolean star; private Map<String, DateTime> extensions = new HashMap<>(); private DateTime edited; private String externalReference; /** * * Create a new instance of the Tick object. * * This will generate a tick identifier automatically and should only be * used when a user is creating a new tick. * * * @param name * @param stubRepo * @param deadline * @param files */ public Tick(String name, String author, DateTime deadline) { this.setName(name); this.setAuthor(author); this.setDeadline(deadline); initTickId(); } /** * Default constructor for Jackson JSON to POJO because java */ public Tick() { } public Tick(TickBean bean) { this.setName(bean.getName()); this.setDeadline(bean.getDeadline()); this.setGroups(bean.getGroups()); this.setExtensions(bean.getExtensions()); this.setExternalReference(bean.getExternalReference()); this.setStar(bean.isStar()); } /** * @return stubRepo */ public String getStubRepo() { return stubRepo; } /** * @param stubRepo */ public void setStubRepo(String stubRepo) { this.stubRepo = stubRepo; } /** * @return deadline */ public DateTime getDeadline() { return deadline; } /** * @param deadline */ public void setDeadline(DateTime deadline) { this.deadline = deadline; } /** * @return name */ public String getName() { return name; } /** * @param name */ public void setName(String name) { this.name = name; } /** * @return author */ public String getAuthor() { return author; } /** * @param author */ public void setAuthor(String author) { this.author = author; } /** * @return edited */ public DateTime getEdited() { return edited; } /** * @param edited */ public void setEdited(DateTime edited) { this.edited = edited; } /** * @return groups */ public List getGroups() { return groups; } /** * @param groups */ public void setGroups(List groups) { this.groups = groups; } public String getExternalReference() { return externalReference; } public void setExternalReference(String externalReference) { this.externalReference = externalReference; } /** * @param groupId */ public void addGroup(String groupId) { groups.add(groupId); } /** * @param groupId */ public void removeGroup(String groupId) { groups.remove(groupId); } /** * * @return extensions */ public Map<String, DateTime> getExtensions() { return extensions; } /** * * @param extensions */ public void setExtensions(Map<String, DateTime> extensions) { this.extensions = extensions; } /** * * @param crsid * @param extension */ public void addExtension(String crsid, DateTime extension) { this.extensions.put(crsid, extension); } /** * * @param crsid */ public void removeExtension(String crsid) { this.extensions.remove(crsid); } /** * @return tickId */ public String getTickId() { return tickId; } /** * Initialises the tickId field for the Tick object */ public void initTickId() { String decodedName = name.replaceAll("_", "__"); decodedName = decodedName.replace(' ', '_'); decodedName = decodedName.replaceAll("[^a-zA-Z0-9_-]", ""); this.tickId = author + "," + decodedName; } /** * Takes , separated tickIds as they are stored in our system and turns them * into / separated ids for use with the other APIs * * @param tickId * @return tickId in / separated format */ public static String replaceDelimeter(String tickId) { return tickId.replace(',', '/'); } /** * @param tickId * @return The name of the tick extracted from the tick ID. */ public static String getNameFromID(String tickId) { return tickId.split(",")[1]; } /** * {@inheritDoc} */ @Override public int compareTo(Tick o) { return this.name.compareToIgnoreCase(o.name); } /** * {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Tick)) { return false; } return this.tickId.equals(((Tick) o).tickId); } /** * {@inheritDoc} */ @Override public int hashCode() { return tickId.hashCode(); } public boolean isStar() { return star; } public void setStar(boolean star) { this.star = star; } }
java
11
0.657942
77
16.270548
292
starcoderdata
/** * @module media/mediatoolbar */ import Plugin from '@ckeditor/ckeditor5-core/src/plugin'; import WidgetToolbarRepository from '@ckeditor/ckeditor5-widget/src/widgettoolbarrepository'; import {getSelectedMediaWidget} from './media/utils'; /** * Media Toolbar Plugin * * @extends module:core/plugin~Plugin */ export default class MediaToolbar extends Plugin { /** * @inheritDoc */ static get requires() { return [WidgetToolbarRepository]; } /** * @inheritDoc */ static get pluginName() { return 'MediaToolbar'; } /** * @inheritDoc */ init() { const editor = this.editor; editor.config.define('media.toolbar', [ 'mediaStyle:left', 'mediaStyle:full', 'mediaStyle:right', '|', 'mediaTextAlternative', ]); } /** * @inheritDoc */ afterInit() { const editor = this.editor; const widgetToolbarRepository = editor.plugins.get(WidgetToolbarRepository); widgetToolbarRepository.register('media', { items: editor.config.get('media.toolbar') || [], getRelatedElement: getSelectedMediaWidget }); } }
javascript
15
0.584739
93
21.636364
55
starcoderdata
#ifndef SORT_FUN_H #define SORT_FUN_H #include #include #include #include #include /********************************/ /*Find the index during the sort*/ /********************************/ template<typename T> class CompareIndicesByAnotherVectorValues { const std::vector values; public: CompareIndicesByAnotherVectorValues(const std::vector val) : values(val) {} bool operator() (const size_t & a, const size_t & b) const { return (*values)[a] < (*values)[b]; } }; template <typename T> std::vector sort_indexes(const std::vector &v) { // initialize original index locations std::vector idx(v.size()); for (size_t i = 0; i != idx.size(); ++i) idx[i] = i; CompareIndicesByAnotherVectorValues idex_comp(&v); // sort indexes based on comparing values in v std::sort(idx.begin(), idx.end(), idex_comp); return idx; } #endif
c
10
0.611863
102
25.694444
36
starcoderdata
package functions.rf; import java.sql.SQLException; import java.util.Random; import functions.dmf.DMF; /** * @author * */ public class NRGResponse { public static void mainDemo() throws SQLException { DMF dmf = new DMF(); ResponseFunction rf = new ResponseFunction(dmf); dmf.setDeficit(randomCurrentDeficit(rf.totalDeviceUsage())); new DevicesTable(rf, dmf); } /** * Returns a random current deficit between 0 and the sum of every device's usage inclusive given the sum of * every device's usage. * * @param totalDevicesUsages the sum of every device's usage * @return a random current deficit */ private static int randomCurrentDeficit(int totalDevicesUsages) { Random random = new Random(); int currentDeficit = random.nextInt(totalDevicesUsages + 1); return currentDeficit; } }
java
12
0.71716
109
20.692308
39
starcoderdata
import boto3 import collections import datetime import base64 import os import json base64_region = os.environ['aws_regions'] aws_sns_arn = os.getenv('aws_sns_arn', None) def send_to_sns(subject, message): if aws_sns_arn is None: return print "Sending notification to: %s" % aws_sns_arn client = boto3.client('sns') response = client.publish( TargetArn=aws_sns_arn, Message=message, Subject=subject) if 'MessageId' in response: print "Notification sent with message id: %s" % response['MessageId'] else: print "Sending notification failed with response: %s" % str(response) def lambda_handler(event, context): decoded_regions = base64.b64decode(base64_region) regions = decoded_regions.split(',') print "Backing up instances in regions: %s" % regions for region in regions: ec = boto3.client('ec2', region_name=region) reservations = ec.describe_instances( Filters=[ {'Name': 'tag-key', 'Values': ['backup', 'Backup']}, ] ).get( 'Reservations', [] ) instances = sum( [ [i for i in r['Instances']] for r in reservations ], []) print "Found %d instances that need backing up in region %s" % (len(instances), region) to_tag_retention = collections.defaultdict(list) to_tag_mount_point = collections.defaultdict(list) for instance in instances: try: retention_days = [ int(t.get('Value')) for t in instance['Tags'] if t['Key'] == 'Retention'][0] except IndexError: retention_days = 7 for dev in instance['BlockDeviceMappings']: if dev.get('Ebs', None) is None: continue vol_id = dev['Ebs']['VolumeId'] dev_attachment = dev['DeviceName'] print "Found EBS volume %s on instance %s attached to %s" % ( vol_id, instance['InstanceId'], dev_attachment) snap = ec.create_snapshot( VolumeId=vol_id, Description=instance['InstanceId'], ) to_tag_retention[retention_days].append(snap['SnapshotId']) to_tag_mount_point[vol_id].append(snap['SnapshotId']) print "Retaining snapshot %s of volume %s from instance %s for %d days" % ( snap['SnapshotId'], vol_id, instance['InstanceId'], retention_days, ) ec.create_tags( Resources=to_tag_mount_point[vol_id], Tags=[ {'Key': 'Name', 'Value': dev_attachment}, ] ) for retention_days in to_tag_retention.keys(): delete_date = datetime.date.today() + datetime.timedelta(days=retention_days) delete_fmt = delete_date.strftime('%Y-%m-%d') print "Will delete %d snapshots on %s" % (len(to_tag_retention[retention_days]), delete_fmt) ec.create_tags( Resources=to_tag_retention[retention_days], Tags=[ {'Key': 'DeleteOn', 'Value': delete_fmt}, ] ) message = "{} instances have been backed up in region {}".format(len(instances), region) send_to_sns('EBS Backups', message)
python
18
0.527147
104
32.425926
108
starcoderdata
// Async "channel" using csp. const csp = require('js-csp'); var ch = csp.chan(); csp.takeAsync(ch, function (value) { return console.log('get value:', value); }); csp.putAsync(ch, 42);
javascript
6
0.652174
42
17.818182
11
starcoderdata
 /*********************************************************************************** ** exvr-exp ** ** MIT License ** ** Copyright (c) [2018] [ ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** ** of this software and associated documentation files (the "Software"), to deal ** ** in the Software without restriction, including without limitation the rights ** ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** ** copies of the Software, and to permit persons to whom the Software is ** ** furnished to do so, subject to the following conditions: ** ** ** ** The above copyright notice and this permission notice shall be included in all ** ** copies or substantial portions of the Software. ** ** ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ** ** SOFTWARE. ** ************************************************************************************/ // system using System; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; // unity using UnityEngine; namespace Ex{ class PythonStreamOutput : MemoryStream{ public override void Write(byte[] buffer, int offset, int count) { string txt = Encoding.UTF8.GetString(buffer, offset, count); if (txt.Length > 2) { //Global.Log().message("From python: " + txt); } } } class PythonStreamErrorOutput : MemoryStream{ public override void Write(byte[] buffer, int offset, int count) { string txt = Encoding.UTF8.GetString(buffer, offset, count); if (txt.Length > 2) { //Global.Log().error("From python: " + txt); } } } public class PythonManager : MonoBehaviour{ public enum PyUnity : int { Void = 0, Color = 1, Vector2 = 2, Vector3 = 3, Vector4 = 4, Rect = 5, Ray = 6, Quaternion = 7, Plane = 8, Texture2D = 9, Array1D = 10, Array2D = 11, List1D = 12, String = 13, Integer = 14, Single = 15, Boolean = 16 }; private Dictionary<Type, Func<object, object>> pyTo; private Dictionary<Type, Func<object, object[]>> pyFrom; public void marshall_from(Type type, ref object value) { if (pyTo.ContainsKey(type)) { value = pyTo[type](value); } } public object[] marshall_to(Type type, object value) { if (pyFrom.ContainsKey(type)) { return pyFrom[type](value); } if (pyFrom.ContainsKey(type.GetGenericTypeDefinition())) { return pyFrom[type](value); } return new object[2] { 0, null }; } public void initialize() { // from python to unity pyTo = new Dictionary<Type, Func<object, object>>(); // # vector 2 pyTo.Add(typeof(Vector2), value => { float[] array = (float[])value; return new Vector2(array[0], array[1]); }); // # vector 3 pyTo.Add(typeof(Vector3), value => { float[] array = (float[])value; return new Vector3(array[0], array[1], array[2]); }); // # vector 4 pyTo.Add(typeof(Vector4), value => { float[] array = (float[])value; return new Vector4(array[0], array[1], array[2], array[3]); }); // # quaternion pyTo.Add(typeof(Quaternion), value => { float[] array = (float[])value; return new Quaternion(array[0], array[1], array[2], array[3]); }); // # color pyTo.Add(typeof(Color), value => { float[] array = (float[])value; return new Color(array[1], array[1], array[2], array[3]); }); // # rect pyTo.Add(typeof(Rect), value => { float[] array = (float[])value; return new Rect(array[0], array[1], array[2], array[3]); }); // # ray2d pyTo.Add(typeof(Ray2D), value => { float[] array = (float[])value; return new Ray2D(new Vector2(array[0], array[1]), new Vector2(array[2], array[3])); }); // # plane pyTo.Add(typeof(Plane), value => { float[] array = (float[])value; return new Plane(new Vector3(array[0], array[1], array[2]), new Vector3(array[3], array[4], array[5])); }); // # texture2D pyTo.Add(typeof(Texture2D), value => { float[,] array2D = (float[,])value; Texture2D tex = new Texture2D(array2D.GetLength(0) / 3, array2D.GetLength(1)); for (int ii = 0; ii < array2D.GetLength(0) / 3; ++ii) { for (int jj = 0; jj < array2D.GetLength(1); ++jj) { tex.SetPixel(ii, jj, new Color(array2D[3 * ii, jj], array2D[3 * ii + 1, jj], array2D[3 * ii + 2, jj])); } } tex.Apply(); return tex; }); // from unity to python pyFrom = new Dictionary<Type, Func<object, object[]>>(); // # vector 2 pyFrom.Add(typeof(Vector2), value => { Vector2 v = (Vector2)value; return new object[2] { (int)PyUnity.Vector2, new float[2] { v.x, v.y } }; }); // # vector 3 pyFrom.Add(typeof(Vector3), value => { Vector3 v = (Vector3)value; return new object[2] { (int)PyUnity.Vector3, new float[3] { v.x, v.y, v.z } }; }); // # vector 4 pyFrom.Add(typeof(Vector4), value => { Vector4 v = (Vector4)value; return new object[2] { (int)PyUnity.Vector4, new float[4] { v.x, v.y, v.z, v.w } }; }); // # color pyFrom.Add(typeof(Color), value => { Color c = (Color)value; return new object[2] { (int)PyUnity.Color, new float[4] { c.r, c.g, c.b, c.a } }; }); // # rect pyFrom.Add(typeof(Rect), value => { Rect r = (Rect)value; return new object[2] { (int)PyUnity.Rect, new float[4] { r.x, r.y, r.width, r.height } }; }); // # list pyFrom.Add(typeof(List<>), value => { IList collection = (IList)value; if (collection.Count > 0) { Array arr = Array.CreateInstance(collection[0].GetType(), collection.Count); for (int jj = 0; jj < collection.Count; ++jj) { arr.SetValue(collection[jj], jj); } return new object[2] { (int)PyUnity.List1D, arr }; } return null; }); // # string pyFrom.Add(typeof(string), value => { return new object[2] { (int)PyUnity.String, value }; }); // # integer pyFrom.Add(typeof(int), value => { return new object[2] { (int)PyUnity.Integer, (int)value }; }); // # single pyFrom.Add(typeof(float), value => { return new object[2] { (int)PyUnity.Single, (float)value }; }); // # boolean pyFrom.Add(typeof(bool), value => { return new object[2] { (int)PyUnity.Boolean, (int)(((bool)value) ? 1 : 0) }; }); } } } //pDll = NativeMethods.LoadLibrary(ExVR.Paths().unityMainDir + "/python_export.dll"); //IntPtr pAddressOfFunctionToCall = NativeMethods.GetProcAddress(pDll, "initialize_python_interpreter"); //initInterpreter = (initialize_python_interpreter)Marshal.GetDelegateForFunctionPointer( // pAddressOfFunctionToCall, typeof(initialize_python_interpreter)); //pAddressOfFunctionToCall = NativeMethods.GetProcAddress(pDll, "clean_python_interpreter"); //cleanInterpreter = (clean_python_interpreter)Marshal.GetDelegateForFunctionPointer( // pAddressOfFunctionToCall, typeof(clean_python_interpreter)); //initInterpreter(); //[UnmanagedFunctionPointer(CallingConvention.Cdecl)] //private delegate void initialize_python_interpreter(); //[UnmanagedFunctionPointer(CallingConvention.Cdecl)] //private delegate void clean_python_interpreter(); //static class NativeMethods{ // [DllImport("kernel32.dll")] // public static extern IntPtr LoadLibrary(string dllToLoad); // [DllImport("kernel32.dll")] // public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName); // [DllImport("kernel32.dll")] // public static extern bool FreeLibrary(IntPtr hModule); //} //private initialize_python_interpreter initInterpreter; //private clean_python_interpreter cleanInterpreter; //private IntPtr pDll;
c#
29
0.51101
132
40.661157
242
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 koper.event.binding; import koper.demo.member.mapper.Member; import koper.event.DataEvent; import koper.event.DataListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.math.BigDecimal; /** * @author caie * @since 1.2 */ @Component @DataListener(dataObject = "koper.demo.member.mapper.impl.MemberMapperImpl") public class MemberListener { private Logger logger = LoggerFactory.getLogger(MemberListener.class); /** * test with Integer String type param */ public void onInsertMember(Integer id, String name, String phone) { logger.info("on insert Member successful, id : {}, name : {}, phone : {}", id, name, phone); } /** * test with pojo and Integer type param */ public void onCancelMember(Integer id, Member member) { logger.info("on cancel member successful, member info : {}, id : {}", member.toString(), id); } /** * test with DataEvent type param */ public void onDeleteMember(DataEvent dataEvent) { logger.info("on delete member successful, dataObjectName : {}, eventName : {}" + "args : {}", dataEvent.getDataObjectName(), dataEvent.getEventName(), dataEvent.getArgs()); } /** * test with Double Long BigDecimal type param */ public void onUpdateMember(Double id, Long name, BigDecimal account) { logger.info("on update member successful, id : {}, name : {}, account : {}", id, name, account); } /** * test with Float Short Byte Character type param */ public void onInsertWithFloatAndShortAndByteAndChar(Float fl, Short s, Byte b, Character c) { logger.info("on insert with Float and Short and Byte and char successful, float : {}, short : {}, byte : {}, char : {}", fl, s, b, c); } /** * test with Integer String DataEvent type param(DataEvent is the last parameter) */ public void onDeleteWithIntegerAndStringAndDataEvent(Integer id, String name, DataEvent dataEvent) { logger.info("on delete with id and name and DataEvent successful," + "id : {}, name : {}, DataEvent : {}", id, name, dataEvent.toString()); } }
java
10
0.662555
128
35.344828
87
starcoderdata
package cn.hub.jackeroo.system.controller; import cn.hub.jackeroo.constant.Constant; import cn.hub.jackeroo.persistence.BaseController; import cn.hub.jackeroo.system.entity.SysDict; import cn.hub.jackeroo.system.service.SysDictService; import cn.hub.jackeroo.utils.StringUtils; import cn.hub.jackeroo.utils.annotation.ApiModule; import cn.hub.jackeroo.utils.validator.annotation.ValidatedUnique; import cn.hub.jackeroo.utils.validator.groups.First; import cn.hub.jackeroo.utils.validator.groups.Insert; import cn.hub.jackeroo.utils.validator.groups.Second; import cn.hub.jackeroo.utils.validator.groups.Update; import cn.hub.jackeroo.vo.Id; import cn.hub.jackeroo.vo.IdList; import cn.hub.jackeroo.vo.PageParam; import cn.hub.jackeroo.vo.Result; import com.baomidou.mybatisplus.core.metadata.IPage; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.List; import java.util.Map; /** * * 数据字典 前端控制器 * * * @author jackeroo * @since 2020-10-10 */ @ApiModule(moduleName = "系统管理") @Api(tags = "数据字典") @RestController @RequestMapping("/system/dict") @RequiredArgsConstructor public class SysDictController extends BaseController { private final SysDictService service; /** * 数据字典列表 * @param entity * @param pageParam * @return */ @GetMapping("list") @ApiOperation("数据字典列表") @RequiresPermissions("system:dict:view") public Result list(SysDict entity, @Validated PageParam pageParam){ entity.setType(SysDict.TYPE_DICT); if(StringUtils.isEmpty(pageParam.getSortField())){ pageParam.setSortField("createTime"); pageParam.setSortOrder(Constant.SORT_DESC); } return ok(service.findPage(entity, pageParam)); } /** * 根据字典code获取字典详情 * @param dictCode * @return */ @GetMapping("getByDictCode") @ApiOperation("根据字典code获取字典详情") public Result getByDictCode(@RequestParam String dictCode){ return ok(service.getByDictCode(dictCode)); } /** * 字典项列表 * @param pageParam * @param dictCode * @return */ @GetMapping("itemList") @ApiOperation("字典项列表") @RequiresPermissions("system:dict:view") public Result itemList(@Validated PageParam pageParam, @RequestParam String dictCode){ SysDict sysDict = new SysDict(); sysDict.setType(SysDict.TYPE_DICT_ITEM); sysDict.setDictCode(dictCode); return ok(service.findPage(sysDict, pageParam)); } /** * 通过字典code获取所有字典项列表 * @param dictCode * @return */ @GetMapping("getDictItemList") @ApiOperation("通过字典code获取所有字典项列表") public Result getDictItemList(@RequestParam String dictCode){ return ok(service.findDictItemByDictCode(dictCode)); } /** * 通过多个code获取字典项列表 * @param dictCode * @return */ @GetMapping("getDictItemByCodes") @ApiOperation("通过多个code获取字典项列表") public Result<Map<String, List getDictItemByCodes(@RequestParam List dictCode){ Map<String, List result = new HashMap<>(); for (String code : dictCode) { result.put(code, service.findDictItemByDictCode(code)); } return ok(result); } /** * 获取当前最大排序号 * @return */ @GetMapping("getMaxSort") @ApiOperation("获取当前最大排序号") public Result getMaxSort(@RequestParam String dictCode){ return ok(service.getMaxSort(dictCode)); } /** * 获取数据字典详情 * @param id * @return */ @GetMapping("/{id}") @ApiOperation("获取数据字典详情") @RequiresPermissions("system:dict:view") public Result get(@PathVariable String id){ return ok(service.getById(id)); } /** * 保存数据字典 * @param entity * @return */ @PostMapping("save") @ApiOperation("保存数据字典") @ValidatedUnique(clazz = SysDict.class, condition = "type=0", groups = Second.class) @RequiresPermissions("system:dict:add") public Result save(@Validated({Insert.class, First.class}) @RequestBody SysDict entity){ service.saveDict(entity); return ok(); } /** * 保存数据字典项 * @param entity * @return */ @PostMapping("saveDictItem") @ApiOperation("保存数据字典项") @ValidatedUnique(clazz = SysDict.class, condition = "type=1 and dict_code = #{dictCode}", groups = First.class) @RequiresPermissions("system:dict:add") public Result saveDictItem(@Validated({Insert.class, Second.class}) @RequestBody SysDict entity){ service.saveDictItem(entity); return ok(); } /** * 更新数据字典 * @param entity * @return */ @PutMapping("update") @ApiOperation("更新数据字典") @ValidatedUnique(clazz = SysDict.class) @RequiresPermissions("system:dict:edit") public Result update(@Validated({Update.class, First.class}) @RequestBody SysDict entity){ service.updateDict(entity); return ok(); } /** * 更新数据字典项 * @param entity * @return */ @PutMapping("updateDictItem") @ApiOperation("更新数据字典项") @ValidatedUnique(clazz = SysDict.class) @RequiresPermissions("system:dict:edit") public Result updateDictItem(@Validated({Update.class, Second.class}) @RequestBody SysDict entity){ service.updateDictItem(entity); return ok(); } /** * 删除字典信息 * @param id * @return */ @DeleteMapping("deleteDict") @ApiOperation("删除字典信息") @RequiresPermissions("system:dict:delete") public Result deleteDict(@Validated @RequestBody Id id){ service.delete(id.getId()); return ok(); } /** * 批量删除 * @param ids * @return */ @DeleteMapping("deleteBatch") @ApiOperation(value = "批量删除") @RequiresPermissions("system:dict:delete") public Result deleteBatch(@Validated @RequestBody IdList ids){ service.delete(ids.getIds().toArray(new String[]{})); return ok(); } /** * 删除字典项信息 * @param id * @return */ @DeleteMapping("deleteDictItem") @ApiOperation("删除字典项信息") @RequiresPermissions("system:dict:delete") public Result deleteDictItem(@Validated @RequestBody Id id){ service.delete(id.getId()); return ok(); } }
java
8
0.677044
115
28.345679
243
starcoderdata
import React from 'react' import LocalizedLink from './localizedLink' import HeaderNav from './headerNav' import LangSwitcher from './langSwitcher' const Header = ({path, langtag}) => { return ( <header className="header"> <LocalizedLink to="/"> <img className="logo" src='https://res.cloudinary.com/danielmeilleurimg/image/upload/c_scale,w_400/v1565391864/echos/logo/Les_Echos_du_Pacifique_logo_color_1200x800-13.png' alt='logo' /> <HeaderNav langtag={langtag}/> {/* language switcher */} <span className="is-hidden-mobile"> <LangSwitcher path={path} langtag={langtag} /> ) } export default Header
javascript
10
0.643041
160
25.758621
29
starcoderdata
# Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the COPYING file. """ testing for qibuild open """ import StringIO import unittest import mock import qibuild.actions.open class OpenTestCase(unittest.TestCase): def setUp(self): self.ask_patcher = mock.patch('qisys.interact.ask_choice') self.ask_mock = self.ask_patcher.start() def test_no_ide_in_conf(self): empty_cfg = qibuild.config.QiBuildConfig() self.assertEqual(qibuild.actions.open.get_ide(empty_cfg), None) def test_qt_creator_in_conf(self): qibuild_cfg = qibuild.config.QiBuildConfig() qt_creator = qibuild.config.IDE() qt_creator.name = "QtCreator" qt_creator.path = "/path/to/qtsdk/bin/qtcreator" qibuild_cfg.add_ide(qt_creator) ide = qibuild.actions.open.get_ide(qibuild_cfg) self.assertEqual(ide.name, "QtCreator") self.assertEqual(ide.path, "/path/to/qtsdk/bin/qtcreator") self.assertFalse(self.ask_mock.called) def test_eclipse_cdt_in_conf(self): qibuild_cfg = qibuild.config.QiBuildConfig() eclipse = qibuild.config.IDE() eclipse.name = "Eclipse CDT" qibuild_cfg.add_ide(eclipse) try: qibuild.actions.open.get_ide(qibuild_cfg) except Exception, e: error = e self.assertFalse(error is None) self.assertFalse("Could not find any IDE in configuration" in error.message) self.assertTrue("`qibuild open` only supports" in error.message) def test_two_ides(self): qibuild_cfg = qibuild.config.QiBuildConfig() vs = qibuild.config.IDE() vs.name = "Visual Studio" qt_creator = qibuild.config.IDE() qt_creator.name = "QtCreator" qt_creator.path = r"C:\QtSDK\bin\QtCreator" qibuild_cfg.add_ide(qt_creator) qibuild_cfg.add_ide(vs) self.ask_mock.return_value = "QtCreator" ide = qibuild.actions.open.get_ide(qibuild_cfg) self.assertEqual(ide.name, "QtCreator") self.assertEqual(ide.path, r"C:\QtSDK\bin\QtCreator") call_args_list = self.ask_mock.call_args_list self.assertEqual(len(call_args_list), 1) (choices, _question) = call_args_list[0][0] self.assertEqual(choices, ['Visual Studio', 'QtCreator']) def test_two_ides_matching_default_conf(self): global_cfg = StringIO.StringIO(r""" <qibuild version="1"> <config name="win32-vs2010" ide="Visual Studio" /> <config name="mingw" ide="QtCreator" /> <ide name="Visual Studio" /> <ide name="QtCreator" path="C:\QtSDK\bin\QtCreator" /> """) qibuild_cfg = qibuild.config.QiBuildConfig() qibuild_cfg.read(global_cfg, create_if_missing=False) local_cfg = StringIO.StringIO(r""" <qibuild version="1"> <defaults config="mingw" /> """) qibuild_cfg.read_local_config(local_cfg) ide = qibuild.actions.open.get_ide(qibuild_cfg) self.assertEqual(ide.name, "QtCreator") self.assertEqual(ide.path, r"C:\QtSDK\bin\QtCreator") def test_two_ides_matching_user_conf(self): # A default config in local config file, # but user used -c qibuild_cfg = qibuild.config.QiBuildConfig() global_cfg = StringIO.StringIO(r""" <qibuild version="1"> <config name="win32-vs2010" ide="Visual Studio" /> <config name="mingw" ide="QtCreator" /> <ide name="Visual Studio" /> <ide name="QtCreator" path="C:\QtSDK\bin\QtCreator" /> """) qibuild_cfg.read(global_cfg, create_if_missing=False) qibuild_cfg.set_active_config("win32-vs2010") ide = qibuild.actions.open.get_ide(qibuild_cfg) self.assertEqual(ide.name, "Visual Studio") self.assertFalse(self.ask_mock.called) def tearDown(self): self.ask_patcher.stop() if __name__ == "__main__": unittest.main()
python
12
0.64188
72
34.27193
114
starcoderdata
module.exports = { targets: [ 'app/*.js', 'app/**/*.js', 'static/**/*.js', 'tests/unit/**/*.js', 'tests/integration/**/*.js', 'tests/system/**/*.js', '!app/node_modules/**', '!app/vendor/**' ] };
javascript
7
0.384328
36
21.333333
12
starcoderdata
#include <iostream> #include <math.h> using namespace std; int main(){ int x,l=1,p=3,maxv=0; cin>>x; int n=sqrt(x); int q=n*n; maxv=q; int b=n; while(b>1){ l=1; for(int j=1;j<=p;j++){ l*=b; } if(l<=x){ p++; if(l>maxv){ maxv=l; } } else{ b--; } } cout<<maxv; return 0; }
c++
11
0.487179
24
10.178571
28
codenet
# coding=utf-8 from django import forms from django.forms import inlineformset_factory from atm_analytics.companies.models import Company, Bank, CompanyAtmLocation, XFSFormat class ConfigForm(forms.ModelForm): class Meta: model = Company fields = ('logo', 'name', 'email', 'phone') class BankForm(forms.ModelForm): atms_number = forms.IntegerField(min_value=1) class Meta: model = Bank fields = ['name', 'atms_number'] BankFormSet = inlineformset_factory( Company, Bank, form=BankForm, extra=0, min_num=1, max_num=1, ) class CompanyAtmLocationForm(forms.ModelForm): class Meta: model = CompanyAtmLocation fields = ['address'] CompanyAtmLocationFormSet = inlineformset_factory( Company, CompanyAtmLocation, form=CompanyAtmLocationForm, extra=0, min_num=1, max_num=1, ) class XFSFormatForm(forms.ModelForm): class Meta: model = XFSFormat fields = ['hardware', 'software', 'xfs_sample_file', 'group_separator', 'row_separator', 'date_pattern', 'total_amount_pattern', 'currency_pattern', 'is_day_first']
python
9
0.655791
87
21.703704
54
starcoderdata
int hdnode_sign(HDNode *node, const uint8_t *msg, uint32_t msg_len, HasherType hasher_sign, uint8_t *sig, uint8_t *pby, int (*is_canonical)(uint8_t by, uint8_t sig[64])) { if (node->curve->params) { return ecdsa_sign(node->curve->params, hasher_sign, node->private_key, msg, msg_len, sig, pby, is_canonical); } else if (node->curve == &curve25519_info) { return 1; // signatures are not supported } else { hdnode_fill_public_key(node); if (node->curve == &ed25519_info) { ed25519_sign(msg, msg_len, node->private_key, node->public_key + 1, sig); } else if (node->curve == &ed25519_sha3_info) { ed25519_sign_sha3(msg, msg_len, node->private_key, node->public_key + 1, sig); } else if (node->curve == &ed25519_keccak_info) { ed25519_sign_keccak(msg, msg_len, node->private_key, node->public_key + 1, sig); } return 0; } }
c
19
0.6596
169
46.222222
18
inline
import numpy as np import scipy.stats as sp from scipy.stats import multivariate_normal from scipy.stats import mvn dim = 20 samples = 10**5 G = multivariate_normal.rvs(np.zeros(dim), np.eye(dim), size = samples) # Calcul de la probabilité G > a # G c'est une gaussienne centre reduite de dim = dim i.e. dim normales indep # Calcul de la prob qu'il existe une plus grand que a a = 6 ind_mc = np.any(G > a, axis = 1) p_emp_MC = np.mean(ind_mc) erreur_MC = 1.96*np.sqrt(p_emp_MC*(1-p_emp_MC)/samples) print("MC estimation") print(p_emp_MC) print("MC error") print(erreur_MC) print("MC intervalle de confiance") print([p_emp_MC - erreur_MC, p_emp_MC + erreur_MC]) print("Real value") real = 1 - sp.norm.cdf(a)**dim print(real) ## Par IS dec = 2 # meme decalage pour toutes #delta = dec * np.ones(dim) delta = np.zeros(dim) delta[0] = dec #delta = dec * np.linspace(0,1,dim) L = -np.dot(G, delta) - np.dot(delta.T, delta)/2 # likelyhood ech_IS = np.any(G + delta > a, axis = 1) * np.exp(L) p_emp_IS = np.mean(ech_IS) var_emp_IS = np.var(ech_IS) erreur_emp_IS = 1.96*np.sqrt(var_emp_IS - p_emp_IS**2)/np.sqrt(samples) print("IS estimation") print(p_emp_IS) print("IS error") print(erreur_emp_IS) print("IS intervalle de confiance") print([p_emp_IS - erreur_emp_IS, p_emp_IS + erreur_emp_IS]) low = -10 * np.ones(dim) upp = a * np.ones(dim) p,i = mvn.mvnun(low,upp,np.zeros(dim),np.eye(dim)) print(1-p)
python
10
0.669498
76
22.566667
60
starcoderdata
/* e_logf.c -- float version of e_log.c. * Conversion to float by Ian Lance Taylor, Cygnus Support, [email protected]. */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ //#include <sys/cdefs.h> //__FBSDID("$FreeBSD$"); #include "math_private.h" static const float ln2_hi = 6.9313812256e-01, /* 0x3f317180 */ ln2_lo = 9.0580006145e-06, /* 0x3717f7d1 */ two25 = 3.355443200e+07, /* 0x4c000000 */ /* |(log(1+s)-log(1-s))/s - Lg(s)| < 2**-34.24 (~[-4.95e-11, 4.97e-11]). */ Lg1 = 0xaaaaaa.0p-24, /* 0.66666662693 */ Lg2 = 0xccce13.0p-25, /* 0.40000972152 */ Lg3 = 0x91e9ee.0p-25, /* 0.28498786688 */ Lg4 = 0xf89e26.0p-26; /* 0.24279078841 */ static const float zero = 0.0; static volatile float vzero = 0.0; float __ieee754_logf(float x) { float hfsq,f,s,z,R,w,t1,t2,dk; int32_t k,ix,i,j; GET_FLOAT_WORD(ix,x); k=0; if (ix < 0x00800000) { /* x < 2**-126 */ if ((ix&0x7fffffff)==0) return -two25/vzero; /* log(+-0)=-inf */ if (ix<0) return (x-x)/zero; /* log(-#) = NaN */ k -= 25; x *= two25; /* subnormal number, scale up x */ GET_FLOAT_WORD(ix,x); } if (ix >= 0x7f800000) return x+x; k += (ix>>23)-127; ix &= 0x007fffff; i = (ix+(0x95f64<<3))&0x800000; SET_FLOAT_WORD(x,ix|(i^0x3f800000)); /* normalize x or x/2 */ k += (i>>23); f = x-(float)1.0; if((0x007fffff&(0x8000+ix))<0xc000) { /* -2**-9 <= f < 2**-9 */ if(f==zero) { if(k==0) { return zero; } else { dk=(float)k; return dk*ln2_hi+dk*ln2_lo; } } R = f*f*((float)0.5-(float)0.33333333333333333*f); if(k==0) return f-R; else {dk=(float)k; return dk*ln2_hi-((R-dk*ln2_lo)-f);} } s = f/((float)2.0+f); dk = (float)k; z = s*s; i = ix-(0x6147a<<3); w = z*z; j = (0x6b851<<3)-ix; t1= w*(Lg2+w*Lg4); t2= z*(Lg1+w*Lg3); i |= j; R = t2+t1; if(i>0) { hfsq=(float)0.5*f*f; if(k==0) return f-(hfsq-s*(hfsq+R)); else return dk*ln2_hi-((hfsq-(s*(hfsq+R)+dk*ln2_lo))-f); } else { if(k==0) return f-s*(f-R); else return dk*ln2_hi-((s*(f-R)-dk*ln2_lo)-f); } }
c++
18
0.532225
75
26.329545
88
research_code
package validation import ( "testing" "github.com/prometheus/common/model" "github.com/prometheus/prometheus/pkg/relabel" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gopkg.in/yaml.v2" ) func TestLimits_Validate(t *testing.T) { t.Parallel() tests := map[string]struct { limits Limits shardByAllLabels bool expected error }{ "max-global-series-per-user disabled and shard-by-all-labels=false": { limits: Limits{MaxGlobalSeriesPerUser: 0}, shardByAllLabels: false, expected: nil, }, "max-global-series-per-user enabled and shard-by-all-labels=false": { limits: Limits{MaxGlobalSeriesPerUser: 1000}, shardByAllLabels: false, expected: errMaxGlobalSeriesPerUserValidation, }, "max-global-series-per-user disabled and shard-by-all-labels=true": { limits: Limits{MaxGlobalSeriesPerUser: 1000}, shardByAllLabels: true, expected: nil, }, } for testName, testData := range tests { testData := testData t.Run(testName, func(t *testing.T) { assert.Equal(t, testData.expected, testData.limits.Validate(testData.shardByAllLabels)) }) } } func TestOverridesManager_GetOverrides(t *testing.T) { tenantLimits := map[string]*Limits{} defaults := Limits{ MaxLabelNamesPerSeries: 100, } ov, err := NewOverrides(defaults, func(userID string) *Limits { return tenantLimits[userID] }) require.NoError(t, err) require.Equal(t, 100, ov.MaxLabelNamesPerSeries("user1")) require.Equal(t, 0, ov.MaxLabelValueLength("user1")) // Update limits for tenant user1. We only update single field, the rest is copied from defaults. // (That is how limits work when loaded from YAML) l := Limits{} l = defaults l.MaxLabelValueLength = 150 tenantLimits["user1"] = &l // Checking whether overrides were enforced require.Equal(t, 100, ov.MaxLabelNamesPerSeries("user1")) require.Equal(t, 150, ov.MaxLabelValueLength("user1")) // Verifying user2 limits are not impacted by overrides require.Equal(t, 100, ov.MaxLabelNamesPerSeries("user2")) require.Equal(t, 0, ov.MaxLabelValueLength("user2")) } func TestLimitsLoadingFromYaml(t *testing.T) { SetDefaultLimitsForYAMLUnmarshalling(Limits{ MaxLabelNameLength: 100, }) inp := `ingestion_rate: 0.5` l := Limits{} err := yaml.UnmarshalStrict([]byte(inp), &l) require.NoError(t, err) assert.Equal(t, 0.5, l.IngestionRate, "from yaml") assert.Equal(t, 100, l.MaxLabelNameLength, "from defaults") } func TestMetricRelabelConfigLimitsLoadingFromYaml(t *testing.T) { SetDefaultLimitsForYAMLUnmarshalling(Limits{}) inp := ` metric_relabel_configs: - action: drop source_labels: [le] regex: .+ ` exp := relabel.DefaultRelabelConfig exp.Action = relabel.Drop regex, err := relabel.NewRegexp(".+") require.NoError(t, err) exp.Regex = regex exp.SourceLabels = model.LabelNames([]model.LabelName{"le"}) l := Limits{} err = yaml.UnmarshalStrict([]byte(inp), &l) require.NoError(t, err) assert.Equal(t, []*relabel.Config{&exp}, l.MetricRelabelConfigs) }
go
16
0.711288
98
26.112069
116
starcoderdata
package com.mall.shopping.dal.persistence; import com.mall.commons.tool.tkmapper.TkMapper; import com.mall.shopping.dal.entitys.ItemCat; public interface ItemCatMapper extends TkMapper { }
java
7
0.815166
58
25.5
8
starcoderdata
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; use App\Models\Project; use App\Models\History; use App\Models\Follow; class ProjectController extends Controller { public function saveProject(Request $request){ $project=new Project(); $project->price=$request->price; $project->title=$request->title; $project->description=$request->description; $project->department_id=$request->department_id; $project->type_id=$request->type_id; $project->user_id=$request->user_id; if($request->image!=""){ $project->image=$request->image; } if($request->pdf!=""){ $project->pdf=$request->pdf; } $project->save(); $project->status="OK"; return $project; } public function Projects(Request $request){ if ($request->state=="default") { //$follows=Follow::where("user_id",$request->user)->orWhere("follow_id",$request->user)->get(); $projects=Project::orderBy('created_at','desc')->paginate(10); return $projects; }else{ $projects=Project::where("department_id",$request->department)->where("type_id",$request->type)->orderBy('created_at','desc')->paginate(10); return $projects; } } public function show(Request $request){ $project=Project::find($request->id); if ($project) { $project->user; $project->status="OK"; return $project; }else{ $project=(object)[]; $project->status="ERROR"; return $project; } } public function edit(Request $request){ $project=Project::find($request->id); $project->title=$request->title; $project->description=$request->description; $project->save(); $project->status="OK"; return $project; } public function delete(Request $request){ $project=Project::find($request->id); if ($project->transactions->count()>0) { $project->status="ERROR"; return $project; } \Storage::disk('local')->delete('project/'.$project->project); $project->delete(); $project->status="OK"; return $project; } }
php
18
0.568513
148
30.181818
77
starcoderdata
using System; using System.IO; using System.Threading.Tasks; using Windows.Storage; using Windows.UI.Xaml.Controls; namespace ApplicationLifetimeSample.Utlitities { public class NavigationSuspensionManager { private const string NavigationStateFile = "NavigationState.txt"; public async Task SetNavigationStateAsync(string navigationState) { StorageFile file = await ApplicationData.Current.LocalCacheFolder.CreateFileAsync(NavigationStateFile, CreationCollisionOption.ReplaceExisting); Stream stream = await file.OpenStreamForWriteAsync(); using (var writer = new StreamWriter(stream)) { await writer.WriteLineAsync(navigationState); } } public async Task GetNavigationStateAsync() { Stream stream = await ApplicationData.Current.LocalCacheFolder.OpenStreamForReadAsync(NavigationStateFile); using (var reader = new StreamReader(stream)) { return await reader.ReadLineAsync(); } } } }
c#
16
0.664879
156
31.911765
34
starcoderdata
let tela = document.getElementById('tela') let ctx = tela.getContext('2d') let img = document.getElementById('red') ctx.drawImage(img, 20, 20)
javascript
3
0.762136
59
24.75
8
starcoderdata
<?php class Researches extends CI_Controller{ public function index(){ $data['title'] = 'List of Researches'; $data['colleges'] = $this->college_model->get_colleges(); $data['courses'] = $this->course_model->get_all_course(); $data['researches'] = $this->research_model->get_researches(); $data['colcount'] = $this->college_model->get_col_count(); $data['rescount'] = $this->research_model->get_res_count(); $data['visits'] = $this->page_model->pageviews(); $this->load->view('templates/header',$data); $this->load->view('researches/index',$data); $this->load->view('templates/footer',$data); /*Previous URL*/ $refering_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $this->session->set_userdata('url', $refering_url); } public function view($college_initials = NULL){ $data['research'] = $this->research_model->get_research_info($college_initials); $id = $data['research']['id']; $data['authors'] = $this->research_model->get_docu_authors($id); $data['images'] = $this->research_model->get_docu_images($id); $data['users'] = $this->user_model->get_users(); $data['colleges'] = $this->college_model->get_colleges(); $data['courses'] = $this->course_model->get_all_course(); if(empty($data['research'])){ show_404(); } $data['colcount'] = $this->college_model->get_col_count(); $data['rescount'] = $this->research_model->get_res_count(); $data['visits'] = $this->page_model->pageviews(); $this->load->view('templates/header',$data); $this->load->view('researches/view',$data); $this->load->view('templates/footer',$data); /*Previous URL*/ $refering_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $this->session->set_userdata('url', $refering_url); } public function create(){ if (!$this->session->userdata('logged_in')) { $this->session->set_flashdata('need_login','You need to login first.'); $url=$this->session->userdata('url'); redirect($url, 'refresh'); } $titleNoSpace = preg_replace('/\s+/','',$this->input->post('title'))."-".date("Y")."-".preg_replace('/\s+/','',$this->input->post('college')); $research_id = $this->research_model->create_research($titleNoSpace); foreach($this->input->post("authors") as $author){ if(!$author == ""){ $this->research_model->add_author($author,$research_id); } } $data = array(); $filesCount = count($_FILES['images']['name']); for($i = 0; $i < $filesCount; $i++){ $_FILES['file']['name'] = $_FILES['images']['name'][$i]; $_FILES['file']['type'] = $_FILES['images']['type'][$i]; $_FILES['file']['tmp_name'] = $_FILES['images']['tmp_name'][$i]; $_FILES['file']['error'] = $_FILES['images']['error'][$i]; $_FILES['file']['size'] = $_FILES['images']['size'][$i]; // File upload configuration $uploadPath = './assets/images/docu'; $config['upload_path'] = $uploadPath; $config['allowed_types'] = 'jpg|jpeg|png|gif'; // Load and initialize upload library $this->load->library('upload', $config); $this->upload->initialize($config); // Upload file to server if($this->upload->do_upload('file')){ // Uploaded file data $fileData = $this->upload->data(); $uploadData[$i]['file_name'] = $fileData['file_name']; $uploadData[$i]['uploaded_on'] = date("Y-m-d H:i:s"); $imageName = $fileData['file_name']; $this->research_model->add_image($imageName,$research_id); } } $this->college_model->update_research_total($collegeName = $this->input->post('college')); $title = "New research added"; $this->activity_model->add($title,$type="book"); $this->session->set_flashdata('research_created','Research successfully added.'); redirect('researches'); } public function addFile(){ if (!$this->session->userdata('logged_in')) { $this->session->set_flashdata('need_login','You need to login first.'); $url=$this->session->userdata('url'); redirect($url, 'refresh'); } $id = $this->input->post('researchId'); // Upload Image $config['upload_path'] = './assets/documents'; $config['allowed_types'] = 'pdf'; $this->load->library('upload', $config); if(!$this->upload->do_upload()){ $errors = array('error' => $this->upload->display_errors()); $this->session->set_flashdata('error_file_upload',"Invalid file."); $url=$this->session->userdata('url'); redirect($url, 'refresh'); } else { $data = array('upload_data' => $this->upload->data()); $file = str_replace(" ", "_", $_FILES['userfile']['name']); $this->research_model->add_file($id,$file); $this->session->set_flashdata('success_file_upload',"File: ".$file." successfully added"); $title = "Research updated"; $this->activity_model->add($title,$type="book"); $url=$this->session->userdata('url'); redirect($url, 'refresh'); } } public function update(){ if (!$this->session->userdata('logged_in')) { $this->session->set_flashdata('need_login','You need to login first.'); $url=$this->session->userdata('url'); redirect($url, 'refresh'); } $titleNoSpace = preg_replace('/\s+/','',$this->input->post('title'))."-".date("Y")."-".preg_replace('/\s+/','',$this->input->post('college')); $this->research_model->update_research($id = $this->input->post('researchId'),$titleNoSpace); $this->research_model->update_author($id = $this->input->post('researchId')); $this->session->set_flashdata('updated',"Research successfully updated"); $title = "Research updated"; $this->activity_model->add($title,$type="book"); redirect('researches/'.$titleNoSpace); } public function removeImage(){ if (!$this->session->userdata('logged_in')) { $this->session->set_flashdata('need_login','You need to login first.'); $url=$this->session->userdata('url'); redirect($url, 'refresh'); } $del = $this->research_model->remove_image($id = $this->input->post('imageId')); if(!$this->input->post('imageId') == ""){ $this->session->set_flashdata('image_deleted','Image successfully removed.'); } $url=$this->session->userdata('url'); redirect($url, 'refresh'); } public function addImage(){ if (!$this->session->userdata('logged_in')) { $this->session->set_flashdata('need_login','You need to login first.'); $url=$this->session->userdata('url'); redirect($url, 'refresh'); } $research_id = $this->input->post('researchId'); $flag = 0; $data = array(); $filesCount = count($_FILES['images']['name']); for($i = 0; $i < $filesCount; $i++){ $_FILES['file']['name'] = $_FILES['images']['name'][$i]; $_FILES['file']['type'] = $_FILES['images']['type'][$i]; $_FILES['file']['tmp_name'] = $_FILES['images']['tmp_name'][$i]; $_FILES['file']['error'] = $_FILES['images']['error'][$i]; $_FILES['file']['size'] = $_FILES['images']['size'][$i]; // File upload configuration $uploadPath = './assets/images/docu'; $config['upload_path'] = $uploadPath; $config['allowed_types'] = 'jpg|jpeg|png|gif'; // Load and initialize upload library $this->load->library('upload', $config); $this->upload->initialize($config); // Upload file to server if($this->upload->do_upload('file')){ // Uploaded file data $fileData = $this->upload->data(); $uploadData[$i]['file_name'] = $fileData['file_name']; $uploadData[$i]['uploaded_on'] = date("Y-m-d H:i:s"); $imageName = $fileData['file_name']; $this->research_model->add_image($imageName,$research_id); $flag = 1; } } if($flag == 1){ $this->session->set_flashdata('image_added','Image/s successfully added.'); } else{ $this->session->set_flashdata('no_image_added','No Image is added.'); } $url=$this->session->userdata('url'); redirect($url, 'refresh'); } }
php
18
0.467469
154
43.443478
230
starcoderdata
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateTestMysqlsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::connection('mysql')->create('test_mysqls', function (Blueprint $table) { $table->id(); $table->string('city'); $table->string('company'); $table->string('country'); $table->string('description'); $table->string('email'); $table->string('first_name'); $table->string('firstname'); $table->string('guid'); $table->string('last_name'); $table->string('lastname'); $table->decimal('lat'); $table->decimal( 'latitude'); $table->decimal('lng'); $table->decimal('longitude'); $table->string('name'); $table->string('password'); $table->string('phone'); $table->string('phone_number'); $table->string('postcode'); $table->string('postal_code'); $table->string('remember_token'); $table->string('slug'); $table->string('street'); $table->string('address1'); $table->string('address2'); $table->string('summary'); $table->string('url'); $table->string('user_name'); $table->string('username'); $table->string('uuid'); $table->string('zip'); $table->string('string'); $table->text('text'); $table->date('date'); $table->time('time'); $table->dateTimeTz('datetimetz'); $table->dateTime('datetime'); $table->integer('integer'); $table->bigInteger('bigint'); $table->smallInteger('smallint'); $table->decimal('decimal'); $table->float('float'); $table->boolean('boolean'); $table->enum('enum', ['one', 'two', 'three']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('test_mysqls'); } }
php
18
0.490323
88
30.418919
74
starcoderdata
package com.marshalchen.common.demoofui.pullscrollview; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; import com.marshalchen.common.demoofui.R; /** * Stretch ScrollView demo. * * @author markmjw * @date 2014-04-30 */ public class StretchViewActivity extends Activity { private TableLayout mMainLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.pull_scroll_view_act_stretch); mMainLayout = (TableLayout) findViewById(R.id.table_layout); showTable(); } public void showTable() { TableRow.LayoutParams layoutParams = new TableRow.LayoutParams( TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT); layoutParams.gravity = Gravity.CENTER; layoutParams.leftMargin = 30; layoutParams.bottomMargin = 10; layoutParams.topMargin = 10; for (int i = 0; i < 40; i++) { TableRow tableRow = new TableRow(this); TextView textView = new TextView(this); textView.setText("Test stretch scroll view " + i); textView.setTextSize(20); textView.setPadding(15, 15, 15, 15); tableRow.addView(textView, layoutParams); if (i % 2 != 0) { tableRow.setBackgroundColor(Color.LTGRAY); } else { tableRow.setBackgroundColor(Color.WHITE); } final int n = i; tableRow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(StretchViewActivity.this, "Click item " + n, Toast.LENGTH_SHORT).show(); } }); mMainLayout.addView(tableRow); } } }
java
20
0.631008
107
30.205882
68
starcoderdata
def _updateBlockTypeFromDB(self, reactor, blockList, dbTimeStep): """Updates blocks in reactor if database says its a different type of block""" dataList = self.readBlockParam("type", dbTimeStep) for blockTypeInDB, b in zip(dataList, blockList): oldBType = b.getType() if blockTypeInDB != oldBType: a = b.parent bolAssem = reactor.blueprints.assemblies.get(a.getType(), None) if not bolAssem: raise RuntimeError( "No BOL assem of type {0} exists in the input.".format( a.getType() ) ) newBlock = bolAssem.getFirstBlockByType(blockTypeInDB) if not newBlock: raise RuntimeError( "Could not find a {0} block in {1}. Not updating block type.".format( blockTypeInDB, a ) ) else: newBlock = copy.deepcopy(newBlock) runLog.extra( "Updating block {} with BOL block: {} because the block type " "changed from {} to {}".format( b, newBlock, oldBType, blockTypeInDB ) ) b.replaceBlockWithBlock(newBlock)
python
17
0.464138
93
44.34375
32
inline
public static boolean is_db_empty() throws ClassNotFoundException, SQLException { Connection connect = null; Statement statement = null; ResultSet resultSet = null; // Setup the connection with the DB connect = DriverManager .getConnection("jdbc:mysql://localhost:3306/" + "?useSSL=false","root", "admin"); statement = connect.createStatement(); String query = "CREATE DATABASE IF NOT EXISTS IOT_MGMT_SYSTEM;"; statement.executeUpdate(query); query = "CREATE TABLE IF NOT EXISTS IOT_MGMT_SYSTEM.USER (" + "username VARCHAR(8) UNIQUE, " + "password VARCHAR(8), " + "user_id VARCHAR(8) PRIMARY KEY" + ");"; statement.executeUpdate(query); query = "CREATE TABLE IF NOT EXISTS IOT_MGMT_SYSTEM.IOT_DEVICE (" + "id varchar(8) primary key, " + "name varchar (20), " + "status varchar(8), " + "user_id varchar(8) " + ");"; statement.executeUpdate(query); connect = DriverManager .getConnection("jdbc:mysql://localhost:3306/" + DB_NAME + "?useSSL=false","root", "admin"); statement = connect.createStatement(); SecureRandom random = new SecureRandom(); byte bytes[] = new byte[20]; random.nextBytes(bytes); query = "SELECT * FROM " + USER_TABLE; if((resultSet = statement.executeQuery(query)) != null) while(resultSet.next()) { return false; } if (resultSet != null) { resultSet.close(); } if (statement != null) { statement.close(); } if (connect != null) { connect.close(); } return true; }
java
11
0.641411
96
22.212121
66
inline
/** @file Defined the platform specific device path which will be used by platform Bbd to perform the platform policy connect. Copyright (c) 2004 - 2008, Intel Corporation. All rights reserved. This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #include "BdsPlatform.h" // // Predefined platform default time out value // UINT16 gPlatformBootTimeOutDefault = 5; ACPI_HID_DEVICE_PATH gPnpPs2KeyboardDeviceNode = gPnpPs2Keyboard; ACPI_HID_DEVICE_PATH gPnp16550ComPortDeviceNode = gPnp16550ComPort; UART_DEVICE_PATH gUartDeviceNode = gUart; VENDOR_DEVICE_PATH gTerminalTypeDeviceNode = gPcAnsiTerminal; // // Predefined platform root bridge // PLATFORM_ROOT_BRIDGE_DEVICE_PATH gPlatformRootBridge0 = { gPciRootBridge, gEndEntire }; EFI_DEVICE_PATH_PROTOCOL *gPlatformRootBridges[] = { (EFI_DEVICE_PATH_PROTOCOL *) &gPlatformRootBridge0, NULL }; // // Platform specific keyboard device path // // // Predefined platform default console device path // BDS_CONSOLE_CONNECT_ENTRY gPlatformConsole[] = { { NULL, 0 } }; // // Predefined platform specific driver option // EFI_DEVICE_PATH_PROTOCOL *gPlatformDriverOption[] = { NULL }; // // Predefined platform connect sequence // EFI_DEVICE_PATH_PROTOCOL *gPlatformConnectSequence[] = { NULL };
c
7
0.721132
84
26.0625
64
starcoderdata
'use strict'; var application = require('./../domain/application'); var getApplications = function (req, res) { application.getApplications( function (err, applications) { if (err) throw err; res.send(applications); }); }; var addApplication = function (req, res) { application.addApplication(req.body.name, req, function (err) { if (err) throw err; res.send(201); }); }; var getApplicationMetaData = function (req, res) { var applicationName = req.params.applicationName; application.getApplicationMetaData(applicationName, function (err, metaData) { if (err) throw err; res.send(metaData); }); }; var saveApplicationMetaData = function (req, res) { var applicationName = req.params.applicationName; var metaDataKey = req.params.metaDataKey; var metaDataValue = req.body.value; application.saveApplicationMetaData(applicationName, metaDataKey, metaDataValue, function (err) { if (err) throw err; res.send(200); }); }; module.exports.registerRoutes = function (app, authenticate) { app.get('/api/applications', getApplications); app.put('/api/applications', authenticate, addApplication); app.get('/api/applications/:applicationName/_meta', getApplicationMetaData); app.put('/api/applications/:applicationName/_meta/:metaDataKey', saveApplicationMetaData); };
javascript
13
0.636129
94
31
47
starcoderdata
import users from '../users'; import { Event } from '../../actions/ActionTypes'; describe('reducers', () => { describe('users', () => { const baseState = { actionGrant: [], pagination: {}, items: [3], byId: { 3: { id: 3, }, }, }; it('Event.SOCKET_EVENT_UPDATED', () => { const prevState = baseState; const action = { type: Event.SOCKET_EVENT_UPDATED, payload: { id: 1, pools: [ { registrations: [ { id: 31, user: { id: 49, }, }, ], }, ], waitingRegistrations: [ { id: 33, user: { id: 50, pic: '123', }, }, ], }, }; expect(users(prevState, action)).toEqual({ actionGrant: [], pagination: {}, items: [3, 49, 50], byId: { 3: { id: 3, }, 49: { id: 49, }, 50: { id: 50, pic: '123', }, }, }); }); it('Event.SOCKET_REGISTRATION.SUCCESS and ADMIN_REGISTER.SUCCESS', () => { const prevState = baseState; const action = { type: Event.SOCKET_REGISTRATION.SUCCESS, payload: { id: 31, user: { id: 49, }, }, }; expect(users(prevState, action)).toEqual({ actionGrant: [], pagination: {}, items: [3, 49], byId: { 3: { id: 3, }, 49: { id: 49, }, }, }); }); }); });
javascript
30
0.327184
78
19.252747
91
starcoderdata
#include "config.h" #include "main.h" #include "cfg_file.h" #include "expressions.h" #include "tests.h" /* Vector of test expressions */ char *test_expressions[] = { "(A&B|!C)&!(D|E)", "/test&!/&!/\\/|/", "header_exists(f(b(aaa)))|header=/bbb/", "!(header_exists(X-Mailer, /aaa,/) | header_exists(User-Agent)) & Received=/cp-out\\d+\\.libero\\.it/H & Message-Id=/<[\\da-f]{12}\\.[\\da-f]{16}@/H", NULL }; void rspamd_expression_test_func () { rspamd_mempool_t *pool; struct expression *cur; struct expression_argument *arg; char **line, *outstr; int r, s; GList *cur_arg; pool = rspamd_mempool_new (1024); line = test_expressions; while (*line) { r = 0; cur = parse_expression (pool, *line); s = strlen (*line) * 4; outstr = rspamd_mempool_alloc (pool, s); while (cur) { if (cur->type == EXPR_REGEXP) { r += rspamd_snprintf (outstr + r, s - r, "OP:%s ", (char *)cur->content.operand); } else if (cur->type == EXPR_STR) { r += rspamd_snprintf (outstr + r, s - r, "S:%s ", (char *)cur->content.operand); } else if (cur->type == EXPR_FUNCTION) { r += rspamd_snprintf (outstr + r, s - r, "F:%s ", ((struct expression_function *)cur->content.operand)->name); cur_arg = ((struct expression_function *)cur->content.operand)->args; while (cur_arg) { arg = cur_arg->data; if (arg->type == EXPRESSION_ARGUMENT_NORMAL) { r += rspamd_snprintf (outstr + r, s - r, "A:%s ", (char *)arg->data); } else { r += rspamd_snprintf (outstr + r, s - r, "AF:%p ", arg->data); } cur_arg = g_list_next (cur_arg); } } else { r += rspamd_snprintf (outstr + r, s - r, "O:%c ", cur->content.operation); } cur = cur->next; } msg_debug ("Parsed expression: '%s' -> '%s'", *line, outstr); line ++; } rspamd_mempool_delete (pool); }
c
24
0.571819
151
27.609375
64
starcoderdata
import React from 'react' const SearchInput = ({ onChange }) => ( <div className="search-input"> <input type="text" name="search" placeholder="Search" onChange={event => onChange(event.currentTarget.value)} /> ); export default SearchInput;
javascript
14
0.689922
116
27.666667
9
starcoderdata
func (r RepoNotifications) Render() []*html.Node { // TODO: Make this much nicer. /* <div class="RepoNotifications list-entry list-entry-border mark-as-read"> <div class="list-entry-header"> <span class="content"><a class="black gray-when-read" href="https://{{.Repo.URI}}"><strong>{{.Repo.URI}}</strong></a></span> </div> {{range .Notifications}} {{render .}} {{end}} </div> */ var ns []*html.Node ns = append(ns, htmlg.DivClass("list-entry-header", htmlg.SpanClass("content", &html.Node{ Type: html.ElementNode, Data: atom.A.String(), Attr: []html.Attribute{ {Key: atom.Class.String(), Val: "black gray-when-read"}, {Key: atom.Href.String(), Val: "https://" + r.Repo.URI}, }, FirstChild: &html.Node{ Type: html.ElementNode, Data: atom.Strong.String(), FirstChild: htmlg.Text(r.Repo.URI), }, }, ), )) anyUnread := false for _, notification := range r.Notifications { if !notification.Read { anyUnread = true } ns = append(ns, notification.Render()...) } divClass := "RepoNotifications list-entry list-entry-border mark-as-read" if !anyUnread { divClass += " read" } div := htmlg.DivClass(divClass, ns...) return []*html.Node{div} }
go
25
0.624695
128
28.333333
42
inline
/* * Copyright: Copyright 2018 (c) Parametric Technology GmbH * Product: PTC Integrity Lifecycle Manager * Author: Principal Consultant ALM * Purpose: Custom Developed Code * ************** File Version Details ************** * Revision: $Revision: 1.3 $ * Last changed: $Date: 2018/05/18 02:18:19CET $ */ package com.ptc.services.utilities.docgen.utils; import com.mks.api.util.MKSLogger; import static java.lang.System.out; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import java.util.TimeZone; import java.util.logging.Level; /** * * @author veckardt */ public class Logger { private static final String tmpDir = System.getProperty("java.io.tmpdir"); private static MKSLogger logger; public static String LOGFILE = tmpDir + "IntegrityDocs_" + getDate() + ".log"; public final static void init() { logger = new MKSLogger(LOGFILE); // IntegrityDocs.log("APISession"); logger.configure(getLoggerProperties()); } public final static void log(String text) { out.println(text); logger.message(text); } public final static void log(String text, int level) { out.println(text); logger.message(text); } public final static void print(String text) { out.print(text); logger.message(text); } // public final static void log(String text, int level, Exception e) { // log(text); // log(e.getMessage()); // } public final static void exception(Level level, int priority, Exception e) { e.printStackTrace(); log(e.getMessage()); logger.exception(level.toString(), priority, e); } public final static String getDate() { DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); df.setTimeZone(TimeZone.getTimeZone("CET")); return df.format(new Date()); } public final static Properties getLoggerProperties() { // Initialize logger properties Properties loggerProps = new Properties(); // Logging Categories loggerProps.put("mksis.logger.message.includeCategory.DEBUG", "10"); loggerProps.put("mksis.logger.message.includeCategory.WARNING", "10"); loggerProps.put("mksis.logger.message.includeCategory.GENERAL", "10"); loggerProps.put("mksis.logger.message.includeCategory.ERROR", "10"); // Output Format loggerProps.put("mksis.logger.message.defaultFormat", "{2}({3}): {4}"); loggerProps.put("mksis.logger.message.format.DEBUG", "{2}({3}): {4}"); loggerProps.put("mksis.logger.message.format.WARNING", "* * * * {2} * * * * ({3}): {4}"); loggerProps.put("mksis.logger.message.format.ERROR", "* * * * {2} * * * * ({3}): {4}"); return loggerProps; } public static String getLogFile() { return LOGFILE; } }
java
11
0.628842
97
31.9
90
starcoderdata
package com.didichuxing.doraemonkit.kit.blockmonitor; import android.content.Context; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.didichuxing.doraemonkit.R; import com.didichuxing.doraemonkit.kit.blockmonitor.bean.BlockInfo; import com.didichuxing.doraemonkit.ui.widget.recyclerview.AbsRecyclerAdapter; import com.didichuxing.doraemonkit.ui.widget.recyclerview.AbsViewBinder; import static android.text.format.DateUtils.FORMAT_SHOW_DATE; import static android.text.format.DateUtils.FORMAT_SHOW_TIME; public class BlockListAdapter extends AbsRecyclerAdapter BlockInfo> { private OnItemClickListener mListener; public BlockListAdapter(Context context) { super(context); } @Override protected AbsViewBinder createViewHolder(View view, int viewType) { return new ItemViewHolder(view); } @Override protected View createView(LayoutInflater inflater, ViewGroup parent, int viewType) { return inflater.inflate(R.layout.dk_item_block_list, parent, false); } private class ItemViewHolder extends AbsViewBinder { private TextView tvTime; private TextView tvTitle; public ItemViewHolder(View view) { super(view); } @Override protected void getViews() { tvTime = getView(R.id.time); tvTitle = getView(R.id.title); } @Override public void bind(BlockInfo blockInfoEx) { } @Override public void bind(final BlockInfo info, int position) { String index; index = (BlockListAdapter.this.getItemCount() - position) + ". "; String title = index + info.concernStackString + " " + getContext().getString(R.string.dk_block_class_has_blocked, String.valueOf(info.timeCost)); tvTitle.setText(title); String time = DateUtils.formatDateTime(getContext(), info.time, FORMAT_SHOW_TIME | FORMAT_SHOW_DATE); tvTime.setText(time); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mListener != null) { mListener.onClick(info); } } }); } } public void setOnItemClickListener(OnItemClickListener listener) { mListener = listener; } public interface OnItemClickListener { void onClick(BlockInfo info); } }
java
17
0.656433
111
31.188235
85
starcoderdata
def initial_correction(subcnt): # the start point genotype of a chromosome should be double check and is correct, so that start from a correct start # the first 10 rows are picked start_index = subcnt.index.min() end_index = start_index + 10 checkcnt = subcnt[subcnt.index.isin(range(start_index, end_index))] checktype = sorted(set(checkcnt.genotype)) if len(checktype) == 1: t1 = checktype[0] return (t1, []) else: check_dict = {c:list(checkcnt.genotype).count(c) for c in checktype} ## to get the correct start genotype c0 = check_dict[checktype[0]] for c in checktype: if check_dict[c] > c0: c0 = check_dict[c] t1 = [g for g in check_dict if check_dict[g] == c0][0] drop_list = checkcnt[checkcnt["genotype"] != t1].index.tolist() return (t1, drop_list)
python
15
0.614865
120
43.45
20
inline
using System; using System.Linq; using System.Text; namespace Betting.Entity.Sqlite { internal static class GuidHelper { public static Guid ToGuid(this string input) { string text = input.TrimEnd(); if (text.Length <= 16) { text += new string(Enumerable.Range(0, 16 - text.Length).Select(_ => ' ').ToArray()); byte[] hash = Encoding.Default.GetBytes(text); return new Guid(hash); } return new Guid(text); } public static Guid ToGuid(this long input) { byte[] bytes = new byte[16]; BitConverter.GetBytes(input).CopyTo(bytes, 0); return new Guid(bytes); } public static Guid ToGuid(this int input) { byte[] bytes = new byte[16]; BitConverter.GetBytes(input).CopyTo(bytes, 0); return new Guid(bytes); } public static string ToString(this Guid input) { byte[] buffer = input.ToByteArray(); return Encoding.UTF8.GetString(buffer, 0, buffer.Length - Trim()); int Trim() { return buffer .Reverse() .Aggregate((0, true), (a, b) => a.Item2 && b == 32 ? (a.Item1 + 1, true) : (a.Item1, false)).Item1; } } public static long ToLong(this Guid input) { byte[] buffer = input.ToByteArray(); long l = BitConverter.ToInt64(buffer, 0); return l; } public static int ToInt(this Guid input) { byte[] buffer = input.ToByteArray(); int i = BitConverter.ToInt32(buffer, 0); return i; } public static Guid ToGuid(this DateTime date) { var bytes = BitConverter.GetBytes(date.Ticks); Array.Resize(ref bytes, 16); return new Guid(bytes); } public static DateTime ToDateTime(this Guid guid) { var dateBytes = guid.ToByteArray(); Array.Resize(ref dateBytes, 8); return new DateTime(BitConverter.ToInt64(dateBytes, 0)); } /// /// https://stackoverflow.com/questions/1383030/how-to-combine-two-guid-values /// public static Guid Merge(this Guid guidA, params Guid[] guidBs) { var aba = guidA.ToByteArray(); var cba = new byte[aba.Length]; Array.Copy(aba, cba, aba.Length); foreach (var byteArray in guidBs.Select(a=>a.ToByteArray())) { cba = MergeTwo(byteArray, cba); } return new Guid(cba); } /// /// https://stackoverflow.com/questions/1383030/how-to-combine-two-guid-values /// public static byte[] MergeTwo(byte[] aba, byte[] bba) { var cba = new byte[aba.Length]; for (var ix = 0; ix < cba.Length; ix++) { cba[ix] = (byte)(aba[ix] ^ bba[ix]); } return cba; } /// /// https://stackoverflow.com/questions/1383030/how-to-combine-two-guid-values /// public static Guid MergeTwo(Guid guidA, Guid guidB) { var aba = guidA.ToByteArray(); var bba = guidB.ToByteArray(); var cba = new byte[aba.Length]; for (var ix = 0; ix < cba.Length; ix++) { cba[ix] = (byte)(aba[ix] ^ bba[ix]); } return new Guid(cba); } } }
c#
23
0.501326
119
27.575758
132
starcoderdata
using System; using System.Globalization; namespace Exemp2 { class Program { static void Main(string[] args) { var p = new Produto("TV", 500.00, 10); p.Nome = "TV 4K"; Console.WriteLine(p.Nome + " e " + p.Preco + " e " + p.Quantidade); } } }
c#
16
0.5
79
21.571429
14
starcoderdata
import { SET_WINDOW_WIDTH, FADOUT_SECTION } from '../../actions/index'; const INITIAL_STATE = { windowWidth: 0, hideSection: false, section: '' }; export default function(state = INITIAL_STATE, action) { switch(action.type) { case SET_WINDOW_WIDTH: return { ...state, windowWidth: action.payload }; case FADOUT_SECTION: return { ...state, hideSection: true, section: action.payload }; default: return state; } }
javascript
11
0.694118
87
25.625
16
starcoderdata
function CatBaseListController($scope, $state, $controller, $log, catBreadcrumbsService, catListDataLoadingService, config) { if (!_.isUndefined(config.listData)) { this.titleKey = 'cc.catalysts.cat-breadcrumbs.entry.' + config.listData.endpoint.getEndpointName(); catBreadcrumbsService.set([ { title: config.title, key: this.titleKey } ]); $scope.listData = config.listData; } else { $log.warn('No listData available!'); } this.title = config.title; this.searchProps = config.searchProps; this.config = config; this.getUrlForId = function (id) { $log.warn('use ui-sref directly - this method will be removed in the near future'); return $state.href('^.detail', {id: id}); }; this.getUrlForNewPage = function () { return this.getUrlForId('new'); }; this.remove = function (id) { config.listData.endpoint.remove(id) .then(function () { catListDataLoadingService.load(config.listData.endpoint, config.listData.searchRequest).then( function (data) { _.assign($scope.listData, data); } ); }); }; try { // extend with custom controller $controller(config.controller, {$scope: $scope, listData: config.listData, config: config}); } catch (unused) { $log.info('Couldn\'t instantiate controller with name ' + config.controller); } }
javascript
21
0.577095
125
32.276596
47
inline
""" Load a Lobe saved model """ from __future__ import annotations import os import json from PIL import Image from typing import Tuple from ._results import PredictionResult from ._model import Model from . import Signature from . import image_utils def load_from_signature(signature: Signature) -> ImageModel: # Select the appropriate backend model_format = signature.format if model_format == "tf": from .backends import _backend_tf as backend elif model_format == "tf_lite": from .backends import _backend_tflite as backend else: raise ValueError("Model is an unsupported format") backend_predict = backend.ImageClassificationModel(signature) return ImageModel(signature, backend_predict) def load(model_path: str) -> ImageModel: # Load the signature signature = Signature.load(model_path) return load_from_signature(signature) class ImageModel(Model): def __init__(self, signature, backend): super(ImageModel, self).__init__(signature) self.__backend = backend def predict_from_url(self, url: str): return self.predict(image_utils.get_image_from_url(url)) def predict_from_file(self, path: str): return self.predict(image_utils.get_image_from_file(path)) def predict(self, image: Image.Image): image_processed = image_utils.preprocess_image(image, self.signature.input_image_size) return self.__backend.predict(image_processed)
python
11
0.704005
94
30.361702
47
starcoderdata
package elasticsearch import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" logging "github.com/openshift/cluster-logging-operator/apis/logging/v1" "github.com/openshift/cluster-logging-operator/test/framework/functional" testfw "github.com/openshift/cluster-logging-operator/test/functional" "github.com/openshift/cluster-logging-operator/test/helpers/types" "github.com/openshift/cluster-logging-operator/test/matchers" ) var _ = Describe("[Functional][Outputs][ElasticSearch] FluentdForward Output to ElasticSearch", func() { var ( framework *functional.CollectorFunctionalFramework // Template expected as output Log outputLogTemplate = functional.NewApplicationLogTemplate() ) BeforeEach(func() { outputLogTemplate.ViaqIndexName = "app-write" framework = functional.NewCollectorFunctionalFrameworkUsingCollector(testfw.LogCollectionType) functional.NewClusterLogForwarderBuilder(framework.Forwarder). FromInput(logging.InputNameApplication). ToElasticSearchOutput() Expect(framework.Deploy()).To(BeNil()) Expect(framework.WritesApplicationLogs(1)).To(BeNil()) }) AfterEach(func() { framework.Cleanup() }) Context("when sending to ElasticSearch "+functional.ElasticSearchTag+" protocol", func() { It("should be compatible", func() { raw, err := framework.GetLogsFromElasticSearch(logging.OutputTypeElasticsearch, logging.InputNameApplication) Expect(err).To(BeNil(), "Expected no errors reading the logs") Expect(raw).To(Not(BeEmpty())) // Parse log line var logs []types.ApplicationLog err = types.StrictlyParseLogs(raw, &logs) Expect(err).To(BeNil(), "Expected no errors parsing the logs") // Compare to expected template outputTestLog := logs[0] outputLogTemplate.ViaqIndexName = "" Expect(outputTestLog).To(matchers.FitLogFormatTemplate(outputLogTemplate)) }) }) })
go
25
0.76647
112
35.607843
51
starcoderdata
protected virtual SectionAnalysisResult FindPureMomentResult(FlexuralCompressionFiberPosition CompressionFiberPosition, TCIterationBound bound, double StrainConvergenceTolerance = 0.00001) { currentCompressionFiberPosition = CompressionFiberPosition; //store this off because it will be necessary during iteration StrainHeight = GetStrainDistributionHeight(CompressionFiberPosition);//store this off because it will be necessary during iteration double SteelStrain = 0; double StrainMax = bound.MaxStrain; double StrainMin = bound.MinStrain; double targetTCDelta = 0; LinearStrainDistribution finalStrainDistribution = null; //SteelStrain = RootFinding.Brent(new FunctionOfOneVariable(GetTandCDeltaForSteelStrainIteration), TCDeltaMin, TCDeltaMax, StrainConvergenceTolerance, targetTCDelta); SteelStrain = RootFinding.Brent(new FunctionOfOneVariable(DeltaTCCalculationFunction), StrainMin, StrainMax, StrainConvergenceTolerance, targetTCDelta); switch (CompressionFiberPosition) { case FlexuralCompressionFiberPosition.Top: finalStrainDistribution = new LinearStrainDistribution(StrainHeight, this.MaxConcreteStrain, SteelStrain); break; case FlexuralCompressionFiberPosition.Bottom: finalStrainDistribution = new LinearStrainDistribution(StrainHeight, SteelStrain, this.MaxConcreteStrain); break; default: throw new CompressionFiberPositionException(); } SectionAnalysisResult finalResult = GetSectionResult(finalStrainDistribution, CompressionFiberPosition); return finalResult; }
c#
14
0.690617
178
52.314286
35
inline
export default { failed: 'Aktion fehlgeschlagen', success: 'Aktion erfolgreich', 'About Us': 'Über uns', 'Apply': 'Bewerben', 'Cancel': 'Abbrechen', 'CV': 'Lebenslauf', 'Contact': 'Kontakt', 'Digital Change': 'Digitaler Wandel', 'Imprint': 'Impressum', 'Login': 'Anmelden', 'Username': 'Benutzername', 'Password': ' 'Post a Job': 'Job eingeben', 'Privacy': 'Datenschutz', 'Search Jobs': 'Jobs suchen', 'Settings': 'Einstellungen', 'Choose Photo': 'Foto wählen', 'fulltime': 'Vollzeit', 'parttime': 'Teilzeit', 'minijob': 'Minijob', 'Job Type': 'Art der Anstellung', 'Select': 'auswählen', 'select file': '{what} {do}', // Logo auswählen 'Drag&Drop': 'Drag & Drop', 'Photo': 'Foto', 'Logo': 'Logo', 'Header Image': 'Headerbild', 'Workload': 'Pensum', 'permanent': 'Festanstellung', 'contract': 'Freie Mitarbeit', 'internship': 'Praktikum', 'apprenticeship': 'Ausbildung', 'Create Job': 'Anzeige erstellen', 'General Data': 'Grunddaten', 'Back': 'Zurück', 'Next': 'Weiter', 'Submit': 'Absenden', 'Clear': 'Löschen', 'Categories': 'Kategorien', 'Work Experience': 'Berufserfahrung', 'Education': 'Ausbildung', 'Desired Work': 'Gewünschte Tätigkeit', 'Start': 'Beginn', 'End': 'Ende', 'Ongoing': 'Bis heute', 'Products': 'Produkte', 'Company/Organization': 'Firma/Organization', 'to': 'bis', 'All my life': 'Mein ganzes Leben', 'Language Skills': 'Sprachkenntnisse', 'Native language': 'Muttersprache', 'Foreign languages': 'Fremdsprachen', 'German': 'Deutsch', 'French': 'Französisch', 'English': 'Englisch', 'Salary expectations': 'Gehaltsvorstellung', 'Currency': 'Währung', 'Period': 'Zeitraum', 'Video Conferencing': 'Videokonferenzen', 'Indivitual Application Forms': 'Individuelle Bewerbungsformulare' }
javascript
6
0.644955
68
28.730159
63
starcoderdata
import React, { useEffect, useCallback } from "react"; import { useSelector, useDispatch } from "react-redux"; import { Helmet } from "react-helmet"; import { Grid, Page } from "tabler-react"; import { isNil } from "ramda"; import { FormattedMessage, useIntl } from "react-intl"; import siteMetaData from "../constants/metadata"; import ChallengeList from "../components/challenges/ChallengeList"; import { fetchChallenges as fetchChallengesAction } from "../actions/seasons"; import usePrevious from "../hooks/usePrevious"; const ChallengesPage = () => { const intl = useIntl(); const dispatch = useDispatch(); const activeChallenges = useSelector(state => state.seasons.activeChallenges); const activeSeason = useSelector(state => state.seasons.activeSeason); const fetchChallenges = useCallback( seasonID => dispatch(fetchChallengesAction(seasonID)), [dispatch] ); const prevProps = usePrevious({ activeSeason }); const { title, description } = siteMetaData; useEffect(() => { const { activeSeason: prevActiveSeason } = prevProps || {}; if ( (isNil(prevActiveSeason) && activeSeason) || (prevActiveSeason && prevActiveSeason.id === activeSeason.id) ) { if (isNil(activeChallenges)) { fetchChallenges(activeSeason.id); } } }, [activeChallenges, activeSeason, fetchChallenges, prevProps]); const challengesIntl = intl.formatMessage({ id: "nav.challenges" }); return ( <> {title} - {challengesIntl} <meta name="description" content={description} /> <Page.Content title={challengesIntl}> <Grid.Col lg={5}> <h1 css={{ fontSize: "2rem" }}> <FormattedMessage id="ChallengesPage.title" /> <p css={{ marginBottom: "3rem" }}> <FormattedMessage id="ChallengesPage.description" /> <ChallengeList challenges={activeChallenges} /> ); }; export default ChallengesPage;
javascript
15
0.636872
80
30.588235
68
starcoderdata
package hello; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.http.MimeTypes; import org.eclipse.jetty.http.PreEncodedHttpField; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.util.BufferUtil; public class PlainTextHandler extends AbstractHandler { ByteBuffer helloWorld = BufferUtil.toBuffer("Hello, World!"); HttpField contentType = new PreEncodedHttpField(HttpHeader.CONTENT_TYPE,MimeTypes.Type.TEXT_PLAIN.asString()); @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); baseRequest.getResponse().getHttpFields().add(contentType); baseRequest.getResponse().getHttpOutput().sendContent(helloWorld.slice()); } }
java
10
0.806028
153
39.4375
32
starcoderdata
var nativePort = chrome.runtime.connectNative("edu.mit.scratch.device"); var callNumber = 0; var portID = {}; var pendingCallbacks = {}; // map: native callback token -> [client port, client callback token] var deviceOwnership = {}; // map: path -> client port // Handle a message coming from the NMH function handleNativeMessage(message) { var port = undefined; if (message[0] == "@") { var nativeCallbackNumber = message[1]; var callbackTuple = pendingCallbacks[nativeCallbackNumber]; delete pendingCallbacks[nativeCallbackNumber]; if (callbackTuple) { port = callbackTuple[0]; message[1] = callbackTuple[1]; // replace native callback token with client callback token } } else { // All non-callback client-facing calls must include a device path as the second argument var devicePath = message[1]; port = deviceOwnership[devicePath]; } if (port) port.postMessage(message); else console.log("SDH-Background: Could not determine client port for native message: " + message); } // Handle a connection coming from a port on some tab function handleConnect(clientPort) { clientPort.onMessage.addListener(function (message) { handleMessage(clientPort, message); }); clientPort.onDisconnect.addListener(function () { handleDisconnect(clientPort); }); } function handleMessage(clientPort, message) { var clientCallbackToken = message[0]; var actualMessage = message[1]; if (actualMessage[0] == "claim") { // this port is claiming ownership of a particular device var path = actualMessage[1]; deviceOwnership[path] = clientPort; var reply = ["@", clientCallbackToken]; clientPort.postMessage(reply); } else { var nativeCallbackToken = (callNumber++).toString(); var nativeMessage = [nativeCallbackToken, actualMessage]; pendingCallbacks[nativeCallbackToken] = [clientPort, clientCallbackToken]; nativePort.postMessage(nativeMessage); } } function handleDisconnect(port) { var numCallbacks = 0; for (var key in pendingCallbacks) { if (pendingCallbacks[key][0] == port) { ++numCallbacks; delete pendingCallbacks[key]; } } var numDevices = 0; for (var key in deviceOwnership) { if (deviceOwnership[key] == port) { ++numDevices; delete deviceOwnership[key]; } } //console.log("SDH-Background: client port disconnected with " + // numDevices + " devices and " + numCallbacks + " pending callbacks"); } nativePort.onMessage.addListener(handleNativeMessage); chrome.runtime.onConnectExternal.addListener(handleConnect);
javascript
12
0.659475
102
34.653846
78
starcoderdata
private void PlayButton_Click(object sender, EventArgs e) { if (ShowModuleFileDialog() == DialogResult.OK) { using (new SleepCursor()) { // Stop playing any modules StopAndFreeModule(); // Clear the module list EmptyList(); // Add all the files in the module list AddFilesToList(moduleFileDialog.FileNames); // Start to load and play the first module LoadAndPlayModule(0); } } }
c#
13
0.615054
57
21.35
20
inline
/** * @module @svizzle/utils/array-[number-boolean] */ import * as _ from 'lamb'; /** * Return a function expecting a number and returning true if the number is within the provided range. * Note that the range is inclusive. * * @function * @arg {array} range - Array of two numbers * @return {function} predicate - Number -> Boolean * * @example > isWithinRange = makeIsWithinRange([0, 5]) > isWithinRange(2) true > isWithinRange(5) true > isWithinRange(8) false * * @since 0.1.0 */ export const makeIsWithinRange = range => _.allOf([ _.isGTE(range[0]), _.isLTE(range[1]) ]);
javascript
8
0.679092
102
19.566667
30
starcoderdata
<?php namespace App\Http\Controllers; use App\Product; use App\Category; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use Illuminate\Http\Response; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\DB; use App\Exports\ProductsExport; use Barryvdh\DomPDF\Facade as PDF; class ProductController extends Controller { public function __construct() { $this->middleware('auth')->except('catalog'); } public function index() { $categories = Category::get(); $products = Product::get(); return view('admin.products.index')->with(['products' => $products, 'categories' => $categories]); } public function create() { $categories = Category::get(); return view('admin.products.create')->with(['product' => new Product, 'categories' => $categories]); } public function store(Request $request) { $this->validate($request,[ 'category_id' => 'required', 'common_name' => 'required|unique:App\Product,common_name', 'scientific_name' => 'required|unique:App\Product,scientific_name', 'cost' => 'required|Integer|min:0', 'stock' => 'required|Integer|min:0', 'use' => 'required', 'image' => 'string' ]); $product = new Product; $product->category_id = $request->input('category_id'); $product->common_name = $request->input('common_name'); $product->scientific_name = $request->input('scientific_name'); $product->cost = $request->input('cost'); $product->stock = $request->input('stock'); $product->use = $request->input('use'); $image = $request->file('image'); if($image){ // Poner nombre único a la imagen $image_name = time().$image->getClientOriginalName(); // Guardar imagen en carpeta (storage/app/productsimg) Storage::disk('productsimg')->put($image_name, File::get($image)); $product->image = $image_name; } $product->save(); return redirect()->route('products.index')->with('status', 'El producto fue creado correctamente.'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $product = Product::findOrFail($id); return view('admin.products.show', compact('product')); } public function edit($id) { $categories = Category::get(); $product = Product::findOrFail($id); return view('admin.products.edit')->with(['product' => $product, 'categories' => $categories]); } public function update(Request $request, $id) { $this->validate($request,[ 'id' => 'required', 'category_id' => 'required', 'common_name' => 'required|unique:App\Product,common_name,'.$id, 'scientific_name' => 'required|unique:App\Product,scientific_name,'.$id, 'cost' => 'required|Integer|min:0', 'stock' => 'required|Integer|min:0', 'use' => 'required', 'image' => '' ]); $product = Product::findOrFail($id); $product->category_id = $request->input('category_id'); $product->common_name = $request->input('common_name'); $product->scientific_name = $request->input('scientific_name'); $product->cost = $request->input('cost'); $product->stock = $request->input('stock'); $product->use = $request->input('use'); $image = $request->file('image'); if($image){ // Poner nombre único a la imagen $image_name = time().$image->getClientOriginalName(); // Guardar imagen en carpeta (storage/app/productsimg) Storage::disk('productsimg')->put($image_name, File::get($image)); $product->image = $image_name; } $product->update(); /* $product->image = $request->file('image')->store('productsimg'); $product->update($request->except('image')); */ return redirect()->route('products.edit', $id)->with('status', 'El producto fue actualizado correctamente.'); } public function destroy(Product $product) { $product->delete(); return redirect()->route('products.index')->with('status', 'El producto fue eliminado correctamente.'); } public function getImage($filename){ $file = Storage::disk('productsimg')->get($filename); return new Response($file, 200); } public function catalog() { $categories = Category::get(); $products = Product::paginate(12); return view('catalog')->with(['products' => $products, 'categories' => $categories]); } public function xls() { $productsExport = new ProductsExport; return $productsExport->download('Products ' . date('Ymd') . '.xlsx'); } public function pdf() { $categories = Category::all(); $products = Product::orderBy('common_name')->get(); $pdf = PDF::loadView('admin.products.pdf', compact('products', 'categories')); $pdf->setPaper('letter', 'landscape'); return $pdf->stream('listado.pdf'); } public function inout($id) { $product = Product::findOrFail($id); return view('admin.products.inout')->with(['product' => $product]); } public function transaction(Request $request, $id) { $this->validate($request,[ 'id' => 'required', 'quantity' => 'required|integer', 'type' => 'required', 'reason' => 'required', ]); $id = $request['id']; $type = $request['type']; $quantity = $request['quantity']; $product = Product::findOrFail($id); switch($type){ case 'entrada': $product->stock += $quantity; $operation = 'agregado'; break; case 'salida': $product->stock -= $quantity; $operation = 'disminuido'; break; default: print (' ha seleccionado el tipo de operación"); } $product->update($request->only('quantity')); DB::table('product_transactions')->insert([ 'product_id' => $id, 'user_id' => auth()->user()->id, 'type' => $type, 'quantity' => $quantity, 'created_at' => new \DateTime ]); return redirect()->route('products.show', $id)->with('status', 'Se han ' . $operation . ' ' . $quantity . ' unidades al producto ' . $product->common_name); } public function orders(){ return $this->belongsToMany('\App\Order', 'order_product', 'product_id', 'order_id')->withPivot('quantity')->withTimestamps(); } }
php
15
0.536212
164
30.933921
227
starcoderdata
""" SMLR (sparse multinomial logistic regression) """ import numpy import SMLRupdate from sklearn.base import BaseEstimator, ClassifierMixin class SMLR(BaseEstimator, ClassifierMixin): def __init__(self): print "SMLR (sparse multinomial logistic regression)" def fit(self,feature,label): #feature: matrix, whose size is # of samples by # of dimensions. #label: label vector, whose size is # of samples. # If you treat a classification problem with C classes, please use 0,1,2,...,(C-1) to indicate classes #Check # of features, # of dimensions, and # of classes self.classes_, indices = numpy.unique(label,return_inverse=True) N=feature.shape[0] D=feature.shape[1] #C=numpy.max(label)+1 #C=C.astype(int) C=len(self.classes_) #transoform label into a 1-d array to avoid possible errors label=indices #make class label based on 1-of-K representation label_1ofK=numpy.zeros((N,C)) for n in range(N): label_1ofK[n,label[n]]=1 #add a bias term to feature feature=numpy.hstack((feature,numpy.ones((N,1)))) D=D+1 #set initial values of theta (wieghts) and alpha (relavence parameters) theta=numpy.zeros((D,C)) alpha=numpy.ones((D,C)) isEffective=numpy.ones((D,C)) effectiveFeature=range(D) #Variational baysian method (see Yamashita et al., 2008) for iteration in range(100): #theta-step newThetaParam=SMLRupdate.thetaStep(theta,alpha,label_1ofK,feature,isEffective) theta=newThetaParam['mu']#the posterior mean of theta #alpha-step alpha=SMLRupdate.alphaStep(alpha,newThetaParam['mu'],newThetaParam['var'],isEffective) #pruning of irrelevant dimensions (that have large alpha values) isEffective=numpy.ones(theta.shape) isEffective[alpha>10**3]=0 theta[alpha>10**3]=0 dim_excluded=(numpy.all(isEffective==0,axis=1)) dim_excluded=[d for d in range(len(dim_excluded)) if dim_excluded[d]] theta=numpy.delete(theta,dim_excluded,axis=0) alpha=numpy.delete(alpha,dim_excluded,axis=0) feature=numpy.delete(feature,dim_excluded,axis=1) isEffective=numpy.delete(isEffective,dim_excluded,axis=0) effectiveFeature=numpy.delete(effectiveFeature,dim_excluded,axis=0) #show progress if iteration%20==0: num_effectiveWeights=numpy.sum(isEffective) print "# of iterations: %d , # of effective dimensions: %d" %(iteration,len(effectiveFeature)) temporal_theta=numpy.zeros((D,C)) temporal_theta[effectiveFeature,:]=theta theta=temporal_theta self.coef_=numpy.transpose(theta[:-1,:]) self.intercept_=theta[-1,:] return theta def predict(self,feature): N=feature.shape[0] D=feature.shape[1] #add a bias term to feature feature=numpy.hstack((feature,numpy.ones((N,1)))) #load weights w=numpy.vstack((numpy.transpose(self.coef_),self.intercept_)) C=w.shape[1] #predictive probability calculation p=numpy.zeros((N,C)) predicted_label=list([]) for n in range(N): p[n,:]=numpy.exp(numpy.dot(feature[n,:],w)) p[n,:]=p[n,:]/sum(p[n,:]) predicted_label.append(self.classes_[numpy.argmax(p[n,:])]) return predicted_label def predict_proba(self,feature): N=feature.shape[0] D=feature.shape[1] #add a bias term to feature feature=numpy.hstack((feature,numpy.ones((N,1)))) #load weights w=numpy.vstack((numpy.transpose(self.coef_),self.intercept_)) C=w.shape[1] #predictive probability calculation p=numpy.zeros((N,C)) predicted_label=numpy.zeros(N) for n in range(N): p[n,:]=numpy.exp(numpy.dot(feature[n,:],w)) p[n,:]=p[n,:]/sum(p[n,:]) return p
python
15
0.576072
116
33.428571
126
starcoderdata
module.exports = function (app) { var postsController = function ($rootScope, $stateParams, discourseDataService, $scope, $state, environmentService, $sce, forumService, localStorageService, loginModalService, $location, $window) { var vm = this; vm.env = environmentService(); //state managment vm.state = 'pending'; //[pending|unrecoverable|ready] //user messaging handling vm.validationErrors = []; vm.unrecoverableErrors = []; vm.createReplyErrors = []; //authorization vm.isAuthenticated = localStorageService.getAuthenticationState(); //data vm.categoryObj = { categorySlug: $stateParams.categorySlug, subCategorySlug: $stateParams.subCategorySlug, topicSlug: $stateParams.topicSlug }; vm.posts = []; //functions vm.init = init; vm.requestCallback = requestCallback; vm.getPostUsername = getPostUsername; vm.getNumPostsByUser = getNumPostsByUser; vm.trustHtml = trustHtml; vm.createReply = createReply; vm.goToReply = goToReply; vm.init(); function init() { //validations // if (!vm.categoryObj.categorySlug || vm.categoryObj.categorySlug==='') { // vm.SetError('Missing category parameter'); // return; // } // if (!vm.categoryObj.subCategorySlug || vm.categoryObj.subCategorySlug==='') { // vm.SetError('Missing sub category parameter'); // return; // } // if (!vm.categoryObj.topicSlug || vm.categoryObj.topicSlug==='') { // vm.SetError('Missing topic parameter'); // return; // } //get forum data forumService.getPosts(vm.categoryObj, requestCallback); //todo: does this jhelp // if (vm.topic && vm.topic.post_stream && vm.topic.post_stream.posts) { // //should be a call getPosts that returns existing rather than allocating more space to hold the same data // vm.posts = vm.topic.post_stream.posts; // } //not sure if we need this for the posts page: //get theme categories for side bar //forumService.getSubCategories(vm.themesObj, vm.themesObjLoadedCB) } function requestCallback() { if (!vm.categoryObj.response.success) { vm.unrecoverableErrors = vm.unrecoverableErrors.concat(vm.categoryObj.response.unrecoverableErrors); vm.unrecoverableId = vm.categoryObj.response.id; vm.state = 'unrecoverable'; return; } vm.state = 'ready'; //simplify access to posts vm.posts = vm.categoryObj.response.data.posts.post_stream.posts; //setup meta tags var title = 'Accessible Travel Forum'; var desc = 'Get answers to your accessible travel questions!'; //TODO: identify image for SEO //var img = vm.env.BASEURL_CONTENT + '/assets/cities/main/' + vm.city.replace(" ", "") + '_main.jpg'; //vm.getMainImagePath(); $rootScope.metaTagService.setup({ metaTitle: title, ogTitle: title, twitterTitle: title, metaDescription: desc, ogDescription: desc, twitterDescription: desc, //ogImage: img, //twitterImage: img }); } function getPostUsername(userId) { if (vm.categoryObj && vm.categoryObj.response && vm.categoryObj.response.data && vm.categoryObj.response.data.posts && vm.categoryObj.response.data.posts.details && vm.categoryObj.response.data.posts.details.participants) { var results = vm.categoryObj.response.data.posts.details.participants.filter(function(x) { return x.id===userId; }); if (results.length===1) { return results[0].username; } } return ''; } function getNumPostsByUser(userId) { if (vm.categoryObj && vm.categoryObj.response && vm.categoryObj.response.data && vm.categoryObj.response.data.posts && vm.categoryObj.response.data.posts.details && vm.categoryObj.response.data.posts.details.participants) { var results = vm.categoryObj.response.data.posts.details.participants.filter(function(x) { return x.id===userId; }); if (results.length===1) { return results[0].post_count; } } return 0; } function trustHtml(post) { if (!post) return '?'; return $sce.trustAsHtml(post.cooked); } function goToReply() { //auth0 authenticated? if (!$rootScope.isAuthenticated) { //define login callback var loginCB = function() { vm.isAuthenticated = true; //scroll to reply form $scope.scrollTo('replyForm'); }; //show login var params = { onSuccessFunc: loginCB }; loginModalService(params); return; } //discourse authentication if (!localStorageService.getDiscourseSession()) { var currentLocation = $location.absUrl(); var url = 'https://community.accessiblego.com/session/sso?return_path='+ encodeURIComponent(currentLocation); $window.open(url, '_self'); } //scroll to reply form $scope.scrollTo('replyForm'); } function createReply() { //are we authenticated? if (!$rootScope.isAuthenticated) { loginModalService(); return; } //reset vm.createReplyErrors = []; //validation // if (!vm.message || vm.message ==='') { // vm.createReplyErrors.push({message: 'Missing message.'}); // return; // } //create the reply var params = { topicId: vm.categoryObj.response.data.topic.id, message: vm.message } var successFunc = function (response) { // if (!response || !response.data) { // vm.createReplyErrors.push({message: 'Error while creating a reply'}); // return; // } // if (response.data.error) { // vm.createReplyErrors.push({message: response.data.error}); // return; // } //error if (!response.data.success) { //unrecoverable errors $.each(response.data.unrecoverableErrors, function(idx, err) { vm.createReplyErrors.push({message: err}); }); //validation errors $.each(response.data.validationErrors, function(idx, err) { vm.createReplyErrors.push({message: err}); }); return; } //success :: refresh posts page var pageParams = { categorySlug:vm.categoryObj.categorySlug, subCategorySlug: vm.categoryObj.subCategorySlug, topicSlug: response.data.data.create_reply.topic_slug }; $state.go($state.current, {}, {reload:true}); }; var errFunc = function (response) { console.log(response); //todo: identify how to detect this and determine if further work is required vm.createReplyErrors.push({message: 'Error while creating a reply'}); }; //get forum data forumService.createReply(params, successFunc, errFunc); } }; postsController.$inject = ['$rootScope', '$stateParams', 'discourseDataService', '$scope', '$state', 'environmentService', '$sce', 'forumService', 'localStorageService', 'loginModalService','$location','$window']; app.controller('postsController', postsController); };
javascript
23
0.530202
235
36.375546
229
starcoderdata
private void loadDataInit(InscriptionDTO data){ binding.txtSpnDirSend.setError(null); List<String> listP = Arrays.asList(getResources().getStringArray(R.array.parentescoOptions)); modelRefPersonal.loadDataInit(data.getReferencia().get(0), listP); modelRefFamiliar.loadDataInit(data.getReferencia().get(1), listP); // model.loadDataInit(data, listDirSend); model.setReferenciado_hint(data.getReferenciado_nombre()); ciudad = new CiudadDTO(String.valueOf(data.getId_ciudad()), data.getName_ciudad()); barrio = new BarrioDTO(String.valueOf(data.getId_barrio()), data.getBarrio()); //esta infor viene codificada barrio_2 = new BarrioDTO(model.getId_barrio_env(), model.getBarrio_env()); ciudad_2 = new CiudadDTO(model.getId_ciudad_env(), model.getName_ciudad_env()); //esta infor viene codificada model.getReferencia().set(0, modelRefPersonal); model.getReferencia().set(1, modelRefFamiliar); }
java
11
0.691089
101
47.142857
21
inline
using System; using System.Collections.Generic; using System.Text; namespace XUtility.Client { /// /// Client异常 /// public class ClientException : Exception { /// /// 构造函数 /// /// <param name="code"> /// <param name="message"> /// <param name="innerException"> public ClientException(int code, string message, Exception innerException) : base(message, innerException) { Code = code; } /// /// 错误码 /// public int Code { get; } } }
c#
10
0.530303
114
22.571429
28
starcoderdata
void __cpu_suspend_save(u32 *ptr, u32 ptrsz, u32 sp, u32 *save_ptr) { u32 *ctx = ptr; *save_ptr = virt_to_phys(ptr); /* This must correspond to the LDM in cpu_resume() assembly */ *ptr++ = virt_to_phys(idmap_pgd); *ptr++ = sp; *ptr++ = virt_to_phys(cpu_do_resume); cpu_do_suspend(ptr); flush_cache_louis(); /* * flush_cache_louis does not guarantee that * save_ptr and ptr are cleaned to main memory, * just up to the Level of Unification Inner Shareable. * Since the context pointer and context itself * are to be retrieved with the MMU off that * data must be cleaned from all cache levels * to main memory using "area" cache primitives. */ __cpuc_flush_dcache_area(ctx, ptrsz); __cpuc_flush_dcache_area(save_ptr, sizeof(*save_ptr)); outer_clean_range(*save_ptr, *save_ptr + ptrsz); outer_clean_range(virt_to_phys(save_ptr), virt_to_phys(save_ptr) + sizeof(*save_ptr)); }
c
10
0.677632
67
28.451613
31
inline
package cache type Interface interface { // IsExpired judge whether the data is expired IsExpired(key string) (bool, error) // DeleteExpired delete all expired data DeleteExpired() // StartGc start gc // After the expiration time is set, GC will be started automatically without manual GC StartGc() error // StopGc stop gc StopGc() error // Get data // When the data does not exist or expires, it will return nonexistence(false) Get(key string) (interface{}, bool) // GetAndDelete get data and delete by key GetAndDelete(key string) (interface{}, bool) // GetAndExpired get data and expire by key // It will be deleted at the next clearing. If the clearing capability is not enabled, it will never be deleted GetAndExpired(key string) (interface{}, bool) // Delete delete data by key Delete(key string) (interface{}, bool) } type MapInterface interface { Interface // Set data by key,it will overwrite the data if the key exists Set(key string, value interface{}) // Add data,Cannot add existing data // To override the addition, use the set method Add(key string, value interface{}) error // Clear remove all data Clear() // Keys get all keys Keys() []string }
go
8
0.731023
112
28.560976
41
starcoderdata
//******************************************************** // Syzygy is licensed under the BSD license v2 // see the file SZG_CREDITS for details //******************************************************** // This can be included multiple times. // Each sublibrary of Syzygy defines or undefines SZG_IMPORT_LIBRARY. // So undefine it here. #undef SZG_IMPORT_LIBRARY #ifndef SZG_COMPILING_SOUND #define SZG_IMPORT_LIBRARY #endif #include "arCallingConventions.h"
c
4
0.578288
69
28.9375
16
starcoderdata