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 |
---|---|---|---|---|---|---|---|
/**
* Perform an click action on the given element
* @param {String} action The action to perform on the target elementID
* @param {String} targetElementIndex The nth element start from 1st,2nd,3rd,4th
* @param {String} targetElement target element selector
* @param {String} parentElementIndex The nth parent element start from 1st,2nd,3rd,4th
* @param {String} parentElement parent element selector
*/
module.exports = (action, targetElementIndex, targetElement, parentElementIndex, parentElement) => {
const targetElementIndexInt = (targetElementIndex) ? parseInt(targetElementIndex) - 1 : 0;
const parentElementIndexInt = (parentElementIndex) ? parseInt(parentElementIndex) - 1 : 0;
var myParentElement, myTargetElement;
if (parentElement) {
myParentElement = browser.$$(parentElement).value[parentElementIndexInt];
myTargetElement = browser.elementIdElements(myParentElement.ELEMENT, targetElement).value[targetElementIndexInt];
} else {
myTargetElement = browser.$$(targetElement).value[targetElementIndexInt];
}
// console.log(myTargetElement);
switch (action) {
case 'moveTo':
browser.moveTo(myTargetElement.ELEMENT);
break;
case 'clear':
browser.elementIdClear(myTargetElement.ELEMENT);
break;
case 'tryClick':
try {
console.log('1st try with direct click ...')
browser.elementIdClick(myTargetElement.ELEMENT);
} catch (e) {
console.log('2nd try with deep click ...')
const deepClick = function(argument) { argument.click(); };
browser.execute(deepClick, myTargetElement);
}
break;
case 'deepClick':
console.log('do deep click ...')
const deepClick = function(argument) { argument.click(); };
browser.execute(deepClick, myTargetElement);
break;
case 'click':
default:
browser.elementIdClick(myTargetElement.ELEMENT);
break;
}
};
|
javascript
| 12 | 0.625 | 121 | 42.137255 | 51 |
starcoderdata
|
<?php
namespace yii2tech\tests\unit\ar\search;
use yii\helpers\ArrayHelper;
use Yii;
/**
* Base class for the test cases.
*/
class TestCase extends \PHPUnit\Framework\TestCase
{
protected function setUp()
{
parent::setUp();
$this->mockApplication();
$this->setupTestDbData();
}
protected function tearDown()
{
$this->destroyApplication();
}
/**
* Populates Yii::$app with a new application
* The application will be destroyed on tearDown() automatically.
* @param array $config The application configuration, if needed
* @param string $appClass name of the application class to create
*/
protected function mockApplication($config = [], $appClass = '\yii\console\Application')
{
new $appClass(ArrayHelper::merge([
'id' => 'testapp',
'basePath' => __DIR__,
'vendorPath' => $this->getVendorPath(),
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'sqlite::memory:',
],
],
], $config));
}
/**
* @return string vendor path
*/
protected function getVendorPath()
{
return dirname(__DIR__) . '/vendor';
}
/**
* Destroys application in Yii::$app by setting it to null.
*/
protected function destroyApplication()
{
Yii::$app = null;
}
/**
* Setup tables for test ActiveRecord
*/
protected function setupTestDbData()
{
$db = Yii::$app->getDb();
// Structure :
$table = 'Item';
$columns = [
'id' => 'pk',
'name' => 'string',
'status' => 'integer',
'price' => 'float',
];
$db->createCommand()->createTable($table, $columns)->execute();
// Data :
$db->createCommand()->batchInsert('Item', ['name', 'status', 'price'], [
['item1', 1, '10.5'],
['item2', 2, '20.5'],
['item3', 3, '20'],
['item4', 4, '50.2'],
['item5', 5, '40.7'],
['item6', 1, '10.5'],
['item7', 2, '20.5'],
['item8', 3, '20'],
['item9', 4, '50.2'],
['item0', 5, '40.7'],
])->execute();
}
/**
* Invokes object method, even if it is private or protected.
* @param object $object object.
* @param string $method method name.
* @param array $args method arguments
* @return mixed method result
*/
protected function invoke($object, $method, array $args = [])
{
$classReflection = new \ReflectionClass(get_class($object));
$methodReflection = $classReflection->getMethod($method);
$methodReflection->setAccessible(true);
$result = $methodReflection->invokeArgs($object, $args);
$methodReflection->setAccessible(false);
return $result;
}
}
|
php
| 19 | 0.515789 | 92 | 25.666667 | 114 |
starcoderdata
|
namespace Plus.Event.Bus
{
///
/// 此接口必须由具有单个泛型参数的事件数据类实现
///
public interface IEventDataWithInheritableGenericArgument
{
///
/// 获取创建该类的参数
///
///
object[] GetConstructorArgs();
}
}
|
c#
| 8 | 0.559871 | 61 | 21.142857 | 14 |
starcoderdata
|
double operator()(const double *par) const {
// Function parameters for chi2 calculation
std::vector<std::vector<double>> parameters;
parameters.reserve(chi2.size());
// Map the array of shared/free parameters to a matrix using the parameter
// index matrix
for (auto &i : parameter_index) {
std::vector<double> tmp_parameters;
for (auto &j : i) {
tmp_parameters.push_back(par[j]);
}
parameters.push_back(tmp_parameters);
}
// sum up the chi2s from each dataset
double global_chi2 = 0.0;
for (std::size_t i = 0; i < chi2.size(); ++i) {
global_chi2 += (*chi2.at(i))(parameters.at(i).data());
}
return global_chi2;
}
|
c++
| 13 | 0.613636 | 78 | 31.045455 | 22 |
inline
|
#include "MappableFloatPair.h"
#include "stdafx.h"
namespace megamol {
namespace protein_cuda {
MappableFloatPair::MappableFloatPair(float offsetX, float offsetY, bool flipX, int holePos)
: protein_calls::DiagramCall::DiagramMappable()
, offsetX(offsetX)
, offsetY(offsetY)
, flipX(flipX)
, holePos(holePos) {}
MappableFloatPair::~MappableFloatPair(void) {}
int MappableFloatPair::GetAbscissaeCount() const {
return 1;
}
int MappableFloatPair::GetDataCount() const {
return 10;
}
bool MappableFloatPair::IsCategoricalAbscissa(const SIZE_T abscissa) const {
return false;
}
bool MappableFloatPair::GetAbscissaValue(
const SIZE_T index, const SIZE_T abscissaIndex, vislib::StringA* category) const {
*category = vislib::StringA("cat");
if (index == holePos) {
return false;
} else {
return true;
}
}
bool MappableFloatPair::GetAbscissaValue(const SIZE_T index, const SIZE_T abscissaIndex, float* value) const {
*value = ((index / static_cast *
(this->GetAbscissaRange(0).Second() - this->GetAbscissaRange(0).First()) +
this->GetAbscissaRange(0).First();
if (index == holePos) {
return false;
} else {
return true;
}
}
float MappableFloatPair::GetOrdinateValue(const SIZE_T index) const {
float x =
((flipX ? 1.0f : 0.0f) + (flipX ? -1.0f : 1.0f) * (index / static_cast + offsetX);
x *= static_cast - this->GetAbscissaRange(0).First()) +
this->GetAbscissaRange(0).First();
return vislib::math::Sqrt(x) + 0.2f * sin(x * 10) + offsetY;
}
vislib::Pair<float, float> MappableFloatPair::GetAbscissaRange(const SIZE_T abscissaIndex) const {
return vislib::Pair<float, float>(1.0f, 10.0f);
}
vislib::Pair<float, float> MappableFloatPair::GetOrdinateRange() const {
return vislib::Pair<float, float>(0.0f, 5.0f);
;
}
MappableWibble::MappableWibble(int holePos) : holePos(holePos) {}
MappableWibble::~MappableWibble(void) {}
int MappableWibble::GetDataCount() const {
return 10;
}
bool MappableWibble::GetAbscissaValue(const SIZE_T index, float* value) const {
*value = static_cast
if (index == holePos) {
return false;
} else {
return true;
}
}
float MappableWibble::GetOrdinateValue(const SIZE_T index) const {
return sin(static_cast + 1.0f;
}
vislib::Pair<float, float> MappableWibble::GetAbscissaRange() const {
return vislib::Pair<float, float>(0.0f, 9.0f);
}
vislib::Pair<float, float> MappableWibble::GetOrdinateRange() const {
return vislib::Pair<float, float>(0.0f, 2.0f);
}
} /* namespace protein_cuda */
} /* namespace megamol */
|
c++
| 19 | 0.664192 | 120 | 25.942857 | 105 |
starcoderdata
|
package org.moe.bindings.protocol;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.ann.ObjCProtocolName;
import org.moe.natj.objc.ann.Selector;
@Generated
@Runtime(ObjCRuntime.class)
@ObjCProtocolName("SDWebImageOperation")
public interface SDWebImageOperation {
@Generated
@Selector("cancel")
void cancel();
}
|
java
| 8 | 0.8 | 46 | 23.470588 | 17 |
starcoderdata
|
bool decompress_internal(unsigned int frameno)
{
if (target_gl_texture == 0)
{
assert(target_cpu_buffer != 0);
assert(target_cpu_pitch > 0);
}
if (frameno >= index.size())
return false;
// find the most recent i frame
unsigned int iframeno = frameno + 1;
do
{
if (index[iframeno - 1].second == FrameType::I)
break;
--iframeno;
}
while (iframeno > 0);
iframeno--;
assert(iframeno <= index.size());
// we are submitting from an i-frame onwards. so we only count relative to it.
requested_frame = frameno - iframeno;
session_frame_count = 0;
// we submit stuff until the decoder has finished with our requested frame.
// this sucks for performance, lots of wasted cycles. but the nv decoder is
// more suitable for continuous playback instead of picking out a few frames.
done_requested_frame = false;
for (unsigned int i = iframeno; i < frameno + 2; ++i)
{
submit_frame(i, iframeno);
if (done_requested_frame)
break;
}
return done_requested_frame;
}
|
c++
| 12 | 0.539921 | 86 | 30.65 | 40 |
inline
|
$(function () {
var l = abp.localization.getResource('EasyAbpPaymentServiceWeChatPay');
var service = easyAbp.paymentService.weChatPay.refundRecords.refundRecord;
var dataTable = $('#RefundRecordTable').DataTable(abp.libs.datatables.normalizeConfiguration({
processing: true,
serverSide: true,
paging: true,
searching: false,
autoWidth: false,
scrollCollapse: true,
order: [[1, "asc"]],
ajax: abp.libs.datatables.createAjax(service.getList),
columnDefs: [
{
rowAction: {
items:
[
{
text: l('Detail'),
action: function (data) {
}
}
]
}
},
{ data: "tenantId" },
{ data: "paymentId" },
{ data: "returnCode" },
{ data: "returnMsg" },
{ data: "appId" },
{ data: "mchId" },
{ data: "transactionId" },
{ data: "outTradeNo" },
{ data: "refundId" },
{ data: "outRefundNo" },
{ data: "totalFee" },
{ data: "settlementTotalFee" },
{ data: "refundFee" },
{ data: "settlementRefundFee" },
{ data: "FeeType" },
{ data: "CashFee" },
{ data: "CashFeeType" },
{ data: "CashRefundFee" },
{ data: "CouponRefundFee" },
{ data: "CouponRefundCount" },
{ data: "CouponTypes" },
{ data: "CouponIds" },
{ data: "CouponRefundFees" },
{ data: "refundStatus" },
{ data: "successTime" },
{ data: "refundRecvAccout" },
{ data: "refundAccount" },
{ data: "refundRequestSource" },
]
}));
});
|
javascript
| 25 | 0.422335 | 98 | 32.40678 | 59 |
starcoderdata
|
ULONG STDMETHODCALLTYPE LegacyImageListWrapper_Release(IImageList* pInterface)
{
LegacyImageListWrapper* pThis = LegacyImageListWrapperFromIImageList(pInterface);
ULONG ret = InterlockedDecrement(&pThis->referenceCount);
if(!ret) {
// the reference counter reached 0, so delete ourselves
ImageList_Destroy(pThis->hImageList);
HeapFree(GetProcessHeap(), 0, pThis);
}
return ret;
}
|
c++
| 10 | 0.789744 | 82 | 34.545455 | 11 |
inline
|
/* Copyright (c) 2012 Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "model/timing_graph/ElectricalTimingNode.h"
#include "model/timing_graph/ElectricalLoad.h"
namespace DSENT
{
// Set the optical node initial visited num
const int ElectricalTimingNode::TIMING_NODE_INIT_VISITED_NUM = 0;
ElectricalTimingNode::ElectricalTimingNode(const String& instance_name_, ElectricalModel* model_)
: m_instance_name_(instance_name_), m_model_(model_), m_false_path_(false), m_crit_path_(-1),
m_visited_num_(ElectricalTimingNode::TIMING_NODE_INIT_VISITED_NUM), m_delay_left_(0.0)
{
m_upstream_nodes_ = new vector<ElectricalTimingNode*>();
m_downstream_nodes_ = new vector<ElectricalTimingNode*>();
}
ElectricalTimingNode::~ElectricalTimingNode()
{
delete m_upstream_nodes_;
delete m_downstream_nodes_;
}
double ElectricalTimingNode::getMaxUpstreamRes() const
{
double max_res = 0.0;
for(unsigned int i = 0; i < m_upstream_nodes_->size(); ++i)
{
double res = m_upstream_nodes_->at(i)->getMaxUpstreamRes();
if(max_res < res)
{
max_res = res;
}
}
return max_res;
}
double ElectricalTimingNode::getTotalDownstreamCap() const
{
double cap_sum = 0;
for(unsigned int i = 0; i < m_downstream_nodes_->size(); ++i)
{
cap_sum += m_downstream_nodes_->at(i)->getTotalDownstreamCap();
}
return cap_sum;
}
vector<ElectricalTimingNode*>* ElectricalTimingNode::getUpstreamNodes() const
{
return m_upstream_nodes_;
}
vector<ElectricalTimingNode*>* ElectricalTimingNode::getDownstreamNodes() const
{
return m_downstream_nodes_;
}
const String& ElectricalTimingNode::getInstanceName() const
{
return m_instance_name_;
}
ElectricalModel* ElectricalTimingNode::getModel()
{
return m_model_;
}
bool ElectricalTimingNode::isDriver() const
{
return false;
}
bool ElectricalTimingNode::isNet() const
{
return false;
}
bool ElectricalTimingNode::isLoad() const
{
return false;
}
const ElectricalModel* ElectricalTimingNode::getModel() const
{
return (const ElectricalModel*) m_model_;
}
void ElectricalTimingNode::addDownstreamNode(ElectricalTimingNode* node_)
{
m_downstream_nodes_->push_back(node_);
node_->m_upstream_nodes_->push_back(this);
return;
}
void ElectricalTimingNode::setFalsePath(bool false_path_)
{
m_false_path_ = false_path_;
return;
}
bool ElectricalTimingNode::getFalsePath() const
{
return m_false_path_;
}
//-------------------------------------------------------------------------
// Functions for delay optimization
//-------------------------------------------------------------------------
// By default, electrical timing nodes cannot be sized up/down
bool ElectricalTimingNode::hasMaxDrivingStrength() const
{
return true;
}
bool ElectricalTimingNode::hasMinDrivingStrength() const
{
return true;
}
void ElectricalTimingNode::increaseDrivingStrength()
{
return;
}
void ElectricalTimingNode::decreaseDrivingStrength()
{
return;
}
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Node variables for critical path delay calculations
//-------------------------------------------------------------------------
void ElectricalTimingNode::setCritPath(int crit_path_)
{
m_crit_path_ = crit_path_;
return;
}
int ElectricalTimingNode::getCritPath() const
{
return m_crit_path_;
}
void ElectricalTimingNode::setVisitedNum(int visited_num_)
{
m_visited_num_ = visited_num_;
return;
}
int ElectricalTimingNode::getVisitedNum() const
{
return m_visited_num_;
}
void ElectricalTimingNode::setDelayLeft(double delay_left_)
{
m_delay_left_ = delay_left_;
}
double ElectricalTimingNode::getDelayLeft() const
{
return m_delay_left_;
}
//-------------------------------------------------------------------------
} // namespace DSENT
|
c++
| 13 | 0.583907 | 101 | 28.061538 | 195 |
research_code
|
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.ballerinalang.model.expressions;
import org.ballerinalang.core.utils.BTestUtils;
import org.ballerinalang.model.BLangProgram;
import org.ballerinalang.model.values.BBoolean;
import org.ballerinalang.model.values.BInteger;
import org.ballerinalang.model.values.BValue;
import org.ballerinalang.util.program.BLangFunctions;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class OperatorPrecedenceTest {
private BLangProgram bLangProgram;
@BeforeClass
public void setup() {
bLangProgram = BTestUtils.parseBalFile("lang/expressions/operator-precedence.bal");
}
@Test
public void testAddSubPrecedence() {
addSubPrecedence(10, 5, 1);
addSubPrecedence(-6, 8, 6);
addSubPrecedence(-3, -7, 5);
addSubPrecedence(-9, -10, -4);
addSubPrecedence(2, -13, 11);
addSubPrecedence(14, 6, -17);
addSubPrecedence(0, 2, 5);
}
private void addSubPrecedence(int a, int b, int c) {
int expected = a - b + c;
BValue[] args = { new BInteger(a), new BInteger(b), new BInteger(c) };
BValue[] returns = BLangFunctions.invoke(bLangProgram, "addSubPrecedence", args);
Assert.assertEquals(returns.length, 1);
Assert.assertSame(returns[0].getClass(), BInteger.class);
int actual = ((BInteger) returns[0]).intValue();
Assert.assertEquals(actual, expected);
}
@Test
public void testAddSubMultPrecedence() {
addSubMultPrecedence(10, 5, 1, 20, 8, 3);
addSubMultPrecedence(-6, 9, 12, 35, 10, 78);
addSubMultPrecedence(5, -39, 54, 65, 13, 10);
addSubMultPrecedence(25, 3, -6, 9, 7, 10);
addSubMultPrecedence(7, 4, 6, -3, 8, 40);
addSubMultPrecedence(13, 12, 74, 65, -10, 37);
addSubMultPrecedence(0, 12, 74, 65, 10, -37);
addSubMultPrecedence(-4, 0, -14, 0, -10, -63);
}
private void addSubMultPrecedence(int a, int b, int c, int d, int e, int f) {
int expected = a * b - c + d * e - f;
BValue[] args = {
new BInteger(a), new BInteger(b), new BInteger(c), new BInteger(d), new BInteger(e), new BInteger(f)
};
BValue[] returns = BLangFunctions.invoke(bLangProgram, "addSubMultPrecedence", args);
Assert.assertEquals(returns.length, 1);
Assert.assertSame(returns[0].getClass(), BInteger.class);
int actual = ((BInteger) returns[0]).intValue();
Assert.assertEquals(actual, expected);
}
@Test
public void testMultDivisionPrecedence() {
// c != 0 , f != 0
multDivisionPrecedence(10, 5, 7, 0, 8, 3);
multDivisionPrecedence(18, -3, 6, 74, 4, -40);
multDivisionPrecedence(0, 9, -7, 41, 9, -40);
multDivisionPrecedence(0, -9, -7, -41, -9, -40);
multDivisionPrecedence(80, -1, 2, 3, -4, 5);
multDivisionPrecedence(2, -13, 28, -36, 74, -9);
multDivisionPrecedence(54, 96, 45, -36, 74, -9);
multDivisionPrecedence(93, 81, 3, 74, 0, -9);
}
private void multDivisionPrecedence(int a, int b, int c, int d, int e, int f) {
int expected = a * b / c * d * e / f;
BValue[] args = {
new BInteger(a), new BInteger(b), new BInteger(c), new BInteger(d), new BInteger(e), new BInteger(f)
};
BValue[] returns = BLangFunctions.invoke(bLangProgram, "multDivisionPrecedence", args);
Assert.assertEquals(returns.length, 1);
Assert.assertSame(returns[0].getClass(), BInteger.class);
int actual = ((BInteger) returns[0]).intValue();
Assert.assertEquals(actual, expected);
}
@Test
public void testAddMultPrecedence() {
addMultPrecedence(5, 6, 7, 8, 9, 10);
addMultPrecedence(64, -79, 14, -36, 39, -40);
addMultPrecedence(-15, 86, -67, 38, -79, 20);
addMultPrecedence(9, 8, 0, 6, -9, 3);
addMultPrecedence(0, 0, 0, 0, 0, 0);
}
private void addMultPrecedence(int a, int b, int c, int d, int e, int f) {
int expected = a * b * c + d * e + f;
BValue[] args = {
new BInteger(a), new BInteger(b), new BInteger(c), new BInteger(d), new BInteger(e), new BInteger(f)
};
BValue[] returns = BLangFunctions.invoke(bLangProgram, "addMultPrecedence", args);
Assert.assertEquals(returns.length, 1);
Assert.assertSame(returns[0].getClass(), BInteger.class);
int actual = ((BInteger) returns[0]).intValue();
Assert.assertEquals(actual, expected);
}
@Test
public void testAddDivisionPrecedence() {
// b != 0, c != 0, e != 0
addDivisionPrecedence(5, 6, 7, 8, 9, 10);
addDivisionPrecedence(64, -79, 14, -36, 39, -40);
addDivisionPrecedence(-15, 86, -67, 38, -79, 20);
}
private void addDivisionPrecedence(int a, int b, int c, int d, int e, int f) {
int expected = a / b / c + d / e + f;
BValue[] args = {
new BInteger(a), new BInteger(b), new BInteger(c), new BInteger(d), new BInteger(e), new BInteger(f)
};
BValue[] returns = BLangFunctions.invoke(bLangProgram, "addDivisionPrecedence", args);
Assert.assertEquals(returns.length, 1);
Assert.assertSame(returns[0].getClass(), BInteger.class);
int actual = ((BInteger) returns[0]).intValue();
Assert.assertEquals(actual, expected);
}
@Test
public void testComparatorPrecedence() {
// false && true || false
comparatorPrecedence(10, 20, 30, 40, 50, 60);
// true && true || false
comparatorPrecedence(0, 5, 5, 9, 34, 80);
// true && true || true
comparatorPrecedence(0, 5, 5, 9, 34, 6);
}
private void comparatorPrecedence(int a, int b, int c, int d, int e, int f) {
boolean expected = (a > b) && (c < d) || (e > f);
BValue[] args = {
new BInteger(a), new BInteger(b), new BInteger(c), new BInteger(d), new BInteger(e), new BInteger(f)
};
BValue[] returns = BLangFunctions.invoke(bLangProgram, "comparatorPrecedence", args);
Assert.assertEquals(returns.length, 1);
Assert.assertSame(returns[0].getClass(), BBoolean.class);
boolean actual = ((BBoolean) returns[0]).booleanValue();
Assert.assertEquals(actual, expected);
}
@Test(description = "Test if addition and subtraction takes same precedence")
public void testAdditionAndSubtractionPrecedence() {
int a = 10;
int b = 20;
int c = 30;
int d = 40;
int expectedResult = a - b + c - d;
BValue[] args = {new BInteger(a), new BInteger(b), new BInteger(c), new BInteger(d)};
BValue[] returns = BLangFunctions.invoke(bLangProgram, "intAdditionAndSubtractionPrecedence", args);
int actualResult = ((BInteger) returns[0]).intValue();
Assert.assertEquals(actualResult, expectedResult, "The results of addition and " +
"subtraction operation differ");
}
@Test(description = "Test if multiplication takes precedence over addition and substraction")
public void testMultiplicationPrecedence() {
int a = 10;
int b = 20;
int c = 30;
int d = 40;
int x = (a + b) * (c * d) + a * b;
int y = (a + b) * (c * d) - a * b;
int z = a + b * c * d - a * b;
int expectedResult = x + y - z;
BValue[] args = {new BInteger(a), new BInteger(b), new BInteger(c), new BInteger(d)};
BValue[] returns = BLangFunctions.invoke(bLangProgram, "intMultiplicationPrecedence", args);
int actualResult = ((BInteger) returns[0]).intValue();
Assert.assertEquals(actualResult, expectedResult, "The results of multiplication operation differ");
}
@Test(description = "Test if division takes precedence over addition and subtraction")
public void testDivisionPrecedence() {
int a = 10;
int b = 20;
int c = 30;
int d = 40;
int x = (a + b) / (c + d) + a / b;
int y = (a + b) / (c - d) - a / b;
int z = a + b / c - d - a / b;
int expectedResult = x - y + z;
BValue[] args = {new BInteger(a), new BInteger(b), new BInteger(c), new BInteger(d)};
BValue[] returns = BLangFunctions.invoke(bLangProgram, "intDivisionPrecedence", args);
int actualResult = ((BInteger) returns[0]).intValue();
Assert.assertEquals(actualResult, expectedResult, "The results of division operation differ");
}
@Test(description = "Test if division and multiplication takes same precedence over addition and subtraction")
public void testDivisionAndMultiplicationPrecedence() {
int a = 10;
int b = 20;
int c = 30;
int d = 40;
int x = (a + b) * (c + d) + a / b;
int y = (a + b) / (c - d) - a * b;
int z = a + b / c - d + a * b;
int expectedResult = x + y + z;
BValue[] args = {new BInteger(a), new BInteger(b), new BInteger(c), new BInteger(d)};
BValue[] returns = BLangFunctions.invoke(bLangProgram, "intMultiplicationAndDivisionPrecedence", args);
int actualResult = ((BInteger) returns[0]).intValue();
Assert.assertEquals(actualResult, expectedResult, "The results of multiplication and " +
"division operation differ");
}
}
|
java
| 12 | 0.608498 | 116 | 36.069597 | 273 |
starcoderdata
|
from dataclasses import dataclass
import pytest
from fastapi.testclient import TestClient
from app.main import app
@dataclass
class TestData:
req = {}
emp_count = 0
@pytest.fixture(scope='session')
def response_data():
data = TestData()
return data
@pytest.fixture(scope="module")
def test_app():
client = TestClient(app)
yield client
@pytest.fixture(scope="module")
def test_data():
test_employee_data = \
{
"name": "
"email": "
"age": 33,
"company": "ExampleCompany",
"join_date": "2002-12-25T05:04:16-08:00",
"job_title": "driver",
"gender": "male",
"salary": 1250
}
return test_employee_data
|
python
| 9 | 0.580726 | 53 | 18.487805 | 41 |
starcoderdata
|
package se.mickelus.mgui.gui;
public class GuiClickable extends GuiElement {
protected final Runnable onClickHandler;
public GuiClickable(int x, int y, int width, int height, Runnable onClickHandler) {
super(x, y, width, height);
this.onClickHandler = onClickHandler;
}
@Override
public void draw(int refX, int refY, int screenWidth, int screenHeight, int mouseX, int mouseY, float opacity) {
super.draw(refX, refY, screenWidth, screenHeight, mouseX, mouseY, opacity);
}
@Override
public boolean onClick(int x, int y) {
if (hasFocus()) {
onClickHandler.run();
return true;
}
return false;
}
}
|
java
| 10 | 0.639831 | 116 | 25.222222 | 27 |
starcoderdata
|
#include "MeanShift.h"
#include "Mgr.h"
#include "ParamMgr.h"
#include "FF.h"
namespace clustering
{
MeanShift::MeanShift()
{
_iterCnt.resize(getMgr().getFFSize());
for (int i = 0; i < (int)_iterCnt.size(); i++)
{
_iterCnt[i].second = i;
}
}
void MeanShift::run()
{
buildRtree();
initKNNs();
shiftFFs();
}
void MeanShift::buildRtree()
{
auto& m = getMgr();
std::vector points;
points.reserve(m.getFFSize());
for (FF_id id = 0; id < m.getFFSize(); id++)
{
FF& f = m.getFF(id);
points.emplace_back(std::make_pair(Point(f.getX(),f.getY()), id));
}
_rtree.insert(points.begin(), points.end());
}
void MeanShift::initKNNs()
{
auto& m = getMgr();
#pragma omp parallel for num_threads(getParamMgr().ThreadNum)
for (FF_id id = 0; id < m.getFFSize(); id++)
{
FF& f = m.getFF(id);
getKNN(id);
if (f.getNeighborSize()==1)
{
f.setShifting(false);
}
else
{
f.setBandWidth();
}
}
}
void MeanShift::getKNN(FF_id id)
{
auto& m = getMgr();
FF& f = m.getFF(id);
std::vector neighbors;
neighbors.reserve(getParamMgr().K);
_rtree.query(bgi::nearest(Point(f.getOrigX(), f.getOrigY()), getParamMgr().K),
std::back_inserter(neighbors));
BOOST_FOREACH(PointWithID const&p, neighbors)
{
double dis = SquareEuclideanDistance(m.getFF(id).getOrigCoor(),
m.getFF(p.second).getOrigCoor());
if (dis < getParamMgr().SqrMaxDisp) f.addNeighbor(p.second, dis);
}
f.sortNeighbors();
}
void MeanShift::shiftFFs()
{
auto& m = getMgr();
#pragma omp parallel for num_threads(getParamMgr().ThreadNum)
for (int i = 0; i < m.getFFSize(); i++)
{
FF& nowFF = m.getFF(i);
if (!nowFF.isShifting())
{
_iterCnt[nowFF.getID()].first = 0;
continue;
}
int iter = 0;
while (++iter)
{
eDist dis = nowFF.doShifting();
if (dis <= getParamMgr().Tol)
{
nowFF.setShifting (false);
_iterCnt[nowFF.getID()].first = iter;
break;
}
}
}
std::sort (_iterCnt.begin(), _iterCnt.end(),
std::less<std::pair<int, FF_id> >());
}
}
|
c++
| 18 | 0.522635 | 83 | 25.042105 | 95 |
starcoderdata
|
#include "import-command-task.hxx"
#include
#include
#include
#include
#include "ansi.hxx"
#include
#include "Database3.hxx"
#include "utils.hxx"
#include "logger.hxx"
#include "command-utils.hxx"
#include "database-utils.hxx"
namespace fs = std::filesystem;
namespace bpo = boost::program_options;
using ansi::style;
namespace {
bool is_stdin(const std::string& s) { return s == "-"; }
class InputFiles : public std::vector {
public:
using std::vector
bool contain_stdin() const {
return std::any_of(cbegin(), cend(), is_stdin);
}
};
class invalid_option_file_not_found : public bpo::error_with_option_name {
public:
explicit invalid_option_file_not_found(const std::string& bad_value)
: bpo::error_with_option_name("argument ('%value%') is an invalid path for option '%canonical_option%'")
{
set_substitute_default("value", "argument ('%value%')", "(empty string)");
set_substitute("value", bad_value);
}
};
class invalid_option_duplicated_value : public bpo::error_with_option_name {
public:
explicit invalid_option_duplicated_value(const std::string& bad_value)
: bpo::error_with_option_name("argument ('%value%') is specified multiple times for option '%canonical_option%'")
{
set_substitute_default("value", "argument ('%value%')", "(empty string)");
set_substitute("value", bad_value);
}
};
void validate(boost::any& v,
const std::vector values,
InputFiles* /*target_type*/, int)
{
// Make sure no previous assignment to 'v' was made.
bpo::validators::check_first_occurrence(v);
// Check unicity of values.
std::vector value_cpy = values;
std::sort(value_cpy.begin(), value_cpy.end());
auto it = std::adjacent_find(value_cpy.begin(), value_cpy.end());
if (it != value_cpy.end())
throw invalid_option_duplicated_value(*it);
for(const std::string& value : values) {
if (is_stdin(value))
continue;
if (!std::filesystem::is_regular_file(value))
throw invalid_option_file_not_found(value);
}
v = boost::any(InputFiles(values.begin(), values.end()));
}
struct pretty_input_name {
const std::string& name;
pretty_input_name(const std::string& name) : name(name) {}
};
std::ostream& operator<<(std::ostream& os, const pretty_input_name& input) {
if (input.name == "-")
os << "stdin";
else
os << input.name;
return os;
}
class ConsoleCommandImporter : public CommandImporter
{
public:
using CommandImporter::CommandImporter;
protected:
void on_command(size_t item, const std::string& line, const CompilationCommand& command) override
{
LOG_CTX() << style::green_fg << "Command #" << item << ": " << style::reset << line;
CommandImporter::on_command(item, line, command);
LOG(debug) << style::blue_fg << "Directory: " << style::reset << command.directory;
LOG(debug) << style::blue_fg << "Output: " << style::reset << command.output << " (" << command.output_type << ")";
}
};
} // anonymous namespace
boost::program_options::options_description ImportCommand_Task::options()
{
bpo::options_description opt("Options");
opt.add_options()
("json", bpo::value "-")->default_value({}, ""),
"Specify that input files are in the JSON compilation database format.\n"
"Use - to read from the standard input (default).")
("list", bpo::value "-")->default_value({}, ""),
"Specify that input files are in text format (one command per line).\n"
"Use - to read from the standard input (default).")
("extract-dependencies", "Extract dependencies from the stored commands.")
("extract-symbols", "Extract symbols from artifacts.")
;
return opt;
}
void ImportCommand_Task::parse_args(const std::vector args)
{
bpo::store(bpo::command_line_parser(args).options(options()).run(), vm);
bpo::notify(vm);
if (/*vm.count("json") > 0 &&*/ vm["json"].as
/*&& vm.count("list") > 0*/ && vm["list"].as {
throw bpo::error("argument '-' (aka stdin) cannot be used multiple times");
}
}
void ImportCommand_Task::execute(Database3& db)
{
ConsoleCommandImporter importer(db);
for(const auto& src : vm["json"].as {
LOG_CTX_FLUSH(info) << "Importing json compilation database from " << pretty_input_name(src);
importer.reset_count();
if (src == "-") {
importer.import_compile_commands(std::cin);
} else {
std::ifstream in(src);
importer.import_compile_commands(in);
}
LOG(info) << importer.count_inserted() << " commands imported";
}
for(const auto& src : vm["list"].as {
LOG_CTX_FLUSH(info) << "Importing list of commands from " << pretty_input_name(src);
importer.reset_count();
if (src == "-") {
importer.import_commands(std::cin);
} else {
std::ifstream in(src);
importer.import_commands(in);
}
LOG(info) << importer.count_inserted() << " commands imported";
}
db.set_timestamp("import-commands", std::chrono::high_resolution_clock::now());
if (vm.count("extract-dependencies")) {
db.load_dependencies();
}
if (vm.count("extract-symbols")) {
db.load_symbols();
}
}
|
c++
| 22 | 0.646685 | 125 | 29.247253 | 182 |
starcoderdata
|
using System;
namespace EcadTeste.Api.DTOs
{
public class AutorMusicaRequestDTO
{
public Guid IdAutor { get; set; }
public Guid IdCategoria { get; set; }
}
}
|
c#
| 8 | 0.681818 | 53 | 21 | 11 |
starcoderdata
|
#ifndef CALLER_PIPELINECONTEXT_HPP
#define CALLER_PIPELINECONTEXT_HPP
#include
#include
#include
#include
#include
#include
CALLER_BEGIN
class IOHandler;
class CALLER_DLL_EXPORT PipelineContext
{
public:
PipelineContext();
virtual ~PipelineContext();
public:
virtual Future connect(const Endpoint &endpoint) = 0;
virtual Future disconnect() = 0;
virtual Future close() = 0;
virtual void read(ByteBuffer buffer) = 0;
virtual void write(const Any &object, const ByteBuffer &buffer) = 0;
virtual Executor* executor() = 0;
virtual IOHandler* handler() = 0;
virtual void notifyActive() = 0;
virtual void notifyInactive() = 0;
virtual void notifyReadComplete() = 0;
virtual void notifyWriteComplete() = 0;
public:
virtual PipelinePtr pipeline() = 0;
};
CALLER_END
#endif // CALLER_PIPELINECONTEXT_HPP
|
c++
| 12 | 0.515443 | 88 | 37.378378 | 37 |
starcoderdata
|
private void fetchContentInfo() throws ProxyCacheException {
Response response = null;
// InputStream inputStream = null;
try {
response = openConnectionForHeader();
if (response == null || !response.isSuccessful()) {
throw new ProxyCacheException("Fail to fetchContentInfo: " + sourceInfo.url);
}
String contentLength = response.header("Content-Length");
long length = contentLength == null ? -1 : Long.parseLong(contentLength);
String mime = response.header("Content-Type", "application/mp4");
// inputStream = response.body().byteStream();
this.sourceInfo = new SourceInfo(sourceInfo.url, length, mime);
this.sourceInfoStorage.put(sourceInfo.url, sourceInfo);
Log.i(TAG, "Content info for `" + sourceInfo.url + "`: mime: " + mime + ", content-length: " + length);
} catch (IOException e) {
Log.e(TAG, "Error fetching info from " + sourceInfo.url, e);
} finally {
// ProxyCacheUtils.close(inputStream);
if (response != null && requestCall != null) {
requestCall.cancel();
}
}
}
|
java
| 14 | 0.57899 | 115 | 50.208333 | 24 |
inline
|
package unito.api;
/**
* Checks the result of the operation
* Created by bynull on 03.06.16.
*/
public interface Spec<T, R> {
void check(T input, R result) throws Exception;
}
|
java
| 6 | 0.68306 | 51 | 19.444444 | 9 |
starcoderdata
|
void absorbContinuousEvidence() {
for (Map.Entry<SingularContinuousVariable, Double> entry : evidences.continuous().entrySet()) {
SingularContinuousVariable variable = entry.getKey();
MixedClique clique = tree.getClique(variable);
// ignore variable not contained in this model
if (clique == null) {
continue;
}
if (evidencesAbsorbed && !clique.focus())
continue;
// proceeds if evidences haven't been absorbed or the clique is
// under focus
clique.absorbEvidence(variable, entry.getValue());
}
}
|
java
| 11 | 0.703499 | 97 | 24.904762 | 21 |
inline
|
namespace Naos.ServiceContext.Application.Web
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using EnsureThat;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Naos.Configuration.Application;
using Naos.Foundation;
using Naos.Foundation.Application;
using NSwag.Annotations;
[Route("naos/servicecontext")]
[ApiController]
public class NaosServiceContextRootController : ControllerBase // or use normal middleware? https://stackoverflow.com/questions/47617994/how-to-use-a-controller-in-another-assembly-in-asp-net-core-mvc-2-0?rq=1
{
private readonly ILogger logger;
private readonly ServiceDescriptor serviceDescriptor;
private readonly IEnumerable features;
public NaosServiceContextRootController(
ILogger logger,
ServiceDescriptor serviceDescriptor,
IEnumerable features)
{
EnsureArg.IsNotNull(logger, nameof(logger));
this.logger = logger;
this.serviceDescriptor = serviceDescriptor;
this.features = features;
}
[HttpGet]
[ProducesResponseType((int)HttpStatusCode.OK)]
[OpenApiTag("Naos Info")]
public async Task Get()
{
var baseUrl = this.Request.GetUri(true);
foreach (var feature in this.features.Safe())
{
if (!feature.EchoRoute.IsNullOrEmpty() && !feature.EchoRoute.StartsWith("http", System.StringComparison.OrdinalIgnoreCase))
{
feature.EchoRoute = this.Url.AbsolutePath(feature.EchoRoute);
}
}
var result = new EchoResponse
{
Service = this.serviceDescriptor,
Request = new Dictionary<string, object> // TODO: replace with RequestCorrelationContext
{
["correlationId"] = this.HttpContext.GetCorrelationId(),
["requestId"] = this.HttpContext.GetRequestId(),
["isLocal"] = this.HttpContext.Request.IsLocal(),
["host"] = Dns.GetHostName(),
["ip"] = (await Dns.GetHostAddressesAsync(Dns.GetHostName()).AnyContext()).Select(i => i.ToString()).Where(i => i.Contains(".", StringComparison.OrdinalIgnoreCase))
//["userIdentity"] = serviceContext.UserIdentity,
//["username"] = serviceContext.Username
},
Runtime = new Dictionary<string, string>
{
// TODO: get these endpoints through DI for all active capabilities
["name"] = Assembly.GetEntryAssembly().GetName().Name,
["version"] = Assembly.GetEntryAssembly().GetName().Version.ToString(),
//["versionFile"] = Assembly.GetEntryAssembly().GetCustomAttribute
["versionInformation"] = Assembly.GetEntryAssembly().GetCustomAttribute
["buildDate"] = Assembly.GetEntryAssembly().GetBuildDate().ToString("o"),
["processName"] = Process.GetCurrentProcess().ProcessName.SafeEquals("dotnet") ? $"{Process.GetCurrentProcess().ProcessName} (kestrel)" : Process.GetCurrentProcess().ProcessName,
["framework"] = RuntimeInformation.FrameworkDescription.ToString(),
["osDescription"] = RuntimeInformation.OSDescription,
["osArchitecture"] = RuntimeInformation.OSArchitecture.ToString(),
["processorCount"] = Environment.ProcessorCount.ToString(),
},
Actions = new Dictionary<string, string>
{
// TODO: get these endpoints through DI for all active capabilities
["index"] = this.Url.AbsolutePath("index.html"),
["logevents-ui"] = this.Url.AbsolutePath("naos/operations/logevents/dashboard"),
["swagger-ui"] = this.Url.AbsolutePath("swagger/index.html"),
["swagger"] = this.Url.AbsolutePath("swagger/v1/swagger.json"),
["health"] = this.Url.AbsolutePath("health"),
// TODO: discover below
["sample-logevents1"] = this.Url.AbsolutePath("naos/operations/logevents"),
["sample-logevents2"] = this.Url.AbsolutePath("naos/operations/logevents?q=Ticks=gt:636855734000000000,Environment=Development"),
["sample-logevents3"] = this.Url.AbsolutePath("naos/operations/logevents?q=Epoch=ge:1546347600,Level=Warning"),
["sample-countries1"] = this.Url.AbsolutePath("api/countries/be"),
["sample-countries2"] = this.Url.AbsolutePath("api/countries?q=name=Belgium&order=name&take=1"),
["sample-countries3"] = this.Url.AbsolutePath("api/countries?q=name=Belgium"),
["sample-customers1"] = this.Url.AbsolutePath("api/customers?q=region=East,state.createdDate=ge:2010-01-01&order=lastName"),
["sample-customers2"] = this.Url.AbsolutePath("api/customers?q=region=East,state.createdDate=ge:2010-01-01"),
["sample-useraccounts1"] = this.Url.AbsolutePath("api/useraccounts?q=visitCount=ge:1&order=email&take=10"),
["sample-useraccounts2"] = this.Url.AbsolutePath("api/useraccounts?q=visitCount=ge:1"),
},
Features = this.features
};
return this.Ok(result);
}
private class EchoResponse
{
public ServiceDescriptor Service { get; set; }
public Dictionary<string, object> Request { get; set; }
public IDictionary<string, string> Runtime { get; set; }
public IEnumerable Features { get; set; }
public IDictionary<string, string> Actions { get; set; }
}
}
}
|
c#
| 30 | 0.612226 | 214 | 53.02521 | 119 |
starcoderdata
|
/*
* videoConfig.h
* ARToolKit5
*
* This file is part of ARToolKit.
*
* ARToolKit is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARToolKit is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ARToolKit. If not, see
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent modules, and to
* copy and distribute the resulting executable under terms of your choice,
* provided that you also meet, for each linked independent module, the terms and
* conditions of the license of that module. An independent module is a module
* which is neither derived from nor based on this library. If you modify this
* library, you may extend this exception to your version of the library, but you
* are not obligated to do so. If you do not wish to do so, delete this exception
* statement from your version.
*
* Copyright 2015 Daqri, LLC.
* Copyright 2002-2015 ARToolworks, Inc.
*
* Author(s):
*
*/
#ifndef AR_CONFIG_H
#define AR_CONFIG_H
#include
#ifdef AR_INPUT_V4L
#define AR_VIDEO_V4L_MODE_PAL 0
#define AR_VIDEO_V4L_MODE_NTSC 1
#define AR_VIDEO_V4L_MODE_SECAM 2
#define AR_VIDEO_V4L_DEFAULT_DEVICE "/dev/video0"
#define AR_VIDEO_V4L_DEFAULT_WIDTH 640
#define AR_VIDEO_V4L_DEFAULT_HEIGHT 480
#define AR_VIDEO_V4L_DEFAULT_CHANNEL 3
#define AR_VIDEO_V4L_DEFAULT_MODE AR_VIDEO_V4L_MODE_NTSC
#endif
#ifdef AR_INPUT_V4L2
#define AR_VIDEO_V4L2_MODE_PAL 0
#define AR_VIDEO_V4L2_MODE_NTSC 1
#define AR_VIDEO_V4L2_MODE_SECAM 2
#define AR_VIDEO_V4L2_DEFAULT_DEVICE "/dev/video0"
#define AR_VIDEO_V4L2_DEFAULT_WIDTH 640
#define AR_VIDEO_V4L2_DEFAULT_HEIGHT 480
#define AR_VIDEO_V4L2_DEFAULT_CHANNEL 0
#define AR_VIDEO_V4L2_DEFAULT_MODE AR_VIDEO_V4L2_MODE_NTSC
#endif
#ifdef AR_INPUT_1394CAM
#define AR_VIDEO_1394_MODE_320x240_YUV422 32
#define AR_VIDEO_1394_MODE_640x480_YUV411 33
#define AR_VIDEO_1394_MODE_640x480_YUV411_HALF 34
#define AR_VIDEO_1394_MODE_640x480_YUV422 35
#define AR_VIDEO_1394_MODE_640x480_RGB 36
#define AR_VIDEO_1394_MODE_640x480_MONO 37
#define AR_VIDEO_1394_MODE_640x480_MONO_COLOR 38
#define AR_VIDEO_1394_MODE_640x480_MONO_COLOR_HALF 39
#define AR_VIDEO_1394_MODE_640x480_MONO_COLOR2 40
#define AR_VIDEO_1394_MODE_640x480_MONO_COLOR_HALF2 41
#define AR_VIDEO_1394_MODE_640x480_MONO_COLOR3 42
#define AR_VIDEO_1394_MODE_640x480_MONO_COLOR_HALF3 43
#define AR_VIDEO_1394_MODE_1024x768_MONO 44
#define AR_VIDEO_1394_MODE_1024x768_MONO_COLOR 45
#define AR_VIDEO_1394_MODE_1024x768_MONO_COLOR_HALF 46
#define AR_VIDEO_1394_MODE_1024x768_MONO_COLOR2 47
#define AR_VIDEO_1394_MODE_1024x768_MONO_COLOR_HALF2 48
#define AR_VIDEO_1394_MODE_1024x768_MONO_COLOR3 49
#define AR_VIDEO_1394_MODE_1024x768_MONO_COLOR_HALF3 50
#define AR_VIDEO_1394_MODE_1280x720_MONO 51
#define AR_VIDEO_1394_MODE_1280x720_MONO_COLOR 52
#define AR_VIDEO_1394_MODE_1280x720_MONO_COLOR_HALF 53
#define AR_VIDEO_1394_MODE_1280x720_MONO_COLOR2 54
#define AR_VIDEO_1394_MODE_1280x720_MONO_COLOR_HALF2 55
#define AR_VIDEO_1394_MODE_1280x720_MONO_COLOR3 56
#define AR_VIDEO_1394_MODE_1280x720_MONO_COLOR_HALF3 57
#define AR_VIDEO_1394_MODE_1600x900_MONO 58
#define AR_VIDEO_1394_MODE_1600x900_MONO_COLOR 59
#define AR_VIDEO_1394_MODE_1600x900_MONO_COLOR_HALF 60
#define AR_VIDEO_1394_MODE_1600x900_MONO_COLOR2 61
#define AR_VIDEO_1394_MODE_1600x900_MONO_COLOR_HALF2 62
#define AR_VIDEO_1394_MODE_1600x900_MONO_COLOR3 63
#define AR_VIDEO_1394_MODE_1600x900_MONO_COLOR_HALF3 64
#define AR_VIDEO_1394_MODE_1600x1200_MONO 65
#define AR_VIDEO_1394_MODE_1600x1200_MONO_COLOR 66
#define AR_VIDEO_1394_MODE_1600x1200_MONO_COLOR_HALF 67
#define AR_VIDEO_1394_MODE_1600x1200_MONO_COLOR2 68
#define AR_VIDEO_1394_MODE_1600x1200_MONO_COLOR_HALF2 69
#define AR_VIDEO_1394_MODE_1600x1200_MONO_COLOR3 70
#define AR_VIDEO_1394_MODE_1600x1200_MONO_COLOR_HALF3 71
#define AR_VIDEO_1394_FRAME_RATE_1_875 1
#define AR_VIDEO_1394_FRAME_RATE_3_75 2
#define AR_VIDEO_1394_FRAME_RATE_7_5 3
#define AR_VIDEO_1394_FRAME_RATE_15 4
#define AR_VIDEO_1394_FRAME_RATE_30 5
#define AR_VIDEO_1394_FRAME_RATE_60 6
#define AR_VIDEO_1394_FRAME_RATE_120 7
#define AR_VIDEO_1394_FRAME_RATE_240 8
#define AR_VIDEO_1394_SPEED_400 1
#define AR_VIDEO_1394_SPEED_800 2
#if AR_INPUT_1394CAM_DEFAULT_PIXEL_FORMAT == AR_PIXEL_FORMAT_MONO
#if defined(AR_INPUT_1394CAM_USE_FLEA_XGA)
#define AR_VIDEO_1394_DEFAULT_MODE AR_VIDEO_1394_MODE_1024x768_MONO
#else
#define AR_VIDEO_1394_DEFAULT_MODE AR_VIDEO_1394_MODE_640x480_MONO
#endif
#else
#if defined(AR_INPUT_1394CAM_USE_DRAGONFLY)
#define AR_VIDEO_1394_DEFAULT_MODE AR_VIDEO_1394_MODE_640x480_MONO_COLOR
#elif defined(AR_INPUT_1394CAM_USE_DF_EXPRESS)
#define AR_VIDEO_1394_DEFAULT_MODE AR_VIDEO_1394_MODE_640x480_MONO_COLOR2
#elif defined(AR_INPUT_1394CAM_USE_FLEA)
#define AR_VIDEO_1394_DEFAULT_MODE AR_VIDEO_1394_MODE_640x480_MONO_COLOR2
#elif defined(AR_INPUT_1394CAM_USE_FLEA_XGA)
#define AR_VIDEO_1394_DEFAULT_MODE AR_VIDEO_1394_MODE_1024x768_MONO_COLOR
#elif defined(AR_INPUT_1394CAM_USE_DFK21AF04)
#define AR_VIDEO_1394_DEFAULT_MODE AR_VIDEO_1394_MODE_640x480_MONO_COLOR3
#else
#define AR_VIDEO_1394_DEFAULT_MODE AR_VIDEO_1394_MODE_640x480_YUV411
#endif
#endif
#define AR_VIDEO_1394_DEFAULT_FRAME_RATE AR_VIDEO_1394_FRAME_RATE_30
#define AR_VIDEO_1394_DEFAULT_SPEED AR_VIDEO_1394_SPEED_400
#define AR_VIDEO_1394_DEFAULT_PORT 0
#endif
#ifdef AR_INPUT_WINDOWS_DIRECTSHOW
#endif
#ifdef AR_INPUT_WINDOWS_DRAGONFLY
#endif
#ifdef AR_INPUT_QUICKTIME
#endif
#endif // !AR_CONFIG_H
|
c
| 12 | 0.680226 | 95 | 44.384615 | 156 |
starcoderdata
|
"""
Errors for papi user clients.
:Copyright:
Copyright 2014 Lastline, Inc. All Rights Reserved.
"""
class Error(Exception):
"""
Base class for all exceptions in the papi_client module
"""
|
python
| 5 | 0.70696 | 64 | 23.818182 | 11 |
starcoderdata
|
#include "Alignment.h"
using namespace std;
string charDequeToString(deque chars){
string str = "";
for(char c : chars){
str += c;
}
return str;
}
Alignment::Alignment(string* a, string* b, string aName, string bName)
: seqA(*a), seqB(*b), lenX(seqA.length()+1), lenY(seqB.length()+1)
{
seqAName = aName;
seqBName = bName;
makeNuclSimMatrix();
initCharIndex();
allocateBacktrackMatrix();
allocateSimMatrix();
initMatrix();
}
Alignment::Alignment(NuclSeq* a, NuclSeq* b)
: seqA(*(a->getContent())), seqB(*(b->getContent())), lenX(seqA.length()+1), lenY(seqB.length()+1)
{
seqAName = *(a->name);
seqBName = *(b->name);
makeNuclSimMatrix();
initCharIndex();
allocateBacktrackMatrix();
allocateSimMatrix();
initMatrix();
}
void Alignment::initCharIndex(){
for(int i = 0; i < 256; i++){
charIndex[i] = -1;
}
charIndex[(int)'A'] = 0;
charIndex[(int)'a'] = 0;
charIndex[(int)'T'] = 1;
charIndex[(int)'t'] = 1;
charIndex[(int)'G'] = 2;
charIndex[(int)'g'] = 2;
charIndex[(int)'C'] = 3;
charIndex[(int)'c'] = 3;
charIndex[(int)'-'] = 4;
}
void Alignment::allocateBacktrackMatrix(){
backtrack = new Point*[lenX];
for(int i = 0; i < lenX; i++){
backtrack[i] = new Point[lenY];
for(int j = 0; j < lenY; j++){
backtrack[i][j] = Point();
}
}
}
bool Alignment::elementCalculated(int x, int y){
//cout << "Verifying if " << x << "_" << y << " has been calculated" << endl;
//cout << backtrack[1][1].x << endl;
//cout << backtrack[x-1][y-1].x << endl;
return (backtrack[x][y].x != -1 && backtrack[x][y].y != -1);
}
void Alignment::allocateSimMatrix(){
simMatrix = new int*[lenX];
for(int i = 0; i < lenX; i++){
simMatrix[i] = new int[lenY];
}
}
void Alignment::initMatrix(){
simMatrix[0][0] = 0;
backtrack[0][0] = Point(0,0);
for (int i = 1; i < lenX; i++){
simMatrix[i][0] = i*sim((int)'-',(int)'-');
backtrack[i][0] = Point(i-1,0);
}
for (int i = 1; i < lenY; i++){
simMatrix[0][i] = i*sim((int)'-',(int)'-');
backtrack[0][i] = Point(0, i-1);
}
}
int Alignment::getValueOfXY(int x, int y){
//cout << "Calculating value of " << x << "_" << y << endl;
if(elementCalculated(x, y)){
return simMatrix[x][y];
}else{
int res;
int a = getValueOfXY(x-1,y-1) + sim((int)seqA[x-1], (int)seqB[y-1]);
int b = getValueOfXY(x,y-1) + sim((int)seqA[x-1], (int)'-');
int c = getValueOfXY(x-1,y) + sim((int)'-', (int)seqB[y-1]);
if ((a > b) && (a > c)){
res = a;
backtrack[x][y].x = x-1;
backtrack[x][y].y = y-1;
}else if ((b > c) && (b > c)){
res = b;
backtrack[x][y].x = x;
backtrack[x][y].y = y-1;
}else{
res = c;
backtrack[x][y].x = x-1;
backtrack[x][y].y = y;
}
simMatrix[x][y] = res;
//cout << "Calculating value of " << x << "_" << y << ":" << endl;
//cout << res << endl;
return res;
}
}
pair<string, string> Alignment::traceAlignment(){
Point lastMovement(-1,-1);
Point current(lenX-1, lenY-1);
deque traceA, traceB;
while(current.x > 0 && current.y > 0){
//cout << "Current element: " << current.x << "_" << current.y << endl;
if(lastMovement.x == -1 && lastMovement.y == -1){
traceA.push_front(seqA[current.x-1]);
traceB.push_front(seqB[current.y-1]);
}else if(lastMovement.x == -1 && lastMovement.y == 0){
traceA.push_front(seqA[current.x-1]);
traceB.push_front('-');
}else{
traceA.push_front('-');
traceB.push_front(seqB[current.y-1]);
}
Point nextElement(backtrack[current.x][current.y].x, backtrack[current.x][current.y].y);
lastMovement.x = nextElement.x-current.x;
lastMovement.y = nextElement.y-current.y;
current.x = nextElement.x;
current.y = nextElement.y;
}
pair<string, string> aligns;
aligns.first = charDequeToString(traceA);
aligns.second = charDequeToString(traceB);
return aligns;
}
void Alignment::align(){
getValueOfXY(lenX-1, lenY-1);
//cout << "Calculated simMatrix" << endl;
alignment = traceAlignment();
value = score(seqA, seqB);
done = true;
}
void Alignment::startAlignment(){
thread alignmentThread(&Alignment::align, this);
done = false;
alignmentThread.detach();
}
float Alignment::score(string seqA, string seqB){
bool coveringGap = false;
int points = 0;
for (int i = 0; i < seqA.length() && i < seqB.length(); i++){
char itemA = seqA[i];
char itemB = seqB[i];
int s = sim(itemA, itemB);
if(!coveringGap && s == nuclSimMatrix[4][4]){
coveringGap = true;
points += gapStartPenalty;
}else if(coveringGap && s != nuclSimMatrix[4][4]){
coveringGap = false;
}
points += s;
}
return points;
}
bool Alignment::isDone(){
return done;
}
float Alignment::getAlignmentValue(){
return value;
}
float Alignment::getAlignmentRelativeValue(){
return ((getAlignmentValue() / alignment.first.length()) / nuclSimMatrix[0][0]);
}
string Alignment::getAlignment(){
int lineLength = 30;
int nextPart = 0;
string output = "";
output += string("querySq = '") + seqAName + string("'\n");
output += string("subject = '") + seqBName + string("'\n");
output += string("Alignment Score = ") + to_string(getAlignmentValue())
+ string("\n");
output += string("Alignment Relative Score = ")
+ to_string(getAlignmentRelativeValue())
+ string("\n\n");
string querySq = alignment.first;
string subject = alignment.second;
int notPrinted = querySq.length();
while(notPrinted > 0){
int start = nextPart;
string qryPart = querySq.substr(start, lineLength);
string sbjPart = subject.substr(start, lineLength);
int end = start + qryPart.length();
nextPart += qryPart.length();
notPrinted -= qryPart.length();
output += string("querySq\t") + to_string(start) + string ("\t");
output += qryPart + string("\t") + to_string(end) + string("\n");
output += string("subject\t") + to_string(start) + string ("\t");
output += sbjPart + string("\t") + to_string(end) + string("\n\n");
}
return output;
}
|
c++
| 17 | 0.542488 | 102 | 28.820628 | 223 |
starcoderdata
|
import { expect } from "chai";
import fs from "fs";
import Stack from '../../lib/stack.js'
describe("Stack1", () => {
it("test", () => {
const lines = fs.readFileSync("C:\\work\\edu\\testing-course\\Patterns\\data.txt")
.split(" ")
.map(line => ({ command: line[0], value: line[1] }));
const stack = new Stack();
for (const line of lines) {
if (line.command === "push") {
stack.push(line.value);
} else {
assert.equal(stack.pop(), line.value);
}
}
});
//#region Почему это плохо?
/*
## Антипаттерн Local Hero
Тест не будет работать на машине другого человека или на Build-сервере.
Да и у того же самого человека после переустановки ОС / повторного Clone репозитория / ...
## Решение
Тест не должен зависеть от особенностей локальной среды.
Если нужна работа с файлами, делайте это по относительным путям.
// path.resolve превращает относительный путь в абсолютный
const lines = fs.readFileSync(path.resolve("data.txt"));
*/
//#endregion
});
|
javascript
| 21 | 0.579274 | 94 | 27.974359 | 39 |
starcoderdata
|
void DoActivate(bool top_level=true) override {
// Activate all of the cell children.
for (auto & row : rows) {
for (auto & col : row.data) {
for (auto & child : col.children) {
child->DoActivate(false);
}
}
}
// Activate this Table.
internal::WidgetInfo::DoActivate(top_level);
}
|
c++
| 12 | 0.501299 | 52 | 28.692308 | 13 |
inline
|
package com.prs.hub;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.GZIPInputStream;
@Slf4j
public class Test {
public static void main(String[] args) throws Exception {
// final String remote_url = "http://192.168.3.11:8000/api/workflows/v1";// 第三方服务器请求地址
// try {
// Map<String, String> filePathMap = new HashMap
// filePathMap.put("workflowSource", "E:\\test\\hello.wdl");
// filePathMap.put("workflowInputs","E:\\test\\inputs.json");
// httpClientUploadFile(filePathMap,remote_url);
//
// }catch (Exception e){
// log.error("",e);
// }
// Calendar c = Calendar.getInstance();
// System.out.println(c.getTime());
//
// // 获得年份
// System.out.println("现在是:" + c.get(Calendar.YEAR) + "年");
//
// // 获得月份
// System.out.println("现在是:" + (c.get(Calendar.MONTH)+1) + "月");
//
// //获得日期
// System.out.println("现在是:" + c.get(Calendar.DATE) + "号");
// System.out.println("现在是:" + c.get(Calendar.DAY_OF_MONTH) + "号");
//
// // 获得这是今年的第几天
// System.out.println("现在是今年第" + c.get(Calendar.DAY_OF_YEAR) + "天");
//
// // 获得今天周几
// System.out.println("现在是星期:" + (c.get(Calendar.DAY_OF_WEEK)-1) );
//
// // 获得今天是这个月的第几周
// System.out.println("现在是第:" + c.get(Calendar.DAY_OF_WEEK_IN_MONTH) + "周" );
//
// // 12小时制的时间
// System.out.println("现在是:" + c.get(Calendar.HOUR) + "点");
//
// // 24小时制的时间
// System.out.println("现在是:" + c.get(Calendar.HOUR_OF_DAY) + "点");
//
// // 分钟数
// System.out.println("现在是:" + c.get(Calendar.MINUTE) + "分");
//
// // 秒数
// System.out.println("现在是:" + c.get(Calendar.SECOND) + "秒");
//
// // 毫秒
// System.out.println("现在是:" + c.get(Calendar.MILLISECOND) + "毫秒");
//
//
//
//
//
//
//
// SimpleDateFormat dc = new SimpleDateFormat();
// dc.applyPattern("yyyy-MM-dd");
// Date d = dc.parse("2017-5-13");
// c.setTime(d);
//
// System.out.println("--------------------2017-5-13信息-----------------------");
//
// // 获得年份
// System.out.println("现在是:" + c.get(Calendar.YEAR) + "年");
//
// // 获得月份
// System.out.println("现在是:" + (c.get(Calendar.MONTH)+1) + "月");
//
// //获得日期
// System.out.println("现在是:" + c.get(Calendar.DATE) + "号");
// System.out.println("现在是:" + c.get(Calendar.DAY_OF_MONTH) + "号");
//
// // 获得这是今年的第几天
// System.out.println("现在是今年第" + c.get(Calendar.DAY_OF_YEAR) + "天");
//
// // 获得今天周几
// System.out.println("现在是星期:" + (c.get(Calendar.DAY_OF_WEEK)-1) );
//
// // 获得今天是这个月的第几周
// System.out.println("现在是第:" + c.get(Calendar.DAY_OF_WEEK_IN_MONTH) + "周" );
String fileName="E:\\test\\P+T\\Height.QC.gz";
Long x = System.currentTimeMillis();
//使用GZIPInputStream解压GZ文件
InputStream in = new GZIPInputStream(new FileInputStream(fileName));
Scanner sc=new Scanner(in);
List lines=new ArrayList();
while(sc.hasNextLine()){
lines.add(sc.nextLine());
}
Long y = System.currentTimeMillis();
System.out.println(y-x);
}
/**
* 上传文件
* @param filePathMap 上传的文件地址
* @param url 上传的地址
* @returnPath
*/
public static String httpClientUploadFile(Map<String, String> filePathMap,String url ) {
log.info("上传文件filePathMap="+JSON.toJSONString(filePathMap));
log.info("上传地址url="+url);
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
try {
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
for (String fileKey :filePathMap.keySet()) {
String filePath = filePathMap.get(fileKey);
File file = new File(filePath);
FileInputStream fileInputStream = new FileInputStream(file);
// MockMultipartFile(String name, @Nullable String originalFilename, @Nullable String contentType, InputStream contentStream)
// 其中originalFilename,String contentType 旧名字,类型 可为空
// ContentType.APPLICATION_OCTET_STREAM.toString() 需要使用HttpClient的包
MultipartFile multipartFile = new MockMultipartFile("copy"+file.getName(),file.getName(),
ContentType.APPLICATION_OCTET_STREAM.toString(),fileInputStream);
String fileName = multipartFile.getOriginalFilename();
builder.addBinaryBody(fileKey, multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);// 执行提交
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
// 将响应内容转换为字符串
result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
}
} catch (IOException e) {
log.error("上传文件IOException",e);
e.printStackTrace();
} catch (Exception e) {
log.error("上传文件Exception",e);
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
log.error("关闭httpClient",e);
e.printStackTrace();
}
}
log.info("上传文件result="+result);
return result;
}
}
|
java
| 14 | 0.590111 | 141 | 35.268156 | 179 |
starcoderdata
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Level : MonoBehaviour
{
public GameObject floaterEnemyContainer;
public GameObject bombEnemyContainer;
public GameObject floaterEnemyPrefab;
public GameObject floaterEnemyHarmfulPrefab;
public GameObject floaterStarPrefab;
public GameObject bombEnemyPrefab;
public GameObject[] gemstones;
public GameObject gate;
public bool[] gemstoneCollected;
[HideInInspector] public ArrayList floaterEnemies = new ArrayList();
[HideInInspector] public ArrayList bombEnemies = new ArrayList();
public float maxFloaterSpawnX;
public float maxFloaterSpawnY;
public float minFloaterSpawnX;
public float minFloaterSpawnY;
private int noFloaterEnemies = 400;
private int noBombEnemies = 40;
private float floaterHarmfulChance = 0.2f;
private float floaterStarChance = 0.1f;
public void SetNoFloaterEnemies(int no)
{
noFloaterEnemies = no;
}
public void SetNoBombEnemies(int no)
{
noBombEnemies = no;
}
public void SetFloaterHarmfulChance(float chance)
{
floaterHarmfulChance = chance;
}
public void SetFloaterStarChance(float chance)
{
floaterStarChance = chance;
}
public void CreateFloaterEnemies()
{
for (int i = 0; i < noFloaterEnemies; i++)
{
//Get random position
Vector3 randomPosition = new Vector3(
Random.Range(minFloaterSpawnX, maxFloaterSpawnX),
Random.Range(minFloaterSpawnY, maxFloaterSpawnY),
transform.position.z
);
//Whether to spawn a normal floater, a harmful floater or a star
GameObject floaterType;
float rand = Random.Range(0f, 1f);
if (rand < floaterHarmfulChance)
{
floaterType = floaterEnemyHarmfulPrefab;
}
else if (rand < floaterHarmfulChance + floaterStarChance)
{
floaterType = floaterStarPrefab;
}
else
{
floaterType = floaterEnemyPrefab;
}
//Create floater enemy
GameObject floaterEnemy = Instantiate(floaterType, randomPosition, Quaternion.identity, floaterEnemyContainer.transform);
floaterEnemies.Add(floaterEnemy);
}
}
public void CreateBombEnemies()
{
for(int i = 0; i < noBombEnemies; i++)
{
//Get random position
Vector3 randomPosition = new Vector3(
Random.Range(minFloaterSpawnX, maxFloaterSpawnX),
Random.Range(minFloaterSpawnY, maxFloaterSpawnY),
transform.position.z
);
//Create bomb enemy
GameObject bombEnemy = Instantiate(bombEnemyPrefab, randomPosition, Quaternion.identity, bombEnemyContainer.transform);
bombEnemies.Add(bombEnemy);
}
}
public bool AllGemstonesCollected()
{
bool _return = true;
foreach(bool gemCollected in gemstoneCollected)
{
if (!gemCollected) _return = false;
}
return _return;
}
public void ResetGemstones()
{
gemstoneCollected = new bool[gemstones.Length];
for(int i = 0; i < gemstoneCollected.Length; i++)
{
gemstoneCollected[i] = false;
}
}
public void CreateEnemies()
{
CreateFloaterEnemies();
CreateBombEnemies();
}
public void UpdateEnemies(GameObject player)
{
foreach(GameObject floaterEnemy in floaterEnemies)
{
floaterEnemy.GetComponent
}
for(int i = 0; i < bombEnemies.Count; i++)
{
GameObject bombEnemy = (GameObject) bombEnemies[i];
BombEnemy bombScript = bombEnemy.GetComponent
bombScript.Move();
bombScript.CheckExplode(player);
}
}
public void DestroyAllEnemies()
{
for(int i = floaterEnemies.Count - 1; i >= 0; i--)
{
GameObject enemy = (GameObject) floaterEnemies[i];
floaterEnemies.Remove(enemy);
Destroy(enemy);
}
for (int i = bombEnemies.Count - 1; i >= 0; i --)
{
GameObject enemy = (GameObject) bombEnemies[i];
bombEnemies.Remove(enemy);
Destroy(enemy);
}
}
}
|
c#
| 17 | 0.600783 | 133 | 26.538922 | 167 |
starcoderdata
|
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ __('البطاقة رقم ' .$card->barcode ) }}
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-xl sm:rounded-lg p-2">
<div class="float-right" style="margin-bottom:50px;">
الحالي للبطاقة : <span class="font-semibold text-gray-800">{{ $card->balance }}
<div class="float-left" style="margin-bottom:50px;">
صاحب البطاقة : <span class="font-semibold text-gray-800">{{ $card->name }}
<div style="clear: both;">
<!-- Tabs navs -->
<ul class="nav nav-tabs nav-justified mb-3" id="ex1" role="tablist">
@if($card->balance > 0)
<li class="nav-item" role="presentation">
<a
class="nav-link active"
id="ex3-tab-1"
data-toggle="tab"
href="#ex3-tabs-1"
role="tab"
aria-controls="ex3-tabs-1"
aria-selected="true"
>حسم
<i class="fa fa-minus">
</a
>
@endif
<li class="nav-item" role="presentation">
<a
class="nav-link"
id="ex3-tab-2"
data-toggle="tab"
href="#ex3-tabs-2"
role="tab"
aria-controls="ex3-tabs-2"
aria-selected="false"
>إضافة رصيد
<i class="fa fa-plus">
</a
>
<!-- Tabs navs -->
<!-- Tabs content -->
<div class="tab-content" id="ex2-content">
<div
class="tab-pane fade show active"
id="ex3-tabs-1"
role="tabpanel"
aria-labelledby="ex3-tab-1"
>
@if($card->balance > 0)
<form method="post" action="{{route('withdraw')}}" id="withdrawForm">
@csrf
<div class="form-group">
قيمة الخصم من البطاقة
<input type="number" class="form-control" name="amount"
placeholder="الرجاء كتابة قيمة الخصم" required min="0"
max="{{$card->balance}}" autofocus>
<input type="hidden" class="" name="barcode" value="{{$card->barcode}}">
<small class="form-text text-muted">يجب ان لا تكون القيمة اكبر من رصيد
البطاقة
<ul class="errors">
@foreach ($errors->get('amount') as $message)
$message }}
@endforeach
<div style="clear: both;">
<div class="form-group">
الفاتورة :
<input type="text" class="form-control" name="orderNo"
placeholder="الرجاء كتابة رقم الفاتورة " required
>
<small class="form-text text-muted">قم بمسح رقم الفاتورة او كتابتها يدوياً
<ul class="errors">
@foreach ($errors->get('orderNo') as $message)
$message }}
@endforeach
<button type="submit" class="btn btn-primary">خصم
@endif
<div
class="tab-pane fade"
id="ex3-tabs-2"
role="tabpanel"
aria-labelledby="ex3-tab-2"
>
<div style="clear: both;">
<form method="post" action="{{route('deposit')}}" id="depositForm">
@csrf
<div class="form-group">
قيمة الفاتورة
<input type="number" class="form-control" name="amount" id="orderAmount"
placeholder="قيمة الفاتورة" required min="1"
autofocus>
<input type="hidden" class="" name="barcode" value="{{$card->barcode}}">
<small class="form-text text-muted">يجب ان لا تكون القيمة سالبة او صفر
<ul class="errors">
@foreach ($errors->get('amount') as $message)
$message }}
@endforeach
<div class="form-group">
الفاتورة :
<input type="text" class="form-control" name="orderNo"
placeholder="الرجاء كتابة رقم الفاتورة " required
>
<small class="form-text text-muted">قم بمسح رقم الفاتورة او كتابتها يدوياً
<ul class="errors">
@foreach ($errors->get('orderNo') as $message)
$message }}
@endforeach
<div style="clear: both;">
<div class="float-right">
القيمة التي ستضاف للبطاقة <span id="cardBalance" style="color: #ff3e3e;">
<button type="submit" class="btn btn-danger">إضافة
<!-- Tabs content -->
<hr width="100%" class="mt-4 mb-4">
<div class="table-responsive col-xs-12 col-md-6 col-lg-6 float-right">
<p class="float-right">عمليات الاضافة
<table class="table table-bordered">
الفاتورة
@if (Auth::user()->isAdmin == 1)
@endif
<?php $i = 0?>
@foreach ($card->deposits as $deposit)
++$i }}
$deposit->user->name }}
$deposit->amount }}
$deposit->orderNo }}
$deposit->date }}
@if (Auth::user()->isAdmin == 1)
<form action="{{route('DeleteDeposit',['id'=>$deposit->id])}}" method="POST">
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger delete_btn">
<i class="fa fa-trash">
@endif
@endforeach
<div class="table-responsive col-xs-12 col-md-6 col-lg-6 float-left">
<p class="float-right">عمليات الخصم
<table class="table table-bordered">
الفاتورة
<?php $i = 0?>
@foreach ($card->withdraw as $withdraw)
++$i }}
$withdraw->user->name }}
$withdraw->amount }}
$withdraw->orderNo }}
$withdraw->date }}
@if (Auth::user()->isAdmin == 1)
<form action="{{route('DeleteWithdraw',['id'=>$withdraw->id])}}" method="POST">
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger delete_btn">
<i class="fa fa-trash">
<form action="{{route('withdrawToDeposit',['id'=>$withdraw->id])}}" method="POST">
@csrf
<button type="submit" class="btn btn-danger move_btn">
<i class="fa fa-minus">
@endif
@endforeach
|
php
| 4 | 0.30896 | 122 | 45.358268 | 254 |
starcoderdata
|
package controller;
import boundary.PlayerApplication;
import boundary.PlayerLevelView;
import model.PlayerModel;
import model.PlayerState;
import model.Point;
import model.Move;
/**
* @author
*/
public class PlayerStartMoveCtrl {
PlayerApplication app;
PlayerModel model;
public PlayerStartMoveCtrl(PlayerApplication app, PlayerModel model) {
this.app = app;
this.model = model;
}
/**
* TODO: is there anything in the boundary that needs to get updated?
*/
public void startMove(Point point) {
model.playerState = PlayerState.SELECT;
model.move = new Move();
model.move.expand(model.level.currentBoard, point);
((PlayerLevelView) app.getView()).boardView.repaint();
}
}
|
java
| 12 | 0.721467 | 72 | 22.741935 | 31 |
starcoderdata
|
package com.lcdd.backend.dbrepositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.lcdd.backend.pojo.User;
public interface UserRepository extends JpaRepository<User, Long> {
User findByName(String name);
User findByEmail(String email);
User findById(long id);
}
|
java
| 7 | 0.7875 | 67 | 21.857143 | 14 |
starcoderdata
|
#ifndef CANVAS_LAYERS_EDITOR_PLUGIN_H
#define CANVAS_LAYERS_EDITOR_PLUGIN_H
#include
#include
class CanvasLayersEditorPlugin: public EditorPlugin {
GDCLASS(CanvasLayersEditorPlugin, EditorPlugin);
MenuButton* menu_btn;
Dictionary layers;
static CanvasLayersEditorPlugin* instance;
protected:
static void _bind_methods();
void _notification(int p_what);
void _check_node_for_layers(Node* node);
void _select_item(int pressed_idx=0);
String _get_layer_group_name(const String &layer) const;
public:
virtual void save_external_data();
static CanvasLayersEditorPlugin* get_singleton() { return instance; };
void add_layer(const String &name, bool selected=true);
bool is_layer_visible(const String &name);
CanvasLayersEditorPlugin();
};
#endif // CANVAS_LAYERS_EDITOR_PLUGIN_H
|
c
| 10 | 0.733189 | 74 | 24.638889 | 36 |
starcoderdata
|
from flask_rest_jsonapi import ResourceDetail, ResourceList
from app.api.bootstrap import api
from app.api.schema.pages import PageSchema
from app.models import db
from app.models.page import Page
class PageList(ResourceList):
"""
List and create page
"""
decorators = (api.has_permission('is_admin', methods="POST"),)
schema = PageSchema
data_layer = {'session': db.session,
'model': Page}
class PageDetail(ResourceDetail):
"""
Page detail by id
"""
schema = PageSchema
decorators = (api.has_permission('is_admin', methods="PATCH,DELETE"),)
data_layer = {'session': db.session,
'model': Page}
|
python
| 10 | 0.651862 | 74 | 24.851852 | 27 |
starcoderdata
|
<?php
namespace App\Traits;
use App\Models\Tag;
trait TagsTrait{
public function createTags($post,$tags){
$tagArr = [];
foreach($tags as $tag){
if (is_numeric($tag)) {
$tagArr[] = $tag;
}else {
$newTag = Tag::create(["tag_name" => $tag, "tag_url" => strtolower($tag)]);
$tagArr[] = $newTag->id;
}
}
return $post->tags()->sync($tagArr);
}
}
|
php
| 21 | 0.455128 | 91 | 21.333333 | 21 |
starcoderdata
|
#include
#include
#ifndef PHOTON_VID_HEADER
#define PHOTON_VID_HEADER
namespace photon {
class Video {
public:
static void initialize();
static void destroy();
};
};
#endif
|
c
| 9 | 0.697115 | 27 | 12 | 16 |
starcoderdata
|
import os
import webbrowser
from functools import partial
from PyQt5 import QtWidgets
from ui import media_objects, MessageBox
from ui import ProviderDialog, PersonDialog
from util import json_to_media, csv_to_media, media_to_json, media_to_csv
from options import options
class AppMenuBar(QtWidgets.QMenuBar):
"""The App Menu Bar consists of menu items and options
to import and export media as a file
:param update_media_func: The function used to update the media in the app
"""
# # # # # # # # # # # # # # # # # # # # # # # # #
def __init__(self, parent: QtWidgets.QWidget = None,
*, update_media_func: callable = None,
update_providers_func: callable = None,
update_persons_func: callable = None):
super().__init__(parent)
self.update_media_func = update_media_func
self.update_providers_func = update_providers_func
self.update_persons_func = update_persons_func
self.file_menu = self.addMenu("File")
self.file_menu_import_all = self.file_menu.addMenu(" Import Media")
self.file_menu_import_all.addAction(
" From JSON", partial(self.import_media, "json"), "Ctrl+O")
self.file_menu_import_all.addAction(
" From CSV", partial(self.import_media, "csv"), "Ctrl+Shift+O")
self.file_menu.addSeparator()
self.file_menu_export_current = self.file_menu.addMenu(" Export Current Media")
self.file_menu_export_current.addAction(" To JSON", partial(self.export_media, "json", True), "Ctrl+S")
self.file_menu_export_current.addAction(" To CSV", partial(self.export_media, "csv", True), "Ctrl+Shift+S")
self.file_menu_export_all = self.file_menu.addMenu(" Export All Media")
self.file_menu_export_all.addAction(
" To JSON", partial(self.export_media, "json", False), "Alt+S")
self.file_menu_export_all.addAction(
" To CSV", partial(self.export_media, "csv", False), "Alt+Shift+S")
self.options_menu = self.addMenu("Options")
self.options_menu.addAction(" Configure Streaming Providers", self.configure_providers, "Ctrl+1")
self.options_menu.addAction(" Configure Persons", self.configure_persons, "Ctrl+2")
def open_browser():
webbrowser.open("https://github.com/FellowHashbrown/MediaQueue/blob/master/README.md")
self.help_menu = self.addMenu("Help")
self.help_menu.addAction(" How to Use", open_browser)
self.help_menu.addAction(" Report Bug or Request Feature", self.show_report_bug)
# # # # # # # # # # # # # # # # # # # # # # # # #
def import_media(self, as_file: str):
"""Asks the user to select a file to import.
The user will only be able to select .csv files
"""
try:
filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(
None, "Select Media", ".",
"CSV Files(*.csv)" if as_file == "csv" else "JSON Files(*.json)")
if len(filenames) > 0:
if as_file == "csv":
target_load_func = csv_to_media
else:
target_load_func = json_to_media
media = []
for filename in filenames:
for media_obj in target_load_func(filename):
media.append(media_obj)
media_obj.save()
media_objects.get_media().extend(media)
self.update_media_func()
MessageBox("Import Success",
"Successfully imported media from the selected file(s)",
self)
except Exception as e:
e = str(e)
MessageBox("Import Failure",
f"The import failed because: \"{e}\"",
self)
def export_media(self, as_file: str, single: False):
"""Exports all Media into the specified filetype
:param as_file: The file type to export the media as
:param single: Whether or not to export a single piece of Media
"""
if not os.path.exists(f"{options.get_base_dir()}/exports"):
os.mkdir(f"{options.get_base_dir()}/exports")
try:
media = media_objects.get_media()
if single:
inner_media = None
if media_objects.get_movie() is not None:
inner_media = media_objects.get_movie()
elif media_objects.get_tv_show() is not None:
inner_media = media_objects.get_tv_show()
elif media_objects.get_podcast() is not None:
inner_media = media_objects.get_podcast()
elif media_objects.get_limited_series() is not None:
inner_media = media_objects.get_limited_series()
# Check if the media is None
if inner_media is None:
raise ValueError("There is no specific piece of Media open right now")
media = inner_media
# Export the media
if as_file == "json":
media_to_json(media)
if as_file == "csv":
media_to_csv(media)
MessageBox("Export Success",
"Successfully exported {} as {}".format(
"all media" if not single else f"\"{media.get_name()}\"",
as_file),
self)
except Exception as e:
e = str(e)
MessageBox("Export Failure",
f"The export failed because: \"{e}\"",
self)
# # # # # # # # # # # # # # # # # # # # # # # # #
def configure_providers(self):
"""Allows a user to configure the Streaming Providers in the application"""
ProviderDialog(self, update_func=self.update_providers_func).exec_()
def configure_persons(self):
"""Allows a user to configure the Persons in the application"""
PersonDialog(self, update_func=self.update_persons_func).exec_()
# # # # # # # # # # # # # # # # # # # # # # # # #
def show_report_bug(self):
"""Shows the user a dialog on how to report a bug in Media Queue"""
MessageBox("How to Report a Bug",
"In order to report a bug, I ask that you go here to do so",
self,
link_title="Github Bug Reporter",
link_url="https://github.com/FellowHashbrown/MediaQueue/issues/new/choose")
|
python
| 17 | 0.552338 | 115 | 42.907285 | 151 |
starcoderdata
|
var express = require('express')
var router = express.Router()
const siteController = require('../app/controllers/SiteController')
// router.get is only for subpaths
// subpath /search returns search()
router.get('/search', siteController.search)
// subpath / returns index() (HOME)
router.get('/', siteController.index)
module.exports = router
|
javascript
| 6 | 0.73639 | 67 | 25.846154 | 13 |
starcoderdata
|
public Point getIntersectionPoint(final LineSegment ls) {
if (this.equals(ls))
return null;
{// Finish fast if the two segments have a common endpoint
// NOTE: this also covers the case that the lines are collinear and overlap only at ONE point
// FIXME: I THINK this is wrong because they could share an endpoint, NOT be equal, but STILL overlap
final Point commonEndpoint = getCommonEndpoint(this, ls);
if (commonEndpoint != null)
return commonEndpoint;
}
/*
* p = this starting point
* q = ls starting point
*
* r = p.aToB
* s = q.aToB
*
* t = scalar of r
* u = scalar of s
*/
final Vector p = Vector.toVector(new Point(a.getX(), a.getY()));
final Vector q = Vector.toVector(new Point(ls.a.getX(), ls.a.getY()));
final Vector r = aToB;
final Vector s = ls.aToB;
final int rCrossS = r.cross(s);
final Vector qMinusP = q.minus(p);
final int qMinPCrossR = (qMinusP).cross(r);
if (rCrossS == 0 && qMinPCrossR == 0) { // is collinear
return null;
}
else if (rCrossS == 0 && qMinPCrossR != 0) { // is parallel
return null;
}
else if (rCrossS != 0) { // POSSIBLY intersects
final float t = (float)qMinusP.cross(s) / rCrossS;
final float u = (float)qMinPCrossR / rCrossS;
if ((t >= 0 && t <= 1) && (u >= 0 && u <= 1)) { // intersects!
final int intersectX = p.getX() + round(t * r.getX());
final int intersectY = p.getY() + round(t * r.getY());
return new Point(intersectX, intersectY);
}
}
// Non-collinear, non-parallel, and does not intersect
return null;
}
|
java
| 17 | 0.630241 | 103 | 29.882353 | 51 |
inline
|
package com.jackhallam.weightless;
import com.jackhallam.weightless.annotations.Create;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class TestCreate extends TestBase {
public TestCreate(Supplier weightlessSupplier) {
super(weightlessSupplier);
}
@Test
public void testCreateOneSuccess() throws Exception {
TestObject testObject = new TestObject();
testObject.testField = "hello";
TestObject savedTestObject = getDal(Dal.class).create(testObject);
assertEquals(testObject.testField, savedTestObject.testField);
}
@Test
public void testCreateMultipleSuccess() throws Exception {
TestObject firstTestObject = new TestObject();
firstTestObject.testField = "hello";
TestObject secondTestObject = new TestObject();
secondTestObject.testField = "world";
List savedTestObjects = getDal(Dal.class).createAll(Arrays.asList(firstTestObject, secondTestObject));
assertEquals(2, savedTestObjects.size());
assertEquals(firstTestObject.testField, savedTestObjects.get(0).testField);
assertEquals(secondTestObject.testField, savedTestObjects.get(1).testField);
}
@Test
public void testCreateReturnVoidSuccess() throws Exception {
TestObject testObject = new TestObject();
testObject.testField = "hello";
getDal(Dal.class).createAllReturnVoid(Collections.singletonList(testObject));
assertEquals("hello", testObject.testField);
}
@Test
public void testCreateNoneSuccess() throws Exception {
TestObject testObject = getDal(Dal.class).create(Collections.emptyList());
assertNull(testObject);
}
@Test
public void testCreateNoneReturnVoidFailure() throws Exception {
assertThrows(WeightlessException.class, () -> getDal(Dal.class).createAllReturnVoid(Collections.emptyList()));
}
@Test
public void testCreateReturnBooleanSuccess() throws Exception {
TestObject testObject = new TestObject();
testObject.testField = "hello";
assertTrue(getDal(Dal.class).createReturnBoolean(testObject));
}
@Test
public void testCreateReturnObjectBooleanSuccess() throws Exception {
TestObject testObject = new TestObject();
testObject.testField = "hello";
assertTrue(getDal(Dal.class).createReturnObjectBoolean(testObject));
}
@Test
public void testCreateReturnIterableSuccess() throws Exception {
TestObject testObject = new TestObject();
testObject.testField = "hello";
assertTrue(getDal(Dal.class).createReturnIterable(testObject).iterator().hasNext());
assertEquals(testObject.testField, getDal(Dal.class).createReturnIterable(testObject).iterator().next().testField);
}
@Test
public void testCreateReturnOptionalSuccess() throws Exception {
TestObject testObject = new TestObject();
testObject.testField = "hello";
assertTrue(getDal(Dal.class).createAllReturnOptional(Collections.singletonList(testObject)).isPresent());
}
@Test
public void testCreateReturnOptionalEmptySuccess() throws Exception {
assertFalse(getDal(Dal.class).createAllReturnOptional(Collections.emptyList()).isPresent());
}
@Test
public void testCreateReturnListEmptySuccess() throws Exception {
assertTrue(getDal(Dal.class).createAll(Collections.emptyList()).isEmpty());
}
public static class TestObject {
public String testField;
}
public interface Dal {
@Create
TestObject create(TestObject testObject);
@Create
TestObject create(List testObject);
@Create
Iterable createReturnIterable(TestObject testObject);
@Create
List createAll(List testObjects);
@Create
void createAllReturnVoid(List testObjects);
@Create
boolean createReturnBoolean(TestObject testObject);
@Create
Boolean createReturnObjectBoolean(TestObject testObject);
@Create
Optional createAllReturnOptional(List testObjects);
}
}
|
java
| 15 | 0.761329 | 119 | 31.11194 | 134 |
starcoderdata
|
<?php
class BlogController extends CI_Controller{
public function blog(){
$data['site_view'] = 'blog';
$data['site_title'] = 'Blog';
$this->load->view('main/main_view', $data);
}
public function title1(){
$data['site_view'] = 'blog1';
$data['site_title'] = 'Title';
$this->load->view('main/main_view', $data);
}
}
|
php
| 10 | 0.531486 | 51 | 23.875 | 16 |
starcoderdata
|
package org.qitmeer.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.qitmeer.model.*;
import java.util.*;
public class Qitmeer {
private String url ;
private String usr ;
private String pass;
public Qitmeer(String url,String usr,String pass){
this.url = url;
this.usr=usr;
this.pass=pass;
}
/**
* 获取当前区块高度
*/
public ServiceResult getBlockCount() {
SendJson s = new SendJson("getBlockCount",new ArrayList
String sendMsg =JSON.toJSONString(s);
String rep = HttpClientUtil.doPost(url, sendMsg, "utf-8",authorization());
return QitmeerUtil.pareRec(rep);
}
/**
* 根据order获取区块信息
* @param order
* @param show 是否显示json true false
*/
public ServiceResult getBlockByOrder(int order,boolean show) {
List params = new ArrayList
params.add(order);
params.add(show);
SendJson s = new SendJson("getBlockByOrder",params);
String sendMsg =JSON.toJSONString(s);
String rep = HttpClientUtil.doPost(url, sendMsg, "utf-8",authorization());
return QitmeerUtil.pareRec(rep);
}
/**
* 获取区块头信息
* @param blockHash
* @param show
* @return
*/
public ServiceResult getBlockHeader(String blockHash,boolean show) {
List params = new ArrayList
params.add(blockHash);
params.add(show);
SendJson s = new SendJson("getBlockHeader",params);
String sendMsg =JSON.toJSONString(s);
String rep = HttpClientUtil.doPost(url, sendMsg, "utf-8",authorization());
return QitmeerUtil.pareRec(rep);
}
/**
* 获取区块weight
* @param blockHash
* @return
*/
public ServiceResult getBlockWeight(String blockHash) {
List params = new ArrayList
params.add(blockHash);
SendJson s = new SendJson("getBlockWeight",params);
String sendMsg =JSON.toJSONString(s);
String rep = HttpClientUtil.doPost(url, sendMsg, "utf-8",authorization());
return QitmeerUtil.pareRec(rep);
}
/**
* 根据hash查询区块信息
* @param blockHash
* @param show
* @return
*/
public ServiceResult getBlockByhash(String blockHash,boolean show) {
List params = new ArrayList
params.add(blockHash);
params.add(show);
SendJson s = new SendJson("getBlock",params);
String sendMsg =JSON.toJSONString(s);
String rep = HttpClientUtil.doPost(url, sendMsg, "utf-8",authorization());
return QitmeerUtil.pareRec(rep);
}
/**
* 根据order获取blockhash
* @param order
* @return
*/
public ServiceResult getBlockHash(int order) {
List params = new ArrayList
params.add(order);
SendJson s = new SendJson("getBlockhash",params);
String sendMsg =JSON.toJSONString(s);
String rep = HttpClientUtil.doPost(url, sendMsg, "utf-8",authorization());
return QitmeerUtil.pareRec(rep);
}
/**
* 获取最新hash
* @return
*/
public ServiceResult getBestBlockHash() {
List params = new ArrayList
SendJson s = new SendJson("getBestBlockHash",params);
String sendMsg =JSON.toJSONString(s);
String rep = HttpClientUtil.doPost(url, sendMsg, "utf-8",authorization());
return QitmeerUtil.pareRec(rep);
}
/**
* blockHash 是否存在
* @param blockHash
* @return
*/
public ServiceResult isOnMainChain(String blockHash) {
List params = new ArrayList
params.add(blockHash);
SendJson s = new SendJson("isOnMainChain",params);
String sendMsg =JSON.toJSONString(s);
String rep = HttpClientUtil.doPost(url, sendMsg, "utf-8",authorization());
return QitmeerUtil.pareRec(rep);
}
public ServiceResult getPeerInfo() {
List params = new ArrayList
SendJson s = new SendJson("getPeerInfo",params);
String sendMsg =JSON.toJSONString(s);
String rep = HttpClientUtil.doPost(url, sendMsg, "utf-8",authorization());
return QitmeerUtil.pareRec(rep);
}
public ServiceResult getNodeInfo() {
List params = new ArrayList
SendJson s = new SendJson("getNodeInfo",params);
String sendMsg =JSON.toJSONString(s);
String rep = HttpClientUtil.doPost(url, sendMsg, "utf-8",authorization());
return QitmeerUtil.pareRec(rep);
}
/**
* 查询utxo信息
* @param txid 交易id
* @param index 索引位置
* @param memo 是否查询memo缓存
* @return
*/
public ServiceResult getUtxo(String txid,int index,boolean memo) {
List params = new ArrayList
params.add(txid);
params.add(index);
params.add(memo);
SendJson s = new SendJson("getUtxo",params);
String sendMsg =JSON.toJSONString(s);
String rep = HttpClientUtil.doPost(url, sendMsg, "utf-8",authorization());
return QitmeerUtil.pareRec(rep);
}
private String authorization(){
if (usr==null || pass==null||pass.equals("")||usr.equals("")){
return null;
}
Base64.Encoder encoder = Base64.getEncoder();
String encodeStr = usr.concat(":").concat(pass);
String encodedText = encoder.encodeToString(encodeStr.getBytes());
return "Basic ".concat(encodedText);
}
/**
* 创建交易
* @param list utxo
* @param toAddr 转账地址
* @param amount 金额
* @param locktime 锁定时间
* @return
*/
public ServiceResult createRawTransaction(List list,String toAddr, float amount, long locktime ){
if(list.isEmpty()){
return null;
}
if (toAddr.equals("")){
return null;
}
if (amount<=0){
return null;
}
List params = new ArrayList
Map<String, Long> map = new HashMap
map.put(toAddr,Float.valueOf(amount).longValue());
params.add(list);
params.add(map);
if(locktime>0){
params.add(locktime);
}
SendJson s = new SendJson("createRawTransaction",params);
String sendMsg =JSON.toJSONString(s);
String rep = HttpClientUtil.doPost(url, sendMsg, "utf-8",authorization());
return QitmeerUtil.pareRec(rep);
}
/**
* 解码交易
* @param transaction
* @return
*/
public ServiceResult decodeRawTransaction( String transaction ){
if (transaction.equals("")){
return null;
}
List params = new ArrayList
Map<String, Long> map = new HashMap
params.add(transaction);
SendJson s = new SendJson("decodeRawTransaction",params);
String sendMsg =JSON.toJSONString(s);
String rep = HttpClientUtil.doPost(url, sendMsg, "utf-8",authorization());
return QitmeerUtil.pareRec(rep);
}
/**
* 根据txid获取交易详情
* @param transaction
* @param show 是否显示json true false
* @return
*/
public ServiceResult getRawTransaction(String txid,boolean show) {
List params = new ArrayList
params.add(txid);
params.add(show);
SendJson s = new SendJson("getRawTransaction",params);
String sendMsg =JSON.toJSONString(s);
String rep = HttpClientUtil.doPost(url, sendMsg, "utf-8",authorization());
return QitmeerUtil.pareRec(rep);
}
/**
* 发送交易
* @param sign_raw_tx
* @param allow_high_fee
* @return
*/
public ServiceResult sendRawTransaction(String sign_raw_tx,boolean allow_high_fee) {
List params = new ArrayList
params.add(sign_raw_tx);
params.add(allow_high_fee);
SendJson s = new SendJson("sendRawTransaction",params);
String sendMsg =JSON.toJSONString(s);
String rep = HttpClientUtil.doPost(url, sendMsg, "utf-8",authorization());
System.out.println("rep:"+rep);
return QitmeerUtil.pareRec(rep);
}
}
|
java
| 12 | 0.675147 | 106 | 26.547529 | 263 |
starcoderdata
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
var id_sorteo = 0;
var sede = '';
function sorteo(id) {
var tombola = document.getElementById('tombola');
if (tombola.style.display === 'none') {
var boton = document.getElementById("boton_sorteo" + id);
boton.disabled = true;
tombola.style = style = "display: block; position: absolute; margin: auto; left: 0; right: 0; text-align: center; z-index: 1;";
setInterval(apagar_sorteo, 2000);
var original = document.getElementById('crud-datatable-original-container');
var buscado = original.childNodes[0].childNodes[2].childNodes;
for (var i = 0; i < buscado.length; i++) {
var item = buscado[i];
if (item.tagName == 'TR' && item.cells[0].innerText == id) {
id_sorteo = item.cells[0].innerText.trim();
sede = item.cells[1].innerText;
console.log(item.cells[1].innerText);
}
}
}
}
function apagar_sorteo() {
var tombola = document.getElementById('tombola');
tombola.style = style = "display:none; position: absolute; margin: auto; left: 0; right: 0; text-align: center; z-index: 1;";
var random = document.getElementById('crud-datatable-random-container');
var tabla = random.childNodes[0].childNodes[2].childNodes;
for (var i = 0; i < tabla.length; i++) {
var item = tabla[i];
if (item.tagName == 'TR') {
if (item.dataset.key == id_sorteo) {
item.cells[1].innerText = sede;
}
}
}
}
|
javascript
| 16 | 0.599417 | 135 | 38.906977 | 43 |
starcoderdata
|
def astype(self, dtype, order='K', casting='unsafe', subok=True, copy=True): # real signature unknown; restored from __doc__
"""
a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
Copy of the array, cast to a specified type.
Parameters
----------
dtype : str or dtype
Typecode or data-type to which the array is cast.
order : {'C', 'F', 'A', 'K'}, optional
Controls the memory layout order of the result.
'C' means C order, 'F' means Fortran order, 'A'
means 'F' order if all the arrays are Fortran contiguous,
'C' order otherwise, and 'K' means as close to the
order the array elements appear in memory as possible.
Default is 'K'.
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
Controls what kind of data casting may occur. Defaults to 'unsafe'
for backwards compatibility.
* 'no' means the data types should not be cast at all.
* 'equiv' means only byte-order changes are allowed.
* 'safe' means only casts which can preserve values are allowed.
* 'same_kind' means only safe casts or casts within a kind,
like float64 to float32, are allowed.
* 'unsafe' means any data conversions may be done.
subok : bool, optional
If True, then sub-classes will be passed-through (default), otherwise
the returned array will be forced to be a base-class array.
copy : bool, optional
By default, astype always returns a newly allocated array. If this
is set to false, and the `dtype`, `order`, and `subok`
requirements are satisfied, the input array is returned instead
of a copy.
Returns
-------
arr_t : ndarray
Unless `copy` is False and the other conditions for returning the input
array are satisfied (see description for `copy` input parameter), `arr_t`
is a new array of the same shape as the input array, with dtype, order
given by `dtype`, `order`.
Notes
-----
.. versionchanged:: 1.17.0
Casting between a simple data type and a structured one is possible only
for "unsafe" casting. Casting to multiple fields is allowed, but
casting from multiple fields is not.
.. versionchanged:: 1.9.0
Casting from numeric to string types in 'safe' casting mode requires
that the string dtype length is long enough to store the max
integer/float value converted.
Raises
------
ComplexWarning
When casting from complex to float or int. To avoid this,
one should use ``a.real.astype(t)``.
Examples
--------
>>> x = np.array([1, 2, 2.5])
>>> x
array([ 1. , 2. , 2.5])
>>> x.astype(int)
array([1, 2, 2])
"""
pass
|
python
| 5 | 0.52026 | 124 | 45.972222 | 72 |
inline
|
private StateSet[] ComputeState(Sentence s) {
StateSet[] S = new StateSet[s.Count + 1];
// Initialize S(0)
S[0] = new StateSet(Grammar.Start);
foreach (var production in Grammar.ProductionsFrom(Grammar.Start)) {
var item = new Item(production, 0, 0);
S[0].Insert(item);
}
// outer loop
for (int stateIndex = 0; stateIndex < S.Length; stateIndex++) {
var stateprob = S[stateIndex];
// If there are no items in the current state, we're stuck
if (stateprob.Count == 0) {
return null;
}
var nextIndex = stateIndex + 1;
if (nextIndex < S.Length) {
S[nextIndex] = new StateSet();
}
StepState(S, s, stateIndex, stateprob);
}
// for those items we added magically, make sure they get treated by completion
for (int stateIndex = 0; stateIndex < S.Length; stateIndex++) {
foreach (var p in S[stateIndex].MagicItems) {
foreach (var t in S[stateIndex]) {
if (t.StartPosition != stateIndex) {
continue;
}
if (t.Production.Lhs != p.PrevWord) {
continue;
}
if (!t.IsComplete()) {
continue;
}
p.AddReduction(stateIndex, t);
}
}
}
return S;
}
|
c#
| 14 | 0.595179 | 82 | 25.173913 | 46 |
inline
|
def print_val(self,tab=0,fh=sys.stdout):
#don't print if the node has no children
if self.children==[]:
return
if self.children[0]==[]:
return
self.print_level_val(tab,fh)
fh.write(str(tab)+tab*" "+25*"-"+"children"+25*"-"+"\n")
ci=0
for c in self.children:
cii=0
for child in c:
fh.write(str(tab)+tab*" "+"child for action "+str(ci)+" observation "+str(cii)+"\n")
child.print_val(tab+1,fh)
cii += 1
ci += 1
fh.write(str(tab)+tab*" "+65*"-"+"\n")
|
python
| 18 | 0.463651 | 100 | 35.470588 | 17 |
inline
|
int preAlps_matrix_readmm_csr(char *filename, int *m, int *n, int *nnz, int **xa, int **asub, double **a){
preAlps_matrix_readmm_csc(filename, m, n, nnz, xa, asub, a);
/* Convert a matrix from csc to csr */
preAlps_matrix_convert_csc_to_csr(*m, *n, xa, *asub, *a);
return 0;
}
|
c
| 7 | 0.627586 | 106 | 31.333333 | 9 |
inline
|
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#ifndef incl_HPHP_EXT_IPC_H_
#define incl_HPHP_EXT_IPC_H_
#include "hphp/runtime/base/base-includes.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
// message queue
int64_t f_ftok(const String& pathname, const String& proj);
Variant f_msg_get_queue(int64_t key, int64_t perms = 0666);
bool f_msg_queue_exists(int64_t key);
bool f_msg_send(CResRef queue, int64_t msgtype, CVarRef message,
bool serialize = true, bool blocking = true,
VRefParam errorcode = uninit_null());
bool f_msg_receive(CResRef queue, int64_t desiredmsgtype, VRefParam msgtype,
int64_t maxsize, VRefParam message, bool unserialize = true,
int64_t flags = 0, VRefParam errorcode = uninit_null());
bool f_msg_remove_queue(CResRef queue);
bool f_msg_set_queue(CResRef queue, CArrRef data);
Array f_msg_stat_queue(CResRef queue);
///////////////////////////////////////////////////////////////////////////////
// semaphore
bool f_sem_acquire(CResRef sem_identifier);
Variant f_sem_get(int64_t key, int64_t max_acquire = 1, int64_t perm = 0666,
bool auto_release = true);
bool f_sem_release(CResRef sem_identifier);
bool f_sem_remove(CResRef sem_identifier);
///////////////////////////////////////////////////////////////////////////////
// shared memory
Variant f_shm_attach(int64_t shm_key, int64_t shm_size = 10000, int64_t shm_flag = 0666);
bool f_shm_detach(int64_t shm_identifier);
bool f_shm_remove(int64_t shm_identifier);
Variant f_shm_get_var(int64_t shm_identifier, int64_t variable_key);
bool f_shm_has_var(int64_t shm_identifier, int64_t variable_key);
bool f_shm_put_var(int64_t shm_identifier, int64_t variable_key, CVarRef variable);
bool f_shm_remove_var(int64_t shm_identifier, int64_t variable_key);
///////////////////////////////////////////////////////////////////////////////
}
#endif // incl_HPHP_EXT_IPC_H_
|
c
| 9 | 0.51388 | 89 | 45.553846 | 65 |
starcoderdata
|
import React, { Component } from 'react';
import AboutText from '../components/AboutText';
import AppHeader from '../components/AppHeader';
import AppHeaderButton from '../components/AppHeaderButton';
import Overlay from '../components/Overlay';
import PlannerContainer from '../containers/PlannerContainer';
import PostEditorContainer from '../containers/PostEditorContainer';
class App extends Component {
state = {
overlayedComponent: null,
};
componentDidMount() {
document.addEventListener('keydown', this.handleKeyDown);
}
componentWillUnmount() {
document.removeEventListener('keydown', this.handleKeyDown);
}
render() {
return (
<AppHeaderButton
href="#about"
icon="question"
onClick={this.handleAboutClick}
/>
<AppHeaderButton
href="#add-post"
icon="plus"
onClick={this.handleAddPostClick}
/>
<PlannerContainer onPostSelect={this.handlePostSelect} />
{this.state.overlayedComponent &&
<Overlay onDismiss={this.handleOverlayDismiss}>
{this.state.overlayedComponent}
);
}
presentAboutText() {
this.setState({ overlayedComponent: <AboutText /> });
}
presentPostEditor(post = null) {
this.setState({
overlayedComponent: (
<PostEditorContainer
post={post}
onSubmit={this.handlePostEditorSubmit}
/>
),
});
}
dismissOverlay() {
this.setState({ overlayedComponent: null });
}
handleKeyDown = e => {
if (document.activeElement === document.body) {
if (e.key === '?') {
e.preventDefault();
this.presentAboutText();
}
if (e.key === 'a' || e.key === 'n') {
e.preventDefault();
this.presentPostEditor();
}
}
if (e.key === 'Escape') {
e.preventDefault();
this.dismissOverlay();
}
};
handleAboutClick = e => {
e.preventDefault();
this.presentAboutText();
};
handleAddPostClick = e => {
e.preventDefault();
this.presentPostEditor();
};
handlePostSelect = post => {
this.presentPostEditor(post);
};
handleOverlayDismiss = () => {
this.dismissOverlay();
};
handlePostEditorSubmit = () => {
this.dismissOverlay();
};
}
export default App;
|
javascript
| 13 | 0.594606 | 68 | 21.449541 | 109 |
starcoderdata
|
package org.urbanbyte.cueserver.cli.actions;
import org.urbanbyte.cueserver.CueServerClient;
import org.urbanbyte.cueserver.cli.InputParser;
import org.urbanbyte.cueserver.data.playback.Playback;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Example for playing a cue on a playback
*
* author:
*/
public class PlayCueAction implements Action
{
/** Client to fire cue */
private final CueServerClient client;
/** For reading input from the user. */
private final InputParser parser = new InputParser();
/**
* Creates a new {@code DetailedPlaybackStatusAction}.
*
* @param client client to retrieve from.
*/
public PlayCueAction(CueServerClient client)
{
this.client = checkNotNull(client, "client cannot be null.");
}
/**
* {@inheritDoc}
*/
@Override
public String getDescription()
{
return "Play a cue on a playback";
}
/**
* {@inheritDoc}
*/
@Override
public void executeAction()
{
double cueNumber = parser.readDouble("Enter cue number: ");
Playback playback = parser.readPlayback("Enter cue number to play the" +
" cue on: ");
client.playCue(cueNumber, playback);
}
}
|
java
| 11 | 0.657664 | 82 | 24.849057 | 53 |
starcoderdata
|
package circhttpjson
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"time"
"github.com/circonus-labs/circonus-unified-agent/cua"
circmgr "github.com/circonus-labs/circonus-unified-agent/internal/circonus"
"github.com/circonus-labs/circonus-unified-agent/internal/release"
"github.com/circonus-labs/circonus-unified-agent/plugins/inputs"
"github.com/circonus-labs/go-trapmetrics"
"github.com/hashicorp/go-retryablehttp"
)
// Collect HTTPTrap JSON payloads and forward to circonus broker
//
// 1. Use HTTP to GET metrics in valid httptrap stream tagged, structured metric format.
// {
// "foo|ST[env:prod,app:web]": { "_type": "n", "_value": 12 },
// "foo|ST[env:qa,app:web]": { "_type": "n", "_value": 0 },
// "foo|ST[b\"fihiYXIp\":b\"PHF1dXg+\"]": { "_type": "n", "_value": 3 }
// }
// _type must be a valid httptrap (reconnoiter) metric type i=int,I=uint,l=int64,L=uint64,n=double,s=text,hH=histograms
// see: https://docs.circonus.com/circonus/integrations/library/httptrap/#httptrap-json-format for more
// information - note, metrics must use stream tag, structured formatting not arbitrary json formatting.
//
// 2. Verify metrics are formatted correctly (json.Marshal)
//
// 3. Forward to httptrap check
//
// Note: this input only supports direct metrics - they do NOT go through a regular output plugin
type Metric struct {
Value interface{} `json:"_value"`
Timestamp *uint64 `json:"_ts,omitempty"`
Type string `json:"_type"`
}
type Metrics map[string]Metric
type CHJ struct {
Log cua.Logger
dest *trapmetrics.TrapMetrics
tlsCfg *tls.Config
InstanceID string `json:"instance_id"`
URL string
TLSCAFile string
TLSCN string
}
func (chj *CHJ) Init() error {
if chj.URL == "" {
return fmt.Errorf("invalid URL (empty)")
}
if chj.InstanceID == "" {
return fmt.Errorf("invalid Instance ID (empty)")
}
if chj.TLSCAFile != "" {
if err := chj.loadTLSCACert(); err != nil {
return fmt.Errorf("loading TLSCAFile: %w", err)
}
}
opts := &circmgr.MetricDestConfig{
MetricMeta: circmgr.MetricMeta{
PluginID: "circ_http_json",
InstanceID: chj.InstanceID,
},
}
dest, err := circmgr.NewMetricDestination(opts, chj.Log)
if err != nil {
return fmt.Errorf("new metric destination: %w", err)
}
chj.dest = dest
return nil
}
func (*CHJ) Description() string {
return "Circonus HTTP JSON retrieves HTTPTrap formatted metrics and forwards them to an HTTPTrap check"
}
func (*CHJ) SampleConfig() string {
return `
instance_id = "" # required
url = "" # required
## Optional: tls ca cert file and common name to use
## pass if URL is https and not using a public ca
# tls_ca_cert_file = ""
# tls_cn = ""
`
}
func (chj *CHJ) Gather(ctx context.Context, _ cua.Accumulator) error {
if chj.dest != nil {
data, err := chj.getURL(ctx)
if err != nil {
return err
}
if err := chj.verifyJSON(data); err != nil {
return err
}
if _, err := chj.dest.FlushRawJSON(ctx, data); err != nil {
return err
}
}
return nil
}
// getURL fetches the raw json from an endpoint, the JSON must:
// 1. use streamtag metric names
// 2. adhere to circonus httptrap formatting
//
func (chj *CHJ) getURL(ctx context.Context) ([]byte, error) {
var client *http.Client
if chj.tlsCfg != nil {
client = &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 3 * time.Second,
FallbackDelay: -1 * time.Millisecond,
}).DialContext,
TLSClientConfig: chj.tlsCfg,
TLSHandshakeTimeout: 10 * time.Second,
DisableKeepAlives: true,
DisableCompression: false,
MaxIdleConns: 1,
MaxIdleConnsPerHost: 0,
},
}
} else {
client = &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 3 * time.Second,
FallbackDelay: -1 * time.Millisecond,
}).DialContext,
DisableKeepAlives: true,
DisableCompression: false,
MaxIdleConns: 1,
MaxIdleConnsPerHost: 0,
},
}
}
rinfo := release.GetInfo()
req, err := retryablehttp.NewRequest("GET", chj.URL, nil)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
req.Header.Set("User-Agent", rinfo.Name+"/"+rinfo.Version)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("Connection", "close")
retryClient := retryablehttp.NewClient()
retryClient.HTTPClient = client
retryClient.Logger = chj.Log
defer retryClient.HTTPClient.CloseIdleConnections()
resp, err := retryClient.Do(req)
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
return nil, fmt.Errorf("making request: %w", err)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("reading response body: %w", err)
}
return body, nil
}
// verifyJSON simply unmarshals a []byte into a metrics struct (defined above)
// if it works it is considered valid
func (chj *CHJ) verifyJSON(data []byte) error {
if len(data) == 0 {
return fmt.Errorf("invalid JSON (empty)")
}
var m Metrics
if err := json.Unmarshal(data, &m); err != nil {
return fmt.Errorf("json unmarshal: %w", err)
}
return nil
}
// loadTLSCACert reads in the configured TLS CA cert file and creates
// a tls.Config to use during metric fetching from URL
func (chj *CHJ) loadTLSCACert() error {
data, err := os.ReadFile(chj.TLSCAFile)
if err != nil {
return err
}
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(data) {
return fmt.Errorf("unable to append cert from pem %s", chj.TLSCAFile)
}
chj.tlsCfg = &tls.Config{
MinVersion: tls.VersionTLS12,
InsecureSkipVerify: true, //nolint:gosec
VerifyConnection: func(cs tls.ConnectionState) error {
commonName := cs.PeerCertificates[0].Subject.CommonName
if commonName != cs.ServerName {
return x509.CertificateInvalidError{
Cert: cs.PeerCertificates[0],
Reason: x509.NameMismatch,
Detail: fmt.Sprintf("cn: %q, acceptable: %q", commonName, cs.ServerName),
}
}
opts := x509.VerifyOptions{
Roots: certPool,
Intermediates: x509.NewCertPool(),
}
for _, cert := range cs.PeerCertificates[1:] {
opts.Intermediates.AddCert(cert)
}
_, err := cs.PeerCertificates[0].Verify(opts)
if err != nil {
return fmt.Errorf("peer cert verify: %w", err)
}
return nil
},
}
if chj.TLSCN != "" {
chj.tlsCfg.ServerName = chj.TLSCN
}
return nil
}
func init() {
inputs.Add("circ_http_json", func() cua.Input {
return &CHJ{}
})
}
|
go
| 26 | 0.664602 | 120 | 24.977011 | 261 |
starcoderdata
|
GLuint Shader::compileShader(GLenum shaderType, const std::string &res, const std::string &shaderName) {
// Read the shader source file into a string
char *shaderString = GLSL::textFileRead((res + shaderName).c_str());
// Stop if there was an error reading the shader source file
if (shaderString == NULL) return 0;
// Create the shader, assign source code, and compile it
GLuint shader = glCreateShader(shaderType);
CHECK_GL_CALL(glShaderSource(shader, 1, &shaderString, NULL));
CHECK_GL_CALL(glCompileShader(shader));
// See whether compile was successful
GLint compileSuccess;
CHECK_GL_CALL(glGetShaderiv(shader, GL_COMPILE_STATUS, &compileSuccess));
if (!compileSuccess) {
GLSL::printShaderInfoLog(shader);
std::cout << "Error compiling shader: " << res << shaderName << std::endl;
std::cin.get();
exit(EXIT_FAILURE);
}
// Free the memory
free(shaderString);
return shader;
}
|
c++
| 11 | 0.665994 | 104 | 37.153846 | 26 |
inline
|
// Copyright 2017
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.archos.mediacenter.video.browser;
import android.animation.TimeInterpolator;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewStub;
import android.view.animation.DecelerateInterpolator;
import com.archos.mediacenter.utils.GlobalResumeView;
import com.archos.medialib.R;
public class BrowserLayout extends android.support.v4.widget.DrawerLayout {
public interface Callback {
/** Called when animation is done. */
public void onLayoutChanged();
/** Called when category view is dragged. */
public void onGoHome();
}
private static final int ANIMATION_DURATION = 300;
/* The layout has never been initialized */
private static final int STATE_UNINITIALIZED = -1;
/* The layout shows the cover and the category */
private static final int STATE_COVER = 0;
/* The layout shows the category and the content */
private static final int STATE_CONTENT = 1;
/* Property name for the cover's animation */
private static final String PROP_COVER_LEFT = "coverLeftAnim";
private static final String TAG = "BrowserLayout";
private static final TimeInterpolator INTERPOLATOR = new DecelerateInterpolator(1.5f);
private Callback mCallback;
private GlobalResumeView mGlobalResumeView;
private View mCategoryView;
private View mContentView;
private ViewStub mGlobalResumeViewStub;
// Arrays of invisible and visible views according the orientation and the
// layout's state.
// The first index is STATE_*
// The second index is the list of the views.
private View[][] mInvisibleViews, mVisibleViews;
public BrowserLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public BrowserLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public BrowserLayout(Context context) {
super(context);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
// TODO This should be in the xml.
mCategoryView = findViewById(R.id.category);
mGlobalResumeViewStub = (ViewStub) findViewById(R.id.global_resume_stub);
mContentView = findViewById(R.id.content);
mCategoryView.setOnKeyListener(mOnKeyListener);
}
private final OnKeyListener mOnKeyListener = new OnKeyListener() {
// This listener is used to check the keypresses when the categories or global resume have the focus
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT && event.getAction() == KeyEvent.ACTION_DOWN) {
mCallback.onGoHome();
return true;
}
return false;
}
};
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
private static float getCoverRollWidthRatio(Configuration config, boolean isAndroidTV) {
final int w = config.screenWidthDp;
if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
// LANDSCAPE
if (w<700)
return 0.50f; // phones
else if (w<900&& !isAndroidTV)
return 0.69f; // Kindle Fire HD (853dp)
else if (w<1000&& !isAndroidTV)
return 0.69f; // Nexus 7 (961dp)
else if (w<1200&& !isAndroidTV)
return 0.66f; // Archos 80 (1024dp)
else
return 0.71f; // Archos 10 (1280dp)
}
else {
// PORTRAIT
if (w<500)
return 0; // phones
else
return 0.5f; // tablets
}
}
public void setCallback(Callback callback) {
mCallback = callback;
}
public View getCategoryView() {
return mCategoryView;
}
public View getContentView() {
return mContentView;
}
/**
* Only call this when you really need to show the global resume view.
*/
public GlobalResumeView getGlobalResumeView() {
if (mGlobalResumeView == null) {
mGlobalResumeView = (GlobalResumeView) mGlobalResumeViewStub.inflate();
mGlobalResumeView.setOnKeyListener(mOnKeyListener);
}
SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
if(!mPreferences.getBoolean("display_resume_box",true))
mGlobalResumeView.setVisibility(View.GONE);
else
mGlobalResumeView.setVisibility(View.VISIBLE);
return mGlobalResumeView;
}
}
|
java
| 15 | 0.65954 | 108 | 29.832402 | 179 |
starcoderdata
|
from mininet.net import Containernet
from mininet.node import Controller
from mininet.cli import CLI
from mininet.link import TCLink
from mininet.log import info, setLogLevel
from subprocess import call
import importlib
setLogLevel("info")
leader = None
res = None
def leader_down(net, restarters, service_name):
hosts = [net[hostname] for hostname in filter(lambda i: i[0] == "h", net.keys())]
ips = [host.IP() for host in hosts]
print(ips)
global leader
global res
print("FAILURE: Stopping Leader")
leader = importlib.import_module(
"systems.%s.scripts.find_leader" % service_name
).find_leader(hosts, ips)
res = restarters[hosts.index(leader)]
print(
"FAILURE: killing screen : `screen -X -S %s quit`"
% (service_name + "_" + leader.name)
)
leader.cmd("screen -X -S %s quit" % (service_name + "_" + leader.name))
def leader_up():
global leader
global res
print("FAILURE: Bringing leader back up")
# call('docker start {0}'.format('mn.'+leader.name).split(' '))
res() # Restarts leader
leader, res = None, None
def setup(net, restarters, service_name, cgrps):
return [lambda: leader_down(net, restarters, service_name), lambda: leader_up()]
|
python
| 12 | 0.66195 | 85 | 26.652174 | 46 |
starcoderdata
|
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use App\Models\LanguageNation;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
// public function __construct(){
// $language = LanguageNation::all();
// // dd($language);
// view()->share(['language'=>$language]);
// }
static function rand_string($length)
{
$str = '';
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen($chars);
for ($i = 0; $i < $length; $i++) {
$str .= $chars[rand(0, $size - 1)];
}
return $str;
}
}
|
php
| 15 | 0.656587 | 82 | 24.722222 | 36 |
starcoderdata
|
def test_data_conf(self):
"""
Validation of the data_conf property
"""
expected = DataConf(_env_file=TESTS_ENV_PATH, data_path=data_mgr.data_path,
defaults=dict(unknown="unknown")).dict()
self.case.assertDictEqual(expected, conf_mgr.data_conf.dict())
conf_mgr._data_conf = None
self.case.assertDictEqual(expected, conf_mgr.data_conf.dict())
|
python
| 14 | 0.604706 | 83 | 41.6 | 10 |
inline
|
public CssLength getLength() throws InvalidParamException {
if (computed_type == CssTypes.CSS_LENGTH) {
// TODO fixme...
// we might change this to CssCheckableValue instead.
}
throw new ClassCastException("unknown");
}
|
java
| 7 | 0.616236 | 65 | 37.857143 | 7 |
inline
|
pub fn open<P: AsRef<Path>>(index_dir: P) -> Result<Index> {
let index_dir = index_dir.as_ref();
// We claim it is safe to open the following memory map because we
// don't mutate them and no other process (should) either.
let seasons = unsafe { fst_set_file(index_dir.join(SEASONS))? };
let tvshows = unsafe { fst_set_file(index_dir.join(TVSHOWS))? };
Ok(Index {
seasons,
tvshows,
})
}
|
rust
| 11 | 0.570213 | 74 | 41.818182 | 11 |
inline
|
/**
* @file AboutCommand.cpp
* @author (
* @brief
* @version 0.1
* @date 2019-05-11 12:43
*
* @copyright Copyright (c) 2019
*
*/
#include "AboutCommand.hpp"
#include "util/constants.hpp"
#include "util/Singleton.hpp"
#include "rest/DiscordAPI.hpp"
#include "guilds/GuildManager.hpp"
#include "users/UserManager.hpp"
namespace discordpp
{
bool AboutCommand::proc(const nlohmann::json &packet)
{
nlohmann::json json;
nlohmann::json embed;
embed["color"] = 15794175;
embed["title"] = ":gem: About ";
embed["description"] = "• Developer :
"• Invite Link : To be added \n"
"• Current Version : Beta 1.0.0\n"
"• Developed in **C++** using [**Discord++**](https://github.com/Devincf/Discordpp)\n"
"• Active in : **"+std::to_string(Singleton + "** servers with a total of **"+std::to_string(Singleton users";
/*embed["fields"] = nlohmann::json::array();
nlohmann::json field1;
field1["name"] = "test field 1";
field1["value"] = "test value 1";
nlohmann::json field2;
field2["name"] = "test field 2";
field2["value"] = "test value 2";
field2["inline"] = true;
embed["fields"].push_back(field1);
embed["fields"].push_back(field2);*/
json["embed"] = embed;
Singleton json);
return true;
}
} // namespace discordpp
|
c++
| 20 | 0.58867 | 204 | 28.017857 | 56 |
starcoderdata
|
public double[][] readDistanceMatrix(final String INPUT_FILE) throws IOException {
double[][] matrix;
BufferedReader br = new BufferedReader(new FileReader(INPUT_FILE));
StringBuilder build = new StringBuilder();
// Find out how many cities there are in the file
int numCities = 0;
while (!build.append(br.readLine()).toString().equalsIgnoreCase("null")) {
numCities++;
build.setLength(0); // Clears the buffer
}
matrix = new double[numCities][numCities];
// Reset reader to the start of the file
br = new BufferedReader(new FileReader(INPUT_FILE));
// Populate the distance matrix
int currentCity = 0;
build = new StringBuilder();
while (!build.append(br.readLine()).toString().equalsIgnoreCase("null")) {
String[] tokens = build.toString().split(" ");
for (int i = 0; i < numCities; i++) {
matrix[currentCity][i] = Double.parseDouble(tokens[i]);
}
currentCity++;
build.setLength(0); // Clears the buffer
}
return matrix;
}
|
java
| 12 | 0.647454 | 82 | 37.592593 | 27 |
inline
|
using System;
using System.Collections.Generic;
using System.Text;
using ClearCanvas.Dicom;
using System.Xml;
using ClearCanvas.ImageViewer.StudyManagement;
namespace MINTLoader
{
class SeriesMINTXml
{
#region Private Members
private DicomAttributeCollection _seriesAttributes = null;
private List _instances = new List
#endregion
#region Public Properties
public DicomAttribute this[uint tag]
{
get
{
// Normalized instance attributes are never considered here...
return (_seriesAttributes == null) ? null : _seriesAttributes[tag];
}
}
public DicomAttribute this[DicomTag tag]
{
get
{
return this[tag.TagValue];
}
}
public IList Instances
{
get
{
return _instances;
}
}
#endregion
#region Constructor
public SeriesMINTXml(
StudyLoaderArgs studyLoaderArgs,
string metaUri,
XmlElement seriesElem,
DicomAttributeCollection studyAttributes)
{
_seriesAttributes =
MINTAttributeCollectionParser.ParseAttributes(studyLoaderArgs, metaUri, seriesElem,
"attributes").Attributes;
var normalizedInstanceAttributes =
MINTAttributeCollectionParser.ParseAttributes(studyLoaderArgs, metaUri, seriesElem,
"normalizedInstanceAttributes").Attributes;
foreach (var subNode in seriesElem)
{
var subElem = subNode as XmlElement;
if ((subElem != null) && subElem.Name.Equals("instances"))
{
foreach (var instanceNode in subElem)
{
var instanceElem = instanceNode as XmlElement;
if ((instanceElem != null) && instanceElem.Name.Equals("instance"))
{
_instances.Add(new InstanceMINTXml(studyLoaderArgs, metaUri, instanceElem, studyAttributes,
_seriesAttributes, normalizedInstanceAttributes));
}
}
}
}
}
#endregion
}
}
|
c#
| 22 | 0.521671 | 119 | 30.538462 | 78 |
starcoderdata
|
function() {
// Get the category object.
var name = $('#category-editor').data('category_name');
var category = $('#configuration').data('configuration').get_category(name);
// Update the category object.
category.name = $('#category-editor input[name="name"]').val();
category.description = $('#category-editor input[name="description"]').val();
category.regexes = $('#category-editor .regexes li.item a').toArray().map(function(element) {
return $(element).html();
});
// Update the category
$('#configuration').data('configuration').save();
}
|
javascript
| 17 | 0.643987 | 97 | 38.5 | 16 |
starcoderdata
|
NDArray* NDArrayList::stack() {
// FIXME: this is bad for perf, but ok as poc
nd4j::ops::concat op;
std::vector<NDArray*> inputs;
std::vector<double> targs;
std::vector<Nd4jLong> iargs({0});
std::vector<bool> bargs;
int numElements = _elements.load();
for (int e = 0; e < numElements; e++)
inputs.emplace_back(_chunks[e]);
iargs.push_back(_axis);
auto result = op.execute(inputs, targs, iargs, bargs);
auto array = result->at(0)->dup();
delete result;
return array;
}
|
c++
| 9 | 0.546374 | 62 | 26 | 22 |
inline
|
package j6;
/**
* @see j6
* @see j6.BUG54962
* @see j6.Bug54962
*/
public class Bug54962 {
}
|
java
| 3 | 0.602041 | 23 | 9.888889 | 9 |
starcoderdata
|
def plot_from_arguments(dataset_folder, task_name, dataset, mesh_name='manipulation_object', plot_mesh='mesh'):
# choose the dataset for plotting
dataset_folder_task = os.path.join(dataset_folder, task_name)
if dataset == "train_original_mesh":
dataset_folder_selection = os.path.join(dataset_folder_task, "train_data", "original_mesh")
elif dataset == "train_random_mesh":
dataset_folder_selection = os.path.join(dataset_folder_task, "train_data", "random_mesh")
elif dataset == "test":
dataset_folder_selection = os.path.join(dataset_folder_task, "test_data", "object_1")
else:
print("Invalid dataset type!")
exit()
json_file = os.path.join(dataset_folder, "config_files", "camera_parameters.json")
with open(json_file) as f:
json_data = json.load(f)
camera_params = {
"intrinsic_matrix": np.array(json_data["intrinsic_matrix"]),
"dist_coeffs": np.array(json_data["dist_coeffs"])
}
# choose to plot mesh or bounding box
if plot_mesh == 'mesh':
mesh_file = os.path.join(dataset_folder_task, "models", mesh_name+".obj")
plot_target_pose(dataset_folder_selection, mesh_file, camera_params)
elif plot_mesh == 'bb':
bb_file = os.path.join(dataset_folder_task, "models", "bounding_box.json")
generate_keypoints_and_plot_3D_bounding_box(dataset_folder_selection, bb_file, camera_params)
else:
print("Invalid plot_mesh type!")
exit()
|
python
| 11 | 0.653102 | 111 | 44.454545 | 33 |
inline
|
package it.polimi.deib.newdem.adrenaline.model.game.killtrack;
import it.polimi.deib.newdem.adrenaline.model.game.player.Player;
import it.polimi.deib.newdem.adrenaline.model.game.utils.Scoreboard;
import it.polimi.deib.newdem.adrenaline.model.game.utils.ScoreboardEntry;
import java.util.ArrayList;
import java.util.List;
/**
* A simple implemntation of {@code KillTrack} useing {@code Cell}s.
*
* @see Cell
*/
public class KillTrackImpl implements KillTrack {
private List kills;
private int initialTrackLength;
private KillTrackListener listener;
private int[] score;
/**
* Minimum size of any {@code KillTrack}. This may override a wrong config option.
*/
public static final int MIN_KILLTRACK_SIZE = 5;
/**
* Maximum size of any {@code KillTrack}. This may override a wrong config option.
*/
public static final int MAX_KILLTRACK_SIZE = 8;
/** Creates a new {@code KillTrack} with {@code trackLength} initial skulls on it.
*
* @param trackLength Amount of initial skulls on the track. Between 5 and 8, inclusive.
* @throws IllegalArgumentException if trackLength is out of bounds
*/
public KillTrackImpl(int trackLength){
if(trackLength < MIN_KILLTRACK_SIZE || trackLength > MAX_KILLTRACK_SIZE) {
throw new IllegalArgumentException("TrackLength must be between 5 and 8 inclusive");
}
kills = new ArrayList<>(0);
initialTrackLength = trackLength;
listener = new NullKillTrackLister();
score = new int[6];
score[0] = 8;
score[1] = 6;
score[2] = 4;
score[3] = 2;
score[4] = 1;
score[5] = 1;
}
/**
* Register a kill for {@code Player}
*
* @param player the killer. Not null.
*/
@Override
public void addKill(Player player, int amount) {
if(null == player) {
throw new IllegalArgumentException("Player must not be null");
}
if(!(0 <= amount && amount <= 2)) throw new IndexOutOfBoundsException();
kills.add(new Cell(player, amount));
listener.playerDidKill(player, amount);
}
/**
* Identifies the {@code Player} that executed the {@code killIndex}-th kill.
*
* @param killIndex The kill index. Must be between 0 (inclusive) and {@code getTotalKills()} (exclusive)
* @return The {@code Player} responsible for the kill
*/
@Override
public Player getKiller(int killIndex) {
if(killIndex < 0 || killIndex > getTotalKills()) {
throw new IndexOutOfBoundsException("KillIndex must be between 0 inclusive and getTotalKills() exclusive");
}
return kills.get(killIndex).getKiller();
}
/**
* Returns the initial length of this {@code KillTrack}
*
* @return the initial length of the {@code KillTrack}
*/
@Override
public int getTrackLength() {
return initialTrackLength;
}
/**
* Returns the total amount of kills up to now.
*
* @return the amount of kills
*/
@Override
public int getTotalKills() {
return kills.size();
}
@Override
public void setListener(KillTrackListener listener) {
this.listener = listener;
if (listener != null) {
listener.killTrackDidRestore(generateKillTrackData());
}
}
@Override
public int getScoreForPlayer(Player player) {
Scoreboard sb = makeScoreboard();
int placement = sb.getPlacement(player);
try{
return score[placement];
}
catch (ArrayIndexOutOfBoundsException e) {
return 0;
}
}
private ScoreboardEntry makeScoreboardEntry(Player player) {
int points = 0;
int earliest = getTotalKills() + 1;
for(int i = 0; i < kills.size(); i++) {
if(kills.get(i).getKiller().equals(player)) {
points += kills.get(i).getAmount();
earliest = Math.min(earliest, i);
}
}
return new ScoreboardEntry(player, points, earliest);
}
private Scoreboard makeScoreboard() {
ArrayList players = new ArrayList<>();
for(Cell c : kills) {
if(!players.contains(c.getKiller())) players.add(c.getKiller());
}
Scoreboard s = new Scoreboard();
for(Player p : players) {
s.registerEntry(makeScoreboardEntry(p));
}
return s;
}
/**
* Creates a new {@code KillTrackData} representing this object at the time of invocation
*
* @return serializable data about this object
*/
@Override
public KillTrackData generateKillTrackData() {
KillTrackData data = new KillTrackData(this);
for (Cell c : kills) {
data.addKill(new KillTrackData.KillData(c.getKiller().getColor(), c.getAmount()));
}
return data;
}
}
|
java
| 15 | 0.609864 | 119 | 28.341176 | 170 |
starcoderdata
|
/*******************************************************************************
Copyright (c) 2016 Advanced Micro Devices, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include "buffers.h"
#include
#include
#include
#include
void check_device_memory_requirements(
struct problem * problem, struct rankinfo * rankinfo)
{
#if 1
//OpenMP does not have routines to query device name and memory sizes
// just hard code this info for now
std::wcout << "device : Quadro K4000" << std::endl;
unsigned long global = 3ul*1024ul*1024ul*1024ul; // for Quadro K4000 (t0)
std::wcout << "device memory: " << global << std::endl;
#else
hc::accelerator acc;
std::wstring device_name(acc.get_description());
std::wcout << "device : " << device_name << std::endl;
unsigned long global = acc.get_dedicated_memory();
// for hsa - accelerator.get_dedicated_memory()
printf("device memory: %ld\n",global);
size_t tsmem = acc.get_max_tile_static_size();
printf("tile static memory: %ld\n",tsmem);
#endif
unsigned long total = 0;
// Add up the memory requirements, in bytes.
total += problem->nang*problem->ng*rankinfo->nx*rankinfo->ny*rankinfo->nz*8;
total += problem->nang*problem->ng*rankinfo->nx*rankinfo->ny*rankinfo->nz*8;
total += problem->nang*problem->ng*rankinfo->ny*rankinfo->nz;
total += problem->nang*problem->ng*rankinfo->nx*rankinfo->nz;
total += problem->nang*problem->ng*rankinfo->nx*rankinfo->ny;
total += problem->ng*rankinfo->nx*rankinfo->ny*rankinfo->nz;
if (problem->cmom-1 == 0)
total += problem->ng*rankinfo->nx*rankinfo->ny*rankinfo->nz;
else
total += 1;
total += problem->nang;
total += problem->nang;
total += problem->nang;
total += problem->nang;
total += problem->nang*problem->cmom*8;
total += problem->ng;
total += problem->ng*rankinfo->nx*rankinfo->ny*rankinfo->nz;
total += problem->cmom*problem->ng*rankinfo->nx*rankinfo->ny*rankinfo->nz;
total += problem->cmom*problem->ng*rankinfo->nx*rankinfo->ny*rankinfo->nz;
total += problem->nmom*problem->ng*problem->ng;
total += 1;
total += problem->nang;
total += problem->nang;
total += problem->ng;
total += problem->ng;
total += problem->nang*problem->ng*rankinfo->nx*rankinfo->ny*rankinfo->nz;
total *= sizeof(double);
if (global < total)
{
fprintf(stderr,"Error: Device does not have enough global memory.\n");
fprintf(stderr, "Required: %.1f GB\n", (double)total/(1024.0*1024.0*1024.0));
fprintf(stderr, "Available: %.1f GB\n", (double)global/(1024.0*1024.0*1024.0));
exit(EXIT_FAILURE);
}
}
void zero_buffer(double *pbuffer, size_t offset, size_t size)
{
#pragma omp target data map(to: pbuffer[offset:size+offset],offset,size)
#pragma omp target
#pragma omp parallel for
for(int i = 0; i<size; i++)
{
pbuffer[i+offset] = 0.0;
}
}
void set_buffer(double *pbuffer, double value, size_t size)
{
#pragma omp target data map(to: pbuffer[:size],value,size)
#pragma omp target teams
#pragma omp parallel for
for(int i = 0; i<size; i++)
{
pbuffer[i] = value;
}
}
void swap_angular_flux_buffers(struct buffers * buffers)
{
double *tmp;
for (int i=0;i<8;i++)
{
tmp = buffers->angular_flux_in[i];
buffers->angular_flux_in[i] = buffers->angular_flux_out[i];
buffers->angular_flux_out[i] = tmp;
}
}
|
c++
| 12 | 0.671285 | 87 | 36.727273 | 132 |
starcoderdata
|
package it.unibz.inf.ontop.spec.mapping.validation;
/*
* #%L
* ontop-obdalib-core
* %%
* Copyright (C) 2009 - 2014 Free University of Bozen-Bolzano
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import it.unibz.inf.ontop.injection.OntopSQLCredentialSettings;
import it.unibz.inf.ontop.spec.mapping.SQLPPSourceQuery;
import it.unibz.inf.ontop.protege.utils.JDBCConnectionManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SQLSourceQueryValidator {
private final OntopSQLCredentialSettings settings;
private SQLPPSourceQuery sourceQuery = null;
private Exception reason = null;
private JDBCConnectionManager modelfactory = null;
private Statement st;
private Connection c;
public SQLSourceQueryValidator(OntopSQLCredentialSettings settings, SQLPPSourceQuery q) {
this.settings = settings;
sourceQuery = q;
}
public boolean validate() {
ResultSet set = null;
try {
modelfactory = JDBCConnectionManager.getJDBCConnectionManager();
c = modelfactory.getConnection(settings);
st = c.createStatement();
set = st.executeQuery(sourceQuery.toString());
return true;
} catch (SQLException e) {
reason = e;
return false;
} catch (Exception e) {
reason = e;
return false;
} finally {
try {
set.close();
} catch (Exception e) {
// NO-OP
}
try {
st.close();
} catch (Exception e) {
// NO-OP
}
}
}
public void cancelValidation() throws SQLException {
st.cancel();
}
/***
* Returns the exception that cause the query to be invalid.
*
* @return Exception that caused invalidity. null if no reason was set or if
* the query is valid.
*/
public Exception getReason() {
return reason;
}
}
|
java
| 13 | 0.719984 | 121 | 25.434783 | 92 |
starcoderdata
|
def initialize(self):
"""
Create the clients and log in. Using easy_client, we can get new creds
from the user via the web browser if necessary
"""
self.tda_client = easy_client(
# You can customize your browser here
webdriver_func=lambda: webdriver.Chrome(),
#webdriver_func=lambda: webdriver.Firefox(),
#webdriver_func=lambda: webdriver.Safari(),
#webdriver_func=lambda: webdriver.Ie(),
api_key=self.api_key,
redirect_uri='https://localhost:8080',
token_path=self.credentials_path)
self.stream_client = StreamClient(
self.tda_client, account_id=self.account_id)
# The streaming client wants you to add a handler for every service type
self.stream_client.add_timesale_equity_handler(
self.handle_timesale_equity)
|
python
| 11 | 0.616927 | 80 | 43.95 | 20 |
inline
|
package com.gorevev.gamebook.context.presentation.injections.components;
import com.gorevev.gamebook.context.presentation.injections.modules.MenuModule;
import com.gorevev.gamebook.context.presentation.injections.scopes.MenuScope;
import com.gorevev.gamebook.context.presentation.main_menu.menu.MenuFragment;
import dagger.Subcomponent;
/**
* Created by Ginko on 17.11.2016.
*/
@MenuScope
@Subcomponent(modules = MenuModule.class)
public interface MenuComponent {
void inject(MenuFragment menuFragment);
}
|
java
| 9 | 0.812854 | 79 | 26.842105 | 19 |
starcoderdata
|
let http = require('http');
let express = require('express');
let fs = require('fs');
let mustache = require('mustache');
let app = express();
let server = http.createServer(app);
let io = require('socket.io')(server);
let opts = {
port: process.env.PORT || 1947,
revealDir: process.cwd(),
pluginDir: __dirname
};
io.on( 'connection', socket => {
socket.on( 'new-subscriber', data => {
socket.broadcast.emit( 'new-subscriber', data );
});
socket.on( 'statechanged', data => {
delete data.state.overview;
socket.broadcast.emit( 'statechanged', data );
});
socket.on( 'statechanged-speaker', data => {
delete data.state.overview;
socket.broadcast.emit( 'statechanged-speaker', data );
});
});
app.use( express.static( opts.revealDir ) );
app.get('/', ( req, res ) => {
res.writeHead( 200, { 'Content-Type': 'text/html' } );
fs.createReadStream( opts.revealDir + '/index.html' ).pipe( res );
});
app.get( '/notes/:socketId', ( req, res ) => {
fs.readFile( opts.pluginDir + '/index.html', ( err, data ) => {
res.send( mustache.render( data.toString(), {
socketId : req.params.socketId
}));
});
});
// Actually listen
server.listen( opts.port || null );
let brown = '\033[33m',
green = '\033[32m',
reset = '\033[0m';
let slidesLocation = 'http://localhost' + ( opts.port ? ( ':' + opts.port ) : '' );
console.log( brown + 'reveal.js - Speaker Notes' + reset );
console.log( '1. Open the slides at ' + green + slidesLocation + reset );
console.log( '2. Click on the link in your JS console to go to the notes page' );
console.log( '3. Advance through your slides and your notes will advance automatically' );
|
javascript
| 16 | 0.632582 | 90 | 25.227273 | 66 |
starcoderdata
|
from legco.models import Meeting, Vote, Motion, Individual, IndividualVote, VoteSummary
from lxml import etree
from datetime import *
import requests
from dateutil.parser import *
import hashlib
def parse_date(s):
for fmt in ["%d/%m/%Y","%d-%m-%Y"]:
try:
return datetime.strptime(s, fmt).date()
except:
pass
raise Exception("failed to parse %s." % (s))
def parse_time(s):
return datetime.strptime(s or "00:00:00", "%H:%M:%S").time()
def upsert_votes_into_db(url):
if url is None:
return []
r = requests.get(url)
s = r.content
print(s[0:300])
doc = etree.XML(s)
individuals = Individual.objects.all()
results = []
for meeting_node in doc.xpath('//meeting'):
md5 = hashlib.new('md5')
md5.update(url.encode('utf-8'))
key = str(md5.hexdigest())
meeting = Meeting.objects.filter(key=key).first()
if meeting is not None:
votes = []
for v in Vote.objects.filter(meeting=meeting):
summaries = VoteSummary.objects.filter(vote=v)
individual_votes = IndividualVote.objects.filter(vote=v)
votes.append({'vote': v, 'summaries': summaries, 'individual_votes': individual_votes})
results.append({'meeting': meeting, 'votes': votes, 'is_created': False})
continue
meeting = Meeting()
meeting.date = parse_date(meeting_node.attrib['start-date'])
meeting.meeting_type = meeting_node.attrib['type']
meeting.source_url = url
meeting.key = key
meeting.save()
votes = []
for vote_node in meeting_node.xpath('./vote'):
motion = Motion()
motion.name_en = vote_node.xpath('motion-en')[0].text or ""
motion.name_ch = vote_node.xpath('motion-ch')[0].text
if len(vote_node.xpath('mover-en')) > 0:
motion.mover_en = vote_node.xpath('mover-en')[0].text
motion.mover_ch = vote_node.xpath('mover-ch')[0].text
motion.mover_type = vote_node.xpath('mover-type')[0].text
else:
motion.mover_en = ""
motion.mover_ch = ""
motion.mover_type = ""
motion.save()
vote = Vote()
vote.meeting = meeting
vote.date = parse_date(vote_node.xpath('vote-date')[0].text)
vote.time = parse_time(vote_node.xpath('vote-time')[0].text)
vote.vote_number = int(vote_node.attrib['number'])
vote.separate = vote_node.xpath('vote-separate-mechanism')[0].text == "Yes"
vote.motion = motion
vote.save()
possible_summary_tags = ['overall','functional-constituency','geographical-constituency']
summary_types = ['OVER', 'FUNC', 'GEOG']
summaries = []
for summary_node in vote_node.xpath('vote-summary')[0].xpath('*'):
summary = VoteSummary()
summary.vote = vote
summary.summary_type = summary_types[possible_summary_tags.index(summary_node.tag)]
summary.present_count = int(summary_node.xpath('present-count')[0].text or 0)
summary.vote_count = int(summary_node.xpath('vote-count')[0].text or 0)
summary.yes_count = int(summary_node.xpath('yes-count')[0].text or 0)
summary.no_count = int(summary_node.xpath('no-count')[0].text or 0)
summary.abstain_count = int(summary_node.xpath('abstain-count')[0].text or 0)
summary.result = summary_node.xpath('result')[0].text
summary.save()
summaries.append(summary)
individual_votes = []
for individual_vote_node in vote_node.xpath('./individual-votes/member'):
name_ch = individual_vote_node.attrib['name-ch']
name_en = individual_vote_node.attrib['name-en']
target_individual = None
for individual in individuals:
if individual.name_ch == name_ch or individual.name_en == name_en:
target_individual = individual
break
if target_individual is None:
raise Exception("Individual not found " + name_ch)
individual_vote = IndividualVote()
individual_vote.result = individual_vote_node.xpath('vote')[0].text.upper()
individual_vote.individual = target_individual
individual_vote.vote = vote
individual_vote.save()
individual_votes.append(individual_vote)
votes.append({'vote': vote, 'summaries': summaries, 'individual_votes': individual_votes })
#Saving Records
meeting.save()
results.append({'meeting': meeting, 'votes':votes , 'is_created': True})
return results
|
python
| 19 | 0.566567 | 103 | 43.598214 | 112 |
starcoderdata
|
import collections
N = int(input())
G = [set() for i in range(N)]
for i in range(N-1):
a, b = map(int, input().split())
a -= 1
b -= 1
G[a].add(b)
G[b].add(a)
F = [-1]*N
F[0] = 0
q = collections.deque()
q.append(0)
while(q):
x = q.popleft()
for y in G[x]:
if F[y] < 0:
F[y] = F[x] + 1
q.append(y)
S = [-1]*N
S[N-1] = 0
q.append(N-1)
while(q):
x = q.popleft()
for y in G[x]:
if S[y] < 0:
S[y] = S[x] + 1
q.append(y)
# print(F)
# print(S)
ans = 0
q = collections.deque()
r = [True]*N
for i in range(N):
if F[i] + S[i] == F[-1]:
if F[i] <= S[i]:
q.append(i)
r[i] = False
else:
r[i] = False
ans = len(q)
while(q):
x = q.popleft()
for y in G[x]:
if r[y]:
ans += 1
q.append(y)
r[y] = False
if ans > N - ans:
print("Fennec")
else:
print("Snuke")
|
python
| 11 | 0.412071 | 36 | 15.288136 | 59 |
codenet
|
def testSaveRestore(self):
""" test saving/restoring replacement to map"""
r1 = QgsStringReplacement('a', 'b', True, True)
props = r1.properties()
r2 = QgsStringReplacement.fromProperties(props)
self.assertEqual(r1, r2)
r1 = QgsStringReplacement('a', 'b', False, False)
props = r1.properties()
r2 = QgsStringReplacement.fromProperties(props)
self.assertEqual(r1, r2)
|
python
| 8 | 0.63242 | 57 | 42.9 | 10 |
inline
|
'use strict'
const ObjectFactory = require( 'nof' )
const NumericFactory = opts => {
const isInteger = !!opts.isInteger
const propertyTransform = ( name, value ) => {
let num = Number( value )
if( Number.isNaN( num ) )
num = 0
return isInteger ? Math.trunc( num ) : num
}
const options = Object.assign( {}, opts, { propertyTransform } )
return ObjectFactory( options )
}
module.exports = NumericFactory
|
javascript
| 14 | 0.625806 | 66 | 19.217391 | 23 |
starcoderdata
|
using Clinicas.Models;
using Clinicas.ViewModels.Consulta;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Clinicas.Repository.Consultas
{
interface IConsulta
{
List All();
Models.Consulta One(int id);
Models.Consulta Store(ConsultaVM model);
Models.Consulta Edit(ConsultaVM model);
}
}
|
c#
| 9 | 0.733471 | 52 | 21 | 22 |
starcoderdata
|
package self.vpalepu.data.toi;
import java.util.ArrayList;
import org.joda.time.LocalDate;
public class Story {
private final String title;
private final String href;
private LocalDate date;
private ArrayList tags;
public Story(String title, String href, LocalDate date) {
this.title = title;
this.href = href;
this.date = date;
}
public String title() {
return this.title;
}
public String href() {
return this.href;
}
public LocalDate date() {
return this.date;
}
public String[] tags() {
String[] split = href.split("/");
return split;
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(this.date()).append(",");
buffer.append("\"").append(title).append("\"").append(",");
buffer.append(href);
return buffer.toString();
}
public static Story fromString(String line) {
String href = line.substring(line.lastIndexOf(',')+1);
String datestring = line.substring(0, line.indexOf(','));
LocalDate date = LocalDate.parse(datestring);
String title = line.substring(line.indexOf('"') + 1, line.lastIndexOf('"'));
Story story = new Story(title, href, date);
return story;
}
public static Story cleanTitledfromString(String line) {
String href = line.substring(line.lastIndexOf(',')+1);
String datestring = line.substring(0, line.indexOf(','));
LocalDate date = LocalDate.parse(datestring);
String title = line.substring(line.indexOf('"') + 1, line.lastIndexOf('"'));
String cleanTitle = cleanTitle(title);
Story story = new Story(cleanTitle, href, date);
return story;
}
private static String cleanTitle(String title) {
final StringBuilder builder = new StringBuilder();
for(final char c : title.toCharArray())
if(Character.isLetterOrDigit(c) || Character.isWhitespace(c))
builder.append(Character.toLowerCase(c));
return builder.toString();
}
}
|
java
| 12 | 0.645813 | 80 | 27.194444 | 72 |
starcoderdata
|
import React from 'react'
import classNames from 'classnames'
import styles from './button.module.scss'
export default function Button({
children,
onClick,
url,
submit,
outline,
primary,
fullWidth,
}) {
const className = classNames(
styles.Button,
outline && styles.outline,
primary && styles.primary,
fullWidth && styles.fullWidth
)
const type = submit ? 'submit' : 'button'
if (url) {
return (
<a href={url} className={className}>
{children}
)
} else {
return (
<button type={type} onClick={onClick} className={className}>
{children}
)
}
}
|
javascript
| 13 | 0.605463 | 66 | 16.810811 | 37 |
starcoderdata
|
/*
* Tencent is pleased to support the open source community by making BlueKing available.
* Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.bk.codecc.defect.service.impl;
import com.tencent.bk.codecc.defect.dao.mongorepository.CLOCDefectRepository;
import com.tencent.bk.codecc.defect.dao.mongorepository.CLOCStatisticRepository;
import com.tencent.bk.codecc.defect.model.CLOCStatisticEntity;
import com.tencent.bk.codecc.defect.service.IQueryStatisticBizService;
import com.tencent.bk.codecc.defect.vo.CLOCDefectQueryRspInfoVO;
import com.tencent.devops.common.api.analysisresult.BaseLastAnalysisResultVO;
import com.tencent.devops.common.api.analysisresult.CLOCLastAnalysisResultVO;
import com.tencent.devops.common.api.analysisresult.ToolLastAnalysisResultVO;
import com.tencent.devops.common.constant.ComConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* cloc查询服务类
*
* @date 2019/11/1
* @version V1.0
*/
@Slf4j
@Service("CLOCQueryStatisticBizService")
public class CLOCQueryStatisticBizServiceImpl implements IQueryStatisticBizService
{
@Autowired
CLOCStatisticRepository clocStatisticRepository;
@Autowired
CLOCDefectRepository clocDefectRepository;
@Override
public BaseLastAnalysisResultVO processBiz(ToolLastAnalysisResultVO arg, boolean isLast) {
log.info("get cloc statistic list, taskId: {} | buildId: {}", arg.getTaskId(), arg.getBuildId());
String buildId = arg.getBuildId();
List clocStatisticEntityList =
clocStatisticRepository.findByTaskIdAndToolNameAndBuildId(arg.getTaskId(), arg.getToolName(), buildId);
long sumCode = 0;
long sumBlank = 0;
long sumComment = 0;
long codeChange = 0;
long blankChange = 0;
long commentChange = 0;
long fileNum = 0;
long fileNumChange = 0;
for (CLOCStatisticEntity clocStatisticEntity : clocStatisticEntityList
) {
if (clocStatisticEntity.getSumCode() != null) {
sumBlank += clocStatisticEntity.getSumBlank();
sumCode += clocStatisticEntity.getSumCode();
sumComment += clocStatisticEntity.getSumComment();
}
if (clocStatisticEntity.getCodeChange() != null) {
blankChange += clocStatisticEntity.getBlankChange();
codeChange += clocStatisticEntity.getCodeChange();
commentChange += clocStatisticEntity.getCommentChange();
}
if (clocStatisticEntity.getFileNum() != null) {
fileNum += clocStatisticEntity.getFileNum();
fileNumChange += clocStatisticEntity.getFileNumChange();
}
}
CLOCLastAnalysisResultVO clocLastAnalysisResultVO = new CLOCLastAnalysisResultVO();
clocLastAnalysisResultVO.setSumCode(sumCode);
clocLastAnalysisResultVO.setSumBlank(sumBlank);
clocLastAnalysisResultVO.setSumComment(sumComment);
clocLastAnalysisResultVO.setTotalLines(sumBlank + sumCode + sumComment);
clocLastAnalysisResultVO.setCodeChange(codeChange);
clocLastAnalysisResultVO.setBlankChange(blankChange);
clocLastAnalysisResultVO.setCommentChange(commentChange);
clocLastAnalysisResultVO.setLinesChange(blankChange + codeChange + commentChange);
clocLastAnalysisResultVO.setFileNum(fileNum);
clocLastAnalysisResultVO.setFileNumChange(fileNumChange);
clocLastAnalysisResultVO.setPattern(String.valueOf(ComConstants.Tool.CLOC));
return clocLastAnalysisResultVO;
}
}
|
java
| 13 | 0.73318 | 119 | 42.55 | 100 |
starcoderdata
|
<?php if(isset($code) && $code == 403) { ?>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="fa fa-times">
class="fa fa-warning"> <?php echo phrase('access_forbidden'); ?>
<div class="modal-body">
<div class="row">
<div class="col-sm-8 col-sm-offset-2 animated shake text-center">
<img src="<?php echo base_url('themes/default/images/large_logo.png'); ?>" />
echo $meta['title']; ?>
echo $meta['descriptions']; ?>
<div class="modal-footer">
<div class="row">
<div class="col-xs-6">
<a href="javascript:void(0)" class="btn btn-default btn-lg pull-left" data-dismiss="modal" aria-hidden="true"><i class="fa fa-times"> <?php echo phrase('close'); ?>
<div class="col-xs-6">
<a href="#login" data-dismiss="modal" aria-hidden="true" data-toggle="modal" class="btn btn-primary btn-lg"><i class="fa fa-sign-in"> <?php echo phrase('login'); ?>
<?php } elseif(isset($code) && $code == 404) { ?>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="fa fa-times">
class="fa fa-warning"> <?php echo phrase('request_not_found'); ?>
<div class="modal-body">
<div class="row">
<div class="col-sm-8 col-sm-offset-2 animated shake text-center">
<img src="<?php echo base_url('themes/default/images/large_logo.png'); ?>" />
echo $meta['title']; ?>
echo $meta['descriptions']; ?>
<div class="modal-footer">
<div class="row">
<div class="col-xs-6">
<a href="javascript:void(0)" class="btn btn-default btn-lg pull-left" data-dismiss="modal" aria-hidden="true"><i class="fa fa-times"> <?php echo phrase('close'); ?>
<div class="col-xs-6">
<a href="#login" data-dismiss="modal" aria-hidden="true" data-toggle="modal" class="btn btn-primary btn-lg"><i class="fa fa-sign-in"> <?php echo phrase('login'); ?>
<?php } ?>
|
php
| 9 | 0.599365 | 176 | 40.603774 | 53 |
starcoderdata
|
#!/usr/bin/env node
const colors = require('colors');
console.log('vue-cf helper'.yellow);
console.log('you can use command:');
console.log('"cfc" or "cfConfigCreator" to create a "CFConfig" file from mysql.');
console.log('also use a config file("cf.config.json"), like this:');
const demo = {
db: {
host: 'localhost',
port: '3306',
user: 'root',
password: '
database: 'demoDB',
}
};
console.log(JSON.stringify(demo, '', 2));
console.log('the file "vue.config.js" like this:'.yellow);
console.log(JSON.stringify({configureWebpack: {
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
include: [/vue-cf/]
}
]
}
}
}, '', 2)
);
|
javascript
| 12 | 0.562183 | 82 | 22.176471 | 34 |
starcoderdata
|
<?php
namespace App\Fields\Extensions\UrlPicker;
use Carbon_Fields\Field\Field;
use Carbon_Fields\Value_Set\Value_Set;
class UrlPicker_Field extends Field
{
protected $url = '';
protected $anchor = '';
protected $blank = 0;
/**
* Create a field from a certain type with the specified label.
*
* @param string $type Field type
* @param string $name Field name
* @param string $label Field label
*/
public function __construct($type, $name, $label)
{
$this->set_value_set(new Value_Set(Value_Set::TYPE_MULTIPLE_PROPERTIES, [
'url' => $this->url,
'anchor' => $this->anchor,
'blank' => (bool) $this->blank
]));
remove_action('wp_ajax_carbonfields_urlpicker_get_tinymce_popup', [$this, 'get_tinymce_popup']);
add_action('wp_ajax_carbonfields_urlpicker_get_tinymce_popup', [$this, 'get_tinymce_popup']);
parent::__construct($type, $name, $label);
}
/**
* Prepare the field type for use
* Called once per field type when activated
*/
public static function field_type_activated()
{
//
}
/**
* Enqueue scripts and styles in admin
* Called once per field type
*/
public static function admin_enqueue_scripts()
{
$root_uri = __DIR__;
$suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min';
# Enqueue JS
wp_register_script('carbon-field-urlpicker', get_template_directory_uri() . "/dist/scripts/admin/bundle.min.js", ['carbon-fields-core', 'wplink', 'wpdialogs']);
wp_localize_script('carbon-field-urlpicker', 'carbonFieldsUrlpickerL10n', [
'select_link' => __('Select Link'),
'remove_link' => __('Remove Link'),
'home_url' => home_url(),
]);
wp_enqueue_script('carbon-field-urlpicker');
# Enqueue CSS
wp_enqueue_style('carbon-field-urlpicker', get_template_directory_uri() . "/dist/scripts/admin/bundle.min.css", ['editor-buttons']);
}
public function get_tinymce_popup()
{
require_once ROOT_DIR . "/public/wp/wp-includes/class-wp-editor.php";
\_WP_Editors::wp_link_dialog();
die();
}
/**
* Load the field value from an input array based on it's name
*
* @param array $input Array of field names and values.
*/
public function set_value_from_input($input)
{
if (!isset($input[$this->get_name()])) {
$this->set_value(null);
return $this;
}
$value_set = [
'url' => $this->url,
'anchor' => $this->anchor,
'blank' => (bool) $this->blank,
];
foreach ($value_set as $key => $v) {
if (isset($input[$this->get_name()][$key])) {
$value_set[$key] = $input[$this->get_name()][$key];
}
}
$this->set_value($value_set);
return $this;
}
/**
* Returns an array that holds the field data, suitable for JSON representation.
*
* @param bool $load Should the value be loaded from the database or use the value from the current instance.
* @return array
*/
public function to_json($load)
{
$field_data = parent::to_json($load);
$field_data['value']['blank'] = (bool)$field_data['value']['blank'];
$field_data = array_merge($field_data, [
'url' => $this->url,
'anchor' => $this->anchor,
'blank' => (bool) $this->blank,
]);
return $field_data;
}
}
|
php
| 17 | 0.634542 | 162 | 24.354839 | 124 |
starcoderdata
|
/*
Joel tiene que pagar impuestos,
él tiene una lista de ingresos y gastos,
cada ingreso está representado en número y significan pesos,
cada gasto tiene un concepto (texto) y el total del gasto en pesos.
Los impuestos que debe pagar son el 16% de sus ingresos
menos el total de sus gastos que estén bajo el concepto de: “salud”
*/
const cuentasJoel = {
ingresos: [300, 600, 200, 400, 500, 700], //2700
gastos: [
{
concepto: "tele",
total: 9000
},
{
concepto: "salud",
total: 100
},
{
concepto: "monas chinas",
total: 987000
},
{
concepto: "pokemones",
total: 3456000
},
{
concepto: "salud",
total: 200
}
]
}
let sumaingresos = 0
let impneto = 0 //432
let gastosalud = 0
for(let i=0; i<cuentasJoel.ingresos.length; i++) {
sumaingresos+=cuentasJoel.ingresos[i];
}
for(let i=0; i<cuentasJoel.gastos.length; i++) {
if(cuentasJoel.gastos[i].concepto==="salud") {
gastosalud+=cuentasJoel.gastos[i].total;
}
}
impneto = sumaingresos*0.16-gastosalud;
console.log("joel debe pagar "+impneto+" pesos");
|
javascript
| 11 | 0.675725 | 67 | 19.830189 | 53 |
starcoderdata
|
bool AABB::Insert(iPoint* newpoint)
{
// If new point is not in the quadtree AABB, return
if (!contains(newpoint))
return false;
// If in this node there is space for the point, pushback it
if (objects.size() < Max_Elements_in_Same_Node)
{
objects.push_back(*newpoint);
return true;
}
// Otherwise, subdivide and add the point to one of the new nodes
if (children[0] == nullptr)
subdivide();
for (uint i = 0; i < 4; i++)
if (children[i]->Insert(newpoint))
return true;
return false;
}
|
c++
| 10 | 0.669276 | 66 | 21.26087 | 23 |
inline
|
def on_data(self, instance, value):
if not (self.canvas or value):
return
img = self.ids.get('qrimage', None)
if not img:
# if texture hasn't yet been created delay the texture updating
Clock.schedule_once(lambda dt: self.on_data(instance, value))
return
img.anim_delay = .25
img.source = self.loading_image
Thread(target=partial(self.generate_qr, value)).start()
|
python
| 12 | 0.593478 | 75 | 37.416667 | 12 |
inline
|
func (fes *APIServer) AppendExtraData(ww http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := AppendExtraDataRequest{}
if err := decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("AppendExtraData: Problem parsing request body: %v", err))
return
}
// Get the transaction bytes from the request data.
txnBytes, err := hex.DecodeString(requestData.TransactionHex)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("AppendExtraData: Problem decoding transaction hex %v", err))
return
}
// Deserialize transaction from transaction bytes.
txn := &lib.MsgDeSoTxn{}
err = txn.FromBytes(txnBytes)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("AppendExtraData: Problem deserializing transaction from bytes: %v", err))
return
}
// Append ExtraData entries
if txn.ExtraData == nil {
txn.ExtraData = make(map[string][]byte)
}
for k, v := range requestData.ExtraData {
vBytes, err := hex.DecodeString(v)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("AppendExtraData: Problem decoding ExtraData: %v", err))
return
}
txn.ExtraData[k] = vBytes
}
// Get the final transaction bytes.
txnBytesFinal, err := txn.ToBytes(true)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("AppendExtraData: Problem serializing transaction: %v", err))
return
}
// Return the final transaction bytes.
res := AppendExtraDataResponse{
TransactionHex: hex.EncodeToString(txnBytesFinal),
}
if err := json.NewEncoder(ww).Encode(res); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("AppendExtraData: Problem encoding response as JSON: %v", err))
return
}
}
|
go
| 13 | 0.723776 | 112 | 31.396226 | 53 |
inline
|
#def createUnitDict(filename):
# unit_info = dict()
# with open(filename, 'r') as unit_file:
# all_units = unit_file.readlines()
# for unit in all_units:
# unit = unit.split(",")
# unit_info[unit[1].split("\n")[0]] = int(unit[0])
# return unit_info
NUM_PROTOSS_ACTIONS = 70;
def getUnitData(units, unit_info):
unit_list = units.split("]")
# remove the empty character at the end of the list
unit_list = unit_list[: len(unit_list)-1]
unit_types = [0 for i in range(NUM_PROTOSS_ACTIONS)]
units_free = [0 for i in range(NUM_PROTOSS_ACTIONS)]
units_being_built = [0 for i in range(NUM_PROTOSS_ACTIONS)]
units_building = [0 for i in range(NUM_PROTOSS_ACTIONS)]
canChronoBoost = 0
for unit in unit_list:
unit = unit.split("[")[1]
csv_unit = unit.split(",")
unit_id = int(csv_unit[0])
frame_started = int(csv_unit[1])
frame_finished = int(csv_unit[2])
builder_id = int(csv_unit[3])
type_id = int(csv_unit[4])
addon_id = int(csv_unit[5])
buildtype_id = int(csv_unit[6])
build_id = int(csv_unit[7])
job_id = int(csv_unit[8])
time_until_built = int(csv_unit[9])
time_until_free = int(csv_unit[10])
time_chronoboost = int(csv_unit[11])
time_chronoboost_again = int(csv_unit[12])
max_energy = int(csv_unit[13])
energy = float(csv_unit[14])
# do stuff with the data here
unit_types[type_id] += 1
if max(time_until_built, time_until_free) == 0:
units_free[type_id] += 1
if time_until_built > 0:
units_being_built[type_id] += 1
if time_until_built == 0 and time_until_free > 0:
units_building[type_id] += 1
# Nexus can use chronoboost
if type_id == unit_info["Nexus"] and energy >= 50.0:
canChronoBoost = 1
return [unit_types, units_free, units_being_built, units_building], canChronoBoost
"""
output_type: 0 = file
1 = string
"""
def parseLine(line, unit_dict, mins_per_worker_per_sec, gas_per_worker_per_sec,
output_type, parsed_file=None):
units_finish = line.find("]]")
units = line[line.find("[[")+1:units_finish+1]
unit_info, canChronoBoost = getUnitData(units, unit_dict)
line = line[units_finish+3:]
being_built_finish = line.find("]")
being_built = line[line.find("[")+1:being_built_finish]
line = line[being_built_finish+2:]
finished_finish = line.find("]")
finished = line[line.find("[")+1:finished_finish]
line = line[finished_finish+2:]
chronoboosts_finish = line.find("]]")
if chronoboosts_finish != -1:
chronoboosts = line[line.find("[[")+1:chronoboosts_finish+1]
line = line[chronoboosts_finish+3:]
else:
line = line[3:]
single_values = line.split(",")
race = single_values[0]
minerals = single_values[1]
gas = single_values[2]
current_supply = single_values[3]
max_supply = single_values[4]
current_frame = single_values[5]
previous_frame = single_values[6]
frame_limit = single_values[7]
mineral_workers = single_values[8]
gas_workers = single_values[9]
building_workers = single_values[10]
num_refineries = single_values[11]
num_depots = single_values[12]
last_action = single_values[13]
last_ability_finish = line.find("]")
last_ability = line[line.find("[")+1:last_ability_finish]
y_value = line[last_ability_finish+2:]
if output_type == 0:
# unit info
for unit_list in unit_info:
for value in unit_list:
parsed_file.write(str(value) + ",")
parsed_file.write(str(canChronoBoost) + ",")
# state info
parsed_file.write(minerals + ",")
parsed_file.write(gas + ",")
parsed_file.write(current_supply + ",")
parsed_file.write(max_supply + ",")
parsed_file.write(current_frame + ",")
parsed_file.write(mineral_workers + ",")
parsed_file.write(gas_workers + ",")
parsed_file.write(frame_limit + ",")
parsed_file.write(str(mins_per_worker_per_sec) + ",")
if y_value == "":
parsed_file.write(str(gas_per_worker_per_sec))
else:
parsed_file.write(str(gas_per_worker_per_sec) + ",")
# y value
parsed_file.write(y_value)
elif output_type == 1:
output = ""
# unit info
for unit_list in unit_info:
for value in unit_list:
output += (str(value) + ",")
output += (str(canChronoBoost) + ",")
# state info
output += (minerals + ",")
output += (gas + ",")
output += (current_supply + ",")
output += (max_supply + ",")
output += (current_frame + ",")
output += (mineral_workers + ",")
output += (gas_workers + ",")
output += (frame_limit + ",")
output += (str(mins_per_worker_per_sec) + ",")
if y_value == "":
output += (str(gas_per_worker_per_sec))
else:
output += (str(gas_per_worker_per_sec) + ",")
# y value
output += (y_value)
return output
|
python
| 16 | 0.644943 | 83 | 27.153374 | 163 |
starcoderdata
|
def topo_dfs(self, V, v, visited, pathset, ret):
"""
Topological sort
:param V: Vertices HashMap
:param v: currently visiting letter
:param visited: visited letters
:param pathset: marked predecessor in the path
:param ret: the path, ordered topologically
:return: whether contains cycles
"""
if v in pathset:
return False
pathset.add(v)
for nbr in V[v]:
if nbr not in visited:
if not self.topo_dfs(V, nbr, visited, pathset, ret):
return False
pathset.remove(v)
visited.add(v) # add visited is in the end rather than at the begining
ret.append(v) # append after lower values
return True
|
python
| 11 | 0.568678 | 79 | 32.913043 | 23 |
inline
|
from django import forms
class AvatarUpload(forms.Form):
"""Image upload form"""
avatar = forms.ImageField()
def clean_avatar(self):
avatar = self.cleaned_data['avatar']
try:
main, sub = avatar.content_type.split('/')
if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']):
raise forms.ValidationError('Image type is not supported')
if len(avatar) > (300 * 1024):
raise forms.ValidationError('Avatar file size may not exceed 300k')
except:
return None
return avatar
|
python
| 14 | 0.582677 | 83 | 30.75 | 20 |
starcoderdata
|
int extendedEuclidGcd(int a, int b, int& x, int& y) {
if(b == 0) {
x = 1;
y = 0;
return a;
}
int x1, y1;
int d = extendedEuclidGcd(b, a % b, x1, y1);
x = y1;
y = x1 - y1*(a/b);
return d;
}
void diophantineEquationSolution(int a, int b, int c) {
int x, y;
int d = extendedEuclidGcd(a, b, x, y);
if(c % d != 0) {
cout << "The given Equation has no solution" << endl;
return;
} else {
cout << "The given has Infinite solutions" << endl;
}
x *= (c / d);
y *= (c / d);
cout << "General Solution is:" << endl;
cout << "x = " << x << " + " << b / d << "k" << endl;
cout << "y = " << y << " - " << a / d << "k" << endl;
cout << "\t\t" << "k = 0, 1, 2..." << endl;
}
int main() {
diophantineEquationSolution(39, 15, 12);// equation 39x + 15y = 12
return 0;
}
|
c++
| 11 | 0.402834 | 70 | 28.058824 | 34 |
starcoderdata
|
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "{{%parcel}}".
*
* @property integer $id
* @property integer $serialnumber
* @property integer $temporarynumber
* @property string $unifiedserialnumber
* @property string $powei
* @property string $poxiang
* @property string $podu
* @property string $agrotype
* @property string $stonecontent
* @property double $grossarea
* @property double $piecemealarea
* @property double $netarea
* @property string $figurenumber
*/
class Parcel extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%parcel}}';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['farms_id'],'integer'],
[['unifiedserialnumber', 'temporarynumber', 'powei', 'poxiang', 'podu', 'agrotype', 'figurenumber'], 'string', 'max' => 500]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'serialnumber' => '编号',
'temporarynumber' => '地块暂编号',
'unifiedserialnumber' => '地块统编号(地块号)',
'powei' => '坡位',
'poxiang' => '坡向',
'podu' => '坡度',
'agrotype' => '土壤类型',
'stonecontent' => '含石量',
'grossarea' => '毛面积',
'piecemealarea' => '零星地类面积',
'netarea' => '净面积',
'figurenumber' => '图幅号',
'create_at' => '创建日期',
'update_at' => '更新日期',
'farms_id' => '农场',
];
}
public static function getFormatzongdi($zongdi)
{
$grossarea = 0;
$zongdiarr = explode('、',$zongdi);
foreach ($zongdiarr as $zd) {
$area = Lease::getArea($zd);
$grossarea += $area;
}
return $grossarea;
}
public static function getAllGrossarea()
{
$all = 0;
$parcels = Parcel::find()->all();
foreach($parcels as $value) {
$all += $value['grossarea'];
}
return $all;
}
public static function parcelState($array)
{
// var_dump($array);exit;
if($array['state']) {
$arrayZongdi = explode('、', $array['zongdi']);
foreach ($arrayZongdi as $zongdi) {
$parcel = Parcel::find()->where(['unifiedserialnumber'=>Lease::getZongdi($zongdi)])->one();
// var_dump(Lease::getZongdi($zongdi));exit;
$model = Parcel::findOne($parcel['id']);
$model->farms_id = $array['farms_id'];
$model->save();
}
} else {
$parcels = Parcel::find()->where(['farms_id'=>$array['farms_id']])->all();
foreach ($parcels as $parcel) {
$model = Parcel::findOne($parcel['id']);
$model->farms_id = NULL;
$model->save();
}
}
}
public static function in_parcel($value,$array,$planting_id=null)
{
// var_dump($value);exit;
$disabled = false;
$area = Lease::getArea($value);
$zongdi = Lease::getZongdi($value);
foreach ($array as $val) {
$vz = Lease::getZongdi($val);
if($zongdi == $vz) {
$area -= Lease::getArea($val);
if(bccomp($area,0) == 0) {
$disabled = true;
}
if(!empty($planting_id)) {
$p = Plantingstructurecheck::findOne($planting_id);
$temp = Lease::getZongdiToNumber($p->zongdi);
if(in_array($zongdi,explode('、',$temp))) {
$disabled = true;
}
}
}
}
return ['area'=>$area,'disabled'=>$disabled,'value'=>$zongdi.'('.$area.')'];
}
//宗地号一致时,合并面积
public static function zongdi_merge_area($array1,$array2)
{
$result = [];
$zongdiArray = array_merge($array1,$array2);
$format = self::zongdiFormat($zongdiArray);
foreach ($format as $key => $value) {
$result[] = $key.'('.array_sum($value).')';
}
// foreach ($array1 as $a1) {
// $num1 = Lease::getZongdi($a1);
// $area1 = Lease::getArea($a1);
// foreach ($array2 as $k2 => $a2) {
// $num2 = Lease::getZongdi($a2);
// $area2 = Lease::getArea($a2);
// if($num1 == $num2) {
// $area = bcadd($area1,$area2,2);
// $result[] = $num1.'('.$area.')';
// unset($array2[$k2]);
// }
// }
// }
// var_dump($result);
// var_dump($array2);
// $result = array_merge($result,$array2);
return $result;
}
public static function zongdiFormat($array)
{
$result = [];
foreach ($array as $value) {
$result[Lease::getZongdi($value)][] = Lease::getArea($value);
}
return $result;
}
}
|
php
| 21 | 0.533944 | 137 | 24.157303 | 178 |
starcoderdata
|
<?php
namespace App\Http\Livewire\User;
use Livewire\Component;
use Illuminate\Support\Facades\Hash;
use Auth;
class ChangePassword extends Component
{
public $old_password;
public $new_password;
public $account;
public $confirmed_password;
public function mount(){
$this->account = Auth::user();
}
public function change_password(){
$this->validate([
'old_password' => '
'new_password' => '
]);
if (!Hash::check($this->old_password, $this->account->password)) {
session()->flash('error', 'The provided password does not match your current password.');
}else{
$this->account->password =
$this->account->save();
$this->reset(['old_password', '
session()->flash('message', 'Your password has been changed successfully.');
}
}
public function render()
{
return view('livewire.user.change-password');
}
}
|
php
| 15 | 0.583178 | 104 | 24.47619 | 42 |
starcoderdata
|
package com.ajegames.storytime.data;
import com.ajegames.storytime.model.Story;
import java.util.List;
public interface StoryTimePersistence {
/**
* Pulls all stories into memory.
* @return list of Story objects read from persistence
*/
List loadStories();
/**
* Saves to persistent storage.
* @param story Story to store
*/
void saveStory(Story story);
/**
* Deletes a story and all associated parts.
*
* @param storyKey The story to delete
* @return true if story was deleted, otherwise false
*/
boolean deleteStory(String storyKey);
}
|
java
| 4 | 0.677966 | 77 | 23.413793 | 29 |
starcoderdata
|
def translate_cellbarcodes(trio_file, translate_table):
printed = {}
with open(trio_file) as trio_fh:
reader = csv.DictReader(trio_fh, delimiter = "\t")
print("\t".join(reader.fieldnames))
for line in reader:
try:
if line['cellBC'] in translate_table:
line['cellBC'] = min(line['cellBC'], translate_table[line['cellBC']])
trio = "\t".join(line.values())
if trio not in printed: #check for duplicates and if cellbarcode in whitelist
print("\t".join(line.values()))
printed[trio] = 1
except KeyError:
print("Please make sure trios file has the right header.", file = sys.stderr)
sys.exit(1)
|
python
| 20 | 0.53125 | 97 | 49.0625 | 16 |
inline
|
def test_process(self, mock_convert):
"""Test that the process method starts parquet conversion."""
mock_convert.return_value = "", pd.DataFrame()
self.report_processor.process()
mock_convert.assert_called()
mock_convert.reset_mock()
file_list = ["path/to/file_one", "path/to/file_two", "path/to/file_three"]
ocp_processor = ParquetReportProcessor(
schema_name=self.schema,
report_path=f"/my/{self.test_assembly_id}/{self.report_name}",
provider_uuid=self.ocp_provider_uuid,
provider_type=Provider.PROVIDER_OCP,
manifest_id=self.manifest_id,
context={"request_id": self.request_id, "start_date": DateHelper().today, "split_files": file_list},
)
ocp_processor.process()
mock_convert.assert_called()
|
python
| 13 | 0.617647 | 112 | 46.277778 | 18 |
inline
|
def do_playlist_info(self):
""" Shows the next 5 tracks in the track list. """
if self.is_client_mod:
if len(self.media.track_list) > 0:
tracks = self.media.get_track_list()
if tracks is not None:
i = 0
for pos, track in tracks:
if i == 0:
self.send_owner_run_msg('(%s) *Next track: %s* %s' %
(pos, track.title, self.format_time(track.time)))
else:
self.send_owner_run_msg('(%s) *%s* %s' %
(pos, track.title, self.format_time(track.time)))
i += 1
else:
self.send_owner_run_msg('*No tracks in the playlist.*')
|
python
| 22 | 0.390553 | 101 | 50.117647 | 17 |
inline
|
from pik.core.models import PUided, Uided
class MyUided(Uided):
pass
class MyPUided(PUided):
pass
|
python
| 4 | 0.709091 | 41 | 11.222222 | 9 |
starcoderdata
|
#include "GpCharset.hpp"
namespace GPlatform {
GP_ENUM_IMPL(GpCharset);
}//namespace GPlatform
|
c++
| 6 | 0.700855 | 24 | 12.75 | 8 |
starcoderdata
|
'''
Solution for day 11 of the 2018 Advent of Code calendar.
Run it with the command `python -m adventofcode run_solution -y 2018 11` from the project root.
'''
from adventofcode.types import Solution
from adventofcode.util import highlight
from typing import DefaultDict, Tuple, NamedTuple
from collections import defaultdict
class SummedAreaFuelGrid:
'''
Holds a grid where each cell's value is the sum of all power levels of the cells above and
to the left of it, including its own power level.
https://www.codeproject.com/Articles/441226/Haar-feature-Object-Detection-in-Csharp#integral
'''
def __init__(self, serial: int, sidelength: int=300) -> None:
grid = defaultdict(int)
for x in range(sidelength):
for y in range(sidelength):
rack_id = x + 11
power = (((((rack_id * (y + 1)) + serial) * rack_id) // 100) % 10) - 5
grid[(x, y)] = (
power
+ grid[(x - 1, y)]
+ grid[(x, y - 1)]
- grid[(x - 1, y - 1)]
)
self.grid: DefaultDict[Tuple[int, int], int] = grid
self.sidelength: int = sidelength
def region_power(self, x: int, y: int, size: int) -> int:
'''
Get the total power of a square region in the grid. x and y give the coordinates of the
top left corner of the region, size gives the sidelength of the square.
'''
s = size - 1
x0, x1, y0, y1 = x - 1, x + s, y - 1, y + s
return self.grid[(x1, y1)] + self.grid[(x0, y0)] - self.grid[(x1, y0)] - self.grid[(x0, y1)]
def max_region_power(self, size: int=3) -> Tuple[int, int, int]:
'''
Computes the max power region of given size.
'''
cutoff = self.sidelength - size + 1
return max((self.region_power(x, y, size), x, y) for x in range(cutoff) for y in range(cutoff))
def solution_1(fuel_grid: SummedAreaFuelGrid) -> str:
power, x, y = fuel_grid.max_region_power()
print('Max power for regions of size 3:', highlight(power), end='\n\n')
return f'{x + 1},{y + 1}'
def solution_2(fuel_grid: SummedAreaFuelGrid) -> str:
print('Determining region with overall max power... ')
power, x, y, size = max(fuel_grid.max_region_power(size) + (size,) for size in range(1, 301))
print()
print('Max power overall:', highlight(power, color='g'), 'for region of size', highlight(size))
return f'{x + 1},{y + 1},{size}'
def run(data: str) -> Solution:
fuel_grid = SummedAreaFuelGrid(int(data))
return (solution_1(fuel_grid), solution_2(fuel_grid))
|
python
| 24 | 0.6407 | 99 | 39.580645 | 62 |
starcoderdata
|
package com.accenture.spm.io;
import java.io.File;
public class IOPathTest {
public static void main(String[] args) {
String path = "/Users/jinwang/Work/StudyGround/ShangXueTang/T1809-Java_Architect/01_Java_Beginner/01_Java300/08_IO_stream/mysol/c8_proj1/IO.png";
System.out.println(File.separatorChar);
System.out.println(path);
}
}
|
java
| 9 | 0.739011 | 147 | 21.75 | 16 |
starcoderdata
|
from pandas import Series
s = Series([100, 200, 300])
s2 = s.shift(1)
print(s)
print(s2)
s3 = s.shift(-1)
print(s3)
|
python
| 6 | 0.638655 | 27 | 10.9 | 10 |
starcoderdata
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.