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 |
---|---|---|---|---|---|---|---|
import PreActResNet18
import torch
import torch.nn as nn
import torchvision.datasets as datasets
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
batch_size = 1
classes = ('plane', 'car', 'bird', 'cat', 'deer',
'dog', 'frog', 'horse', 'ship', 'truck')
test_data = datasets.CIFAR10(
root='./data',
train=False,
transform=transforms.ToTensor(),
download=True
)
test_loader = DataLoader(test_data, batch_size=batch_size, shuffle=True)
net = PreActResNet18.PreActResNet18()
epsilons = [0.01, 0.02, 0.031, 0.04, 0.05, 0.06]
net = PreActResNet18.PreActResNet18()
check_point = torch.load("CIFAR10_PreActResNet18.checkpoint")
device = torch.device("cuda")
model = net.to(device)
model.load_state_dict(check_point['state_dict'])
model.eval()
criterion = nn.CrossEntropyLoss()
def pgd_attack(model, test_loader, epsilon=0.031, alpha=2/255, iterations=10):
correct = 0
for data, target in test_loader:
data, target = data.to(device), target.to(device)
output = model(data)
init_pred = output.max(1, keepdim=True)[1]
if init_pred.item() != target.item():
continue
orig_data = data
pred = 0
for t in range(iterations):
data.requires_grad = True
output = model(data)
pred = output.max(1, keepdim=True)[1]
if pred.item() != target.item():
break
loss = criterion(output, target)
model.zero_grad()
loss.backward()
data_grad = data.grad.data
sign_data_grad = data_grad.sign()
adv_data = data + alpha * sign_data_grad
eta = torch.clamp(adv_data - orig_data, -epsilon, epsilon)
data = torch.clamp(orig_data + eta, 0, 1).detach()
if pred.item() == target.item():
correct += 1
final_acc = correct / float(len(test_loader))
print("Epsilon: {}\tTest Accuracy = {} / {} = {}".format(epsilon, correct, len(test_loader), final_acc))
return final_acc
step_size = 8/255
inner_iteration = 10
for eps in epsilons:
pgd_attack(model, test_loader, eps, step_size, inner_iteration)
|
python
| 14 | 0.620548 | 108 | 32.181818 | 66 |
starcoderdata
|
<?php
declare(strict_types=1);
namespace Mcfedr\QueueManagerBundle\Exception;
class NoSuchQueueException extends JobNotDeletableException
{
public function __construct()
{
parent::__construct('No such queue exists.');
}
}
|
php
| 10 | 0.714286 | 59 | 17.846154 | 13 |
starcoderdata
|
#Import the necessary methods from tweepy library
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import tweepy
import string
import threading, logging, time
import sys,traceback
from kafka import KafkaConsumer, KafkaProducer
import io
import avro.schema
import avro.io
import pprint
pp = pprint.PrettyPrinter(indent=4,width=80)
#Variables that contains the user credentials to access Twitter API
consumer_key = 'XXXXXXXXXXu3oqffw'#eWkgf0izE2qtN8Ftk5yrVpaaI
consumer_secret = '
access_token = '
access_token_secret = '
twitter_schema='''
{"namespace": "example.avro",
"type": "record",
"name": "StatusTweet",
"fields": [
{"name": "tweet_id" , "type": "long"},
{"name": "followers_count", "type": "int"},
{"name": "statuses_count" , "type": "int"},
{"name": "id_str" , "type": "string"},
{"name": "friends_count" , "type": "int"},
{"name": "text" , "type": "string"},
{"name": "tweet_ts" , "type": "long"},
{"name": "screen_name" , "type": "string"}
]
}
'''
#This is a basic listener that just prints received tweets to stdout.
class StdOutListener(StreamListener):
def __init__(self, topic, broker,numpartitions):
tweepy.StreamListener.__init__(self)
self.topic=topic
self.numpartitions = numpartitions
# 'ip-172-31-10-235:9092'
self.broker = broker
self.id=0
self.producer = KafkaProducer(bootstrap_servers=broker)
self.schema = avro.schema.parse(twitter_schema)
#self.writer = avro.io.DatumWriter(self.schema)
#self.bytes_writer = io.BytesIO()
#self.encoder = avro.io.BinaryEncoder(self.bytes_writer)
def on_status(self, status):
# Prints the text of the tweet
writer = avro.io.DatumWriter(self.schema)
bytes_writer = io.BytesIO()
encoder = avro.io.BinaryEncoder(bytes_writer)
# Schema changed to add the tweet text
#print '%d,%d,%d,%s,%s' % (status.user.followers_count, status.user.friends_count,status.user.statuses_count, status.text, status.user.screen_name)
message = status.text #+ ',' + status.user.screen_name
msg = filter(lambda x: x in string.printable, message)
#print "---"
#pp.pprint(status)
#print "---"
try:
writer.write(
{"tweet_id" : status.id,
"followers_count": status.user.followers_count,
"friends_count" : status.user.friends_count ,
"statuses_count" : status.user.statuses_count ,
"id_str" : status.user.id_str ,
"text" : msg ,
"screen_name" : status.user.screen_name ,
"tweet_ts" : long(status.timestamp_ms) },encoder)
raw_bytes = bytes_writer.getvalue()
self.producer.send(topic=self.topic, value=raw_bytes,key=str(status.id), partition=hash(status.user.screen_name) % self.numpartitions)
#self.producer.send(topic=self.topic, value=str(msg),key=str(self.id), partition=self.id % self.numpartitions)
# print 'fc >%d % (status.user.followers_count, status.user.friends_count,status.user.statuses_count, status.user.id_str, status.user.screen_name)
print " topic %s just published %s" % (self.topic, msg)
self.id += 1
except Exception, e:
print " failed %s just published %s" % (self.topic, str(msg))
print "Unexpected error:", sys.exc_info()[0]
print '-'*60
traceback.print_exc(file=sys.stdout)
print '-'*60
return True
return True
def ZZon_data(self, data):
print data
return True
def on_error(self, status):
print status
if __name__ == '__main__':
#This handles Twitter authetification and the connection to Twitter Streaming API
l = StdOutListener('twitterstream' , 'ip-172-31-10-235:9092',1 )
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
#This line filter Twitter Streams to capture data by the keywords: 'python', 'javascript', 'ruby'
stream.filter(track=['python', 'spark', 'cloudera'])
|
python
| 16 | 0.603753 | 189 | 33.458647 | 133 |
starcoderdata
|
int
setlineno(int n)
{
struct line *clp;
if (n >= 0) {
if (n == 0)
n++;
curwp->w_dotline = n;
clp = lforw(curbp->b_headp); /* "clp" is first line */
while (--n > 0) {
if (lforw(clp) == curbp->b_headp) {
curwp->w_dotline = curwp->w_bufp->b_lines;
break;
}
clp = lforw(clp);
}
} else {
curwp->w_dotline = curwp->w_bufp->b_lines + n;
clp = lback(curbp->b_headp); /* "clp" is last line */
while (n < 0) {
if (lback(clp) == curbp->b_headp) {
curwp->w_dotline = 1;
break;
}
clp = lback(clp);
n++;
}
}
curwp->w_dotp = clp;
curwp->w_doto = 0;
curwp->w_rflag |= WFMOVE;
return (TRUE);
}
|
c
| 13 | 0.517829 | 56 | 18 | 34 |
inline
|
# -*- coding: utf-8 -*-
"""
--------------------------------------
@File : model_movie_user.py
@Author : maixiaochai
@Email :
@Created on : 2020/5/10 15:30
--------------------------------------
"""
from werkzeug.security import generate_password_hash, check_password_hash
from App.ext import db
from App.models import BaseModel
from App.models.model_constant import USER_COMMON, USER_BLACK
class MovieUser(BaseModel):
username = db.Column(db.String(32), unique=True)
_password = db.Column(db.String(256))
phone = db.Column(db.String(32), unique=True)
is_deleted = db.Column(db.Boolean, default=False)
permission = db.Column(db.Integer, default=USER_COMMON)
@property
def password(self):
raise Exception("You have no access to password.")
@password.setter
def password(self, passwd):
self._password = generate_password_hash(passwd)
def check_password(self, passwd):
return check_password_hash(self._password, passwd)
def check_permission(self, permission):
# 权限值与运算判断权限,
# 与之后,相同,则有权限,不同则无权限
if (USER_BLACK & self.permission) == USER_BLACK:
return False
else:
return permission & self.permission == permission
|
python
| 12 | 0.621344 | 73 | 29.119048 | 42 |
starcoderdata
|
package com.github.nijian.jkeel.i18n;
import com.github.nijian.jkeel.commons.feature.Feature;
public class I18nFeature implements Feature<String, I18nFeatureParam> {
@Override
public String apply(I18nFeatureParam param) {
return "hello world";
}
}
|
java
| 5 | 0.743243 | 71 | 20.142857 | 14 |
starcoderdata
|
<?php $__env->startSection('title_area'); ?>
:: Organization Information ::
<?php $__env->stopSection(); ?>
<?php $__env->startSection('show_message'); ?>
<?php if(Session::has('message')): ?>
<div class="alert alert-success alert-dismissible" id="alert_hide_after" role="alert"
style="margin-bottom:10px; ">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×
<?php echo e(Session::get('message')); ?>
<?php endif; ?>
<?php $__env->stopSection(); ?>
<?php $__env->startSection('main_content_area'); ?>
<article class="col-sm-12 col-md-12 col-lg-12">
<!-- Widget ID (each widget will need unique ID)-->
<div class="jarviswidget" id="wid-id-2" data-widget-colorbutton="false" data-widget-editbutton="false">
<span class="widget-icon"> <i class="fa fa-check txt-color-green">
Information
<div class="widget-body no-padding">
<div class="col-sm-12">
<div class="col-sm-12" style="margin-top:10px;">
<?php echo Form::open(['url' => '/company_info_update', 'method' => 'post','class'=>'form-horizontal','files' => true,'enctype' => 'multipart/form-data']); ?>
<div class="form-group">
<label class="col-md-2 control-label">Company Name
<div class="col-md-4">
<input type="text" id="name" value="<?php echo e($company_data->com_name); ?>" class="form-control" placeholder="Company Name" name="name">
<label class="col-md-2 control-label">Application Name
<div class="col-md-4">
<input type="text" id="name" class="form-control" value="<?php echo e($company_data->apps_name); ?>" placeholder="Application Name" name="apps_name">
<div class="form-group">
<label class="col-md-2 control-label">Email
<div class="col-md-4">
<input type="text" id="email" value="<?php echo e($company_data->email); ?>" class="form-control" placeholder="Email" name="email">
<label class="col-md-2 control-label">Mobile
<div class="col-md-4">
<input type="text" id="mobile" value="<?php echo e($company_data->mobile); ?>" class="form-control" placeholder="Mobile" name="mobile">
<div class="form-group">
<label class="col-md-2 control-label">Address
<div class="col-md-4">
<textarea type="text" id="address" class="form-control" placeholder="address" name="address"><?php echo e($company_data->address); ?>
<label class="col-md-2 control-label">Apps. Share Link
<div class="col-md-4">
<textarea type="text" id="apps_link" class="form-control" placeholder="Apps. Share Link" name="apps_link"><?php echo e($company_data->apps_link); ?>
<div class="form-group">
<label class="col-md-2 control-label">Helpline
<div class="col-md-4">
<input type="text" id="email" value="<?php echo e($company_data->helpline); ?>" class="form-control" placeholder="Helpline" name="helpline">
<label class="col-md-2 control-label">Web Address
<div class="col-md-4">
<input type="text" id="name" value="<?php echo e($company_data->web_address); ?>" class="form-control" placeholder="Web Address" name="web_address">
<div class="form-group">
<label class="col-md-2 control-label">Default Email
<div class="col-md-4">
<input type="text" id="default_email_send" value="<?php echo e($company_data->default_email_send); ?>" class="form-control" placeholder="Default Email" name="default_email_send">
<label class="col-md-2 control-label">Logo
<div class="col-md-4">
<input type="file" class="form-control" value="" name="image"/>
<input type="hidden" id="old_image" value="<?php echo e($company_data->company_logo); ?>" name="old_image">
<div class="form-group">
<div class="col-sm-offset-8 col-md-4">
<?php if( !empty($company_data->company_logo) && file_exists('images/logo/'.$company_data->company_logo) ): ?>
<img class="img-thumbnail" src=" <?php echo e(url('images/logo/'.$company_data->company_logo)); ?>" style="height: 50px;width:100px;">
<?php else: ?>
<img class="img-thumbnail" src=" <?php echo e(url('images/default/default-avatar.png')); ?>" style="height: 50px;width:100px;">
<?php endif; ?>
<div class="modal-footer">
<button type="submit" id="updateBtn" class="btn btn-success"><i class="glyphicon glyphicon-save"> Update
<input type="hidden" value="<?php echo e($company_data->id); ?>" name="setting_id" id="setting_id">
<?php echo Form::close(); ?>
<?php $__env->stopSection(); ?>
<?php echo $__env->make("master_hr", array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
|
php
| 13 | 0.457505 | 211 | 61.87037 | 108 |
starcoderdata
|
using System;
using System.Threading.Tasks;
namespace InCountrySDK.Implementation.Authorization
{
public class ExternalTokenClient : ITokenClient
{
private readonly Func _tokenAccessor;
public ExternalTokenClient(Func tokenAccessor)
{
_tokenAccessor = tokenAccessor;
}
public Task RefreshTokenAsync(bool force, string audience, string region)
{
return Task.FromResult(_tokenAccessor.Invoke());
}
}
}
|
c#
| 13 | 0.663462 | 89 | 25 | 20 |
starcoderdata
|
public class CompareVersionNumbers {
public int compareVersion(String version1, String version2) {
if (version1.equals(version2)) return 0;
String[] v1 = version1.split("\\.");
String[] v2 = version2.split("\\.");
for (int i = 0; i < v1.length && i < v2.length; ++i) {
Integer t1 = new Integer(v1[i]);
Integer t2 = new Integer(v2[i]);
if (t1 < t2) {
return -1;
} else if (t1 > t2) {
return 1;
} else {
continue;
}
}
if (v1.length == v2.length) return 0;
if (v1.length > v2.length) {
int flag = 0;
for (int i = v2.length; i < v1.length; ++i) {
Integer t = new Integer(v1[i]);
if (t != 0) flag = 1;
}
return flag;
} else {
int flag = 0;
for (int i = v1.length; i < v2.length; ++i) {
Integer t = new Integer(v2[i]);
if (t != 0) flag = -1;
}
return flag;
}
}
}
|
java
| 12 | 0.433219 | 65 | 32.371429 | 35 |
starcoderdata
|
private void postStatementList(List<LrsStatement> list) {
try {
ResponseEntity<Object> response =
sendRequest(
STATEMENTS_REST_ENDPOINT, HttpMethod.POST, null, list, Object.class);
if (response.getStatusCode().series() == Series.SUCCESSFUL) {
logger.trace(
"LRS provider successfully sent to {}, statement list: {}",
getLRSUrl(),
list);
logger.trace("Sent batch statement. RESULTS: " + response.getBody().toString());
} else {
logger.error(
"LRS provider failed to send to {}, statement list: {}", getLRSUrl(), list);
logger.error("- Response: {}", response);
}
// todo: Need to think through a strategy for handling errors submitting
// to the LRS.
} catch (HttpClientErrorException e) {
// log some additional info in this case...
logger.error(
"LRS provider for URL " + getLRSUrl() + " failed to send statement list", e);
logger.error(
"- Status: {}, Response: {}", e.getStatusCode(), e.getResponseBodyAsString());
} catch (Exception e) {
logger.error(
"LRS provider for URL " + getLRSUrl() + " failed to send statement list", e);
}
}
|
java
| 14 | 0.505126 | 100 | 47.8 | 30 |
inline
|
pubkey = 569581432115411077780908947843367646738369018797567841
with open("flag.enc") as f:
encoded = f.read()
flag = ""
for c in encoded.split(','):
if not c: break
if int(c, 16) != 0:
flag += "0"
else:
flag += "1"
print(hex(int(flag, 2))[2:].rstrip("L").decode("hex"))
|
python
| 13 | 0.584967 | 63 | 20.857143 | 14 |
starcoderdata
|
def __init__(self, cache_store, period=None):
"""
Initialize Heartbeat listener object.
Args:
cache_store (DebuggerCacheStore): Cache store for debugger server.
period (int): The max waiting seconds for each period.
"""
super(HeartbeatListener, self).__init__()
self._heartbeat_queue = Queue(maxsize=1)
self._cache_store = cache_store
# the waiting period time for next heartbeat, default waiting for 15 seconds
time_delay = 0.5
self._period = period + time_delay if period else 15
self._running = threading.Event()
self._running.clear()
|
python
| 8 | 0.612462 | 84 | 40.1875 | 16 |
inline
|
def test_predict(self):
# load reference predictions
ref_file = os.path.join(self.data_dir, 'pred.npy')
pred_ref = np.load(open(ref_file, 'rb'))
# load module and predict
module_dir = os.path.join(self.data_dir, 'B1')
module = Signaturizer(module_dir, local=True)
res = module.predict(self.test_smiles)
np.testing.assert_almost_equal(pred_ref, res.signature[:])
# test saving to file
destination = os.path.join(self.tmp_dir, 'pred.h5')
res = module.predict(self.test_smiles, destination)
self.assertTrue(os.path.isfile(destination))
np.testing.assert_almost_equal(pred_ref, res.signature[:])
self.assertEqual(len(res.applicability[:]), 2)
self.assertFalse(np.isnan(res.applicability[0]))
# test prediction of invalid SMILES
res = module.predict(self.invalid_smiles)
for comp in res.signature[0]:
self.assertFalse(math.isnan(comp))
for comp in res.signature[1]:
self.assertTrue(math.isnan(comp))
for comp in res.signature[2]:
self.assertFalse(math.isnan(comp))
|
python
| 10 | 0.629437 | 66 | 47.166667 | 24 |
inline
|
int
bcmltm_md_lt_retrieve(int unit, bcmltm_table_catg_t catg,
uint32_t ltid,
bcmltm_lt_md_t **ltm_md_ptr)
{
SHR_FUNC_ENTER(unit);
/* Check unit */
LTM_MD_UNIT_CHECK(unit);
/* Check table category */
LTM_MD_TABLE_CATG_CHECK(unit, catg);
switch(catg) {
case BCMLTM_TABLE_CATG_PTHRU:
SHR_IF_ERR_EXIT(bcmltm_md_pthru_lt_retrieve(unit, ltid, ltm_md_ptr));
break;
case BCMLTM_TABLE_CATG_LOGICAL:
SHR_IF_ERR_VERBOSE_EXIT
(bcmltm_md_logical_lt_retrieve(unit, ltid, ltm_md_ptr));
break;
default:
SHR_RETURN_VAL_EXIT(SHR_E_UNAVAIL);
break;
}
exit:
SHR_FUNC_EXIT();
}
|
c
| 11 | 0.565585 | 77 | 23.482759 | 29 |
inline
|
<?php
/**
* @file
* @license https://opensource.org/licenses/Apache-2.0 Apache-2.0
*/
namespace Wikimedia\CSS\Grammar;
use Wikimedia\CSS\Objects\ComponentValueList;
use Wikimedia\CSS\Objects\SimpleBlock;
use Wikimedia\CSS\Objects\Token;
use Wikimedia\TestingAccessWrapper;
/**
* @covers \Wikimedia\CSS\Grammar\BlockMatcher
*/
class BlockMatcherTest extends MatcherTestBase {
public function testException() {
$this->expectException( \InvalidArgumentException::class );
$this->expectExceptionMessage( 'A block is delimited by either {}, [], or ().' );
// @phan-suppress-next-line PhanNoopNew
new BlockMatcher( Token::T_RIGHT_BRACE, new TokenMatcher( Token::T_COMMA ) );
}
public function testStandard() {
$m = TestingAccessWrapper::newFromObject(
new BlockMatcher( Token::T_LEFT_BRACE, new TokenMatcher( Token::T_COMMA ) )
);
$ws = new Token( Token::T_WHITESPACE );
$c = new Token( Token::T_COMMA );
$b1 = SimpleBlock::newFromDelimiter( Token::T_LEFT_BRACE );
$b1->getValue()->add( $c );
$b2 = SimpleBlock::newFromDelimiter( Token::T_LEFT_BRACKET );
$b2->getValue()->add( $c );
$b3 = SimpleBlock::newFromDelimiter( Token::T_LEFT_BRACE );
$list = new ComponentValueList( [ $ws, $b1, $b1, $ws, $ws, $b2, $b3, $c, $b1, $ws ] );
$expect = [ false, 2, 5, false, false, false, false, false, 10, false, false ];
$options = [ 'skip-whitespace' => true ];
foreach ( $expect as $i => $v ) {
$this->assertPositions( $i, $v ? [ $v ] : [], $m->generateMatches( $list, $i, $options ),
"Skipping whitespace, index $i" );
}
$options = [ 'skip-whitespace' => false ];
foreach ( $expect as $i => $v ) {
$this->assertPositions( $i, $v ? [ $i + 1 ] : [], $m->generateMatches( $list, $i, $options ),
"Not skipping whitespace, index $i" );
}
}
public function testCaptures() {
$matcher = TestingAccessWrapper::newFromObject( new BlockMatcher( Token::T_LEFT_BRACE,
TokenMatcher::create( Token::T_COMMA )->capture( 'foo' ) ) );
$ws = new Token( Token::T_WHITESPACE );
$c = new Token( Token::T_COMMA );
$b1 = SimpleBlock::newFromDelimiter( Token::T_LEFT_BRACE );
$b1->getValue()->add( [ $ws, $c, $ws ] );
$lb = new Token( Token::T_LEFT_BRACE );
$rb = new Token( Token::T_RIGHT_BRACE );
$list = new ComponentValueList( [ $b1 ] );
$ret = iterator_to_array( $matcher->generateMatches( $list, 0, [ 'skip-whitespace' => true ] ) );
$this->assertEquals( [
new GrammarMatch( $list, 0, 1, null, [ new GrammarMatch( $b1->getValue(), 1, 2, 'foo' ) ] ),
], $ret );
}
}
|
php
| 21 | 0.639421 | 99 | 34.027397 | 73 |
starcoderdata
|
##
##
class NetworkNode:
'''This is the class doctring...'''
_totalNodeCount = 0
def __init__(obj, hostname, serial, ip, brand):
obj.hostname = hostname
obj.serial = serial
obj.ip = ip
obj.brand = brand
NetworkNode._totalNodeCount += 1
def displayNode(obj):
print('Node Hostname: ', obj.hostname)
print('Node Serial Number: ', obj.serial)
print('Node IP Address: ', obj.ip)
print('Node Manufacturer: ', obj.brand)
print('Instantiating our first instance/object!!!')
node0001 = NetworkNode('rtr001', 'ftx8675309', '10.0.2.3', 'Cisco')
node0002 = NetworkNode('sw001', 'ftx8675302', '10.0.9.2', 'Juniper')
node0001.displayNode()
node0002.displayNode()
print('The total number of nodes in your network is: ', NetworkNode._totalNodeCount)
##
## End of file...
|
python
| 9 | 0.630896 | 84 | 28.241379 | 29 |
starcoderdata
|
// RegEx: Character Classes XII - \t
// You can think of character classes as characters with special meaning. They are recognized as special when you place the \ before the character.
// Here are a list of the characters classes in JavaScript:
// ., \cX, \d, \D, \f, \n, \r, \s, \S, \t, \v, \w, \W, \0, \xhh, \uhhhh, \uhhhhh, [\b]
// We have the \t and \v character classes that match any tabs in a string. But more specifically \t is used to match horizontal tabs while \v matches vertical tabs. Vertical tabs were once a thing but are rarely used anymore. We generally use horizontal tabs which are produced by the tab key on our keyboards.
// Find how many tabs with one literal whitespace immediately following the tab are in a string.
// Notes
// Not all whitespaces are the same.
// See Resources for help.
const REGEXP = /[\t\W]/;
|
javascript
| 4 | 0.714793 | 311 | 55.333333 | 15 |
starcoderdata
|
namespace Dapper.Repositories.UnitTests
{
using System;
using Dapper.Repositories.UnitTests.Mocks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class ConnectionFactoryTest
{
private const string DatabaseName = "TestDb";
[TestInitialize]
public void Initialize()
{
TestDatabase.Create(DatabaseName);
}
[TestCleanup]
public void Cleanup()
{
TestDatabase.Delete(DatabaseName);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Register_ShouldThrowExceptionWhenAlreadyRegistered()
{
// arrange
var factory = new ConnectionFactory();
// act
factory.Register("DefaultConnection", TestDatabase.GetConnectionString(DatabaseName), true);
factory.Register("DefaultConnection", TestDatabase.GetConnectionString(DatabaseName));
// assert
// should throw exception
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Register_ShouldThrowExceptionWhenNullName()
{
// arrange
var factory = new ConnectionFactory();
// act
factory.Register(null, TestDatabase.GetConnectionString(DatabaseName));
// assert
// should throw exception
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Register_ShouldThrowExceptionWhenNullConnectionString()
{
// arrange
var factory = new ConnectionFactory();
// act
factory.Register("DefaultConnection", null);
// assert
// should throw exception
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Create_ShouldThrowExceptionWhenNameNotFound()
{
var factory = new ConnectionFactory();
factory.Register("DefaultConnection", TestDatabase.GetConnectionString(DatabaseName));
// create a connection using 'UndefinedConnection' string
// connection not registered will throw an ArgumentException
factory.Create("UndefinedConnection");
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Create_ShouldThrowExceptionWhenDefaultNotRegistered()
{
var factory = new ConnectionFactory();
factory.Register("NotDefaultConnection", TestDatabase.GetConnectionString(DatabaseName));
// create a connection using the default connection string
// the default is not defined above which will throw an ArgumentNullException
factory.Create();
}
[TestMethod]
public void Create_ShouldReturnDefaultConnection()
{
var factory = new ConnectionFactory();
factory.Register("DefaultConnection", TestDatabase.GetConnectionString(DatabaseName), true);
var connection = factory.Create();
Assert.IsNotNull(connection);
}
[TestMethod]
public void Create_ShouldReturnNamedConnection()
{
var factory = new ConnectionFactory();
factory.Register("NotDefaultConnection", TestDatabase.GetConnectionString(DatabaseName));
var connection = factory.Create("NotDefaultConnection");
Assert.IsNotNull(connection);
}
}
}
|
c#
| 13 | 0.617857 | 104 | 29.847458 | 118 |
starcoderdata
|
using Xunit;
namespace Jint.Tests.Ecma
{
public class Test_15_9_4 : EcmaTest
{
[Fact]
[Trait("Category", "15.9.4")]
public void TheDateConstructorHasThePropertyPrototype()
{
RunTest(@"TestCases/ch15/15.9/15.9.4/S15.9.4_A1.js", false);
}
[Fact]
[Trait("Category", "15.9.4")]
public void TheDateConstructorHasThePropertyParse()
{
RunTest(@"TestCases/ch15/15.9/15.9.4/S15.9.4_A2.js", false);
}
[Fact]
[Trait("Category", "15.9.4")]
public void TheDateConstructorHasThePropertyUtc()
{
RunTest(@"TestCases/ch15/15.9/15.9.4/S15.9.4_A3.js", false);
}
[Fact]
[Trait("Category", "15.9.4")]
public void TheValueOfTheInternalPrototypePropertyOfTheDateConstructorIsTheFunctionPrototypeObject()
{
RunTest(@"TestCases/ch15/15.9/15.9.4/S15.9.4_A4.js", false);
}
[Fact]
[Trait("Category", "15.9.4")]
public void DateConstructorHasLengthPropertyWhoseValueIs7()
{
RunTest(@"TestCases/ch15/15.9/15.9.4/S15.9.4_A5.js", false);
}
}
}
|
c#
| 12 | 0.578534 | 108 | 25.045455 | 44 |
starcoderdata
|
public static ProcessWindowFunction<NMAPacketData, SessionPacketFrequency, Integer, TimeWindow>
getBurstsPerSessionProcessFunction() {
ProcessWindowFunction<NMAPacketData, SessionPacketFrequency, Integer, TimeWindow> sessionsPerSecond =
new ProcessWindowFunction<NMAPacketData, SessionPacketFrequency, Integer, TimeWindow>() {
@Override
public void process(Integer key,
ProcessWindowFunction<NMAPacketData,SessionPacketFrequency,Integer,TimeWindow>.Context ctx,
Iterable<NMAPacketData> iterable,
Collector<SessionPacketFrequency> collector) throws Exception {
Date time = null;
Long c_t0 = 0l;
Long s_t0 = 0l;
Long c_dur = 0l;
Long s_dur = 0l;
Inet4Address client = null;
Inet4Address server = null;
int source_port = 0;
int dest_port = 0;
int c2sBurstPkts = 0;
int s2cBurstPkts = 0;
double c2sMeanBurstPktSize = 0;
double s2cMeanBurstPktSize = 0;
// todo capire come tenere le informazioni sulla
// direzione come uno stato globale
//ctx.globalState().getState();
//discover direction
for (NMAPacketData element : iterable) {
if( element.getSessionState().equals("OPENING")){
client = element.getSrc_ip();
server = element.getDst_ip();
source_port = element.sport;
dest_port = element.dport;
//esco dal for perché ho scoperto definitivamente la direzione
break;
} else if(element.sport > element.dport) {
//guessing direction
client = element.getSrc_ip();
server = element.getDst_ip();
source_port = element.sport;
dest_port = element.dport;
} else {
//guessing direction
server = element.getSrc_ip();
client = element.getDst_ip();
dest_port= element.sport;
source_port = element.dport;
}
}
//extract c_t0
for (NMAPacketData element : iterable) {
if(client.equals(element.src_ip)){
c_t0 = element.getTime().getTime();
break;
}
}
//extract s_t0
for (NMAPacketData element : iterable) {
if(server.equals(element.src_ip)){
s_t0 = element.getTime().getTime();
break;
}
}
// extract info (duration, mean size, pkt count)
for(NMAPacketData element : iterable){
time = element.getTime();
if(client.equals(element.src_ip)){
c_dur += element.getTime().getTime();
c2sBurstPkts++;
c2sMeanBurstPktSize = ((double) element.getSize() / c2sBurstPkts);
}
else {
s_dur += element.getTime().getTime();
s2cBurstPkts++;
s2cMeanBurstPktSize = ((double) element.getSize() / s2cBurstPkts);
}
}
c_dur -= c_t0;
s_dur -= s_t0;
collector.collect( new SessionPacketFrequency(time, client, server, source_port, dest_port,
c_dur, c2sBurstPkts, c2sMeanBurstPktSize, s_dur, s2cBurstPkts, s2cMeanBurstPktSize));
}
};
return sessionsPerSecond;
}
|
java
| 20 | 0.647638 | 103 | 23.739496 | 119 |
inline
|
import _ from 'lodash'
import { SignIn, SignOut } from '../../index.js'
beforeAll(() => {
const session = MEMO.readable(SignIn.METHOD, SignIn.ENDPOINT)
return MEMO.writable(new SignOut())
.call({
access_token: _.get(session, 'access_token'),
})
.then((signOut) => {
MEMO.set(signOut)
})
})
test('output match', () => {
expect(SignOut.outputMatch(MEMO.get())).toBe(true)
})
afterAll(() => {
MEMO.save()
})
|
javascript
| 16 | 0.55 | 65 | 21.857143 | 21 |
starcoderdata
|
#pragma once
#include "Factory.h"
#include "RenderComponent.h"
#include
// FACTORY INFRASTRUCTURE DECLARATION
DECLARE_FACTORY(SpotLightRC);
namespace Ogre {
class SceneNode;
class SceneManager;
class Light;
typedef float Real;
template <int Dims, typename T> class Vector;
typedef Vector<3, Real> Vector3;
} // namespace Ogre
class SpotLightRC final : public RenderComponent {
Ogre::SceneManager* msM_ = nullptr;
Ogre::Light* light_ = nullptr;
public:
SpotLightRC();
virtual ~SpotLightRC();
// set light
void setLight(const std::string& entityId);
// get light
Ogre::Light* getLight() const;
// set the colour of the light
void setColour(Ogre::Vector3 colour);
// set the direction of the light
void setDirection(Ogre::Vector3 dir);
// called each frame
virtual void render();
};
|
c
| 8 | 0.68247 | 50 | 21.675 | 40 |
starcoderdata
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('HomeModel','hm');
if (!$this->session->userdata('openedCuyEa')) {
redirect('login');
} elseif ($this->session->userdata('hak') == "owner") {
redirect('dashboard');
}
}
public function index()
{
$data['title'] = "Dashboard";
$this->load->view('sales/template/header', $data);
$this->load->view('sales/home');
$this->load->view('sales/template/footer');
}
public function ajax_list()
{
$list = $this->hm->get_datatables();
$data = array();
$no = $_POST['start'] + 1;
foreach ($list as $r) {
$row = array();
$row[] = '<p class="text-center">' .$no++. '
$row[] = $r->nota;
$row[] = 'Rp. ' . number_format($r->total_harga, 0,',' ,'.');
$row[] = 'Rp. ' . number_format($r->diskon, 0,',' ,'.');
$row[] = 'Rp. ' . number_format($r->hrgDiskon, 0,',' ,'.');
$row[] = ($r->status) ? "<span class='badge badge-success'>Lunas : "<span class='badge badge-warning'>Proses
$row[] = $r->tgl_ubah;
//add html for action
$row[] = '
<div align="center">
<a class="btn btn-primary" href="javascript:void(0)" title="Detail" onclick="detail('."'".$r->id_pemesanan."'".')"><i class="fas fa-eye"> Detail
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->hm->count_all(),
"recordsFiltered" => $this->hm->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
public function ajax_detail($id)
{
$dataPI = $this->hm->pemesanan_id($id);
$dataDPI = $this->hm->detail_pemesanan_id($id);
foreach ($dataPI as $row) {
echo '<section class="section">
<div class="section-body">
<h2 class="section-title">
No. Invoice : INV-'. $row->id_pemesanan .'
<span class="mt-1 keKanan text-right" style="font-size: 14px;color: #ff00c8;font-weight: bold;">
Status : '. (($row->status == 1) ? "Lunas" : "Proses") .'
<p class="section-lead invHead">Kasir : '. $row->nama .' <span class="keKanan text-right">Tanggal : '. $row->tgl_ubah .'
<div class="table-responsive" id="showTable">
<table class="table table-bordered" id="myTable">
<th class="text-center no"> #
Menu
$no = 1;
if ($dataDPI->num_rows() > 0) {
foreach ($dataDPI->result() as $r) {
echo '
<td class="text-center">'. $no++ .'
$r->nama_menu .'
$r->jumlah_menu .'
'. number_format($r->harga_asli, 0,',' ,'.') .'
}
}else {
echo '
<td class="text-center" colspan="4"><h4 style="color:red">Data Kosong
}
echo ' <tr style="border: 1px; background-color: #6777ef; color: #fff; font-weight: bold;">
<td class="text-right" colspan="3">SubTotal Harga :
'. number_format($row->total_harga, 0,',' ,'.') .'
<tr style="border: 1px; background-color: #6777ef; color: #fff; font-weight: bold;">
<td class="text-right" colspan="3">Diskon :
'. number_format($row->diskon, 0,',' ,'.') .'
<tr style="border: 1px; background-color: #6777ef; color: #fff; font-weight: bold;">
<td class="text-right" colspan="3">Total Harga :
'. number_format($row->hrgDiskon, 0,',' ,'.') .'
';
}
}
}
|
php
| 22 | 0.401536 | 172 | 41.680672 | 119 |
starcoderdata
|
<?php
namespace App\Http\Controllers\Fm;
use App\Fmmastawokia;
use App\Fmmelaya;
use App\Fmmereja;
use App\Fmprogram;
use App\Http\Controllers\Controller;
use App\Mastawokia;
use App\Mereja;
use App\Program;
use App\ProgramKen;
use App\ProgramMeleya;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AllcontrollerFM extends Controller
{
public function __construct()
{
$this->middleware(['auth'])->except('logout');
}
public function programListByDateFm($id)
{
// dd($id); is_artayi
$ken = ProgramKen::find($id);
return view('fm.programs.program-list-by-date-fm')
->with('ken', $ken)
->with('mastawokiafm', Fmmastawokia::orderBy('position')->where('program_ken_id', $id)->get())
->with('programfm', Fmprogram::all()->where('program_ken_id', $id))
->with('programmeleyaid', Fmmelaya::all());
}
public function updatePositionFm(Request $request)
{
// dd($request->all());
if (Auth::user()->role_id == 9 || Auth::user()->role_id == 10) {
$mastawokiafm = Fmmastawokia::all();
foreach ($mastawokiafm as $mast) {
$mast->timestamps = false; // To disable update_at field updation
$id = $mast->id;
foreach ($request->order as $order) {
if ($order['id'] == $id) {
$mast->update(['position' => $order['position']]);
}
}
}
return response()->json(
[
'success' => true,
'message' => 'የማስታወቂያ ቅደም ተከተለል አስተካክለሀል'
]
);
// return response('Update Successfully.', 200);
} else {
session()->flash('error', "የማስታወቂያ ቅደም ተከተለል ማስተካከል አትችልም ፡፡ ");
return redirect()->back();
}
}
public function programListByDateTewatFm($id)
{
$ken = ProgramKen::find($id);
return view('fm.programs.inc.all-tewat-fm')
->with('ken', $ken)
->with('mastawokiafm', Fmmastawokia::orderBy('position')->where('program_ken_id', $id)->get())
// ->with('mastawokiafm', Fmmastawokia::all()->where('program_ken_id', $id))
->with('merejafm', Fmmereja::all())
->with('programfm', Fmprogram::all()->where('program_ken_id', $id))
->with('programmeleyaid', Fmmelaya::all());
}
public function programListByDateKenFm($id)
{
$ken = ProgramKen::find($id);
return view('fm.programs.inc.all-ken-fm')
->with('ken', $ken)
// ->with('mastawokiafm', Fmmastawokia::all()->where('program_ken_id', $id))
->with('mastawokiafm', Fmmastawokia::orderBy('position')->where('program_ken_id', $id)->get())
->with('merejafm', Fmmereja::all())
->with('programfm', Fmprogram::all()->where('program_ken_id', $id))
->with('programmeleyaid', Fmmelaya::all());
//
}
public function programListByDateMataFm($id)
{
$ken = ProgramKen::find($id);
return view('fm.programs.inc.all-mata-fm')
->with('ken', $ken)
// ->with('mastawokiafm', Fmmastawokia::all()->where('program_ken_id', $id))
->with('mastawokiafm', Fmmastawokia::orderBy('position')->where('program_ken_id', $id)->get())
->with('merejafm', Fmmereja::all())
->with('programfm', Fmprogram::all()->where('program_ken_id', $id))
->with('programmeleyaid', Fmmelaya::all());
//
}
public function programListByDateLelitFm($id)
{
$ken = ProgramKen::find($id);
return view('fm.programs.inc.all-lelit-fm')
->with('ken', $ken)
// ->with('mastawokiafm', Fmmastawokia::all()->where('program_ken_id', $id))
->with('mastawokiafm', Fmmastawokia::orderBy('position')->where('program_ken_id', $id)->get())
->with('merejafm', Fmmereja::all())
->with('programfm', Fmprogram::all()->where('program_ken_id', $id))
->with('programmeleyaid', Fmmelaya::all());
//
}
public function programListByDateTewatPrintFm($id)
{
$ken = ProgramKen::find($id);
return view('fm.programs.print.p-tewat')
->with('ken', $ken)
// ->with('mastawokiafm', Fmmastawokia::all()->where('program_ken_id', $id))
->with('merejafm', Fmmereja::all())
->with('mastawokiafm', Fmmastawokia::orderBy('position')->where('program_ken_id', $id)->get())
->with('programfm', Fmprogram::all()->where('program_ken_id', $id))
->with('programmeleyaid', Fmmelaya::all());
}
public function programListByDateKenPrintFm($id)
{
$ken = ProgramKen::find($id);
return view('fm.programs.print.p-ken')
->with('ken', $ken)
// ->with('mastawokiafm', Fmmastawokia::all()->where('program_ken_id', $id))
->with('merejafm', Fmmereja::all())
->with('mastawokiafm', Fmmastawokia::orderBy('position')->where('program_ken_id', $id)->get())
->with('programfm', Fmprogram::all()->where('program_ken_id', $id))
->with('programmeleyaid', Fmmelaya::all());
}
public function programListByDateMataPrintFm($id)
{
$ken = ProgramKen::find($id);
return view('fm.programs.print.p-mata')
->with('ken', $ken)
->with('mastawokiafm', Fmmastawokia::orderBy('position')->where('program_ken_id', $id)->get())
// ->with('mastawokiafm', Fmmastawokia::all()->where('program_ken_id', $id))
->with('merejafm', Fmmereja::all())
->with('programfm', Fmprogram::all()->where('program_ken_id', $id))
->with('programmeleyaid', Fmmelaya::all());
}
public function programListByDateLelitPrintFm($id)
{
$ken = ProgramKen::find($id);
return view('fm.programs.print.p-lelit')
->with('ken', $ken)
->with('mastawokiafm', Fmmastawokia::orderBy('position')->where('program_ken_id', $id)->get())
// ->with('mastawokiafm', Fmmastawokia::all()->where('program_ken_id', $id))
->with('merejafm', Fmmereja::all())
->with('programfm', Fmprogram::all()->where('program_ken_id', $id))
->with('programmeleyaid', Fmmelaya::all());
}
}
|
php
| 21 | 0.545932 | 106 | 35.184358 | 179 |
starcoderdata
|
using FluentAvalonia.UI.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace FluentAvaloniaSamples.ViewModels
{
public class IconsPageViewModel : ViewModelBase
{
public IconsPageViewModel()
{
Symbols = (from item in (Symbol[])Enum.GetValues(typeof(Symbol)) select item.ToString())
.OrderBy(x => x.Substring(0, 1).ToUpper()).ToList();
}
public List Symbols { get; }
public string Header => DescriptionServiceProvider.Instance.GetInfo("Icons", "Header");
public string SymbolIconUsageNotes => DescriptionServiceProvider.Instance.GetInfo("Icons", "SymbolIcon", "UsageNotes");
public string SymbolIconSourceXamlSource => DescriptionServiceProvider.Instance.GetInfo("Icons", "SymbolIconSource", "XamlSource");
public string FontIconUsageNotes => DescriptionServiceProvider.Instance.GetInfo("Icons", "FontIcon", "UsageNotes");
public string FontIconSourceXamlSource => DescriptionServiceProvider.Instance.GetInfo("Icons", "FontIconSource", "XamlSource");
public string PathIconXamlSource => DescriptionServiceProvider.Instance.GetInfo("Icons", "PathIcon", "XamlSource");
public string PathIconSourceXamlSource => DescriptionServiceProvider.Instance.GetInfo("Icons", "PathIconSource", "XamlSource");
public string BitmapIconUsageNotes => DescriptionServiceProvider.Instance.GetInfo("Icons", "BitmapIcon", "UsageNotes");
public string BitmapIconSourceXamlSource => DescriptionServiceProvider.Instance.GetInfo("Icons", "BitmapIconSource", "XamlSource");
public string ImageIconUsageNotes => DescriptionServiceProvider.Instance.GetInfo("Icons", "ImageIcon", "UsageNotes");
public string ImageIconSourceXamlSource => DescriptionServiceProvider.Instance.GetInfo("Icons", "ImageIconSource", "XamlSource");
}
}
|
c#
| 21 | 0.766525 | 133 | 49.702703 | 37 |
starcoderdata
|
func New(host string, port int) *MongoClient {
mongoClient := MongoClient{}
var err error
// client
mongoClient.uri = fmt.Sprintf("mongodb://%s:%d", host, port)
mongoClient.client, err = mongo.NewClient(options.Client().ApplyURI(mongoClient.uri))
if err != nil {
log.Fatalln(errors.Wrap(err, "Database new client error"))
}
// context and cancel
mongoClient.context, mongoClient.Cancel = context.WithTimeout(context.Background(), 10*time.Second)
// connection
err = mongoClient.client.Connect(mongoClient.context)
if err != nil {
log.Fatalln(errors.Wrap(err, "Database connection error"))
}
return &mongoClient
}
|
go
| 11 | 0.728278 | 100 | 29.190476 | 21 |
inline
|
package main
import "net/http" // "net/http"
func main() {
var x *http.Client // "net/http Client"
var y int
z := http.RoundTripper(nil) // "net/http RoundTripper"
_ = x
_ = y
_ = &http.Client{ // "net/http Client"
Transport: z, // "net/http Client Transport"
}
}
|
go
| 10 | 0.614545 | 55 | 18.642857 | 14 |
starcoderdata
|
namespace EA.Iws.Core.Reports
{
using System.ComponentModel.DataAnnotations;
public enum ShipmentsReportDates
{
[Display(Name = "Notification received date")]
NotificationReceivedDate,
[Display(Name = "Consent valid from date")]
ConsentFrom,
[Display(Name = "Consent valid to date")]
ConsentTo,
[Display(Name = "Shipment received date")]
ReceivedDate,
[Display(Name = "Shipment recovered/disposed of date")]
CompletedDate,
[Display(Name = "Actual date of shipment")]
ActualDateOfShipment,
[Display(Name = "Rejected shipment date")]
RejectedShipmentDate
}
}
|
c#
| 9 | 0.632312 | 63 | 23.758621 | 29 |
starcoderdata
|
static void _rfMessageHandler(const char *owner, IARM_EventId_t eventId, void *data, size_t len)
{
MSOBusAPI_Packet_t* busMsg;
int statusCode;
IARM_Bus_PWRMgr_SetPowerState_Param_t param;
busMsg = (MSOBusAPI_Packet_t*)data;
if(len != (busMsg->length + sizeof(MSOBusAPI_Packet_t) - sizeof(MSOBusAPI_Msg_t))) //Message size + header of packet
{
LOG("BusTestApplication: %i MsgIndication with wrong length rec:%d exp:%d\n",eventId,
len, (busMsg->length + sizeof(MSOBusAPI_Packet_t) - sizeof(MSOBusAPI_Msg_t)));
return;
}
//LOG("BusTestApplication: Message received: id:%d\n", busMsg->msgId);
switch(busMsg->msgId)
{
case MSOBusAPI_MsgId_GhostCommand:
{
LOG("BusTestApplication: command code : id:%d\n", busMsg->msg.UserCommand.commandCode);
if (busMsg->msg.UserCommand.commandCode == 1 || busMsg->msg.UserCommand.commandCode == 2)
{
param.newState = IARM_BUS_PWRMGR_POWERSTATE_ON;
//LOG("Setting Powerstate to new=%d\r\n", param.newState);
_SetPowerState((void *)¶m);
}
break;
}
default:
{
//LOG("BusTestApplication: Message received: id:%d\n", busMsg->msgId);
break;
}
}
}
|
c
| 15 | 0.439955 | 132 | 48.527778 | 36 |
inline
|
var server = require('http').createServer();
server.on('request', function (req, res) {
console.log('REQUEST: ' + JSON.stringify(req.headers));
res.end();
});
server.listen(8081, function () {
console.log('Listening on %d.', this.address().port)
});
|
javascript
| 13 | 0.651163 | 57 | 24.8 | 10 |
starcoderdata
|
@Test
public void testAveragePrecision() {
// Test Case from TIP
EvaluateInvertedIndex ei = new EvaluateInvertedIndex();
List<Integer> resultIds = Arrays.asList(7, 17, 9, 42, 5);
Set<Integer> relevantIds = new HashSet<>(Arrays.asList(5, 7, 12, 42));
assertEquals(0.525, ei.averagePrecision(resultIds, relevantIds), 0.001);
}
|
java
| 9 | 0.68169 | 76 | 42.625 | 8 |
inline
|
using System;
using System.IO;
using System.Windows.Forms;
namespace PingTester
{
static class Program
{
/* TODO:
* issue 1: add support to new file format (xml)
* issue 2: add full support for telnet, ssh, remote desktop, vnc (icons and prebuilt passwords)
* issue 3: add log file to ping responses and state changes
* issue 4: add status bar indication how much online/offline
*/
public const string LastPingerFileName = "pinger_history.txt";
///
/// The main entry point for the application.
///
[STAThread]
static void Main(string[] Args)
{
try
{
var culture = System.Configuration.ConfigurationManager.AppSettings["Globalization.CultureInfo"];
if (!string.IsNullOrWhiteSpace(culture))
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(culture);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
FrmMain main = new FrmMain();
main.LastPingerFileName = Path.Combine(System.Environment.CurrentDirectory, Program.LastPingerFileName);
if (Args.Length > 0)
main.StartupFileName = Args[0];
else
main.StartupFileName = main.LastPingerFileName;
Application.Run(main);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
}
}
}
}
|
c#
| 17 | 0.575808 | 123 | 34.88 | 50 |
starcoderdata
|
private void triggerPathUpdate() {
// List<PathwayPath> pathSegments = new ArrayList<>(1);
PathwayPathSelectionEvent pathEvent = new PathwayPathSelectionEvent();
if (selectedPath != null) {
if (pathSegments.size() > 0)
pathSegments.set(pathSegments.size() - 1, new PathSegment(selectedPath));
else
pathSegments.add(new PathSegment(selectedPath));
}
pathEvent.setPath(pathSegments);
pathEvent.setSender(this);
pathEvent.setEventSpace(pathwayPathEventSpace);
eventPublisher.triggerEvent(pathEvent);
}
|
java
| 12 | 0.750943 | 77 | 34.4 | 15 |
inline
|
<?php
namespace bootbuilder\Pane;
abstract class Pane extends \bootbuilder\Controls\Control {
/**
* @var \bootbuilder\Controls\Control
*/
protected $controls;
public function __construct($label, $id = null) {
parent::__construct("", $label, $id, null);
$this->controls = array();
}
/**
* Add control to pane group
* @param \bootbuilder\Controls\Control $control
*/
public function addControl(\bootbuilder\Controls\Control $control) {
array_push($this->controls, $control);
}
/**
* Add multiple controls to pane group
* @param \bootbuilder\Controls\Control $control,... Multiple controls
*/
public function addAll() {
if(func_num_args() > 0) {
for($i = 0; $i < func_num_args(); $i++) {
if(func_get_arg($i) instanceof \bootbuilder\Controls\Control){
array_push($this->controls, func_get_arg($i));
}
}
}
}
/**
* Get raw controls array
* @return array array with controls
*/
public function getRawControls() {
return $this->controls;
}
}
|
php
| 19 | 0.550969 | 78 | 25.977273 | 44 |
starcoderdata
|
module.exports = {
publicPath: '/static',
runtimeCompiler: true,
pluginOptions: {
svg: {
inline: {}, // Pass options to vue-svg-loader
data: {}, // Pass options to url-loader
sprite: {}, // Pass options to svg-sprite-loader
external: {} // Pass options to file-loader
}
},
}
|
javascript
| 10 | 0.590476 | 54 | 25.25 | 12 |
starcoderdata
|
var fluxo = new FlowEngine();
fluxo.Historia();
|
c#
| 7 | 0.564103 | 29 | 6.777778 | 9 |
starcoderdata
|
nums = []
print(len(nums))
print(not nums)
nums = [1,3,4,5,2]
nums.sort()
print(nums)
print(1^2)
stack =[]
stack.append(1)
print(stack)
stack.append(2)
print(stack)
stack.pop() # 意思是stack.pop(index = -1)
print(stack)
|
python
| 6 | 0.662393 | 38 | 12.055556 | 18 |
starcoderdata
|
const {
getAndroidManifestPath,
inject,
ANCHORS,
projectPath,
} = require('@shoutem/build-tools');
const billingPermission = `<uses-permission android:name="com.android.vending.BILLING" />`;
function injectBillingPermission() {
const manifestPath = getAndroidManifestPath({ cwd: projectPath });
inject(manifestPath, ANCHORS.ANDROID.MANIFEST.ROOT, billingPermission);
console.log(`Android: Added BILLING permission to Android manifest`);
}
module.exports = {
injectBillingPermission,
};
|
javascript
| 10 | 0.767797 | 91 | 27.095238 | 21 |
starcoderdata
|
LayoutRect RenderText::collectSelectionRectsForLineBoxes(const RenderLayerModelObject* repaintContainer, bool clipToVisibleContent, Vector<LayoutRect>* rects)
{
ASSERT(!needsLayout());
ASSERT(!simpleLineLayout());
if (selectionState() == SelectionNone)
return LayoutRect();
if (!containingBlock())
return LayoutRect();
// Now calculate startPos and endPos for painting selection.
// We include a selection while endPos > 0
unsigned startPos;
unsigned endPos;
if (selectionState() == SelectionInside) {
// We are fully selected.
startPos = 0;
endPos = text().length();
} else {
startPos = view().selection().startPosition();
endPos = view().selection().endPosition();
if (selectionState() == SelectionStart)
endPos = text().length();
else if (selectionState() == SelectionEnd)
startPos = 0;
}
if (startPos == endPos)
return IntRect();
LayoutRect resultRect;
if (!rects)
resultRect = m_lineBoxes.selectionRectForRange(startPos, endPos);
else {
m_lineBoxes.collectSelectionRectsForRange(startPos, endPos, *rects);
for (auto& rect : *rects) {
resultRect.unite(rect);
rect = localToContainerQuad(FloatRect(rect), repaintContainer).enclosingBoundingBox();
}
}
if (clipToVisibleContent)
return computeRectForRepaint(resultRect, repaintContainer);
return localToContainerQuad(FloatRect(resultRect), repaintContainer).enclosingBoundingBox();
}
|
c++
| 16 | 0.654845 | 158 | 34.111111 | 45 |
inline
|
@Override
public int compareTo(final IFormula<? extends IAssignment> obj) {
final int classNameCompared =
this.getClass().getCanonicalName().compareTo(
obj.getClass().getCanonicalName());
if (classNameCompared != 0) {
return classNameCompared;
}
// Class names are equal
return 0;
}
|
java
| 10 | 0.684543 | 66 | 24.583333 | 12 |
inline
|
package db
var StoredAs = MakeEnum(
MakeID("30a04b8c-720a-468e-8bc6-6ff101e412b3"),
"storedAs",
[]EnumValueL{
BoolStorage,
IntStorage,
StringStorage,
BytesStorage,
FloatStorage,
UUIDStorage,
NotStored,
})
var NotStored = MakeEnumValue(
MakeID("e0f86fe9-10ea-430b-a393-b01957a3eabf"),
"notStored",
)
var BoolStorage = MakeEnumValue(
MakeID("4f71b3af-aad5-422a-8729-e4c0273aa9bd"),
"bool",
)
var IntStorage = MakeEnumValue(
MakeID("14b3d69a-a940-4418-aca1-cec12780b449"),
"int",
)
var StringStorage = MakeEnumValue(
MakeID("200630e4-6724-406e-8218-6161bcefb3d4"),
"string",
)
var BytesStorage = MakeEnumValue(
MakeID("bc7a618f-e87a-4044-a451-9e239212fe2e"),
"bytes",
)
var FloatStorage = MakeEnumValue(
MakeID("ef9995c7-2881-44de-98ff-8960df0e5046"),
"float",
)
var UUIDStorage = MakeEnumValue(
MakeID("4d744a2c-e3f3-4a8b-b645-0af46b0235ae"),
"uuid",
)
|
go
| 9 | 0.734007 | 48 | 17.183673 | 49 |
starcoderdata
|
def clear(self):
"""
Clears the bar graph
` """
self.mc.setBlocks(
self.pos.x,
self.pos.y,
self.pos.z,
self.pos.x + (self.maxLength * self.xIncrement),
self.pos.y + self.height,
self.pos.x + (self.maxLength * self.zIncrement),
block.AIR.id)
|
python
| 10 | 0.468927 | 60 | 28.583333 | 12 |
inline
|
private void SerialComms()
{
while (_continueComms)
{
// If serial is started, don't try to use it.
// TODO: lock the serial object when doing comms so it doesnt get interrupted mid-write.
if (!serial.IsOpen)
{
Thread.Sleep(1000); // just so CPU usage doesn't spike.
continue;
}
lock (serial)
{
if (stage == SerialStage.Handshake)
{
// First, send a message to the device
if (stagepart == 0)
{
serial.Write("010");
stagepart = 1;
}
// Next, wait for a response. If one isn't recieved in 5 seconds, restart.
else if (stagepart == 1)
{
var check = Task.Run(() => SerialResponse("101"));
if (check.Wait(TimeSpan.FromSeconds(5)))
{
stage = SerialStage.ComputerParts;
stagepart = 0;
}
else
{
stage = SerialStage.Handshake;
stagepart = 0;
}
}
}
else if (stage == SerialStage.ComputerParts)
{
if (stagepart == 0)
{
lock (_compMutex)
{
serial.Write($"{cpuName}|{gpuName}|{ramTotal}GB|");
}
stagepart = 1;
}
else if (stagepart == 1)
{
var check = Task.Run(() => SerialResponse("222"));
if (check.Wait(TimeSpan.FromSeconds(5)))
{
stage = SerialStage.ContinuousStats;
stagepart = 0;
}
else
{
stage = SerialStage.Handshake;
stagepart = 0;
}
}
}
else if (stage == SerialStage.ContinuousStats)
{
if (stagepart == 0)
{
lock (_compMutex)
{
serial.Write($"{cpuFreq}|{cpuTemp}|{cpuLoad}|{ramUsed}|{gpuTemp}|" +
$"{gpuCoreClock}|{gpuCoreLoad}|{gpuVramClock}|{gpuVramLoad}|");
}
stagepart = 1;
}
else if (stagepart == 1)
{
// wait for response "333" for 5 seconds, if nothing then restart
var check = Task.Run(() => SerialResponse("333"));
if (check.Wait(TimeSpan.FromSeconds(5)))
{
stage = SerialStage.ContinuousStats;
stagepart = 0;
}
else
{
stage = SerialStage.Handshake;
stagepart = 0;
}
}
}
}
// Sleep for a moment, we don't need to spam the serial pipe.
Thread.Sleep(50);
}
}
|
c#
| 27 | 0.297364 | 104 | 39.6 | 100 |
inline
|
from collections import namedtuple
from typing import List
from alexafsm.session_attributes import SessionAttributes as SessionAttributesBase, INITIAL_STATE
from tests.skillsearch.skill import Skill
Slots = namedtuple('Slots', ['query', 'nth'])
NUMBER_SUFFIXES = {'st', 'nd', 'rd', 'th'}
ENGLISH_NUMBERS = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth',
'ninth', 'tenth']
class SessionAttributes(SessionAttributesBase):
slots_cls = Slots
not_sent_fields = ['searched', 'first_time']
def __init__(self,
intent: str = None,
slots=None,
state: str = INITIAL_STATE,
query: str = None,
skills: List[Skill] = None,
number_of_hits: int = None,
skill_cursor: int = None,
searched: bool = False,
first_time: bool = True,
first_time_presenting_results: bool = False,
said_interrupt: bool = False):
super().__init__(intent, slots, state)
self.query = query
if skills:
self.skills = [Skill.from_es(skill) for skill in skills]
else:
self.skills = None
self.number_of_hits = number_of_hits
self.skill_cursor = skill_cursor
self.searched = searched
self.first_time = first_time
self.first_time_presenting_results = first_time_presenting_results
self.said_interrupt = said_interrupt
@property
def nth_as_index(self):
"""Return -1 if we cannot figure out what index was actually meant by the user"""
if not self.slots.nth: # Amazon's intent system might not give us anything
return -1
elif self.slots.nth in ENGLISH_NUMBERS:
return ENGLISH_NUMBERS.index(self.slots.nth)
else:
try:
# Amazon SOMETIMES gives us "5th" instead of "fifth", so we can try to parse it!
# this is not always the case -- it gives us "second" instead of 2nd
if self.slots.nth[-2:] in NUMBER_SUFFIXES:
return int(self.slots.nth[:-2]) - 1
else:
# otherwise probably directly a number in string format
return int(self.slots.nth) - 1
except ValueError:
return -1
@property
def skill(self):
return self.skills[self.skill_cursor]
|
python
| 20 | 0.571429 | 97 | 37.075758 | 66 |
starcoderdata
|
/**********************************************************************
*
* simulate.h
*
* copyright (c) 2006,
*
* last modified Jul, 2006
* first written Jul, 2006
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License,
* version 3, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but without any warranty; without even the implied warranty of
* merchantability or fitness for a particular purpose. See the GNU
* General Public License, version 3, for more details.
*
* A copy of the GNU General Public License, version 3, is available
* at http://www.r-project.org/Licenses/GPL-3
*
* C functions for the R/qtl package
*
* These functions are for simulating backcross genotype data
*
* Contains: sim_bc_ni, sim_bc, R_sim_bc, R_sim_bc_ni
*
**********************************************************************/
/**********************************************************************
*
* R_sim_bc_ni Wrapper for sim_bc_ni
*
* geno is empty, of size n_mar * n_ind
*
**********************************************************************/
void R_sim_bc_ni(int *n_mar, int *n_ind, double *rf, int *geno);
/**********************************************************************
*
* sim_bc_ni Simulate backcross under no interference
*
* n_mar Number of markers
* n_ind Number of individuals
* rf recombination fractions (length n_mar-1)
* Geno Matrix of size n_ind x n_mar to contain genotype data
*
**********************************************************************/
void sim_bc_ni(int n_mar, int n_ind, double *rf, int **Geno);
/**********************************************************************
*
* R_sim_bc Wrapper for sim_bc
*
* geno is empty, of size n_mar * n_ind
*
**********************************************************************/
void R_sim_bc(int *n_mar, int *n_ind, double *pos,
int *m, double *p, int *geno);
/**********************************************************************
*
* sim_bc Simulate backcross under Stahl's interference model
*
* n_mar Number of markers
* n_ind Number of individuals
* pos Positions of markers (in cM)
* m Interference parameter (integer > 0)
* p Probability chiasma comes from no interference mechanism
* Geno Matrix of size n_ind x n_mar to contain genotype data
*
**********************************************************************/
void sim_bc(int n_mar, int n_ind, double *pos, int m, double p, int **Geno);
/* end of simulate.h */
|
c
| 10 | 0.483648 | 76 | 33.4 | 80 |
starcoderdata
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace MoreMountains.Tools
{
[Serializable]
public class MMAim
{
/// the list of possible control modes .
public enum AimControls { Off, PrimaryMovement, SecondaryMovement, Mouse, Script }
/// the list of possible rotation modes
public enum RotationModes { Free, Strict4Directions, Strict8Directions }
[Header("Control Mode")]
[MMInformation("Pick a control mode : mouse (aims towards the pointer), primary movement (you'll aim towards the current input direction), or secondary movement (aims " +
"towards a second input axis, think twin stick shooters), and set minimum and maximum angles.", MoreMountains.Tools.MMInformationAttribute.InformationType.Info, false)]
/// the aim control mode
public AimControls AimControl = AimControls.SecondaryMovement;
/// the rotation mode
public RotationModes RotationMode = RotationModes.Free;
[Header("Limits")]
[Range(-180, 180)]
/// the minimum angle at which the weapon's rotation will be clamped
public float MinimumAngle = -180f;
[Range(-180, 180)]
/// the maximum angle at which the weapon's rotation will be clamped
public float MaximumAngle = 180f;
/// the current angle the weapon is aiming at
[MMReadOnly]
public float CurrentAngle;
public Vector3 CurrentPosition { get; set; }
public Vector2 PrimaryMovement { get; set; }
public Vector2 SecondaryMovement { get; set; }
protected float[] _possibleAngleValues;
protected Vector3 _currentAim = Vector3.zero;
protected Vector3 _direction;
protected Vector3 _mousePosition;
protected Camera _mainCamera;
///
/// Grabs the weapon component, initializes the angle values
///
public virtual void Initialization()
{
if (RotationMode == RotationModes.Strict4Directions)
{
_possibleAngleValues = new float[5];
_possibleAngleValues[0] = -180f;
_possibleAngleValues[1] = -90f;
_possibleAngleValues[2] = 0f;
_possibleAngleValues[3] = 90f;
_possibleAngleValues[4] = 180f;
}
if (RotationMode == RotationModes.Strict8Directions)
{
_possibleAngleValues = new float[9];
_possibleAngleValues[0] = -180f;
_possibleAngleValues[1] = -135f;
_possibleAngleValues[2] = -90f;
_possibleAngleValues[3] = -45f;
_possibleAngleValues[4] = 0f;
_possibleAngleValues[5] = 45f;
_possibleAngleValues[6] = 90f;
_possibleAngleValues[7] = 135f;
_possibleAngleValues[8] = 180f;
}
_mainCamera = Camera.main;
}
///
/// Computes the current aim direction
///
public virtual Vector2 GetCurrentAim()
{
switch (AimControl)
{
case AimControls.Off:
_currentAim = Vector2.zero;
break;
case AimControls.Script:
// in that mode we simply use _currentAim, as set by the SetAim method
break;
case AimControls.PrimaryMovement:
_currentAim = PrimaryMovement;
break;
case AimControls.SecondaryMovement:
_currentAim = SecondaryMovement;
break;
case AimControls.Mouse:
_mousePosition = Input.mousePosition;
_mousePosition.z = 10;
_direction = _mainCamera.ScreenToWorldPoint(_mousePosition);
_direction.z = CurrentPosition.z;
_currentAim = _direction - CurrentPosition;
break;
default:
_currentAim = Vector2.zero;
break;
}
// we compute our angle in degrees
CurrentAngle = Mathf.Atan2(_currentAim.y, _currentAim.x) * Mathf.Rad2Deg;
// we clamp our raw angle if needed
if ((CurrentAngle < MinimumAngle) || (CurrentAngle > MaximumAngle))
{
float minAngleDifference = Mathf.DeltaAngle(CurrentAngle, MinimumAngle);
float maxAngleDifference = Mathf.DeltaAngle(CurrentAngle, MaximumAngle);
CurrentAngle = (Mathf.Abs(minAngleDifference) < Mathf.Abs(maxAngleDifference)) ? MinimumAngle : MaximumAngle;
}
// we round to the closest angle
if (RotationMode == RotationModes.Strict4Directions || RotationMode == RotationModes.Strict8Directions)
{
CurrentAngle = MMMaths.RoundToClosest(CurrentAngle, _possibleAngleValues);
}
// we clamp the final value
CurrentAngle = Mathf.Clamp(CurrentAngle, MinimumAngle, MaximumAngle);
// we return our aim vector
_currentAim = (_currentAim.magnitude == 0f) ? Vector2.zero : MMMaths.RotateVector2(Vector2.right, CurrentAngle);
return _currentAim;
}
///
/// Use this method to set the aim when in AimControl mode : Script
///
/// <param name="newAim">
public virtual void SetAim(Vector2 newAim)
{
_currentAim = newAim;
}
}
}
|
c#
| 17 | 0.579976 | 180 | 37.812081 | 149 |
starcoderdata
|
const parser = require("../parsers/searchParser")
const request = require("../utils/request")
exports.device = async (req, res) => {
/*
#swagger.tags = ['Catalog']
#swagger.summary = 'Find devices by keyword'
#swagger.parameters['device'] = {
schema: 'casio'
}
*/
request.send(res, process.env.URI + '/results.php3?sQuickSearch=yes&sName=' + req.params.device, parser.search)
}
|
javascript
| 9 | 0.636364 | 115 | 29.714286 | 14 |
starcoderdata
|
package de.hpi.visio;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.oryxeditor.server.diagram.Point;
import de.hpi.visio.data.Page;
import de.hpi.visio.data.Shape;
import de.hpi.visio.util.DistanceToShapeComparator;
import de.hpi.visio.util.ImportConfigurationUtil;
import de.hpi.visio.util.VisioShapeDistanceUtil;
import java.util.Collections;
/**
* HeuristicVisioFreeTextInterpreter interprets visio shapes, that do not have a
* nameU (type) but a label and therefore are free-text that is on the visio
* page and that must be handled to import this information to oryx.
* Depending on the label's length, the distance to the next shape and the shapes type
* this label will be the nearest shape's label, an associated annotation or a
* dangling annotation.
*
* @author Thamsen
*/
public class HeuristicVisioFreeTextInterpreter {
private ImportConfigurationUtil importUtil;
private VisioShapeDistanceUtil shapeUtil;
public HeuristicVisioFreeTextInterpreter(ImportConfigurationUtil importUtil, VisioShapeDistanceUtil shapeUtil) {
this.importUtil = importUtil;
this.shapeUtil = shapeUtil;
}
public Page interpretShapes(Page visioPage) {
List shapesWithNames = new ArrayList
Boolean shouldSkipUnnamedWithLabel = Boolean.valueOf(importUtil.getHeuristic("skipUnknownNameUButWithLabel"));
Boolean isInSimpleInterpretationMode = importUtil.getHeuristic("labelOnlyInterpretationMode").equalsIgnoreCase(
"simple");
String defaultTypeWithLabel = importUtil.getStencilSetConfig("unknownNameUButWithLabelType");
for (Shape shape : visioPage.getShapes()) {
if (shape.name == null || shape.name.equals("")) {
if (shape.getLabel() != null && shape.getLabel() != "") {
if (shouldSkipUnnamedWithLabel)
continue;
if (isInSimpleInterpretationMode) {
shape.setName(defaultTypeWithLabel);
} else {
interpreteShapeWithoutNameButWithLabelHeuristic(shape, visioPage, shapesWithNames);
continue;
}
}
}
shapesWithNames.add(shape);
}
visioPage.setShapes(shapesWithNames);
return visioPage;
}
private void interpreteShapeWithoutNameButWithLabelHeuristic(Shape freeTextShape, Page visioPage, List shapesWithNames) {
Double isLabelThreshold = Double.valueOf(importUtil.getHeuristic("labelOnlyIsLabelForAnotherShapeThreshold"));
Double isAnnotationThreshold = Double.valueOf(importUtil.getHeuristic("labelOnlyIsAnnotationToAnotherShapeThreshold"));
String annotationType = importUtil.getStencilSetConfig("labelOnlyAnnotationType");
Map<Shape, Double> labelThresholdShapes = new HashMap<Shape, Double>();
Map<Shape, Double> annotationThresholdShapes = new HashMap<Shape, Double>();
for (Shape otherShape : getNotExcludedShapesWithType(visioPage)) {
if (freeTextShape == otherShape)
continue;
Double currentDistance = shapeUtil.getAroundMinimalDistanceBetweenTwoShapeBorders(freeTextShape, otherShape);
if (currentDistance < isLabelThreshold)
labelThresholdShapes.put(otherShape, currentDistance);
if (currentDistance < isAnnotationThreshold)
annotationThresholdShapes.put(otherShape, currentDistance);
}
List<Map.Entry<Shape, Double>> labelThresholdShapeList = new ArrayList<Map.Entry<Shape, Double>>(labelThresholdShapes.entrySet());
List<Map.Entry<Shape, Double>> annotationThresholdShapeList = new ArrayList<Map.Entry<Shape, Double>>(annotationThresholdShapes.entrySet());
Integer stringLengthThresholdForLabels = Integer.valueOf(importUtil.getHeuristic("labelOnlyTooLongForAnotherShapesLabelThreshold"));
Collections.sort(labelThresholdShapeList, new DistanceToShapeComparator());
Integer considerationThreshold = Integer.valueOf(importUtil.getHeuristic("considerXShapesWithinLabelThresholdWithXIs"));
Boolean handled = false;
if (freeTextShape.getLabel().length() < stringLengthThresholdForLabels) {
for (int i = 0; !handled && i < labelThresholdShapeList.size() && i < considerationThreshold; i++) {
if (labelThresholdShapeList.get(i).getKey().getLabel() == null || "".equals(labelThresholdShapeList.get(i).getKey().getLabel())) {
labelThresholdShapeList.get(i).getKey().setLabel(freeTextShape.getLabel());
handled = true;
shapeUtil.getDistanceToShapeBorderFromPoint(labelThresholdShapeList.get(i).getKey(), freeTextShape.getCentralPin());
}
}
}
if (!handled) {
freeTextShape.setName(annotationType);
shapesWithNames.add(freeTextShape);
if (annotationThresholdShapes.size() > 0) {
Collections.sort(annotationThresholdShapeList, new DistanceToShapeComparator());
Shape association = createAssociationBetween(annotationThresholdShapeList.get(0).getKey(),freeTextShape);
shapesWithNames.add(association);
}
}
}
private List getNotExcludedShapesWithType(Page visioPage) {
List shapesWithType = new ArrayList
String excludedStencilsString = importUtil.getStencilSetConfig("FromFreeTextInterpretationExcludedStencils");
String[] excludedStencils = excludedStencilsString.split(",");
for (Shape shape : visioPage.getShapes()) {
String configuredStencilId = importUtil.getStencilIdForName(shape.getName());
if (configuredStencilId == null || "".equals(configuredStencilId))
continue;
Boolean isExcluded = false;
if (excludedStencilsString != null && !"".equals(excludedStencilsString)) {
for (String excludedStencil : excludedStencils) {
if (excludedStencil.equalsIgnoreCase(configuredStencilId))
isExcluded = true;
}
}
if (!isExcluded) {
shapesWithType.add(shape);
}
}
return shapesWithType;
}
private Shape createAssociationBetween(Shape shape, Shape annotation) {
String associationType = importUtil.getStencilSetConfig("labelOnlyAnnotationAssociation");
Shape association = new Shape();
association.setName(associationType);
association.setStartPoint(shape.getCentralPin());
association.setEndPoint(annotation.getCentralPin());
association.setHeight(Math.abs(association.getStartPoint().getY() - association.getEndPoint().getY()));
association.setWidth(Math.abs(association.getStartPoint().getX() - association.getEndPoint().getX()));
Double centralPinX;
Double centralPinY;
if (association.getStartPoint().getY() > association.getEndPoint().getY()) {
centralPinY = association.getStartPoint().getY() + association.getHeight() / 2;
} else {
centralPinY = association.getEndPoint().getY() + association.getHeight() / 2;
}
if (association.getStartPoint().getX() > association.getEndPoint().getX()) {
centralPinX = association.getStartPoint().getX() + association.getWidth() / 2;
} else {
centralPinX = association.getEndPoint().getX() + association.getWidth() / 2;
}
association.setCentralPin(new Point(centralPinX, centralPinY));
return association;
}
}
|
java
| 18 | 0.769018 | 142 | 44.529801 | 151 |
starcoderdata
|
import React from "react";
import { Mutation } from "@treats/graphql";
import { todoMutation, todoQuery } from "@graphql/todo";
import style from "../todographql.css";
const TodoForm = () => (
<Mutation
mutation={todoMutation.CreateListTodo}
refetchQueries={[{ query: todoQuery.GetAllListTodoes }]}
>
{(addTodo, { loading, error }) => {
let input;
return (
<form
onSubmit={e => {
e.preventDefault();
addTodo({ variables: { todoAction: input.value } });
input.value = "";
}}
>
<input
ref={node => {
input = node;
}}
/>
<button className={style.button__green} type="submit">Add Todo
{loading &&
{error && :( Please try again
);
}}
);
export default TodoForm;
|
javascript
| 23 | 0.40865 | 95 | 30.186047 | 43 |
starcoderdata
|
class wxDatePickerCtrl : public wxControl
{
public:
/**
Initializes the object and calls Create() with all the parameters.
*/
wxDatePickerCtrl(wxWindow* parent, wxWindowID id,
const wxDateTime& dt = wxDefaultDateTime,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = wxDP_DEFAULT | wxDP_SHOWCENTURY,
const wxValidator& validator = wxDefaultValidator,
const wxString& name = "datectrl");
/**
@param parent
Parent window, must not be non-@NULL.
@param id
The identifier for the control.
@param dt
The initial value of the control, if an invalid date (such as the
default value) is used, the control is set to today.
@param pos
Initial position.
@param size
Initial size. If left at default value, the control chooses its own
best size by using the height approximately equal to a text control
and width large enough to show the date string fully.
@param style
The window style, should be left at 0 as there are no special
styles for this control in this version.
@param validator
Validator which can be used for additional date checks.
@param name
Control name.
@return @true if the control was successfully created or @false if
creation failed.
*/
bool Create(wxWindow* parent, wxWindowID id,
const wxDateTime& dt = wxDefaultDateTime,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = wxDP_DEFAULT | wxDP_SHOWCENTURY,
const wxValidator& validator = wxDefaultValidator,
const wxString& name = "datectrl");
/**
If the control had been previously limited to a range of dates using
SetRange(), returns the lower and upper bounds of this range. If no
range is set (or only one of the bounds is set), @a dt1 and/or @a dt2
are set to be invalid.
@param dt1
Pointer to the object which receives the lower range limit or
becomes invalid if it is not set. May be @NULL if the caller is not
interested in lower limit.
@param dt2
Same as above but for the upper limit.
@return @false if no range limits are currently set, @true if at least
one bound is set.
*/
virtual bool GetRange(wxDateTime* dt1, wxDateTime* dt2) const = 0;
/**
Returns the currently selected. If there is no selection or the
selection is outside of the current range, an invalid object is
returned.
*/
virtual wxDateTime GetValue() const = 0;
/**
Sets the valid range for the date selection. If @a dt1 is valid, it
becomes the earliest date (inclusive) accepted by the control. If
@a dt2 is valid, it becomes the latest possible date.
@remarks If the current value of the control is outside of the newly
set range bounds, the behaviour is undefined.
*/
virtual void SetRange(const wxDateTime& dt1, const wxDateTime& dt2) = 0;
/**
Changes the current value of the control.
The date should be valid unless the control was created with @c
wxDP_ALLOWNONE style and included in the currently selected range, if
any.
Calling this method does not result in a date change event.
*/
virtual void SetValue(const wxDateTime& dt) = 0;
}
|
c
| 10 | 0.611868 | 79 | 39.236559 | 93 |
inline
|
import {
getInitialState,
reduceActions,
reduceActionsFrom
} from 'redux-preboiled'
import reducer, { increment, decrement, multiply } from './counter.redux'
test('initial state is 0', () => {
expect(getInitialState(reducer)).toBe(0)
})
test('increment', () => {
const state = reduceActions(reducer, increment())
expect(state).toBe(1)
})
test('multiple increments', () => {
const state = reduceActions(reducer, increment(), increment())
expect(state).toBe(2)
})
test('decrement', () => {
const state = reduceActionsFrom(3, reducer, decrement())
expect(state).toBe(2)
})
test('multiply', () => {
const state = reduceActionsFrom(2, reducer, multiply(4))
expect(state).toBe(8)
})
|
javascript
| 13 | 0.672805 | 73 | 22.533333 | 30 |
starcoderdata
|
/**
* Custom channel: {channel}
*/
class {name}
{
onPublish(conn, topic, message, exclude, eligible)
{
// Broadcast message to all subscribers
topic.broadcast(message, exclude, eligible)
}
onSubscribe(conn, topic)
{
}
onUnSubscribe(conn, topic)
{
}
onOpen(conn)
{
}
onClose(conn)
{
}
onCall(conn, id, topic, params)
{
}
onError(conn, e)
{
}
}
|
javascript
| 5 | 0.542 | 54 | 11.5 | 40 |
starcoderdata
|
using System;
namespace Improbable.Gdk.Core
{
///
/// A unique identifier used to look up an entity in SpatialOS.
///
///
/// Instances of this type should be treated as transient identifiers that will not be
/// consistent between different runs of the same simulation.
///
public readonly struct EntityId : IEquatable IComparable IComparable
{
///
/// The value of the EntityId.
///
///
/// Though this value is numeric, you should not perform any mathematical operations on it.
///
public readonly long Id;
///
/// Constructs a new instance of an EntityId.
///
public EntityId(long id)
{
Id = id;
}
///
/// Whether this represents a valid SpatialOS entity ID. Specifically, > 0
///
/// iff valid.
public bool IsValid()
{
return Id > 0;
}
/// <inheritdoc cref="IEquatable{T}" />
public override bool Equals(object obj)
{
if (!(obj is EntityId))
{
return false;
}
return Equals((EntityId) obj);
}
/// <inheritdoc cref="IEquatable{T}" />
public bool Equals(EntityId obj)
{
return Id.Equals(obj.Id);
}
///
/// Returns true if entityId1 is exactly equal to entityId2.
///
public static bool operator ==(EntityId entityId1, EntityId entityId2)
{
return entityId1.Equals(entityId2);
}
///
/// Returns true if entityId1 is not exactly equal to entityId2.
///
public static bool operator !=(EntityId entityId1, EntityId entityId2)
{
return !entityId1.Equals(entityId2);
}
/// <inheritdoc cref="object" />
public override int GetHashCode()
{
var res = 1327;
res = res * 977 + Id.GetHashCode();
return res;
}
/// <inheritdoc cref="object" />
public override string ToString()
{
return Id.ToString();
}
public int CompareTo(EntityId other)
{
return Id.CompareTo(other.Id);
}
public int CompareTo(object obj)
{
if (ReferenceEquals(null, obj))
{
return 1;
}
return obj is EntityId other
? CompareTo(other)
: throw new ArgumentException($"Object must be of type {nameof(EntityId)}");
}
public static bool operator <(EntityId left, EntityId right)
{
return left.CompareTo(right) < 0;
}
public static bool operator >(EntityId left, EntityId right)
{
return left.CompareTo(right) > 0;
}
public static bool operator <=(EntityId left, EntityId right)
{
return left.CompareTo(right) <= 0;
}
public static bool operator >=(EntityId left, EntityId right)
{
return left.CompareTo(right) >= 0;
}
}
}
|
c#
| 18 | 0.520057 | 103 | 27.145161 | 124 |
starcoderdata
|
# import keras
from keras.callbacks import TerminateOnNaN, TensorBoard
import numpy as np
from data_utils import Data, postprocess, mix_tracks
from keras_models import get_gan
import os
from glob import glob
from tqdm import tqdm as tq
from utils import *
from keras_augmented import load_model
def predict_song(tup, model):
list_ = [x[:16000 * 40] for x in tup]
mix_array = mix_tracks(list_)[np.newaxis]
return model.predict([mix_array, sample_latent_noise(mix_array.shape)])[0]
def sample_latent_noise(shape, min_=-1, max_=1):
return (max_ - min_) * np.random.random_sample(shape) + min_
def generator_latent(data_generator):
while 1:
mix, voice = next(data_generator)
yield [mix, sample_latent_noise(mix.shape)], voice
def train_generator(gan, data_generator_train):
mix, voice = next(data_generator_train)
latent_noise = sample_latent_noise(mix.shape)
target = np.ones((mix.shape[0], 1), dtype=np.float32)
return gan.train_on_batch([mix, latent_noise], target)
def train_discriminator(generator, discriminator, data_generator_train):
mix1, voice1 = next(data_generator_train)
mix2, voice2 = next(data_generator_train)
assert mix1.shape[0] == mix2.shape[0]
latent_noise = sample_latent_noise(mix1.shape)
artificial_voice = generator.predict([mix1, latent_noise])
mae = np.mean(np.abs(voice1 - artificial_voice))
mix = np.concatenate([mix1, mix2], axis=0)
voice = np.concatenate([artificial_voice, voice2])
target = np.ones((mix.shape[0], 1), dtype=np.float32)
half = target.shape[0] / 2
assert int(half) == half
target[:int(half)] = 0
stats = discriminator.train_on_batch([mix, voice], target)
stats.append(mae)
return stats
def training_procedure(gan, generator, discriminator, data_generator_train, data_generator_val, nb_steps_gan, database):
# Some setup on the first run. It's just for the timing.
train_generator(gan, data_generator_train)
train_discriminator(generator, discriminator, data_generator_train)
result_dir = "./result/"
mk(result_dir)
generator.fit_generator(generator_latent(data_generator_train), 30, 2)
song = predict_song(database.validation_set[-1], generator)
postprocess(song, result_dir + "first.wav")
for i in tq(range(nb_steps_gan)):
stats_generator = train_generator(gan, data_generator_train)
stats_discriminator = train_discriminator(generator, discriminator, data_generator_train)
tq.write(str(stats_generator + stats_discriminator))
if i % 10 == 0:
song = predict_song(database.validation_set[-1], generator)
postprocess(song, result_dir + "it_" + str(i) + ".wav")
def main():
models_directory = "./models/"
mk(models_directory)
nb_steps_gan = 10000
gan, generator, discriminator = get_gan(24, nb_blocks=2, conv_per_block=10, padding_generator="valid")
generator.compile("adam", "mae")
discriminator.compile("adam", "binary_crossentropy", metrics=["accuracy"])
# We freeze the discriminator in the gan.
discriminator.trainable = False
gan.compile("adam", "binary_crossentropy", metrics=["accuracy"])
database = Data(padding=generator.padding)
training_procedure(gan, generator, discriminator,
database.training_generator(16, 10000),
database.validation_generator(16, 10000), nb_steps_gan, database)
generator.save(models_directory + "model1.h5")
load_model(models_directory + "model1.h5") # to be sure that we can load it afterwards.
postprocess(predict_song(database.training_set[0], generator), "./checks/train_predict.wav")
postprocess(predict_song(database.validation_set[-1], generator), "./checks/val_predict.wav")
if __name__ == "__main__":
main()
|
python
| 14 | 0.683896 | 120 | 34.321101 | 109 |
starcoderdata
|
package models
import (
i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91 "github.com/microsoft/kiota-abstractions-go/serialization"
)
// ComanagementEligibleDevicesSummaryable
type ComanagementEligibleDevicesSummaryable interface {
i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.AdditionalDataHolder
i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable
GetComanagedCount()(*int32)
GetEligibleButNotAzureAdJoinedCount()(*int32)
GetEligibleCount()(*int32)
GetIneligibleCount()(*int32)
GetNeedsOsUpdateCount()(*int32)
SetComanagedCount(value *int32)()
SetEligibleButNotAzureAdJoinedCount(value *int32)()
SetEligibleCount(value *int32)()
SetIneligibleCount(value *int32)()
SetNeedsOsUpdateCount(value *int32)()
}
|
go
| 8 | 0.819005 | 128 | 39.181818 | 22 |
starcoderdata
|
<?php
namespace App\Services;
class OrderService
{
public $stripeService;
public function __construct(StripeService $stripeService)
{
$this->stripeService = $stripeService;
}
public function discount()
{
dump('remise sur le montant : ' .$this->stripeService->amount);
}
}
|
php
| 13 | 0.642633 | 71 | 16.777778 | 18 |
starcoderdata
|
package org.javainaction.slidingwindow;
import java.util.*;
/**
* Given an array of integers and a number k, where 1 <= k <= length of the array,
* compute the maximum values of each subarray of length k.
*
* For example, given array = [10, 5, 2, 7, 8, 7] and k = 3, we should get: [10, 7, 8, 8], since:
*
* 10 = max(10, 5, 2)
* 7 = max(5, 2, 7)
* 8 = max(2, 7, 8)
* 8 = max(7, 8, 7)
* Do this in O(n) time and O(k) space.
* @see SlidingWindowMaximum
*/
public class MaxSubArrayK {
public static void printMaximums(int[] a, int k) {
int n = a.length;
Deque deck = new ArrayDeque<>();
List result = new ArrayList<>();
for (int i = 0; i < n; i++) {
//if value we are adding is bigger than any elements in queue, remove all of them so we do not keep
//track of them anymore
while (!deck.isEmpty() && a[i] >= deck.peekLast()[0]) deck.pollLast();
//add value with its index
deck.offer(new int[] {a[i], i});
//if index of first val in queue is beyond the range of K pop that out
//removing last max elements that is going out of range
while (!deck.isEmpty() && deck.peekFirst()[1] <= i - k) deck.pollFirst();
//when we have hit the k window rage, get the first of the maximum values
if (i >= k - 1) result.add(Objects.requireNonNull(deck.peekFirst())[0]);
}
System.out.println(result);
}
public static void main(String[] arg) {
int[] array = new int[] {10, 5, 2 , 7, 8, 7};
printMaximums(array, 3);
printMaximums(array, 2);
}
}
|
java
| 16 | 0.570999 | 111 | 36.772727 | 44 |
starcoderdata
|
def add_bases(self, bases:str):
#Strip whitespace
bases = bases.strip()
#Make sure 'bases' only contains ACTGs
if (re.match("^[ACTGURYKMSWBDHVN-]+$", bases) is None):
raise ValueError("Parameter 'bases' must contain only standard "
+ "IUB/IUPAC codes.")
self.bases += bases
self.ccount += bases.count("C")
self.gcount += bases.count("G")
self.acount += bases.count("A")
self.tcount += bases.count("T")
self.length += len(bases)
|
python
| 10 | 0.537634 | 76 | 36.266667 | 15 |
inline
|
import React from 'react';
import { storiesOf } from '@storybook/react';
import { text, select, boolean } from '@storybook/addon-knobs';
import { action } from '@storybook/addon-actions';
import OptionsHelper from '../../utils/helpers/options-helper';
import notes from './documentation';
import Message from './message.component';
storiesOf('Message', module).add(
'default',
() => {
const variant = select('type', OptionsHelper.messages, Message.defaultProps.variant);
const open = boolean('open', Message.defaultProps.open);
const title = text('title');
const transparent = boolean('transparent', Message.defaultProps.transparent);
const children = text('children', 'This is some information from the Message Component.');
// Allows onDismiss knob to be a boolean, but pass a function to component
const onDismiss = boolean('onDismiss', true);
const testOnDismiss = onDismiss ? (evt) => { action('click')(evt); } : undefined;
return (
<Message
variant={ variant } open={ open }
title={ title } transparent={ transparent }
onDismiss={ testOnDismiss }
>
{children}
);
},
{
notes: { markdown: notes },
knobs: { escapeHTML: false }
}
);
|
javascript
| 13 | 0.669663 | 94 | 35.081081 | 37 |
starcoderdata
|
def get_path_or_error(path):
"""
returns the path or exists with an error, if it is not existing
"""
path = os.path.expanduser(path)
if not os.path.exists(path) or not os.path.isdir(path):
sys.exit("The path '%s' does not exist. Abort!" % path)
return path
|
python
| 10 | 0.629758 | 67 | 31.222222 | 9 |
inline
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.CodeAnalysis.Editor.Commands;
using Microsoft.VisualStudio.Text.Operations;
using VSCommanding = Microsoft.VisualStudio.Commanding;
using VSEditorCommands = Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
namespace Microsoft.CodeAnalysis.Editor.Implementation.BlockCommentEditing
{
///
/// This class implements both legacy and modern editor command handler becuase TypeScript
/// uses it to implement legacy Microsoft.CodeAnalysis.Editor.ICommandHandler based command.
/// Once TypeScript migrates to the modern editor commanding (tracked by
/// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/548409), the part implementing
/// Microsoft.CodeAnalysis.Editor.ICommandHandler can be deleted.
///
internal abstract class AbstractBlockCommentEditingCommandHandler : BaseAbstractBlockCommentEditingCommandHandler,
ICommandHandler
VSCommanding.ICommandHandler
{
protected AbstractBlockCommentEditingCommandHandler(
ITextUndoHistoryRegistry undoHistoryRegistry,
IEditorOperationsFactoryService editorOperationsFactoryService)
: base(undoHistoryRegistry, editorOperationsFactoryService)
{
}
#region Legacy ICommandHandler
public CommandState GetCommandState(ReturnKeyCommandArgs args, Func nextHandler) => nextHandler();
public void ExecuteCommand(ReturnKeyCommandArgs args, Action nextHandler)
{
if (TryHandleReturnKey(args.SubjectBuffer, args.TextView))
{
return;
}
nextHandler();
}
#endregion
#region Modern editor ICommandHandler
public string DisplayName => EditorFeaturesResources.Block_Comment_Editing;
public VSCommanding.CommandState GetCommandState(VSEditorCommands.ReturnKeyCommandArgs args) => VSCommanding.CommandState.Unspecified;
public bool ExecuteCommand(VSEditorCommands.ReturnKeyCommandArgs args, VSCommanding.CommandExecutionContext context)
{
return TryHandleReturnKey(args.SubjectBuffer, args.TextView);
}
#endregion
}
}
|
c#
| 12 | 0.748273 | 161 | 42.433333 | 60 |
starcoderdata
|
#pragma once
#include
namespace ln {
namespace detail {
// RefObject のキャッシュ管理。
// RefObject を作りたいときは、まず先に findObject を呼び出してキャッシュ探す。なければ呼び出し側で作って registerObject()。
// RefObject は普通に makeRef で作ってよい。また、作った直後は registerObject() で登録しておく。
// 定期的に collectUnreferenceObjects() を呼び出すことで、aliveList からしか参照されていない Object を freeList に移動する。
// ※frameUpdate で呼ばなくても、オブジェクトを new する時でも構わない。
// RefObject を release するとき、その直前で releaseObject() に指定して呼び出しておくと、明示的に freeList に入れることができる。
// 最大オブジェクト数とメモリ量は free オブジェクトの条件。alive は影響しない。
// 最大オブジェクト数とメモリ量は or 条件。どちらかが満たされたら古いオブジェクトを削除する。0 の場合は無視。
template<class TKey, class TObject>
class ObjectCache
{
public:
ObjectCache()
: m_maxCacheObjectCount(0)
, m_maxCacheMemory(0)
, m_aliveList()
, m_freeList()
, m_freeObjectMemory(0)
{}
void init(uint32_t maxCacheObjectCount = 64, uint32_t maxCacheMemory = 0)
{
dispose();
m_maxCacheObjectCount = maxCacheObjectCount;
m_maxCacheMemory = maxCacheMemory;
}
void dispose()
{
m_aliveList.clear();
m_freeList.clear();
m_aliveListItr = m_aliveList.begin();
m_maxCacheObjectCount = 0;
m_maxCacheMemory = 0;
m_freeObjectMemory = 0;
}
Ref findObject(const TKey& key)
{
if (LN_REQUIRE(!isDisposed())) return nullptr;
for (auto itr = m_aliveList.begin(); itr != m_aliveList.end(); ++itr) {
if (itr->key == key) {
return itr->obj;
}
}
for (auto itr = m_freeList.begin(); itr != m_freeList.end(); ++itr) {
if (itr->key == key) {
m_freeObjectMemory -= itr->memorySize;
m_aliveList.splice(m_aliveList.end(), std::move(m_freeList), itr); // move to tail
m_aliveListItr = m_aliveList.end();
return m_aliveList.back().obj;
}
}
return nullptr;
}
void registerObject(const TKey& key, TObject* obj, uint32_t memorySize = 0)
{
if (LN_REQUIRE(!isDisposed())) return;
if (obj) {
m_aliveList.push_back({ key, obj, memorySize });
m_aliveListItr = m_aliveList.end();
}
}
void releaseObject(TObject* obj)
{
if (LN_REQUIRE(!isDisposed())) return;
if (obj) {
auto itr = m_aliveList.begin();
for (; itr != m_aliveList.end(); ++itr) {
if (itr->obj == obj) {
break;
}
}
if (LN_REQUIRE(itr != m_aliveList.end())) return; // not contained m_aliveList
m_aliveListItr = m_aliveList.end();
if (itr->memorySize > m_maxCacheMemory) {
// キャッシュに入らない大きなオブジェクトはここで削除
m_aliveList.erase(itr);
}
else {
m_freeList.splice(m_freeList.end(), std::move(m_aliveList), itr);
m_freeObjectMemory += itr->memorySize;
collectOldObject();
}
}
}
void collectUnreferenceObjects(bool all)
{
auto stepCollect = [this]() {
if (RefObjectHelper::getReferenceCount(m_aliveListItr->obj) == 1) // m_aliveList からのみ参照されている
{
if (m_aliveListItr->memorySize > m_maxCacheMemory) {
// キャッシュに入らない大きなオブジェクトはここで削除
m_aliveListItr = m_aliveList.erase(m_aliveListItr);
}
else {
m_freeList.push_back(*m_aliveListItr);
m_freeObjectMemory += m_aliveListItr->memorySize;
m_aliveListItr = m_aliveList.erase(m_aliveListItr);
collectOldObject();
}
}
else {
++m_aliveListItr;
}
};
if (all) {
m_aliveListItr = m_aliveList.begin();
for (; m_aliveListItr != m_aliveList.end();)
{
stepCollect();
//if (RefObjectHelper::getReferenceCount(itr->obj) == 1) // m_aliveList からのみ参照されている
//{
// if (itr->memorySize > m_maxCacheMemory) {
// // キャッシュに入らない大きなオブジェクトはここで削除
// itr = m_aliveList.erase(itr);
// }
// else {
// m_freeList.push_back(*itr);
// m_freeObjectMemory += itr->memorySize;
// itr = m_aliveList.erase(itr);
// collectOldObject();
// }
//}
//else {
// ++itr;
//}
}
}
else {
if (m_aliveListItr == m_aliveList.end()) {
// restart
m_aliveListItr = m_aliveList.begin();
}
if (m_aliveListItr != m_aliveList.end()) {
stepCollect();
}
}
}
std::vector aliveObjects() const
{
std::vector result;
for (auto& e : m_aliveList) result.push_back(e.obj);
return result;
}
std::vector freeObjects() const
{
std::vector result;
for (auto& e : m_freeList) result.push_back(e.obj);
return result;
}
private:
bool isDisposed() const
{
return m_maxCacheObjectCount == 0 && m_maxCacheMemory == 0;
}
void collectOldObject()
{
if (m_maxCacheObjectCount > 0)
{
int count = static_cast - m_maxCacheObjectCount);
if (count > 0) {
for (int i = 0; i < count; i++) {
m_freeList.pop_front();
}
}
}
if (m_maxCacheMemory > 0)
{
while (!m_freeList.empty() && m_freeObjectMemory > m_maxCacheMemory)
{
m_freeObjectMemory -= m_freeList.front().memorySize;
m_freeList.pop_front();
}
}
}
struct Entry
{
TKey key;
Ref obj;
uint32_t memorySize;
};
typedef typename std::list EntryList;
typedef typename std::list EntryListIterator;
uint32_t m_maxCacheObjectCount;
uint32_t m_maxCacheMemory;
EntryList m_aliveList;
EntryList m_freeList; // front:oldest, back:newest
EntryListIterator m_aliveListItr;
size_t m_freeObjectMemory;
};
} // namespace detail
} // namespace ln
|
c++
| 23 | 0.648032 | 95 | 22.167401 | 227 |
starcoderdata
|
##########################################################################
# Copyright (c) 2009, ETH Zurich.
# All rights reserved.
#
# This file is distributed under the terms in the attached LICENSE file.
# If you do not find this file, copies can be found by writing to:
# ETH Zurich D-INFK, Universitaetstrasse 6, CH-8092 Zurich. Attn: Systems Group.
##########################################################################
import re
import tests
from common import TestCommon
from results import PassFailResult
@tests.add_test
class MemTest(TestCommon):
'''prints out free and total memory after system boot up'''
name = "freemem"
def get_modules(self, build, machine):
modules = super(MemTest, self).get_modules(build, machine)
modules.add_module("freemem")
return modules
def get_finish_string(self):
return "freemem done!"
def process_data(self, testdir, rawiter):
# the test passed iff the last line is the finish string
lastline = ''
for line in rawiter:
lastline = line
passed = lastline.startswith(self.get_finish_string())
return PassFailResult(passed)
|
python
| 12 | 0.598131 | 80 | 33.617647 | 34 |
starcoderdata
|
'use strict'
// ----------------------------------------------------------------------------
const assert = require ('assert')
, testLedgerItem = require ('./test.ledgerItem')
// ----------------------------------------------------------------------------
module.exports = async (exchange, code) => {
if (exchange.has.fetchLedger) {
const items = await exchange.fetchLedger (code)
assert (items instanceof Array)
console.log ('Fetched', items.length, 'ledger items')
const now = Date.now ()
for (let i = 0; i < items.length; i++) {
testLedgerItem (exchange, items[i], code, now)
if (i > 0) {
assert (items[i].timestamp >= items[i - 1].timestamp)
}
}
if (exchange.has.fetchLedgerItem) {
const { id } = items.pop ()
let item = await exchange.fetchLedgerItem (id)
if (Array.isArray (item)) {
item = item[0]
}
testLedgerItem (exchange, item, code, now)
}
} else {
console.log ('Fetching ledger items not supported')
}
}
|
javascript
| 11 | 0.459087 | 79 | 26 | 43 |
starcoderdata
|
import faker from "faker";
import puppeteer from "puppeteer";
const APP = "http://localhost:3000";
const user = {
email: faker.internet.email(),
password:
};
let page;
let browser;
beforeAll(async () => {
browser = await puppeteer.launch({
headless: false,
slowMo: 80
});
page = await browser.newPage();
});
afterAll(() => {
browser.close();
});
describe("User Form", () => {
test(
"can create a user",
async () => {
await page.goto(APP);
await page.waitForSelector("form[name=userForm]");
await page.click("input[name=email]");
await page.type("input[name=email]", user.email);
await page.click("input[name=password]");
await page.type("input[name=password]", user.password);
await page.$('button[disabled]') !== null;
await page.click("button[name=btnCreateUser]");
},
16000
);
});
|
javascript
| 13 | 0.612403 | 61 | 21.02439 | 41 |
starcoderdata
|
@page
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
上传大文件示例 - Thinksea.Net.FileUploader_AspNetCoreDemo
<script type="text/javascript" charset="utf-8" src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js">
<script type="text/javascript" charset="utf-8" src="lib/jsext-1.2.0/jsext.min.js">
<script type="text/javascript" src="https://cdn.bootcss.com/crypto-js/4.0.0/crypto-js.min.js">
<script type="text/javascript" charset="utf-8" src="Thinksea.Net.FileUploader.js" asp-append-version="true">
<script type="text/javascript" charset="utf-8" src="JavascriptUploadFileDemo.js" asp-append-version="true">
<div id="ctl5" class="form-group">
<button type="button" class="btn btn-default" data-clickupload="true" data-dragoverupload="true">拖入可上传
<div data-dragoverupload="true">
<div class="clearfix fileinsertmark">
<input type="file" multiple="multiple" class="fileUpload" style="visibility:hidden; width:0px; height: 0px;" />
<input type="hidden" name="fileUrls" />
|
c#
| 8 | 0.688502 | 122 | 52.148148 | 27 |
starcoderdata
|
import { useRef, useEffect } from 'react';
const useOnMouseLeave = onMouseLeave => {
const element = useRef(null);
useEffect(() => {
if (element.current) {
element.current.addEventListener("mouseleave", onMouseLeave);
}
return () => {
if (element.current) {
element.current.removeEventListener("mouseleave", onMouseLeave);
}
};
}, []);
return element;
};
export default useOnMouseLeave;
|
javascript
| 19 | 0.613187 | 72 | 23.388889 | 18 |
starcoderdata
|
package painting
import "github.com/sirtalin/democrart/internal/model"
type Store interface {
CreatePainting(*model.Artist, *model.Painting) error
CreateImage(*model.Painting, *model.Image) error
GetPainting(string, string) (*model.Painting, error)
GetPaintings(*model.Painting) ([]*model.Artist, error)
GetPaintingsImages(*model.Painting) ([]*model.Artist, error)
}
|
go
| 10 | 0.772727 | 61 | 33 | 11 |
starcoderdata
|
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\Mail\Test\Unit;
/**
* test Magento\Framework\Mail\Message
*/
class MessageTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\Mail\Message
*/
protected $message;
protected function setUp()
{
$this->message = new \Magento\Framework\Mail\Message();
}
public function testSetBodyHtml()
{
$this->message->setBodyHtml('body');
$part = $this->message->getBody()->getParts()[0];
$this->assertEquals('text/html', $part->getType());
$this->assertEquals('quoted-printable', $part->getEncoding());
$this->assertEquals('utf-8', $part->getCharset());
$this->assertEquals('body', $part->getContent());
$this->assertEquals('inline', $part->getDisposition());
}
public function testSetBodyText()
{
$this->message->setBodyText('body');
$part = $this->message->getBody()->getParts()[0];
$this->assertEquals('text/plain', $part->getType());
$this->assertEquals('quoted-printable', $part->getEncoding());
$this->assertEquals('utf-8', $part->getCharset());
$this->assertEquals('body', $part->getContent());
$this->assertEquals('inline', $part->getDisposition());
}
}
|
php
| 12 | 0.611151 | 70 | 29.021739 | 46 |
starcoderdata
|
def plot_tFac_Conc(ax, tFac, respDF):
"""Plots tensor factorization of Conc"""
concs = respDF.Dose.unique()
concFacs = tFac[1][2]
markersConcs = [".", ".", ".", "."]
for i in range(0, concFacs.shape[1]):
ax.plot(concs, concFacs[:, i], marker=markersConcs[i], label="Component " + str(i + 1), markersize=5)
ax.legend()
ax.set(title="Concentration", xlabel="Concentration (nM)", xlim=(concs[-1], concs[0]), ylabel="Component Weight", ylim=(0, 1), xscale='log')
|
python
| 13 | 0.610887 | 144 | 44.181818 | 11 |
inline
|
using System.Windows.Input;
using System;
using System.Windows;
namespace InputCapture
{
public interface IKeyboardCapture
{
event EventHandler KeyboardNotification;
event EventHandler KeyboardReset;
void PreviewKeyDown(object sender, KeyEventArgs e);
void KeyDown(object sender, KeyEventArgs e);
void KeyUp(object sender, KeyEventArgs e);
void PreviewKeyUp(object sender, KeyEventArgs e);
void Reset();
void RegisterWindow(UIElement window);
int LookupIntKey(Key key);
char LookupCharKey(Key key);
void SuspendNotifications(bool value);
}
}
|
c#
| 9 | 0.720317 | 79 | 32 | 23 |
starcoderdata
|
package com.omilia.channels.commons.responses;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.omilia.channels.commons.DiamantApp;
import java.util.ArrayList;
import java.util.List;
public class StatusResponse extends Response {
// constants
protected static final String DEFAULT_MESSAGE = "Service is operating normally";
// attributes
public final String message;
public final String version;
@JsonProperty("diamant_apps")
public final List diamantApps;
// constructors
public StatusResponse(String version) {
this(version, DEFAULT_MESSAGE, new ArrayList<>());
}
public StatusResponse(String version, String message) {
this(version, message, new ArrayList<>());
}
public StatusResponse(String version, List diamantApps) {
this(version, DEFAULT_MESSAGE, new ArrayList<>());
}
public StatusResponse(String version, String message, List diamantApps) {
super(true);
this.version = version;
this.message = message;
this.diamantApps = diamantApps;
}
}
|
java
| 10 | 0.700441 | 89 | 24.795455 | 44 |
starcoderdata
|
// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
/* Copyright 2013-2016 IBM Corp. */
#ifndef __STB_STATUS_CODES_H
#define __STB_STATUS_CODES_H
/* general return codes */
#define STB_ERROR -1
#define STB_ARG_ERROR -2
#define STB_DRIVER_ERROR -3
/* secure boot */
#define STB_SECURE_MODE_DISABLED 100
#define STB_VERIFY_FAILED -100
/* trusted boot */
#define STB_TRUSTED_MODE_DISABLED 200
#define STB_MEASURE_FAILED -200
/* TPM */
#define STB_NO_TPM_INITIALIZED 300
#define STB_TPM_OVERFLOW -300
#define STB_TPM_TIMEOUT -301
#endif /* __STB_STATUS_CODES_H */
|
c
| 3 | 0.699828 | 58 | 22.32 | 25 |
starcoderdata
|
# -*- coding: utf-8 -*-
"""
Dumbed-down Hive hook somewhat-inspired-by :py:mod:`airflow.hooks.hive_hooks`,
using :py:class:`pyhive.hive.Connection` backend instead of wrapping the CLI.
"""
from airflow.hooks.base_hook import BaseHook
from pyhive import hive
# noinspection PyAbstractClass
class PyHiveHook(BaseHook):
"""Interact with Hive via PyHive.
:param str hive_conn_id: Connection ID to fetch connection info.
:param str username: Effective user for Hive connection.
:param dict configuration: Hive connection properties (`set
"""
def __init__(self, hive_conn_id: str = 'hiveserver2_default',
username: str = None, configuration: dict = None):
super().__init__(source='hive')
self.hive_conn_id = hive_conn_id
self.username = username
self.configuration = configuration or {
'hive.exec.dynamic.partition.mode': 'nonstrict'
}
def get_conn(self) -> hive.Connection:
connection = self.get_connections(self.hive_conn_id)[0]
if self.username:
username = self.username
else:
username = connection.login
return hive.Connection(host=connection.host, port=connection.port,
username=username,
configuration=self.configuration)
|
python
| 11 | 0.633896 | 80 | 33.075 | 40 |
starcoderdata
|
@Test
@SuppressWarnings("unchecked")
public void bigDecimalSerializationTests() {
SimpleMapper mapper = SimpleMapper.getInstance();
String NUMBER = "number";
String ONE = "0.00000001";
String ZERO = "0.00000000";
SimpleNumber one = new SimpleNumber(ONE);
SimpleNumber zero = new SimpleNumber(ZERO);
// verify hash map result
Map<String, Object> mapOne = mapper.getMapper().readValue(one, Map.class);
// numeric value is preserved
Assert.assertEquals(ONE, mapOne.get(NUMBER));
// ensure that ZERO is converted to "0"
Map<String, Object> mapZero = mapper.getMapper().readValue(zero, Map.class);
Assert.assertEquals("0", mapZero.get(NUMBER));
// verify PoJo class conversion behavior - this will return the original object because the class is the same
SimpleNumber numberOne = mapper.getMapper().readValue(one, SimpleNumber.class);
Assert.assertEquals(numberOne.number, one.number);
// this will pass thru the serializer
String zeroValue = mapper.getMapper().writeValueAsString(zero);
SimpleNumber numberZero = mapper.getMapper().readValue(zeroValue, SimpleNumber.class);
// the original number has the zero number with many zeros after the decimal
Assert.assertEquals("0E-8", zero.number.toString());
Assert.assertEquals(ZERO, zero.number.toPlainString());
// the converted BigDecimal gets a zero number without zeros after the decimal
Assert.assertEquals("0", numberZero.number.toString());
// verify map to PoJo serialization behavior
SimpleNumber number0 = mapper.getMapper().readValue(mapZero, SimpleNumber.class);
Assert.assertTrue(mapper.isZero(number0.number));
Assert.assertTrue(mapper.isZero(zero.number));
// the two zero objects are different because of precision
Assert.assertNotEquals(number0.number, zero.number);
SimpleNumber number1 = mapper.getMapper().readValue(mapOne, SimpleNumber.class);
// non-zero numbers are exactly the same
Assert.assertEquals(number1.number, one.number);
}
|
java
| 9 | 0.687184 | 117 | 57.864865 | 37 |
inline
|
//------------------------------------------------------------
// Author: 烟雨迷离半世殇
// Mail:
// Data: 2019年8月22日 21:10:35
//------------------------------------------------------------
using System;
using Sirenix.OdinInspector;
namespace ETModel.TheDataContainsAction
{
public class NP_ClassForStoreAction
{
///
/// 归属的UnitID
///
[HideInEditorMode]
public long Unitid;
///
/// 归属的运行时行为树id
///
[HideInEditorMode]
public long RuntimeTreeID;
[HideInEditorMode]
public Action m_Action;
[HideInEditorMode]
public Func m_Func1;
[HideInEditorMode]
public Func<bool, NPBehave.Action.Result> m_Func2;
///
/// 获取将要执行的委托函数,也可以在这里面做一些初始化操作
///
///
public virtual Action GetActionToBeDone()
{
return null;
}
public virtual Func GetFunc1ToBeDone()
{
return null;
}
public virtual Func<bool, NPBehave.Action.Result> GetFunc2ToBeDone()
{
return null;
}
public NPBehave.Action _CreateNPBehaveAction()
{
GetActionToBeDone();
if (m_Action != null)
{
return new NPBehave.Action(this.m_Action);
}
GetFunc1ToBeDone();
if (m_Func1 != null)
{
return new NPBehave.Action(m_Func1);
}
GetFunc2ToBeDone();
if (m_Func2 != null)
{
return new NPBehave.Action(m_Func2);
}
Log.Info("_CreateNPBehaveAction失败,因为没有找到可以绑定的委托");
return null;
}
}
}
|
c#
| 15 | 0.484093 | 76 | 22.886076 | 79 |
starcoderdata
|
namespace Microsoft.Maui.Controls.Design
{
public class LinearItemsLayoutDesignTypeConverter : KnownValuesDesignTypeConverter
{
public LinearItemsLayoutDesignTypeConverter()
{
}
protected override string[] KnownValues
=> new string[] { "Vertical", "Horizontal" };
}
}
|
c#
| 10 | 0.763251 | 83 | 22.666667 | 12 |
starcoderdata
|
from django.db import models
from django.conf import settings
import os
import uuid
# Create your models here.
class BaseModel(models.Model):
insert_time = models.DateTimeField(auto_now_add=True, verbose_name='插入时间')
update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')
class Meta:
abstract = True
class AppModel(BaseModel):
app_name = models.CharField(max_length=20, help_text='app的名称', verbose_name='名称')
app_id = models.CharField(max_length=50, null=True, blank=True)
app_secret = models.CharField(max_length=50, null=True, blank=True)
forward_url = models.URLField(verbose_name='转发的网址', help_text='收到的微信消息都会发送到该url上')
debug_url = models.URLField(verbose_name='debug网址', help_text='错误和调试信息会发送到该网址上')
token = models.CharField(max_length=32, help_text='生成签名的必要参数', verbose_name='token')
bind_user = models.OneToOneField('WxUser', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="绑定的微信用户")
class Meta:
verbose_name_plural = verbose_name = '对接应用'
@classmethod
def create_app(cls):
app_id, app_secret = uuid.uuid4().hex, uuid.uuid1().hex
try:
cls.objects.get(app_id=app_id)
except cls.DoesNotExist:
return app_id, app_secret
return cls.create_app()
@property
def puid_pkl(self):
"""存储puid pkl的路径 保证信息的唯一性"""
return os.path.join(settings.PKL_PATH, f'{self.app_id}_puid.pkl')
def cache_pkl(self, delete=False):
cache_pkl = os.path.join(settings.PKL_PATH, f'{self.app_id}_cache.pkl')
"""重新登录的时候需要删除原来的,不然会卡在那里"""
if delete is True:
try:
os.remove(cache_pkl)
except FileNotFoundError:
pass
return cache_pkl
def __str__(self):
return self.app_name
class WxUser(BaseModel):
SEX_CHOICES = (
(1, '男'),
(2, '女')
)
puid = models.CharField(max_length=15, primary_key=True, help_text='微信用户的外键', verbose_name='PUID')
name = models.CharField(max_length=32, verbose_name='名称', null=True)
nick_name = models.CharField(max_length=32, verbose_name='昵称', null=True)
user_name = models.CharField(max_length=80, verbose_name='用户名', null=True)
remark_name = models.CharField(max_length=32, verbose_name='备注名', null=True)
avatar = models.URLField(verbose_name="头像")
signature = models.CharField(max_length=255, verbose_name="签名", null=True)
sex = models.IntegerField(choices=SEX_CHOICES, verbose_name="性别", null=True)
province = models.CharField(max_length=15, verbose_name="省", null=True)
city = models.CharField(max_length=15, verbose_name="市", null=True)
is_friend = models.BooleanField(null=True, verbose_name='和我有好友关系')
friend = models.BooleanField(null=True, verbose_name='我的好友')
owner = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, related_name='wxuser_owner')
class Meta:
verbose_name_plural = verbose_name = '微信用户'
def __str__(self):
return self.remark_name or self.nick_name or self.name
class WxGroup(BaseModel):
puid = models.CharField(max_length=15, primary_key=True)
name = models.CharField(max_length=32, verbose_name='名称')
nick_name = models.CharField(max_length=32, verbose_name='昵称')
user_name = models.CharField(max_length=80)
avatar = models.URLField(verbose_name='头像')
members = models.ManyToManyField(WxUser, related_name='members', verbose_name='群员')
owner = models.ForeignKey(WxUser, on_delete=models.SET_NULL, null=True, verbose_name='群归属')
class Meta:
verbose_name_plural = verbose_name = '微信群组'
class WxMps(BaseModel):
puid = models.CharField(max_length=15, primary_key=True)
name = models.CharField(max_length=32, verbose_name='名称')
nick_name = models.CharField(max_length=32, verbose_name='昵称')
province = models.CharField(max_length=15, verbose_name="省", null=True)
city = models.CharField(max_length=15, verbose_name="市", null=True)
signature = models.CharField(max_length=255, verbose_name="签名", null=True)
owner = models.ForeignKey(WxUser, on_delete=models.SET_NULL, null=True, verbose_name='群归属')
class Meta:
verbose_name_plural = verbose_name = '微信公众号'
def __str__(self):
return self.name
class Message(BaseModel):
TYPE_CHOICES = (
('Text', '文本'),
('Map', '位置'),
('Card', '名片'),
('Note', '提示'),
('Sharing', '分享'),
('Picture', '图片'),
('Recording', '语音'),
('Attachment', '文件'),
('Video', '视频'),
('Friends', '好友请求'),
('System', '系统'),
)
id = models.BigIntegerField(primary_key=True)
type = models.CharField(max_length=15, choices=TYPE_CHOICES, verbose_name='消息类型')
create_time = models.DateTimeField(verbose_name='创建时间')
receive_time = models.DateTimeField(verbose_name='接受时间')
is_at = models.BooleanField(default=False, null=True, verbose_name='是否@')
send_user = models.ForeignKey(WxUser, on_delete=models.SET_NULL, null=True, related_name='send_user',
verbose_name='主动发送消息的用户')
send_group = models.ForeignKey(WxGroup, on_delete=models.SET_NULL, null=True, verbose_name='主动发送消息的群组')
maps = models.ForeignKey(WxMps, on_delete=models.SET_NULL, null=True, verbose_name='公众号')
receiver = models.ForeignKey(WxUser, on_delete=models.SET_NULL, null=True, related_name='receiver',
verbose_name='接受信息的用户')
receiver_group = models.ForeignKey(WxGroup, on_delete=models.SET_NULL, null=True, related_name='receiver_group',
verbose_name='接受信息的群组')
owner = models.ForeignKey(WxUser, on_delete=models.SET_NULL, null=True, related_name='msg_owner',
verbose_name='信息的拥有者')
class Meta:
verbose_name = verbose_name_plural = '消息记录'
def __str__(self):
return f'{self.type}-{self.owner.name}'
class BaseMessage(BaseModel):
message = models.OneToOneField(Message, on_delete=models.SET_NULL, null=True)
class Meta:
abstract = True
class TextMessage(BaseMessage):
text = models.CharField(max_length=2048, verbose_name='文本内容')
class Meta:
verbose_name = verbose_name_plural = '文本消息'
class MapMessage(BaseMessage):
x = models.FloatField()
y = models.FloatField()
scale = models.IntegerField()
label = models.CharField(max_length=255)
maptype = models.IntegerField()
poiname = models.CharField(max_length=255)
poiid = models.CharField(max_length=255, blank=True)
url = models.CharField(max_length=500)
text = models.CharField(max_length=255)
class Meta:
verbose_name = verbose_name_plural = '位置消息'
class SharingMessage(BaseMessage):
url = models.CharField(max_length=500)
text = models.CharField(max_length=50)
class Meta:
verbose_name = verbose_name_plural = '分享消息'
class PictureMessage(BaseMessage):
file_name = models.CharField(max_length=255, verbose_name='文件名', blank=True)
url = models.CharField(verbose_name='文件地址', max_length=500)
img_height = models.IntegerField(verbose_name='图片高度', null=True)
img_width = models.IntegerField(verbose_name='图片宽度', null=True)
class Meta:
verbose_name = verbose_name_plural = '图片消息'
class RecordingMessage(BaseMessage):
voice_length = models.BigIntegerField(null=True, verbose_name='录音时间')
url = models.CharField(max_length=500)
file_name = models.CharField(max_length=255, blank=True, verbose_name='文件名')
class Meta:
verbose_name = verbose_name_plural = '录音消息'
class AttachmentMessage(BaseMessage):
file_name = models.CharField(max_length=255, blank=True)
file_size = models.CharField(max_length=20, null=True)
url = models.CharField(max_length=500)
class Meta:
verbose_name = verbose_name_plural = '文件消息'
class VideoMessage(BaseMessage):
play_length = models.IntegerField(null=True)
file_name = models.CharField(max_length=255, blank=True)
url = models.CharField(max_length=500)
class Meta:
verbose_name = verbose_name_plural = '视频消息'
class Friends(BaseMessage):
text = models.CharField(max_length=255)
class Meta:
verbose_name = verbose_name_plural = '好友请求'
|
python
| 12 | 0.658881 | 120 | 35.618421 | 228 |
starcoderdata
|
#include "bootsector.h"
extern uint8_t *FILE_SYSTEM;
BOOT_SECTOR PBS_BOOT_SEC = {0};
uint16_t BYTES_PER_SECTOR = 0;
void readBootSector()
{
PBS_BOOT_SEC = *(BOOT_SECTOR*)FILE_SYSTEM;
BYTES_PER_SECTOR = PBS_BOOT_SEC.bytes_per_sector;
}
BOOT_SECTOR* getBootSector(uint8_t* fileSystem)
{
return (BOOT_SECTOR*)fileSystem;
}
void printBootSector(BOOT_SECTOR* bootSector)
{
printf("Bytes per sector = %d\n", bootSector->bytes_per_sector);
printf("Sectors per cluster = %d\n", bootSector->sectors_per_cluster);
printf("Number of FATs = %d\n", bootSector->number_of_FATs);
printf("Number of reserved sectors = %d\n", bootSector->number_of_reserved_sectors);
printf("Max number of root entries = %d\n", bootSector->max_root_dir_entries);
printf("Total sector count = %d\n", bootSector->total_sector_count);
printf("Sectors per FAT = %d\n", bootSector->sectors_per_FAT);
printf("Sectors per track = %d\n", bootSector->sectors_per_track);
printf("Number of heads = %d\n", bootSector->number_of_heads);
printf("Boot signiture (in hex) = 0x%x\n", bootSector->boot_signature);
printf("Volume ID (in hex) = 0x%x\n", bootSector->volume_id);
printf("OEM Name = ");
for (int i = 0; i < 8 || bootSector->OEM_name[i] == '\0'; i++)
{
printf("%c", bootSector->OEM_name[i]);
}
printf("\nVolume label = ");
for (int i = 0; i < 11 || bootSector->volume_label[i] == '\0'; i++)
{
printf("%c", bootSector->volume_label[i]);
}
printf("\nFile system type = ");
for (int i = 0; i < 8 || bootSector->file_system_type[i] == '\0'; i++)
{
printf("%c", bootSector->file_system_type[i]);
}
printf("\n");
}
|
c
| 10 | 0.569049 | 90 | 33.462963 | 54 |
starcoderdata
|
public static void main(String[] args) {
// Each function that is added to the ParserContext is essentially a singleton, since it keeps no state.
FunctionManager.getInstance().addPreprocessorFunction(ArpeggiatedChordFunction.getInstance());
// There are two rounds of Staccato parsing. The first round, "preprocessing," expands
// special functions and other capabilities to their Staccato representations.
// The FunctionPreprocessor expands preprocessor functions. Note that Staccato has
// preprocessor functions, which are resolved before the Staccato string is parsed,
// and subparser functions, which are resolved while the Staccato string is being parsed.
// This is demonstrating only the preprocessor.
FunctionPreprocessor preprocessor = FunctionPreprocessor.getInstance();
// Now, let's see what happens when we preprocess a string that contains a function!
System.out.println(preprocessor.preprocess(":ARPEGGIATED(Cmajq)", (StaccatoParserContext)null));
Player player = new Player();
player.play(":ARPEGGIATED(Cmajq) Cw");
}
|
java
| 9 | 0.765138 | 106 | 59.611111 | 18 |
inline
|
/* eslint-disable consistent-return */
import jwt from 'jsonwebtoken';
import httpResponse from '../helpers/http-response';
const checkSuperUserToken = (req, res, next) => {
const header = req.headers.authorization;
try {
if (typeof header !== 'undefined') {
const bearer = header.split(' ');
const token = bearer[1] || req.token;
const decodedToken = jwt.verify(token, process.env.SECRET_JWT_SUPERUSER_KEY);
if (decodedToken) {
req.user = decodedToken;
req.token = token;
return next();
}
return res.sendStatus(403).json({
code: 403,
message: 'Invalid token',
});
}
// if header is undefined , return bad request
return res.sendStatus(403).json({
code: 403,
message: 'Not Authorized',
});
} catch (error) {
return httpResponse.error(res, 500, error.message, 'verification failed');
}
};
export default checkSuperUserToken;
|
javascript
| 13 | 0.637 | 83 | 29.30303 | 33 |
starcoderdata
|
using System;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using CodingConnected.JsonRPC;
using CodingConnected.TLCFI.NET.Client.Data;
using CodingConnected.TLCFI.NET.Core.Generic;
using CodingConnected.TLCFI.NET.Core.Models.Generic;
using CodingConnected.TLCFI.NET.Core.Models.TLC;
using CodingConnected.TLCFI.NET.Core.Models.TLC.Base;
using CodingConnected.TLCFI.NET.Core.Proxies;
using NLog;
namespace CodingConnected.TLCFI.NET.Client.Session
{
///
/// Represents the session with a remote TLC Facilities.
/// This class handled TLC-FI JSON-RPC calls and monitors session health via alive checking.
/// The class responds to JSON-RPC calls by calling methods and setting state in the CLABase class.
///
internal class TLCFIClientSessionJsonRpcHandler : ITLCFIClient
{
#region Fields
private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
private readonly JsonRpcService _service;
private readonly TLCFIClientStateManager _stateManager;
private readonly TLCProxy _tlcProxy;
private readonly CancellationToken _sessionCancellationToken;
private readonly Regex _jsonRpcMethodRegex = new Regex(@"['""]method['""]", RegexOptions.Compiled);
#endregion // Fields
#region Events
public event EventHandler ReceivedAlive;
public event EventHandler UpdateStateCalled;
public event EventHandler NotifyEventCalled;
#endregion // Events
#region Public Methods
public async Task SetReqControlStateAsync(ControlState state)
{
_stateManager.ControlSession.ReqControlState = state;
try
{
await _tlcProxy.UpdateStateAsync(GetObjectStateUpdateGroup(_stateManager.Session), _sessionCancellationToken);
}
catch (TaskCanceledException)
{
}
_stateManager.Session.ResetChanged();
}
public async Task SetIntersectionReqStateAsync(IntersectionControlState state)
{
_stateManager.Intersection.ReqState = state;
try
{
await _tlcProxy.UpdateStateAsync(GetObjectStateUpdateGroup(_stateManager.Intersection), _sessionCancellationToken);
}
catch (TaskCanceledException)
{
}
_stateManager.Intersection.ResetChanged();
}
#endregion // Public Methods
#region Private Methods
private ObjectStateUpdateGroup GetObjectStateUpdateGroup(TLCObjectBase obj)
{
var objectStateUpdate = new[]
{
new ObjectStateUpdate
{
Objects = new ObjectReference()
{
Ids = new[] { obj.Id },
Type = obj.ObjectType
},
States = new[]
{
obj.GetState()
}
}
};
return new ObjectStateUpdateGroup
{
Ticks = TLCFIClient.CurrentTicks,
Update = objectStateUpdate
};
}
#endregion // Private Methods
#region ITLCFIApplication
[JsonRpcMethod]
public AliveObject Alive(AliveObject alive)
{
ReceivedAlive?.Invoke(this, EventArgs.Empty);
return alive;
}
[JsonRpcMethod]
public void NotifyEvent(ObjectEvent objectevent)
{
NotifyEventCalled?.Invoke(this, objectevent);
}
[JsonRpcMethod]
public void UpdateState(ObjectStateUpdateGroup objectstateupdategroup)
{
var updategroup = objectstateupdategroup.Update;
foreach (var update in updategroup)
{
var objects = update.Objects;
var states = update.States;
if (objects.Ids.Length != states.Length)
{
throw new JsonRpcException((int)ProtocolErrorCode.Error, "List of object ids and list of states were of different lengths.", null);
}
if (objects.Ids.Length == 0)
{
throw new JsonRpcException((int)ProtocolErrorCode.Error, "List of objects is empty.", null);
}
UpdateStateCalled?.Invoke(this, update);
}
}
[JsonRpcMethod]
public ObjectMeta ReadMeta(ObjectReference objectReference)
{
throw new JsonRpcException((int)ProtocolErrorCode.Error, "This application does not support the ReadMeta method; ReadMeta should be called on the actual TLC Facilities only", null);
}
#endregion // ITLCFIApplication
#region Constructor
public TLCFIClientSessionJsonRpcHandler(
TLCFIClientStateManager stateManager,
TLCProxy tlcProxy,
TLCFIClientSessionState sessionState,
TwoWayTcpClient tcpClient,
CancellationToken token)
{
_stateManager = stateManager;
_tlcProxy = tlcProxy;
_sessionCancellationToken = token;
tcpClient.DataReceived += async (o, e) =>
{
if (!_jsonRpcMethodRegex.IsMatch(e)) return;
var result = _service?.HandleRpc(e);
if (result != null)
{
await tcpClient.SendDataAsync(result, token);
}
};
_service = JsonRpcProcedureBinder.Default.GetInstanceService(this);
}
#endregion // Constructor
}
}
|
c#
| 22 | 0.595481 | 193 | 32.827586 | 174 |
starcoderdata
|
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package dart
import (
"bytes"
"fmt"
"strings"
"text/template"
gidlconfig "go.fuchsia.dev/fuchsia/tools/fidl/gidl/config"
gidlir "go.fuchsia.dev/fuchsia/tools/fidl/gidl/ir"
gidlmixer "go.fuchsia.dev/fuchsia/tools/fidl/gidl/mixer"
"go.fuchsia.dev/fuchsia/tools/fidl/lib/fidlgen"
)
var benchmarkTmpl = template.Must(template.New("benchmarkTmpls").Parse(`
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// @dart = 2.8
import 'dart:convert';
import 'dart:io' hide exit;
import 'dart:typed_data';
import 'package:fidl/fidl.dart';
import 'package:fidl_benchmarkfidl/fidl_async.dart';
import 'package:fuchsia/fuchsia.dart';
import 'package:sl4f/sl4f.dart';
import 'package:test/test.dart';
{{- if .UsesHandles }}
import 'package:topaz.lib.gidl/handles.dart';
{{- end }}
typedef _CallbackSetter = void Function(void Function());
typedef _DefinitionBlock = void Function(
_CallbackSetter run, _CallbackSetter teardown);
class _Definition {
final String name;
final _DefinitionBlock block;
void Function() _run;
void Function() _teardown;
_Definition(this.name, this.block);
double execute() {
block((void Function() run) => _run = run,
(void Function() teardown) => _teardown = teardown);
if (_run == null) {
throw Exception("Benchmark $name doesn't declare what to run.");
}
// Warmup for at least 100ms. Discard result.
_measure(100);
// Run the benchmark for at least 1s.
double result = _measure(1000);
if (_teardown != null) {
_teardown();
}
print('$name $result ms\n');
return result;
}
// Measures the score for this benchmark by executing it repeateldy until
// time minimum has been reached.
double _measure(int minimumMillis) {
int minimumMicros = minimumMillis * 1000;
int iter = 0;
Stopwatch watch = Stopwatch()..start();
int elapsed = 0;
while (elapsed < minimumMicros) {
_run();
elapsed = watch.elapsedMicroseconds;
iter++;
}
return elapsed / iter;
}
}
class BenchmarkGroup {
final List definitions;
final String name;
BenchmarkGroup(this.name) : definitions = [];
void benchmark(final String name, final _DefinitionBlock block) {
definitions.add(_Definition(name, block));
}
List run() {
final List results = [];
for (final def in definitions) {
final result = def.execute();
results.add(TestCaseResults(def.name, Unit.nanoseconds, [result * 1000]));
}
return results;
}
}
{{ range .Benchmarks }}
void encode{{ .Name }}Benchmark(run, teardown) {
{{- if .HandleDefs }}
final handles = createHandles({{ .HandleDefs }});
teardown(() {
closeHandles(handles);
});
{{- end }}
final value = {{ .Value }};
run(() {
final Encoder encoder = Encoder(kWireFormatDefault)
..alloc({{ .ValueType}}.inlineSize(kWireFormatDefault), 0);
{{ .ValueType }}.encode(encoder, value, 0, 1);
});
}
void decode{{ .Name }}Benchmark(run, teardown) {
{{- if .HandleDefs }}
final handles = createHandles({{ .HandleDefs }});
teardown(() {
closeHandles(handles);
});
{{- end }}
final value = {{ .Value }};
final Encoder encoder = Encoder(kWireFormatDefault)
..alloc({{ .ValueType}}.inlineSize(kWireFormatDefault), 0);
{{ .ValueType }}.encode(encoder, value, 0, 1);
run(() {
final Decoder decoder = Decoder(IncomingMessage.fromOutgoingMessage(encoder.message))
..claimMemory({{ .ValueType}}.inlineSize(kWireFormatDefault), 0);
{{ .ValueType }}.decode(decoder, 0, 1);
});
}
{{ end }}
List<Map<String, dynamic>> resultsToJson(
List results, String suiteName) {
return results.map((result) => result.toJson(testSuite: suiteName)).toList();
}
void main() async {
test('main', () async {
final benchmarks = BenchmarkGroup('fuchsia.fidl_microbenchmarks')
{{ range .Benchmarks }}
..benchmark('Dart/Encode/{{ .ChromeperfPath }}/WallTime', encode{{.Name}}Benchmark)
..benchmark('Dart/Decode/{{ .ChromeperfPath }}/WallTime', decode{{.Name}}Benchmark)
{{ end }};
final results = benchmarks.run();
if (results.isEmpty) {
exit(1);
}
var encoder = JsonEncoder.withIndent(' ');
await File('/data/results.json').writeAsString(
encoder.convert(resultsToJson(results, benchmarks.name)),
mode: FileMode.write);
}, timeout: Timeout(Duration(minutes: 10)));
}
`))
type benchmarkTmplInput struct {
UsesHandles bool
Benchmarks []benchmark
}
type benchmark struct {
Name, ChromeperfPath, Value, ValueType, HandleDefs string
}
// GenerateBenchmarks generates Dart benchmarks.
func GenerateBenchmarks(gidl gidlir.All, fidl fidlgen.Root, config gidlconfig.GeneratorConfig) ([]byte, error) {
schema := gidlmixer.BuildSchema(fidl)
var benchmarks []benchmark
usesHandles := false
for _, gidlBenchmark := range gidl.Benchmark {
decl, err := schema.ExtractDeclaration(gidlBenchmark.Value, gidlBenchmark.HandleDefs)
if err != nil {
return nil, fmt.Errorf("benchmark %s: %s", gidlBenchmark.Name, err)
}
value := visit(gidlBenchmark.Value, decl)
valueType := typeName(decl)
benchmarks = append(benchmarks, benchmark{
Name: benchmarkName(gidlBenchmark.Name),
ChromeperfPath: gidlBenchmark.Name,
Value: value,
ValueType: valueType,
HandleDefs: buildHandleDefs(gidlBenchmark.HandleDefs),
})
if len(gidlBenchmark.HandleDefs) > 0 {
usesHandles = true
}
}
input := benchmarkTmplInput{
UsesHandles: usesHandles,
Benchmarks: benchmarks,
}
var buf bytes.Buffer
err := benchmarkTmpl.Execute(&buf, input)
return buf.Bytes(), err
}
func benchmarkName(gidlName string) string {
return fidlgen.ToSnakeCase(strings.ReplaceAll(gidlName, "/", "_"))
}
|
go
| 16 | 0.681668 | 112 | 27.509434 | 212 |
starcoderdata
|
from unittest.mock import patch, call, mock_open
from owca.testing import create_open_mock
def test_create_open_mock_autocreated():
with patch('builtins.open', create_open_mock({
'/some/path.txt': 'foo',
})) as mocks:
assert open('/some/path.txt').read() == 'foo'
open('/some/path.txt', 'w').write('bar')
mocks['/some/path.txt'].assert_has_calls(
[call().write('bar')])
def test_create_open_mock_manually():
my_own_mock_open = mock_open(read_data='foo')
with patch('builtins.open', create_open_mock({
'/some/path.txt': my_own_mock_open
})):
assert open('/some/path.txt').read() == 'foo'
open('/some/path.txt', 'w').write('bar')
my_own_mock_open.assert_has_calls(
[call().write('bar')])
|
python
| 14 | 0.575148 | 53 | 34.208333 | 24 |
starcoderdata
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include "vpu_case_common.hpp"
using CompilationTestParam = WithParamInterface<std::tuple<PluginDevicePair, CompilationParameter>>;
using ClassificationTestVpuParam = WithParamInterface<std::tuple<
PluginDevicePair,
Precision,
Batch,
DoReshape,
Resources,
ClassificationSrcParam>>;
using ClassificationSpecificTestVpuParam = WithParamInterface<std::tuple<
PluginDevicePair,
Precision,
Batch,
DoReshape>>;
//------------------------------------------------------------------------------
// class VpuNoClassificationRegression
//------------------------------------------------------------------------------
class VpuNoClassificationRegression : public VpuNoRegressionBase,
public ClassificationTestVpuParam {
public:
//Operations
static std::string getTestCaseName(
TestParamInfo param);
protected:
// Data section
int resources_;
ClassificationSrcParam source_param_;
//Operations
void SetUp() override;
void InitConfig() override;
};
//------------------------------------------------------------------------------
// class VpuNoClassificationRegressionSpecific
//------------------------------------------------------------------------------
class VpuNoClassificationRegressionSpecific : public VpuNoRegressionBase,
public ClassificationSpecificTestVpuParam {
public:
//Operations
static std::string getTestCaseName(
TestParamInfo param);
protected:
//Operations
void SetUp() override;
void InitConfig() override;
};
//------------------------------------------------------------------------------
// class VpuNoRegressionWithCompilation
//------------------------------------------------------------------------------
class VpuNoRegressionWithCompilation : public Regression::RegressionTests,
public CompilationTestParam {
public:
// Operations
static std::string getTestCaseName(TestParamInfo param);
// Accessors
std::string getDeviceName() const override;
protected:
// Data section
std::string plugin_name_;
std::string device_name_;
CompilationParameter compilation_param_;
//Operations
void SetUp() override;
};
//------------------------------------------------------------------------------
// Implementation of methods of class VpuNoRegressionWithCompilation
//------------------------------------------------------------------------------
inline std::string VpuNoRegressionWithCompilation::getDeviceName() const {
return plugin_name_;
}
|
c++
| 11 | 0.546204 | 100 | 30.989011 | 91 |
starcoderdata
|
def build_model(self):
if self.classif_dims is None:
return []
classif_layers = nn.ModuleList()
# Just one convolution
if len(self.classif_dims) == 1:
if self.conv_output:
h2o = RelGraphConv(in_feat=self.last_dim_embedder,
out_feat=self.classif_dims[0],
num_rels=self.num_rels,
num_bases=self.num_bases,
self_loop=self.self_loop,
# Old fix for a bug in dgl<0.6
# self_loop=self.self_loop and self.classif_dims[0] > 1,
activation=None)
else:
h2o = nn.Linear(self.last_dim_embedder, self.classif_dims[0])
classif_layers.append(h2o)
return classif_layers
# The supervised is more than one layer
else:
i2h = RelGraphConv(in_feat=self.last_dim_embedder,
out_feat=self.classif_dims[0],
num_rels=self.num_rels,
num_bases=self.num_bases,
activation=F.relu,
self_loop=self.self_loop)
classif_layers.append(i2h)
last_hidden, last = self.classif_dims[-2:]
short = self.classif_dims[:-1]
for dim_in, dim_out in zip(short, short[1:]):
h2h = RelGraphConv(in_feat=dim_in,
out_feat=dim_out,
num_rels=self.num_rels,
num_bases=self.num_bases,
activation=F.relu,
self_loop=self.self_loop)
classif_layers.append(h2h)
# hidden to output
if self.conv_output:
h2o = RelGraphConv(in_feat=last_hidden,
out_feat=last,
num_rels=self.num_rels,
num_bases=self.num_bases,
self_loop=self.self_loop,
activation=None)
else:
h2o = nn.Linear(last_hidden, last)
classif_layers.append(h2o)
return classif_layers
|
python
| 14 | 0.421869 | 91 | 45.264151 | 53 |
inline
|
/*
GOCR Copyright (C) 2000
GOCR API Copyright (C) 2001
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "_gocr.h"
/**
\brief Returns the full word given a box
Given a character, returns the word it's part of. This word is defined as all
letters (see gocr_wcharIsLetter) that...
Should underline '_' be considered a valid character?
\param block The block.
\param box The box.
\sa gocr_wcharIsLetter
\retval 0 OK
\retval -1 error.
*/
wchar_t *gocr_textBlockGetWord ( gocr_Block *block, gocr_Box *box ) {
wchar_t *text, *t;
int size = 1;
gocr_Node *begin, *end;
gocr_Box *b;
_gocr_debug(3, fprintf(_data.error, "gocr_textBlockGetWord(%p,%p)\n", block,
box);)
if ( block->t != gocr_blockTypeGetByName("TEXT") ) {
_gocr_debug(2, fprintf(_data.error, "Not a text block.\n");)
return NULL;
}
if ( !gocr_wcharIsAlpha(box->ch->c) ) {
_gocr_debug(3, fprintf(_data.error, "%lx: Not a letter.\n", box->ch->c);)
return NULL;
}
begin = list_node_from_data(&block->boxlist, box);
end = begin->next;
b = (gocr_Box *)begin->data;
while ( gocr_wcharIsAlpha(b->ch->c) && begin->previous != NULL ) {
begin = begin->previous;
b = (gocr_Box *)begin->data;
size++;
}
b = (gocr_Box *)end->data;
while ( gocr_wcharIsAlpha(b->ch->c) && end->next != NULL ) {
end = end->next;
b = (gocr_Box *)end->data;
size++;
}
text = (wchar_t *)malloc(size*sizeof(wchar_t));
if ( text == NULL ) {
_gocr_debug(1, fprintf(_data.error, "gocr_textBlockGetWord: NULL malloc %d.\n", size);)
return NULL;
}
/* fill */
for (t = text; begin != end->next; begin = begin->next ) {
b = begin->data;
*t++ = b->ch->c;
}
*t = '\0';
return text;
}
#undef FUNCTION
#define FUNCTION "_gocr_blockTextFill"
/**
\brief Fills the text field
This function sweeps the list of gocr_Boxes, filling the block->text field with
the codes. If the block->text field was previously allocated, it's freed.
\param b The block.
\retval 0 OK
\retval -1 error.
*/
int _gocr_blockTextFill ( gocr_Block *b ) {
gocr_Box *box;
int size;
wchar_t *s, *t;
_gocr_printf(3, FUNCTION, "(%p)\n", b);
if (!b) {
_gocr_printf(1, FUNCTION, "Null block\n");
return -1;
}
if (list_empty(&b->boxlist)) {
_gocr_printf(2, FUNCTION, "empty list\n");
return 0;
}
if (b->text) {
_gocr_printf(3, FUNCTION, "text exists, freeing it\n");
free(b->text);
}
/* allocate memory. The size is a first guess. */
size = list_total(&b->boxlist) * 1.2;
b->text = (wchar_t *) malloc(size * sizeof(wchar_t));
if (b->text == NULL) {
_gocr_printf(3, FUNCTION, "NULL malloc\n");
return -1;
}
b->text[0] = '\0';
s = b->text;
for_each_data(&b->boxlist) {
box = (gocr_Box *) list_get_current(&b->boxlist);
if (box == NULL) {
_gocr_printf(2, FUNCTION, "NULL box, ignoring.\n");
continue;
}
/* do we need to realloc? */
if ((s - b->text) + (box->attributes == NULL ? 0 :
wcslen(box->attributes)) + 2 > size) {
wchar_t *newtext;
int diff;
diff = s - b->text;
size = (int)((float)size)*1.2 + 3;
_gocr_printf(4, FUNCTION, "Realloc: %d\n", size);
newtext =
(wchar_t *) realloc(b->text,
size * sizeof(wchar_t));
if (!newtext) {
_gocr_printf(1, FUNCTION, "Null realloc\n");
return -1;
}
b->text = newtext;
s = b->text + diff;
}
/* now fill it */
t = box->attributes;
if (t)
while (*t) { /* could do with memcpy */
*s++ = *t++;
}
if (box->ch)
*s++ = box->ch->c;
*s = '\0';
}
end_for_each(&b->boxlist);
return 0;
}
|
c
| 14 | 0.614724 | 91 | 24.181287 | 171 |
starcoderdata
|
package com.github.mygreen.sqlmapper.core.where.metamodel;
import com.github.mygreen.sqlmapper.metamodel.Visitor;
import com.github.mygreen.sqlmapper.metamodel.expression.Expression;
import com.github.mygreen.sqlmapper.metamodel.operation.Operation;
import com.github.mygreen.sqlmapper.metamodel.operator.UnaryOp;
/**
* 単項演算子({@link UnaryOp})に対する処理を定義します。
*
*
* @author T.TSUCHIE
*
*/
public class UnaryOpHandler extends OperationHandler {
@Override
protected void init() {
addTemplate(UnaryOp.NOT, "not {0}");
addTemplate(UnaryOp.IS_NULL, "{0} is null");
addTemplate(UnaryOp.IS_NOT_NULL, "{0} is not null");
addTemplate(UnaryOp.EXISTS, "exists {0}");
addTemplate(UnaryOp.NOT_EXISTS, "not exists {0}");
}
@Override
public void handle(UnaryOp operator, Operation expr, Visitor visitor, VisitorContext context) {
Expression left = expr.getArg(0);
VisitorContext leftContext = new VisitorContext(context);
// 左辺の評価
invoke(operator, left, visitor, leftContext);
// 評価した結果を親のコンテキストに追加する
String sql = formatWithTemplate(operator, leftContext.getCriteria());
context.appendSql(sql);
context.addParamValues(leftContext.getParamValues());
}
}
|
java
| 11 | 0.695951 | 118 | 29.44186 | 43 |
starcoderdata
|
SCIP_BANDITDATA* SCIPbanditGetData(
SCIP_BANDIT* bandit /**< bandit algorithm data structure */
)
{
assert(bandit != NULL);
return bandit->data;
}
|
c
| 8 | 0.59116 | 84 | 21.75 | 8 |
inline
|
def trace_linestrings(points, keys=(), feature_properties=()):
"""Render sequence of points as geojson linestring features.
points -- [{geojson: json.dumps({coordinates: [lon, lat]})} ...]
keys -- render separate linestring when these values change in points
feature_properties -- dict added to each feature's properties object
"""
# collect by same activity for line coloring
groups = dict_groups(points, keys)
streaks = [{"properties": g[0], "points": g[1]} for g in groups]
# start line from last point of prior streak
for i in range(1, len(streaks)):
streaks[i]["points"].insert(0, streaks[i-1]["points"][-1])
for streak in streaks:
if len(streak["points"]) < 2:
continue # one point does not make a line
streak["properties"].update(feature_properties)
yield {
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [
point_coordinates(x) for x in streak["points"]]},
"properties": streak["properties"]}
|
python
| 15 | 0.598004 | 73 | 39.851852 | 27 |
inline
|
using System.Text;
using SshNet.Security.Cryptography.Common.Tests;
using Xunit;
namespace SshNet.Security.Cryptography.Tests
{
///
/// Test cases are defined in RFC 1321, section A.5
///
public class MD5Test
{
private readonly MD5 _hashAlgorithm;
public MD5Test()
{
_hashAlgorithm = new MD5();
}
[Fact]
public void Rfc1321_1()
{
var data = new byte[0]; // ""
var expectedHash = ByteExtensions.HexToByteArray("d41d8cd98f00b204e9800998ecf8427e");
var actualHash = _hashAlgorithm.ComputeHash(data);
Assert.Equal(expectedHash, actualHash);
}
[Fact]
public void Rfc1321_2()
{
var data = ByteExtensions.HexToByteArray("61"); // "a"
var expectedHash = ByteExtensions.HexToByteArray("0cc175b9c0f1b6a831c399e269772661");
var actualHash = _hashAlgorithm.ComputeHash(data);
Assert.Equal(expectedHash, actualHash);
}
[Fact]
public void Rfc1321_3()
{
var data = ByteExtensions.HexToByteArray("616263"); // "abc"
var expectedHash = ByteExtensions.HexToByteArray("900150983cd24fb0d6963f7d28e17f72");
var actualHash = _hashAlgorithm.ComputeHash(data);
Assert.Equal(expectedHash, actualHash);
}
[Fact]
public void Rfc1321_4()
{
var data = ByteExtensions.HexToByteArray("6d65737361676520646967657374"); // "message digest"
var expectedHash = ByteExtensions.HexToByteArray("f96b697d7cb7938d525a2f31aaf161d0");
var actualHash = _hashAlgorithm.ComputeHash(data);
Assert.Equal(expectedHash, actualHash);
}
[Fact]
public void Rfc1321_5()
{
var data = ByteExtensions.HexToByteArray("6162636465666768696a6b6c6d6e6f707172737475767778797a"); // "abcdefghijklmnopqrstuvwxyz"
var expectedHash = ByteExtensions.HexToByteArray("c3fcd3d76192e4007dfb496cca67e13b");
var actualHash = _hashAlgorithm.ComputeHash(data);
Assert.Equal(expectedHash, actualHash);
}
[Fact]
public void Rfc1321_6()
{
var data = ByteExtensions.HexToByteArray("4142434445464748494a4b4c4d4e4f505152535455565758595a6162636465666768696a6b6c6d6e6f707172737475767778797a30313233343536373839"); // "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
var expectedHash = ByteExtensions.HexToByteArray("d174ab98d277d9f5a5611c2c9f419d9f");
var actualHash = _hashAlgorithm.ComputeHash(data);
Assert.Equal(expectedHash, actualHash);
}
[Fact]
public void Rfc1321_7()
{
var data = ByteExtensions.HexToByteArray(StringExtensions.Repeat("31323334353637383930", 8)); // "1234567890" * 8
var expectedHash = ByteExtensions.HexToByteArray("57edf4a22be3c955ac49da2e2107b67a");
var actualHash = _hashAlgorithm.ComputeHash(data);
Assert.Equal(expectedHash, actualHash);
}
}
}
|
c#
| 18 | 0.638592 | 249 | 31.469388 | 98 |
starcoderdata
|
package wang.leal.ahel.socket.client;
import wang.leal.ahel.socket.log.Logger;
import wang.leal.ahel.socket.netty.Netty;
public class SocketClient implements IConnection.OnConnectionListener {
private IConnection connection;
private Callback callback;
private final String url;
private final int port;
private SocketClient(String url,int port){
this.url = url;
this.port = port;
}
public static SocketClient with(String url, int port){
return new SocketClient(url,port);
}
public SocketClient connect(){
this.connection = getConnection();
this.connection.connect(this.url,this.port,this);
return this;
}
public SocketClient callback(Callback callback){
this.callback = callback;
return this;
}
public void send(String message){
if (connection!=null){
connection.sendMessage(message);
}
}
public void disconnect(){
Logger.e("socket client disconnect");
this.connection.close();
}
private static IConnection getConnection(){
return new Netty();
}
@Override
public void onMessageReceive(String message) {
if (callback!=null){
callback.onMessageReceive(this.url,this.port,message);
}
}
@Override
public void onConnected() {
if (callback!=null){
callback.onConnected(this.url,this.port);
}
}
public interface Callback {
void onMessageReceive(String url,int port,String message);
void onConnected(String url,int port);
}
}
|
java
| 11 | 0.637261 | 71 | 23.938462 | 65 |
starcoderdata
|
public String ethSendTransaction(Function function, BigInteger value)
throws IOException, InterruptedException, ExecutionException {
// 1. Account Lock 해제
PersonalUnlockAccount personalUnlockAccount = web3j.personalUnlockAccount(from, pwd).send();
if (personalUnlockAccount.accountUnlocked()) { // unlock 일때
//2. account에 대한 nonce값 가져오기.
EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
from, DefaultBlockParameterName.LATEST).sendAsync().get();
BigInteger nonce = ethGetTransactionCount.getTransactionCount();
//3. Transaction값 제작
Transaction transaction = Transaction.createFunctionCallTransaction(from, nonce,
Transaction.DEFAULT_GAS,
null, contract,
value == null ? (BigInteger)null : value,
FunctionEncoder.encode(function));
// 4. ethereum Call &
EthSendTransaction ethSendTransaction = web3j.ethSendTransaction(transaction).send();
// transaction에 대한 transaction Hash값 얻기.
String transactionHash = ethSendTransaction.getTransactionHash();
// ledger에 쓰여지기 까지 기다리기.
// Thread.sleep(1000);
return transactionHash;
} else {
throw new PersonalLockException("check ethereum personal Lock");
}
}
|
java
| 12 | 0.632271 | 100 | 40.285714 | 35 |
inline
|
def forward(self, words):
emb = self.embedding(words) # nwords x emb_size
emb = emb.unsqueeze(0).permute(0, 2, 1) # 1 x emb_size x vocab
h = self.conv_1d(emb) # perform convolution over the stretched embeddings
# max pooling
h = h.max(dim = 2)[0]
h = self.relu(h)
out = self.projection_layer(h)
return out
|
python
| 9 | 0.636095 | 77 | 32.9 | 10 |
inline
|
func (worker *Worker) Shutdown() {
worker.Lock()
defer worker.Unlock()
lg.InfoD("shutdown", logger.M{"message": "Received sigterm. Shutting down gracefully."})
if worker.w != nil {
// Shutdown blocks, waiting for all jobs to finish
worker.w.Shutdown()
}
}
|
go
| 11 | 0.693182 | 89 | 28.444444 | 9 |
inline
|
int Glue<T>::usr_attr_newindex(lua_State *L) {
// find setter:
lua_getmetatable(L, 1);
lua_pushstring(L, "__setters");
lua_rawget(L, -2);
lua_pushvalue(L, 2);
lua_rawget(L, -2);
// call setter:
if(lua_type(L, -1) == LUA_TFUNCTION) {
lua_pushvalue(L, 1);
lua_pushvalue(L, 3);
int err = lua_pcall(L, 2, 0, 0);
if(err) {
luaL_error(L, "error indexing %s.%s: %s\n",
lua_tostring(L, 1),
lua_tostring(L, 2),
lua_tostring(L, -1));
}
} else {
lua_pop(L, 1); // non-setter
}
lua_pop(L, 2); // __setters, metatable
// store the value in the fenv:
lua_getfenv(L, 1);
lua_pushvalue(L, 2);
lua_pushvalue(L, 3);
lua_rawset(L, -3);
lua_pop(L, 1); // fenv
return 0;
// lua_getmetatable(L, 1);
//
// lua_pushstring(L, "__setters");
// lua_rawget(L, -2);
// lua_pushvalue(L, 2);
// lua_rawget(L, -2);
//
// if(lua_type(L, -1) == LUA_TFUNCTION) {
// lua_pushvalue(L, 1);
// lua_pushvalue(L, 3);
//
// int err = lua_pcall(L, 2, 0, 0);
// if(err) {
// luaL_error(L, "error indexing %s.%s: %s\n",
// lua_tostring(L, 1),
// lua_tostring(L, 2),
// lua_tostring(L, -1));
// lua_pop(L, 1);
// }
// lua_pop(L, 3);
// }
// else {
// lua_pop(L, 3);
//
// lua_getfenv(L, 1);
// lua_pushvalue(L, 2);
// lua_pushvalue(L, 3);
// lua_rawset(L, -3);
//
// lua_pop(L, 1);
// }
// return 0;
}
|
c++
| 12 | 0.517467 | 48 | 20.153846 | 65 |
inline
|
<?php
include_once 'header.php';
require_once 'include/inc.db.php';
$sql = "SELECT DISTINCT Extract(month FROM orderdate) as mon, Extract(year FROM orderdate) as ye from sales";
$res = mysqli_query($connect,$sql) or die("An Error Occured.. Error Code= 0x0016");
$num = mysqli_num_rows($res);
if(!($num > 0))
{
echo "No Data to be displayed";
exit();
}
else
{
?>
<div class="container">
<div class="panel panel-info">
<div class="panel-heading">Montly Sales
<div class="panel-body">
<?php
while ($row = mysqli_fetch_assoc($res))
{
$mon = getMonth($row['mon']);
?>
echo $mon;?>
echo date("Y", strtotime($row['ye']));?>
<?php $mon = $row['mon'];?>
<table class="table table-hover">
<?php
$sas = 'select sum(total) as T from sales where EXTRACT(month from orderdate)= '.$mon;
$pop = mysqli_query($connect,$sas) or die("AN error occured. Error Code = 0x0016");
$col = mysqli_fetch_assoc($pop);
?>
<td style="font-weight: bold">Total Earning:
echo $col['T']; ?>
<?php
}
?>
<?php
}
function getMonth($mon)
{
if($mon == 1)
{
return 'January';
}
else if($mon == 2)
{
return 'February';
}
else if($mon == 3)
{
return 'March';
}
else if($mon == 4)
{
return 'April';
}
else if($mon == 5)
{
return 'May';
}
else if($mon == 6)
{
return 'June';
}
else if($mon == 7)
{
return 'July';
}
else if($mon == 8)
{
return 'August';
}
else if($mon == 9)
{
return 'September';
}
else if($mon == 10)
{
return 'October';
}
else if($mon == 11)
{
return 'November';
}
else
{
return 'December';
}
}
?>
|
php
| 28 | 0.359118 | 114 | 24.514851 | 101 |
starcoderdata
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEngine;
namespace Assets.Editor
{
[CanEditMultipleObjects]
[CustomEditor(typeof(IK))]
public class IKEditor:UnityEditor.Editor
{
IK ik;
bool showBones = true;
private void OnSceneGUI()
{
var ik = target as IK;
foreach(var bone in ik.Bones)
{
bone._showAsActive = true;
}
}
public override void OnInspectorGUI()
{
ik = target as IK;
var bone = EditorGUILayout.ObjectField("Start Bone", ik.StartBone, typeof(Bone), true) as Bone;
if (bone != ik.StartBone)
{
ik.StartBone = bone;
InitBones();
}
bone = EditorGUILayout.ObjectField("End Bone", ik.EndBone, typeof(Bone), true) as Bone;
if (bone != ik.EndBone)
{
ik.EndBone = bone;
InitBones();
}
EditorGUILayout.Space();
showBones = EditorGUILayout.Foldout(showBones, "Bones");
if (showBones)
{
GUIStyle style = new GUIStyle();
style.margin.left = 20;
EditorGUILayout.BeginVertical(style);
for (var i = 0; i < ik.Bones.Length; i++)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.ObjectField(ik.Bones[i], typeof(Bone), true);
EditorGUILayout.Vector3Field("", ik.Bones[i].transform.localRotation.eulerAngles);
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.EndVertical();
}
}
public void InitBones()
{
ik = target as IK;
if (ik.StartBone && ik.EndBone)
{
ik.Bones = SearchBones(ik.EndBone.transform, ik.StartBone).ToArray();
}
}
public List SearchBones(Transform current, Bone target)
{
if (current.GetComponent == target)
return new List Bone[] { current.GetComponent });
if (!current.transform.parent)
throw new Exception("Cannot reach the Start Bone.");
var next = SearchBones(current.parent, target);
if (current.GetComponent
next.Add(current.GetComponent
return next;
}
}
}
|
c#
| 21 | 0.499626 | 107 | 31.45 | 80 |
starcoderdata
|
using System;
using System.Threading.Tasks;
using EasyAbp.CacheManagement.CacheItems;
using EasyAbp.CacheManagement.CacheItems.Dtos;
namespace EasyAbp.CacheManagement.Web.Pages.CacheManagement.CacheItems.CacheItem
{
public class KeyListModel : CacheManagementPageModel
{
private readonly ICacheItemAppService _service;
public CacheItemDto CacheItem { get; set; }
public KeyListModel(ICacheItemAppService service)
{
_service = service;
}
public async Task OnGetAsync(Guid cacheItemId)
{
CacheItem = await _service.GetAsync(cacheItemId);
await Task.CompletedTask;
}
}
}
|
c#
| 13 | 0.670471 | 80 | 25.961538 | 26 |
starcoderdata
|
package net.bolbat.kit.event.common;
import java.io.Serializable;
/**
* Common, entity updated event listener.
*
* @param
* event entity type
* @param
* event itself, {@link EntitySavedEvent} any instance
* @author h3llka
*/
public interface EntitySavedEventListener<Saved extends Serializable, SavedEvent extends EntitySavedEvent {
/**
* General {@link EntitySavedEvent} handling point.
* Important: don't forget to use {@link com.google.common.eventbus.Subscribe} annotation inside implementation.
* Details:
*
* @param savedEvent
* event itself
*/
void listen(final SavedEvent savedEvent);
}
|
java
| 7 | 0.712329 | 117 | 27.076923 | 26 |
starcoderdata
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.