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 |
---|---|---|---|---|---|---|---|
namespace VSP_46275z_MyProject.Dal.Models.Common.Contracts
{
public interface IValidateModel
{
bool Validate();
}
} | c# | 8 | 0.705521 | 59 | 19.5 | 8 | starcoderdata |
import pokesCounter from './itemscountMock.js';
describe('Testing items counter function', () => {
test('Count Pokemons', () => {
const items = ['pok1', 'pok2', 'pok3'];
const itesmLength = items.length;
const res = pokesCounter(items);
expect(res).toBe(itesmLength);
});
}); | javascript | 16 | 0.635135 | 50 | 28.7 | 10 | starcoderdata |
H,W=map(int, input().split())
if min(H,W)==1:
print(1)
else:
ans=(W//2+W%2)*(H//2+H%2)+(W//2)*(H//2)
print(int(ans))
| python | 11 | 0.5 | 41 | 16.714286 | 7 | codenet |
<?php
declare(strict_types=1);
namespace OpenTelemetry\Tests\Integration\SDK;
use AssertWell\PHPUnitGlobalState\EnvironmentVariables;
use OpenTelemetry\SDK\Common\Attribute\Attributes;
use OpenTelemetry\SDK\Trace\SpanLimitsBuilder;
use PHPUnit\Framework\TestCase;
/**
* @coversNothing
*/
class SpanLimitsBuilderTest extends TestCase
{
use EnvironmentVariables;
public function tearDown(): void
{
$this->restoreEnvironmentVariables();
}
/**
* @group trace-compliance
*/
public function test_span_length_limits_builder_uses_environment_variable(): void
{
$this->setEnvironmentVariable('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT', 9);
$builder = new SpanLimitsBuilder();
$spanLimits = $builder->build();
$this->assertEquals(Attributes::factory(128, 9), $spanLimits->getAttributesFactory());
}
/**
* @group trace-compliance
*/
public function test_span_length_limits_builder_uses_configured_value(): void
{
$this->setEnvironmentVariable('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT', 9);
$builder = new SpanLimitsBuilder();
$builder->setAttributeValueLengthLimit(201);
$spanLimits = $builder->build();
$this->assertEquals(Attributes::factory(128, 201), $spanLimits->getAttributesFactory());
}
/**
* @group trace-compliance
*/
public function test_span_event_limits_builder_uses_environment_variable(): void
{
$this->setEnvironmentVariable('OTEL_SPAN_EVENT_COUNT_LIMIT', 200);
$builder = new SpanLimitsBuilder();
$spanLimits = $builder->build();
$this->assertEquals(200, $spanLimits->getEventCountLimit());
}
/**
* @group trace-compliance
*/
public function test_span_event_limits_builder_uses_configured_value(): void
{
$this->setEnvironmentVariable('OTEL_SPAN_EVENT_COUNT_LIMIT', 200);
$builder = new SpanLimitsBuilder();
$builder->setEventCountLimit(185);
$spanLimits = $builder->build();
$this->assertEquals(185, $spanLimits->getEventCountLimit());
}
/**
* @group trace-compliance
*/
public function test_span_limits_link_builder_uses_environment_variable(): void
{
$this->setEnvironmentVariable('OTEL_SPAN_LINK_COUNT_LIMIT', 1101);
$builder = new SpanLimitsBuilder();
$spanLimits = $builder->build();
$this->assertEquals(1101, $spanLimits->getLinkCountLimit());
}
/**
* @group trace-compliance
*/
public function test_span_limits_link_builder_uses_configured_value(): void
{
$this->setEnvironmentVariable('OTEL_SPAN_LINK_COUNT_LIMIT', 1102);
$builder = new SpanLimitsBuilder();
$builder->setLinkCountLimit(193);
$spanLimits = $builder->build();
$this->assertEquals(193, $spanLimits->getLinkCountLimit());
}
/**
* @group trace-compliance
*/
public function test_span_attribute_per_event_count_limits_builder_uses_environment_variable(): void
{
$this->setEnvironmentVariable('OTEL_EVENT_ATTRIBUTE_COUNT_LIMIT', 400);
$builder = new SpanLimitsBuilder();
$spanLimits = $builder->build();
$this->assertEquals(Attributes::factory(400), $spanLimits->getEventAttributesFactory());
}
/**
* @group trace-compliance
*/
public function test_span_event_attribute_per_event_count_limits_builder_uses_configured_value(): void
{
$this->setEnvironmentVariable('OTEL_EVENT_ATTRIBUTE_COUNT_LIMIT', 400);
$builder = new SpanLimitsBuilder();
$builder->setAttributePerEventCountLimit(155);
$spanLimits = $builder->build();
$this->assertEquals(Attributes::factory(155), $spanLimits->getEventAttributesFactory());
}
/**
* @group trace-compliance
*/
public function test_span_attribute_per_link_count_limits_builder_uses_environment_variable(): void
{
$this->setEnvironmentVariable('OTEL_LINK_ATTRIBUTE_COUNT_LIMIT', 500);
$builder = new SpanLimitsBuilder();
$spanLimits = $builder->build();
$this->assertEquals(Attributes::factory(500), $spanLimits->getLinkAttributesFactory());
}
/**
* @group trace-compliance
*/
public function test_span_link_attribute_per_event_count_limits_builder_uses_configured_value(): void
{
$this->setEnvironmentVariable('OTEL_LINK_ATTRIBUTE_COUNT_LIMIT', 500);
$builder = new SpanLimitsBuilder();
$builder->setAttributePerLinkCountLimit(450);
$spanLimits = $builder->build();
$this->assertEquals(Attributes::factory(450), $spanLimits->getLinkAttributesFactory());
}
} | php | 12 | 0.657566 | 106 | 33.23913 | 138 | starcoderdata |
#!/usr/bin/python2.7
# Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import mail
from recaptcha.client import captcha
from model import db
import datetime
import model
import reveal
import utils
from django.utils.translation import ugettext as _
# When a record is restored after undeletion, its new expiry date is this
# length of time into the future.
RESTORED_RECORD_TTL = datetime.timedelta(60, 0, 0)
class RestoreError(Exception):
"""Container for user-facing error messages about the restore operation."""
pass
class Handler(utils.BaseHandler):
"""This handler lets the user restore a record that has expired but hasn't
been wiped yet. This can 'undelete' a deleted record, as long as it has
been less than within delete.EXPIRED_TTL_DAYS days after deletion."""
def get(self):
"""Prompts a user with a CAPTCHA to restore the specified record.
There must be a valid token supplied in the 'token' query parameter."""
try:
person, token = self.get_person_and_verify_params()
except RestoreError, e:
return self.error(400, unicode(e))
self.render('restore.html',
captcha_html=self.get_captcha_html(),
token=token,
id=self.params.id)
def post(self):
"""If the Turing test response is valid, restores the record by setting
its expiry date into the future. Otherwise, offer another test."""
try:
person, token = self.get_person_and_verify_params()
except RestoreError, err:
return self.error(400, unicode(err))
captcha_response = self.get_captcha_response()
if not captcha_response.is_valid and not self.env.test_mode:
captcha_html = self.get_captcha_html(captcha_response.error_code)
self.render('restore.html',
captcha_html=captcha_html,
token=token,
id=self.params.id)
return
# Log the user action.
model.UserActionLog.put_new('restore', person)
# Move the expiry date into the future to cause the record to reappear.
person.expiry_date = utils.get_utcnow() + RESTORED_RECORD_TTL
person.put_expiry_flags()
record_url = self.get_url('/view', person.repo, id=person.record_id)
subject = _('[Person Finder] Record restoration notice for '
'"%(full_name)s"') % {'full_name': person.primary_full_name}
email_addresses = person.get_associated_emails()
for address in email_addresses:
self.send_mail(
subject=subject,
to=address,
body=self.render_to_string(
'restoration_email.txt',
full_name=person.primary_full_name,
record_url=record_url
)
)
self.redirect(record_url)
def get_person_and_verify_params(self):
"""Checks the request for a valid person id and valid crypto token.
Returns a tuple containing: (person, token)
If there is an error we raise a RestoreError, instead of pretending
we're using C."""
person = model.Person.get_by_key_name(self.params.id)
if not person:
raise RestoreError(
'The record with the following ID no longer exists: %s' %
self.params.id.split(':', 1)[1])
token = self.request.get('token')
data = 'restore:%s' % self.params.id
if not reveal.verify(data, token):
raise RestoreError('The token was invalid')
return (person, token) | python | 16 | 0.627107 | 79 | 37.142857 | 112 | starcoderdata |
@Override
public void onClick(View v) {
email = mEmailadress.getText().toString().trim();
wachtwoord = mWachtwoord.getText().toString().trim();
wachtwoord_confire = mWachtwoord_confire.getText().toString().trim();
username = mUsernaem.getText().toString().trim();
if(TextUtils.isEmpty(email)){
mEmailadress.setError("Uw emailadress mag niet leeg zijn.");
return;
}
if(TextUtils.isEmpty(wachtwoord)){
mWachtwoord.setError("Uw wachtwoord mag niet leeg zijn.");
return;
}
if(!wachtwoord_confire.equals(wachtwoord)){
mWachtwoord_confire.setError("Wachtwoord is niet gelijk.");
}
if(wachtwoord.length()< 6){
mWachtwoord.setError("Uw wachtwoord moet langer dan 6 karakters zijn");
return;
}
progressBar.setVisibility(View.VISIBLE);
//Registreren de gebruiker
Registratie();
} | java | 9 | 0.5 | 91 | 44.192308 | 26 | inline |
package com.thoughtworks.go.plugin.infra;
import com.thoughtworks.go.plugin.infra.commons.GoFileSystem;
import com.thoughtworks.go.plugin.infra.commons.PluginUploadResponse;
import com.thoughtworks.go.util.SystemEnvironment;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import java.io.File;
import java.io.IOException;
import static com.thoughtworks.go.util.SystemEnvironment.PLUGIN_EXTERNAL_PROVIDED_PATH;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
public class PluginWriterTest {
@Mock
private SystemEnvironment systemEnvironment;
@Mock
private GoFileSystem goFileSystem;
@InjectMocks
private PluginWriter pluginWriter = new PluginWriter(systemEnvironment, goFileSystem);
private String EXTERNAL_DIRECTORY_PATH = "external_path";
private File SRC_FILE = new File("a_plugin.jar");
@Before
public void init() throws IOException {
initMocks(this);
SRC_FILE.createNewFile();
}
@After
public void clean() {
FileUtils.deleteQuietly(SRC_FILE);
}
@Test
public void shouldConstructCorrectDestinationFilePath() throws Exception {
when(systemEnvironment.get(PLUGIN_EXTERNAL_PROVIDED_PATH)).thenReturn(EXTERNAL_DIRECTORY_PATH);
pluginWriter.addPlugin(SRC_FILE, SRC_FILE.getName());
ArgumentCaptor srcfileArgumentCaptor = ArgumentCaptor.forClass(File.class);
ArgumentCaptor destfileArgumentCaptor = ArgumentCaptor.forClass(File.class);
verify(goFileSystem).copyFile(srcfileArgumentCaptor.capture(), destfileArgumentCaptor.capture());
assertThat(srcfileArgumentCaptor.getValue(), is(SRC_FILE));
assertThat(destfileArgumentCaptor.getValue().getName(), is(new File(EXTERNAL_DIRECTORY_PATH + "/" + SRC_FILE.getName()).getName()));
}
@Test
public void shouldReturnSuccessResponseWhenSuccessfullyUploadedFile() throws Exception {
when(systemEnvironment.get(PLUGIN_EXTERNAL_PROVIDED_PATH)).thenReturn(EXTERNAL_DIRECTORY_PATH);
PluginUploadResponse response = pluginWriter.addPlugin(SRC_FILE, SRC_FILE.getName());
assertTrue(response.isSuccess());
assertThat(response.success(), is("Your file is saved!"));
}
@Test
public void shouldReturnErrorResponseWhenFailedToUploadFile() throws Exception {
when(systemEnvironment.get(PLUGIN_EXTERNAL_PROVIDED_PATH)).thenReturn(EXTERNAL_DIRECTORY_PATH);
doThrow(new IOException()).when(goFileSystem).copyFile(any(File.class), any(File.class));
PluginUploadResponse response = pluginWriter.addPlugin(SRC_FILE, SRC_FILE.getName());
assertFalse(response.isSuccess());
assertTrue(response.errors().containsKey(HttpStatus.SC_INTERNAL_SERVER_ERROR));
}
} | java | 16 | 0.753731 | 140 | 35.545455 | 88 | starcoderdata |
const axios = require('axios')
const parseString = require('xml2js').parseString
const state = {
PostObj: {},
Comments: []
}
const mutations = {
setPost (state, postObj) {
state.PostObj = postObj
},
setComments (state, Comments) {
state.Comments = Comments
}
}
const getters = {
getPostObj (state) {
return state.PostObj
},
getComments (state) {
return state.Comments
}
}
const actions = {
setPost ({ dispatch, commit }, postObj) {
commit('setPost', postObj)
dispatch('loadComments', postObj.url)
},
async loadComments ({ commit }, url) {
// commit('INCREMENT_MAIN_COUNTER')
const type = 'json'
const response = await axios(url + '.json', type)
if (type === 'xml') {
// UNTESTED
parseString(response.data, (err, result) => {
if (!err) {
console.log(result.feed.entry)
commit('setComments', result.feed.entry)
}
})
} else if (type === 'json') {
commit('setComments', response.data[1].data.children)
}
}
}
export default {
state,
mutations,
getters,
actions
} | javascript | 14 | 0.607877 | 59 | 19.491228 | 57 | starcoderdata |
ownerclass = 'ResultWindowBase'
ownerimport = 'ResultWindowBase.h'
result = Window(557, 400, "dupeGuru Results")
toolbar = result.createToolbar('ResultsToolbar')
table = TableView(result)
table.OBJC_CLASS = 'HSTableView'
statsLabel = Label(result, "")
contextMenu = Menu("")
#Setup toolbar items
toolbar.displayMode = const.NSToolbarDisplayModeIconOnly
directoriesToolItem = toolbar.addItem('Directories', "Directories", image='folder32')
actionToolItem = toolbar.addItem('Action', "Action")
filterToolItem = toolbar.addItem('Filter', "Filter")
optionsToolItem = toolbar.addItem('Options', "Options")
quicklookToolItem = toolbar.addItem('QuickLook', "Quick Look")
toolbar.defaultItems = [actionToolItem, optionsToolItem, quicklookToolItem, directoriesToolItem,
toolbar.flexibleSpace(), filterToolItem]
actionPopup = Popup(None)
actionPopup.pullsdown = True
actionPopup.bezelStyle = const.NSTexturedRoundedBezelStyle
actionPopup.arrowPosition = const.NSPopUpArrowAtBottom
item = actionPopup.menu.addItem("") # First item is invisible
item.hidden = True
item.image = 'NSActionTemplate'
actionPopup.width = 44
actionToolItem.view = actionPopup
filterField = SearchField(None, "Filter")
filterField.action = Action(owner, 'filter')
filterField.sendsWholeSearchString = True
filterToolItem.view = filterField
filterToolItem.minSize = Size(80, 22)
filterToolItem.maxSize = Size(300, 22)
quickLookButton = Button(None, "")
quickLookButton.bezelStyle = const.NSTexturedRoundedBezelStyle
quickLookButton.image = 'NSQuickLookTemplate'
quickLookButton.width = 44
quickLookButton.action = Action(owner, 'toggleQuicklookPanel')
quicklookToolItem.view = quickLookButton
optionsSegments = SegmentedControl(None)
optionsSegments.segmentStyle = const.NSSegmentStyleCapsule
optionsSegments.trackingMode = const.NSSegmentSwitchTrackingSelectAny
optionsSegments.font = Font(FontFamily.System, 11)
optionsSegments.addSegment("Details", 57)
optionsSegments.addSegment("Dupes Only", 82)
optionsSegments.addSegment("Delta", 48)
optionsSegments.action = Action(owner, 'changeOptions')
optionsToolItem.view = optionsSegments
# Popuplate menus
actionPopup.menu.addItem("Send Marked to Trash...", action=Action(owner, 'trashMarked'))
actionPopup.menu.addItem("Move Marked to...", action=Action(owner, 'moveMarked'))
actionPopup.menu.addItem("Copy Marked to...", action=Action(owner, 'copyMarked'))
actionPopup.menu.addItem("Remove Marked from Results", action=Action(owner, 'removeMarked'))
actionPopup.menu.addSeparator()
for menu in (actionPopup.menu, contextMenu):
menu.addItem("Remove Selected from Results", action=Action(owner, 'removeSelected'))
menu.addItem("Add Selected to Ignore List", action=Action(owner, 'ignoreSelected'))
menu.addItem("Make Selected into Reference", action=Action(owner, 'switchSelected'))
menu.addSeparator()
menu.addItem("Open Selected with Default Application", action=Action(owner, 'openSelected'))
menu.addItem("Reveal Selected in Finder", action=Action(owner, 'revealSelected'))
menu.addItem("Rename Selected", action=Action(owner, 'renameSelected'))
# Doing connections
owner.filterField = filterField
owner.matches = table
owner.optionsSwitch = optionsSegments
owner.optionsToolbarItem = optionsToolItem
owner.stats = statsLabel
table.bind('rowHeight', defaults, 'values.TableFontSize', valueTransformer='vtRowHeightOffset')
# Rest of the setup
result.minSize = Size(340, 340)
result.autosaveName = 'MainWindow'
statsLabel.alignment = TextAlignment.Center
table.alternatingRows = True
table.menu = contextMenu
table.allowsColumnReordering = True
table.allowsColumnResizing = True
table.allowsColumnSelection = False
table.allowsEmptySelection = False
table.allowsMultipleSelection = True
table.allowsTypeSelect = True
table.gridStyleMask = const.NSTableViewSolidHorizontalGridLineMask
table.setAnchor(Pack.UpperLeft, growX=True, growY=True)
statsLabel.setAnchor(Pack.LowerLeft, growX=True)
# Layout
# It's a little weird to pack with a margin of -1, but if I don't do that, I get too thick of a
# border on the upper side of the table.
table.packToCorner(Pack.UpperLeft, margin=-1)
table.fill(Pack.Right, margin=0)
statsLabel.packRelativeTo(table, Pack.Below, margin=6)
statsLabel.fill(Pack.Right, margin=0)
table.fill(Pack.Below, margin=5) | python | 10 | 0.797685 | 96 | 43.081633 | 98 | starcoderdata |
void Set2D(
GlTextureInterface* txi,
Texture* tex,
GLuint numC,
GLuint fmt,
GLuint typ,
GLuint tgt,
int BPP,
int inummips,
int& iw,
int& ih,
DataBlockInputStream inpstream) {
DataBlockInputStream copy_stream = inpstream;
// size_t ifilelen = 0;
// EFileErrCode eFileErr = file.GetLength(ifilelen);
int isize = iw * ih * BPP;
auto glto = (GLTextureObject*)tex->_internalHandle;
glto->_maxmip = 0;
int mipbias = 0;
#if defined(__APPLE__) // todo move to gfx user settings
if (iw >= 4096) {
// mipbias = 2;
}
#endif
for (int imip = 0; imip < inummips; imip++) {
if (iw < 4)
continue;
if (ih < 4)
continue;
GLuint nfmt = fmt;
/////////////////////////////////////////////////
// allocate space for image
// see http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Board=3&Number=159972
// and http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=240547
// basically you can call glTexImage2D once with the s3tc format as the internalformat
// and a null data ptr to let the driver 'allocate' space for the texture
// then use the glCompressedTexSubImage2D to overwrite the data in the pre allocated space
// this decouples allocation from writing, allowing you to overwrite more efficiently
/////////////////////////////////////////////////
GLint intfmt = 0;
// printf( "fmt<%04x>\n", fmt );
int isiz2 = isize;
// printf( "numC<%d> typ<%04x>\n", numC, typ );
switch (nfmt) {
case GL_BGR:
intfmt = GL_RGB;
nfmt = GL_BGR;
break;
case GL_BGRA:
if ((numC == 4) && (typ == GL_UNSIGNED_BYTE))
intfmt = GL_RGBA;
break;
case GL_RGBA:
if (numC == 4)
switch (typ) {
case GL_UNSIGNED_SHORT_5_5_5_1:
case GL_UNSIGNED_BYTE:
intfmt = GL_RGBA;
break;
default:
assert(false);
}
break;
case GL_RGB:
if ((numC == 3) && (typ == GL_UNSIGNED_BYTE))
intfmt = GL_RGB;
break;
default:
break;
}
OrkAssert(intfmt != 0);
// printf( "tgt<%04x> imip<%d> intfmt<%04x> w<%d> h<%d> isiz2<%d> fmt<%04x> typ<%04x>\n", tgt, imip, intfmt,
// iw,ih,isiz2,nfmt,typ);
GL_ERRORCHECK();
bool bUSEPBO = false;
if (bUSEPBO) {
glTexImage2D(tgt, imip, intfmt, iw, ih, 0, nfmt, typ, 0);
GL_ERRORCHECK();
/////////////////////////////
// imgdata->PBO
/////////////////////////////
auto pbo = txi->_getPBO(isiz2);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo->_handle);
GL_ERRORCHECK();
u32 map_flags = GL_MAP_WRITE_BIT;
map_flags |= GL_MAP_INVALIDATE_BUFFER_BIT;
map_flags |= GL_MAP_UNSYNCHRONIZED_BIT;
void* pgfxmem = glMapBufferRange(GL_PIXEL_UNPACK_BUFFER, 0, isiz2, map_flags);
// printf( "UPDATE IMAGE UNC imip<%d> iw<%d> ih<%d> isiz<%d> pbo<%d> mem<%p>\n", imip, iw, ih, isiz2, PBOOBJ, pgfxmem );
auto copy_src = inpstream.current();
memcpy(pgfxmem, copy_src, isiz2);
inpstream.advance(isiz2);
glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
GL_ERRORCHECK();
////////////////////////
// PBO->texture
////////////////////////
glTexSubImage2D(tgt, imip, 0, 0, iw, ih, nfmt, typ, 0);
GL_ERRORCHECK();
////////////////////////
// unbind the PBO
////////////////////////
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
txi->_returnPBO(pbo);
GL_ERRORCHECK();
} else // not PBO
{
auto pgfxmem = inpstream.current();
inpstream.advance(isiz2);
if (imip >= mipbias) {
glTexImage2D(tgt, imip - mipbias, intfmt, iw, ih, 0, nfmt, typ, pgfxmem);
glto->_maxmip = imip - mipbias;
}
GL_ERRORCHECK();
}
////////////////////////
// irdptr+=isize;
// pimgdata = & dataBASE[irdptr];
iw >>= 1;
ih >>= 1;
isize = iw * ih * BPP;
}
} | c++ | 15 | 0.523051 | 126 | 26.560811 | 148 | inline |
void MapView::request_finished(QNetworkReply* reply)
{
/*
printf("mapview::request_finished()\n");
printf(" request url: %s\n",
reply->request().url().path().toStdString().c_str());
*/
const string url(reply->request().url().path().toStdString());
if (url.size() < 10)
return;
const size_t zoom_start = 6;
const size_t zoom_end = url.find('/', zoom_start);
if (zoom_end == string::npos)
return;
const string zoom_str = url.substr(zoom_start, zoom_end - zoom_start);
const size_t x_start = zoom_end + 1;
if (x_start >= url.size())
return;
const size_t x_end = url.find('/', x_start);
const string x_str = url.substr(x_start, x_end - x_start);
const size_t y_start = x_end + 1;
if (y_start >= url.size())
return;
const size_t y_end = url.find('.', y_start);
const string y_str = url.substr(y_start, y_end - y_start);
const int zoom = std::stoi(zoom_str);
const int x = std::stoi(x_str);
const int y = std::stoi(y_str);
QByteArray bytes = reply->readAll();
printf("received %d-byte tile: zoom=%d x=%d y=%d\n",
bytes.length(),
zoom,
x,
y);
QImage image;
bool parse_ok = image.loadFromData(bytes);
if (parse_ok)
{
QPixmap pixmap(QPixmap::fromImage(image.convertToFormat(
QImage::Format_Grayscale8)));
tile_cache.set(zoom, x, y, bytes);
// find the placeholder pixmapitem and update its pixmap
for (auto& item : tile_pixmap_items)
{
if (item.x == x && item.y == y && item.zoom == zoom)
{
item.item->setPixmap(pixmap);
item.item->setGraphicsEffect(nullptr);
item.state = MapTilePixmapItem::State::COMPLETED;
break;
}
}
}
else
{
printf(" unable to parse\n");
}
// Now that this request is completed, we can issue the next request
// in the queue.
process_request_queue();
} | c++ | 14 | 0.607085 | 72 | 26.820896 | 67 | inline |
"""
SQLAlchemy-JSONAPI Example
-
An example of basic usage of SQLAlchemy-JSONAPI
"""
from pprint import pprint
from sqlalchemy import create_engine, Column, Integer, Unicode, UnicodeText
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy_jsonapi import JSONAPIMixin, JSONAPI, as_relationship
# Start your engines...and session.
engine = create_engine('sqlite:///:memory:')
Base = declarative_base()
session = sessionmaker(bind=engine)()
# Extend the JSONAPIMixin so we can convert numerial IDs into strings.
# This is not done automatically so as to be more back-end agnostic
class APIMixin(JSONAPIMixin):
jsonapi_columns_override = {
'id': lambda self: str(self.id)
}
# Model definitions
class User(APIMixin, Base):
__tablename__ = 'users'
# We don't want the password to be sent in the response, so we exclude it.
jsonapi_columns_exclude = ['password']
id = Column(Integer, primary_key=True)
username = Column(Unicode(30))
password = Column(Unicode(30))
class Post(APIMixin, Base):
__tablename__ = 'posts'
jsonapi_relationships_include = ['my_relationship']
id = Column(Integer, primary_key=True)
title = Column(Unicode(100))
content = Column(UnicodeText)
user_id = Column(Integer, ForeignKey('users.id'))
user = relationship('User', lazy='select',
backref=backref('posts', lazy='dynamic'))
@as_relationship()
def my_relationship(self):
return session.query(User).first()
class Comment(APIMixin, Base):
__tablename__ = 'comments'
id = Column(Integer, primary_key=True)
content = Column(UnicodeText)
user_id = Column(Integer, ForeignKey('users.id'))
post_id = Column(Integer, ForeignKey('posts.id'))
user = relationship('User', lazy='joined',
backref=backref('comments', lazy='dynamic'))
post = relationship('Post', lazy='joined',
backref=backref('comments', lazy='dynamic'))
# Initialize the database and fill it with some sample data
Base.metadata.create_all(engine)
user = User(username='sampleuser', password='
post = Post(title='Sample Post',
content='Lorem ipsum dolor sit amet fakus latinus',
user=user)
comment = Comment(content='Sample comment',
user=user, post=post)
session.add(user)
session.commit()
# Create the serializer and serialize a collection.
# Note: It MUST be a list or a collection. Individual objects require
# as_collection to be False in the call to serialize().
post_serializer = JSONAPI(Post)
query = session.query(Post)
json_api_dict = post_serializer.serialize(query)
# Finally, let's see what the output is.
pprint(json_api_dict)
"""
Output from the pprint statement:
{'linked': {'comments': [{'content': 'Sample comment',
'id': '1',
'links': {'post': '1', 'user': '1'}}],
'my_relationship': [{'id': '1',
'links': {},
'username': 'sampleuser'}],
'users': [{'id': '1', 'links': {}, 'username': 'sampleuser'}]},
'meta': {},
'posts': [{'content': 'Lorem ipsum dolor sit amet fakus latinus',
'id': '1',
'links': {'comments': ['1'], 'user': '1'},
'title': 'Sample Post'}]}
""" | python | 12 | 0.637706 | 78 | 31.915888 | 107 | starcoderdata |
// Copyright (c) 2018 Aurigma Inc. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using tar_cs;
namespace Aurigma.GraphicsMill.AjaxControls.VectorObjects.Svg
{
public class TarArchive : BaseArchive
{
private readonly TarWriter _tarWriter;
private long _initialPosition;
private int _currentFileIndex = 0;
private readonly Dictionary<string, int> _tarContent = new Dictionary<string, int>();
private readonly Stream _tarStream;
private TarArchiveReadStream _tarReadStream = null;
private TarArchiveWriteStream _tarWriteStream = null;
private Mode _storageMode;
public enum Mode
{
Create,
Read
}
public TarArchive(Stream tarStream, Mode mode)
{
_tarStream = tarStream;
_storageMode = mode;
switch (mode)
{
case Mode.Create:
_tarWriter = new TarWriter(_tarStream);
break;
case Mode.Read:
InitTarReading();
break;
default:
throw new TarFileStorageException("Unexpected mode");
}
}
private void InitTarReading()
{
_initialPosition = _tarStream.Position;
var initialTarReader = new TarReader(_tarStream);
for (var number = 0; initialTarReader.MoveNext(skipData: true); number++)
{
var fileInfo = initialTarReader.FileInfo;
if (fileInfo.EntryType != EntryType.File)
{
Configuration.Logger.Warning(string.Format("Unexpected entry type {0} in tar", fileInfo.EntryType));
continue;
}
_tarContent[fileInfo.FileName] = number;
}
RewindStream();
}
private void RewindStream()
{
_tarStream.Position = _initialPosition;
}
private void RememberFile(string fileId)
{
_tarContent[fileId] = _currentFileIndex;
_currentFileIndex++;
}
public override void AddFileWithId(string fileId, Stream fileData, bool isSource = false)
{
if (_storageMode != Mode.Create)
throw new TarFileStorageException("Mode!");
if (FileExists(fileId))
return;
_tarWriter.Write(fileData, fileData.Length - fileData.Position, fileId);
RememberFile(fileId);
}
public override Stream GetReadStream(string fileId, bool isSource = false)
{
if (_storageMode != Mode.Read)
throw new TarFileStorageException("Mode!");
if (_tarReadStream != null && !_tarReadStream.IsClosed)
throw new TarFileStorageException("Previews read stream have to be closed before creation new one");
var initialStreamPosition = _tarStream.Position;
var tarReader = new TarReader(_tarStream);
if (!FileExists(fileId))
throw new TarFileStorageException(string.Format("File {0} not found in tar file", fileId));
var i = 0;
do
{
tarReader.MoveNext(skipData: true);
i++;
} while ((i - 1) != _tarContent[fileId]);
return (_tarReadStream = new TarArchiveReadStream(tarReader, () => _tarStream.Position = initialStreamPosition));
}
private Stream GetWriteStream(string fileId)
{
if (_tarWriteStream != null && !_tarWriteStream.IsClosed)
throw new TarFileStorageException("Previews write stream have to be closed before creation new one");
_tarWriteStream = new TarArchiveWriteStream(fileId, _tarWriter);
RememberFile(fileId);
return _tarWriteStream;
}
public override bool FileExists(string fileId)
{
return _tarContent.ContainsKey(fileId);
}
public override void WriteToStream(string fileId, Action action)
{
using (var stream = GetWriteStream(fileId))
{
action(stream);
}
}
public override void Dispose()
{
if (_tarWriter != null)
_tarWriter.Dispose();
}
public class TarFileStorageException : Exception
{
public TarFileStorageException()
{
}
public TarFileStorageException(string message) : base(message)
{
}
public TarFileStorageException(string message, Exception innerException) : base(message, innerException)
{
}
protected TarFileStorageException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}
} | c# | 19 | 0.561282 | 125 | 28.953757 | 173 | starcoderdata |
@Override
protected Directory getDirectory(Directory in) {
assert in instanceof MockDirectoryWrapper;
if (!useNonNrtReaders) ((MockDirectoryWrapper) in).setAssertNoDeleteOpenFile(true);
Directory[] directories = new Directory[1 + random().nextInt(5)];
directories[0] = in;
for (int i = 1; i < directories.length; i++) {
final File tempDir = createTempDir(getTestName());
directories[i] = newMockFSDirectory(tempDir); // some subclasses rely on this being MDW
if (!useNonNrtReaders) ((MockDirectoryWrapper) directories[i]).setAssertNoDeleteOpenFile(true);
}
for (Directory dir : directories) {
((MockDirectoryWrapper) dir).setCheckIndexOnClose(false);
}
try {
if (random().nextBoolean()) {
return new MockDirectoryWrapper(random(), new DistributorDirectory(directories));
} else {
return new DistributorDirectory(directories);
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
} | java | 12 | 0.61325 | 107 | 40.407407 | 27 | inline |
package com.dtstack.taier.develop.vo.datasource;
import io.swagger.annotations.ApiModelProperty;
import java.util.List;
public class DsPreviewResultVO {
@ApiModelProperty(value = "字段列表")
private List columnList;
@ApiModelProperty(value = "数据信息")
private Object dataList;
public List getColumnList() {
return columnList;
}
public void setColumnList(List columnList) {
this.columnList = columnList;
}
public Object getDataList() {
return dataList;
}
public void setDataList(Object dataList) {
this.dataList = dataList;
}
} | java | 9 | 0.67874 | 56 | 19.483871 | 31 | starcoderdata |
def insert(self, k):
"""
Calls the respective helper functions for insertion into B-Tree
:param k: The key to be inserted.
"""
root = self.root
# If a node is full, split the child
if len(root.keys) == (2 * self.t) - 1:
temp = Node()
self.root = temp
# Former root becomes 0'th child of new root 'temp'
temp.children.insert(0, root)
self._splitChild(temp, 0)
self._insertNonFull(temp, k)
else:
self._insertNonFull(root, k) | python | 9 | 0.522807 | 71 | 34.6875 | 16 | inline |
std::pair<int, std::shared_ptr<RuntimePreparedModel>> DriverDevice::prepareModel(
const ModelFactory& makeModel, ExecutionPreference preference, Priority priority,
const OptionalTimePoint& deadline, const std::string& cacheDir,
const std::optional<CacheToken>& maybeToken) const {
// Attempt to compile from cache if token is present.
if (maybeToken.has_value()) {
auto result = prepareModelFromCacheInternal(deadline, cacheDir, *maybeToken);
if (result.has_value()) {
return {ANEURALNETWORKS_NO_ERROR,
std::make_shared<DriverPreparedModel>(this, std::move(result).value())};
} else {
LOG(ERROR) << "prepareModelFromCache failure (" << result.error().code
<< "): " << result.error().message;
}
}
// Get cache files if they exist, otherwise create them.
CacheHandles cache;
if (maybeToken.has_value()) {
auto result =
getCacheHandles(cacheDir, *maybeToken, kInterface->getNumberOfCacheFilesNeeded(),
/*createIfNotExist=*/true);
if (result.has_value()) {
cache = std::move(result).value();
} else {
LOG(ERROR) << "getCacheHandles failure (" << result.error().code
<< "): " << result.error().message;
}
}
// Get the token if it exists, otherwise get a null token.
static constexpr CacheToken kNullToken = {};
const CacheToken token = maybeToken.value_or(kNullToken);
// Fallback to full compilation (possibly with token) if
// prepareModelFromCache could not be used or failed.
const Model model = makeModel();
auto result = kInterface->prepareModel(model, preference, priority, deadline, cache.modelCache,
cache.dataCache, token);
if (!result.ok()) {
LOG(ERROR) << "IDevice::prepareModel() error: " << result.error().message;
return {ANEURALNETWORKS_OP_FAILED, nullptr}; // TODO: confirm
}
SharedPreparedModel preparedModel = std::move(result).value();
CHECK(preparedModel != nullptr)
<< "IDevice::prepareModel() returned nullptr without error code";
return {ANEURALNETWORKS_NO_ERROR,
std::make_shared<DriverPreparedModel>(this, std::move(preparedModel))};
} | c++ | 15 | 0.617138 | 99 | 47.367347 | 49 | inline |
bag udp_bag_init()
{
// this should be some kind of parameterized listener.
// we can do the same trick that we tried to do
// with time, by creating an open read, but it
// has strange consequences. sidestep by just
// having an 'eve port'
heap h = allocate_rolling(pages, sstring("udp bag"));
udp_bag ub = allocate(h, sizeof(struct udp_bag));
ub->h = h;
ub->b.prepare = cont(h, udp_prepare, ub);
ub->b.scan = cont(h, udp_scan, ub);
ub->b.listeners = allocate_table(h, key_from_pointer, compare_pointer);
ub->channels = create_value_table(h);
// doctopus
// ub->ev = ev;
return (bag)ub;
} | c | 10 | 0.620214 | 75 | 35.333333 | 18 | inline |
#!/usr/bin/env python3
import re
import os
import sys
import argparse
import numpy as np
from astropy.io import ascii, fits
from astropy.table import Table, Column
import pyds9
import mskpy
parser = argparse.ArgumentParser(
description='Define background sections for target data.')
parser.add_argument('file', nargs='+', help='FITS files to examine.')
parser.add_argument('--overwrite', action='store_true',
help='Re-define the background section.')
parser.add_argument(
'-o', default='bg-sections.txt', help='Save sections to this file.')
args = parser.parse_args()
number = '([0-9]+(\.[0-9]*(e[+-][0-9]+)*)*)'
boxpat = 'box\({}\)'.format(','.join([number] * 5))
annpat = 'annulus\({}\)'.format(','.join([number] * 4))
ds9 = pyds9.DS9('bgsections', wait=60)
ds9.set('cmap viridis')
ds9.set('scale zscale')
ds9.set('mode pointer')
sections = Table(names=('file', 'sections'), dtype=('U128', 'U256'))
if os.path.exists(args.o):
tab = ascii.read(args.o)
os.system('cp {0} {0}~'.format(args.o))
print('Read in previous table and created backup file.')
sections = Table(names=('file', 'sections'), dtype=('U128', 'U256'),
data=(tab['file'].data, tab['sections'].data))
else:
sections = Table(names=('file', 'sections'), dtype=('U128', 'U256'))
c = None
last_object = None
for f in sorted(args.file):
if (f in sections['file']) and (not args.overwrite):
continue
h = fits.getheader(f)
if h['OBSTYPE'] != 'OBJECT':
continue
print(f, h['OBJECT'], h['FILTERS'])
if f in sections['file']:
section = sections['sections'][sections['file'] == f][0]
ds9.set('fits {}'.format(f))
ds9.set('zoom to 0.25')
ds9.set('regions color red')
ds9.set('regions system physical')
if 's:' in section:
j = section.find('[')
for s in section[j:].split('+'):
corners = [int(x) for x in re.split('[,:]', s[1:-1])]
xc = np.array(corners[:2]).mean().astype(int) + 1
xw = np.array(corners[:2]).ptp()
yc = np.array(corners[2:]).mean().astype(int) + 1
yw = np.array(corners[2:]).ptp()
ds9.set(
'regions', 'box({}, {}, {}, {}, 0)'.format(xc, yc, xw, yw))
else:
xc, yc = h['CX'] + 1, h['CY'] + 1
rinner, router = [int(x) for x in section[3:].split(',')]
ds9.set(
'regions', 'annulus({}, {}, {}, {})'.format(rinner, router))
else:
if h['OBJECT'] == last_object:
ds9.set('regions system wcs')
regions = ds9.get('regions')
ds9.set('fits {}'.format(f))
ds9.set('zoom to 0.25')
if h['OBJECT'] == last_object:
ds9.set('regions system wcs')
ds9.set('regions color green')
regions = ds9.set('regions', regions)
ds9.set('regions system physical')
print("- Mark background with annulus or boxes and press enter or")
print(" - [s]kip\n - [w]rite and quit\n - [q]uit")
sys.stdin.flush()
c = None
while c not in ['', 's', 'w', 'q']:
c = sys.stdin.readline().strip()
section = None
if c == 's':
continue
elif c in ['w', 'q']:
break
ds9.set('regions system physical')
regions = ds9.get('regions')
if 'box' in regions:
boxes = []
for box in re.findall(boxpat, regions):
x, y, xw, yw, angle = [float(v) for v in box[::3]]
corners = [y - yw / 2, y + yw / 2, x - xw / 2, x + xw / 2]
boxes.append('[{:.0f}:{:.0f}, {:.0f}:{:.0f}]'.format(
*corners))
section = 's: {}'.format('+'.join(boxes))
elif 'annulus' in regions:
for annulus in re.findall(annpat, regions)[:1]:
x, y, r0, r1 = [float(v) for v in annulus[::3]]
section = 'r: {:.0f}, {:.0f}'.format(r0, r1)
if section is not None:
assert len(section) > 3, regions
i = np.flatnonzero(sections['file'] == f)
if len(i) == 0:
sections.add_row((f, section))
else:
sections[i]['sections'] = section
print(section)
last_object = h['OBJECT']
if (c != 'q') and (c is not None):
sections.write('bg-sections.txt', format='ascii', delimiter=',',
overwrite=True) | python | 20 | 0.531044 | 79 | 33.085271 | 129 | starcoderdata |
def unique_numbers(texts, calls):
numbers = {} # Hash table / dictionary
# Traverse texts records
for i in range(len(texts)):
sending = texts[i][0]
receiving = texts[i][1]
numbers[sending] = numbers.get(sending, 0) + 1
numbers[receiving] = numbers.get(receiving, 0) + 1
# Traverse calls records
for i in range(len(calls)):
calling = calls[i][0]
receiving = calls[i][1]
numbers[calling] = numbers.get(calling, 0) + 1
numbers[receiving] = numbers.get(receiving, 0) + 1
return numbers | python | 10 | 0.602812 | 58 | 37 | 15 | inline |
/* AJAX stuff for AJAX enabled ea campaign */
/* create and return XMLHttpRequest or ActiveXObject, depending on browser
*/
function createXMLRequest() {
var xmlobj = null;
try {
// instantiate request object for Mozilla, Nestcape, etc.
xmlobj = new XMLHttpRequest();
} catch(e) {
try {
// instantiate object for Internet Explorer
xmlobj=new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) {
return null;
}
}
return xmlobj;
}
/* Submits ajax request based on the received form
* and puts the results of the request in the received target div
*/
function doAJAXForm(form, target, disableForm) {
var serverProcess = form.action;
var formElements=form.elements;
var firstParameter=true;
var theValue=null;
for (var i=0;i<formElements.length;i++) {
var theValue=null;
var theElement=formElements[i];
//alert(theElement.name + " " + theElement.type);
if (theElement.type == 'button'
|| theElement.type == 'reset'
|| theElement.type == 'submit'
|| theElement.disabled == true) {
//skip
} else if (theElement.tagName == 'SELECT') {
var options = theElement.options;
for (var k=0;k<options.length;k++) {
if (options[k].selected) {
if(firstParameter == true) {
serverProcess=serverProcess + "?";
firstParameter=false;
} else {
serverProcess=serverProcess + "&";
}
//alert(theElement.name + ' = ' + options[k].value);
serverProcess += theElement.name + "=" + options[k].value;
}
}
theValue=null;
} else if (theElement.type == 'checkbox') {
if (theElement.checked) {
if(firstParameter == true) {
serverProcess=serverProcess + "?";
firstParameter=false;
} else {
serverProcess=serverProcess + "&";
}
//alert(theElement.name + ' = ' + theElement.value);
serverProcess += theElement.name + "=" + theElement.value;
}
} else if (theElement.type == 'radio') {
if (theElement.checked) {
if(firstParameter == true) {
serverProcess=serverProcess + "?";
firstParameter=false;
} else {
serverProcess=serverProcess + "&";
}
//alert(theElement.name + ' = ' + theElement.value);
serverProcess += theElement.name + "=" + theElement.value;
}
} else {
theValue = theElement.value;
}
//alert('the value ' + theValue);
if (theValue != null) {
if(firstParameter == true) {
serverProcess=serverProcess + "?";
firstParameter=false;
} else {
serverProcess=serverProcess + "&";
}
serverProcess=serverProcess + theElement.name + "=" + theValue;
}
}
//alert(serverProcess);
var result = doAJAX(serverProcess);
//alert('disableForm ' + disableForm);
if (disableForm == true && result.indexOf(" < 0) {
handleExistingFormElements(form);
var spans = document.getElementsByTagName("span");
for (var l=0;l<spans.length;l++) {
hideSubmitResetButtons(spans[l]);
}
}
if (result.indexOf(" >= 0) {
result = getErrorMessage(result);
putResultInTarget(result, "eaAjaxErrorMessageContainer", true);
} else {
clearContainerNamedAndChildren("eaAjaxErrorMessageContainer");
putResultInTarget(result, target, true);
}
}
function doAJAXLink(url,target) {
var result = doAJAX(url);
if (result.indexOf(" >= 0) {
result = getErrorMessage(result);
putResultInTarget(result, "eaAjaxErrorMessageContainer", true);
} else {
clearContainerNamedAndChildren("eaAjaxErrorMessageContainer");
putResultInTarget(result, target, true);
}
}
function getErrorMessage(result) {
var idx = result.indexOf("
return result.substring(idx + 18);
}
function doAJAX(url) {
//alert('url\n ' + url);
//append eaAJAXsubmit parameter
url = url + "&ea.AJAX.submit=true";
var result = "";
var xmlobj = createXMLRequest();
// open socket connection
xmlobj.open('POST',url,false);
// send request
xmlobj.send(null);
// if request is completed, grab the content
if(xmlobj.readyState==4){
if(xmlobj.status==200){
result=xmlobj.responseText;
}
}
//alert('result \n' + result);
return result;
}
function putResultInTarget(result, target, clearTarget) {
var divs = document.getElementsByTagName("div");
var theDiv;
for (var i=0;i<divs.length;i++) {
theDiv = divs[i];
if (theDiv.className && theDiv.className.match(target)) {
if (clearTarget) {
//clearContainer(theDiv);
}
theDiv.style.display="";
var newdiv = document.createElement("div");
newdiv.innerHTML = result;
theDiv.appendChild(newdiv);
return;
}
}
}
function putResultInTargetWithId(result, targetId, clearTarget) {
var theDiv = document.getElementById(targetId);
if (clearTarget) {
clearContainer(theDiv);
}
theDiv.style.display="";
var newdiv = document.createElement("div");
newdiv.innerHTML = result;
theDiv.appendChild(newdiv);
return;
}
function clearContainerNamed(targetName) {
var divs = document.getElementsByTagName("div");
var theDiv;
for (var i=0;i<divs.length;i++) {
theDiv = divs[i];
if (theDiv.className && theDiv.className.match(targetName)) {
clearContainer(theDiv);
}
}
}
function clearContainerNamedAndChildren(targetName) {
var divs = document.getElementsByTagName("div");
var theDiv;
for (var i=0;i<divs.length;i++) {
theDiv = divs[i];
if (theDiv.className && theDiv.className.match(targetName)) {
clearContainerAndChildren(theDiv);
}
}
}
function clearContainer(theContainer) {
theContainer.style.display = "none";
theContainer.innerHTML="";
}
function clearContainerAndChildren(theContainer) {
while(theContainer.firstChild) {
theContainer.removeChild(theContainer.firstChild);
}
}
/* hide any existing submit/reset buttons
*/
function hideSubmitResetButtons(theSpan) {
if (theSpan.className && theSpan.className.match("eaSubmitResetButtonGroup")) {
theSpan.style.display = "none";
}
}
/* deaden existing form elements since they can not be resubmitted anyway.
*/
function handleExistingFormElements(form) {
var formElements = form.elements;
for (var i=0;i<formElements.length;i++) {
var theElement = formElements[i];
theElement.disabled = true;
}
}
function clearContentWithBaseClass(baseClass) {
var divs = document.getElementsByTagName("div");
var theDiv;
for (var i=0;i<divs.length;i++) {
theDiv = divs[i];
if (theDiv.className && theDiv.className.match(baseClass)) {
clearContainer(theDiv);
}
}
} | javascript | 18 | 0.626547 | 80 | 27.914894 | 235 | starcoderdata |
void GetMetadataInfo(int contentbytelength, int jumper, bool isBigEndian)
{
_blocklist = new XMFBlockList();
stream.Read(buffer = new byte[16], 0, 16);
blockhash = BytesToHex(buffer);
stream.Position += jumper;
stream.Read(buffer = new byte[4], 0, 4);
blocksize = isBigEndian ? BytesToUInt32Big(buffer) : BitConverter.ToUInt32(buffer, 0);
// Reserve 4 bytes but will read as it requested by contentbytelength.
stream.Read(buffer = new byte[4], 0, contentbytelength);
contentcount = isBigEndian ? BytesToUInt32Big(buffer) : BitConverter.ToUInt32(buffer, 0);
_blocklist.BlockHash = blockhash;
_blocklist.BlockSize = blocksize;
#if (DEBUG)
Console.WriteLine($" > {blockhash} -> {SummarizeSizeSimple(blocksize)} ({contentcount} chunks)");
#endif
} | c# | 13 | 0.617582 | 112 | 42.380952 | 21 | inline |
public void sendSMSMessage(){
String smsMessage = etSMSMessage.getText().toString();
if (etSMSMessage.length() >0 && fullNumbers != null){
final String[] numbers = fullNumbers.split(",");
if (sendButtonPressedMoreThanOnce){
} else {
tvMessageStatus.setText("Total SMS to send: " + String.valueOf(numbers.length));
tvMessageStatus.setText(tvMessageStatus.getText().toString() + "\n" + "Preparing to send");
//btStopSending.setVisibility(View.VISIBLE);
sendingSMSActive = true;
}
for (int i=0; i< numbers.length; i++){
sendButtonPressedMoreThanOnce = true;
sendingSMSActive = true;
if (sendingSMSActive){
final String numberToSendTo = numbers[i];
final String message = smsMessage;
final int sendCount = i;
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Do something after 5s = 5000ms
runnable=this;
if (sendSMS2(numberToSendTo, message)){
tvMessageStatus.setText(tvMessageStatus.getText().toString() + "\n" + "SMS Sent to " + String.valueOf(numberToSendTo));
if (sendCount + 1 == numbers.length){
sendButtonPressedMoreThanOnce = false;
sendingSMSActive = false;
//btStopSending.setVisibility(View.GONE);
}
handler.removeCallbacks(runnable);
}else {
tvMessageStatus.setText(tvMessageStatus.getText().toString() + "\n" +"Failed to send to " + String.valueOf(numberToSendTo));
}
handler.removeCallbacks(runnable);
}
}, 1000);
} else {
tvMessageStatus.setText(tvMessageStatus.getText().toString() + "\n" + "Sending SMS Has been stopped.");
}
}
} else {
Toast.makeText(getApplicationContext(), "Message or number list cannot be empty.",Toast.LENGTH_LONG).show();
}
} | java | 27 | 0.469841 | 156 | 29.743902 | 82 | inline |
import { CollectionView } from 'marionette';
import styles from './faqItems.css';
import FaqItemView from './faqItemView.js';
import FaqType from './faqType.js';
export default CollectionView.extend({
tagName: 'ul',
className: styles.faqItems,
childView: FaqItemView,
_type: FaqType.None,
initialize(options) {
this._type = options.type;
},
filter(faqItem) {
return faqItem.get('type') === this._type;
}
}); | javascript | 12 | 0.683486 | 46 | 20.85 | 20 | starcoderdata |
package com.tinytongtong.androidstudy.textview;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;
import com.tinytongtong.androidstudy.R;
/**
* @Description:
* @Author tinytongtong
* @Date 2020/10/29 1:58 PM
* @Version
*/
public class TextViewTestActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_view_test);
TextView tv = (TextView) findViewById(R.id.tv);
String str1 = "感谢您是选择吉利汽车App\n\n";
String str2 = "我们非常重视您的个人信息和隐私保护。为了更好的保证您的个人权益,在您使用我们的产品钱,请务必审慎阅读";
String str3 = "《用户协议》";
String str4 = "与";
String str5 = "《隐私政策》";
String str6 = "内的是所有条款。";
txtAppendSsb(tv,str1,R.color.font_assist_1);
txtAppendSsb(tv,str2,R.color.font_assist_1);
txtAppendSsb(tv,str3,R.color.txt_red_f2233b);
txtAppendSsb(tv,str4,R.color.font_assist_1);
txtAppendSsb(tv,str5,R.color.txt_red_f2233b);
txtAppendSsb(tv,str6,R.color.font_assist_1);
}
private void txtAppendSsb(TextView txt, String str, int color) {
SpannableString ssb = new SpannableString(str);
ssb.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, color)), 0, str.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
txt.append(ssb);
}
} | java | 12 | 0.704739 | 133 | 32.612245 | 49 | starcoderdata |
"""
This script will execute the tracking of a person in a video stream
using an algorithm to control the movements of the drone.
We'll connect to the drone, get the video stream and check
whether a person is in the frame. If so, we'll use the algorithm
to control the drone, otherwise the drone will stay still.
*Before executing the script:*
Be sure that you connected the drone to the computer
"""
import cv2
from djitellopy import Tello
ARROW_KEYS = {
'UP': 0,
'DOWN': 1,
'LEFT': 2,
'RIGHT': 3
}
tello = Tello()
tello.connect()
print(f'Available battery: {tello.get_battery()}')
tello.streamon()
cap = tello.get_video_capture()
while True:
ret, frame = cap.read()
if not ret:
break
frame = cv2.resize(frame, (160, 90))
cv2.imshow('Drone video frame', frame)
if cv2.waitKey(1) == ARROW_KEYS['UP']:
print(f'Pressed UP')
tello.takeoff()
if cv2.waitKey(1) == ARROW_KEYS['RIGHT']:
print(f'Pressed RIGHT')
tello.rotate_clockwise(60)
if cv2.waitKey(1) == ARROW_KEYS['LEFT']:
print(f'Pressed LEFT')
tello.rotate_counter_clockwise(60)
if cv2.waitKey(1) == ARROW_KEYS['DOWN']:
print(f'Pressed DOWN')
tello.land()
tello.streamoff()
break
cv2.destroyAllWindows() | python | 9 | 0.702593 | 67 | 21.053571 | 56 | starcoderdata |
"""
File: CheckerTest.py
License: Part of the PIRA project. Licensed under BSD 3 clause license. See LICENSE.txt file at https://github.com/jplehr/pira/LICENSE.txt
Description: Tests for the Checker-module
"""
import sys
sys.path.append('../../')
import unittest
import lib.Utility as util
import lib.Logging as L
from lib.Configuration import PiraConfiguration, PiraConfigurationErrorException, PiraConfigurationII, PiraItem, PiraConfigurationAdapter
import lib.Checker as Ch
functor_files = [
"/home/pira/build_dir/item1/functors/analyse_item1_ct.py",
"/home/pira/build_dir/item1/functors/clean_item1_ct.py",
"/home/pira/build_dir/item1/functors/no_instr_item1_ct.py",
"/home/pira/build_dir/item1/functors/item1_ct.py",
"/home/pira/build_dir/item1/functors/runner_item1_ct.py",
"/home/pira/build_dir/item2/functors/analyse_item2.py",
"/home/pira/build_dir/item2/functors/clean_item2.py",
"/home/pira/build_dir/item2/functors/no_instr_item2.py",
"/home/pira/build_dir/item2/functors/item2.py",
"/home/pira/build_dir/item2/functors/runner_item2.py",
]
directories_to_create = [
"/home/pira/build_dir/item1/analyzer",
"/home/pira/build_dir/item1/functors",
"/home/pira/build_dir/item2/analyzer",
"/home/pira/build_dir/item2/functors"
]
tempdir = util.get_tempdir()
dep_aw_ins_anal = {
'item1': [tempdir + '/home/pira/build_dir/item1/functors',
tempdir + '/home/pira/build_dir/item1/cubes',
tempdir + '/home/pira/build_dir/item1/analyzer'],
'item2': [tempdir + '/home/pira/build_dir/item2/functors',
tempdir + '/home/pira/build_dir/item2/cubes',
tempdir + '/home/pira/build_dir/item2/analyzer']
}
build_dirs_v2 = {"item1": tempdir + "/home/pira/build_dir/item1",
"item2": tempdir + "/home/pira/build_dir/item2"}
items_v2 = ["item1","item2"]
class CheckerTestCase(unittest.TestCase):
@classmethod
def setUp(self):
self.config_v1= PiraConfiguration()
self.config_v1.set_build_directories([tempdir + '/home/pira/build_dir'])
self.config_v1.populate_build_dict(self.config_v1.directories)
self.config_v1.set_items(['item1', 'item2'], self.config_v1.directories[0])
self.config_v1.initialize_item_dict(self.config_v1.directories[0], self.config_v1.builds[self.config_v1.directories[0]]['items'])
for build_dir in self.config_v1.directories:
for item in self.config_v1.builds[build_dir]['items']:
self.config_v1.set_item_instrument_analysis(dep_aw_ins_anal[item], build_dir, item)
self.config_v1.set_item_builders(tempdir + '/home/pira/build_dir/item1/functors', build_dir, item)
self.config_v1.set_item_args([], build_dir, item)
self.config_v1.set_item_runner("/" + item + "/runner/functors.dir", build_dir, item)
self.config_v2 = PiraConfigurationII()
pira_item1 = PiraItem("item1")
pira_item1.set_analyzer_dir(tempdir + "/home/pira/build_dir/item1/analyzer")
pira_item1.set_cubes_dir(tempdir + "/home/pira/build_dir/item1/cubes")
pira_item1.set_flavors(["ct"])
pira_item1.set_functors_base_path(tempdir + "/home/pira/build_dir/item1/functors")
pira_item1.set_mode("CT")
self.config_v2.add_item(tempdir + "/home/pira/build_dir/item1/",pira_item1)
pira_item2 = PiraItem("item2")
pira_item2.set_analyzer_dir(tempdir + "/home/pira/build_dir/item2/analyzer")
pira_item2.set_cubes_dir(tempdir + "/home/pira/build_dir/item2/cubes")
pira_item2.set_flavors([])
pira_item2.set_functors_base_path(tempdir + "/home/pira/build_dir/item2/functors")
pira_item2.set_mode("CT")
self.config_v2.add_item(tempdir + "/home/pira/build_dir/item2/",pira_item2)
self.config_adapter = PiraConfigurationAdapter(self.config_v2)
self.create_tempfiles(self)
def tearDown(self):
self.delete_tempfolders()
def create_tempfiles(self):
for directory in directories_to_create:
util.make_dirs(tempdir + directory)
for filepath in functor_files:
tempfile = open(tempdir + filepath,'a')
tempfile.close()
def delete_tempfolders(self):
util.remove_dir(tempdir + "/home/pira/")
def test_checker_v1_valid_config(self):
Ch.Checker.check_configfile_v1(self.config_v1)
def test_checker_v1_dirs_missing(self):
for directory in directories_to_create:
util.remove_dir(tempdir + directory)
with self.assertRaises(PiraConfigurationErrorException): Ch.Checker.check_configfile_v1(self.config_v1)
self.create_tempfiles()
def test_checker_v2_valid_config(self):
Ch.Checker.check_configfile_v2(self.config_v2)
def test_checker_v2_adapter_valid_config(self):
Ch.Checker.check_configfile_v2(self.config_adapter)
def test_checker_v2_functors_missing(self):
for file in functor_files:
util.remove_file(tempdir + file)
with self.assertRaises(PiraConfigurationErrorException): Ch.Checker.check_configfile_v2(self.config_v2)
self.create_tempfiles()
def test_checker_v2_dirs_missing(self):
for directory in directories_to_create:
util.remove_dir(tempdir + directory)
with self.assertRaises(PiraConfigurationErrorException): Ch.Checker.check_configfile_v2(self.config_v2)
self.create_tempfiles()
if __name__ == '__main__':
L.get_logger().set_state('info', False)
unittest.main() | python | 16 | 0.705694 | 138 | 38.288889 | 135 | starcoderdata |
module.exports = {
title: 'Getting Productive with AWS',
description:
'The quickest way to be productive with Amazon Web Services. It covers the most used (by far) services and common architectures/patterns.',
base: '/resources/',
dest: 'docs',
extraWatchFiles: ['.vuepress/config.js'],
lastUpdated: 'Last updated',
themeConfig: {
nav: [
{ text: 'Home', link: '/' },
{
text: 'AWS Training',
link: 'https://github.com/ro-msg-aws-training/resources',
},
{
text: 'React Training',
link: 'https://github.com/ro-msg-react-training/resources',
},
{
text: 'Angular Training',
link: 'https://github.com/ro-msg-angular-training/resources',
},
{
text: 'Spring Training',
link: 'https://github.com/ro-msg-spring-training/resources',
},
],
sidebar: [
{
title: 'Preface',
path: '/',
},
{
title: 'Cloud Intro',
path: '/cloud/',
},
{
title: 'AWS Intro',
path: '/aws/',
},
{
title: 'AWS Services',
path: '/services/',
},
{
title: 'Regions and AZs',
path: '/infra/',
},
{
title: 'Infrastructure as Code',
path: '/iac/',
},
{
title: 'IAM',
path: '/iam/',
},
{
title: 'Security',
path: '/security/',
},
{
title: 'Networking',
path: '/networking/',
},
{
title: 'EC2',
path: '/ec2/',
},
{
title: 'RDS',
path: '/rds/',
},
{
title: 'S3',
path: '/s3/',
},
{
title: 'Containers',
path: '/containers/',
},
{
title: 'Integration',
path: '/integration/',
},
{
title: 'Serverless',
path: '/serverless/',
},
{
title: 'Lambda',
path: '/lambda/',
},
{
title: 'Cognito',
path: '/cognito/',
},
{
title: 'DynamoDB',
path: '/dynamo/',
},
{
title: 'API Gateway',
path: '/apigw/',
},
],
},
}; | javascript | 9 | 0.429649 | 143 | 19.669725 | 109 | starcoderdata |
// Copyright (C) 2011 - 2014 See included LICENCE file.
#include
namespace GT
{
TextMesh::TextMesh()
: m_vertices(), m_indices(), m_glyphMapHandle(0)
{
}
TextMesh::TextMesh(const TextMeshVertex* verticesIn, size_t vertexCount, const unsigned int* indicesIn, size_t indexCount, GlyphMapHandle glyphMapHandle)
: m_vertices(vertexCount), m_indices(indexCount), m_glyphMapHandle(glyphMapHandle)
{
for (size_t i = 0; i < vertexCount; ++i)
{
m_vertices.PushBack(verticesIn[i]);
}
for (size_t i = 0; i < indexCount; ++i)
{
m_indices.PushBack(indicesIn[i]);
}
}
TextMesh::~TextMesh()
{
}
void TextMesh::SetVertexColours(float r, float g, float b)
{
for (size_t i = 0; i < m_vertices.count; ++i)
{
auto &vertex = m_vertices[i];
vertex.colourR = r;
vertex.colourG = g;
vertex.colourB = b;
}
}
} | c++ | 12 | 0.559048 | 157 | 24 | 42 | starcoderdata |
def itemSelected(self, index):
if index == -1:
print "canceld"
return
# Reduce index by one, because buffer does not contains ..
index = index - 2
if self.data[index + 2] == '..':
self.path = self.dirname(self.path)
self.getFiles(self.path)
return
if self.data[index + 2] == '.':
if self.action == 'save_file':
self.getFilename(self.path)
else:
self.getFiles(self.path)
return
self.path = self.buffer[index].get('name')
if self.action == 'open_file':
if self.buffer[index].get('type') == 'file':
self.openFile(self.path)
return
if self.buffer[index].get('type') == 'directory':
self.getFiles(self.path)
return
if self.action == 'save_file':
if self.buffer[index].get('type') == 'directory':
self.getFilename(self.path)
return
if self.buffer[index].get('type') == 'file':
self.saveFile()
return | python | 12 | 0.605464 | 60 | 27.580645 | 31 | inline |
def __init__(self, pinlist, cols, rows = 2): # Init with pin nos for enable, rs, D4, D5, D6, D7
self.initialising = True
self.LCD_E = Pin(pinlist[1], Pin.OUT) # Create and initialise the hardware pins
self.LCD_RS = Pin(pinlist[0], Pin.OUT)
self.datapins = [Pin(pin_name, Pin.OUT) for pin_name in pinlist[2:]]
self.cols = cols
self.rows = rows
self.lines = [""] * self.rows
self.dirty = [False] * self.rows
for thisbyte in LCD.INITSTRING:
self.lcd_byte(thisbyte, LCD.CMD)
self.initialising = False # Long delay after first byte only
loop = asyncio.get_event_loop()
loop.create_task(self.runlcd()) | python | 9 | 0.586111 | 95 | 50.5 | 14 | inline |
package lyf.framework.admin.controller;
import lombok.AllArgsConstructor;
import lyf.framework.admin.service.RegistryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* @author lyf
* @description 测试nacos注册服务
* @date 2020-01-14 11:26
*/
@RestController
@RequestMapping("admin/test")
@AllArgsConstructor
public class TestController {
private RegistryService registryService;
private final RestTemplate restTemplate;
@GetMapping("/echo/{arg}")
public String echo(@PathVariable String arg) {
// rest调用
//return restTemplate.getForObject("http://nacos-registry/registry/echo/" + arg, String.class );
// 声明式远程调用
return registryService.feignTest(arg);
}
} | java | 13 | 0.775635 | 105 | 31.6 | 35 | starcoderdata |
package tjp.wiji.drawing;
import static com.google.common.base.Preconditions.checkNotNull;
import java.net.URISyntaxException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import tjp.wiji.event.EventProcessor;
import tjp.wiji.event.GameEvent;
import tjp.wiji.gui.Screen;
import tjp.wiji.gui.ScreenContext;
import tjp.wiji.representations.ImageRepresentation;
public abstract class MainFrame extends ApplicationAdapter
implements InputProcessor {
private SpriteBatch batch;
private EventProcessor eventProcessor;
private Texture spriteSheet;
private long startTime = 0;
private long timeSinceLastRender = 0;
private BitmapContext bitmapContext;
private ShaderContext shaderContext;
private ScreenContext screenContext;
private final int widthInSlots, heightInSlots;
private final static Logger logger = LoggerFactory.getLogger(MainFrame.class);
public MainFrame(final BitmapContext bitmapContext,
final int widthInSlots, final int heightInSlots) {
this.bitmapContext = bitmapContext;
this.widthInSlots = widthInSlots;
this.heightInSlots = heightInSlots;
}
@Override
public void create() {
Gdx.input.setInputProcessor(this);
batch = new SpriteBatch();
bitmapContext.init();
spriteSheet = new Texture(bitmapContext.getCharsheet());
try {
shaderContext = new ShaderContext();
} catch (URISyntaxException e) {
Gdx.app.error("ERROR", "my error message", e);
System.exit(0);
}
this.screenContext = createStartingScreenContext();
}
protected abstract ScreenContext createStartingScreenContext();
protected BitmapContext getBitmapContext() {
return bitmapContext;
}
public Screen getCurrentScreen() {
return screenContext.getCurrentScreen();
}
//temporarily kludged to be public, please make protected
public int getImageGridHeight() {
return heightInSlots;
}
//temporarily kludged to be public, please make protected
public int getImageGridWidth() {
return widthInSlots;
}
@Override
public final boolean keyDown(int keycode) {
getCurrentScreen().handleEvent(new GameEvent(keycode));
return false;
}
@Override
public final boolean keyTyped(char character) {
getCurrentScreen().handleEvent(new GameEvent(character));
return false;
}
@Override
public final boolean keyUp(int keycode) {
return false;
}
@Override
public final boolean mouseMoved(int screenX, int screenY) {
return false;
}
@Override
public void dispose() {
batch.dispose();
spriteSheet.dispose();
shaderContext.getShader().dispose();
disposeHook();
System.exit(0);
}
protected abstract void disposeHook();
@Override
public void render () {
timeSinceLastRender = System.nanoTime() - startTime;
ImageRepresentation[][] cellsToDraw = getCurrentScreen().render(timeSinceLastRender/1000,
getImageGridWidth(), getImageGridHeight());
timeSinceLastRender = 0;
startTime = System.nanoTime();
Gdx.gl.glClearColor(0f, 1f, 0f, 0f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.setShader(shaderContext.getShader());
int pixelWidth = bitmapContext.getCharPixelWidth();
int pixelHeight = bitmapContext.getCharPixelHeight();
for(int row = 0; row < cellsToDraw.length ; row++) {
for(int col = 0; col < cellsToDraw[row].length ; col++) {
ImageRepresentation currCell = cellsToDraw[row][col];
drawBatch(row, col, pixelWidth, pixelHeight, currCell);
batch.flush();
}
}
batch.end();
}
private void configureShaderForCell(final Color backColor, final Color foreColor) {
shaderContext.getShader().setAttributef("a_backColor",
backColor.getClampedRed(), backColor.getClampedGreen(), backColor.getClampedBlue(), 1);
shaderContext.getShader().setAttributef("a_frontColor",
foreColor.getClampedRed(), foreColor.getClampedGreen(), foreColor.getClampedBlue(), 1);
}
/**
*
* @param row
* @param col
* @param pixelWidth
* @param pixelHeight
* @param currCell
*/
private void drawBatch(int row, int col, int pixelWidth, int pixelHeight,
ImageRepresentation currCell) {
checkNotNull(currCell);
checkNotNull(currCell.getBackColor());
checkNotNull(currCell.getForeColor());
configureShaderForCell(currCell.getBackColor(), currCell.getForeColor());
int graphicIndex = currCell.getImgChar();
int charsheetWidth = bitmapContext.getCharsheetGridHeight();
int charCodeX = graphicIndex % charsheetWidth;
int charCodeY = graphicIndex / charsheetWidth;
int x = row * pixelWidth;
int y = (heightInSlots - col - 1) * pixelHeight;
batch.draw(
spriteSheet,
//coordinates in screen space
x, y,
//coordinates of the scaling and rotation origin
//relative to the screen space coordinates
x, y,
//width and height in pixels
pixelWidth, pixelHeight,
//scale of the rectangle around originX/originY
1,1,
//the angle of counter clockwise rotation of the
//rectangle around originX/originY
0,
//coordinates in texel space
charCodeX * pixelWidth, charCodeY * pixelHeight,
//source width and height in texels
pixelWidth, pixelHeight,
//whether to flip the sprite horizontally or vertically
false,false);
}
@Override
public final boolean scrolled(int amount) {
return false;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
return false;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return false;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
} | java | 13 | 0.631771 | 103 | 30.855814 | 215 | starcoderdata |
///*|-----------------------------------------------------------------------------
// *| This source code is provided under the Apache 2.0 license --
// *| and is provided AS IS with no warranty or guarantee of fit for purpose. --
// *| See the project's LICENSE.md for details. --
// *| Copyright 2018. All rights reserved. --
///*|-----------------------------------------------------------------------------
package com.thomsonreuters.ema.access;
/**
* OmmConsumer class encapsulates functionality of an Omm consuming type application.
*
* provides interfaces to open, modify and close items.
* It establishes and maintains connection to server, maintains open item watch list,
* performs connection and item recovery, etc.
*
* provides a default behaviour / functionality.
* This may be tuned / modified by application when using OmmConsumerConfig.
*
* interacts with server through the OmmConsumer interface methods.
* The results of these interactions are communicated back to application through
* OmmConsumerClient and OmmConsumerErrorClient.
*
* OmmConsumer is created from EmaFactory
* (see {@link com.thomsonreuters.ema.access.EmaFactory#createOmmConsumer(OmmConsumerConfig)}
* or {@link com.thomsonreuters.ema.access.EmaFactory#createOmmConsumer(OmmConsumerConfig, OmmConsumerErrorClient)}).
*
*
* The following consumer example shows basic usage of OmmConsumer class in a simple consumer type app.
* This application opens a regular streaming item named RTR from a service RDF from the 1.1.1.1 server
* on port 14002.
*
*
* // create an implementation for OmmConsumerClient to process received item messages
* class AppClient implements OmmConsumerClient
* {
* public void onRefreshMsg(RefreshMsg refreshMsg, OmmConsumerEvent event)
* {
* System.out.println(refreshMsg);
* }
*
* public void onUpdateMsg(UpdateMsg updateMsg, OmmConsumerEvent event)
* {
* System.out.println(updateMsg);
* }
*
* public void onStatusMsg(StatusMsg statusMsg, OmmConsumerEvent event)
* {
* System.out.println(statusMsg);
* }
*
* public void onGenericMsg(GenericMsg genericMsg, OmmConsumerEvent consumerEvent){}
* public void onAckMsg(AckMsg ackMsg, OmmConsumerEvent consumerEvent){}
* public void onAllMsg(Msg msg, OmmConsumerEvent consumerEvent){}
* }
*
* public class Consumer
* {
* public static void main(String[] args)
* {
* OmmConsumer consumer = null;
* try
* {
* AppClient appClient = new AppClient();
* OmmConsumerConfig config = EmaFactory.createOmmConsumerConfig();
*
* // instantiate OmmConsumer object and connect it to a server
* consumer = EmaFactory.createOmmConsumer(config.host("1.1.1.1:14002"));
*
* // open an item of interest
* ReqMsg reqMsg = EmaFactory.createReqMsg();
* consumer.registerClient(reqMsg.serviceName("RDF").name("RTR"), appClient);
*
* Thread.sleep(60000); // API calls onRefreshMsg(), onUpdateMsg() and onStatusMsg()
* }
* catch (InterruptedException | OmmException excp)
* {
* System.out.println(excp.getMessage());
* }
* finally
* {
* if (consumer != null) consumer.uninitialize();
* }
* }
* }
*
*
* @see OmmConsumerConfig
* @see OmmConsumerClient
* @see OmmConsumerErrorClient
* @see EmaFactory
*/
public interface OmmConsumer
{
/**
* The Class DispatchTimeout.
*/
public static class DispatchTimeout
{
/** dispatch blocks till a message arrives. */
public static final int INFINITE_WAIT = 0;
/** dispatch exits immediately even if there is no message. */
public static final int NO_WAIT = 1;
}
/**
* The Class DispatchReturn.
*/
public static class DispatchReturn
{
/** dispatch exits immediately even if there is no message. */
public static final int TIMEOUT = 0;
/** a message was dispatched on this dispatch call. */
public static final int DISPATCHED = 1;
}
/**
* Retrieve internally generated consumer instance name.
*
* @return name of this OmmConsumer instance
*/
public String consumerName();
/**
*
* Opens an item stream.
*
* method is ObjectLevelSafe if OmmConsumerErrorClient is used and an error condition is encountered,
* then null handle is returned.
*
* @param reqMsg specifies item and its unique attributes
* @param client specifies OmmConsumerClient instance receiving notifications about this item
* @return item identifier (a.k.a. handle)
* @throws OmmInvalidUsageException if application passes invalid ReqMsg
* @throws OmmInvalidHandleException if application passes invalid parent item handle
*/
public long registerClient(ReqMsg reqMsg, OmmConsumerClient client);
/**
*
* Opens an item stream.
*
* method is ObjectLevelSafe if OmmConsumerErrorClient is used and an error condition is encountered,
* then null handle is returned.
*
* @param reqMsg specifies item and its unique attributes
* @param client specifies OmmConsumerClient instance receiving notifications about this item
* @param closure specifies application defined item identification
* @return item identifier (a.k.a. handle)
* @throws OmmInvalidUsageException if application passes invalid ReqMsg
* @throws OmmInvalidHandleException if application passes invalid parent item handle
*/
public long registerClient(ReqMsg reqMsg, OmmConsumerClient client, Object closure);
/**
*
* Opens an item stream.
*
* method is ObjectLevelSafe if OmmConsumerErrorClient is used and an error condition is encountered,
* then null handle is returned.
*
* @param reqMsg specifies item and its unique attributes
* @param client specifies OmmConsumerClient instance receiving notifications about this item
* @param closure specifies application defined item identification
* @param parentHandle specifies handle of tunnel stream over which this substream is open (required for substreams)
* @return item identifier (a.k.a. handle)
* @throws OmmInvalidUsageException if application passes invalid ReqMsg
* @throws OmmInvalidHandleException if application passes invalid parent item handle
*/
public long registerClient(ReqMsg reqMsg, OmmConsumerClient client, Object closure, long parentHandle);
/**
* Opens a tunnel stream.
*
* method is ObjectLevelSafe if OmmConsumerErrorClient is used and an error condition is encountered,
* then null handle is returned.
*
* @param tunnelStreamRequest specifies tunnel stream attributes
* @param client specifies OmmConsumerClient instance receiving notifications about this item
* @return tunnel stream handle (a.k.a. parentHandle)
* @throws OmmInvalidUsageException if application passes invalid TunnelStreamRequest
*/
public long registerClient(TunnelStreamRequest tunnelStreamRequest, OmmConsumerClient client);
/**
* Opens a tunnel stream.
*
* method is ObjectLevelSafe if OmmConsumerErrorClient is used and an error condition is encountered,
* then null handle is returned.
*
* @param tunnelStreamRequest specifies tunnel stream attributes
* @param client specifies OmmConsumerClient instance receiving notifications about this item
* @param closure specifies application defined item identification
* @return tunnel stream handle (a.k.a. parentHandle)
* @throws OmmInvalidUsageException if application passes invalid TunnelStreamRequest
*/
public long registerClient(TunnelStreamRequest tunnelStreamRequest, OmmConsumerClient client, Object closure);
/**
*
* Changes the interest in an open item stream.
* The first formal parameter houses a ReqMsg.
* ReqMsg attributes that may change are Priority(), InitialImage(), InterestAfterRefresh(),
* Pause() and Payload ViewData().
* The second formal parameter is a handle that identifies the open stream to be modified.
* This method is ObjectLevelSafe.
*
* @param reqMsg specifies modifications to the open item stream
* @param handle identifies item to be modified
* @throws OmmInvalidHandleException if passed in handle does not refer to an open stream
* @throws OmmInvalidUsageException if passed in ReqMsg violates reissue rules
*/
public void reissue(ReqMsg reqMsg, long handle);
/**
* Sends a GenericMsg.
* method is ObjectLevelSafe.
*
* @param genericMsg specifies GenericMsg to be sent on the open item stream
* @param handle identifies item stream on which to send the GenericMsg
* @throws OmmInvalidHandleException if passed in handle does not refer to an open stream
*/
public void submit(GenericMsg genericMsg, long handle);
/**
* Sends a PostMsg.
* Accepts a PostMsg and optionally a handle associated to an open item stream.
* Specifying an item handle is known as "on stream posting".
* Specifying a login handle is known as "off stream posting".
* This method is ObjectLevelSafe.
*
* @param postMsg specifies PostMsg to be sent on the open item stream
* @param handle identifies item stream on which to send the PostMsg
* @throws OmmInvalidHandleException if passed in handle does not refer to an open stream
*/
void submit(PostMsg postMsg, long handle);
/**
* Relinquishes application thread of control to receive callbacks via OmmConsumerClient descendant.
* Requires OperationalModel to be set to {@link OmmConsumerConfig.OperationModel#USER_DISPATCH}.
* This method is ObjectLevelSafe.
*
* @return {@link DispatchReturn#TIMEOUT} if nothing was dispatched; {@link DispatchReturn#DISPATCHED} otherwise
* @throws OmmInvalidUsageException if OperationalModel is not set to {@link OmmConsumerConfig.OperationModel#USER_DISPATCH}
*/
public long dispatch();
/**
* Relinquishes application thread of control to receive callbacks via OmmConsumerClient descendant.
* Requires OperationalModel to be set to {@link OmmConsumerConfig.OperationModel#USER_DISPATCH}.
* This method is ObjectLevelSafe.
*
* @param timeOut specifies time in microseconds to wait in dispatch() for a message to dispatch
* @return {@link DispatchReturn#TIMEOUT} if nothing was dispatched; {@link DispatchReturn#DISPATCHED} otherwise
* @throws OmmInvalidUsageException if OperationalModel is not set to {@link OmmConsumerConfig.OperationModel#USER_DISPATCH}
*/
public long dispatch(long timeOut);
/**
* Relinquishes interest in an open item stream.
* This method is ObjectLevelSafe.
*
* @param handle identifies item to close
*/
public void unregister(long handle);
/**
* Uninitializes the OmmConsumer object.
* This method is ObjectLevelSafe.
*/
public void uninitialize();
/**
* Retrieves channel information on the OmmConsumer object.
*
* @param ci the ChannelInformation
*/
public void channelInformation(ChannelInformation ci);
} | java | 7 | 0.6973 | 125 | 38.280702 | 285 | starcoderdata |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LoopsCript : MonoBehaviour {
// Start is called before the first frame update
void Start() {
/* foreach(Type elementName in collection) { } */
List studentsNames = new List
studentsNames.Add("Christian");
studentsNames.Add("Camilo");
studentsNames.Add("Fulano");
studentsNames.Add("Anastasia");
studentsNames.Add("Jack");
foreach (string person in studentsNames) {
Debug.Log(person);
}
}
// Update is called once per frame
void Update() {
}
} | c# | 12 | 0.67863 | 53 | 22.576923 | 26 | starcoderdata |
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateDatosMedicosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('datos_medicos', function(Blueprint $table) {
$table->increments('id');
$table->integer('id_estudiante')->unsigned();
$table->foreign('id_estudiante')->references('id')->on('datos_generales_estudiante')->onDelete('Cascade');
$table->string('grupo_sanguineo', 50);
$table->double('peso', 10,2);
$table->double('altura', 10,2);
$table->text('capacidad_especial');
$table->integer('porcentaje_discapacidad');
$table->text('medicinas_contraindicadas');
$table->text('alergico_a');
$table->text('patologia');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('datos_medicos');
}
} | php | 19 | 0.572148 | 118 | 28.073171 | 41 | starcoderdata |
CBackgroundCache::CBackgroundCache() :
m_semaphoreQueue(0, 0xF000000)
{
m_aPieces = NULL;
m_aTable = NULL;
m_aHelperTable = NULL;
m_pQueue = NULL;
m_pWorkerThread = NULL;
// set the last position to nonsense value
m_rcLastViewportPosition.SetRect(-1000, -1000, -1000, -1000);
} | c++ | 6 | 0.694915 | 63 | 21.769231 | 13 | inline |
#include <bits/stdc++.h>
using namespace std;
int main() {
long hh,ww,h,w,a=0;
cin >> hh >> ww >> h >> w;
vector<vector<long>> ans(hh,vector<long>(ww));
for(long i=0;i<hh;i++) {
for(long j=0;j<ww;j++) {
if(i%h+j%w==0) ans[i][j]=999999999,a+=999999999;
else if((i+1)%h+(j+1)%w==0) ans[i][j]=-1000000000,a-=1000000000;
}
}
if(a>0&&h*w>1) {
cout << "Yes" << endl;
for(long i=0;i<hh;i++) {
for(long j=0;j<ww;j++) cout << ans[i][j] << " ";
cout << endl;
}
} else {
cout << "No" << endl;
}
} | c++ | 16 | 0.481818 | 70 | 22.956522 | 23 | codenet |
/**
* google-books-search
*
* The Coding Boot Camp at UNC Charlotte.
* (c) 2019
*/
module.exports = {
Book: require('./book'),
}; | javascript | 8 | 0.580645 | 41 | 14.5 | 10 | starcoderdata |
import os
import torch
import torchaudio
import pandas as pd
from typing import Tuple
from torch.utils.data import Dataset
from .preprocessing import NumberToTextVec, LogMelSpectrogram
class VoiceDataset(Dataset):
"""
Parsing CSV Dataset, load raw-audio and labels and preprocessing
"""
def __init__(self, path_csv_dataset: str, num_mels: int = 128):
super(VoiceDataset, self).__init__()
self._path_dataset = os.path.dirname(path_csv_dataset)
self._data = pd.read_csv(path_csv_dataset)
self._number_process = NumberToTextVec()
self._transform = LogMelSpectrogram(n_mels=num_mels)
def __getitem__(self, index: int) -> Tuple[torch.Tensor, torch.Tensor, int, int]:
path, number = self._data[["path", "number"]].iloc[index]
path_to_file = os.path.join(self._path_dataset, path)
waveform, _ = torchaudio.load(path_to_file)
label = self._number_process.number_to_index_vector(number)
label = torch.tensor(label)
# channel, feature, time
spectrogram = self._transform(waveform)
return spectrogram, label, spectrogram.shape[-1] // 2, len(label)
def __len__(self):
return self._data.shape[0] | python | 12 | 0.656377 | 85 | 30.564103 | 39 | starcoderdata |
import tensorflow as tf
import numpy as np
from tensorflow.compat.v1.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, Flatten, Dense, Lambda, Concatenate, \
Reshape
from tensorflow.compat.v1.keras import backend as K
class DecoderBlock(tf.keras.Model):
def __init__(self, kernel_size, filter, block, data_format):
super(DecoderBlock, self).__init__(name='')
conv_name = f'decode_{block}_branch'
self.conv2a = Conv2D(filter, kernel_size=kernel_size, padding='same', kernel_initializer='he_normal',
name=conv_name + '2a', data_format=data_format)
self.conv2b = Conv2D(filter, kernel_size=kernel_size, padding='same', kernel_initializer='he_normal',
name=conv_name + '2b', data_format=data_format)
def call(self, input_tensor, training=False):
x = UpSampling2D()(input_tensor)
x = self.conv2a(x)
x = self.conv2b(x)
return x
class EncoderBlock(tf.keras.Model):
def __init__(self, kernel_size, filter, block, data_format):
super(EncoderBlock, self).__init__(name='')
conv_name = f'encode_{block}_branch'
self.conv2a = Conv2D(filter, kernel_size=kernel_size, padding='same', kernel_initializer='he_normal',
name=conv_name + '2a', data_format=data_format)
self.conv2b = Conv2D(filter, kernel_size=kernel_size, padding='same', kernel_initializer='he_normal',
name=conv_name + '2b', data_format=data_format)
def call(self, input_tensor, training=False):
x = self.conv2a(input_tensor)
x = self.conv2b(x)
x = MaxPooling2D()(x)
return x
class Encoder(tf.keras.Model):
def __init__(self, height, width, data_format, start_filters, latent_dim, conditioning_dim=0, name=''):
super(Encoder, self).__init__(name=name)
valid_channel_values = ('channels_first', 'channels_last')
if data_format not in valid_channel_values:
raise ValueError('Unknown data_format: %s. Valid values: %s' %
(data_format, valid_channel_values))
self.start_filter = start_filters
self.latent_dim = latent_dim
self.height = height
self.width = width
def encode_block(filter, block):
return EncoderBlock(3, filter, block, data_format=data_format)
if conditioning_dim > 0:
self.condition_layer = Dense(height*width, name='conditioning')
self.l1a = encode_block(start_filters, block=1)
self.l2a = encode_block(start_filters * 2, block=2)
self.l3a = encode_block(start_filters * 4, block=3)
self.l4a = encode_block(start_filters * 8, block=4)
self.flatten = Flatten()
self.mean = Dense(self.latent_dim, name='mean')
self.noise = Dense(self.latent_dim, name='noise')
def sampling(self, args):
z_mean, z_log_sigma = args
batch = tf.shape(z_mean)[0]
epsilon = K.random_normal(shape=(batch, self.latent_dim), mean=0., stddev=1.)
return z_mean + K.exp(z_log_sigma) * epsilon
def build_call(self, input_tensor, conditions=None, training=True):
if conditions is not None:
condition_up = self.condition_layer(conditions)
condition_up = Reshape([self.height, self.width, 1])(condition_up)
x = Concatenate(axis=3)([input_tensor, condition_up])
else:
x = input_tensor
x = self.l1a(x)
x = self.l2a(x)
x = self.l3a(x)
x = self.l4a(x)
_, *shape_spatial = x.get_shape().as_list()
x = self.flatten(x)
z_mean = self.mean(x)
z_log_sigma = self.noise(x)
z = Lambda(self.sampling, output_shape=(self.latent_dim,))([z_mean, z_log_sigma])
# kl_loss = - 0.5 * K.mean(1 + z_log_sigma - K.square(z_mean) - K.exp(z_log_sigma), axis=-1)
return z, z_mean, z_log_sigma, shape_spatial
def call(self, input_tensor, conditions=None, training=True):
return self.build_call(input_tensor, conditions=conditions, training=training)
class Decoder(tf.keras.Model):
def __init__(self, shape_spatial, data_format, name=''):
super(Decoder, self).__init__(name=name)
self.shape_spatial = shape_spatial
def decode_block(filter, block):
return DecoderBlock(3, filter, block, data_format=data_format)
self.embedding = Dense(np.prod(shape_spatial), name='embedding')
start_filters = shape_spatial[-1]
self.m1a = decode_block(start_filters, block=1)
self.m2a = decode_block(start_filters//2, block=2)
self.m3a = decode_block(start_filters//4, block=3)
self.m4a = decode_block(start_filters//8, block=4)
self.activation = Conv2D(3, 1, activation='sigmoid')
def call(self, input_tensor, conditions=None, training=True):
if conditions is not None:
x = Concatenate()([input_tensor, conditions])
else:
x = input_tensor
x = self.embedding(x)
x = Reshape(self.shape_spatial)(x)
x = self.m1a(x)
x = self.m2a(x)
x = self.m3a(x)
x = self.m4a(x)
x = self.activation(x)
return x
class VAEBasic(tf.keras.Model):
def __init__(self, height, width, latent_dim, conditioning_dim=0,
start_filters=8, name='VAE'):
super(VAEBasic, self).__init__(name=name)
self.encoder = Encoder(height, width, data_format='channels_last', start_filters=start_filters,
latent_dim=latent_dim, conditioning_dim=conditioning_dim, name='encoder')
trivial_images = tf.random.uniform((1, height, width, 3), maxval=1, dtype=tf.float32)
if conditioning_dim != 0:
trivial_conditions = tf.zeros((1, conditioning_dim), dtype=tf.float32)
else:
trivial_conditions = None
_, z_mean, z_log_sigma, shape_spatial = self.encoder(trivial_images, trivial_conditions, training=False)
self.decoder = Decoder(shape_spatial, data_format='channels_last', name='decoder')
@property
def trainable_weights(self):
return (self.encoder.trainable_weights + self.decoder.trainable_weights)
def call(self, input_tensor, conditions=None, training=True):
z, z_mean, z_log_sigma, _ = self.encoder.build_call(input_tensor, conditions, training=training)
output_tensor = self.decoder(z, conditions, training=training)
return output_tensor, z_mean, z_log_sigma | python | 14 | 0.607643 | 120 | 34.741935 | 186 | starcoderdata |
<?php
declare(strict_types=1);
namespace Genkgo\Camt\Decoder;
use Genkgo\Camt\Decoder\Factory\DTO as DTOFactory;
use Genkgo\Camt\DTO;
use SimpleXMLElement;
abstract class Message
{
/**
* @var Record
*/
protected $recordDecoder;
/**
* @var DateDecoderInterface
*/
protected $dateDecoder;
/**
* Message constructor.
*/
public function __construct(Record $recordDecoder, DateDecoderInterface $dateDecoder)
{
$this->recordDecoder = $recordDecoder;
$this->dateDecoder = $dateDecoder;
}
public function addGroupHeader(DTO\Message $message, SimpleXMLElement $document): void
{
$xmlGroupHeader = $this->getRootElement($document)->GrpHdr;
$groupHeader = new DTO\GroupHeader(
(string) $xmlGroupHeader->MsgId,
$this->dateDecoder->decode((string) $xmlGroupHeader->CreDtTm)
);
if (isset($xmlGroupHeader->AddtlInf)) {
$groupHeader->setAdditionalInformation((string) $xmlGroupHeader->AddtlInf);
}
if (isset($xmlGroupHeader->MsgRcpt)) {
$groupHeader->setMessageRecipient(
DTOFactory\Recipient::createFromXml($xmlGroupHeader->MsgRcpt)
);
}
if (isset($xmlGroupHeader->MsgPgntn)) {
$groupHeader->setPagination(new DTO\Pagination(
(string) $xmlGroupHeader->MsgPgntn->PgNb,
('true' === (string) $xmlGroupHeader->MsgPgntn->LastPgInd) ? true : false
));
}
$message->setGroupHeader($groupHeader);
}
public function addCommonRecordInformation(DTO\Record $record, SimpleXMLElement $xmlRecord): void
{
if (isset($xmlRecord->ElctrncSeqNb)) {
$record->setElectronicSequenceNumber((string) $xmlRecord->ElctrncSeqNb);
}
if (isset($xmlRecord->CpyDplctInd)) {
$record->setCopyDuplicateIndicator((string) $xmlRecord->CpyDplctInd);
}
if (isset($xmlRecord->LglSeqNb)) {
$record->setLegalSequenceNumber((string) $xmlRecord->LglSeqNb);
}
if (isset($xmlRecord->FrToDt)) {
$record->setFromDate($this->dateDecoder->decode((string) $xmlRecord->FrToDt->FrDtTm));
$record->setToDate($this->dateDecoder->decode((string) $xmlRecord->FrToDt->ToDtTm));
}
}
abstract public function addRecords(DTO\Message $message, SimpleXMLElement $document): void;
abstract public function getRootElement(SimpleXMLElement $document): SimpleXMLElement;
} | php | 21 | 0.630062 | 101 | 30.703704 | 81 | starcoderdata |
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;
int main() {
ll n, p;
cin >> n >> p;
vector<int> a(n);
for (int& i : a) cin >> i;
ll c0 = 0, c1 = 0;
for (int i : a) ++(i & 1 ? c1 : c0);
c0 = 1ll << c0;
c1 = (c1 > 0 ? (1ll << (c1 - 1)) : 0);
cout << c0 * max(c1, p ? c1 : 1ll) << endl;
cerr << "c0,c1:" << c0 << "," << c1 << endl;
return 0;
}
| c++ | 11 | 0.43659 | 48 | 25.722222 | 18 | codenet |
namespace CyberCAT.Core.DumpedEnums
{
public enum toolsMessageSeverity
{
Success = 0,
Info = 1,
Warning = 2,
Error = 3
}
} | c# | 6 | 0.700787 | 35 | 11.7 | 10 | starcoderdata |
# The world is a prison for the believer.
## https://www.youtube.com/watch?v=DWfNYztUM1U
from django.dispatch import Signal
## This event is fired before CyberPanel core start creation of an email account.
preSubmitEmailCreation = Signal(providing_args=["request"])
## This event is fired after CyberPanel core finished creation of an email account.
postSubmitEmailCreation = Signal(providing_args=["request", "response"])
## This event is fired before CyberPanel core start deletion of an email account
preSubmitEmailDeletion = Signal(providing_args=["request"])
## This event is fired after CyberPanel core finished deletion of an email account
postSubmitEmailDeletion = Signal(providing_args=["request", "response"])
## This event is fired before CyberPanel core start deletion of email forwarding.
preSubmitForwardDeletion = Signal(providing_args=["request"])
## This event is fired after CyberPanel core finished deletion of email forwarding.
postSubmitForwardDeletion = Signal(providing_args=["request", "response"])
## This event is fired before CyberPanel core start creation of email forwarding.
preSubmitEmailForwardingCreation = Signal(providing_args=["request"])
## This event is fired after CyberPanel core finished creation of email forwarding.
postSubmitEmailForwardingCreation = Signal(providing_args=["request", "response"])
## This event is fired before CyberPanel core start changing password for email account.
preSubmitPasswordChange = Signal(providing_args=["request"])
## This event is fired after CyberPanel core finished changing password for email account.
postSubmitPasswordChange = Signal(providing_args=["request", "response"])
## This event is fired before CyberPanel core start generating dkim keys.
preGenerateDKIMKeys = Signal(providing_args=["request"])
## This event is fired after CyberPanel core finished generating dkim keys.
postGenerateDKIMKeys = Signal(providing_args=["request", "response"]) | python | 8 | 0.794237 | 90 | 47.268293 | 41 | starcoderdata |
@Override
public <T> T urnToValue(URI urn, Class<T> type) {
HandlerMethodInvocation methodInvocation = converter.urnToHandlerMethodInvocation(urn);
if (methodInvocation != null) {
Object result = invokeHandler(methodInvocation);
if (result != null) {
Class<?> resultType = result.getClass();
// if resultType can be assigned to type, we can return it directly
if (type.isAssignableFrom(resultType)) {
return (T) result;
}
// if type is an interface, then take a shortcut - if the returned value implements all the methods
// then we can generate a Proxy (duck typing) instead of using Jackson to convert the value.
if (type.isInterface() && isDuckTyped(type, resultType)) {
logger.debug(resultType + " is duck typed to interface " + type + " - returning dynamic proxy.");
return (T) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[]{type},
(proxy, method, args) -> {
Method target = ReflectionUtils.findMethod(resultType, method.getName(), method.getParameterTypes());
return target.invoke(result, args);
});
} else {
return objectMapper.convertValue(result, type);
}
}
}
return null;
} | java | 21 | 0.539724 | 133 | 55.444444 | 27 | inline |
using System;
using System.Windows;
namespace Microsoft.Research.DynamicDataDisplay.DataSources
{
/// source that returns sequence of 2D points.
public interface IPointDataSource
{
/// object to enumerate points in source.
IPointEnumerator GetEnumerator(DependencyObject context);
/// event is raised when contents of source are changed.
event EventHandler DataChanged;
}
public class Context : DependencyObject
{
private readonly static Context emptyContext = new Context();
public static Context EmptyContext
{
get { return emptyContext; }
}
public void ClearValues()
{
var localEnumerator = GetLocalValueEnumerator();
localEnumerator.Reset();
while (localEnumerator.MoveNext())
{
ClearValue(localEnumerator.Current.Property);
}
}
public Rect VisibleRect
{
get { return (Rect)GetValue(VisibleRectProperty); }
set { SetValue(VisibleRectProperty, value); }
}
public static readonly DependencyProperty VisibleRectProperty =
DependencyProperty.Register(
"VisibleRect",
typeof(Rect),
typeof(Context),
new PropertyMetadata(new Rect()));
public Rect Output
{
get { return (Rect)GetValue(OutputProperty); }
set { SetValue(OutputProperty, value); }
}
public static readonly DependencyProperty OutputProperty =
DependencyProperty.Register(
"Output",
typeof(Rect),
typeof(Context),
new PropertyMetadata(new Rect()));
}
} | c# | 17 | 0.722259 | 82 | 23.564516 | 62 | starcoderdata |
// Copyright 2016 The Fuchsia 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
//
// 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.
#ifndef COBALT_ALGORITHMS_FORCULUS_FORCULUS_UTILS_H_
#define COBALT_ALGORITHMS_FORCULUS_FORCULUS_UTILS_H_
#include "config/encodings.pb.h"
#include "util/datetime_util.h"
// Common utilities used in the encoder and analyzer.
namespace cobalt {
namespace forculus {
using util::kInvalidIndex;
// Compute the Forculus epoch index for the given |day_index| based on
// the given |epoch_type|.
uint32_t EpochIndexFromDayIndex(uint32_t day_index,
const EpochType& epoch_type);
} // namespace forculus
} // namespace cobalt
#endif // COBALT_ALGORITHMS_FORCULUS_FORCULUS_UTILS_H_ | c | 11 | 0.736581 | 75 | 32.638889 | 36 | starcoderdata |
#include <bits/stdc++.h>
using namespace std;
class adj_list {
vector<vector<int>> m_vt;
public:
explicit adj_list( int s ): m_vt( s+1 ) {}
void add_edge( int a, int b ) {
m_vt[a].push_back( b );
m_vt[b].push_back( a );
}
int find_path() const {
vector<bool> vf( m_vt.size()+1 );
vf[1] = true;
return dfs( 1, 1, vf );
}
int dfs( int nd, int nv, vector<bool>& vf ) const {
if( nv == m_vt.size()-1 ) {
return 1;
}
int result = 0;
auto& ed = m_vt[nd];
for( int i = 0; i < ed.size(); ++i ) {
if( !vf[ed[i]] ) {
vf[ed[i]] = true;
result += dfs( ed[i], nv+1, vf );
vf[ed[i]] = false;
}
}
return result;
}
};
int main() {
ios_base::sync_with_stdio( false );
int N, M;
cin >> N >> M;
adj_list al( N );
for( int i = 0; i < M; ++i ) {
int a, b;
cin >> a >> b;
al.add_edge( a, b );
}
cout << al.find_path() << endl;
}
| c++ | 15 | 0.496614 | 52 | 14.821429 | 56 | codenet |
package pojos;
import lt.viko.eif.final_project.pojos.LaunchPad;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import static org.junit.jupiter.api.Assertions.*;
/**
* @author
*/
class LaunchPadTest {
private LaunchPad launchPad;
@BeforeEach
void setUp() {
launchPad = new LaunchPad();
}
@AfterEach
void tearDown() {
launchPad = null;
}
@Test
void getId() {
launchPad.setId(7);
assertEquals(7, launchPad.getId());
}
@Test
void setId() {
launchPad.setId(7);
assertEquals(7, launchPad.getId());
}
@Test
void getName() {
launchPad.setName("TestName");
assertEquals("TestName", launchPad.getName());
}
@Test
void setName() {
launchPad.setName("TestName");
assertEquals("TestName", launchPad.getName());
}
@Test
void getLocationName() {
launchPad.setLocationName("TestLocation");
assertEquals("TestLocation", launchPad.getLocationName());
}
@Test
void setLocationName() {
launchPad.setLocationName("TestLocation");
assertEquals("TestLocation", launchPad.getLocationName());
}
@Test
void getLatitude() {
launchPad.setLatitude(BigDecimal.TEN);
assertEquals(BigDecimal.TEN, launchPad.getLatitude());
}
@Test
void setLatitude() {
launchPad.setLatitude(BigDecimal.TEN);
assertEquals(BigDecimal.TEN, launchPad.getLatitude());
}
@Test
void getLongitude() {
launchPad.setLongitude(BigDecimal.TEN);
assertEquals(BigDecimal.TEN, launchPad.getLongitude());
}
@Test
void setLongitude() {
launchPad.setLongitude(BigDecimal.TEN);
assertEquals(BigDecimal.TEN, launchPad.getLongitude());
}
@Test
void getWikiURL() {
launchPad.setWikiURL("https://example.com");
assertEquals("https://example.com", launchPad.getWikiURL());
}
@Test
void setWikiURL() {
launchPad.setWikiURL("https://example.com");
assertEquals("https://example.com", launchPad.getWikiURL());
}
@Test
void getMapsURL() {
launchPad.setMapsURL("https://example.com");
assertEquals("https://example.com", launchPad.getMapsURL());
}
@Test
void setMapsURL() {
launchPad.setMapsURL("https://example.com");
assertEquals("https://example.com", launchPad.getMapsURL());
}
@Test
void addLink() {
launchPad.addLink("https://example.com", "rel");
assertEquals(1, launchPad.getLinks().size());
}
@Test
void getLinks() {
launchPad.addLink("https://example.com", "rel");
assertEquals(1, launchPad.getLinks().size());
}
} | java | 9 | 0.618802 | 68 | 22.427419 | 124 | starcoderdata |
package com.apicatalog.projection.context;
import java.util.Arrays;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.apicatalog.projection.source.SourceType;
public final class ExtractionContext {
final Logger logger = LoggerFactory.getLogger(ExtractionContext.class);
public static final int MAX_OBJECTS = 25;
final SourceType[] types;
final Object[] objects;
int index;
final ContextNamespace namespace;
protected ExtractionContext() {
this.types = new SourceType[MAX_OBJECTS];
this.objects = new Object[MAX_OBJECTS];
this.index = 0;
this.namespace = new ContextNamespace();
}
public static final ExtractionContext newInstance() {
return new ExtractionContext();
}
public ExtractionContext accept(String name, Class objectType, Class componentType) {
final String qualifiedName = Optional.ofNullable(name).map(n -> namespace.getQName(name)).orElse(null);
objects[index] = null;
types[index++] = SourceType.of(qualifiedName, objectType, componentType);
return this;
}
public void set(final String name, final Object object) {
if (index == 0) {
throw new IllegalStateException();
}
final String qualifiedName = Optional.ofNullable(name).map(n -> namespace.getQName(name)).orElse(null);
for (int i=index - 1; i >= 0; i--) {
if (types[i].isInstance(qualifiedName, object)) {
if (logger.isDebugEnabled()) {
logger.debug("Set {}, {}",
Optional.ofNullable(qualifiedName).orElse("n/a"),
object
);
}
objects[i] = object;
return;
}
}
if (logger.isTraceEnabled()) {
logger.trace("Rejected to set {}, qualifier = {}", object.getClass().getSimpleName(), qualifiedName);
}
}
public Optional get(final SourceType sourceType) {
return get(sourceType.getName(), sourceType.getType(), sourceType.getComponentType());
}
public Optional get(final String name, final Class objectType, final Class componentType) {
if (index == 0) {
throw new IllegalStateException();
}
final String qualifiedName = Optional.ofNullable(name).map(n -> namespace.getQName(name)).orElse(null);
for (int i=index - 1; i >= 0; i--) {
if (types[i].isAssignableFrom(qualifiedName, objectType, componentType)) {
return Optional.ofNullable(objects[i]);
}
}
return Optional.empty();
}
public Optional remove(final String name, final Class objectType, final Class componentType) {
if (index == 0) {
throw new IllegalStateException();
}
final String qualifiedName = Optional.ofNullable(name).map(n -> namespace.getQName(name)).orElse(null);
for (int i=index - 1; i >= 0; i--) {
if (types[i].isAssignableFrom(qualifiedName, objectType, componentType)) {
index--;
return Optional.ofNullable(objects[i]);
}
}
return Optional.empty();
}
public int size() {
return index;
}
public boolean isAccepted(SourceType sourceType) {
return isAccepted(sourceType.getName(), sourceType.getType(), sourceType.getComponentType());
}
public boolean isAccepted(String name, Class objectType, Class componentType) {
if (index == 0) {
throw new IllegalStateException();
}
final String qualifiedName = Optional.ofNullable(name).map(n -> namespace.getQName(name)).orElse(null);
for (int i=index - 1; i >= 0; i--) {
if (types[i].isAssignableFrom(qualifiedName, objectType, componentType)) {
return true;
}
}
return false;
}
public SourceType[] getAcceptedTypes() {
return Arrays.copyOf(types, index);
}
public Optional getAssignableType(final SourceType sourceType) {
return getAssignableType(sourceType.getName(), sourceType.getType(), sourceType.getComponentType());
}
public Optional getAssignableType(String qualifier, Class objectType, Class componentType) {
if (index == 0) {
throw new IllegalStateException();
}
final String qualifiedName = Optional.ofNullable(qualifier).map(n -> namespace.getQName(qualifier)).orElse(null);
for (int i=index - 1; i >= 0; i--) {
if (types[i].isAssignableFrom(qualifiedName, objectType, componentType)) {
return Optional.ofNullable(types[i].getType());
}
}
return Optional.empty();
}
public void addNamespace(String name) {
this.namespace.push(name);
}
public String removeLastNamespace() {
return this.namespace.pop();
}
} | java | 17 | 0.695279 | 115 | 25.993902 | 164 | starcoderdata |
#include
#include
#include "Util.h"
#include
using namespace std;
list Util::splitString(string s, string delimiter){
list result;
size_t pos = 0;
string token;
while((pos = s.find(delimiter)) != string::npos){
token = s.substr(0, pos);
result.push_back(token);
s.erase(0, pos+delimiter.length());
}
if(s.size()>0){
result.push_back(s);
}
return result;
} | c++ | 11 | 0.663484 | 59 | 17.217391 | 23 | starcoderdata |
// JavaScript source code
_ = require('underscore');
var tally = {
printPoll: function (data) {
// the string that separates poll items when printing
separator = ' \n';
// build the output
pollResults = 'Current Brown Bag Poll: ';
pollResults += '\nResults: \n';
_.each(data.answers, function (answer) {
formattedAnswerName = answer.answerName.capitalizeFirstLetter();
pollResults += formattedAnswerName + ': ' + answer.votes.length + separator;
});
// Remove the last separator (newline) to avoid extra empty line
lastIndexOfSeparator = pollResults.lastIndexOf(separator);
if (lastIndexOfSeparator > separator.length) {
pollResults = pollResults.substring(0, lastIndexOfSeparator);
}
return pollResults;
}
};
module.exports = tally; | javascript | 18 | 0.623864 | 88 | 29.37931 | 29 | starcoderdata |
def __call__(self):
if self.context.portal_type == 'AnalysisRequest':
self._ars = [self.context]
elif self.context.portal_type == 'AnalysisRequestsFolder' \
and self.request.get('items',''):
uids = self.request.get('items').split(',')
uc = getToolByName(self.context, 'uid_catalog')
self._ars = [obj.getObject() for obj in uc(UID=uids)]
else:
#Do nothing
self.destination_url = self.request.get_header("referer",
self.context.absolute_url())
# Group ARs by client
groups = {}
for ar in self._ars:
idclient = ar.aq_parent.id
if idclient not in groups:
groups[idclient] = [ar]
else:
groups[idclient].append(ar)
self._arsbyclient = [group for group in groups.values()]
# Do publish?
if self.request.form.get('publish', '0') == '1':
self.publishFromPOST()
else:
return self.template() | python | 13 | 0.518173 | 69 | 37.357143 | 28 | inline |
package storage
import (
"context"
)
// ErrNotFound is returned when an item requested is not found
type ErrNotFound struct {
Message string
}
func (e ErrNotFound) Error() string {
return e.Message
}
// Provider represents a provider
type Provider struct {
Type string `json:"type,omitempty"`
Label string `json:"label,omitempty"`
FeedURL string `json:"feedURL,omitempty"`
PollFrequencySeconds int `json:"pollFrequencySeconds,omitempty"`
}
// ProviderRepository defines functionality to CRUD providers in underlying store
type ProviderRepository interface {
InsertProviders(ctx context.Context, p []Provider) ([]string, error)
GetProviders(ctx context.Context, offset, count int) ([]Provider, error)
GetProvider(ctx context.Context, providerID string) (Provider, error)
} | go | 8 | 0.732869 | 81 | 27.7 | 30 | starcoderdata |
public virtual TEditViewModel CreateEditViewModel(T entity) {
// This calls the basic creation method so that any other information, such as dropdown
// list data or otherwise may be bound to the view model
var viewModel = CreateEditViewModel();
// Set the entity property to the "data filled" entity provided
viewModel.GetType().GetProperty(typeof(T).Name).SetValue(viewModel, entity, null);
return viewModel;
} | c# | 12 | 0.642998 | 100 | 49.8 | 10 | inline |
public void InOrderIterative(BST tree)
{
Stack<BST> s = new Stack<BST>();
BST curr = tree;
// traverse the tree
while (curr != null || s.Count > 0)
{
/* Reach the left most Node of the
curr Node */
while (curr != null)
{
/* place pointer to a tree node on
the stack before traversing
the node's left subtree */
s.Push(curr);
curr = curr.left;
}
/* Current must be NULL at this point */
curr = s.Pop();
Console.WriteLine(curr.value + " ");
/* we have visited the node and its
left subtree. Now, it's right
subtree's turn */
curr = curr.right;
}
} | c# | 12 | 0.385744 | 56 | 29.806452 | 31 | inline |
import http from 'http';
import serverHandlers from './config/server/serverHandlers';
import server from './config/server';
const Server = http.createServer(server);
/**
* Binds and listens for connections on the specified host
*/
Server.listen(server.get('port'));
/**
* Server Events
*/
Server.on('error', (error) => serverHandlers.onError(error, server.get('port')));
Server.on('listening', serverHandlers.onListening.bind(Server));
Server.on('close', () => serverHandlers.onClose()); | javascript | 7 | 0.717647 | 81 | 27.333333 | 18 | starcoderdata |
unsigned short getLetterByteSize(const unsigned char* const pPosition)
{
//Look here https://en.wikipedia.org/wiki/UTF-8
if ((*pPosition) >= 252)
{
//we need read 6 byte
return 6;
}
else if ((*pPosition) >= 248)
{
//we need read 5 byte
return 5;
}
else if ((*pPosition) >= 240)
{
//we need read 4 byte
return 4;
}
else if ((*pPosition) >= 224)
{
//we need read 3 byte
return 3;
}
else if ((*pPosition) >= 192)
{
//we need read 2 byte
return 2;
}
else if ((*pPosition) <= 127)
{
return 1;
}
else
{
return 0;
}
} | c++ | 18 | 0.589928 | 70 | 14.054054 | 37 | inline |
function smartProperty(obj, name) { // get a camel-cased/namespaced property of an object
if (obj[name] !== undefined) {
return obj[name];
}
var parts = name.split(/(?=[A-Z])/),
i=parts.length-1, res;
for (; i>=0; i--) {
res = obj[parts[i].toLowerCase()];
if (res !== undefined) {
return res;
}
}
return obj[''];
} | javascript | 11 | 0.591592 | 89 | 22.857143 | 14 | inline |
<?php
/**
* styles generator
* by fliegwerk
* (c) 2020. MIT License
*/
require_once "utility.php";
/**
* Build a valid cascading style sheet to colorize sections and navigation items.
*
* @param string $classname the id or class name of the section
* @param string $color the color of the section
* @return string a valid cascading style sheet
*/
function build_color_styles(string $classname, string $color): string {
return <<<"EOT"
.$classname::after,
#$classname li::after {
background-color: $color;
}
#$classname header {
border-color: $color;
}
EOT;
}
/**
* Renders an image or placeholder if the image not in the path list.
*
* @param array $images
* @param string $color
* @param string $id
* @param string $name
* @return string
*/
function render_image(array $images, string $color, string $id, string $name): string {
$filenames = array_map('get_filename', $images);
$key = array_search($id, $filenames);
if ($key === false) {
// render svg placeholder
$initials = get_initials($name);
return <<<"EOT"
<svg viewBox="0 0 300 300">
<rect x="0" y="0" width="300" height="300" style="fill: $color;"/>
<text text-anchor="middle" x="150" y="210">$initials
EOT;
} else {
$path = $images[$key];
// render img tag
return "<img src=\"$path\" alt=\"$name logo\">";
}
} | php | 11 | 0.65538 | 87 | 22.315789 | 57 | starcoderdata |
@Test
public void startInstanceWithParams() {
//1、获取processEngine对象
ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
//2、获取runtimeService对象
RuntimeService runtimeService = defaultProcessEngine.getRuntimeService();
//3、创建流程实例,也就是开启一个流程。通过流程key
// Holiday holiday = new Holiday();
// holiday.setNum(2f);
Map<String, Object> params = new HashMap<>();
// params.put("user1", "zhangsan");
// params.put("holiday", holiday);
//也可以刚启动的时候设置完所有的参数,也可以完成一个任务并且设置下一个任务的参数
// params.put("user2", "lisi");
// params.put("user3", "wangwu");
ProcessInstance myProcess_1 = runtimeService.startProcessInstanceByKey("bingxing", params);
//4、输出信息
System.out.println(myProcess_1.getDeploymentId());
System.out.println(myProcess_1.getProcessDefinitionId());
System.out.println(myProcess_1.getProcessDefinitionKey());
System.out.println(myProcess_1.getProcessInstanceId());
System.out.println(myProcess_1.getId());
System.out.println(myProcess_1.getActivityId());
} | java | 8 | 0.664917 | 99 | 46.666667 | 24 | inline |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Author:
Date Updated: 2/18/2020
Purpose: This includes a few functions to match places based on geographic
distance using latitude and longitude coordinates. These functions use
numpy, pandas, scipy.spatial.distance.cdist, and time.time.
'''
import numpy as np
import pandas as pd
from scipy.spatial.distance import cdist
from time import time
def GetNClosest(data1, data2, indecies, latvars, lonvars, nummatches=10,
chunksize=1000):
'''
Description
-----------
This function takes two data frames and returns a crosswalk between the
indecies from 'data1' and the indecies for the specified number of closest
matches from 'data2', in order of distance, least to most.
Parameters
----------
data1 - Pandas DataFrame - The first DataFrame.
data2 - Pandas DataFrame - The second DataFrame.
indecies - list - A list with two entries specifying the columns of the
index variables for each DataFrame, which should be unique for
both DataFrames: ['index for data1', 'index for data2']
latvars - list - A list with two entries specifying the columns of the
latitude variables for each DataFrame, in order.
lonvars - list - A list with two entries specifying the columns of the
longitude variables for each DataFrame, in order.
nummatches - int - The desired number of matches from 'data2' for each
index in 'data1'.
chunksize - int - The number of rows to do at a time from 'data1'. This
is specified because if you have many rows in both data sets,
the process can be extremely memory intensive. If you have the
necessary computing power, set chunksize to be the length of
'data1'.
Returns
-------
A Pandas DataFrame with two columns, the first being the indecies from
'data1' and the second being a list with the specified number of indecies
for the closest places from 'data2'.
'''
# Start the timer.
start_time = time()
# Copy each data set.
df1 = data1.copy().reset_index(drop=True)
df2 = data2.copy().reset_index(drop=True)
# Loop over increments of chunksize.
for x in range(0,len(df1),chunksize):
# Get the argument numbers for the closest matches.
args = list(cdist(np.array(list(zip(df1.loc[x:x+chunksize, latvars[0]],df1.loc[x:x+chunksize, lonvars[0]]))),
np.array(list(zip(df2[latvars[1]],df2[lonvars[1]])))).argpartition(
range(nummatches),axis=1)[:,0:nummatches])
# Make a DataFrame for the return values.
# Get the correct indecies from the original DataFrame 2.
if nummatches == 1:
df1.loc[x:x+chunksize, '__matches__'] = args
df1.loc[x:x+chunksize, '__matches__'] = df1.loc[x:x+chunksize, '__matches__'].apply(lambda x: df2[indecies[1]].loc[int(x)])
else:
df1.loc[x:x+chunksize, '__matches__'] = pd.Series(args)
df1.loc[x:x+chunksize, '__matches__'] = df1.loc[x:x+chunksize, '__matches__'].apply(lambda x: [df2[indecies[1]].loc[y] for y in x])
# Print the time.
now = time()
print('Progress: ', round((x/len(df1))*100,2), '%')
print('Time Remaining:', round((((now-start_time)/(x+chunksize)) * (len(df1) - min(x + chunksize, len(df1))))/3600,3), 'Hours')
print(' ')
# Keep only the two index columns and return.
if nummatches == 1:
df1['__matches__'] = df1['__matches__'].astype(np.int64)
else:
df1['__matches__'] = df1['__matches__'].apply(lambda x: [int(y) for y in x])
# Drop if missing lat or lon.
df1 = df1.loc[(df1[latvars[0]].notnull()) & (df1[lonvars[0]].notnull())]
df1 = df1[[indecies[0], '__matches__']]
return df1 | python | 23 | 0.612687 | 143 | 38.029126 | 103 | starcoderdata |
<?php
namespace Omikron\FactFinder\Oxid\Export\Stream;
interface StreamInterface
{
/**
* @param array $entity
*/
public function addEntity(array $entity): void;
} | php | 8 | 0.709957 | 51 | 18.25 | 12 | starcoderdata |
import { graphql } from 'gatsby'
import React from 'react'
import loadable from '@loadable/component'
const Layout = loadable(() => import('../components/Layout'))
const ContactUs = loadable(() => import('../components/services/ContactUs'))
const Header = loadable(() => import('../components/services/Header'))
const InEngineAnimation = loadable(() => import('../components/services/InEngineAnimation'))
const Performance = loadable(() => import('../components/services/Performance'))
const PhotoReal = loadable(() => import('../components/services/PhotoReal'))
const PreRenderedAnimation = loadable(() => import('../components/services/PreRenderedAnimation'))
const RealTime = loadable(() => import('../components/services/RealTime'))
const ServiceIndex = ({data: {page}}) => {
return (
<Layout meta={page.frontmatter.meta || false}>
<Header data={page.frontmatter}/>
<PhotoReal data={page.frontmatter.photorealCg}/>
<InEngineAnimation data={page.frontmatter.inEngineAnimation}/>
<PreRenderedAnimation data={page.frontmatter.preRenderedAnimation}/>
<Performance data={page.frontmatter.performaceCapture}/>
<RealTime data={page.frontmatter.realTimeAnimation}/>
<ContactUs description={page.frontmatter.contactUsDescription} image={page.frontmatter.contactUsImage}/>
)
}
export default ServiceIndex
export const pageQuery = graphql`
query ServiceIndex($id: String !) {
page: markdownRemark(id: {eq: $id}) {
...Meta
html
id
frontmatter {
title
subtitle
description
featuredImages {
image
alt
title
}
photorealCg {
title
description
image
}
preRenderedAnimation {
title
description
image
}
inEngineAnimation {
title
description
image
}
performaceCapture {
title
description
image {
image
alt
title
}
}
realTimeAnimation {
title
description
desktopImage
mobileImage
}
contactUsDescription
contactUsImage
}
}
}
` | javascript | 14 | 0.500879 | 120 | 34.111111 | 81 | starcoderdata |
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/ezh/jenkins-consul-friends/pkg/consul"
"github.com/hashicorp/consul/api"
)
func get(consul *consul.Client) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
for key := range r.URL.Query() {
kv, _, err := consul.KV().Get(key, nil)
if err != nil {
panic(err)
}
if kv == nil {
log.Println(key, "not found")
fmt.Fprintf(w, "%s not found\n", key)
} else {
log.Println("get", key, "=", string(kv.Value))
fmt.Fprintf(w, "%s\n", string(kv.Value))
}
}
}
}
func set(consul *consul.Client) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
values := r.URL.Query()
for key := range values {
kv := &api.KVPair{
Key: key,
Value: []byte(values[key][0]),
}
_, err := consul.KV().Put(kv, nil)
if err != nil {
panic(err)
}
log.Println("set", key, "=", values[key][0])
}
fmt.Fprintf(w, "Success\n")
}
}
func ping(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "pong\n")
}
func main() {
consul := consul.New("jenkins-consul-friends", time.Second*5)
consul.ServiceRegister()
defer consul.ServiceDeregister()
go consul.ServiceHealthLoop()
http.HandleFunc("/get-value", get(consul))
http.HandleFunc("/set-value", set(consul))
http.HandleFunc("/ping", ping)
log.Fatal(http.ListenAndServe(":9003", nil))
} | go | 19 | 0.635588 | 78 | 23.174603 | 63 | starcoderdata |
protected override void OnInternalClosed(IAmqpObject sender, Error error)
{
Tracer.InfoFormat("Closed subscription {0} state {1}", this.Info.SubscriptionName, this.State);
if (error != null && !this.IsOpening && !this.IsClosing)
{
if (this.remoteSource == null)
{
// ignore detach request
if (error != null)
{
Tracer.DebugFormat("Received detach request on invalid subscription {0}. Cause for detach : {1}", this.Info.SubscriptionName, error);
}
}
else
{
Tracer.WarnFormat("Subscription {0} on connection {1} has been destroyed. Cause {2}", this.Info.SubscriptionName, this.Info.ClientId, error);
}
}
base.OnInternalClosed(sender, error);
this.OnResponse();
} | c# | 17 | 0.505688 | 161 | 45.095238 | 21 | inline |
<?php
/**
* PositiveIntegerTest file
*
* @category Tests
* @package Railway Validations
* @author
* @copyright 2016 @MartinAlsinet
* @license MIT License
* @version Release: 0.1.0
* @link http://github.com/malsinet/railway-validations
*/
namespace github\malsinet\Railway\Validations\Tests;
use PHPUnit\Framework\TestCase;
use github\malsinet\Railway\Validations as V;
/**
* PositiveIntegerTest class
*
* Test should throw an exception if the $field is not a positive integer
*
* @category Tests
* @package Railway Validations
* @author
* @copyright 2016 @MartinAlsinet
* @license MIT License
* @version Release: 0.1.0
* @link http://github.com/malsinet/railway-validations
*/
class PositiveIntegerTest extends TestCase
{
public function testEmptyValueThrowsException()
{
$field = new V\PositiveInteger(
new V\AlwaysValid(
new V\DefaultRequest(array())
),
"number"
);
$this->expectException(V\ValidationException::class);
$field->validate();
}
public function testNegativeIntegerThrowsException()
{
$value = -33;
$field = new V\PositiveInteger(
new V\AlwaysValid(
new V\DefaultRequest(array("number" => $value))
),
"number"
);
$this->expectException(V\ValidationException::class);
$field->validate();
}
public function testNegativeStringThrowsException()
{
$value = "-44";
$field = new V\PositiveInteger(
new V\AlwaysValid(
new V\DefaultRequest(array("number" => $value))
),
"number"
);
$this->expectException(V\ValidationException::class);
$field->validate();
}
public function testNegativeFloatStringThrowsException()
{
$value = "-4.3";
$field = new V\PositiveInteger(
new V\AlwaysValid(
new V\DefaultRequest(array("number" => $value))
),
"number"
);
$this->expectException(V\ValidationException::class);
$field->validate();
}
public function testNegativeFloatThrowsException()
{
$value = -4.3;
$field = new V\PositiveInteger(
new V\AlwaysValid(
new V\DefaultRequest(array("number" => $value))
),
"number"
);
$this->expectException(V\ValidationException::class);
$field->validate();
}
public function testLettersThrowsException()
{
$value = "4.ewewe222";
$field = new V\PositiveInteger(
new V\AlwaysValid(
new V\DefaultRequest(array("number" => $value))
),
"number"
);
$this->expectException(V\ValidationException::class);
$field->validate();
}
public function testValidIntegerReturnsTrue()
{
$value = 400;
$field = new V\PositiveInteger(
new V\AlwaysValid(
new V\DefaultRequest(array("number" => $value))
),
"number"
);
$this->assertTrue(
$field->validate(),
"Validating a positive number [$value] should return true"
);
}
public function testValidStringReturnsTrue()
{
$value = "400";
$field = new V\PositiveInteger(
new V\AlwaysValid(
new V\DefaultRequest(array("number" => $value))
),
"number"
);
$this->assertTrue(
$field->validate(),
"Validating a positive number [$value] should return true"
);
}
} | php | 19 | 0.55858 | 73 | 24.848276 | 145 | starcoderdata |
[TestMethod]
public void TriggerTestHostLaunchedHandlerShouldStartProcDumpUtilityForFullDumpIfFullDumpEnabledCaseSensitivity()
{
var dumpConfig = this.GetDumpConfigurationElement();
var dumpTypeAttribute = dumpConfig.OwnerDocument.CreateAttribute("DuMpType");
dumpTypeAttribute.Value = "FuLl";
dumpConfig[BlameDataCollector.Constants.DumpModeKey].Attributes.Append(dumpTypeAttribute);
var dumpOnExitAttribute = dumpConfig.OwnerDocument.CreateAttribute("CollEctAlways");
dumpOnExitAttribute.Value = "FaLSe";
dumpConfig[BlameDataCollector.Constants.DumpModeKey].Attributes.Append(dumpOnExitAttribute);
// Initializing Blame Data Collector
this.blameDataCollector.Initialize(
dumpConfig,
this.mockDataColectionEvents.Object,
this.mockDataCollectionSink.Object,
this.mockLogger.Object,
this.context);
// Raise TestHostLaunched
this.mockDataColectionEvents.Raise(x => x.TestHostLaunched += null, new TestHostLaunchedEventArgs(this.dataCollectionContext, 1234));
// Verify StartProcessDumpCall
this.mockProcessDumpUtility.Verify(x => x.StartTriggerBasedProcessDump(1234, It.IsAny<string>(), It.IsAny<string>(), true));
} | c# | 16 | 0.684822 | 145 | 54.12 | 25 | inline |
#pragma once
//Borders
int borders[134] = {
140, 925,
172, 898,
170, 885,
59, 823,
59, 685,
121, 560,
89, 510,
68, 469,
51, 416,
39, 363,
31, 312,
24, 220,
28, 210,
40, 205,
49, 210,
69, 268,
127, 241,
117, 210,
118, 194,
123, 183,
157, 153,
191, 131,
227, 117,
265, 111,
304, 114,
343, 122,
369, 136,
390, 152,
413, 171,
431, 192,
444, 207,
456, 226,
462, 244,
466, 265,
466, 834,
442, 833,
444, 298,
441, 263,
425, 224,
411, 201,
395, 184,
375, 168,
355, 155,
331, 141,
318, 162,
345, 184,
365, 204,
380, 227,
387, 246,
389, 265,
432, 264,
436, 346,
405, 364,
405, 393,
435, 414,
435, 534,
399, 556,
399, 632,
417, 652,
417, 828,
314, 882,
314, 900,
371, 924,
512, 924,
511, 75,
0, 75,
0, 926
};
int leftBumper[10] = {
111, 716,
120, 716,
160, 805,
151, 810,
112, 786
};
int rightBumper[10] = {
365, 785,
365, 717,
359, 716,
318, 804,
324, 808
};
int limitRight[12] = {
399, 799,
399, 711,
392, 711,
392, 794,
319, 835,
323, 842
};
int limitLeft[12] = {
78, 799,
78, 711,
85, 711,
85, 795,
160, 835,
155, 841
}; | c | 4 | 0.542831 | 23 | 9.364486 | 107 | starcoderdata |
using System;
using MoonSharp.Interpreter;
namespace DSTEd.Core.Klei.Data {
public class OptionsEntry {
private string description;
private string hover;
private object data;
public OptionsEntry(TablePair data) {
Console.WriteLine(data.ToString());
this.description = "";
this.hover = "";
this.data = (object) "";
}
public string GetDescription() {
return this.description;
}
public string GetHover() {
return this.hover;
}
public object GetData() {
return this.data;
}
}
} | c# | 13 | 0.539394 | 47 | 21.758621 | 29 | starcoderdata |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using ERY.EMath;
namespace TightBindingSuite
{
class AgrWriter: IDisposable
{
StreamWriter file;
public AgrWriter(string filename)
{
file = new StreamWriter(filename);
}
public void Dispose()
{
file.Dispose();
}
[Obsolete]
public void WriteGraceDottedSetStyle(int index)
{
WriteGraceSetLineStyle(index, 2);
}
public void WriteGraceSetLineStyle(int index, int linestyle)
{
file.WriteLine("@ s{0} line linestyle {1}", index, linestyle);
}
public void WriteGraceLegend(int dataset, string text)
{
file.WriteLine("@ s{0} legend \"{1}\"", dataset, text);
}
public void WriteGraceSetLineColor(int start, params int[] linecolor)
{
for (int i = 0; i < linecolor.Length; i++)
{
file.WriteLine("@ s{0} line linewidth 2.0", i + start);
file.WriteLine("@ s{0} line color {1}", i + start, linecolor[i]);
}
}
public void WriteGraceSetSymbol(int set, int symbol)
{
file.WriteLine("@ s{0} symbol {1}", set, symbol);
}
public void WriteGraceSetSymbolColor(int set, int symbolcolor)
{
file.WriteLine("@ s{0} symbol color {1}", set, symbolcolor);
file.WriteLine("@ s{0} symbol fill color {1}", set, symbolcolor);
}
public void WriteGraceSetSymbolFill(int set, int symbolfill)
{
file.WriteLine("@ s{0} symbol fill pattern {1}", set, symbolfill);
}
public void WriteGraceHeader(KptList kpath)
{
file.WriteLine("@with g0");
var pairs = kpath.Kpts.Select(
(kpt, index) => new Pair<int, KPoint>(index, kpt)).ToArray();
var pts = (
from val in pairs
where string.IsNullOrEmpty(val.Second.Name) == false
select val
).ToArray();
file.WriteLine("@ xaxis tick spec type both");
file.WriteLine("@ xaxis tick spec {0}", pts.Length);
for (int i = 0; i < pts.Length; i++)
{
string label = pts[i].Second.Name;
if (label.StartsWith("G"))
label = @"\xG\f{}" + label.Substring(1);
label = label.Replace("$_", @"\s");
label = label.Replace("$^", @"\S");
label = label.Replace("$.", @"\N");
file.WriteLine("@ xaxis tick major {0}, {1}", i, pts[i].First);
file.WriteLine("@ xaxis ticklabel {0}, \"{1}\"", i, label);
}
}
public void WriteGraceBaseline(int length)
{
file.WriteLine("@type xy");
file.WriteLine("0 0");
file.WriteLine("{0} 0", length);
file.WriteLine("&");
}
public void WriteGraceDataset(int length, Func<int, Pair data)
{
file.WriteLine("@type xy");
for (int i = 0; i < length; i++)
{
var val = data(i);
file.WriteLine("{0} {1}", val.First, val.Second);
}
file.WriteLine("&");
}
public void WriteGraceDataset(string type, int length, Func<int, Triplet<double, double,double>> data)
{
file.WriteLine("@type {0}", type);
for (int i = 0; i < length; i++)
{
var val = data(i);
if (val == null)
continue;
file.WriteLine("{0} {1} {2}", val.First, val.Second, val.Third);
}
file.WriteLine("&");
}
}
} | c# | 22 | 0.58699 | 104 | 23.661417 | 127 | starcoderdata |
//
// T03_shu-zu-zhong-zhong-fu-de-shu-zi-lcof.c
// algorithm
//
// Created by Ankui on 4/17/21.
// Copyright © 2021 Ankui. All rights reserved.
//
// https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/
#include "T03_shu-zu-zhong-zhong-fu-de-shu-zi-lcof.h"
#include "algorithm-common.h"
int findRepeatNumber(int* nums, int numsSize) {
int list[numsSize];
memset(list, 0, sizeof(list));
// [2, 3, 1, 0, 2, 5, 3]
for (int i = 0; i < numsSize; i++) {
list[nums[i]]++;
}
// [1, 1, 2, 2, 0, 1, 0]
for (int i = 0; i < numsSize; i++) {
if (list[i] >= 2) {
return i;
}
}
return -1;
}
int t03cmp(const void* a, const void* b) {
return *(int*)a - *(int*)b;
}
int findRepeatNumber1(int* nums, int numsSize) {
qsort(nums, numsSize, sizeof(int), t03cmp);
for (int i = 0; i < numsSize; i++) {
if (nums[i + 1] == nums[i]) {
return nums[i];
}
}
return -1;
} | c | 10 | 0.545543 | 73 | 21.434783 | 46 | starcoderdata |
package mediator;
/**
* @ClassName Mediator
* @Description TODO
* @Author Wangxianglu
* @Date 2019/5/17 11:25
* @Version 1.0
**/
public interface Mediator {
void createMediator();
void walkAll();
} | java | 5 | 0.651163 | 27 | 13.333333 | 15 | starcoderdata |
import React, {Component} from 'react'
import {compose} from 'redux'
import {connect} from 'react-redux'
import {Link} from 'react-router-dom'
class Stats extends Component {
componentDidMount() {
document.querySelector('.appContent').scrollTo(0, 0)
}
render() {
const allTimeStats = this.props.year === 'all'
return (
? 'Tilastot' : `Tilastot ${this.props.year}`}
<Link to="/stats/hi-scores">
→
<Link to="/stats/latest-findings">
havainnot →
)
}
}
export default compose(
connect((state) => ({
year: state.year
}))
)(Stats) | javascript | 15 | 0.587193 | 76 | 21.9375 | 32 | starcoderdata |
<?php
namespace keygenqt\amazonSes;
use \yii\base\Exception;
use yii\base\Widget;
class AmazonSes extends Widget
{
const AWS_US_EAST_1 = 'email.us-east-1.amazonaws.com';
const AWS_US_WEST_2 = 'email.us-west-2.amazonaws.com';
const AWS_EU_WEST1 = 'email.eu-west-1.amazonaws.com';
public $access;
public $secret;
public $email;
public $host = self::AWS_EU_WEST1;
/** @var \SimpleEmailService */
private $ses;
public function init()
{
if (!$this->access || !$this->secret) {
throw new Exception("Access and secret required!");
}
$this->ses = new \SimpleEmailService($this->access, $this->secret, $this->host);
parent::init();
}
public function send(array $emails, $subject, $body)
{
$m = new \SimpleEmailServiceMessage();
$m->setFrom($this->email);
$m->addTo($emails);
$m->setSubject($subject);
$m->setMessageFromString('', $body);
return $this->ses->sendEmail($m);
}
} | php | 13 | 0.601301 | 88 | 24.046512 | 43 | starcoderdata |
@Override
protected void onPause() {
// TODO: exercise 7c - unregister the broadcast receiver
//unregisterReceiver(startedServiceBroadcastReceiver);
super.onPause();
Log.d(Constants.TAG, "onPause() method was invoked");
} | java | 7 | 0.644195 | 64 | 36.428571 | 7 | inline |
#ifndef _BINARYSEP_H
#define _BINARYSEP_H
#include
#include
#include
#include
#include "intrusive_list.h"
using namespace std;
/**
* 将变量内容分开保存
*/
template <typename T>
class BinarySep {
public:
BinarySep() {}
BinarySep(const T *t, uint32_t heap_size = 0);
BinarySep(const T &t, uint32_t heap_size = 0);
BinarySep(const BinarySep &cp);
~BinarySep();
BinarySep& operator=(const BinarySep &cp);
void hide(const T &t, uint32_t heap_size = 0);
T get();
private:
void init_hide_list();
bool hide_list_empty();
void check_heap_content(uint32_t heap_size);
bool is_heap_size() {return false;}
char* get_content_ptr() {return (char *)&origi;}
#define SEP_UNIT 3 //设置按几个字节来分片
#define PTR_SIZE (sizeof(unsigned long))
private:
uint32_t size;
static const uint32_t padding_size = PTR_SIZE - (SEP_UNIT % PTR_SIZE);
list_head_t hide_head;
char *heap_origi;
T origi;
typedef struct unit_list {
struct list_head list;
char hide[SEP_UNIT];
char padding[padding_size]; //用随机内容填充多余的空间造成混淆
}unit_list_t;
};
template<> bool BinarySep<char *>::is_heap_size() {return true;}
template<> bool BinarySep<const char *>::is_heap_size() {return true;}
template<> char *BinarySep<char *>::get_content_ptr() {return heap_origi;}
template<> char *BinarySep<const char *>::get_content_ptr() {return heap_origi;}
template <typename T>
BinarySep T *t, uint32_t heap_size)
{
size = is_heap_size() ? heap_size : sizeof(T);
heap_origi = NULL;
init_hide_list();
hide(*t, heap_size);
}
template <typename T>
BinarySep T &t, uint32_t heap_size)
{
size = is_heap_size() ? heap_size : sizeof(T);
heap_origi = NULL;
init_hide_list();
hide(t, heap_size);
}
template <typename T>
BinarySep BinarySep &cp)
{
size = cp.size;
heap_origi = NULL;
init_hide_list();
hide(cp.origi, cp.size);
}
template <typename T>
BinarySep
{
list_head_t *l, *p;
list_for_each_safe(l, p, &hide_head) {
unit_list_t *unit = list_entry(l, unit_list_t, list);
if (!unit) continue;
free(unit);
}
if (heap_origi) {
free(heap_origi);
}
}
template <typename T>
BinarySep BinarySep BinarySep &cp)
{
if (this == &cp) {
return *this;
}
size = cp.size;
if (hide_list_empty()) {
init_hide_list();
}
hide(cp.origi, cp.size);
return *this;
}
template <typename T>
void BinarySep T &t, uint32_t heap_size)
{
origi = t;
check_heap_content(heap_size);
list_head_t *l = hide_head.next;
char *c = get_content_ptr();
for (uint32_t i = 0; i < size; l = l->next) {
if (l == &hide_head) break;
unit_list_t *field = list_entry(l, unit_list_t, list);
for (uint32_t j = 0; (i < size && j < SEP_UNIT); i++, j++, c++) {
field->hide[j] = *c ^ *(char *)&hide_head;
}
}
}
template <typename T>
T BinarySep
{
list_head_t *l = hide_head.next;
char *c = get_content_ptr();
for (uint32_t i = 0; i < size; l = l->next) {
if (l == &hide_head) break;
unit_list_t *field = list_entry(l, unit_list_t, list);
for (uint32_t j = 0; (i < size && j < SEP_UNIT); i++, j++, c++) {
if (*c != (field->hide[j] ^ *(char *)&hide_head)) {
//这里处理内存被修改了
}
}
}
return heap_origi ? *(T *)&heap_origi : origi;
}
template <typename T>
void BinarySep
{
INIT_LIST_HEAD(&hide_head);
srand(*(uint32_t *)&hide_head);
for (uint32_t i = 0; i < size; i += SEP_UNIT) {
unit_list_t *unit = (unit_list_t *)calloc(1, (sizeof(unit_list_t)));
for (uint32_t j = 0; j < padding_size; j++) {
unit->padding[j] = rand();
}
list_add(&unit->list, &hide_head);
}
}
template <typename T>
bool BinarySep
{
if (list_empty(&hide_head)) return true;
list_head_t *l = hide_head.next;
for (uint32_t i = 0; i < size; i += SEP_UNIT, l = l->next) {
unit_list_t *field = list_entry(l, unit_list_t, list);
if (!field) return true;
}
return false;
}
template <typename T>
void BinarySep heap_size)
{
heap_origi = NULL;
}
template <>
void BinarySep<char *>::check_heap_content(uint32_t heap_size)
{
if (heap_origi && heap_size > size) { //已经存在数据,现有的内存空间不足
free(heap_origi);
heap_origi = NULL;
//TODO 扩大list
}
if (!heap_origi) {
heap_origi = (char *)calloc(1, sizeof(char) * heap_size + 1);
}
memcpy(heap_origi, ((char *)origi), heap_size);
heap_origi[heap_size] = '\0';
size = heap_size;
}
template <>
void BinarySep<const char *>::check_heap_content(uint32_t heap_size)
{
if (heap_origi && heap_size > size) { //已经存在数据,现有的内存空间不足
free(heap_origi);
heap_origi = NULL;
//TODO 扩大list
}
if (!heap_origi) {
heap_origi = (char *)calloc(1, sizeof(char) * heap_size + 1);
}
memcpy(heap_origi, ((char *)origi), heap_size);
heap_origi[heap_size] = '\0';
size = heap_size;
}
#endif | c | 15 | 0.630006 | 80 | 20.202586 | 232 | starcoderdata |
#pragma once
#include "fluid_force.hpp"
namespace sph
{
namespace disph
{
class FluidForce : public sph::FluidForce {
real m_gamma;
public:
void initialize(std::shared_ptr param) override;
void calculation(std::shared_ptr sim) override;
};
}
} | c++ | 15 | 0.743662 | 68 | 17.736842 | 19 | starcoderdata |
#!/usr/bin/env python3
import sys
input = sys.stdin.readline
def S():
return input().rstrip()
def I():
return int(input())
def MI():
return map(int, input().split())
s = S()
t = S()
n = len(s)
c = 0
for i in range(n):
if s[i] != t[i]:
c += 1
print(c)
| python | 10 | 0.520979 | 36 | 9.214286 | 28 | codenet |
void ParamListStandard::forceNoUse(ParamActive *active, int4 start, int4 stop) const
{
bool seendefnouse = false;
int4 curgroup = -1;
bool exclusion = false;
bool alldefnouse = false;
for (int4 i = start; i < stop; ++i) {
ParamTrial &curtrial(active->getTrial(i));
if (curtrial.getEntry() == (const ParamEntry *) 0)
continue; // Already marked as not used
int4 grp = curtrial.getEntry()->getGroup();
exclusion = curtrial.getEntry()->isExclusion();
if ((grp <= curgroup) && exclusion) {// If in the same exclusion group
if (!curtrial.isDefinitelyNotUsed()) // A single element that might be used
alldefnouse = false; // means that the whole group might be used
}
else { // First trial in a new group (or next element in same non-exclusion group)
if (alldefnouse) // If all in the last group were defnotused
seendefnouse = true;// then force everything afterword to be defnotused
alldefnouse = curtrial.isDefinitelyNotUsed();
curgroup = grp + curtrial.getEntry()->getGroupSize() - 1;
}
if (seendefnouse)
curtrial.markInactive();
}
} | c++ | 16 | 0.675 | 86 | 40.518519 | 27 | inline |
using AutoMapper;
using DBContext.Models;
using Shared.Models;
using Car = Shared.Models.Car;
using Detail = DBContext.Models.Detail;
using Refill = DBContext.Models.Refill;
namespace Business.AutoMapper
{
public static class AutoMapperConfig
{
public static IMapper Mapper { get; set; }
public static void Initialize()
{
var cfg = new MapperConfiguration(
x =>
{
x.AddProfile
x.AllowNullCollections = true;
x.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
x.DestinationMemberNamingConvention = new PascalCaseNamingConvention();
});
Mapper = cfg.CreateMapper();
}
public class MappingProfile : Profile
{
public MappingProfile()
{
UserMapping();
EventMapping();
CarMapping();
DetailMapping();
ReferenceDataMapping();
}
private void UserMapping()
{
CreateMap<User, UserInfo>();
CreateMap<UserInfo, User>();
}
private void ReferenceDataMapping()
{
CreateMap<TransmissionType, Type>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.TransmissionTypeId));
CreateMap<FuelType, Type>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.FuelTypeId));
CreateMap<Role, Type>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.RoleId));
CreateMap<Right, Type>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.RightId));
}
private void CarMapping()
{
CreateMap<DBContext.Models.Car, Car>();
CreateMap<Car, DBContext.Models.Car>();
}
private void DetailMapping()
{
CreateMap<Shared.Models.Detail, Detail>();
CreateMap<Detail, Shared.Models.Detail>();
}
private void EventMapping()
{
CreateMap<CarEvent, Event>()
.ForMember(dest => dest.UserId, opt => opt.MapFrom(src => src.UserCar.UserId))
.ForMember(dest => dest.CarId, opt => opt.MapFrom(src => src.UserCar.CarId));
CreateMap<ServiceType, Type>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.ServiceTypeId));
CreateMap<EventType, Type>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.EventTypeId));
CreateMap<Event, CarEvent>();
CreateMap<CarEvent, Shared.Models.Refill>()
.IncludeBase<CarEvent, Event>();
CreateMap<CarEvent, EventService>()
.IncludeBase<CarEvent, Event>();
CreateMap<EventService, CarService>();
CreateMap<EventService, CarEvent>();
CreateMap<Shared.Models.Refill, Refill>();
CreateMap<Shared.Models.Refill, CarEvent>();
}
}
}
} | c# | 22 | 0.521424 | 106 | 33.54 | 100 | starcoderdata |
import os
import sys
import time
os.system('clear')
#Welcoming User...
print("Welcome! To The World Of Random & Strong Password")
#Taking A Data
os.system('clear')
length =int(input("How Many Characters Will Be On Your Password ? : "))
#Importing Depen..
os.system('clear')
import random
import string
#Doing Some Process
lower = string.ascii_lowercase
upper = string.ascii_uppercase
num = string.digits
symbols = string.punctuation
all = lower + upper + num + symbols
#Creating And Printing
print("Creating Password")
temp = random.sample(all,length)
print("Ready ?")
time.sleep(5)
password =
print("Your Password Is Ready")
time.sleep(5)
os.system('clear')
print()
print()
print()
print()
print("The AutoGenreated Password For You", password)
print()
print()
print()
print()
time.sleep(10)
os.system('clear')
print("Thanks For Using")
time.sleep(0.10) | python | 8 | 0.734163 | 71 | 19.55814 | 43 | starcoderdata |
//
// Created by cleve on 1/13/2022.
//
#pragma once
#include
#include
#include
#include
#include "display/screen.h"
namespace cchip8::display
{
/// \brief Owner class for display window
class display_window
{
public:
using sdl_window_pointer = std::unique_ptr<SDL_Window, decltype([](SDL_Window* w)
{
SDL_DestroyWindow(w);
})>;
using sdl_texture_pointer = std::unique_ptr<SDL_Texture, decltype([](SDL_Texture* t)
{
SDL_DestroyTexture(t);
})>;
using sdl_renderer_pointer = std::unique_ptr<SDL_Renderer, decltype([](SDL_Renderer* r)
{
SDL_DestroyRenderer(r);
})>;
public:
display_window(uint32_t scale, std::string_view title);
display_window(display_window&& another) noexcept:
window_(std::exchange(another.window_, nullptr))
{
}
~display_window();
display_window(const display_window&) = delete;
display_window& operator=(const display_window&) = delete;
explicit operator bool() const
{
return !(!window_);
}
bool operator!() const
{
return !window_;
}
[[nodiscard]] SDL_Window* get_window() const
{
return window_.get();
}
void update(const screen &scr);
[[nodiscard]] bool process_events(std::span keys);
private:
sdl_window_pointer window_{ nullptr };
sdl_texture_pointer texture_{ nullptr };
sdl_renderer_pointer renderer_{ nullptr };
};
} | c | 11 | 0.684638 | 88 | 17.310811 | 74 | starcoderdata |
<?php
/**
* Created by PhpStorm.
* User: galat
* Date: 01/03/2019
* Time: 16:18
*/
namespace common\models;
use Yii;
class Scopes extends \common\models\db\Scopes
{
const SCOPES_FOR_CUSTOMER = "Scopes_for_customer";
const SCOPES_FOR_USER_ID = "Scopes_for_user_id_";
public static function removeCacheScope($key,$user_id = 1){
Yii::$app->cache->delete($key);
Yii::$app->cache->delete(Scopes::SCOPES_FOR_CUSTOMER);
Yii::$app->cache->delete(Scopes::SCOPES_FOR_USER_ID.$user_id);
}
} | php | 11 | 0.638941 | 70 | 21.083333 | 24 | starcoderdata |
public static Type GetTypeByName(string className)
{
var returnVal = new System.Collections.Generic.List<Type>();
// Check the executing assembly first before anything else
var thisAsm = System.Reflection.Assembly.GetExecutingAssembly();
foreach (var assemblyType in thisAsm.GetTypes()) {
if (assemblyType.Name == className) {
returnVal.Add(assemblyType);
}
}
if (returnVal.Count == 0) {
// Check all of the assemblies
foreach (var a in AppDomain.CurrentDomain.GetAssemblies()) {
Type[] assemblyTypes = a.GetTypes();
for (int j = 0; j < assemblyTypes.Length; j++) {
if (assemblyTypes[j].Name == className) {
returnVal.Add(assemblyTypes[j]);
}
}
}
}
// Look for a full name match
foreach (var t in returnVal) {
if (t.FullName == className) {
return t;
}
}
// Pick the first I guess
if (returnVal.Count == 0) {
return null;
}
return returnVal[0];
} | c# | 19 | 0.62963 | 67 | 25.297297 | 37 | inline |
public Task<Void> submit() {
// create a new summary and save to Firestore if the ID does not exist
// else update the document
if (mId == null) {
add();
}
return db.collection(collectionName).document(mId).set(docData, SetOptions.merge())
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "ActivityTransition successfully written!");
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error writing ActivityTransition", e);
}
});
} | java | 15 | 0.494712 | 91 | 41.6 | 20 | inline |
static inline void checkCameraID(CamSensorSelect_t sensor)
{
u16 devID = CAMDRV_GetDeviceID(sensor);
// system in little endian, while I2C data in big endian
swap_byte((u8 *)&devID, 2);
printk(KERN_INFO "[CAM] DeviceID = 0x%04x\n", devID);
} | c | 9 | 0.716599 | 58 | 26.555556 | 9 | inline |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.xbean.propertyeditor;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class PropertyEditorsTest extends Assert {
@Test
public void testCanConvert() throws Exception {
assertTrue(PropertyEditors.canConvert(Blue.class));
}
/**
* Although an object can be converted via static factory
* or constructor, if there is a propertyeditor present,
* we must use the editor.
*/
@Test
public void propertyEditorIsUsed() throws Exception {
final Blue expected = new Blue("blue");
calls.clear();
final Object actual = PropertyEditors.getValue(Blue.class, "blue");
assertNotNull(actual);
assertEquals(expected, actual);
final List expectedCalls = Arrays.asList(
"BlueEditor.setAsText",
"Blue.constructor");
assertEquals(join(expectedCalls), join(calls));
}
/**
* Constructors beat static factory methods
*/
@Test
public void constructorIsUsed() throws Exception {
final Orange expected = new Orange("orange");
calls.clear();
final Object actual = PropertyEditors.getValue(Orange.class, "orange");
assertNotNull(actual);
assertEquals(expected, actual);
assertEquals("Orange.constructor", join(calls));
}
/**
* With no editor and no public constructor, we default
* to the static factory method.
*/
@Test
public void staticFactoryIsUsed() throws Exception {
final Red expected = new Red("red");
calls.clear();
final Object actual = PropertyEditors.getValue(Red.class, "red");
assertNotNull(actual);
assertEquals(expected, actual);
final List expectedCalls = Arrays.asList(
"Red.valueOf",
"Red.constructor");
assertEquals(join(expectedCalls), join(calls));
}
public static String join(Collection items) {
final StringBuilder sb = new StringBuilder();
for (final Object item : items) {
sb.append(item + "\n");
}
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
private static final List calls = new ArrayList
/**
* The BluePropertyEditor should be found and preferred over
* the constructor or static factory method
*/
public static class Blue {
private final String string;
public Blue(final String string) {
this.string = string;
calls.add("Blue.constructor");
}
public static Blue valueOf(final String string) {
calls.add("Blue.valueOf");
return new Blue(string);
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final Blue blue = (Blue) o;
if (!string.equals(blue.string)) return false;
return true;
}
@Override
public int hashCode() {
return string.hashCode();
}
}
public static class BlueEditor extends java.beans.PropertyEditorSupport {
public void setAsText(String text) throws IllegalArgumentException {
calls.add("BlueEditor.setAsText");
setValue(new Blue(text));
}
}
/**
* The constructor is public so should be preferred over the
* static factory method
*/
public static class Orange {
private final String string;
public Orange(final String string) {
this.string = string;
calls.add("Orange.constructor");
}
public static Orange valueOf(final String string) {
calls.add("Orange.valueOf");
return new Orange(string);
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final Orange Orange = (Orange) o;
if (!string.equals(Orange.string)) return false;
return true;
}
@Override
public int hashCode() {
return string.hashCode();
}
}
/**
* The constructor is private so should not be used
*/
public static class Red {
private final String string;
private Red(final String string) {
this.string = string;
calls.add("Red.constructor");
}
public static Red valueOf(final String string) {
calls.add("Red.valueOf");
return new Red(string);
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final Red Red = (Red) o;
if (!string.equals(Red.string)) return false;
return true;
}
@Override
public int hashCode() {
return string.hashCode();
}
}
} | java | 13 | 0.598402 | 79 | 26.630631 | 222 | starcoderdata |
from django.shortcuts import render, redirect
from django.utils import translation, timezone
from django.http import HttpResponseRedirect
from django.urls import reverse
from .models import Hire, Apply
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# Create your views here.
def hire_list(request):
hires = Hire.objects.filter(end_date__gte=timezone.now())
applys = Apply.objects.all()
paginator = Paginator(hires, 5) # Show 25 contacts per page
page = request.GET.get('page')
message = ""
error = False
if request.session.get('message', False):
message = request.session['message']
del request.session['message']
if request.session.get('error', False):
error = request.session['error']
del request.session['error']
try:
contacts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
contacts = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
contacts = paginator.page(paginator.num_pages)
context = {
'contacts': contacts,
'site': "apply", 'message':message,
'error':error, 'hires':hires,
'apply_len':len(applys)
}
return render(request, 'apply/hire/hire_list.html', context)
def hire_create(request):
if request.method == 'POST':
kind = request.POST.get('kind')
num = request.POST.get('num')
hire_type = request.POST.get('hire_type')
start_date = request.POST.get('start_date')
end_date = request.POST.get('end_date')
content1 = request.POST.get('content1')
content2 = request.POST.get('content2')
hire = Hire(
kind = kind,
num = num,
hire_type = hire_type,
start_date = start_date,
end_date = end_date,
content1 = content1,
content2 = content2
)
hire.save()
return redirect(reverse('hire_list'))
hire = ''
context = {'hire': hire, 'site': "apply"}
return render(request, 'apply/hire/hire_form.html', context)
def hire_view(request, pk):
hire = Hire.objects.get(pk = pk)
context = {'hire': hire, 'site': "apply"}
return render(request, 'apply/hire/hire_view.html', context)
def apply_create(request, pk):
if request.method == 'POST':
e_mail = request.POST.get('e_mail')
if Apply.objects.filter(e_mail = e_mail).exists():
request.session['error'] = False
request.session['message'] = "이미 존재하는 이메일 입니다."
return redirect(reverse('hire_list'))
apply = Apply(
name = request.POST.get('name'),
age = request.POST.get('age'),
phone = request.POST.get('phone'),
e_mail = e_mail,
address = request.POST.get('address'),
college = request.POST.get('college'),
major = request.POST.get('major'),
graduate = request.POST.get('graduate'),
document = request.FILES.get('document'),
hire = Hire.objects.get(pk = pk),
password = request.POST.get('password')
)
apply.save()
return redirect(reverse('hire_list'))
hire = Hire.objects.get(pk = pk)
context = {'hire':hire, 'pk':pk}
return render(request, 'apply/apply_form.html', context)
def apply_update(request):
try:
apply_pk = request.POST.get('apply_pk')
hire_pk = request.POST.get('hire_pk')
apply = Apply.objects.get(pk = apply_pk)
apply.name = request.POST.get('name')
apply.age = request.POST.get('age')
apply.phone = request.POST.get('phone')
apply.address = request.POST.get('address')
apply.college = request.POST.get('college')
apply.major = request.POST.get('major')
apply.graduate = request.POST.get('graduate')
apply.hire = Hire.objects.get(pk = hire_pk)
apply.password = request.POST.get('password')
apply.document.delete()
apply.document = request.FILES.get('document')
apply.save()
except:
request.session['error'] = True
request.session['message'] = "업데이트에 실패하였습니다."
return redirect(reverse('hire_list'))
def check_apply(request):
hires = Hire.objects.filter(end_date__gte=timezone.now())
try:
password =
e_mail = request.POST.get('e_mail')
apply = Apply.objects.get(e_mail = e_mail)
if apply.e_mail == str(e_mail):
if apply.password == password or apply.password == str(password):
message = "해당 신청서를 찾았습니다."
error = False
context = {'message':message, 'error':error, 'hire':apply.hire, 'pk':apply.hire.pk, 'apply':apply}
return render(request, 'apply/apply_form.html', context)
else:
message = "Password가 일치하지 않습니다."
error = True
else:
message = "해당 이메일로 신청 된 신청내역이 없습니다."
error = True
except:
message = "잘못된 요청입니다."
error = True
request.session['error'] = error
request.session['message'] = message
return redirect(reverse('hire_list')) | python | 15 | 0.589292 | 114 | 35.848276 | 145 | starcoderdata |
# from .base import (
# ListOf,
# DictOf,
# DotDict,
# RequiredKeysDotDict,
# AllowedKeysDotDict,
# OrderedKeysDotDict,
# )
#
# from .expectations import (
# Expectation,
# ExpectationSuite,
# ValidationResult,
# ValidationResultSuite,
# )
from .configurations import (
# Config,
ClassConfig
)
class DictDot(object):
def __getitem__(self, item):
if isinstance(item, int):
return list(self.__dict__.keys())[item]
return getattr(self, item)
def __setitem__(self, key, value):
setattr(self, key, value)
def __delitem__(self, key):
delattr(self, key) | python | 14 | 0.592988 | 51 | 18.878788 | 33 | starcoderdata |
#!/usr/bin/env python
# The MIT License (MIT)
# Copyright (c) 2020
# Paper: "Self-Supervised Relational Reasoning for Representation Learning", & NeurIPS 2020
# GitHub: https://github.com/mpatacchiola/self-supervised-relational-reasoning
# Test on different datasets/backbones given a pre-trained checkpoint.
# This is generally used after the linear-evaluation phase.
# Example command:
#
# python test.py --dataset="cifar10" --backbone="conv4" --seed=3 --data_size=128 --gpu=0 --checkpoint="./checkpoint/relationnet/cifar10/relationnet_cifar10_conv4_seed_3_epoch_100_linear_evaluation.tar"
import os
import argparse
parser = argparse.ArgumentParser(description='Test script: loads and test a pre-trained model (e.g. after linear evaluation)')
parser.add_argument('--seed', default=-1, type=int, help='Seed for Numpy and pyTorch. Default: -1 (None)')
parser.add_argument('--dataset', default='cifar10', help='Dataset: cifar10|100, supercifar100, tiny, slim, stl10')
parser.add_argument('--backbone', default='conv4', help='Backbone: conv4, resnet|8|32|34|56')
parser.add_argument('--data_size', default=256, type=int, help='Total number of epochs.')
parser.add_argument('--checkpoint', default='./', help='Address of the checkpoint file')
parser.add_argument('--gpu', default=0, type=int, help='GPU id in case of multiple GPUs')
args = parser.parse_args()
os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu)
import torch
import torch.optim
import torchvision.datasets as dset
import torchvision.transforms as transforms
import argparse
import numpy as np
import random
if(args.seed>=0):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
torch.cuda.manual_seed(args.seed)
torch.cuda.manual_seed_all(args.seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
print("[INFO] Setting SEED: " + str(args.seed))
else:
print("[INFO] Setting SEED: None")
if(torch.cuda.is_available() == False): print('[WARNING] CUDA is not available.')
print("[INFO] Found " + str(torch.cuda.device_count()) + " GPU(s) available.")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("[INFO] Device type: " + str(device))
from datamanager import DataManager
manager = DataManager(args.seed)
num_classes = manager.get_num_classes(args.dataset)
if(args.backbone=="conv4"):
from backbones.conv4 import Conv4
feature_extractor = Conv4(flatten=True)
elif(args.backbone=="resnet8"):
from backbones.resnet_small import ResNet, BasicBlock
feature_extractor = ResNet(BasicBlock, [1, 1, 1], channels=[16, 32, 64], flatten=True)
elif(args.backbone=="resnet32"):
from backbones.resnet_small import ResNet, BasicBlock
feature_extractor = ResNet(BasicBlock, [5, 5, 5], channels=[16, 32, 64], flatten=True)
elif(args.backbone=="resnet56"):
from backbones.resnet_small import ResNet, BasicBlock
feature_extractor = ResNet(BasicBlock, [9, 9, 9], channels=[16, 32, 64], flatten=True)
elif(args.backbone=="resnet34"):
from backbones.resnet_large import ResNet, BasicBlock
feature_extractor = ResNet(BasicBlock, layers=[3, 4, 6, 3],zero_init_residual=False,
groups=1, width_per_group=64, replace_stride_with_dilation=None,
norm_layer=None)
else:
raise RuntimeError("[ERROR] the backbone " + str(args.backbone) + " is not supported.")
print("[INFO]", str(str(args.backbone)), "loaded in memory.")
print("[INFO] Feature size:", str(feature_extractor.feature_size))
test_loader = manager.get_test_loader(args.dataset, args.data_size)
def main():
from methods.standard import StandardModel
model = StandardModel(feature_extractor, num_classes)
print("[INFO] Loading checkpoint...")
model.load(args.checkpoint)
print("[INFO] Loading checkpoint: done!")
model.to(device)
print("Testing...")
loss_test, accuracy_test = model.test(test_loader)
print("===========================")
print("Seed:", str(args.seed))
print("Test loss:", str(loss_test) + "%")
print("Test accuracy:", str(accuracy_test) + "%")
print("===========================")
if __name__== "__main__": main() | python | 12 | 0.698233 | 201 | 40.617647 | 102 | starcoderdata |
<?php
namespace TravelPayouts\Components;
use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Exception\GuzzleException;
use RuntimeException;
class Client extends BaseClient
{
private const API_HOST = 'https://api.travelpayouts.com';
private string $token;
public function __construct(string $token)
{
$this->token = $token;
$this->client = new HttpClient(
[
'base_uri' => self::API_HOST,
'headers' =>
[
'Content-Type' => 'application/json',
'X-Access-Token' => $this->token,
'Accept-Encoding' => 'gzip,deflate,sdch',
],
]
);
}
/**
* @param string $url
* @param array<string, mixed> $options
* @param string $type
* @param bool|true $replaceOptions
*
* @return mixed
* @throws GuzzleException
*/
public function execute(string $url, array $options, string $type = 'GET', bool $replaceOptions = true)
{
$url = '/' . $this->getApiVersion() . '/' . $url;
$params = [
'http_errors' => false,
];
if ($replaceOptions) {
$paramName = $type === 'GET' ? 'query' : 'body';
$params[$paramName] = $options;
}
if (!$replaceOptions) {
$params += $options;
}
$body = $this->validateResponse($url, $params, $type);
return $this->makeApiResponse($body->getContents());
}
public function getToken(): string
{
return $this->token;
}
/**
* @return mixed
* @throws RuntimeException
*/
private function makeApiResponse(string $jsonString)
{
$data = json_decode($jsonString, true);
if (!$data) {
throw new RuntimeException(sprintf('Unable to decode json response: %s', $jsonString));
}
return $data;
}
} | php | 16 | 0.517189 | 107 | 24.037975 | 79 | starcoderdata |
//
// Created by FLXR on 5/18/2019.
//
#include "examplebox2d.hpp"
#include
#include
using namespace xe;
ExampleBox2D *ExampleBox2D::instance = nullptr;
ExampleBox2D::ExampleBox2D() :
density(130.0f),
friction(0.2f),
restitution(0.5f),
boxHooked(false) {
const float width = app.getWindowSize().x;
const float height = app.getWindowSize().y;
camera = new Camera(mat4::ortho(0.0f, width, 0.0f, height, -1.0f, 1.0f));
renderer = new Renderer2D(width, height, camera);
contactListener = new MyListener();
world = new PhysicsWorld2D({0.0f, -9.8f});
world->setContactListener(contactListener);
box = new RectangleShape({50.0f, 50.0f});
box->transformation({400.0f, 400.0f});
boxCollider = new BoxCollider2D(world, ColliderType::Dynamic, box);
boxCollider->setDensity(density);
boxCollider->setFriction(friction);
boxCollider->setRestitution(restitution);
boxCollider->setCategoryBits(BOX);
boxCollider->setMask(GROUND | CIRCLE0 | CIRCLE2);
boxCollider->setUserData((void *) "box");
ground0 = new RectangleShape({500.0f, 5.0f});
ground0->transformation({400.0f, 50.0f}, 20.0f);
groundCollider0 = new BoxCollider2D(world, ColliderType::Static, ground0);
groundCollider0->setCategoryBits(GROUND);
groundCollider0->setMask(BOX | CIRCLE1 | CIRCLE2);
ground1 = new RectangleShape({500.0f, 5.0f});
ground1->transformation({850.0f, 165.0f}, 10.0f);
groundCollider1 = new BoxCollider2D(world, ColliderType::Static, ground1);
groundCollider1->setCategoryBits(GROUND);
groundCollider1->setMask(BOX | CIRCLE1 | CIRCLE2);
circle0 = new CircleShape(100.0f);
circle0->transformation({370.0f, 200.0f});
circleCollider0 = new CircleCollider2D(world, ColliderType::Static, circle0);
circleCollider0->setCategoryBits(CIRCLE0);
circleCollider0->setMask(BOX | CIRCLE1 | CIRCLE2);
circle1 = new CircleShape(50.0f);
circle1->transformation({470.0f, 500.0f});
circleCollider1 = new CircleCollider2D(world, ColliderType::Dynamic, circle1);
circleCollider1->setCategoryBits(CIRCLE1);
circleCollider1->setMask(GROUND | CIRCLE0);
circle2 = new CircleShape(100.0f);
circle2->transformation({530.0f, 600.0f});
circleCollider2 = new CircleCollider2D(world, ColliderType::Dynamic, circle2);
circleCollider2->setDensity(10.5f);
circleCollider2->setFriction(0.2f);
circleCollider2->setRestitution(0.5f);
circleCollider2->setCategoryBits(CIRCLE2);
circleCollider2->setMask(GROUND | CIRCLE0 | BOX);
}
ExampleBox2D::~ExampleBox2D() {
delete camera;
delete renderer;
delete box;
delete ground0;
delete ground1;
delete circle0;
delete circle1;
delete circle2;
delete boxCollider;
delete groundCollider0;
delete groundCollider1;
delete circleCollider0;
delete circleCollider1;
delete circleCollider2;
delete contactListener;
delete world;
}
void ExampleBox2D::init() {
box->setColor(color::Red);
ground0->setTexture(GETTEXTURE("grass"));
ground1->setTexture(GETTEXTURE("grass"));
circle0->setTexture(GETTEXTURE("test1"));
circle1->setTexture(GETTEXTURE("test2"));
circle2->setTexture(GETTEXTURE("test3"));
}
void ExampleBox2D::render() {
renderer->begin();
renderer->submit(ground0);
renderer->submit(ground1);
renderer->submit(circle0);
renderer->submit(circle1);
renderer->submit(circle2);
renderer->submit(box);
renderer->end();
renderer->flush();
}
void ExampleBox2D::renderImGui() {
ImGui::Begin("Physics 2D", nullptr);
static bool fixedRot = false;
if (ImGui::Checkbox("Box fixedRotation", &fixedRot)) {
boxCollider->setFixedRotation(fixedRot);
}
if (ImGui::DragFloat("Box density", &density, 0.1f, 0.1f, 300.0f)) {
boxCollider->setDensity(density);
boxCollider->recreate();
}
if (ImGui::DragFloat("Box friction", &friction, 0.001f, 0.0f, 1.0f)) {
boxCollider->setFriction(friction);
boxCollider->recreate();
}
if (ImGui::DragFloat("Box restitution", &restitution, 0.001f, 0.0f, 1.0f)) {
boxCollider->setRestitution(restitution);
boxCollider->recreate();
}
ImGui::End();
}
void ExampleBox2D::update(float delta) {
if (boxHooked) {
boxCollider->set(mousePos, boxCollider->getRotation());
boxCollider->setAwake(true);
boxCollider->setAngularVelocity(0.0f);
boxCollider->setLinearVelocity({0.0f, 0.0f});
}
}
void ExampleBox2D::fixedUpdate(float delta) {
world->update(delta, 6, 3);
}
void ExampleBox2D::input(xe::Event &event) {
if (event.type == Event::MouseButtonPressed) {
if (event.mouseButton.button == Mouse::Left) {
boxHooked = true;
mousePos = Mouse::getPosition(window);
}
}
if (event.type == Event::MouseButtonReleased) {
if (event.mouseButton.button == Mouse::Left) {
boxHooked = false;
}
}
if (event.type == Event::MouseMoved) {
if (boxHooked) {
mousePos = vec2(event.mouseMove.x, event.mouseMove.y);
}
}
}
//contact listner
void MyListener::beginContact(b2Contact *contact) {
// XE_TRACE("begin contact");
}
void MyListener::endContact(b2Contact *contact) {
// XE_TRACE("end contact");
}
void MyListener::preSolve(b2Contact *contact, const b2Manifold *oldManifold) {
// XE_TRACE("presolve contact");
}
void MyListener::postSolve(b2Contact *contact, const b2ContactImpulse *impulse) {
// XE_TRACE("postsolve contact");
} | c++ | 13 | 0.707453 | 81 | 27.240838 | 191 | starcoderdata |
package cn.stj.fphealth.util;
import android.content.Context;
import android.net.wifi.ScanResult;
import android.telephony.NeighboringCellInfo;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;
import android.text.TextUtils;
import cn.stj.fphealth.app.Constants;
import cn.stj.fphealth.entity.Mobile;
import cn.stj.fphealth.entity.MobileBaseStation;
import cn.stj.fphealth.entity.RemindInfo;
import cn.stj.fphealth.entity.Wifi;
import cn.stj.fphealth.entity.WifiHotspot;
import cn.stj.fphealth.http.DeviceInitResponse;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
/**
* json util Created by hhj@20160810.
*/
public class JsonUtil {
private static Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes f) {
// Filtered off the field name contains the "baseObjId"
return f.getName().contains("baseObjId");
}
@Override
public boolean shouldSkipClass(Class clazz) {
return false;
}
}).setDateFormat("yyyy-MM-dd HH:mm:ss").create();
public static Gson getGson() {
return gson;
}
/**
* Use Gson analyzed
*
* @param jsonString
* @param cls
* @param
* @return Objects obtained after parsing
*/
public static T getData(String jsonString, Class cls) {
T t = null;
System.out.println("jsonString =" + jsonString + " cls = " + cls);
try {
t = gson.fromJson(jsonString, cls);
} catch (Exception e) {
e.printStackTrace();
}
return t;
}
/**
* Use Gson analyzed
*
* @param jsonString
* @param cls
* @param
* @return object list
*/
public static List getDatas(String jsonString, Class cls) {
List list = new ArrayList
try {
Type listType = type(List.class, cls);
list = gson.fromJson(jsonString, listType);
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
static ParameterizedType type(final Class raw, final Type... args) {
return new ParameterizedType() {
public Type getRawType() {
return raw;
}
public Type[] getActualTypeArguments() {
return args;
}
public Type getOwnerType() {
return null;
}
};
}
public static String getWifiJson(List wifis) {
JSONArray jsonArray = new JSONArray();
try {
for (int i = 0; i < wifis.size(); i++) {
Wifi wifi = wifis.get(i);
JSONObject jsonObject = new JSONObject();
List wifiHotspots = wifi.getWifiHotspots();
for (int j = 0; j < wifiHotspots.size(); j++) {
WifiHotspot wifiHotspot = wifiHotspots.get(j);
jsonObject.put("mac" + (j + 1), wifiHotspot.getMac());
jsonObject.put("macName" + (j + 1), wifiHotspot.getMacName());
jsonObject.put("signal" + (j + 1), wifiHotspot.getSignal());
}
jsonObject.put("time", wifi.getTime());
jsonArray.put(jsonObject);
}
return jsonArray.toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
/**
* Get mobile phone base station information
*
* @throws JSONException
*/
public static String getGSMCellLocationJson(List mobiles) {
try {
JSONArray jsonArray = new JSONArray();
for(int i = 0;i < mobiles.size();i++){
Mobile mobile = mobiles.get(i);
JSONObject jsonObject = new JSONObject();
jsonObject.put("serverIp", mobile.getServerIp());
jsonObject.put("network", mobile.getNetwork());
jsonObject.put("mcc", mobile.getMcc());
jsonObject.put("mnc", mobile.getMnc());
jsonObject.put("time", mobile.getTime());
List mobileBaseStations = mobile.getMobileBaseStations();
if (mobileBaseStations != null && mobileBaseStations.size() > 0) {
for (int j = 0; j < mobileBaseStations.size(); j++) {
MobileBaseStation mobileBaseStation = mobileBaseStations.get(j);
jsonObject.put("lac" + (j + 1), mobileBaseStation.getLac());
jsonObject.put("ci" + (j + 1), mobileBaseStation.getCi());
jsonObject.put("rssi" + (j + 1), TextUtils.isEmpty(mobileBaseStation.getRssi())?"":Integer.valueOf(mobileBaseStation.getRssi()));
}
}
jsonArray.put(jsonObject);
}
return jsonArray.toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
/**
* get all device parameters string
* @return
*/
public static String getAllDeviceParams(Context context){
String allParams = "" ;
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put(Constants.DEVICE_PARAM.COMMON, PreferencesUtils.getString(context, Constants.DEVICE_PARAM.COMMON_CODE));
jsonObject.put(Constants.DEVICE_PARAM.CONNECT, PreferencesUtils.getString(context, Constants.DEVICE_PARAM.CONNECT_CODE));
jsonObject.put(Constants.DEVICE_PARAM.FREQUENCY, PreferencesUtils.getString(context, Constants.DEVICE_PARAM.FREQUENCY_CODE));
jsonObject.put(Constants.DEVICE_PARAM.HEALTH, PreferencesUtils.getString(context, Constants.DEVICE_PARAM.HEALTH_CODE));
allParams = jsonObject.toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return allParams;
}
} | java | 19 | 0.573962 | 153 | 32.859296 | 199 | starcoderdata |
import CardMovie from "../../components/CardMovie";
import { ReactComponent as ArrowLit } from '../../assets/img/arrowLit.svg';
import { ReactComponent as ArrowOff } from '../../assets/img/arrowOff.svg';
import Api from "../../services/Api.js";
import "./index.css"
import { useState, useEffect } from "react";
function List() {
const [datas, setDatas] = useState(false);
const [numPages, setNumPages] = useState(datas.numPages);
const [page, setPage] = useState(1);
let getData = async (page) => {
let response = await Api.get(`movies/page/${page}`);
setNumPages(response.data.numPages);
setDatas(response.data);
}
// When the varible page change, called the function
useEffect(() => {
getData(page);
}, [page])
let listMovies = "Não tem Filmes Disponiveis"
if (datas != false) {
listMovies = datas.movies?.map( (movie, key) => <div key={key}><CardMovie movie={movie} /> )
}
return (
<>
<div className="next-preview-page container">
<a className="spin-arrow" onClick={() => setPage(page > 1 ? page - 1 : page)}> {page > 1 ? <ArrowLit /> : <ArrowOff className="arrowDisable" />}
{page == undefined ? 1 : page} de {numPages}
<a onClick={() => setPage(page < numPages ? page + 1 : page)} >{page < numPages ? <ArrowLit /> : <ArrowOff className="arrowDisable" />}
<div className="cards-movies container">
{listMovies}
)
}
export default List; | javascript | 20 | 0.574032 | 169 | 36.361702 | 47 | starcoderdata |
/** @private */
function setDocletKindToTitleCustom(doclet, tag) {
// doclet.addTag( 'custom_kind', tag.title );
doclet.custom_kind = tag.title;
}
function setDocletNameToValueCustom(doclet, tag) {
if (tag.value && tag.value.description) { // as in a long tag
doclet.changelog_name = tag.value.description;
}
else if (tag.text) { // or a short tag
doclet.changelog_name = tag.text;
}
}
exports.defineTags = function(dictionary) {
dictionary.defineTag('created', {
mustHaveValue: true,
onTagged : function(doclet, tag) {
doclet.created = tag.value;
}
});
dictionary.defineTag('modified', {
mustHaveValue: true,
onTagged : function(doclet, tag) {
doclet.modified = tag.value;
}
});
dictionary.defineTag('todo', {
canHaveType: true,
canHaveName: true,
onTagged: function(doclet, tag) {
doclet.todo = doclet.todo || [];
doclet.todo.push(tag.value || {});
doclet.kind_todolist = 'todolist';
}
});
dictionary.defineTag('fixme', {
canHaveType: true,
canHaveName: true,
onTagged: function(doclet, tag) {
doclet.fixme = doclet.fixme || [];
doclet.fixme.push(tag.value || {});
doclet.kind_todolist = 'todolist';
}
});
dictionary.defineTag('done', {
canHaveType: true,
canHaveName: true,
onTagged: function(doclet, tag) {
doclet.done = doclet.done || [];
doclet.done.push(tag.value || {});
doclet.kind_todolist = 'todolist';
}
});
dictionary.defineTag('changelog', {
canHaveType: true,
canHaveName: true,
onTagged: function(doclet, tag) {
doclet.changelog = doclet.changelog || [];
doclet.changelog.push(tag.value || {});
doclet.kind_changelog = tag.title;
}
});
};
exports.handlers = {
newDoclet: function(e) {
}
}; | javascript | 22 | 0.598667 | 65 | 26.871429 | 70 | starcoderdata |
// V8 内置了一个性能分析工具——Tick Processor,可以记录 JavaScript/C/C++ 代码的堆栈信息,该功能默认是关闭的,可以通过添加命令行参数 --prof 开启。
const crypto = require('crypto')
/*
function hash (password) {
const salt = crypto.randomBytes(128).toString('base64')
const hash = crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha512')
return hash
}
let i = 0
console.time('pbkdf2Sync')
for (let i = 0; i < 100; i++) {
hash('random_password')
}
console.log(i++) // 上边的hash为同步代码, for执行完才会向下执行
console.timeEnd('pbkdf2Sync')
*/
// 运行 node --prof app
// 0
// pbkdf2Sync: 738.553ms
// 早期我们需要借助 node-tick-processor 这样的工具解析 v8.log,但 Node.js 在 v5.2.0 之后包含了 v8.log 处理器,添加命令行参数 --prof-process 开启。
// 运行
// node --prof-process isolate-0x103000000-v8.log
/*
Statistical profiling result from isolate-000001B8262F1FE0-12168-v8.log, (408 ticks, 0 unaccounted, 0 excluded).
[Shared libraries]:
ticks total nonlib name
395 96.8% D:\software\nodejs\node.exe
13 3.2% C:\Windows\SYSTEM32\ntdll.dll
[JavaScript]:
ticks total nonlib name
[C++]:
ticks total nonlib name
[Summary]:
ticks total nonlib name
0 0.0% NaN% JavaScript
0 0.0% NaN% C++
2 0.5% Infinity% GC
408 100.0% Shared libraries
[C++ entry points]:
ticks cpp total name
[Bottom up (heavy) profile]:
Note: percentage shows a share of a particular caller in the total
amount of its parent calls.
Callers occupying less than 1.0% are not shown.
ticks parent name
395 96.8% D:\software\nodejs\node.exe
387 98.0% D:\software\nodejs\node.exe
354 91.5% LazyCompile: ~pbkdf2Sync internal/crypto/pbkdf2.js:45:20
354 100.0% LazyCompile: ~hash E:\Joy\Note\Nodejs\Debugging\Tick Processor\app.js:5:15
354 100.0% Eval: ~ E:\Joy\Note\Nodejs\Debugging\Tick Processor\app.js:1:1
354 100.0% LazyCompile: ~Module._compile internal/modules/cjs/loader.js:868:37
15 3.9% LazyCompile: ~NativeModule.compile internal/bootstrap/loaders.js:272:42
15 100.0% LazyCompile: ~nativeModuleRequire internal/bootstrap/loaders.js:183:29
2 13.3% Eval: ~ tty.js:1:1
2 100.0% LazyCompile: ~NativeModule.compile internal/bootstrap/loaders.js:272:42
2 13.3% Eval: ~ internal/bootstrap/node.js:1:1
2 13.3% Eval: ~ crypto.js:1:1
2 100.0% LazyCompile: ~NativeModule.compile internal/bootstrap/loaders.js:272:42
1 6.7% LazyCompile: ~setupProcessObject internal/bootstrap/node.js:319:28
1 100.0% Eval: ~ internal/bootstrap/node.js:1:1
1 6.7% LazyCompile: ~setupPrepareStackTrace internal/bootstrap/node.js:300:32
1 100.0% Eval: ~ internal/bootstrap/node.js:1:1
1 6.7% LazyCompile: ~setupBuffer internal/bootstrap/node.js:403:21
1 100.0% Eval: ~ internal/bootstrap/node.js:1:1
1 6.7% LazyCompile: ~getColorDepth internal/tty.js:94:23
1 100.0% LazyCompile: ~Console. internal/console/constructor.js:251:49
1 6.7% Eval: ~ timers.js:1:1
1 100.0% LazyCompile: ~NativeModule.compile internal/bootstrap/loaders.js:272:42
1 6.7% Eval: ~ internal/source_map/source_map_cache.js:1:1
1 100.0% LazyCompile: ~NativeModule.compile internal/bootstrap/loaders.js:272:42
1 6.7% Eval: ~ internal/modules/cjs/loader.js:1:1
1 100.0% LazyCompile: ~NativeModule.compile internal/bootstrap/loaders.js:272:42
1 6.7% Eval: ~ internal/console/global.js:1:1
1 100.0% LazyCompile: ~NativeModule.compile internal/bootstrap/loaders.js:272:42
1 6.7% Eval: ~ fs.js:1:1
1 100.0% LazyCompile: ~NativeModule.compile internal/bootstrap/loaders.js:272:42
13 3.2% C:\Windows\SYSTEM32\ntdll.dll
2 15.4% D:\software\nodejs\node.exe
1 50.0% LazyCompile: ~prepareMainThreadExecution internal/bootstrap/pre_execution.js:9:36
1 100.0% Eval: ~ internal/main/run_main_module.js:1:1
1 50.0% Eval: ~ internal/streams/lazy_transform.js:1:1
1 100.0% LazyCompile: ~NativeModule.compile internal/bootstrap/loaders.js:272:42
1 100.0% LazyCompile: ~nativeModuleRequire internal/bootstrap/loaders.js:183:29
1 100.0% Eval: ~ internal/crypto/cipher.js:1:1
*/
// 将同步的 pbkdf2Sync 改为异步的 pbkdf2
function hash (password, cb) {
const salt = crypto.randomBytes(128).toString('base64')
crypto.pbkdf2(password, salt, 10000, 64, 'sha512', cb)
}
let count = 0
console.time('pbkdf2')
for (let i = 0; i < 100; i++) {
hash('random_password', () => {
count++
if (count === 100) {
console.timeEnd('pbkdf2')
}
})
}
// node --prof app
// pbkdf2: 222.907ms 速度提升了2倍 | javascript | 14 | 0.61829 | 112 | 42.581197 | 117 | starcoderdata |
using System;
using System.Collections.Generic;
namespace MFlow.Data
{
///
/// Holds the data of a work item.
///
public class WorkItem : IEquatable
{
#region Properties
///
/// Gets or sets the identifier.
///
public Guid Id { get; init; }
///
/// Gets or sets the creation date.
///
public DateTime Creation { get; init; }
///
/// Gets or sets the name.
///
public string Name { get; set; }
///
/// Gets or sets the identifier of the associated category.
///
public Guid CategoryId { get; init; }
///
/// Gets or sets the count of the working phases.
///
public List WorkingPhases { get; } = new();
///
/// Gets or sets the finished state.
///
public bool IsFinished { get; set; }
#endregion
#region Equality members
/// whether the current object is equal to another object of the same type.
/// <param name="other">An object to compare with this object.
///
/// <see langword="true" /> if the current object is equal to the <paramref name="other" /> parameter; otherwise, <see langword="false" />.
public bool Equals(WorkItem other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
if (!Id.Equals(other.Id) || !Creation.Equals(other.Creation) || Name != other.Name ||
!CategoryId.Equals(other.CategoryId) || IsFinished != other.IsFinished ||
WorkingPhases.Count != other.WorkingPhases.Count)
{
return false;
}
for (var index = 0; index < WorkingPhases.Count; index++)
{
if (WorkingPhases[index] != other.WorkingPhases[index])
return false;
}
return true;
}
/// whether the specified object is equal to the current object.
/// <param name="obj">The object to compare with the current object.
///
/// <see langword="true" /> if the specified object is equal to the current object; otherwise, <see langword="false" />.
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((WorkItem) obj);
}
/// as the default hash function.
/// hash code for the current object.
public override int GetHashCode()
{
return HashCode.Combine(Id, Creation, Name, CategoryId, WorkingPhases, IsFinished);
}
#endregion
#region Overrides of Object
///
/// Returns a string that represents the current object.
///
/// string that represents the current object.
public override string ToString()
{
return Name;
}
#endregion
}
} | c# | 18 | 0.552639 | 157 | 32.476636 | 107 | starcoderdata |
std::string SSocket::build_query(const std::map<std::string, std::string> query) {
//Reuse our static string buffer
SSocket::READ_BUFFER = "";
//Loop through the hash and add the keys to the buffer
for (const auto &it : query)
SSocket::READ_BUFFER += it.first + "=" + it.second + "&";
// Remove the trailing "&"
SSocket::READ_BUFFER.pop_back();
return SSocket::READ_BUFFER;
} | c++ | 10 | 0.625 | 82 | 31.076923 | 13 | inline |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.