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
<?php namespace App\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="App\Repository\ContactFormTypeEntityRepository") */ class ContactFormTypeEntity { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") * @ORM\OrderBy({"id" = "DESC"}) */ private $id; /** * @ORM\Column(type="string", length=255) */ private $formTypeName; /** * @ORM\Column(type="string", length=255, unique=true) */ private $formTypeAlias; /** * @ORM\Column(type="datetime") */ private $createAt; /** * @ORM\OneToMany(targetEntity="App\Entity\ContactFormEntity", mappedBy="contactFormTypeEntity") */ private $contactFormEntitys; /** * @ORM\OneToMany(targetEntity="App\Entity\ContactFormFieldEntity", mappedBy="contactFormTypeEntity", cascade={"persist", "remove"}) */ private $contactFormFieldEntities; public function __construct() { $this->contactFormEntitys = new ArrayCollection(); $this->contactFormFieldEntities = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getFormTypeName(): ?string { return $this->formTypeName; } public function setFormTypeName(string $formTypeName): self { $this->formTypeName = $formTypeName; return $this; } public function getFormTypeAlias(): ?string { return $this->formTypeAlias; } public function setFormTypeAlias(string $formTypeAlias): self { $this->formTypeAlias = $formTypeAlias; return $this; } public function getCreateAt(): ?\DateTimeInterface { return $this->createAt; } public function setCreateAt(\DateTimeInterface $createAt): self { $this->createAt = $createAt; return $this; } /** * @return Collection|ContactFormEntity[] */ public function getContactFormEntitys(): Collection { return $this->contactFormEntitys; } public function addContactFormEntity(ContactFormEntity $contactFormEntity): self { if (!$this->contactFormEntitys->contains($contactFormEntity)) { $this->contactFormEntitys[] = $contactFormEntity; $contactFormEntity->setContactFormTypeEntity($this); } return $this; } public function removeContactFormEntity(ContactFormEntity $contactFormEntity): self { if ($this->contactFormEntitys->contains($contactFormEntity)) { $this->contactFormEntitys->removeElement($contactFormEntity); // set the owning side to null (unless already changed) if ($contactFormEntity->getContactFormTypeEntity() === $this) { $contactFormEntity->setContactFormTypeEntity(null); } } return $this; } /** * @return Collection|ContactFormFieldEntity[] */ public function getContactFormFieldEntities(): Collection { return $this->contactFormFieldEntities; } public function addContactFormFieldEntity(ContactFormFieldEntity $contactFormFieldEntity): self { if (!$this->contactFormFieldEntities->contains($contactFormFieldEntity)) { $this->contactFormFieldEntities[] = $contactFormFieldEntity; // $this->contactFormFieldEntities->add($contactFormFieldEntity); $contactFormFieldEntity->setContactFormTypeEntity($this); } return $this; } public function removeContactFormFieldEntity(ContactFormFieldEntity $contactFormFieldEntity): self { if ($this->contactFormFieldEntities->contains($contactFormFieldEntity)) { $this->contactFormFieldEntities->removeElement($contactFormFieldEntity); // set the owning side to null (unless already changed) if ($contactFormFieldEntity->getContactFormTypeEntity() === $this) { $contactFormFieldEntity->setContactFormTypeEntity(null); } } return $this; } }
php
13
0.640449
136
24.580838
167
starcoderdata
public override bool SupportCoercionForArg(int argIndex) { if (!base.SupportCoercionForArg(argIndex)) { return false; } // For first arg we don't support coercion. return argIndex != 0; }
c#
9
0.510714
56
27.1
10
inline
// Copyright (C) 2019 The DMLab2D Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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. // //////////////////////////////////////////////////////////////////////////////// #include "dmlab2d/lib/system/grid_world/collections/object_pool.h" #include "dmlab2d/lib/system/grid_world/collections/handle.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace deepmind::lab2d { namespace { using ::testing::Eq; struct TestHandleTag { static constexpr char kName[] = "TestHandle"; }; using TestHandle = Handle<struct TestHandleTag>; TEST(ObjectPoolTest, CreateWorks) { ObjectPool<TestHandle, int> int_pool; auto ten = int_pool.Create(10); auto twenty = int_pool.Create(20); auto thirty = int_pool.Create(30); EXPECT_THAT(ten.Value(), Eq(0)); EXPECT_THAT(twenty.Value(), Eq(1)); EXPECT_THAT(thirty.Value(), Eq(2)); } TEST(ObjectPoolTest, LookUpWorks) { ObjectPool<TestHandle, int> int_pool; auto ten = int_pool.Create(10); auto twenty = int_pool.Create(20); auto thirty = int_pool.Create(30); int_pool[ten] = 15; int_pool[twenty] = 25; int_pool[thirty] = 35; EXPECT_THAT(int_pool[ten], Eq(15)); EXPECT_THAT(int_pool[twenty], Eq(25)); EXPECT_THAT(int_pool[thirty], Eq(35)); } TEST(ObjectPoolTest, ConstLookUpWorks) { ObjectPool<TestHandle, int> int_pool; auto ten = int_pool.Create(10); auto twenty = int_pool.Create(20); auto thirty = int_pool.Create(30); const auto& read_only_int_pool = int_pool; EXPECT_THAT(read_only_int_pool[ten], Eq(10)); EXPECT_THAT(read_only_int_pool[twenty], Eq(20)); EXPECT_THAT(read_only_int_pool[thirty], Eq(30)); } TEST(ObjectPoolTest, ReleaseWorks) { ObjectPool<TestHandle, int> int_pool; auto ten = int_pool.Create(10); auto twenty = int_pool.Create(20); auto thirty = int_pool.Create(30); int_pool.Release(twenty); auto twenty_two = int_pool.Create(22); EXPECT_THAT(int_pool[twenty_two], Eq(22)); EXPECT_THAT(twenty_two.Value(), Eq(1)); int_pool.Release(twenty_two); int_pool.Release(ten); int_pool.Release(thirty); } TEST(ObjectPoolTest, RemoveAllElementsWorks) { ObjectPool<TestHandle, int> int_pool; auto ten = int_pool.Create(10); auto twenty = int_pool.Create(20); auto thirty = int_pool.Create(30); int_pool.Release(thirty); int_pool.Release(twenty); int_pool.Release(ten); ten = int_pool.Create(10); twenty = int_pool.Create(20); thirty = int_pool.Create(30); EXPECT_THAT(ten.Value(), Eq(0)); EXPECT_THAT(twenty.Value(), Eq(1)); EXPECT_THAT(thirty.Value(), Eq(2)); int_pool.Release(thirty); } TEST(ObjectPoolTest, PreconditionsAreCheckedInDebugWithHole) { ObjectPool<TestHandle, int> int_pool; auto ten = int_pool.Create(10); auto twenty = int_pool.Create(20); const auto& read_only_int_pool = int_pool; EXPECT_THAT(read_only_int_pool[ten], Eq(10)); int_pool.Release(ten); #ifndef NDEBUG EXPECT_DEATH(int_pool[ten], "Attempting to use released handle!"); EXPECT_DEATH(read_only_int_pool[ten], "Attempting to use released handle!"); EXPECT_DEATH(int_pool.Release(ten), "Object removed twice!"); #endif EXPECT_THAT(read_only_int_pool[twenty], Eq(20)); } TEST(ObjectPoolTest, PreconditionsAreCheckedInDebugEmpty) { ObjectPool<TestHandle, int> int_pool; auto ten = int_pool.Create(10); const auto& read_only_int_pool = int_pool; EXPECT_THAT(read_only_int_pool[ten], Eq(10)); int_pool.Release(ten); #ifndef NDEBUG EXPECT_DEATH(int_pool[ten], "Attempting to use released handle!"); EXPECT_DEATH(read_only_int_pool[ten], "Attempting to use released handle!"); EXPECT_DEATH(int_pool.Release(ten), "Object removed twice!"); #endif } } // namespace } // namespace deepmind::lab2d
c++
13
0.69356
80
31.889764
127
starcoderdata
public String getContent() { String content = this.pojo.getContent(); // escape content if content-type is text/plain if("text/plain".equals(this.pojo.getContentType())) { content = StringEscapeUtils.escapeHtml4(content); } // apply plugins PluginManager pmgr = WebloggerFactory.getWeblogger().getPluginManager(); content = pmgr.applyCommentPlugins(this.pojo, content); // always add rel=nofollow for links content = Utilities.addNofollow(content); return content; }
java
9
0.599671
80
32.777778
18
inline
const Room = require("colyseus").Room; const Player = require("../player").Player; module.exports = class TownRoom extends Room { onInit() { this.maxClients = 16; this.blockSameUser = false; this.timeout = 15; this.setState({ currentTurn: null, players: [], idList: [], }); } requestJoin(opts, isNew) { if (isNew) { return true; } //check if room allows same user to log in twice if (!this.blockSameUser) { return true; } //check if the optional args contains nickname and id if (!("NickName" in opts) || !("ID" in opts)) { return false; } //check if client is already connected for (i = 0; i < Object.keys(this.state.players).length; i++) { if (opts.ID === this.state.idList[i]) { return false; } } //check if the user is already in the players list return !this.players.includes(opts.NickName); } onJoin(client) { //sets the player object in the array client.playerIndex = Object.keys(this.state.players).length; this.state.players[client.playerIndex] = new Player( client.NickName, client.playerIndex ); this.state.idList[client.playerIndex] = client.id; if (this.clients.length == this.maxClients) { //start a time to do a random move. this.chooseRandomTimeout = this.clock.setTimeout( this.chooseRandom.bind(this, client), this.timeout * 1000 ); // lock this room for new users this.lock(); this.GameStart(); } } onLeave(client) { for (i = 0; i < Object.keys(this.state.players).length; i++) { if (client.playerIndex === this.state.players[i].id) { this.state.players.splice(i, 1); this.state.idList.splice(i, 1); } } this.CheckWin(); } GameStart() { //implement later with this.send(client, { message: "Hello world!" }); } CheckWin() { winningside = this.state.players[0].side; for (i = 0; i < Object.keys(this.state.players).length; i++) { if (this.state.players[i].side != winningside) { return false; } } WinScreen(winningside); return true; } Winscreen(wside) { //implement later. } };
javascript
14
0.603249
91
23.621053
95
starcoderdata
const TypeProto = { location: null, toString() { return this.location ? `[${this.name}](${this.location})` : this.name; } }; const defaultTypes = { 'string': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String', 'number': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number', 'boolean': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean', 'function': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype', 'Function': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype', 'Array': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array', 'Promise': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise', 'Node': 'https://developer.mozilla.org/en-US/docs/Web/API/Node', 'Element': 'https://developer.mozilla.org/en-US/docs/Web/API/Element', 'HTMLElement': 'https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement', 'void': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined', 'undefined': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined', 'null': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null', 'object': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object', 'IDBDatabase': 'https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase', 'IDBTransaction': 'https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction', }; const resolveType = module.exports = function(type, module, fileNameResolver = null, exported = false) { if (typeof type !== 'string') { if (type === undefined) { return '?'; } return resolveType(type.toString()); } type = type.split('|'); if (type.length > 1){ return type.map(type => resolveType(type, module, fileNameResolver)) .join('&#124;'); } type = type[0]; let generic = null; if ((generic = type.match(/([^ { const [, type, returnType] = generic; return `${resolveType(type, module, fileNameResolver)}.&lt;${resolveType(returnType, module, fileNameResolver)}&gt;`; } if (/\[\]$/.test(type)) { return resolveType(`Array.<${type.substr(0, type.length - 2)}>`, module, fileNameResolver); } // we've got a type literal if (/^\s*\{.*\}\s*$/.test(type)) { let pair = null; const keyValueMatcher = /\s*([^\s:]+)\s*:\s*([^:\s]+)(?:\s*,|\s*,\s*}|\s*})/g; const resolvedLiteral = []; while ((pair = keyValueMatcher.exec(type))) { const [, key, value] = pair; resolvedLiteral.push(`${key}: ${resolveType(value, module, fileNameResolver)}`); } return `{ ${resolvedLiteral.join(', ')} }`; } if (!module) { return { name: type, __proto__: TypeProto, }; } if (defaultTypes[type]) { return { name: type, location: defaultTypes[type], __proto__: TypeProto, }; } const definition = Array.from(module.definitions).find(def => (exported ? def.export : def.name) === type); if (!definition) { return { name: type, __proto__: TypeProto, }; } if (definition.kind !== 'import') { const filename = fileNameResolver ? fileNameResolver(module.name) : module.name; return { name: definition.name, location: `./${filename}#${definition.name.toLowerCase()}`, export: definition.export, __proto__: TypeProto, }; } const originalType = definition.type; const originalDef = resolveType(originalType, module.parent.getModule(definition.origin), fileNameResolver, true); if (originalDef.name === 'default') { originalDef.name = definition.name; } if (originalDef && originalDef.location === null) { return originalDef.name.replace(/(\\\*|\*)/, '\\*'); } if (originalDef && originalDef.export === originalType) { return originalDef; } if (originalDef && originalDef.export && originalDef.name === originalType) { return originalDef; } };
javascript
16
0.610162
125
34.395349
129
starcoderdata
package properties; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import network.NetworkManager; import properties.event.EventHandler; import properties.network.PropertiesPacketCallback; import static properties.Constants.*; @Mod(modid = MODID, name = NAME, version = VERSION) public class ModMain { public static NetworkManager network = new NetworkManager(MODID, new PropertiesPacketCallback()); @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { new EventHandler(); } }
java
9
0.776632
101
26.714286
21
starcoderdata
from django.conf.urls import url from cnf_xplor.food_search import views urlpatterns = [ url(r'^$', views.Search.as_view(), name='food_search'), url(r'food/(?P views.Food_Detail.as_view(), name='food_detail'), url(r'conversionfactor/(?P views.ConversionFactor_Detail.as_view(), name='conversionfactor_detail'), url(r'nutrient/(?P views.Nutrient_Detail.as_view(), name='nutrient_detail'), url(r'test/$', views.Test.as_view(), name='test'), ]
python
9
0.650699
116
37.538462
13
starcoderdata
@Override public Object field(Object target) { // lazy init to have the settings in place if (value == null) { value = new RawJson(StringUtils.toJsonString(settings.getMappingVersionType())); } return value; }
java
13
0.546713
96
35.25
8
inline
/* * Copyright (c) 2020, All rights reserved. http://edevapps.com */ package com.edevapps.jira.security; import static com.edevapps.util.ObjectsUtil.requireNonNull; import static com.edevapps.util.StringUtil.EMPTY_STRING; import com.atlassian.upm.api.license.PluginLicenseManager; import com.atlassian.upm.api.license.entity.LicenseError; import com.atlassian.upm.api.util.Option; public class LicenseCheckerImpl implements LicenseChecker { private final PluginLicenseManager pluginLicenseManager; public LicenseCheckerImpl(final PluginLicenseManager pluginLicenseManager) { this.pluginLicenseManager = requireNonNull(pluginLicenseManager, "pluginLicenseManager"); } @Override public void checkLicense() throws SecurityException { try { if (this.pluginLicenseManager.getLicense().isDefined()) { Option licenseError = this.pluginLicenseManager.getLicense().get() .getError(); if (licenseError.isDefined()) { throw new SecurityException("License error:" + licenseError.get().toString()); } } else { throw new SecurityException("No license installed"); } } catch (Exception ex) { throw new SecurityException("Error retrieving license:" + ex.getMessage()); } } @Override public boolean isLicensed() { try { if (this.pluginLicenseManager.getLicense().isDefined()) { return !this.pluginLicenseManager.getLicense().get().getError().isDefined(); } else { return false; } } catch (Exception ex) { return false; } } @Override public String getLicenseError() { try { if (this.pluginLicenseManager.getLicense().isDefined()) { Option licenseError = this.pluginLicenseManager.getLicense().get().getError(); if (licenseError.isDefined()) { return licenseError.get().toString(); } } return EMPTY_STRING; } catch (Exception ex) { return ex.getMessage(); } } }
java
18
0.684236
100
29.757576
66
starcoderdata
package com.mpobjects.formats.sofalife.stream.impl; import javax.xml.stream.Location; public class LocationImpl implements Location { private int characterOffset = -1; private int columnNumber = -1; private int lineNumber = -1; private String publicId; private String systemId; public LocationImpl(Location aLocation) { publicId = aLocation.getPublicId(); systemId = aLocation.getSystemId(); lineNumber = aLocation.getLineNumber(); columnNumber = aLocation.getColumnNumber(); characterOffset = aLocation.getCharacterOffset(); } public LocationImpl(String aPublicId, String aSystemId) { publicId = aPublicId; systemId = aSystemId; } @Override public int getCharacterOffset() { return characterOffset; } @Override public int getColumnNumber() { return columnNumber; } @Override public int getLineNumber() { return lineNumber; } @Override public String getPublicId() { return publicId; } @Override public String getSystemId() { return systemId; } public void setCharacterOffset(int aCharacterOffset) { characterOffset = aCharacterOffset; } public void setColumnNumber(int aColumnNumber) { columnNumber = aColumnNumber; } public void setLineNumber(int aLineNumber) { lineNumber = aLineNumber; } }
java
9
0.71151
58
17.970149
67
starcoderdata
// MIT License // // Copyright (c) 2016-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. using System; using System.Runtime.CompilerServices; namespace ExtendedXmlSerializer.Core { /// /// Attribution: https://msdn.microsoft.com/en-us/library/system.runtime.serialization.objectmanager(v=vs.110).aspx /// sealed class ObjectIdGenerator { readonly static uint[] Sizes = { 5, 11, 29, 47, 97, 197, 397, 797, 1597, 3203, 6421, 12853, 25717, 51437, 102877, 205759, 411527, 823117, 1646237, 3292489, 6584983 }; uint _currentCount, _currentSize; uint[] _ids; object[] _objs; /// a new instance of the <see cref="T:System.Runtime.Serialization.ObjectIDGenerator" /> class. public ObjectIdGenerator() { _currentCount = 1; _currentSize = Sizes[0]; _ids = new uint[_currentSize * 4]; _objs = new object[_currentSize * 4]; } uint FindIndex(object obj, out bool found) { var hashCode = RuntimeHelpers.GetHashCode(obj); var num1 = (int) (1 + (hashCode & int.MaxValue) % (_currentSize - 2)); while (true) { var num2 = (hashCode & int.MaxValue) % _currentSize * 4; for (var index = num2; index < num2 + 4; ++index) { var o = _objs[index]; if (o == null) { found = false; return (uint) index; } if (o == obj) { found = true; return (uint) index; } } hashCode += num1; } } /// the ID for the specified object, generating a new ID if the specified object has not already been identified by the <see cref="T:System.Runtime.Serialization.ObjectIDGenerator" />. /// object's identity context, which can be used for serialization. FirstEncounter is set to true if this is the first time the object has been identified; otherwise, it is set to false. /// <param name="obj">The object you want an ID for. /// <exception cref="T:System.ArgumentNullException">The <paramref name="obj" /> parameter is null. /// <exception cref="T:System.Runtime.Serialization.SerializationException">The <see cref="T:System.Runtime.Serialization.ObjectIDGenerator" /> has been asked to keep track of too many objects. public uint For(object obj) { if (obj == null) throw new ArgumentNullException(nameof(obj), "ArgumentNull_Obj"); bool found; var index = FindIndex(obj, out found); var result = found ? _ids[index] : Create(obj, index); return result; } uint Create(object obj, uint index) { uint id; _objs[index] = obj; var ids = _ids; var count = _currentCount; _currentCount = count + 1; ids[index] = count; id = _ids[index]; if (_currentCount > _currentSize * 4 / 2) Rehash(); return id; } public bool Contains(object obj) { bool result; FindIndex(obj, out result); return result; } void Rehash() { var index1 = 0; var currentSize = _currentSize; while (index1 < Sizes.Length && Sizes[index1] <= currentSize) ++index1; if (index1 == Sizes.Length) throw new InvalidOperationException("Serialization_TooManyElements"); _currentSize = Sizes[index1]; var numArray = new uint[_currentSize * 4]; var objArray = new object[_currentSize * 4]; var ids = _ids; var objs = _objs; _ids = numArray; _objs = objArray; for (var index2 = 0; index2 < objs.Length; ++index2) { if (objs[index2] != null) { var element = FindIndex(objs[index2], out _); _objs[element] = objs[index2]; _ids[element] = ids[index2]; } } } } }
c#
21
0.673735
213
32.787234
141
starcoderdata
/** * Author: Sajeeb Roy Chowdhury * Created: 10/8/22 * Email: [email protected] * **/ #include <vector> #include <list> #include <unordered_map> #include <unordered_set> #include <string> #include <iostream> #include <memory> #include "IRTreeVisitor.h" #include "dispatcher.h" #include "../exception.h" #include "../../foundations.h" #ifndef EXPONENT_VECTOR_VISITOR_H #define EXPONENT_VECTOR_VISITOR_H #ifndef LOG #define LOG(x) std::cout << __FILE__ << ":" << __LINE__ << ": " << x << std::endl; #endif using std::shared_ptr; using std::list; using std::unordered_set; using std::vector; using std::unordered_map; using std::string; class managed_variables_index_table : public unordered_map<string, size_t> { typedef unordered_map<string, size_t> base_t; public: template<class T> void insert(const T& name) { base_t::insert({name, size()}); } template<class T, class... Args> void insert(const T& name, const Args&... args) { base_t::insert({name, size()}); insert(args...); } size_t index(const string& key) const { return base_t::at(key); } }; std::ostream& operator<< (std::ostream& os, const managed_variables_index_table& obj); struct monomial_coefficient_table_hash_function final { using algorithms = orbiter::layer1_foundations::data_structures::algorithms; uint32_t operator()(const vector<unsigned int>& exponent_vector) const { static algorithms algo_instance; return algo_instance.SuperFastHash_uint(exponent_vector.data(), exponent_vector.size()); } }; struct monomial_coefficient_table_key_equal_function final { bool operator()(const vector<unsigned int>& a, const vector<unsigned int>& b) const { using sorting = orbiter::layer1_foundations::data_structures::sorting; static sorting keyEqualFn; return !keyEqualFn.integer_vec_std_compare(a, b); } }; class monomial_coefficient_table final : public unordered_map<vector<unsigned int>, vector<shared_ptr<irtree_node>>, monomial_coefficient_table_hash_function, monomial_coefficient_table_key_equal_function> {}; class exponent_vector_visitor final : public IRTreeVoidReturnTypeVisitorInterface, public IRTreeVoidReturnTypeVariadicArgumentVisitorInterface<shared_ptr<irtree_node>&>, public IRTreeVoidReturnTypeVariadicArgumentVisitorInterface<vector<unsigned int>&, list<shared_ptr<irtree_node> >::iterator&, shared_ptr<irtree_node>&, shared_ptr<irtree_node>&> { using IRTreeVoidReturnTypeVariadicArgumentVisitorInterface<shared_ptr<irtree_node>&>::visit; using IRTreeVoidReturnTypeVariadicArgumentVisitorInterface<vector<unsigned int>&, list<shared_ptr<irtree_node> >::iterator&, shared_ptr<irtree_node>&, shared_ptr<irtree_node>&>::visit; using IRTreeVoidReturnTypeVisitorInterface::visit; typedef size_t index_t; void visit(plus_node* node, shared_ptr<irtree_node>& node_self) override; void visit(minus_node* node, shared_ptr<irtree_node>& node_self) override; void visit(multiply_node* node, shared_ptr<irtree_node>& node_self) override; void visit(exponent_node* node, shared_ptr<irtree_node>& node_self) override; void visit(unary_negate_node* node, shared_ptr<irtree_node>& node_self) override; void visit(sentinel_node* node, shared_ptr<irtree_node>& node_self) override; void visit(plus_node* node, vector<unsigned int>& exponent_vector, list<shared_ptr<irtree_node> >::iterator& link, shared_ptr<irtree_node>& node_self, shared_ptr<irtree_node>& parent_node) override; void visit(minus_node* node, vector<unsigned int>& exponent_vector, list<shared_ptr<irtree_node> >::iterator& link, shared_ptr<irtree_node>& node_self, shared_ptr<irtree_node>& parent_node) override; void visit(multiply_node* node, vector<unsigned int>& exponent_vector, list<shared_ptr<irtree_node> >::iterator& link, shared_ptr<irtree_node>& node_self, shared_ptr<irtree_node>& parent_node) override; void visit(exponent_node* node, vector<unsigned int>& exponent_vector, list<shared_ptr<irtree_node> >::iterator& link, shared_ptr<irtree_node>& node_self, shared_ptr<irtree_node>& parent_node) override; void visit(unary_negate_node* node, vector<unsigned int>& exponent_vector, list<shared_ptr<irtree_node> >::iterator& link, shared_ptr<irtree_node>& node_self, shared_ptr<irtree_node>& parent_node) override; void visit(variable_node* num_node, vector<unsigned int>& exponent_vector, list<shared_ptr<irtree_node> >::iterator& link, shared_ptr<irtree_node>& node_self, shared_ptr<irtree_node>& parent_node) override; void visit(parameter_node* node, vector<unsigned int>& exponent_vector, list<shared_ptr<irtree_node> >::iterator& link, shared_ptr<irtree_node>& node_self, shared_ptr<irtree_node>& parent_node) override; void visit(number_node* node, vector<unsigned int>& exponent_vector, list<shared_ptr<irtree_node> >::iterator& link, shared_ptr<irtree_node>& node_self, shared_ptr<irtree_node>& parent_node) override; void visit(sentinel_node* node, vector<unsigned int>& exponent_vector, list<shared_ptr<irtree_node> >::iterator& link, shared_ptr<irtree_node>& node_self, shared_ptr<irtree_node>& parent_node) override; managed_variables_index_table* symbol_table; public: monomial_coefficient_table monomial_coefficient_table_; void visit(sentinel_node* node) override; exponent_vector_visitor& operator()(managed_variables_index_table& symbol_table) { this->symbol_table = &symbol_table; return *this; } void print() const { for (const auto& it : monomial_coefficient_table_) { const vector<unsigned int>& vec = it.first; const vector<shared_ptr<irtree_node>>& root_nodes = it.second; std::cout << "["; for (const auto& node : root_nodes) std::cout << node << " "; std::cout << "]: ["; for (const auto& itit : vec) std::cout << itit << " "; std::cout << "]" << std::endl; } } friend dispatcher; }; #endif // EXPONENT_VECTOR_VISITOR_H
c
14
0.597963
124
40.662791
172
research_code
<?php namespace App; use Illuminate\Database\Eloquent\Model; use App\Articulo; class tipo extends Model { public function articulos (){ // return $this->hasMany(evento::class); return $this->hasMany('App\articulo','tipo'); } // }
php
10
0.678295
47
15.125
16
starcoderdata
import { getSessionToken } from "/app/model/Session.js"; import { ajaxRequest } from "/app/model/Utils.js"; let observers = {} function notify() { for (const [observer, callback] of Object.entries(observers)) { callback() } } export function observePosts(object, callback) { observers[object] = callback; } export function stopObservePosts(object) { delete observers[object] } export function createTextPost(content, postRespond, onSuccess, onFailure) { content = content.trim() if (content == '') { return onFailure("Vous ne pouvez pas publier de post vide"); } ajaxRequest( "create-post", { sessionToken: getSessionToken(), postType: "text", postContent: newPost.value, postRespond: postRespond, }, respond => { if (respond.success) { onSuccess(); notify(); } else { onFailure(respond.message) } }); } export function createReaction(reaction, postId, onSuccess) { ajaxRequest( "create-reaction", { sessionToken: getSessionToken(), postId: postId, reaction: reaction, }, respond => { if (respond.success) { onSuccess(); } else { onFailure(respond.message) } }); }
javascript
14
0.547055
76
23.213115
61
starcoderdata
<?php /* * This file is part of the AppMigration package. * * (c) * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace DreadLabs\AppMigration; use DreadLabs\AppMigration\Exception\LockingException; /** * LockInterface * * @author */ interface LockInterface { /** * Acquires a lock * * @return void * * @throws LockingException If the lock is not acquirable */ public function acquire(); /** * Releases a lock * * @return void */ public function release(); }
php
6
0.625378
74
15.974359
39
starcoderdata
// Code generated from ./BODLParser.g4 by ANTLR 4.7.2. DO NOT EDIT. package bodlgo // BODLParser import "github.com/antlr/antlr4/runtime/Go/antlr" // BODLParserListener is a complete listener for a parse tree produced by BODLParser. type BODLParserListener interface { antlr.ParseTreeListener // EnterProgram is called when entering the program production. EnterProgram(c *ProgramContext) // EnterStatements is called when entering the statements production. EnterStatements(c *StatementsContext) // EnterImportStatement is called when entering the importStatement production. EnterImportStatement(c *ImportStatementContext) // EnterDefinitions is called when entering the definitions production. EnterDefinitions(c *DefinitionsContext) // EnterDefinition is called when entering the definition production. EnterDefinition(c *DefinitionContext) // EnterBlock is called when entering the block production. EnterBlock(c *BlockContext) // EnterItemList is called when entering the itemList production. EnterItemList(c *ItemListContext) // EnterElement is called when entering the element production. EnterElement(c *ElementContext) // EnterBoAction is called when entering the boAction production. EnterBoAction(c *BoActionContext) // EnterMessage is called when entering the message production. EnterMessage(c *MessageContext) // EnterNode is called when entering the node production. EnterNode(c *NodeContext) // EnterAssociation is called when entering the association production. EnterAssociation(c *AssociationContext) // EnterAssociationUsingDefinition is called when entering the associationUsingDefinition production. EnterAssociationUsingDefinition(c *AssociationUsingDefinitionContext) // EnterValuationDefinition is called when entering the valuationDefinition production. EnterValuationDefinition(c *ValuationDefinitionContext) // EnterValutaionExpressionList is called when entering the valutaionExpressionList production. EnterValutaionExpressionList(c *ValutaionExpressionListContext) // EnterValutaionExpression is called when entering the valutaionExpression production. EnterValutaionExpression(c *ValutaionExpressionContext) // EnterRaiseMessage is called when entering the raiseMessage production. EnterRaiseMessage(c *RaiseMessageContext) // EnterAnnotations is called when entering the annotations production. EnterAnnotations(c *AnnotationsContext) // EnterAnnotation is called when entering the annotation production. EnterAnnotation(c *AnnotationContext) // EnterTypeList is called when entering the typeList production. EnterTypeList(c *TypeListContext) // EnterTypeDeclaration is called when entering the typeDeclaration production. EnterTypeDeclaration(c *TypeDeclarationContext) // EnterTypeDefaultValue is called when entering the typeDefaultValue production. EnterTypeDefaultValue(c *TypeDefaultValueContext) // EnterValueAssignList is called when entering the valueAssignList production. EnterValueAssignList(c *ValueAssignListContext) // EnterValueAssign is called when entering the valueAssign production. EnterValueAssign(c *ValueAssignContext) // EnterMultiplicity is called when entering the multiplicity production. EnterMultiplicity(c *MultiplicityContext) // EnterMemberExpression is called when entering the memberExpression production. EnterMemberExpression(c *MemberExpressionContext) // EnterIdentifierList is called when entering the identifierList production. EnterIdentifierList(c *IdentifierListContext) // EnterKeyword is called when entering the keyword production. EnterKeyword(c *KeywordContext) // EnterLiteral is called when entering the literal production. EnterLiteral(c *LiteralContext) // EnterComments is called when entering the comments production. EnterComments(c *CommentsContext) // EnterCompareOperator is called when entering the compareOperator production. EnterCompareOperator(c *CompareOperatorContext) // EnterLogicOperator is called when entering the logicOperator production. EnterLogicOperator(c *LogicOperatorContext) // EnterIdentifier is called when entering the identifier production. EnterIdentifier(c *IdentifierContext) // ExitProgram is called when exiting the program production. ExitProgram(c *ProgramContext) // ExitStatements is called when exiting the statements production. ExitStatements(c *StatementsContext) // ExitImportStatement is called when exiting the importStatement production. ExitImportStatement(c *ImportStatementContext) // ExitDefinitions is called when exiting the definitions production. ExitDefinitions(c *DefinitionsContext) // ExitDefinition is called when exiting the definition production. ExitDefinition(c *DefinitionContext) // ExitBlock is called when exiting the block production. ExitBlock(c *BlockContext) // ExitItemList is called when exiting the itemList production. ExitItemList(c *ItemListContext) // ExitElement is called when exiting the element production. ExitElement(c *ElementContext) // ExitBoAction is called when exiting the boAction production. ExitBoAction(c *BoActionContext) // ExitMessage is called when exiting the message production. ExitMessage(c *MessageContext) // ExitNode is called when exiting the node production. ExitNode(c *NodeContext) // ExitAssociation is called when exiting the association production. ExitAssociation(c *AssociationContext) // ExitAssociationUsingDefinition is called when exiting the associationUsingDefinition production. ExitAssociationUsingDefinition(c *AssociationUsingDefinitionContext) // ExitValuationDefinition is called when exiting the valuationDefinition production. ExitValuationDefinition(c *ValuationDefinitionContext) // ExitValutaionExpressionList is called when exiting the valutaionExpressionList production. ExitValutaionExpressionList(c *ValutaionExpressionListContext) // ExitValutaionExpression is called when exiting the valutaionExpression production. ExitValutaionExpression(c *ValutaionExpressionContext) // ExitRaiseMessage is called when exiting the raiseMessage production. ExitRaiseMessage(c *RaiseMessageContext) // ExitAnnotations is called when exiting the annotations production. ExitAnnotations(c *AnnotationsContext) // ExitAnnotation is called when exiting the annotation production. ExitAnnotation(c *AnnotationContext) // ExitTypeList is called when exiting the typeList production. ExitTypeList(c *TypeListContext) // ExitTypeDeclaration is called when exiting the typeDeclaration production. ExitTypeDeclaration(c *TypeDeclarationContext) // ExitTypeDefaultValue is called when exiting the typeDefaultValue production. ExitTypeDefaultValue(c *TypeDefaultValueContext) // ExitValueAssignList is called when exiting the valueAssignList production. ExitValueAssignList(c *ValueAssignListContext) // ExitValueAssign is called when exiting the valueAssign production. ExitValueAssign(c *ValueAssignContext) // ExitMultiplicity is called when exiting the multiplicity production. ExitMultiplicity(c *MultiplicityContext) // ExitMemberExpression is called when exiting the memberExpression production. ExitMemberExpression(c *MemberExpressionContext) // ExitIdentifierList is called when exiting the identifierList production. ExitIdentifierList(c *IdentifierListContext) // ExitKeyword is called when exiting the keyword production. ExitKeyword(c *KeywordContext) // ExitLiteral is called when exiting the literal production. ExitLiteral(c *LiteralContext) // ExitComments is called when exiting the comments production. ExitComments(c *CommentsContext) // ExitCompareOperator is called when exiting the compareOperator production. ExitCompareOperator(c *CompareOperatorContext) // ExitLogicOperator is called when exiting the logicOperator production. ExitLogicOperator(c *LogicOperatorContext) // ExitIdentifier is called when exiting the identifier production. ExitIdentifier(c *IdentifierContext) }
go
8
0.827108
102
37.671498
207
starcoderdata
#include #include #include "element.h" #include "util.h" void addel(Elements *e, const char *s) { if(e->n == 0) { if(e->el == 0) e->el = emalloc(sizeof(char *)); } else e->el = erealloc(e->el, (e->n + 1) * sizeof(char *)); e->n++; e->el[e->n - 1] = emalloc(strlen(s) + 1); strcpy(e->el[e->n - 1], s); } void rmel(Elements *e) { if(e->n == 0) return; free(e->el[e->n - 1]); e->n--; if(e->n == 0) { free(e->el); e->el = 0; return; } e->el = erealloc(e->el, e->n * sizeof(char*)); } char * curel(Elements *e) { return e->el[e->n - 1]; } int isin(Elements *e, char *s) { int i; for(i = 0; i < e->n; i++) { if(strcmp(e->el[i], s) == 0) return 1; } return 0; }
c
13
0.501389
55
13.117647
51
starcoderdata
@Nonnull @ReturnsMutableCopy public MappedValueList getSwappedSourceAndDest () { // Ctor with mapping function return new MappedValueList (new CommonsArrayList <> (m_aList, MappedValue::getSwappedSourceAndDest)); }
java
9
0.76087
105
32
7
inline
#ifndef BLOOM_FILTER_H #define BLOOM_FILTER_H #include typedef struct { int hash_count; int arr_len; bool *bit_array; } bloom_filter_t; bloom_filter_t *bloom_filter_create( int elem_count, float false_positive_probability); void bloom_filter_add(bloom_filter_t *filter, char *s); bool bloom_filter_might_contain(bloom_filter_t *filter, char *s); void bloom_filter_destroy(bloom_filter_t *filter); #endif
c
7
0.713996
65
20.434783
23
starcoderdata
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; #define ii pair<int,int> #define ll long long #define pll pair<ll,ll> #define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> #define iiordered_set tree<pll, null_type,less<pll>, rb_tree_tag,tree_order_statistics_node_update> using namespace std; #define MOD (1000*1000*1000+7) ll power(ll a,ll b, ll m=MOD) { ll res=1; while(b>0) { if(b&1) res=(res*a)%MOD; a=(a*a)%MOD; b>>=1; } return res; } ll inverse(ll a,ll m=MOD) { return power(a,m-2,m); } int ceil(int a,int b) { return (a+b-1)/b; } #define INFl (1e18+5) #define vi vector<int> #define vvi vector<vi> #define vl vector<long long> #define vvl vector<vl> #define vll vector<pll> #define vii vector<ii> #define vvii vector<vii> #define tri pair<int,ii> #define F first #define S second #define forl(i,n) for(int i=0;i<n;i++) #define fore(i,n) for(int i=1;i<=n;i++) #define rforl(i,n) for(int i=n-1;i>=0;i--) #define rfore(i,n) for(int i=n;i>=1;i--) #define CASE(t) cout<<"Case #"<<(t)<<": "; #define INF 1020000000 #define gcd(a,b) __gcd(a,b) #define all(x) x.begin(),x.end() #define mp make_pair #define pb push_back #define print(x) for(auto it=x.begin();it!=x.end();it++) cout<<*it<<' '; cout<<endl; #define printii(x) for(auto it=x.begin();it!=x.end();it++) cout<<it->F<<' '<<it->S<<endl; #define fastio ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL) int main() { int n,m; cin>>n>>m; if(n==m) cout<<"Yes"<<endl; else cout<<"No"<<endl; }
c++
11
0.626341
99
25.234375
64
codenet
package com.haulmont.sampler.web.ui.components.codeeditor.mode; import com.haulmont.cuba.gui.components.HasValue; import com.haulmont.cuba.gui.components.HighlightMode; import com.haulmont.cuba.gui.components.LookupField; import com.haulmont.cuba.gui.components.SourceCodeEditor; import com.haulmont.cuba.gui.components.SourceCodeEditor.Mode; import com.haulmont.cuba.gui.screen.ScreenFragment; import com.haulmont.cuba.gui.screen.Subscribe; import com.haulmont.cuba.gui.screen.UiController; import com.haulmont.cuba.gui.screen.UiDescriptor; import javax.inject.Inject; import java.util.HashMap; import java.util.Map; @UiController("mode-codeeditor") @UiDescriptor("mode-codeeditor.xml") public class ModeCodeEditorSample extends ScreenFragment { @Inject private SourceCodeEditor codeEditor; @Inject private LookupField modeField; @Subscribe protected void onInit(InitEvent event) { Map<String, HighlightMode> modes = new HashMap<>(); for (HighlightMode mode : Mode.values()) { modes.put(mode.toString(), mode); } modeField.setOptionsMap(modes); modeField.setValue(codeEditor.getMode()); } @Subscribe("modeField") protected void onModeFieldValueChange(HasValue.ValueChangeEvent event) { if (event.getValue() != null) { codeEditor.setMode(event.getValue()); } } }
java
14
0.751285
137
35.209302
43
starcoderdata
MetadataItemPropertiesPanel::MetadataItemPropertiesPanel( MetadataItemPropertiesFrame* parent, MetadataItem* object) : wxPanel(parent, wxID_ANY), pageTypeM(ptSummary), objectM(object), htmlReloadRequestedM(false) { wxASSERT(object); mipPanels.push_back(this); html_window = new PrintableHtmlWindow(this, wxID_ANY); parent->SetTitle(object->getName_()); wxBoxSizer* bSizer2 = new wxBoxSizer( wxVERTICAL ); bSizer2->Add(html_window, 1, wxEXPAND, 0 ); SetSizer( bSizer2 ); Layout(); wxAcceleratorEntry entries[4]; entries[0].Set(wxACCEL_CMD, (int) 'W', wxID_CLOSE_FRAME); entries[1].Set(wxACCEL_CMD, (int) 'R', wxID_REFRESH); // MSW only entries[2].Set(wxACCEL_CTRL, WXK_F4, wxID_CLOSE_FRAME); entries[3].Set(wxACCEL_NORMAL, WXK_F5, wxID_REFRESH); bool isMSW = (wxPlatformInfo::Get().GetOperatingSystemId() & wxOS_WINDOWS) != 0; wxAcceleratorTable acct(isMSW ? 4 : 2, entries); SetAcceleratorTable(acct); Connect(wxID_CLOSE_FRAME, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MetadataItemPropertiesPanel::OnCloseFrame)); Connect(wxID_ANY, wxEVT_COMMAND_HTML_CELL_HOVER, wxHtmlCellEventHandler(MetadataItemPropertiesPanel::OnHtmlCellHover)); Connect(wxID_REFRESH, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MetadataItemPropertiesPanel::OnRefresh)); // request initial rendering requestLoadPage(true); objectM->attachObserver(this, true); }
c++
12
0.707805
78
37.461538
39
inline
#include #include "view/IMLoginWidget.h" #include "view/IMMainWidget.h" #include "view/IMChatWidget.h" #include #include #include "view/IMInformationWidget.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); // 以下部分解决中文乱码 QTextCodec::setCodecForTr(QTextCodec::codecForName("utf-8")); QTextCodec::setCodecForLocale(QTextCodec::codecForName("utf-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForName("utf-8")); // 以上部分解决中文乱码 IMLoginWidget w; w.show(); if (true == w.getIsAutoLogin()) { qDebug() << "click"; w.onClickBtnLogin(); } UserInformation me; IMMainWidget mw(me); mw.show(); ChatInformation in; IMChatWidget chat(in); chat.show(); // IMInformationWidget w; // w.setReadOnly(true, true); // w.show(); return a.exec(); }
c++
9
0.649944
71
22
39
starcoderdata
package com.github.rolandhe.thrift.enhancer.translator.pojo; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; /** * @author rolandhe */ @JacksonXmlRootElement(localName="getStyle_result") public class PojoGetStyleResult { public PojoAdStyle getSuccess() { return success; } public void setSuccess(PojoAdStyle success) { this.success = success; } private PojoAdStyle success; }
java
7
0.766529
77
20.043478
23
starcoderdata
/* eslint-disable no-useless-escape */ const _ = require('lodash'); /* So basically we need to apply all of the `conditions` to item, if it pass return it. */ const applyConditionalOperators = (params, item, conditions) => { /* How about first you take care of = and make sure your test still passes? */ const { ExpressionAttributeNames: attributeNames, ExpressionAttributeValues: attributeValues } = params; const checkCondition = { /* Behavior for Conditional Operator begins_with */ begins_with: { check: (doc, match, exprNames, exprValues) => { /* Step 1 - parse the expression value and name from `match` */ /* example match: 'begins_with(#complex_field, :v_state)'*/ match = match.replace(' ', ''); match = match.replace('begins_with(', ''); match = match.replace(')', ''); match = match.split(','); /* Check to see if we need to do a attribute lookup */ let exprName = match[0]; if (exprName[0] === '#') { exprName = exprNames[exprName]; } let exprVal = match[1]; exprVal = exprValues[exprVal]; /* Check if conditions satisfied on doc - return True/False */ return doc[exprName].startsWith(exprVal); } }, /* Behavior for Conditional Operator BETWEEN */ between: { check: (doc, match, exprNames, exprValues) => { /* Example match: '#complex_field between :v_start and :v_stop' */ match = match.split('between'); /* Grab the field we'll be searching on. */ let exprName = match[0].replace(' ', ''); if (exprName[0] === '#') { exprName = exprNames[exprName]; } /* We need to grab the two values we're BETWEEN */ const exprValue = match[1].split('and'); /* Lower bounds. */ let exprLow = exprValue[0].replace(/\s+/g, ''); exprLow = exprValues[exprLow]; /* Upper bounds. */ let exprHigh = exprValue[1].replace(/\s+/g, ''); exprHigh = exprValues[exprHigh]; /* Check if conditions satisfied on doc - return True/False */ return ((doc[exprName] <= exprHigh) && (doc[exprName] >= exprLow)); } }, /* Behavior for Conditional Operator = */ '=': { check: (doc, match, exprNames, exprValues) => { /* We dont want no stinking spaces. */ match = match.replace(/\s+/g, ''); match = match.split('='); let exprName = match[0]; if (exprName[0] === '#') { exprName = exprNames[exprName]; } let exprValue = match[1]; exprValue = exprValues[exprValue]; /* Check if conditions satisfied on doc - return True/False */ return (doc[exprName] === exprValue); } }, '>': { check: (doc, match, exprNames, exprValues) => { /* We dont want no stinking spaces. */ match = match.replace(/\s+/g, ''); match = match.split('>'); let exprName = match[0]; if (exprName[0] === '#') { exprName = exprNames[exprName]; } let exprValue = match[1]; exprValue = exprValues[exprValue]; /* Check if conditions satisfied on doc - return True/False */ return (doc[exprName] > exprValue); } }, '>=': { check: (doc, match, exprNames, exprValues) => { /* We dont want no stinking spaces. */ match = match.replace(/\s+/g, ''); match = match.split('>='); let exprName = match[0]; if (exprName[0] === '#') { exprName = exprNames[exprName]; } let exprValue = match[1]; exprValue = exprValues[exprValue]; /* Check if conditions satisfied on doc - return True/False */ return (doc[exprName] >= exprValue); } }, '<': { check: (doc, match, exprNames, exprValues) => { /* We dont want no stinking spaces. */ match = match.replace(/\s+/g, ''); match = match.split('<'); let exprName = match[0]; if (exprName[0] === '#') { exprName = exprNames[exprName]; } let exprValue = match[1]; exprValue = exprValues[exprValue]; /* Check if conditions satisfied on doc - return True/False */ return (doc[exprName] < exprValue); } } }; // Assume ANDs for implementation return _.every(conditions, ({ matches, key }) => _.every(matches, (requiredConditionMatch) => checkCondition[key].check(item, requiredConditionMatch, attributeNames, attributeValues) )); }; module.exports = ((dynamoInstance, params, table) => { /* Sadly we don't even support less than equals to and what not yet - but using regex we can easily XD. */ const regexConditions = { '=': { expression: /#?[a-zA-Z\_]+ = :?[0-9a-zA-Z\_\-]+/g, matches: [] }, '<': { expression: /#?[a-zA-Z\_]+ < :?[0-9a-zA-Z\_\-]+/, matches: [] }, '>': { expression: /#?[a-zA-Z\_]+ > :?[0-9a-zA-Z\_\-]+/, matches: [] }, '>=': { expression: /#?[a-zA-Z\_]+ >= :?[0-9a-zA-Z\_\-]+/, matches: [] }, begins_with: { expression: /begins_with\(#?[a-zA-z\_]+,[ ]?:?[a-zA-Z\_]+\)/, matches: [] }, between: { expression: /#?[a-zA-z]+ between :[a-zA-Z\_]+ [aA][nN][dD] :[a-zA-z\_]+/, matches: [] } }; const { KeyConditionExpression: conditions, Select: selectValue, AttributesToGet: attributesToGet } = params; const conditionsToUse = _(regexConditions) .map(({ expression }, key) => _.merge({ key }, { matches: conditions.match(expression) })) .filter(({ matches }) => !_.isNull(matches)) .value(); const queryResults = _(dynamoInstance.context[table]) /* Looping through each entry in the table... lets go ahead and check if it matches our conditions? */ .filter((item) => applyConditionalOperators(params, item, conditionsToUse)) .value(); const querySelect = _.isUndefined(selectValue) ? 'ALL_ATTRIBUTES' : selectValue; switch (querySelect) { case 'ALL_ATTRIBUTES': case 'ALL_PROJECTED_ATTRIBUTES': // for now until implemented return { Count: _.size(queryResults), Items: queryResults }; case 'SPECIFIC_ATTRIBUTES': return { Count: _.size(queryResults), Items: _.map(queryResults, (item) => _.pick(item, attributesToGet || [])) }; case 'COUNT': return { Count: _.size(queryResults) }; default: throw new Error('Invalid Select value'); } });
javascript
21
0.474605
110
34.957746
213
starcoderdata
// Copyright 2019 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 CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_EXTERNAL_CONNECTOR_IMPL_H_ #define CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_EXTERNAL_CONNECTOR_IMPL_H_ #include #include #include #include "base/callback.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/sequence_checker.h" #include "chromecast/external_mojo/external_service_support/external_connector.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/remote.h" namespace chromecast { namespace external_service_support { class ExternalConnectorImpl : public ExternalConnector { public: explicit ExternalConnectorImpl(const std::string& broker_path); explicit ExternalConnectorImpl( const std::string& broker_path, mojo::PendingRemote connector_pending_remote); ~ExternalConnectorImpl() override; // ExternalConnector implementation: std::unique_ptr AddConnectionErrorCallback(base::RepeatingClosure callback) override; void RegisterService(const std::string& service_name, ExternalService* service) override; void RegisterService( const std::string& service_name, mojo::PendingRemote service_remote) override; void BindInterface(const std::string& service_name, const std::string& interface_name, mojo::ScopedMessagePipeHandle interface_pipe, bool async = true) override; std::unique_ptr Clone() override; void SendChromiumConnectorRequest( mojo::ScopedMessagePipeHandle request) override; void QueryServiceList( base::OnceCallback< void(std::vector< chromecast::external_mojo::mojom::ExternalServiceInfoPtr>)> callback) override; private: void BindInterfaceImmediately(const std::string& service_name, const std::string& interface_name, mojo::ScopedMessagePipeHandle interface_pipe); void OnMojoDisconnect(); bool BindConnectorIfNecessary(); void InitializeBrokerConnection(); void AttemptBrokerConnection(); std::string broker_path_; mojo::Remote connector_; base::CallbackList error_callbacks_; // If connecting to a broker, |connector_pending_receiver_for_broker_| is used // to keep |connector_| bound while waiting for the broker. mojo::PendingReceiver connector_pending_receiver_for_broker_; // If cloned, |connector_pending_remote_from_clone_| is stored until an IO // operation is performed to ensure it happens on the correct sequence. mojo::PendingRemote connector_pending_remote_from_clone_; SEQUENCE_CHECKER(sequence_checker_); base::WeakPtrFactory weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ExternalConnectorImpl); }; } // namespace external_service_support } // namespace chromecast #endif // CHROMECAST_EXTERNAL_MOJO_EXTERNAL_SERVICE_SUPPORT_EXTERNAL_CONNECTOR_IMPL_H_
c
16
0.731245
87
37.655556
90
starcoderdata
<?php class MetadataName { const Title = "title"; const Columns = "columns"; const ColumnDescription = "column-descriptions"; const TableClasses = "table-classes"; const Rows = "rows"; const Value = "value"; const ClassName = "class"; const Inherit = "inherit"; const Data = "data"; const Name = "name"; const TID = "tid"; const PID = "pid"; const ID = "id"; const Unit = "unit"; const Results = "results"; const TimeRange = "time-range"; const Begin = "begin"; const End = "end"; }
php
6
0.625239
50
21.782609
23
starcoderdata
/****************************************************************************** @file sm_ecc.c @brief This file contains the SM ECC Event for P-256 and Diffie-Hellman keys When a network processor is used. Group: WCS, BTS Target Device: CC2640R2 ****************************************************************************** Copyright (c) 2011-2016, Texas Instruments Incorporated All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Texas Instruments Incorporated nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ****************************************************************************** Release Name: ti-ble-3.0-stack-sdk_3_00_00 Release Date: 2016-12-21 12:44:48 *****************************************************************************/ #include "bcomdef.h" #include "osal.h" #include "hci.h" #include "sm.h" #include "rom_jt.h" /********************************************************************* * MACROS */ /********************************************************************* * CONSTANTS */ /********************************************************************* * GLOBAL VARIABLES */ #if defined(BLE_V42_FEATURES) && (BLE_V42_FEATURES & SECURE_CONNS_CFG) #if defined(HCI_TL_FULL) // Application Task ID. Used to send ECC Key events when an network processor // application task is registered to do so. extern uint8 SM_appTaskID; #endif //(HCI_TL_FULL) #endif //(BLE_V42_FEATURES & SECURE_CONNS_CFG) /********************************************************************* * EXTERNAL VARIABLES */ /********************************************************************* * EXTERNAL FUNCTIONS */ /********************************************************************* * LOCAL VARIABLES */ /********************************************************************* * LOCAL FUNCTION PROTOTYPES */ /********************************************************************* * CALLBACKS */ /********************************************************************* * API FUNCTIONS */ /********************************************************************* * @fn SM_p256KeyCB * * @brief Read P-256 Key Event Callback from the Controller. The secret key * used to generate the public key pair is also input here. * * @params pK - pointer to HCI BLE Read P256 Public Key Complete struct * which contain the X and Y Coordinates of the ECC Public * Keys. * * @param privateKey - the private key used to generated the ECC Public Keys. * * @return None */ void SM_p256KeyCB( hciEvt_BLEReadP256PublicKeyComplete_t *pK, uint8 *privateKey ) { #if defined(BLE_V42_FEATURES) && (BLE_V42_FEATURES & SECURE_CONNS_CFG) #if defined(HCI_TL_FULL) smEccKeysEvt_t *eccKeys; eccKeys = (smEccKeysEvt_t *)MAP_osal_msg_allocate( sizeof (smEccKeysEvt_t) ); if ( eccKeys ) { eccKeys->hdr.event = SM_MSG_EVENT; eccKeys->hdr.status = pK->status; eccKeys->opcode = SM_ECC_KEYS_EVENT; // If key generation was successful if (pK->status == SUCCESS) { MAP_osal_memcpy( eccKeys->privateKey, privateKey, SM_ECC_KEY_LEN ); MAP_osal_memcpy( eccKeys->publicKeyX, pK->p256Key, SM_ECC_KEY_LEN ); MAP_osal_memcpy( eccKeys->publicKeyY, &pK->p256Key[SM_ECC_KEY_LEN], SM_ECC_KEY_LEN ); } // Send to app. MAP_osal_msg_send( SM_appTaskID, (uint8 *)eccKeys ); } #endif //(HCI_TL_FULL) #endif //(BLE_V42_FEATURES & SECURE_CONNS_CFG) } /********************************************************************* * @fn SM_dhKeyCB * * @brief BLE Generate Diffie-Hellman Key Event Callback from the controller. * * @params - pointer to HCI BLE Read P256 Public Key Complete struct * which contain the X and Y Coordinates of the ECC Public * Keys. * * @param pDhKey - the Diffie-Hellman X and Y Coordinates output from the * ECDH operation. * * @return None */ void SM_dhKeyCB( hciEvt_BLEGenDHKeyComplete_t *pDhKey ) { #if defined(BLE_V42_FEATURES) && (BLE_V42_FEATURES & SECURE_CONNS_CFG) #if defined(HCI_TL_FULL) smDhKeyEvt_t *dhKey; dhKey = (smDhKeyEvt_t *)MAP_osal_msg_allocate( sizeof (smDhKeyEvt_t) ); if ( dhKey ) { dhKey->hdr.event = SM_MSG_EVENT; dhKey->hdr.status = pDhKey->status; dhKey->opcode = SM_DH_KEY_EVENT; if ( pDhKey->status == SUCCESS ) { MAP_osal_memcpy( dhKey->dhKey,pDhKey->dhKey, SM_ECC_KEY_LEN ); } MAP_osal_msg_send( SM_appTaskID, (uint8 *)dhKey ); } #endif //(HCI_TL_FULL) #endif //(BLE_V42_FEATURES & SECURE_CONNS_CFG) } /********************************************************************* *********************************************************************/
c
15
0.549314
81
32.87027
185
starcoderdata
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Windows.Forms; namespace RSoft.Componenets.WinForm { [ToolboxItem(true)] public class CircularProgressBar : Label { private System.Windows.Forms.Timer _Tmr; private int _MaxValue = 100; private int _Value = 0; public int ProgressBorder { get; set; } = 3; private Color _ProgressColor = Color.Red; private Color _ProgressBackColor = Color.LightGray; public override ContentAlignment TextAlign => ContentAlignment.MiddleCenter; public override Color ForeColor => _ProgressColor; private int _LoadingPosition = 0; private int LoadingPosition { get { return _LoadingPosition >= 360 ? _LoadingPosition = 0 : ++_LoadingPosition; } } public int MaxValue { get { return _MaxValue; } set { _MaxValue = value; Refresh(); } } public int Value { get { return _Value; } set { _Value = value; Refresh(); if (_Value == _MaxValue || _Value == 0) _Tmr.Stop(); else _Tmr.Start(); } } public Color ProgressColor { get { return _ProgressColor; } set { _ProgressColor = value; Refresh(); } } public Color ProgressBackColor { get { return _ProgressBackColor; } set { _ProgressBackColor = value; Refresh(); } } public CircularProgressBar() { _Tmr = new System.Windows.Forms.Timer(); _Tmr.Interval = 50; _Tmr.Tick += Tmr_Tick; } private void Tmr_Tick(object sender, EventArgs e) { Refresh(); } protected override void OnPaint(PaintEventArgs e) { Rectangle rec = new Rectangle(5, 5, Width - 10, Height - 10); e.Graphics.DrawArc(new Pen(_ProgressBackColor, ProgressBorder), rec, 90, 360); e.Graphics.DrawArc(new Pen(_ProgressColor, ProgressBorder), rec, 0 + LoadingPosition, 360 * ((float)Value / (float)MaxValue)); Text = string.Concat("%", 100 * ((float)_Value / (float)_MaxValue)); base.OnPaint(e); } } }
c#
16
0.464868
95
23.896552
116
starcoderdata
inline RealType quantile(const kolmogorov_smirnov_distribution<RealType, Policy>& dist, const RealType& p) { BOOST_MATH_STD_USING static const char* function = "boost::math::quantile(const kolmogorov_smirnov_distribution<%1%>&, %1%)"; // Error check: RealType error_result; RealType n = dist.number_of_observations(); if(false == detail::check_probability(function, p, &error_result, Policy())) return error_result; if(false == detail::check_df(function, n, &error_result, Policy())) return error_result; RealType k = detail::kolmogorov_smirnov_quantile_guess(p) / sqrt(n); const int get_digits = policies::digits<RealType, Policy>();// get digits from policy, std::uintmax_t m = policies::get_max_root_iterations<Policy>(); // and max iterations. return tools::newton_raphson_iterate(detail::kolmogorov_smirnov_quantile_functor<RealType, Policy>(dist, p), k, RealType(0), boost::math::tools::max_value<RealType>(), get_digits, m); }
c++
13
0.698589
111
51.263158
19
inline
namespace OneAPIDotNet.VPL { /// /// This enum itemizes hardware acceleration stack to use. /// public enum MfxAccelerationMode { /// /// Hardware acceleration is not applicable. /// NotApplicable = 0, /// /// Hardware acceleration goes through the Microsoft* Direct3D9* infrastructure. /// ViaDirect3D9 = 0x0200, /// /// Hardware acceleration goes through the Microsoft* Direct3D11* infrastructure. /// ViaDirect3D11 = 0x0300, /// /// Hardware acceleration goes through the Linux* VA-API infrastructure. /// ViaVAAPI = 0x0400, /// /// Hardware acceleration goes through the Linux* VA-API infrastructure with DRM RENDER MODE as default acceleration access point. /// ViaVAAPIDRMRenderMode = ViaVAAPI, /// /// Hardware acceleration goes through the Linux* VA-API infrastructure with DRM MODESET as default acceleration access point. /// ViaVAAPIDRMModeSet = 0x0401, /// /// Hardware acceleration goes through the Linux* VA-API infrastructure with OpenGL Extension to the X Window System as default acceleration access point. /// ViaVAAPIGLX = 0x0402, /// /// Hardware acceleration goes through the Linux* VA-API infrastructure with X11 as default acceleration access point. /// ViaVAAPIX11 = 0x0403, /// /// Hardware acceleration goes through the Linux* VA-API infrastructure with Wayland as default acceleration access point. /// ViaVAAPIWayland = 0x0404, /// /// Hardware acceleration goes through the HDDL* Unite*. /// ViaHDDLUnite = 0x0500 } }
c#
7
0.596117
162
31.571429
63
starcoderdata
const expect = chai.expect; describe("Form validation", function () { describe("when form is blank", function () { before(function () { const form = document.querySelector("#searchForm"); const event = new window.Event("submit"); form.dispatchEvent(event); }); after(function () { const error = document.querySelector("#searchError"); const form = document.querySelector("#searchForm"); if (error) { form.removeChild(error); } }); it('should create error element with id "searchError"', function () { const error = document.querySelector("#searchError"); expect(error).to.not.be.null; }); it('should create error element with class named "error"', function () { const error = document.querySelector("#searchError"); expect(error.className).to.equal("error"); }); it('should create error element with text "Please enter a search term"', function () { const error = document.querySelector("#searchError"); expect(error.innerHTML).to.equal("Please enter a search term"); }); }); describe("when form contains only whitespace", function () { before(function () { const form = document.querySelector("#searchForm"); const searchInput = document.querySelector("#searchTerm"); searchInput.value = " "; const event = new window.Event("submit"); form.dispatchEvent(event); }); after(function () { const error = document.querySelector("#searchError"); const form = document.querySelector("#searchForm"); if (error) { form.removeChild(error); } }); it('should create error element with id "searchError"', function () { const error = document.querySelector("#searchError"); expect(error).to.not.be.null; }); it('should create error element with class named "error"', function () { const error = document.querySelector("#searchError"); expect(error.className).to.equal("error"); }); it('should create error element with text "Please enter a search term"', function () { const error = document.querySelector("#searchError"); expect(error.innerHTML).to.equal("Please enter a search term"); }); }); }); describe("Search function", function () { describe("when the search term is not found", function () { before(function () { const form = document.querySelector("#searchForm"); const searchInput = document.querySelector("#searchTerm"); searchInput.value = "gumdrop"; const event = new window.Event("submit"); form.dispatchEvent(event); }); after(function () { const articles = document.querySelectorAll("article"); for (let article of articles) { article.classList.remove("hidden"); } const searchInput = document.querySelector("#searchTerm"); searchInput.value = ""; }); it("should not display an error message", function () { const error = document.querySelector("#searchError"); expect(error).to.be.null; }); it("should display no articles", function () { const hiddenArticles = document.querySelectorAll(".hidden"); expect(hiddenArticles.length).to.equal(8); }); }); describe("when the search term is found", function () { before(function () { const form = document.querySelector("#searchForm"); const searchInput = document.querySelector("#searchTerm"); searchInput.value = "Art"; const event = new window.Event("submit"); form.dispatchEvent(event); }); after(function () { const articles = document.querySelectorAll("article"); for (let article of articles) { article.classList.remove("hidden"); } const searchInput = document.querySelector("#searchTerm"); searchInput.value = ""; }); it("should not display an error message", function () { const error = document.querySelector("#searchError"); expect(error).to.be.null; }); it("should display articles partially containing the search term", function () { const shownArticles = document.querySelectorAll("article:not(.hidden)"); expect(shownArticles.length).to.equal(4); }); it("should hide articles not partially containing the search term", function () { const hiddenArticles = document.querySelectorAll(".hidden"); expect(hiddenArticles.length).to.equal(4); }); }); describe("when the search term case is different", function () { before(function () { const form = document.querySelector("#searchForm"); const searchInput = document.querySelector("#searchTerm"); searchInput.value = "art"; const event = new window.Event("submit"); form.dispatchEvent(event); }); after(function () { const articles = document.querySelectorAll("article"); for (let article of articles) { article.classList.remove("hidden"); } const searchInput = document.querySelector("#searchTerm"); searchInput.value = ""; }); it("should not display an error message", function () { const error = document.querySelector("#searchError"); expect(error).to.be.null; }); it("should display articles partially containing the search term", function () { const shownArticles = document.querySelectorAll("article:not(.hidden)"); expect(shownArticles.length).to.equal(4); }); it("should hide articles not partially containing the search term", function () { const hiddenArticles = document.querySelectorAll(".hidden"); expect(hiddenArticles.length).to.equal(4); }); }); });
javascript
23
0.641165
90
33.331325
166
starcoderdata
package ch.protonmail.vladyslavbond.quizzing.controllers; public final class Exams extends Controller { // TODO }
java
6
0.768595
57
16.285714
7
starcoderdata
package de.lksbhm.mona; import de.lksbhm.gdx.platforms.AbstractPlatform; import de.lksbhm.gdx.util.GregorianCalendarInterface; public abstract class MonaPlatform extends AbstractPlatform { /** * * How to implement: Retrieve the localized year, month and day at the time * this method is called. Then interpret those as a date in GMT timezone and * retrieve the milliseconds of that date at 0:00am. Build a * {@link GregorianCalendarInterface} from the information you just received * (day, month, year, millis) and set its timezone to "GMT" * * @return */ public abstract GregorianCalendarInterface getToday(); public abstract String formatCalendarLocalized( GregorianCalendarInterface calendar, String formatString); public abstract String formatInt2Digits(int i); public abstract String getLineSeparator(); }
java
7
0.773697
77
32.76
25
starcoderdata
package io.rxmicro.examples.rest.client.headers; import io.rxmicro.rest.client.RestClientConfig; import io.rxmicro.rest.client.detail.AbstractRestClient; import io.rxmicro.rest.client.detail.HeaderBuilder; import io.rxmicro.rest.client.detail.HttpClient; import io.rxmicro.rest.client.detail.HttpResponse; import java.util.concurrent.CompletableFuture; import static io.rxmicro.rest.client.detail.ErrorResponseCheckerHelper.throwExceptionIfNotSuccess; /** * Generated by {@code RxMicro Annotation Processor} */ public final class $$ComplexStaticHeadersRestClient extends AbstractRestClient implements ComplexStaticHeadersRestClient { private final HttpClient client; private final RestClientConfig config; public $$ComplexStaticHeadersRestClient(final HttpClient client, final RestClientConfig config) { this.client = client; this.config = config; } @Override public CompletableFuture get1() { final HeaderBuilder headerBuilder = new HeaderBuilder(); headerBuilder.add("Parent-Header2", "new-Parent-Header2-value"); headerBuilder.add("Parent-Header2", "new-Parent-Header2-value"); headerBuilder.add("Parent-Header1", "new-Parent-Header1-value"); final CompletableFuture response = client .sendAsync("GET", "/get1", headerBuilder.build()) .handle(throwExceptionIfNotSuccess()); return response .thenApply(resp -> null); } @Override public CompletableFuture get2() { final HeaderBuilder headerBuilder = new HeaderBuilder(); headerBuilder.add("Parent-Header2", "new-Parent-Header2-value"); headerBuilder.add("Parent-Header2", "new-Parent-Header2-value"); headerBuilder.add("Parent-Header1", "new-Parent-Header1-value"); headerBuilder.add("Child-Header2", "new-Child-Header2-value"); headerBuilder.add("Child-Header2", "new-Child-Header2-value"); headerBuilder.add("Child-Header1", "new-Child-Header1-value"); final CompletableFuture response = client .sendAsync("GET", "/get2", headerBuilder.build()) .handle(throwExceptionIfNotSuccess()); return response .thenApply(resp -> null); } @Override public CompletableFuture get3() { final HeaderBuilder headerBuilder = new HeaderBuilder(); headerBuilder.add("Parent-Header2", "new-Child-Parent-Header2-value"); headerBuilder.add("Parent-Header1", "new-Child-Parent-Header1-value"); final CompletableFuture response = client .sendAsync("GET", "/get3", headerBuilder.build()) .handle(throwExceptionIfNotSuccess()); return response .thenApply(resp -> null); } @Override public CompletableFuture get4() { final HeaderBuilder headerBuilder = new HeaderBuilder(); headerBuilder.add("Parent-Header2", "new-Parent-Header2-value"); headerBuilder.add("Parent-Header2", "new-Parent-Header2-value"); headerBuilder.add("Parent-Header2", "new-Child-Parent-Header2-value"); headerBuilder.add("Parent-Header1", "new-Parent-Header1-value"); headerBuilder.add("Parent-Header1", "new-Child-Parent-Header1-value"); final CompletableFuture response = client .sendAsync("GET", "/get4", headerBuilder.build()) .handle(throwExceptionIfNotSuccess()); return response .thenApply(resp -> null); } }
java
12
0.673704
122
42.939759
83
starcoderdata
<?php namespace App\HTTP\Controllers; use App\Libraries\ControllerMother; use App\Libraries\Cookie; use App\Libraries\HPML; use App\Libraries\Packages\AngularStrong; use App\Libraries\Request; use App\Libraries\Session; class MainController extends ControllerMother { public function index(Request $request) { /*$view = new AngularStrong('index'); return $view->bind('yourName', 'Artin')->bind('test', 'kdasd')->bind('listof', [ [ 'title' => 'Item 1', 'show' => true ], [ 'title' => 'Item 2', 'show' => false ], [ 'title' => 'Item 3', 'show' => true ], [ 'title' => 'Item 4', 'show' => false ], [ 'title' => 'Item 5', 'show' => true ] ])->render();*/ Cookie::set('artin', 'Artin'); Cookie::set('pelang', 12); Cookie::hashing_off(); vd(Cookie::all()); } }
php
11
0.556174
88
27.125
32
starcoderdata
export default { namespaced: true, actions: { GET_SERVICES_FROM_API({commit}, gameSlug) { return axios.get('/api/services/'+gameSlug) .then((response) => { commit('SET_SERVICES_TO_STATE', response.data); return response.data; }) .catch((error) => { console.log(error); return error; }); }, SERVICES_CLEAR({commit}) { commit('SET_SERVICES_TO_STATE', null); } }, mutations: { SET_SERVICES_TO_STATE: (state, dataServices) => { state.services = dataServices; }, }, state: { services: [], }, getters: { getServices: state => { return state.services; }, }, }
javascript
18
0.446469
67
24.823529
34
starcoderdata
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package header import ( "encoding/binary" "strings" "tcpip/netstack/tcpip" ) const ( versTCFL = 0 payloadLen = 4 nextHdr = 6 hopLimit = 7 v6SrcAddr = 8 v6DstAddr = 24 ) // IPv6Fields contains the fields of an IPv6 packet. It is used to describe the // fields of a packet that needs to be encoded. type IPv6Fields struct { // TrafficClass is the "traffic class" field of an IPv6 packet. TrafficClass uint8 // FlowLabel is the "flow label" field of an IPv6 packet. FlowLabel uint32 // PayloadLength is the "payload length" field of an IPv6 packet. PayloadLength uint16 // NextHeader is the "next header" field of an IPv6 packet. NextHeader uint8 // HopLimit is the "hop limit" field of an IPv6 packet. HopLimit uint8 // SrcAddr is the "source ip address" of an IPv6 packet. SrcAddr tcpip.Address // DstAddr is the "destination ip address" of an IPv6 packet. DstAddr tcpip.Address } // IPv6 represents an ipv6 header stored in a byte array. // Most of the methods of IPv6 access to the underlying slice without // checking the boundaries and could panic because of 'index out of range'. // Always call IsValid() to validate an instance of IPv6 before using other methods. type IPv6 []byte const ( // IPv6MinimumSize is the minimum size of a valid IPv6 packet. IPv6MinimumSize = 40 // IPv6AddressSize is the size, in bytes, of an IPv6 address. IPv6AddressSize = 16 // IPv6ProtocolNumber is IPv6's network protocol number. IPv6ProtocolNumber tcpip.NetworkProtocolNumber = 0x86dd // IPv6Version is the version of the ipv6 protocol. IPv6Version = 6 // IPv6MinimumMTU is the minimum MTU required by IPv6, per RFC 2460, // section 5. IPv6MinimumMTU = 1280 ) // PayloadLength returns the value of the "payload length" field of the ipv6 // header. func (b IPv6) PayloadLength() uint16 { return binary.BigEndian.Uint16(b[payloadLen:]) } // HopLimit returns the value of the "hop limit" field of the ipv6 header. func (b IPv6) HopLimit() uint8 { return b[hopLimit] } // NextHeader returns the value of the "next header" field of the ipv6 header. func (b IPv6) NextHeader() uint8 { return b[nextHdr] } // TransportProtocol implements Network.TransportProtocol. func (b IPv6) TransportProtocol() tcpip.TransportProtocolNumber { return tcpip.TransportProtocolNumber(b.NextHeader()) } // Payload implements Network.Payload. func (b IPv6) Payload() []byte { return b[IPv6MinimumSize:][:b.PayloadLength()] } // SourceAddress returns the "source address" field of the ipv6 header. func (b IPv6) SourceAddress() tcpip.Address { return tcpip.Address(b[v6SrcAddr : v6SrcAddr+IPv6AddressSize]) } // DestinationAddress returns the "destination address" field of the ipv6 // header. func (b IPv6) DestinationAddress() tcpip.Address { return tcpip.Address(b[v6DstAddr : v6DstAddr+IPv6AddressSize]) } // Checksum implements Network.Checksum. Given that IPv6 doesn't have a // checksum, it just returns 0. func (IPv6) Checksum() uint16 { return 0 } // TOS returns the "traffic class" and "flow label" fields of the ipv6 header. func (b IPv6) TOS() (uint8, uint32) { v := binary.BigEndian.Uint32(b[versTCFL:]) return uint8(v >> 20), v & 0xfffff } // SetTOS sets the "traffic class" and "flow label" fields of the ipv6 header. func (b IPv6) SetTOS(t uint8, l uint32) { vtf := (6 << 28) | (uint32(t) << 20) | (l & 0xfffff) binary.BigEndian.PutUint32(b[versTCFL:], vtf) } // SetPayloadLength sets the "payload length" field of the ipv6 header. func (b IPv6) SetPayloadLength(payloadLength uint16) { binary.BigEndian.PutUint16(b[payloadLen:], payloadLength) } // SetSourceAddress sets the "source address" field of the ipv6 header. func (b IPv6) SetSourceAddress(addr tcpip.Address) { copy(b[v6SrcAddr:v6SrcAddr+IPv6AddressSize], addr) } // SetDestinationAddress sets the "destination address" field of the ipv6 // header. func (b IPv6) SetDestinationAddress(addr tcpip.Address) { copy(b[v6DstAddr:v6DstAddr+IPv6AddressSize], addr) } // SetNextHeader sets the value of the "next header" field of the ipv6 header. func (b IPv6) SetNextHeader(v uint8) { b[nextHdr] = v } // SetChecksum implements Network.SetChecksum. Given that IPv6 doesn't have a // checksum, it is empty. func (IPv6) SetChecksum(uint16) { } // Encode encodes all the fields of the ipv6 header. func (b IPv6) Encode(i *IPv6Fields) { b.SetTOS(i.TrafficClass, i.FlowLabel) b.SetPayloadLength(i.PayloadLength) b[nextHdr] = i.NextHeader b[hopLimit] = i.HopLimit copy(b[v6SrcAddr:v6SrcAddr+IPv6AddressSize], i.SrcAddr) copy(b[v6DstAddr:v6DstAddr+IPv6AddressSize], i.DstAddr) } // IsValid performs basic validation on the packet. func (b IPv6) IsValid(pktSize int) bool { if len(b) < IPv6MinimumSize { return false } dlen := int(b.PayloadLength()) if dlen > pktSize-IPv6MinimumSize { return false } return true } // IsV4MappedAddress determines if the provided address is an IPv4 mapped // address by checking if its prefix is 0:0:0:0:0:ffff::/96. func IsV4MappedAddress(addr tcpip.Address) bool { if len(addr) != IPv6AddressSize { return false } return strings.HasPrefix(string(addr), "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff") } // IsV6MulticastAddress determines if the provided address is an IPv6 // multicast address (anything starting with FF). func IsV6MulticastAddress(addr tcpip.Address) bool { if len(addr) != IPv6AddressSize { return false } return addr[0] == 0xff } // SolicitedNodeAddr computes the solicited-node multicast address. This is // used for NDP. Described in RFC 4291. The argument must be a full-length IPv6 // address. func SolicitedNodeAddr(addr tcpip.Address) tcpip.Address { const solicitedNodeMulticastPrefix = "\xff\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\xff" return solicitedNodeMulticastPrefix + addr[len(addr)-3:] } // LinkLocalAddr computes the default IPv6 link-local address from a link-layer // (MAC) address. func LinkLocalAddr(linkAddr tcpip.LinkAddress) tcpip.Address { // Convert a 48-bit MAC to an EUI-64 and then prepend the link-local // header, FE80::. // // The conversion is very nearly: // aa:bb:cc:dd:ee:ff => FE80::Aabb:ccFF:FEdd:eeff // Note the capital A. The conversion aa->Aa involves a bit flip. lladdrb := [16]byte{ 0: 0xFE, 1: 0x80, 8: linkAddr[0] ^ 2, 9: linkAddr[1], 10: linkAddr[2], 11: 0xFF, 12: 0xFE, 13: linkAddr[3], 14: linkAddr[4], 15: linkAddr[5], } return tcpip.Address(lladdrb[:]) }
go
11
0.71036
92
28.838983
236
starcoderdata
// This file is part of graze/golang-service // // Copyright (c) 2016 Nature Delivered Ltd. // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. // // license: https://github.com/graze/golang-service/blob/master/LICENSE // link: https://github.com/graze/golang-service /* Package metrics provides a some helpers for sending metrics Statsd Connect to a statsd endpoint using environment variables Environment Variables: STATSD_HOST: The host of the statsd server STATSD_PORT: The port of the statsd server STATSD_NAMESPACE: The namespace to prefix to every metric name STATSD_TAGS: A comma separared list of tags to apply to every metric reported Example: STATSD_HOST: localhost STATSD_PORT: 8125 STATSD_NAMESPACE: app.live. STATSD_TAGS: env:live,version:1.0.2 Usage: client, _ := GetStatsdFromEnv() client.Incr("metric", []string{"tag","tag2"}, 1) */ package metrics
go
8
0.734579
81
29.571429
35
starcoderdata
#ifndef __OBS_H_ #define __OBS_H_ #include #include #include #include "ros/ros.h" using namespace std; class Observation{ public: Observation(); Observation(int left_f,int left_s, int right_s, int right_f); void setValues(int left_f,int left_s, int right_s, int right_f); int lf; int ls; int rs; int rf; double log_lf; double log_ls; double log_rs; double log_rf; }; #endif
c
8
0.679724
65
14.5
28
starcoderdata
package main // 基于闭包的工厂函数 import "strings" func MakeAddSuffix(suffix string) func(string) string { return func(name string) string { if !strings.HasSuffix(name, suffix) { return name + suffix } return name } }
go
12
0.725869
55
16.266667
15
starcoderdata
using PiRhoSoft.Variables; namespace PiRhoSoft.Expressions { public abstract class ComparisonOperator : InfixOperator { private const string _comparisonTypeMismatchException = "unable to compare types {0} and {1} with operator '{2}'"; public override Variable Evaluate(IVariableDictionary variables) { var left = Left.Evaluate(variables); var right = Right.Evaluate(variables); var result = Compare(variables, left, right); if (!result.HasValue) throw new OperationException(_comparisonTypeMismatchException, left, right, Symbol); return Variable.Bool(result.Value); } protected abstract bool? Compare(IVariableDictionary variables, Variable left, Variable right); } public class EqualOperator : ComparisonOperator { protected override bool? Compare(IVariableDictionary variables, Variable left, Variable right) => Variable.IsEqual(left, right); } public class InequalOperator : ComparisonOperator { // The ! operator works as expected with null but comparison operators do not. protected override bool? Compare(IVariableDictionary variables, Variable left, Variable right) => !Variable.IsEqual(left, right); } public class LessOperator : ComparisonOperator { protected override bool? Compare(IVariableDictionary variables, Variable left, Variable right) { var comparison = Variable.Compare(left, right); return comparison.HasValue ? comparison.Value < 0 : (bool?)null; } } public class LessOrEqualOperator : ComparisonOperator { protected override bool? Compare(IVariableDictionary variables, Variable left, Variable right) { var comparison = Variable.Compare(left, right); return comparison.HasValue ? comparison.Value <= 0 : (bool?)null; } } public class GreaterOperator : ComparisonOperator { protected override bool? Compare(IVariableDictionary variables, Variable left, Variable right) { var comparison = Variable.Compare(left, right); return comparison.HasValue ? comparison.Value > 0 : (bool?)null; } } public class GreaterOrEqualOperator : ComparisonOperator { protected override bool? Compare(IVariableDictionary variables, Variable left, Variable right) { var comparison = Variable.Compare(left, right); return comparison.HasValue ? comparison.Value >= 0 : (bool?)null; } } }
c#
14
0.756405
131
31.9
70
starcoderdata
var xpaytoreload = 0; var xpaytimer = setInterval(function(){ if (typeof jQuery == 'undefined') return; var $ = jQuery; var t = $('#xpay-timer'); if (t.length > 0) { ++xpaytoreload; if (xpaytoreload > 30) { location.reload(true); clearInterval(xpaytimer); return; } var s = t.attr('data-seconds'); --s; t.attr('data-seconds', s); if (s < 0) { t.html('EXPIRADO'); location.reload(true); clearInterval(xpaytimer); return; } var mm = parseInt(s/60); var ss = s%60; if (mm < 10) mm = '0'+mm; if (ss < 10) ss = '0'+ss; t.html(mm+':'+ss); } }, 950);
javascript
11
0.57541
42
20.068966
29
starcoderdata
import { CliController } from 'cli-router'; import { promiseResolve } from 'azk/utils/promises'; export default class TestOptions extends CliController { index(params={}) { return promiseResolve([{ number: params.number }]); } }
javascript
13
0.714286
56
28.75
8
starcoderdata
package me.wallhacks.spark.gui.clickGui.panels.mainScreen.setting; import baritone.api.BaritoneAPI; import baritone.api.pathing.goals.GoalBlock; import baritone.api.pathing.goals.GoalXZ; import me.wallhacks.spark.Spark; import me.wallhacks.spark.gui.clickGui.panels.mainScreen.setting.settings.*; import me.wallhacks.spark.gui.clickGui.panels.navigation.waypointlist.WayPointItem; import me.wallhacks.spark.gui.clickGui.settingScreens.kitSetting.KitSettingGui; import me.wallhacks.spark.gui.panels.GuiPanelBase; import me.wallhacks.spark.gui.panels.GuiPanelButton; import me.wallhacks.spark.gui.panels.GuiPanelScroll; import me.wallhacks.spark.manager.ConfigManager; import me.wallhacks.spark.manager.WaypointManager; import me.wallhacks.spark.systems.hud.HudElement; import me.wallhacks.spark.systems.module.Module; import me.wallhacks.spark.systems.module.modules.misc.InventoryManager; import me.wallhacks.spark.systems.setting.settings.*; import me.wallhacks.spark.util.GuiUtil; import net.minecraft.util.ResourceLocation; import me.wallhacks.spark.systems.SettingsHolder; import me.wallhacks.spark.systems.setting.Setting; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3i; import java.util.ArrayList; public class GuiEditSettingPanel extends GuiPanelBase { public GuiEditSettingPanel() { super(); } final static ResourceLocation settingIcon = new ResourceLocation("textures/icons/settingsicon.png"); public SettingsHolder getCurrentSettingsHolder(){ return currentSettingsHolder; } public void setCurrentSettingsHolder(SettingsHolder currentSettingsHolder){ this.currentSettingsHolder = currentSettingsHolder; guiEditSettingPanelHolder.groups = new ArrayList<>(); if(currentSettingsHolder != null) { ArrayList groups = new ArrayList<>(); for (Setting s : currentSettingsHolder.getSettings()) { if(!groups.contains(s.getCategory())) groups.add(s.getCategory()); } for (String group : groups) { ArrayList settings = new ArrayList<>(); for (Setting s : currentSettingsHolder.getSettings()) { if(s.getCategory().equals(group)){ if(s instanceof IntSetting) settings.add(new GuiIntSettingPanel((IntSetting) s)); if(s instanceof DoubleSetting) settings.add(new GuiDoubleSettingPanel((DoubleSetting) s)); if(s instanceof BooleanSetting) settings.add(new GuiBooleanSettingPanel((BooleanSetting) s)); if(s instanceof ModeSetting) settings.add(new GuiEnumSettingPanel((ModeSetting) s)); if(s instanceof KeySetting) settings.add(new GuiKeySettingPanel((KeySetting) s)); if(s instanceof ColorSetting) settings.add(new GuiColorSettingPanel((ColorSetting) s)); if(s instanceof StringSetting) settings.add(new GuiStringSettingPanel((StringSetting) s)); if(s instanceof ListSelectSetting) settings.add(new GuiListSettingPanel((ListSelectSetting) s)); if(s instanceof VectorSetting) settings.add(new GuiVectorSettingPanel((VectorSetting) s)); } } GuiEditSettingPanelGroup g = new GuiEditSettingPanelGroup(group,guiEditSettingPanelHolder,settings); g.setExtended(groups.size() <= 4); guiEditSettingPanelHolder.groups.add(g); } buttonFunction = null; if(currentSettingsHolder instanceof InventoryManager) { buttonFunction = buttonFunction = new GuiPanelButton[] { new GuiPanelButton(() -> { mc.displayGuiScreen(new KitSettingGui(Spark.clickGuiScreen)); },"Kit Editor")}; } if(currentSettingsHolder instanceof HudElement) { buttonFunction = new GuiPanelButton[] { new GuiPanelButton(() -> { HudElement h = (HudElement)currentSettingsHolder; h.resetPos(); },"Reset Location") }; } if(currentSettingsHolder instanceof ConfigManager.Config) { buttonFunction = new GuiPanelButton[] { new GuiPanelButton(() -> { Spark.configManager.deleteConfig((ConfigManager.Config) currentSettingsHolder); },"Delete"), new GuiPanelButton(() -> { Spark.configManager.loadConfig((ConfigManager.Config) currentSettingsHolder,true); },"Load") }; } if(currentSettingsHolder instanceof WaypointManager.Waypoint) { buttonFunction = new GuiPanelButton[] { new GuiPanelButton(() -> { WaypointManager.Waypoint waypoint = (WaypointManager.Waypoint) currentSettingsHolder; Spark.waypointManager.getWayPoints().remove(waypoint); }, "Delete"), new GuiPanelButton(() -> { WaypointManager.Waypoint waypoint = (WaypointManager.Waypoint) currentSettingsHolder; Vec3i v = waypoint.getLocation(); Spark.sendInfo("Going to "+waypoint.getName()); if(waypoint.hasY()) BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalBlock(new BlockPos(v.getX(),v.getY(),v.getZ()))); else BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalXZ(v.getX(),v.getZ())); mc.displayGuiScreen(null); }, "Goto") }; } } } SettingsHolder currentSettingsHolder = null; GuiEditSettingPanelHolder guiEditSettingPanelHolder = new GuiEditSettingPanelHolder(this); GuiEditModuleSettings guiEditModuleSettings = new GuiEditModuleSettings(this); GuiPanelScroll guiPanelScroll = new GuiPanelScroll(posX, posY, width, height,guiEditSettingPanelHolder); GuiPanelButton[] buttonFunction; public void renderContent(int MouseX, int MouseY, float deltaTime) { // super.renderContent(MouseX,MouseY,deltaTime); int nameBarHeight = 18; drawRect(posX,posY,posX+width,posY+nameBarHeight, guiSettings.getGuiSubPanelBackgroundColor().getRGB()); if(currentSettingsHolder != null) { String s = currentSettingsHolder.getName(); fontManager.drawString(s,posX+2+nameBarHeight,posY+nameBarHeight/2-fontManager.getTextHeight()/2, guiSettings.getContrastColor().getRGB()); } GuiUtil.drawCompleteImage(posX+3,posY+3, nameBarHeight-6, nameBarHeight-6,settingIcon, guiSettings.getContrastColor()); int Yoffset = 0; if(currentSettingsHolder instanceof Module) { guiEditModuleSettings.setPositionAndSize(posX,posY+height-18,guiPanelScroll.width,18); Yoffset += guiEditModuleSettings.height + guiSettings.spacing; guiEditModuleSettings.renderContent(MouseX,MouseY,deltaTime); } if(buttonFunction != null && buttonFunction.length > 0) { int w = guiPanelScroll.width/buttonFunction.length-(guiSettings.spacing*(buttonFunction.length-1)/2); for (int i = 0; i < buttonFunction.length; i++) { buttonFunction[i].setPositionAndSize(posX+i*(w+guiSettings.spacing),posY+height-Yoffset-18,w,18); buttonFunction[i].renderContent(MouseX,MouseY,deltaTime); } Yoffset += buttonFunction[0].height + guiSettings.spacing; } guiPanelScroll.setPositionAndSize(posX,posY+18+ guiSettings.spacing,width,height-18-guiSettings.spacing-Yoffset); guiPanelScroll.drawBackGround(guiSettings.getGuiSubPanelBackgroundColor().getRGB()); guiPanelScroll.renderContent(MouseX,MouseY,deltaTime); } }
java
27
0.613979
174
39.087558
217
starcoderdata
func main() { //Initialize the router with the EnvInit middleware m := web.New() m.Use(middleware.EnvInit) //Make a plain path m.Handle("/sloths", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Sloths rule!") }) //Route parameters m.Handle("/:flavor/tea", func(c web.C, w http.ResponseWriter, r *http.Request) { flavor := c.URLParams["flavor"] fmt.Fprintf(w, "I could go for some %s tea!", flavor) }) //Path prefix with a * m.Handle("/img/*", http.StripPrefix("/img/", http.FileServer(http.Dir("public/images")))) //GET-specific route m.Get("/get-route", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "This route only responds to GET requests") }) //Route with a regular expression path coffeeRegexp := regexp.MustCompile(`^/(coffee)+$`) m.Get(coffeeRegexp, func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Lemurs = sloths that had too much coffee") }) m.Handle("/", youreNo1000000) //Catch-all route m.Handle("/*", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "This route matches all requests.") }) server := &http.Server{ Addr: ":1123", Handler: m, } server.ListenAndServe() }
go
13
0.670293
81
26.181818
44
inline
#!/usr/bin/env python import sys import os import re import subprocess import shellpython.config as config from shellpython.preprocessor import preprocess_file from argparse import ArgumentParser from shellpython.constants import * def main2(): main(python_version=2) def main3(): main(python_version=3) def main(python_version): custom_usage = '''%(prog)s [SHELLPY ARGS] file [SCRIPT ARGS] For arguments help use: %(prog)s --help ''' custom_epilog = '''github : github.com/lamerman/shellpy''' try: spy_file_index = next(index for index, arg in enumerate(sys.argv) if re.match('.+\.spy$', arg)) shellpy_args = sys.argv[1:spy_file_index] script_args = sys.argv[spy_file_index + 1:] except StopIteration: shellpy_args = sys.argv[1:] spy_file_index = None parser = ArgumentParser(description='A tool for convenient shell scripting in python', usage=custom_usage, epilog=custom_epilog) parser.add_argument('-v', '--verbose', help='increase output verbosity. Always print the command being executed', action="store_true") parser.add_argument('-vv', help='even bigger output verbosity. All stdout and stderr of executed commands is ' 'printed', action="store_true") shellpy_args, _ = parser.parse_known_args(shellpy_args) if spy_file_index is None: exit('No *.spy file was specified. Only *.spy files are supported by the tool.') if shellpy_args.verbose or shellpy_args.vv: config.PRINT_ALL_COMMANDS = True if shellpy_args.vv: config.PRINT_STDOUT_ALWAYS = True config.PRINT_STDERR_ALWAYS = True filename = sys.argv[spy_file_index] processed_file = preprocess_file(filename, is_root_script=True, python_version=python_version) # include directory of the script to pythonpath new_env = os.environ.copy() new_env['PYTHONPATH'] = new_env.get("PYTHONPATH", '') + os.pathsep + os.path.dirname(filename) new_env[SHELLPY_PARAMS] = config.dumps() retcode = subprocess.call(processed_file + ' ' + ' '.join(script_args), shell=True, env=new_env) exit(retcode) if __name__ == '__main__': main()
python
13
0.654529
117
31.637681
69
starcoderdata
package com.ripple.core.types.known.sle; import com.ripple.core.coretypes.Vector256; import com.ripple.core.coretypes.uint.UInt32; import com.ripple.core.serialized.enums.LedgerEntryType; public class LedgerHashes extends LedgerEntry { public LedgerHashes() { super(LedgerEntryType.LedgerHashes); } public Vector256 hashes() { return get(Vector256.Hashes); } public void hashes(Vector256 hashes) { put(Vector256.Hashes, hashes); } public UInt32 lastLedgerSequence() { return get(UInt32.LastLedgerSequence); } public UInt32 firstLedgerSequence() {return get(UInt32.FirstLedgerSequence);} public void firstLedgerSequence(UInt32 val) { put(UInt32.FirstLedgerSequence, val);} public void lastLedgerSequence(UInt32 val) { put(UInt32.LastLedgerSequence, val);} public boolean hasFirstLedgerSequence() {return has(UInt32.FirstLedgerSequence);} public boolean hasLastLedgerSequence() {return has(UInt32.LastLedgerSequence);} }
java
9
0.73913
88
30.625
32
starcoderdata
def _binning_xyz(self, data): """ Returns the spatial position according the the precisions of the deaggregation data """ xyz = data.copy() cols = xyz.columns # rounds to bin precision xyz[cols[0]] = xyz[cols[0]] / self.p_lon xyz[cols[1]] = xyz[cols[1]] / self.p_lat xyz[cols[2]] = xyz[cols[2]] / self.p_mag xyz = xyz.round() xyz[cols[0]] = xyz[cols[0]] * self.p_lon xyz[cols[1]] = xyz[cols[1]] * self.p_lat xyz[cols[2]] = xyz[cols[2]] * self.p_mag return xyz
python
8
0.52069
54
33.176471
17
inline
def cases(x, y, xdim, ydim, xc, yc, xb, yb): # Consider three states in which an operand may be # 1: split, contracting # 2: split, not contracting # 3: not split # # We will handle the following cases, marked by corresponding letter # symbols: # # |1 2 3|y # -+-----+- # 1|a b c # 2|d e f # 3|g h i # -+ # x| # # Case i is already covered and we can assume that it is excluded at the # outset, since a papply rule is not invoked when no operands are split. if xdim in xc: # cases a, b, c if ydim in yc: # case a: both operands are split and contracting # TODO(frostig): Might the following work? # z = lax.dot_general( # x, y, sub_dims(xdim, ydim, xc, yc, xb, yb), precision) # return True, (psum(z, name), None) return False, 'both operands split and contracting' elif ydim is not None: # case b: x split and contracting, y split but not contracting # TODO(frostig): Might the following work? # new_ydim = yc[xc.index(xdim)] # y = all_to_all(y, name, new_ydim, ydim) # z = lax.dot_general( # x, y, sub_dims(xdim, new_ydim, xc, yc, xb, yb), precision) # return True, (psum(z, name), None) return False, 'rhs split but not contracting, lhs split and contracting' else: # case c: x split and contracting, y not split assert ydim is None return False, 'one operand split and contracting, other is not split' elif xdim is not None: # cases d, e, f if ydim in yc: # case d: x split but not contracting, y split and contracting # TODO(frostig): Might the following work? # new_xdim = xc[yc.index(ydim)] # x = all_to_all(x, name, new_xdim, xdim) # z = lax.dot_general( # x, y, sub_dims(new_xdim, ydim, xc, yc, xb, yb), precision) # return True, (psum(z, name), None) return False, 'lhs split but not contracting, rhs split and contracting' elif ydim is not None: # case e: both operands are split but not contracting y = _allgather(y, ydim, size, name) z = lax.dot_general( x, y, sub_dims(xdim, None, xc, yc, xb, yb), precision) zdim = xdim + len(xb) - len([d for d in range(xdim) if d in xc]) return True, (z, zdim) else: # case f: x split but not contracting, y not split assert ydim is None z = lax.dot_general( x, y, sub_dims(xdim, None, xc, yc, xb, yb), precision) zdim = xdim + len(xb) - len([d for d in range(xdim) if d in xc]) return True, (z, zdim) else: # cases g, h assert xdim is None if ydim in yc: # case g: x not split, y split and contracting return False, 'one operand split and contracting, other is not split' else: # case h: x not split, y split but not contracting assert ydim is not None # TODO(frostig): Might the following work? # z = lax.dot_general( # x, y, sub_dims(None, ydim, xc, yc, xb, yb), precision) # zdim = ( # ydim + len(xb) + # batch dimensions # x.ndim - len(xc) - # non-contracting x dimensions # len([d for d in range(ydim) if d in yc])) # return True, (z, zdim) return False, 'lhs not split, rhs split but not contracting' assert False, 'unreachable'
python
18
0.56083
80
39.448276
87
inline
package brennus.asm.specializer; public interface InterfaceFixture { Object foo(Object bar); }
java
6
0.754902
35
13.571429
7
starcoderdata
IX_ETH_ACC_PUBLIC IxEthAccStatus ixEthAccPortRxCallbackRegister(IxEthAccPortId portId, IxEthAccPortRxCallback rxCallbackFn, UINT32 callbackTag) { IxEthAccPortId port; if (!IX_ETH_ACC_IS_SERVICE_INITIALIZED()) { return (IX_ETH_ACC_FAIL); } if (!IX_ETH_ACC_IS_PORT_VALID(portId)) { return (IX_ETH_ACC_INVALID_PORT); } if (IX_ETH_ACC_SUCCESS != ixEthAccSingleEthNpeCheck(portId)) { IX_ETH_ACC_WARNING_LOG("ixEthAccPortRxCallbackRegister: Unavailable Eth %d: Cannot register Rx Callback.\n",(INT32)portId,0,0,0,0,0); return IX_ETH_ACC_SUCCESS ; } if (!IX_ETH_IS_PORT_INITIALIZED(portId)) { return (IX_ETH_ACC_PORT_UNINITIALIZED); } /* Check for null function pointer here. */ if (rxCallbackFn == NULL) { return (IX_ETH_ACC_INVALID_ARG); } /* Check the user is not changing the callback type * when the port is enabled. */ if (ixEthAccMacState[portId].portDisableState == ACTIVE) { for (port = 0; port < IX_ETH_ACC_NUMBER_OF_PORTS; port++) { if ((ixEthAccMacState[port].portDisableState == ACTIVE) && (ixEthAccPortData[port].ixEthAccRxData.rxMultiBufferCallbackInUse == TRUE)) { /* one of the active ports has a different rx callback type. * Changing the callback type when the port is enabled * is not safe */ return (IX_ETH_ACC_INVALID_ARG); } } } /* update the callback pointer : this is done before * registering the new qmgr callback */ ixEthAccPortData[portId].ixEthAccRxData.rxCallbackFn = rxCallbackFn; ixEthAccPortData[portId].ixEthAccRxData.rxCallbackTag = callbackTag; /* update the qmgr callback for rx queues */ if (ixEthAccQMgrRxCallbacksRegister(ixEthRxFrameQMCallback) != IX_ETH_ACC_SUCCESS) { /* unexpected qmgr error */ IX_ETH_ACC_FATAL_LOG("ixEthAccPortRxCallbackRegister: unexpected QMgr error, " \ "could not register Rx single-buffer callback\n", 0, 0, 0, 0, 0, 0); RX_INC(portId,rxUnexpectedError); return (IX_ETH_ACC_INVALID_ARG); } ixEthAccPortData[portId].ixEthAccRxData.rxMultiBufferCallbackInUse = FALSE; return (IX_ETH_ACC_SUCCESS); }
c
15
0.670726
141
28.573333
75
inline
<?php if (isset($_POST['email'])) { //Email information $admin_email = " $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; //send email mail($admin_email, "Web Contact", $message . ' - ', "From:" . $email); header('Location: https://felix-asante.github.io/Ghasam/index.html#contact-form'); }
php
9
0.544737
86
26.214286
14
starcoderdata
#include "external/envoy/test/test_common/utility.h" #include "source/client/sni_utility.h" #include "source/common/uri_impl.h" #include "gtest/gtest.h" using namespace testing; namespace Nighthawk { namespace Client { class SniUtilityTest : public Test { public: std::string checkSniHostComputation(const std::vector uris, const std::vector request_headers, const Envoy::Http::Protocol protocol) { std::vector parsed_uris; parsed_uris.reserve(uris.size()); for (const std::string& uri : uris) { parsed_uris.push_back(std::make_unique } return SniUtility::computeSniHost(parsed_uris, request_headers, protocol); } }; TEST_F(SniUtilityTest, SniHostComputation) { const std::vector all_protocols{ Envoy::Http::Protocol::Http10, Envoy::Http::Protocol::Http11, Envoy::Http::Protocol::Http2, Envoy::Http::Protocol::Http3}; for (const auto protocol : all_protocols) { EXPECT_EQ(checkSniHostComputation({"localhost"}, {}, protocol), "localhost"); EXPECT_EQ(checkSniHostComputation({"localhost:81"}, {}, protocol), "localhost"); EXPECT_EQ(checkSniHostComputation({"localhost"}, {"Host: foo"}, protocol), "foo"); EXPECT_EQ(checkSniHostComputation({"localhost:81"}, {"Host: foo"}, protocol), "foo"); const std::string expected_sni_host(protocol >= Envoy::Http::Protocol::Http2 ? "foo" : "localhost"); EXPECT_EQ(checkSniHostComputation({"localhost"}, {":authority: foo"}, protocol), expected_sni_host); EXPECT_EQ(checkSniHostComputation({"localhost:81"}, {":authority: foo"}, protocol), expected_sni_host); } } } // namespace Client } // namespace Nighthawk
c++
19
0.638442
97
39.957447
47
starcoderdata
package rpc import ( "net/rpc" //"net/http" "net" "testing" "time" log "github.com/golang/glog" ) type Args struct { A, B int } type Arith int //func (t *Arith) Multiply(args *Args, reply *([]string)) error { // *reply = append(*reply, "test") // log.Infoln(args) // return nil //} func TestProtoFriendListData(t *testing.T) { newServer := rpc.NewServer() newServer.Register(new(Arith)) l, e := net.Listen("tcp", "127.0.0.1:1234") // any available address if e != nil { log.Fatalf("net.Listen tcp :0: %v", e) } go newServer.Accept(l) newServer.HandleHTTP("/foo", "/bar") time.Sleep(2 * time.Second) address, err := net.ResolveTCPAddr("tcp", "127.0.0.1:1234") if err != nil { panic(err) } conn, _ := net.DialTCP("tcp", nil, address) defer conn.Close() client := rpc.NewClient(conn) defer client.Close() args := &Args{7, 8} reply := make([]string, 10) err = client.Call("Arith.Multiply", args, &reply) if err != nil { log.Fatal("arith error:", err) } log.Infoln(reply) }
go
9
0.636023
69
18.035714
56
starcoderdata
package org.lightadmin.core.config.domain.unit.visitor; import com.google.common.collect.FluentIterable; import org.lightadmin.api.config.unit.FieldSetConfigurationUnit; import org.lightadmin.core.config.domain.field.FieldMetadata; import org.lightadmin.core.config.domain.field.FieldMetadataUtils; import org.lightadmin.core.config.domain.field.PersistentFieldMetadata; import org.lightadmin.core.config.domain.unit.ConfigurationUnit; import org.lightadmin.core.config.domain.unit.HierarchicalConfigurationUnit; import java.util.Set; public class HierarchicalConfigurationUnitVisitor extends ParametrizedConfigurationUnitVisitor { private ConfigurationUnit parentUnit; public HierarchicalConfigurationUnitVisitor(ConfigurationUnit parentUnit) { this.parentUnit = parentUnit; } @Override protected void visitInternal(HierarchicalConfigurationUnit configurationUnit) { if (parentUnit instanceof FieldSetConfigurationUnit && configurationUnit instanceof FieldSetConfigurationUnit) { Set parentDecls = ((FieldSetConfigurationUnit) parentUnit).getFields(); FluentIterable localDecls = FluentIterable.from(((FieldSetConfigurationUnit) configurationUnit).getFields()).filter(PersistentFieldMetadata.class); for (PersistentFieldMetadata localDecl : localDecls) { PersistentFieldMetadata parentDecl = FieldMetadataUtils.getPersistentField(parentDecls, localDecl.getField()); if (parentDecl != null) { localDecl.inheritFrom(parentDecl); } } } } }
java
15
0.771292
184
47
35
starcoderdata
using System.Diagnostics; using GraphQL.Utilities; namespace GraphQL.Types { /// /// A class that represents an enumeration definition. /// [DebuggerDisplay("{Name}: {Value}")] public class EnumValueDefinition : MetadataProvider, IProvideDescription, IProvideDeprecationReason { /// /// Initializes a new instance with the specified name and value. /// public EnumValueDefinition(string name, object? value) { Name = name; Value = value; UnderlyingValue = value is Enum ? Convert.ChangeType(value, Enum.GetUnderlyingType(value.GetType())) : value; } /// /// The name of the enumeration member, as exposed through the GraphQL endpoint (e.g. "RED"). /// public string Name { get; set; } //TODO: important to set this property only BEFORE EnumValuesBase.AddValue called /// /// A description of the enumeration member. /// public string? Description { get; set; } /// /// The reason this enumeration member has been deprecated; <see langword="null"/> if this member has not been deprecated. /// public string? DeprecationReason { get => this.GetDeprecationReason(); set => this.SetDeprecationReason(value); } /// /// The value of the enumeration member, as referenced by the code (e.g. <see cref="ConsoleColor.Red"/>). /// public object? Value { get; } /// /// When mapped to a member of an <see cref="Enum"/>, contains the underlying enumeration value; otherwise contains <see cref="Value" />. /// internal object? UnderlyingValue { get; } } }
c#
18
0.596242
145
35.462963
54
starcoderdata
<?php //For Admin dashboard Route. Route::get('/dashboard/products/', 'ProductBackEndController@index')->name('productIndex'); Route::get('/dashboard/products/create', 'ProductBackEndController@create')->name('productCreate'); Route::post('/dashboard/products', 'ProductBackEndController@store')->name('productStore'); Route::get('/dashboard/products/{id}/edit','ProductBackEndController@edit')->name('productEdit'); Route::post('/dashboard/products/{id}/update', 'ProductBackEndController@update')->name('productUpdate'); //For Customer Route.
php
7
0.760757
105
47.416667
12
starcoderdata
public String[] splitStringFunctions(String str) { ArrayList<String> parts = new ArrayList<>(); parts.add(""); int nest_count = 0; char prev_c = ' '; for(int i=0; i<str.length(); i++) { char c = str.charAt(i); if(c == '<' && prev_c != '\\') { if(nest_count == 0) parts.add(""); nest_count++; } int last_elem = parts.size() - 1; parts.set(last_elem, parts.get(last_elem) + c); if(c == '>' && prev_c != '\\') { nest_count--; if(nest_count == 0) parts.add(""); } prev_c = c; } // discard empty strs parts.removeAll(Collections.singleton("")); return (String[]) parts.toArray(new String[parts.size()]); }
java
12
0.414384
66
34.08
25
inline
/* * * Filename: set_abcw.hpp * * Author: * Email : * Description: --- * Create: 2017-08-27 22:49:19 * Last Modified: 2017-08-27 22:49:19 **/ #ifndef GUARD_MIOPENGEMM_SETABCW_HPP #define GUARD_MIOPENGEMM_SETABCW_HPP #include #include namespace MIOpenGEMM { namespace setabcw { template <typename TFloat> void set_abc(std::vector v_a, std::vector v_b, std::vector v_c); template <typename TFloat> void set_multigeom_abc(std::vector v_a, std::vector v_b, std::vector v_c); template <typename TFloat> void set_abcw(std::vector v_a, std::vector v_b, std::vector v_c, std::vector v_workspace); template <typename TFloat> void test(TFloat& a); template <typename TFloat> void print(); } } #endif /*GUARD_MIOPENGEMM_SETABCW_HPP*/
c++
15
0.521212
60
25.860465
43
starcoderdata
def get_tag_map(self, indices=False, tag_names=False): """ Mapping raw tag ids to the combined tag ids """ assert indices or tag_names assert not (indices and tag_names) if indices: id2tag_raw = load_pkl(os.path.join(self.data_dir, "raw_id2tag.pkl")) tag2id_raw = load_pkl(os.path.join(self.data_dir, "raw_tag2id.pkl")) id2tag_combined = load_pkl( os.path.join(self.data_dir, "combined_id2tag.pkl") ) tag2id_combined = load_pkl( os.path.join(self.data_dir, "combined_tag2id.pkl") ) raw_to_combined_id = {} for key, value in raw_to_combined_tag_map.items(): for pfx in ["B-", "I-"]: raw_id = tag2id_raw[pfx + key] if value != "DISCARD": combined_id = tag2id_combined[pfx + value] else: combined_id = tag2id_combined["O"] assert raw_id not in raw_to_combined_id raw_to_combined_id[raw_id] = combined_id raw_to_combined_id[tag2id_raw["O"]] = tag2id_combined["O"] raw_to_combined_id[-100] = -100 return raw_to_combined_id elif tag_names: tag_map_dct = {"O": "O"} for key, value in raw_to_combined_tag_map.items(): for item in value: for pfx in ["B-", "I-"]: if key != "DISCARD": tag_map_dct[pfx + item] = pfx + key else: tag_map_dct[pfx + item] = "O" return tag_map_dct
python
19
0.466667
80
44.421053
38
inline
package org.taitasciore.android.event; /** * Created by roberto on 19/04/17. */ public class RequestCountryAndCityEvent { }
java
5
0.728682
41
13.333333
9
starcoderdata
from django.core.files import File from mayan.apps.documents.models import Document from mayan.apps.documents.tests.base import GenericDocumentTestCase from mayan.apps.documents.tests.literals import ( TEST_COMPRESSED_DOCUMENT_PATH, TEST_SMALL_DOCUMENT_CHECKSUM, TEST_SMALL_DOCUMENT_PATH ) from ..source_backends.literals import SOURCE_UNCOMPRESS_CHOICE_ALWAYS from .mixins.base_mixins import InteractiveSourceBackendTestMixin from .mixins.web_form_source_mixins import WebFormSourceTestMixin class WebFormSourceBackendTestCase( InteractiveSourceBackendTestMixin, WebFormSourceTestMixin, GenericDocumentTestCase ): auto_create_test_source = False auto_upload_test_document = False def _process_test_document(self, test_file_path=TEST_SMALL_DOCUMENT_PATH): source_backend_instance = self.test_source.get_backend_instance() with open(file=test_file_path, mode='rb') as file_object: self.test_forms = { 'document_form': self.test_document_form, 'source_form': InteractiveSourceBackendTestMixin.MockSourceForm( file=File(file=file_object) ), } source_backend_instance.process_documents( document_type=self.test_document_type, forms=self.test_forms, request=self.get_test_request() ) def test_upload_simple_file(self): self._create_test_web_form_source() document_count = Document.objects.count() self._process_test_document() self.assertEqual(Document.objects.count(), document_count + 1) self.assertEqual( Document.objects.first().file_latest.checksum, TEST_SMALL_DOCUMENT_CHECKSUM ) def test_upload_compressed_file(self): self._create_test_web_form_source( extra_data={'uncompress': SOURCE_UNCOMPRESS_CHOICE_ALWAYS} ) document_count = Document.objects.count() self._process_test_document( test_file_path=TEST_COMPRESSED_DOCUMENT_PATH ) self.assertEqual(Document.objects.count(), document_count + 2) self.assertTrue( 'first document.pdf' in Document.objects.values_list( 'label', flat=True ) ) self.assertTrue( 'second document.pdf' in Document.objects.values_list( 'label', flat=True ) )
python
17
0.650264
80
32.22973
74
starcoderdata
def set_rgb_lut(myv_glyph): """ Sets the LUT of the Mayavi glyph to RGB-LUT. """ lut = myv_glyph.module_manager.scalar_lut_manager.lut lut._vtk_obj.SetTableRange(0, LUT_RGB.__lut__.shape[0]) lut.number_of_colors = LUT_RGB.__lut__.shape[0] lut.table = LUT_RGB.__lut__
python
9
0.571429
63
39.375
8
inline
import React from 'react'; import PropTypes from 'prop-types'; import DefaultStyleRoot from './styles/StyleRoot'; import withDragDropContext from './withDragDropContext'; import DefaultDragLayer from '../DragLayer'; import ReactDOM from 'react-dom'; import irisTheme from 'themes/irisTheme'; import * as styles from './styles'; import { Foreground } from 'behaviors'; /** * Including this provider at the root of your app will define some global styling, * and set up needed contexts for interactions like drag and drop. It also allows * you to control the theme programmatically or apply a different theme at a * particular level. */ class BandwidthProvider extends React.PureComponent { static propTypes = { /** * A custom theme; pass one of the themes from `themes/` or pass in your own JSON! */ customTheme: PropTypes.object, /** * The DOM element to attach the drag layer. By default, attaches it to this component */ dragLayerPortal: PropTypes.object, /** * The DOM element to provide to all Foreground components to render into. Skip this * prop and we will generate one for you inside BandwidthProvider */ foregroundLayerPortal: PropTypes.any, /** * Should the global style be skipped. Defaults to false. */ skipGlobalStyle: PropTypes.bool, /** * Custom StyleRoot component */ StyleRoot: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), /** * Custom drag layer component */ DragLayer: PropTypes.func, /** * Any stuff you want to render in your app */ children: PropTypes.node.isRequired, }; static defaultProps = { customTheme: irisTheme, dragLayerPortal: null, StyleRoot: styles.StyleRoot, DragLayer: DefaultDragLayer, skipGlobalStyle: false, }; static styles = styles; render() { const { StyleRoot, DragLayer, dragLayerPortal, customTheme, skipGlobalStyle, children, foregroundLayerPortal, } = this.props; return ( <StyleRoot className="styleroot"> <Foreground.Provider element={foregroundLayerPortal}> {children} {dragLayerPortal ? ( ReactDOM.createPortal(<DragLayer />, dragLayerPortal) ) : ( <DragLayer /> )} {skipGlobalStyle || <styles.GlobalStyle theme={customTheme} />} ); } } export default withDragDropContext(BandwidthProvider);
javascript
14
0.66311
90
28.483146
89
starcoderdata
func NewHTTPConnector( config_obj *api_proto.Config, manager *crypto.CryptoManager, logger *logging.LogContext) *HTTPConnector { max_poll := config_obj.Client.MaxPoll if max_poll == 0 { max_poll = 60 } tls_config := &tls.Config{ MinVersion: tls.VersionTLS12, } // For self signed certificates we must ignore the server name // and only trust certs issued by our server. if config_obj.UseSelfSignedSsl { logger.Info("Expecting self signed certificate for server.") CA_Pool := x509.NewCertPool() CA_Pool.AppendCertsFromPEM([]byte(config_obj.Client.CaCertificate)) tls_config.ServerName = constants.FRONTEND_NAME // We only trust **our** root CA. tls_config.RootCAs = CA_Pool } return &HTTPConnector{ manager: manager, logger: logger, minPoll: time.Duration(1) * time.Second, maxPoll: time.Duration(max_poll) * time.Second, urls: config_obj.Client.ServerUrls, client: &http.Client{ Transport: &http.Transport{ DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, }).DialContext, Proxy: http.ProxyFromEnvironment, MaxIdleConns: 100, IdleConnTimeout: 30 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, ResponseHeaderTimeout: 10 * time.Second, TLSClientConfig: tls_config, }, }, } }
go
29
0.680253
69
24.428571
56
inline
// Copyright (c) // Licensed under the Apache License, Version 2.0. using System; using System.Buffers.Binary; using System.IO; namespace SixLabors.ImageSharp.Formats.Tiff.Writers { /// /// Utility class for writing TIFF data to a <see cref="Stream"/>. /// internal sealed class TiffStreamWriter : IDisposable { private static readonly byte[] PaddingBytes = new byte[4]; /// /// A scratch buffer to reduce allocations. /// private readonly byte[] buffer = new byte[4]; /// /// Initializes a new instance of the <see cref="TiffStreamWriter"/> class. /// /// <param name="output">The output stream. public TiffStreamWriter(Stream output) => this.BaseStream = output; /// /// Gets a value indicating whether the architecture is little-endian. /// public bool IsLittleEndian => BitConverter.IsLittleEndian; /// /// Gets the current position within the stream. /// public long Position => this.BaseStream.Position; /// /// Gets the base stream. /// public Stream BaseStream { get; } /// /// Writes an empty four bytes to the stream, returning the offset to be written later. /// /// offset to be written later. public long PlaceMarker() { long offset = this.BaseStream.Position; this.Write(0u); return offset; } /// /// Writes an array of bytes to the current stream. /// /// <param name="value">The bytes to write. public void Write(byte[] value) => this.BaseStream.Write(value, 0, value.Length); /// /// Writes the specified value. /// /// <param name="value">The bytes to write. public void Write(ReadOnlySpan value) => this.BaseStream.Write(value); /// /// Writes a byte to the current stream. /// /// <param name="value">The byte to write. public void Write(byte value) => this.BaseStream.WriteByte(value); /// /// Writes a two-byte unsigned integer to the current stream. /// /// <param name="value">The two-byte unsigned integer to write. public void Write(ushort value) { if (this.IsLittleEndian) { BinaryPrimitives.WriteUInt16LittleEndian(this.buffer, value); } else { BinaryPrimitives.WriteUInt16BigEndian(this.buffer, value); } this.BaseStream.Write(this.buffer.AsSpan(0, 2)); } /// /// Writes a four-byte unsigned integer to the current stream. /// /// <param name="value">The four-byte unsigned integer to write. public void Write(uint value) { if (this.IsLittleEndian) { BinaryPrimitives.WriteUInt32LittleEndian(this.buffer, value); } else { BinaryPrimitives.WriteUInt32BigEndian(this.buffer, value); } this.BaseStream.Write(this.buffer.AsSpan(0, 4)); } /// /// Writes an array of bytes to the current stream, padded to four-bytes. /// /// <param name="value">The bytes to write. public void WritePadded(Span value) { this.BaseStream.Write(value); if (value.Length % 4 != 0) { this.BaseStream.Write(PaddingBytes, 0, 4 - (value.Length % 4)); } } /// /// Writes a four-byte unsigned integer to the specified marker in the stream. /// /// <param name="offset">The offset returned when placing the marker /// <param name="value">The four-byte unsigned integer to write. public void WriteMarker(long offset, uint value) { long back = this.BaseStream.Position; this.BaseStream.Seek(offset, SeekOrigin.Begin); this.Write(value); this.BaseStream.Seek(back, SeekOrigin.Begin); } public void WriteMarkerFast(long offset, uint value) { this.BaseStream.Seek(offset, SeekOrigin.Begin); this.Write(value); } /// /// Disposes <see cref="TiffStreamWriter"/> instance, ensuring any unwritten data is flushed. /// public void Dispose() => this.BaseStream.Flush(); } }
c#
17
0.561784
101
33.089041
146
starcoderdata
package pucrs.alpro2.tf.ocorrencias; import java.util.Calendar; public class OcorrenciaDiaSem extends Ocorrencia { private int dia_sem; public OcorrenciaDiaSem(Calendar c) { super(c); super.setValue(c); this.dia_sem = c.get(Calendar.DAY_OF_WEEK); } public int getDia_sem() { return this.dia_sem; } @Override public String toString() { switch(this.dia_sem) { case 1: return "DOMINGO"; case 2: return "SEGUNDA-FEIRA"; case 3: return "TERÇA-FEIRA"; case 4: return "QUARTA-FEIRA"; case 5: return "QUINTA-FEIRA"; case 6: return "SEXTA-FEIRA"; default: return "SÁBADO"; } } @Override public boolean equals(Object obj) { if (obj instanceof OcorrenciaDiaSem) { OcorrenciaDiaSem o = (OcorrenciaDiaSem) obj; return this.dia_sem == o.getDia_sem(); } return false; } }
java
9
0.653361
63
19.255319
47
starcoderdata
public void Epoch(Vector input, Vector expectedOutput) { Vector actualOutput = FeedForward(input); Vector error = expectedOutput.Expand(1d) - actualOutput; double[] nextError; // Loop over all the weight layers that need updating. for (int i = WeightCount - 1; i >= 0; i--) { Matrix weights = _weights[i]; double[,] deltaWeights = new double[weights.RowCount, weights.ColCount]; Vector sourceNodes = _previousRun[i]; Vector destNodes = _previousRun[i + 1]; nextError = new double[sourceNodes.Count]; // Loop over all the destination nodes in the current layer. for (int j = 0; j < destNodes.Count - 1; j++) { double sigma = 0d; for (int k = 0; k < sourceNodes.Count; k++) { // Console.WriteLine($"{k} {j}"); // Console.WriteLine(sourceNodes); // Console.WriteLine(weights); sigma += sourceNodes[k] * weights[j, k]; nextError[k] += error[j] * weights[j, k]; } double sigmoid = Program.Sigmoid(sigma); double total = -error[j] * sigmoid * (1 - sigmoid) * destNodes[j]; for (int k = 0; k < sourceNodes.Count; k++) { deltaWeights[j, k] += -(total * weights[j, k] * 0.1); } } error = Vector.Build(nextError.ToList()); _weights[i] += new Matrix().FromArray(deltaWeights); } }
c#
19
0.598507
76
26.9375
48
inline
#ifndef GPUMORPH_IMGIO_H #define GPUMORPH_IMGIO_H #include #include template <class T> void save(const std::string &fname, const rod::dimage &img); template <class T> void load(rod::dimage &img, const std::string &fname); #endif
c
8
0.716418
63
19.615385
13
starcoderdata
<?php namespace App\Libraries\Traits; use Illuminate\Database\Eloquent\Builder; trait Searchable { /** * Search the result follow the search request and columns searchable * * @param \Illuminate\Database\Eloquent\Builder $query query model * * @return void */ public function scopeSearch(Builder $query) { $query->select($this->getTable() . '.*'); $this->makeJoins($query); $this->makeSearch($query); $this->makeFilters($query); $this->makeOrderBy($query); } /** * Get columns searchable * * @return mixed */ protected function getColumnsSearch() { return array_get($this->searchable, 'columns', []); } /** * Get columns condition * * @return mixed */ protected function getColumnsCondition() { $array = array_get($this->searchable, 'conditions', []); return $this->unsetIfNullValue($array); } /** * Get columns orderable * * @return mixed */ protected function getColumnsOrder() { $array = array_get($this->searchable, 'orders', []); return $this->unsetIfNullValue($array); } /** * Get columns orderable * * @return mixed */ protected function getColumnsFilter() { $array = array_get($this->searchable, 'filters', []); return $this->unsetIfNullValue($array); } /** * Get joins * * @return mixed */ protected function getJoins() { return array_get($this->searchable, 'joins', []); } /** * Set search columns for searchable * * @param array $array [ 'table1' => ['column1', 'column2', ...], 'table2' => ['column3', 'column4', ...], ...] * * @return void */ public function setColumnsSearch($array) { $this->searchable['columns'] = $array; } /** * Set condition columns for condition search * * @param array $array [ 'table1' => ['column1', 'column2', ...], 'table2' => ['column3', 'column4', ...], ...] * * @return void */ public function setColumnsCondition($array) { $this->searchable['conditions'] = $array; } /** * Set order-by columns for order by * * @param array $array ['table1' => ['columns1' => 'desc', 'columns2' => 'asc', ...], 'table2' => ['columns1' => 'desc', 'columns2' => 'asc', ...], ...] * * @return void */ public function setColumnsOrder($array) { $this->searchable['orders'] = $array; } /** * Set order-by columns for filter * * @param array $array ['columns1' => 'desc', 'columns2' => 'asc', ...] * * @return void */ public function setColumnsFilter($array) { $this->searchable['filters'] = $array; } /** * Set 'joins table for searchable * * @param Array $array ['table1' => ['key1' => 'ref-key1'], 'table2' => ['key2', 'ref-key2'], ...] * * @return void */ public function setJoins($array) { $this->searchable['joins'] = $array; } /** * Make joins * * @param Builder $query query model * * @return void */ protected function makeJoins(Builder $query) { foreach ($this->getJoins() as $table => $foreign) { $query->leftJoin($table, function ($join) use ($table, $foreign) { foreach ($foreign as $key => $foreignKey) { $join->on($this->getTable() . '.' . $key, '=', $table . '.' . $foreignKey); } }); } } /** * Make order by * * @param Builder $query query model * * @return void */ protected function makeOrderBy(Builder $query) { foreach ($this->getColumnsOrder() as $key => $value) { if (is_array($value)) { foreach ($value as $column => $orderType) { $query = $query->orderBy($key . '.' . $column, $orderType); } } else { $query = $query->orderBy($this->getTable() . '.' . $key, $value); } } } /** * Make search * * @param Builder $query query model * * @return void */ protected function makeSearch(Builder $query) { $keyword = request('search'); if (isset($this->searchable['keyword'])) { $keyword = $this->searchable['keyword']; } $query->where(function ($subQuery) use ($keyword) { foreach ($this->getColumnsSearch() as $key => $value) { if (is_array($value)) { foreach ($value as $column) { $subQuery->orWhere($key . '.' . $column, "LIKE", "%$keyword%"); } } else { $subQuery->orWhere($this->getTable() . '.' . $value, "LIKE", "%$keyword%"); } } })->where(function ($subQuery) { foreach ($this->getColumnsCondition() as $key => $value) { if (is_array($value)) { foreach ($value as $column => $valueColumn) { if (is_array($valueColumn)) { $subQuery->where($key . '.' . $column, $valueColumn[0], $valueColumn[1]); } else { $subQuery->where($this->getTable() . '.' . $key, $value[0], $value[1]); } } } else { $subQuery->where($this->getTable() . '.' . $key, 'LIKE', "$value"); } }; }); } /** * Make filter * * @param Builder $query query model * * @return void */ protected function makeFilters(Builder $query) { $filters = []; foreach ($this->getColumnsFilter() as $key => $value) { if (is_array($value)) { foreach ($value as $column) { array_push($filters, $key . '.' . $column); } } else { array_push($filters, $this->getTable() . '.' . $value); } } if ($filters == []) { return; } $query->select($filters); } }
php
28
0.470111
156
25.585062
241
starcoderdata
var instance_skel = require('../../instance_skel'); const MarshallCamera = require('./visca/lib/Marshall/MarshallCamera'); const commands = require('./visca/lib/Marshall/commands') const { Range, List } = require('./visca/lib/Parameters'); class instance extends instance_skel { constructor(system, id, config) { super(system, id, config) this.initActions() } init() { this.camera = new MarshallCamera(this.config.host) } updateConfig(config) { if (this.config.host !== config.host) { this.camera = new MarshallCamera(config.host) } this.config = config } destroy() { } config_fields() { return [ { type: 'text', id: 'info', width: 12, label: 'Information', value: 'This will establish a TCP connection to the device' }, { type: 'textinput', id: 'host', label: 'Target IP', width: 6, regex: this.REGEX_IP } ] } initActions() { let actions = {} let commandsArray = Object.values(commands) for (const command of commandsArray) { const pattern = command.pattern const parameters = pattern.getParameters() let options = [] for (const parameter of parameters) { let option = { id: parameter.name, label: parameter.name, } option.tooltip = parameter.comment switch (parameter.constructor) { case Range: option.type = 'number', option.min = parameter.min, option.max = parameter.max, option.default = parameter.min option.required = true break case List: option.type = 'dropdown', option.choices = parameter.itemNameArray.map(itemName => ({ id: itemName, label: itemName})) option.default = parameter.itemNameArray[0] break } options.push(option) } const fullName = command.familyName ? `${command.familyName} - ${command.name}` : command.name actions[fullName] = { label: fullName, options: options, callback: ((action, _) => { this.camera.sendCommand(command, action.options) }) } } this.setActions(actions) } } exports = module.exports = instance;
javascript
17
0.475207
116
29.578947
95
starcoderdata
package gravitacija; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; public class Svemirac { /*crtanje karaktera kada "hoda" po donjoj liniji */ public void slikajdole(Graphics g2, int b){ if(b<20) g2.drawImage(slika_dole1,pocetakX,pocetakY,sirina,visina,null); else if(b<40) g2.drawImage(slika_dole2,pocetakX,pocetakY,sirina,visina,null); else if(b<60) g2.drawImage(slika_dole3,pocetakX,pocetakY,sirina,visina,null); else if(b<80) g2.drawImage(slika_dole4,pocetakX,pocetakY,sirina,visina,null); } /*crtanje karaktera kada "hoda" po gornjoj liniji */ public void slikajgore(Graphics g2, int b){ if(b<20) g2.drawImage(slika_gore1,pocetakX,pocetakY,sirina,visina,null); else if(b<40) g2.drawImage(slika_gore2,pocetakX,pocetakY,sirina,visina,null); else if(b<60) g2.drawImage(slika_gore3,pocetakX,pocetakY,sirina,visina,null); else if(b<80) g2.drawImage(slika_gore4,pocetakX,pocetakY,sirina,visina,null); } /*crtanje karaktera kada je u skoku*/ public void slikajskok(Graphics g2, int b){ if(b<20) g2.drawImage(slika_skok1,pocetakX,pocetakY,sirina,visina,null); else if(b<40) g2.drawImage(slika_skok2,pocetakX,pocetakY,sirina,visina,null); else if(b<60) g2.drawImage(slika_skok3,pocetakX,pocetakY,sirina,visina,null); else if(b<80) g2.drawImage(slika_skok4,pocetakX,pocetakY,sirina,visina,null); } /*da li karakter ima podlogu pod sobom, odnosno da li je potrebno da mu se menja "Y" koordinata*/ public int isImapodlogu(int a, int b, boolean c) { if ((pocetakY == 320-a*40 && c) || (pocetakY == 150+b*40 && !c)) return 2; if(pocetakY ==320 || pocetakY ==150 ) return 1; return 0; } /*da li je karakter zapeo o prepreku*/ public int zapeogore(){ if(pocetakY >= 150 && pocetakY < 190) return 1; return 0; } public int zapeodole(){ if(pocetakY <= 320 && pocetakY > 280) return 1; return 0; } /*kretanje karaktera duz "X" ose*/ public void unazad(){ pocetakX--; } /*kretanje karaktera duz "Y" ose*/ public void gore(){ pocetakY--; } public void dole(){ pocetakY++; } /*da li je karakter izguran sa prozora, da li je kraj igre*/ public boolean kraj(){ return pocetakX < -40 ? true:false; } /*Geteri i Seteri*/ public int getSirina() { return sirina; } public int getVisina() { return visina; } public int getPocetakY() { return pocetakY; } public int getPocetakX() { return pocetakX; } public void setPocetakX(int pocetakX) { this.pocetakX = pocetakX; } public void setPocetakY(int pocetakY) { this.pocetakY = pocetakY; } /*Slike koje ilustruju kretanje karaktera svemirom*/ private final Image slika_dole1 = Toolkit.getDefaultToolkit().getImage("slike/svemirac/dole1.png"); private final Image slika_dole2 = Toolkit.getDefaultToolkit().getImage("slike/svemirac/dole2.png"); private final Image slika_dole3 = Toolkit.getDefaultToolkit().getImage("slike/svemirac/dole3.png"); private final Image slika_dole4 = Toolkit.getDefaultToolkit().getImage("slike/svemirac/dole4.png"); private final Image slika_skok1 = Toolkit.getDefaultToolkit().getImage("slike/svemirac/skok1.png"); private final Image slika_skok2 = Toolkit.getDefaultToolkit().getImage("slike/svemirac/skok2.png"); private final Image slika_skok3 = Toolkit.getDefaultToolkit().getImage("slike/svemirac/skok3.png"); private final Image slika_skok4 = Toolkit.getDefaultToolkit().getImage("slike/svemirac/skok4.png"); private final Image slika_gore1 = Toolkit.getDefaultToolkit().getImage("slike/svemirac/gore1.png"); private final Image slika_gore2 = Toolkit.getDefaultToolkit().getImage("slike/svemirac/gore2.png"); private final Image slika_gore3 = Toolkit.getDefaultToolkit().getImage("slike/svemirac/gore3.png"); private final Image slika_gore4 = Toolkit.getDefaultToolkit().getImage("slike/svemirac/gore4.png"); private int pocetakX = 200; // Pocetna X koordinata karaktera private int pocetakY = 320; // Pocetna Y koordinata karaktera private int sirina = 50; // Sirina karaktera private int visina = 70; // Visina Karaktera }
java
13
0.732858
100
32.628099
121
starcoderdata
<?php namespace Gap\Open\Server\Grant; use Gap\Open\Dto\AuthCodeDto; use Gap\Open\Dto\AccessTokenDto; use Gap\Open\Server\Service\AuthCodeService; class AuthCodeGrant extends GrantBase { protected $authCodeService; public function authCode( string $appId, string $userId, string $redirectUrl, string $scope = '' ): ?AuthCodeDto { $authCodeService = $this->getAuthCodeService(); $authCode = $authCodeService->generate( $appId, $userId, $redirectUrl, $scope ); $authCodeService->create($authCode); return $authCode; } public function accessToken(string $appId, string $code): ?AccessTokenDto { $authCodeService = $this->getAuthCodeService(); $authCode = $authCodeService->fetch($code); if (is_null($authCode)) { return null; } if ($authCode->appId !== $appId) { throw new \Exception('appId not match'); } if (empty($authCode->userId)) { throw new \Exception('userId cannot be empty'); } $accessTokenService = $this->getAccessTokenService(); $refreshTokenService = $this->getRefreshTokenService(); $this->cnn->trans()->begin(); $userId = $authCode->userId; $scope = $authCode->scope; try { $refreshToken = $refreshTokenService->create([ 'appId' => $appId, 'userId' => $userId, 'scope' => $scope ]); $accessToken = $accessTokenService->create([ 'appId' => $appId, 'userId' => $userId, 'scope' => $scope, 'refresh' => $refreshToken->refresh ]); $authCodeService->destroy($authCode); } catch (\Exception $exp) { $this->cnn->trans()->rollback(); throw $exp; } $this->cnn->trans()->commit(); return $accessToken; } protected function getAuthCodeService(): AuthCodeService { if ($this->authCodeService) { return $this->authCodeService; } $this->authCodeService = new AuthCodeService( $this->repoManager, $this->cache ); return $this->authCodeService; } }
php
16
0.537603
77
26.5
88
starcoderdata
@Override public boolean hasExplicitPermission(PermissionEntry entry, Permission p) { // Jenkins will pass in the object Id as sid final String objectId = entry.getSid(); if (objectId == null) { return false; } PermissionEntry entry1 = new PermissionEntry(entry.getType(), objId2FullSidMap.getOrOriginal(objectId)); return super.hasExplicitPermission(entry1, p); }
java
9
0.665127
112
38.454545
11
inline
def get_build_index(config, subdir, clear_cache=False, omit_defaults=False): log = utils.get_logger(__name__) log.debug("Building new index for subdir '{}' with channels {}, condarc channels = {}".format( subdir, config.channel_urls, not omit_defaults)) # priority: local by croot (can vary), then channels passed as args, # then channels from config. if config.debug: log_context = partial(utils.LoggingContext, logging.DEBUG) if config.verbose: capture = contextlib.contextmanager(lambda: (yield)) log_context = partial(utils.LoggingContext, logging.INFO) else: capture = utils.capture log_context = partial(utils.LoggingContext, logging.CRITICAL + 1) # Note on conda and indexes: # get_index is unfortunately much more stateful than simply returning an index. # You cannot run get_index on one set of channels, and then later append a different # index from a different set of channels - conda has some other state that it is loading # and your second get_index will invalidate results from the first. =( # global CURRENT_INDEX # if CURRENT_INDEX.get(subdir) and not clear_cache: # index = CURRENT_INDEX[subdir] # else: urls = list(config.channel_urls) if os.path.isdir(config.croot): urls.insert(0, url_path(config.croot)) ensure_valid_channel(config.croot, subdir, config) # silence output from conda about fetching index files with log_context(): with capture(): try: index = get_index(channel_urls=urls, prepend=not omit_defaults, use_local=True, use_cache=False, platform=subdir) # HACK: defaults does not have the many subfolders we support. Omit it and try again. except CondaHTTPError: if 'defaults' in urls: urls.remove('defaults') index = get_index(channel_urls=urls, prepend=omit_defaults, use_local=True, use_cache=False, platform=subdir) # CURRENT_INDEX[subdir] = index or {} return index
python
16
0.587234
98
46.02
50
inline
class Node { constructor (e = null, next = null) { this.e = e; this.next = next; } } class LinkedList { constructor () { this.head = null; this.size = 0; } getSize () { return this.size; } isEmpty () { return this.size === 0; } add (index, e) { if (index < 0 || index > this.size) { throw new Error("Add failed. Illegal index."); } if (index === 0) { this.addFirst(e); } let prev = this.head; for (let i = 0; i < index - 1; i++) { prev = prev.next; } // let node = new Node(e); // node.next = prev.next; // prev.next = node; // 上面三句可以合成一句 prev.next = new Node(e, prev.next); this.size++; } addFirst (e) { // const node = new Node(e); // node.next = this.head; // this.head = node; this.head = new Node(e, head); size++; } addLast (e) { this.add(this.size, e); } } module.exports = LinkedList
javascript
11
0.504742
52
15.362069
58
starcoderdata
using NetCore2Blockly.Swagger; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NetCore2Blockly.JavascriptGeneration { /// /// generates js for seeing blocks in toolbox /// public class BlocklyToolBoxJSGenerator { /// /// Generates the blockly tool box value. /// /// <param name="types">The types. /// <param name="key">site key. /// public string GenerateBlocklyToolBoxValue(TypeArgumentBase[] types,string key="") { string blockText = ""; var globalVars = $"var glbVar{key}=function(workspace){{"; var sort = types.OrderBy(it => it.Name).ToArray(); foreach (var type in sort) { var typeName = type.TypeNameForBlockly; var newTypeName = type.TranslateToNewTypeName(); globalVars += $"workspace.createVariable('var_{typeName}', '{newTypeName}');"; blockText += $@"{Environment.NewLine} var blockText_{typeName} = '<block type=""{newTypeName}"">'; "; blockText = GenerateToolBoxCodeForAllPropertiesOfAType(blockText, type); blockText += $@"{Environment.NewLine}blockText_{typeName} += ' var block_{typeName}_dom = Blockly.Xml.textToDom(blockText_{typeName}); /*xmlList.push(block_{typeName}_dom);*/ var block_{typeName}Set=`<block type=""variables_set""><field name=""VAR"">var_{typeName} <value name=""VALUE"">${{blockText_{typeName}}} block_{typeName}Set = Blockly.Xml.textToDom(block_{typeName}Set); xmlList.push(block_{typeName}Set); "; } var strDef = $@" var registerValues{key} = function() {{ var xmlList = []; {blockText} return xmlList; }}; "; globalVars += "}"; strDef += globalVars; return strDef; } /// /// Generates tool box code for all properties of a type. /// /// <param name="blockText">The block text. /// <param name="type">The type. /// public string GenerateToolBoxCodeForAllPropertiesOfAType(string blockText, TypeArgumentBase type) { var validProperties = type.GetProperties(); foreach (var property in type.GetProperties()) { var propertyType = property.PropertyType; if (!propertyType.ConvertibleToBlocklyType()) continue; var typeName = type.TypeNameForBlockly; blockText += createBlockShadowDef(property.Name, propertyType.TranslateToBlocklyBlocksType()); blockText += $"blockText_{typeName} += blockTextLocalSiteFunctions;"; } return blockText; } string createBlockShadowDef(string name, string blockShadowType) { return $@"{Environment.NewLine} var blockTextLocalSiteFunctions = '<value name=""val_{name}""><shadow type=""{blockShadowType}""> "; } } }
c#
19
0.521271
195
36.14
100
starcoderdata
TEE_Result tee_mac_final( void *ctx, uint32_t algo, const uint8_t *data, size_t data_len, uint8_t *digest, size_t digest_len) { struct cbc_state *cbc; size_t pad_len; switch (algo) { case TEE_ALG_HMAC_MD5: case TEE_ALG_HMAC_SHA224: case TEE_ALG_HMAC_SHA1: case TEE_ALG_HMAC_SHA256: case TEE_ALG_HMAC_SHA384: case TEE_ALG_HMAC_SHA512: if (CRYPT_OK != hmac_process((hmac_state *)ctx, data, data_len)) return TEE_ERROR_BAD_STATE; if (CRYPT_OK != hmac_done((hmac_state *)ctx, digest, (unsigned long *)&digest_len)) return TEE_ERROR_BAD_STATE; break; case TEE_ALG_AES_CBC_MAC_NOPAD: case TEE_ALG_AES_CBC_MAC_PKCS5: case TEE_ALG_DES_CBC_MAC_NOPAD: case TEE_ALG_DES_CBC_MAC_PKCS5: case TEE_ALG_DES3_CBC_MAC_NOPAD: case TEE_ALG_DES3_CBC_MAC_PKCS5: cbc = (struct cbc_state *)ctx; if (TEE_SUCCESS != tee_mac_update(ctx, algo, data, data_len)) return TEE_ERROR_BAD_STATE; /* Padding is required */ switch (algo) { case TEE_ALG_AES_CBC_MAC_PKCS5: case TEE_ALG_DES_CBC_MAC_PKCS5: case TEE_ALG_DES3_CBC_MAC_PKCS5: /* * Padding is in whole bytes. The value of each added * byte is the number of bytes that are added, i.e. N * bytes, each of value N are added */ pad_len = cbc->block_len - cbc->current_block_len; memset(cbc->block+cbc->current_block_len, pad_len, pad_len); cbc->current_block_len = 0; if (TEE_SUCCESS != tee_mac_update( ctx, algo, cbc->block, cbc->block_len)) return TEE_ERROR_BAD_STATE; break; default: /* nothing to do */ break; } if ((!cbc->is_computed) || (cbc->current_block_len != 0)) return TEE_ERROR_BAD_STATE; memcpy(digest, cbc->digest, MIN(digest_len, cbc->block_len)); tee_cipher_final(&cbc->cbc, algo); break; case TEE_ALG_AES_CMAC: if (CRYPT_OK != omac_process((omac_state *)ctx, data, data_len)) return TEE_ERROR_BAD_STATE; if (CRYPT_OK != omac_done((omac_state *)ctx, digest, (unsigned long *)&digest_len)) return TEE_ERROR_BAD_STATE; break; default: return TEE_ERROR_NOT_SUPPORTED; } return TEE_SUCCESS; }
c
15
0.654362
66
26.103896
77
inline
#ifndef NCODE_HTSIM_UDP_H #define NCODE_HTSIM_UDP_H #include #include "../common/common.h" #include "../common/logging.h" #include "../net/net_common.h" #include "packet.h" namespace ncode { namespace htsim { class UDPSource : public Connection { public: UDPSource(const std::string& id, const net::FiveTuple& five_tuple, PacketHandler* out_handler, EventQueue* event_queue); void AddData(uint64_t data) override; void Close() override { CHECK(false) << "Cannot close a UDP connection"; } void ReceivePacket(PacketPtr pkt) override { Unused(pkt); CHECK(false) << "UDP sources should not receive any packets"; } private: DISALLOW_COPY_AND_ASSIGN(UDPSource); }; class UDPSink : public Connection { public: UDPSink(const std::string& id, const net::FiveTuple& five_tuple, PacketHandler* out_handler, EventQueue* event_queue); void AddData(uint64_t data) override { Unused(data); CHECK(false) << "UDP sinks cannot send data"; } void Close() override { CHECK(false) << "Cannot close a UDP connection"; } private: void ReceivePacket(PacketPtr pkt) override; DISALLOW_COPY_AND_ASSIGN(UDPSink); }; } // namespace htsim } // namespace ncode #endif
c
14
0.69237
76
22.245283
53
starcoderdata
<?php namespace AppBundle\Repository; use AppBundle\Entity\Visite; class VisiteRepository extends \Doctrine\ORM\EntityRepository { /** * @param mixed $ip Adresse IP de l'utilisateur * @param mixed $userAgent UserAgent de l'utilisateur * @param int $seconds Nombre de secondes d'une période * @return mixed La visite la plus récente de la période s'il y en a une, null sinon * @throws \Doctrine\ORM\NonUniqueResultException */ public function findLastVisitPeriod(Visite $visite, int $seconds) { $dateLastPeriod = (new \DateTime())->modify('-' . $seconds . ' seconds'); $query = $this->createQueryBuilder('v') ->where("v.ip = :ip")->setParameter("ip", $visite->getIp()) ->andWhere("v.userAgent = :userAgent")->setParameter("userAgent", $visite->getUserAgent()) ->andWhere("v.dateVisite > :dateVisite")->setParameter("dateVisite", $dateLastPeriod) ->orderBy("v.dateVisite", 'DESC') ->setMaxResults(1) ->getQuery(); return $query->getOneOrNullResult(); } /** * Retourne un tableau de statistiques de l'entité * * @return array Un tableau contenant des statistiques * @throws \Doctrine\ORM\NoResultException * @throws \Doctrine\ORM\NonUniqueResultException */ public function getStat() { $array = array(); $array['total'] = $this->createQueryBuilder('v') ->select('count(v) total') ->getQuery()->getSingleResult()['total']; $dateJ30 = new \DateTime(); $dateJ30->setTimestamp($dateJ30->getTimestamp() - (3600 * 24 * 30)); $array['j30'] = $this->createQueryBuilder('v') ->select('count(v) j30') ->where('v.dateVisite > :j30')->setParameter('j30', $dateJ30) ->getQuery()->getSingleResult()['j30']; $dateJ7 = new \DateTime(); $dateJ7->setTimestamp($dateJ7->getTimestamp() - (3600 * 24 * 7)); $array['j7'] = $this->createQueryBuilder('v') ->select('count(v) j7') ->where('v.dateVisite > :j7')->setParameter('j7', $dateJ7) ->getQuery()->getSingleResult()['j7']; $dateH24 = new \DateTime(); $dateH24->setTimestamp($dateH24->getTimestamp() - (3600 * 24)); $array['h24'] = $this->createQueryBuilder('v') ->select('count(v) h24') ->where('v.dateVisite > :h24')->setParameter('h24', $dateH24) ->getQuery()->getSingleResult()['h24']; return $array; } }
php
20
0.58678
102
34.930556
72
starcoderdata
protected void updateRequestWithIndexAndRoutingOptions(Select select, SearchRequestBuilder request) { for (Hint hint : select.getHints()) { if (hint.getType() == HintType.IGNORE_UNAVAILABLE) { //saving the defaults from TransportClient search request.setIndicesOptions(IndicesOptions.fromOptions(true, false, true, false, IndicesOptions.strictExpandOpenAndForbidClosed())); } if (hint.getType() == HintType.ROUTINGS) { Object[] routings = hint.getParams(); String[] routingsAsStringArray = new String[routings.length]; for (int i = 0; i < routings.length; i++) { routingsAsStringArray[i] = routings[i].toString(); } request.setRouting(routingsAsStringArray); } } }
java
14
0.596065
146
53.0625
16
inline
def is_private_packs_updated(public_index_json, private_index_path): """ Checks whether there were changes in private packs from the last upload. The check compares the `content commit hash` field in the public index with the value stored in the private index. If there is at least one private pack that has been updated/released, the upload should be performed and not skipped. Args: public_index_json (dict) : The public index.json file. private_index_path (str): Path to where the private index.zip is located. Returns: is_private_packs_updated (bool): True if there is at least one private pack that was updated/released, False otherwise (i.e there are no private packs that have been updated/released). """ logging.debug("Checking if there are updated private packs") private_index_file_path = os.path.join(private_index_path, f"{GCPConfig.INDEX_NAME}.json") private_index_json = load_json(private_index_file_path) private_packs_from_private_index = private_index_json.get("packs") private_packs_from_public_index = public_index_json.get("packs") if len(private_packs_from_private_index) != len(private_packs_from_public_index): # private pack was added or deleted logging.debug("There is at least one private pack that was added/deleted, upload should not be skipped.") return True id_to_commit_hash_from_public_index = {private_pack.get("id"): private_pack.get("contentCommitHash", "") for private_pack in private_packs_from_public_index} for private_pack in private_packs_from_private_index: pack_id = private_pack.get("id") content_commit_hash = private_pack.get("contentCommitHash", "") if id_to_commit_hash_from_public_index.get(pack_id) != content_commit_hash: logging.debug("There is at least one private pack that was updated, upload should not be skipped.") return True logging.debug("No private packs were changed") return False
python
11
0.691973
118
52.051282
39
inline
package com.zenhomes.gateway.config; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; import springfox.documentation.swagger.web.SwaggerResource; import springfox.documentation.swagger.web.SwaggerResourcesProvider; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Component @Primary @EnableAutoConfiguration @EnableSwagger2 public class GatewaySwaggerResourceProvider implements SwaggerResourcesProvider { @Autowired private DiscoveryClient discoveryClient; public GatewaySwaggerResourceProvider() { } @Override public List get() { return this.discoveryClient.getServices().stream().map(serviceName -> { ServiceInstance instance = discoveryClient.getInstances(serviceName).get(0); return swaggerResource(serviceName, instance.getUri().toString() + "/v2/api-docs", ""); }).collect(Collectors.toList()); } private SwaggerResource swaggerResource(String name, String location, String version) { SwaggerResource swaggerResource = new SwaggerResource(); swaggerResource.setName(name); swaggerResource.setLocation(location); swaggerResource.setSwaggerVersion(version); return swaggerResource; } }
java
16
0.826715
121
34.361702
47
starcoderdata
_registerCommands() { let commandGroups = this.commandGroups.array(); for(let i=0; i<commandGroups.length; i++) { //iterate through groups let groupDirectoryPath = this._getGroupDirectoryPath(commandGroups[i].id); let groupDirectoryFiles = fs.readdirSync(groupDirectoryPath); for(let j=0; j<groupDirectoryFiles.length; j++) { //iterate through files in a groups directory let fileSplit = groupDirectoryFiles[j].split('.'); let fileExt = fileSplit[fileSplit.length-1]; if(fileExt !== 'js') continue; //exclude any file without a .js extension this._registerCommand(commandGroups[i].id, `${groupDirectoryPath}/${groupDirectoryFiles[j]}`); //register file as a command } } return this; }
javascript
12
0.623798
139
58.5
14
inline
import requests import re from lxml import html, etree def scrape_acm(page): tree = html.fromstring(page.content) author_affiliations = [] # The ACM author affiliations are stored in a kind of nasty table layout, # best to view source or inspect element on their page for an explanation of this. authors = tree.xpath('//td/a[@title="Author Profile Page"]') for a in authors: affiliation = a.getparent().getnext().find("a/small") # If we don't find it under a URL it's likely just a if affiliation == None: affiliation = a.getparent().getnext().find("small") if affiliation != None: affiliation = affiliation.text else: affiliation = "None" author_affiliations.append(affiliation) return author_affiliations # IEEE Actually has an API! So we use that to get author affilation information from them def scrape_ieee(doi_url): match_doi = re.compile("http:\/\/.*doi[^\/]*\/(.+)") doi = match_doi.match(doi_url) if doi: doi = doi.group(1) page = requests.get("http://ieeexplore.ieee.org/gateway/ipsSearch.jsp?doi=" + doi) tree = etree.fromstring(page.content) authors = tree.xpath("//authors/text()") affiliations = tree.xpath("//affiliations/text()") return affiliations # Returns an array of the author affilations, ordered by the author appearance list on the paper # e.g. first author, second author, etc. This is done because we can't assume the names in the DBLP # database exactly match the names shown on the webpage. def scrape_affiliation(doi): if doi: # The doi urls are typically just http://dx.doi.org/... and we get the actual publication host # by following the redirect, so we must hit the page before we know if we can handle the URL # or not. try: page = requests.get(doi) if page.url.startswith("http://dl.acm.org/"): return scrape_acm(page) elif page.url.startswith("http://www.computer.org/") \ or page.url.startswith("http://ieeexplore.ieee.org/"): return scrape_ieee(doi) print("Warning! Unhandled Journal Site {}".format(page.url)) except: print("Warning! Exception encountered when processing {}".format(page.url)) else: print("Warning! Empty DOI URL") return None
python
15
0.640481
102
42.77193
57
starcoderdata
<div class="container"> <div class="divider"> <div class="carousel carousel-slider "> <a class="carousel-item"><img src="http://images.paginasamarillas.com/16778864/10/animation/2.jpg"> <a class="carousel-item"><img src="http://images.paginasamarillas.com/16778864/10/animation/4.jpg"> <a class="carousel-item"><img src="http://images.paginasamarillas.com/15458079/63/animation/3.jpg"> <a class="carousel-item"><img src="https://cdn1.elblogdelasalud.info/wp-content/uploads/2016/12/Diario-de-un-microbiologo-medico.jpg"> <a class="carousel-item"><img src="http://www.lei.com.mx/images/images/content/microbiologia.jpg"> <a class="carousel-item"><img src="<?= base_url();?>images/galeria_calidad_mod1.jpg"> <button class="btn transparent left" id="beforeButton"><i class="material-icons black-text">navigate_before <button class="btn transparent right" id="nextButton"><i class="material-icons black-text">navigate_next <div class="section"> <div class="section">
php
4
0.696751
143
60.611111
18
starcoderdata
using System.Collections.Generic; using System.Linq; namespace LineEngine { public interface IAnimated { Animation Animation { get; } Dictionary<string, Animation> Animations { get; } Sprite Sprite { get; } Animation GetAnimation(); Animation GetDefaultAnimation(); Animation SetDefaultAnimation(Animation animation); Animation SetAnimation(string name); } public interface ITranslatable { void Translate(int x, int y); void Translate(Point point); // : planned // void Rotate(); // void Scale(); } public interface IPositional { bool IsTouching(); bool XIsTouching(); bool YIsTouching(); bool IsOffScreen(); } public class Renderable { public string Id { get; } private Animation ActualAnimation { get; set; } public Animation Animation => GetAnimation(); public Dictionary<string, Animation> Animations { get; } public Sprite Sprite => ActualAnimation == null ? null : Animation.Sprite; protected Renderable() { Id = null; ActualAnimation = null; Animations = new Dictionary<string, Animation>(); } protected Renderable(string id) { Id = id; ActualAnimation = null; Animations = new Dictionary<string, Animation>(); } protected Animation GetAnimation() { return ActualAnimation ?? GetDefaultAnimation(); } protected Animation GetDefaultAnimation() { return Animations["default"]; } protected Animation SetDefaultAnimation(Animation animation) { Animations.Add("default", animation); ActualAnimation = Animations["default"]; return ActualAnimation; } public Animation SetAnimation(string name) { var oldOrigin = Animation.Sprite.Origin; var animation = Animations[name]; if (animation == null) return GetDefaultAnimation(); animation.Sprites.ToList().ForEach(s => s.Origin = oldOrigin); return ActualAnimation = animation; } public Renderable Start(Game game) { GetAnimation().Start(game); return this; } // Translation // ReSharper disable once UnusedMember.Global public void Translate(int x, int y) { foreach (var sprite in Animation.Sprites) { sprite.Translate(y, x); } } // ReSharper disable once UnusedMember.Global public void Translate(Point point) { foreach (var sprite in Animation.Sprites) { sprite.Translate(point); } } } }
c#
14
0.553463
82
25.553571
112
starcoderdata
package com.taotao.service.impl; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.taotao.common.pojo.EUTreeNode; import com.taotao.common.utils.TaotaoResult; import com.taotao.mapper.TbContentCategoryMapper; import com.taotao.pojo.TbContentCategory; import com.taotao.pojo.TbContentCategoryExample; import com.taotao.pojo.TbContentCategoryExample.Criteria; import com.taotao.service.ContentCategoryService; @Service public class ContentCategoryServiceImpl implements ContentCategoryService { @Autowired private TbContentCategoryMapper contentCategoryMapper; @Override public List getCategoryList(long parentId) { TbContentCategoryExample example = new TbContentCategoryExample(); Criteria criteria = example.createCriteria(); criteria.andParentIdEqualTo(parentId); List list = contentCategoryMapper.selectByExample(example); List result = new ArrayList<>(); for (TbContentCategory category : list) { EUTreeNode node = new EUTreeNode(); node.setId(category.getId()); node.setText(category.getName()); node.setState(category.getIsParent() ? "closed" : "open"); result.add(node); } return result; } @Override public TaotaoResult insertCategory(long parentId, String name) { TbContentCategory category = new TbContentCategory(); category.setName(name); category.setParentId(parentId); category.setIsParent(false); category.setStatus(1); category.setSortOrder(1); category.setCreated(new Date()); category.setUpdated(new Date()); contentCategoryMapper.insert(category); // 更新父节点 TbContentCategory parent = contentCategoryMapper.selectByPrimaryKey(parentId); if (!parent.getIsParent()) { parent.setIsParent(true); contentCategoryMapper.updateByPrimaryKey(parent); } // 返回结果 return TaotaoResult.ok(category); } @Override public TaotaoResult deleteCategory(long id) { // 递归删除 TbContentCategory category = contentCategoryMapper.selectByPrimaryKey(id); deleteCats(category); // 如果父节点没有子节点,修改parent // 得到parentID long parentId = category.getParentId(); TbContentCategoryExample example = new TbContentCategoryExample(); Criteria criteria = example.createCriteria(); criteria.andParentIdEqualTo(parentId); List list = contentCategoryMapper.selectByExample(example); if (list == null || list.size() == 0) { TbContentCategory parent = contentCategoryMapper.selectByPrimaryKey(parentId); parent.setIsParent(false); contentCategoryMapper.updateByPrimaryKey(parent); } return TaotaoResult.ok(); } private void deleteCats(TbContentCategory category) { if (category.getIsParent()) { TbContentCategoryExample example = new TbContentCategoryExample(); Criteria criteria = example.createCriteria(); criteria.andParentIdEqualTo(category.getId()); List list = contentCategoryMapper.selectByExample(example); // 遍历节点的子节点,并删除 for (TbContentCategory child : list) { deleteCats(child); } // 删除完子节点后,更新为叶子节点 contentCategoryMapper.deleteByPrimaryKey(category.getId()); } else { contentCategoryMapper.deleteByPrimaryKey(category.getId()); } } @Override public TaotaoResult updateCategory(long id, String name) { TbContentCategory category = contentCategoryMapper.selectByPrimaryKey(id); category.setName(name); contentCategoryMapper.updateByPrimaryKey(category); return TaotaoResult.ok(); } }
java
13
0.777343
81
29.818966
116
starcoderdata
#include "myhead.h" void transpose(float * a, int m, int n) { float *tmp = (float *)malloc(m * n * sizeof(float)); for (int i = 0; i < m; i++) for(int j = 0; j < n; j++) tmp[j * m + i] = a[i * n + j]; for (int i = 0; i < m * n; i++) a[i] = tmp[i]; free(tmp); } // a: m x n, b: n x k, c = a * b = m x k void matrmul(MPI_Comm comm, int np, int iam, float *a, float *b, float *c, int m, int n, int k) { float *partialA = (float *)malloc((m / np * n) * sizeof(float)); float *partialB = (float *)malloc((k / np * n) * sizeof(float)); float *bufferPartialB = (float *)malloc((k / np * n) * sizeof(float)); // for send & recv float *partialC = (float *)malloc((m / np * k / np) * sizeof(float)); float *buffer; // process 0 only MPI_Status status; int next = (iam + 1) % np; int prev = (iam - 1 + np) % np; if (iam == 0) { buffer = (float *)malloc(np * (m /np * k / np) * sizeof(float)); printf("Process %d: np = %d, m = %d, n = %d, k = %d\n", iam, np, m, n, k); //printf("Process %d: sizeof partial a = %d\n", iam, (m / np * n)); //printf("Process %d: sizeof partial b = %d\n", iam, (k / np * n)); //printf("Process %d: sizeof partial c = %d\n", iam, (m / np * k / np)); } // load data for (int i = 0; i < (m / np); i++) for(int j = 0; j < n; j++) { partialA[i * n + j] = a[(m / np * iam + i) * n + j]; //printf("Process %d: partialA[%d] = %f\n", iam, j, partialA[j]); } transpose(b, n, k); // transpose matrix b: n*k ==> k*n for (int i = 0; i < (k / np); i++) for (int j = 0; j < n; j++) { partialB[i * n + j] = b[(k / np * iam + i) * n + j]; //printf("Process %d: partialB[%d] = %f\n", iam, j, partialB[j]); } for (int step = 0; step < np; step++) { for (int i = 0; i < (m / np * k / np); i++) partialC[i] = 0; if (iam == 0) printf("Process %d: Calculation step %d.\n", iam, step); // Generate partial result for (int i = 0; i < (m / np); i++) for (int j = 0; j < (k / np); j++) for (int tmp = 0; tmp < n; tmp++) { partialC[i * m / np + j] += partialA[i * n + tmp] * partialB[j * n + tmp]; if(iam == 0) printf("Process %d: tmp = %d, a = %f, b = %f, c = %f\n", iam, tmp, partialA[i * n + tmp], partialB[j * k + tmp], partialC[i * m / np + j]); } // Gather partial result to process 0 MPI_Gather(partialC, (m /np * k / np), MPI_FLOAT, buffer, (m /np * k / np), MPI_FLOAT, 0, comm); //printf("Process %d: Results gathered.\n", iam); // c[i + process * (m / np)][j + ((process + step) % np) * (k / np)] = buffer[process][i][j]; if (iam == 0) for (int process = 0; process < np; process++) for(int i = 0; i < (m / np); i++) for(int j = 0; j < (k / np); j++) c[(i + (process * (m / np))) * k + (j + (((process + step) % np) * (k / np)))] = buffer[process * (m / np * k / np) + i * (k / np) + j]; // exchange matrix partial b if (iam == 0) { MPI_Send(partialB, (k / np * n), MPI_FLOAT, prev, 1, comm); //printf("Process %d: Partial matrix b send.\n", iam); MPI_Recv(bufferPartialB, (k / np * n), MPI_FLOAT, next, 1, comm, &status); //printf("Process %d: Partial matrix b received.\n", iam); } else { MPI_Recv(bufferPartialB, (k / np * n), MPI_FLOAT, next, 1, comm, &status); //printf("Process %d: Partial matrix b received.\n", iam); MPI_Send(partialB, (k / np * n), MPI_FLOAT, prev, 1, comm); //printf("Process %d: Partial matrix b send.\n", iam); } for (int i = 0; i < (k / np * n); i++) partialB[i] = bufferPartialB[i]; //printf("Process %d: Exchange matrix partial B.\n", iam); } }
c
21
0.491356
145
35.795918
98
starcoderdata
package config // Storage storage config type Storage struct { Dir string `yaml:"dir" json:"dir"` }
go
6
0.748252
40
19.428571
7
starcoderdata
const CartItemsList = (props) => { const cartItems = ( {[{ id: "item1", name: "placeholderName", amount: 2, price: 12.99 }].map( (item) => ( <li key={item.id}>{item.name} ) )} ); return ( {cartItems} <button onClick={props.onClick}>Close ); }; export default CartItemsList;
javascript
17
0.496416
79
19.666667
27
starcoderdata
void init_video(void); void check_coincidence(void); void update_STAT(void); void cycle_video(void); unsigned char bg_display; unsigned char sprite_display_enable; unsigned char sprite_size; unsigned char bg_tile_map_display_select; unsigned char bg_window_tile_data_select; unsigned char window_display_enable; unsigned char window_tile_map_display_select; unsigned char lcd_display_enable; unsigned char lcd_line; unsigned char lcd_coincidence_flag; unsigned char mode_0_H_Blank_interrupt; unsigned char mode_1_V_Blank_interrupt; unsigned char mode_2_OAM_interrupt; unsigned char LYC_LY_coincidence_interrupt; unsigned char lcd_scroll_y; unsigned char lcd_scroll_x; unsigned char lcd_mode_flag; unsigned char lcd_LY_compare; unsigned char window_y_pos; unsigned char shade_for_color_0; unsigned char shade_for_color_1; unsigned char shade_for_color_2; unsigned char shade_for_color_3; unsigned char sprite_0_shade_for_color_0; unsigned char sprite_0_shade_for_color_1; unsigned char sprite_0_shade_for_color_2; unsigned char sprite_1_shade_for_color_0; unsigned char sprite_1_shade_for_color_1; unsigned char sprite_1_shade_for_color_2; unsigned char window_y_position; unsigned char window_x_position; unsigned int lcd_cycles; #define DURING_H_BLANK 0 #define DURING_V_BLANK 1 #define DURING_SEARCHING_OAM_RAM 2 #define DURING_TRANSFER_DATA_TO_LCD 3
c
5
0.780347
45
31.952381
42
starcoderdata
#!/usr/bin/env python """Tests for `zeppelin` package.""" import pytest import os.path from zeppelin.scrape_lyrics import save_all_lyrics from zeppelin.create_lyricscorpus import create_corpuslist from zeppelin.model import vectors_and_df, predict # decorators to get the links @pytest.fixture def link(): url = 'https://www.lyrics.com/artist/Koffee/3491656' url, directory = save_all_lyrics(url, 'Koffee') return directory @pytest.fixture def link_2(): url = 'https://www.lyrics.com/artist/MF-Doom/300089' url, directory = save_all_lyrics(url, 'MFDOOM') return directory # test generating correct numbers of sub-directories PASSING_CONDITIONS = ['https://www.lyrics.com/artist/Koffee/3491656', 'https://www.lyrics.com/artist/MF-Doom/300089', 'https://www.lyrics.com/artist/Danger-Doom/742954'] NAME = ['Koffee', 'MF DOOM', 'Danger Doom'] @pytest.mark.parametrize("url", PASSING_CONDITIONS, "name", NAME) def test_save_all_lyrics(url, name): url, name = save_all_lyrics(url, name) files_list = os.listdir('lyrics-files/') assert len(files_list) == 3 # test if the corpus lists have correct size def test_create_corpuslist(name): create_corpuslist(NAME) assert len(CORPUS) == len(LABEL) # test the possible outcomes of the predictions and the merge and train function def test_model(): df, vectorizer = vectors_and_df(CORPUS, LABEL) prediction = predict("ANY LYRICS") assert prediction == ['Koffee'] or prediction == ['MF DOOM']
python
9
0.715719
80
31.5
46
starcoderdata
/* ****************************************************************** ** ** OpenSees - Open System for Earthquake Engineering Simulation ** ** Pacific Earthquake Engineering Research Center ** ** ** ** ** ** (C) Copyright 1999, The Regents of the University of California ** ** All Rights Reserved. ** ** ** ** Commercial use of this program without express permission of the ** ** University of California, Berkeley, is strictly prohibited. See ** ** file 'COPYRIGHT' in main directory for information on usage and ** ** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. ** ** ** ** Developed by: ** ** ( ** ** ( ** ** ( ** ** ** ** ****************************************************************** */ // $Revision: 1.8 $ // $Date: 2007-02-02 01:18:42 $ // $Source: /usr/local/cvs/OpenSees/SRC/material/section/fiber/Fiber.h,v $ // File: ~/fiber/Fiber.h // // Written: // Created: 10/98 // Revision: // // Description: This file contains the class definition for // Fiber. Fiber is an abstract base class and thus no objects of // it's type can be instatiated. It has pure virtual functions which // must be implemented in it's derived classes. // // What: "@(#) Fiber.h, revA" #ifndef Fiber_h #define Fiber_h #include #include #include class Matrix; class ID; class UniaxialMaterial; class NDMaterial; class Information; class Response; class Fiber : public TaggedObject, public MovableObject { public: Fiber (int tag, int classTag); virtual ~Fiber(); virtual int setTrialFiberStrain(const Vector &vs)=0; virtual Vector &getFiberStressResultants(void) =0; virtual Matrix &getFiberTangentStiffContr(void) =0; virtual int commitState(void)=0; virtual int revertToLastCommit(void)=0; virtual int revertToStart(void)=0; virtual Fiber *getCopy(void) = 0; virtual int getOrder(void) = 0; virtual const ID &getType(void) = 0; virtual Response *setResponse(const char **argv, int argc, OPS_Stream &s); virtual int getResponse(int responseID, Information &info); virtual void getFiberLocation(double &y, double &z) =0; virtual double getArea(void) =0; virtual UniaxialMaterial *getMaterial(void) {return 0;} virtual NDMaterial *getNDMaterial(void) {return 0;} virtual const Vector &getFiberSensitivity(int gradNumber, bool cond); virtual int commitSensitivity(const Vector &dedh, int gradNumber, int numGrads); protected: Vector *sDefault; Matrix *fDefault; private: }; #endif
c
11
0.503842
78
35.782609
92
starcoderdata
namespace Xena.Contracts.ApiRoutes { public class ReportEmailSetupRoutes : BaseRoutes { /// public const string Base = "Fiscal/{fiscalId}/ReportEmailSetup"; /// public const string GetForPartner = "ForPartner"; } }
c#
7
0.688312
72
28.692308
13
starcoderdata
# -*- coding: utf-8 -*- import json import sys from . import Phantom phantom = Phantom() conf = { 'headers': { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.72 Safari/537.36", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3", "Sec-Fetch-Mode": "navigate", 'Sec-Fetch-Site': 'same-origin', 'Upgrade-Insecure-Requests': '1', } } conf.update(json.loads(sys.argv[1])) if __name__ == '__main__': a = phantom.download_page(conf, ssl_verify=False) print(a)
python
8
0.629794
139
27.25
24
starcoderdata
<?php use yii\widgets\ListView; use yii\helpers\ArrayHelper; use yii\helpers\Url; use yii\widgets\Pjax; use yii\helpers\Html; use yii\widgets\ActiveForm; ?> <div uk-height-viewport class="uk-flex uk-flex-middle bg-gradient-primary log-wrap"> <div class="uk-width-1-3@m uk-width-1-3@s m-auto rounded"> <div class="uk-child-width-1-1@m uk-grid-collapse " uk-grid> <!-- column one --> <div class="uk-margin-auto-vertical uk-text-center uk-animation-scale-up p-3 uk-light"> <img src="<?= Yii::$app->request->baseUrl; ?>/images/lootah.png" /> <!-- column two --> <div class="uk-card-default py-4 px-5"> <div class="mt-4 mb-2 uk-text-center"> <h3 class="mb-0">Forgot Password <p class="my-2">Enter your emailid <form name="frm" onsubmit="return validation();" class="uk-grid-small uk-grid" action="<?= Yii::$app->request->baseUrl; ?>/stationoperator/forgotpwdsub" method="POST"> <div class="uk-form-group"> <label class="uk-form-label"> Email <div class="uk-position-relative w-100"> <span class="uk-form-icon"> <i class="icon-feather-mail"> <input class="uk-input" type="email" name="email" id="email" placeholder="Enter your emailid"> <span id="result"> <div class="mt-4 uk-flex-middle uk-grid-small" uk-grid> <div class="uk-width-expand@s"> to <a href="<?= Yii::$app->request->baseUrl; ?>/stationoperator/index">Login <div class="uk-width-auto@s"> <button type="submit" class="btn btn-primary">Update End column two --> input, input[type="text"]{ padding: 0 36px; } input, input[type="password"]{ padding: 0 36px; } //$(document).ready(function(){ function validation() { event.preventDefault(); var str = $("#email").val(); $.ajax({ type: "POST", url: "<?= Yii::$app->request->baseUrl. '/stationoperator/findemail'; ?>", dataType: "text", data: {email:str}, success: function (response) { if(response=="0"){ $("#result").html("Invalid emailid!"); $("#result").css("color", "red"); return false; }else{ document.frm.submit(); return true; } }, }); } //});
php
7
0.447458
167
34.67033
91
starcoderdata
import React from 'react'; import { render } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import Contact from '../Contact'; describe('<Contact />', () => { const setup = (overrides) => { const props = { handleClose: jest.fn(), ...overrides }; const R = render(<Contact {...props} />); return { ...R, props }; }; beforeAll(() => { // eslint-disable-next-line no-console console.error = jest.fn(); }); afterAll(() => { jest.resetAllMocks(); jest.clearAllMocks(); }); it('calls fetch on submit', async () => { global.fetch = jest.fn(() => Promise.resolve()); jest.spyOn(global, 'fetch'); const { getByRole, getByPlaceholderText } = setup(); expect(global.fetch).not.toHaveBeenCalled(); userEvent.type(getByPlaceholderText('Prince'), 'Bob'); userEvent.type(getByPlaceholderText('Nelson'), 'Dylan'); userEvent.type(getByPlaceholderText(' ' userEvent.click(getByRole('button')); expect(await global.fetch).toHaveBeenCalled(); }); it('calls handleClose on submit', async () => { const handleClose = jest.fn(); global.fetch = jest.fn(() => Promise.resolve()); const { getByRole, getByPlaceholderText } = setup({ handleClose }); expect(handleClose).not.toHaveBeenCalled(); userEvent.type(getByPlaceholderText('Prince'), 'Bob'); userEvent.type(getByPlaceholderText('Nelson'), 'Dylan'); userEvent.type(getByPlaceholderText(' ' userEvent.click(getByRole('button')); expect(await handleClose).toHaveBeenCalled(); }); });
javascript
17
0.633786
71
25.453125
64
starcoderdata