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 |
---|---|---|---|---|---|---|---|
exports.rndPostcode = function rndPostcode() {
const postcodeAreas = [
"AB",
"B",
"BA",
"BB",
"BD",
"BH",
"BL",
"BN",
"BR",
"BS",
"BT",
"CA",
"CB",
"CF",
"CH",
"CM",
"CO",
"CR",
"CT",
"CV",
"CW",
"DA",
"DD",
"DE",
"DG",
"DH",
"DL",
"DN",
"DT",
"DY",
"E",
"EC",
"EH",
"EN",
"EX",
"FK",
"FY",
"G",
"GL",
"GU",
"HA",
"HD",
"HG",
"HP",
"HR",
"HS",
"HU",
"HX",
"IG",
"IP",
"IV",
"KA",
"KT",
"KW",
"KY",
"L",
"LA",
"LD",
"LE",
"LL",
"LN",
"LS",
"LU",
"M",
"ME",
"MK",
"ML",
"N",
"NE",
"NG",
"NN",
"NP",
"NR",
"NW",
"OL",
"OX",
"PA",
"PE",
"PH",
"PL",
"PO",
"PR",
"RG",
"RH",
"RM",
"S",
"SA",
"SE",
"SG",
"SK",
"SL",
"SM",
"SN",
"SO",
"SP",
"SR",
"SS",
"ST",
"SW",
"SY",
"TA",
"TD",
"TF",
"TN",
"TQ",
"TR",
"TS",
"TW",
"UB",
"W",
"WA",
"WC",
"WD",
"WF",
"WN",
"WR",
"WS",
"WV",
"YO",
"ZE"
];
let chars = "abcdefghijklmnopqrstuvwxyz".toUpperCase().split("");
const rnd = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
const rndLetter = () => chars[rnd(0, chars.length - 1)];
return postcodeAreas[rnd(0, postcodeAreas.length - 1)] + rnd(1, 9) + rnd(1,9) + " " + rnd(1, 9) + rndLetter() + rndLetter();
}; | javascript | 17 | 0.305538 | 126 | 11.274809 | 131 | starcoderdata |
async def embed_post(
self, ctx, name: StoredEmbedConverter, channel: MessageableChannel = None
):
"""Post a stored embed."""
channel = channel or ctx.channel
await channel.send(embed=discord.Embed.from_dict(name["embed"]))
async with self.config.guild(ctx.guild).embeds() as a:
a[name["name"]]["uses"] += 1 | python | 12 | 0.61708 | 81 | 44.5 | 8 | inline |
bool SIBlock::load(uint8_t const *dataPtr) {
bool result = false;
// Load data into a struct for easier access.
auto ptr = reinterpret_cast<SIBlockData const *>(dataPtr);
type = ptr->type.value();
busType = ptr->bus_type.value();
flags = ptr->flags.value();
result = true;
return result;
} | c++ | 10 | 0.628834 | 62 | 24.153846 | 13 | inline |
#include
#include
#include
#include
#include
using namespace System;
using namespace System::Collections::Generic;
namespace {
TEST(DictionaryTest, Constructor) {
Dictionary<string, string> dictionary;
ASSERT_EQ(0, dictionary.Count);
}
TEST(DictionaryTest, AddKeyValRef) {
Dictionary<Int32, string> dictionary;
dictionary.Add(Int32(1), "Test1");
dictionary.Add(Int32(2), "Test2");
dictionary.Add(Int32(3), "Test3");
dictionary.Add(Int32(4), "Test4");
ASSERT_TRUE(dictionary.ContainsKey(Int32(1)));
ASSERT_TRUE(dictionary.ContainsValue(string("Test4")));
ASSERT_EQ(dictionary[Int32(4)], "Test4");
}
TEST(DictionaryTest, AddSpPairRef) {
Dictionary<Int32, string> dictionary;
$<KeyValuePair<Int32, string>> pair(new KeyValuePair<Int32, string>(Int32(42), "Hello"));
dictionary.Add(*pair);
ASSERT_TRUE(dictionary.ContainsKey(Int32(42)));
ASSERT_TRUE(dictionary.ContainsValue(string("Hello")));
ASSERT_EQ(dictionary[Int32(42)], string("Hello"));
}
TEST(DictionaryTest, AddPairPtr) {
Dictionary<Int32, string> dictionary;
dictionary.Add(KeyValuePair<Int32, string>(Int32(42), "Hello"));
ASSERT_TRUE(dictionary.ContainsKey(Int32(42)));
ASSERT_TRUE(dictionary.ContainsValue(string("Hello")));
ASSERT_EQ(dictionary[Int32(42)], "Hello");
}
TEST(DictionaryTest, IntPtr) {
Dictionary<IntPtr, IntPtr> dictionary;
dictionary.Add(IntPtr(Int32(1)), IntPtr(Int32(2)));
dictionary.Add(IntPtr(Int32(2)), IntPtr(Int32(3)));
IntPtr res = dictionary[IntPtr(Int32(2))];
ASSERT_EQ(res, IntPtr(Int32(3)));
}
TEST(DictionaryTest, Enumerator) {
Dictionary<int32, string> ints;
ints[5] = "five";
ints[1] = "one";
ints[2] = "two";
bool seen[6] = { false, false, false, false, false, false };
Dictionary<int32, string>::Enumerator e(ints);
while (e.MoveNext()) {
KeyValuePair<int32, string> pair = e.Current;
int32 key = pair.Key();
ASSERT_GE(key, 0);
ASSERT_LT(key, 6);
ASSERT_FALSE(seen[key]);
seen[key] = true;
if (key == 1) ASSERT_EQ("one", pair.Value());
if (key == 2) ASSERT_EQ("two", pair.Value());
if (key == 5) ASSERT_EQ("five", pair.Value());
}
ASSERT_FALSE(seen[0]);
ASSERT_FALSE(seen[3]);
ASSERT_FALSE(seen[4]);
}
TEST(DictionaryTest, Enumerator_Empty) {
Dictionary<int32, string> ints;
Dictionary<int32, string>::Enumerator e(ints);
while (e.MoveNext())
ASSERT_FALSE(true);
}
} | c++ | 13 | 0.664128 | 93 | 31.05814 | 86 | starcoderdata |
package net.minecraft.network.protocol.game;
import javax.annotation.Nullable;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.Packet;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.sounds.SoundSource;
public class ClientboundStopSoundPacket implements Packet {
private static final int HAS_SOURCE = 1;
private static final int HAS_SOUND = 2;
@Nullable
private final ResourceLocation name;
@Nullable
private final SoundSource source;
public ClientboundStopSoundPacket(@Nullable ResourceLocation pName, @Nullable SoundSource pSource) {
this.name = pName;
this.source = pSource;
}
public ClientboundStopSoundPacket(FriendlyByteBuf pBuffer) {
int i = pBuffer.readByte();
if ((i & 1) > 0) {
this.source = pBuffer.readEnum(SoundSource.class);
} else {
this.source = null;
}
if ((i & 2) > 0) {
this.name = pBuffer.readResourceLocation();
} else {
this.name = null;
}
}
/**
* Writes the raw packet data to the data stream.
*/
public void write(FriendlyByteBuf pBuffer) {
if (this.source != null) {
if (this.name != null) {
pBuffer.writeByte(3);
pBuffer.writeEnum(this.source);
pBuffer.writeResourceLocation(this.name);
} else {
pBuffer.writeByte(1);
pBuffer.writeEnum(this.source);
}
} else if (this.name != null) {
pBuffer.writeByte(2);
pBuffer.writeResourceLocation(this.name);
} else {
pBuffer.writeByte(0);
}
}
@Nullable
public ResourceLocation getName() {
return this.name;
}
@Nullable
public SoundSource getSource() {
return this.source;
}
/**
* Passes this Packet on to the NetHandler for processing.
*/
public void handle(ClientGamePacketListener pHandler) {
pHandler.handleStopSoundEvent(this);
}
} | java | 13 | 0.641304 | 103 | 25.644737 | 76 | starcoderdata |
package com.thiyagu_7.adventofcode.year2021.day18;
import java.util.List;
public class SolutionDay18 {
public long part1(List input) {
String result = input.get(0);
SnailfishNumber snailfishNumber = null;
for (int i = 1; i < input.size(); i++) {
String number = join(result, input.get(i));
snailfishNumber = new SnailfishNumber(number);
snailfishNumber.reduce();
result = snailfishNumber.getSnailfishNumber();
}
// last number is the final - get magnitude of that.
assert snailfishNumber != null;
return snailfishNumber.findMagnitude();
}
private String join(String number1, String number2) {
return "[" + number1 + "," + number2 + "]";
}
public long part2(List input) {
long max = 0;
for (int i = 0; i < input.size() - 1; i++) {
for (int j = 1 + 1; j < input.size(); j++) {
SnailfishNumber snailfishNumber1 = new SnailfishNumber(join(input.get(i), input.get(j)));
SnailfishNumber snailfishNumber2 = new SnailfishNumber(join(input.get(j), input.get(i)));
snailfishNumber1.reduce();
snailfishNumber2.reduce();
max = Math.max(max, Math.max(snailfishNumber1.findMagnitude(), snailfishNumber2.findMagnitude()));
}
}
return max;
}
} | java | 17 | 0.584096 | 114 | 36.394737 | 38 | starcoderdata |
"""Check constraints for season/episodes identified by individual item IDs"""
import click
from pywikibot import Site, ItemPage
from bots import getbot
from click_utils import validate_item_id
@click.command()
@click.argument('item_ids', nargs=-1)
@click.option('--autofix', is_flag=True, default=False)
@click.option("--accumulate", is_flag=True, default=False, help="Accumulate all fixes before applying them")
@click.option("--filter", default="", help="Comma separated property names/tags to filter")
def validate_constraints(item_ids=[], autofix=False, accumulate=False, filter=""):
item_ids = (validate_item_id(None, None, item_id) for item_id in item_ids)
itempages = (ItemPage(Site(), item_id) for item_id in item_ids)
bot = getbot(itempages, autofix=autofix, accumulate=accumulate, always=False, property_filter=filter)
bot.run()
if __name__ == "__main__":
validate_constraints() | python | 11 | 0.726293 | 108 | 41.181818 | 22 | starcoderdata |
package advance.datastructureandalgorithm;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class CollectionTest1 {
public static void main(String[] args) {
List list = new ArrayList<>();
Set set = new LinkedHashSet<>();
Map<Integer, String> map = new HashMap<>();
String[] stringArray = new String[]{"a","b","c","d","e","a","f","a","g"};
list.addAll(Arrays.asList(stringArray));
set.addAll(Arrays.asList(stringArray));
for(int i = 0; i < stringArray.length; i++) {
map.put(i, stringArray[i]);
}
System.out.println("list.length = " + list.size());
System.out.println("set.length = " + set.size());
System.out.println("datastructure.map.length = " + map.size());
System.out.println("datastructure.map.keyset.length = " + map.keySet().size());
//遍历map,输出每个key的值、hash值
Set set1 = map.keySet();
for (Iterator iterator = set1.iterator(); iterator.hasNext();) {
Integer integer = (Integer) iterator.next();
System.out.println("key : " + integer + " hash key : " + integer.hashCode() );
}
}
} | java | 12 | 0.669249 | 81 | 28.340909 | 44 | starcoderdata |
import pytest
import requests
from caseworker.cases.forms import review_goods
from caseworker.core.services import get_control_list_entries
from core.middleware import RequestsSessionMiddleware
@pytest.fixture
def control_list_entries(mock_control_list_entries, rf, client):
request = rf.get("/")
request.session = client.session
request.requests_session = requests.Session()
data = get_control_list_entries(request, convert_to_options=True)
return [(item.value, item.key) for item in data]
def test_export_control_characteristics_form_no_clc(control_list_entries):
form = review_goods.ExportControlCharacteristicsForm(
control_list_entries_choices=control_list_entries,
data={"control_list_entries": [], "report_summary": "Foo bar",},
)
assert form.is_valid() is False
assert form.errors["does_not_have_control_list_entries"] == [form.MESSAGE_NO_CLC_REQUIRED]
def test_export_control_characteristics_form_mutex(control_list_entries):
form = review_goods.ExportControlCharacteristicsForm(
control_list_entries_choices=control_list_entries,
data={
"control_list_entries": ["ML1"],
"does_not_have_control_list_entries": True,
"report_summary": "Foo bar",
},
)
assert form.is_valid() is False
assert form.errors["does_not_have_control_list_entries"] == [form.MESSAGE_NO_CLC_MUTEX]
@pytest.mark.parametrize(
"data",
[
{"control_list_entries": ["ML1"], "report_summary": "Foo bar",},
{"control_list_entries": ["ML1"], "report_summary": "Foo bar", "is_precedent": True},
{"control_list_entries": ["ML1"], "report_summary": "Foo bar", "is_precedent": False},
],
)
def test_export_control_characteristics_form_ok(control_list_entries, data):
form = review_goods.ExportControlCharacteristicsForm(control_list_entries_choices=control_list_entries, data=data,)
assert form.is_valid() is True | python | 12 | 0.6965 | 119 | 38.215686 | 51 | starcoderdata |
<?php
namespace App\Routing;
class Route{
protected $currentRequestUri;
protected $currentRequestMethod;
protected static $routes = [];
public function __construct()
{
$dirname = dirname($_SERVER['SCRIPT_NAME']);
$basename = basename($_SERVER['SCRIPT_NAME']);
$this->currentRequestUri = str_replace([$dirname, $basename], '', $_SERVER['REQUEST_URI']);
$this->currentRequestMethod = $_SERVER['REQUEST_METHOD'];
$this->route();
}
public static function get($path, $module, $middlewares = []){
self::$routes[] = ['GET', $path, $module, $middlewares];
}
public static function post($path, $module, $middlewares = []){
self::$routes[] = ['POST', $path, $module, $middlewares];
}
private function route(){
foreach(self::$routes as $route){
list($requestMethod, $path, $module, $middlewares) = $route;
$path = str_replace(array_keys(URL_PATTERNS), array_values(URL_PATTERNS), $path);
$pattern = '@^' . $path . '\/?$@';
$requestMethodCheck = $requestMethod == $this->currentRequestMethod;
$pathCheck = preg_match($pattern, $this->currentRequestUri, $params);
if($requestMethodCheck && $pathCheck){
array_shift($params);
if(!empty($middlewares)){
foreach($middlewares as $middleware){
$middlewareClass = 'App\\Middlewares\\' . $middleware;
$middlewareClass = new $middlewareClass;
call_user_func_array([$middlewareClass, 'handle'], [$this->currentRequestMethod]);
}
}
if(is_callable($module)){
return call_user_func_array($module, $params);
}
$module = explode('@', $module);
list($controller, $controllerMethod) = $module;
$controllerFile = CONTROLLER_BASE . $controller . 'Controller.php';
if(file_exists($controllerFile)){
require $controllerFile;
$class = explode('/', $controller);
$class = 'App\\Controllers\\' . end($class) . 'Controller';
$class = new $class;
return call_user_func_array([$class, $controllerMethod], $params);
}
else{
trigger_error(' . $controllerFile . ') Dosya Bulunamadı...! ', E_USER_ERROR);
exit();
}
}
}
echo 'Sayfa Bulunamadı';
}
}
?> | php | 21 | 0.45744 | 110 | 36.78481 | 79 | starcoderdata |
# pylint: disable=line-too-long
from django.contrib import admin
from .models import QuestionSet, ScheduledItem
@admin.register(QuestionSet)
class QuestionSetAdmin(admin.ModelAdmin):
list_display = ('identifier', 'name',)
search_fields = ('identifier', 'name',)
@admin.register(ScheduledItem)
class ScheduledItemAdmin(admin.ModelAdmin):
list_display = ('respondent', 'date', 'start_time', 'end_time',)
search_fields = ('respondent',)
list_filter = ('date', 'start_time', 'end_time', 'questions', 'respondent',) | python | 8 | 0.711191 | 80 | 31.588235 | 17 | starcoderdata |
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.DurableTask;
using Functionless.Durability;
namespace Functionless.Example
{
public class ReportFunction
{
private readonly ReportJob reportJob;
public ReportFunction(ReportJob reportJob)
{
this.reportJob = reportJob;
}
[FunctionName("reportjob-execute")]
public async Task Execute(
[HttpTrigger] HttpRequest request,
[DurableClient] IDurableOrchestrationClient client)
{
await client.DurablyInvokeAsync(
async () => await this.reportJob.ExecuteAsync()
);
}
}
} | c# | 18 | 0.66127 | 63 | 24.903226 | 31 | starcoderdata |
def test_generate_data_with_PUT(
default_http_arguments_as_json,
default_http_arguments_as_string,
):
"""Assign arguments to body of request in PUT."""
data, params = generate_data('PUT', default_http_arguments_as_json)
assert not params
assert data == default_http_arguments_as_string | python | 8 | 0.708738 | 71 | 37.75 | 8 | inline |
package de.uni_koeln.info.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tartarus.snowball.Stemmer;
public final class Tokenizer {
//Logger logger = LoggerFactory.getLogger(getClass());
private String delimiter;
private boolean normalize;
private List stopWords;
private boolean removeStopWords;
private Stemmer stemmer;
public Tokenizer(Delimiter delimiter, boolean normalize, boolean removeStopWords) {
this.delimiter = delimiter.getValue();
this.normalize = normalize;
this.stopWords = ReaderUtil.getStopWords();
this.removeStopWords = removeStopWords;
this.stemmer = new Stemmer();
}
// TERMS
public List getTerms(final String input) {
SortedSet result = new TreeSet
add(input, result);
if(normalize) {
result = (SortedSet normalize(result);
}
return new ArrayList
}
// TOKENS
public List getTokens(final String input) {
List result = new ArrayList
add(input, result);
// logger.info("original :: " + result.size());
StringBuilder sbOut = new StringBuilder();
result.forEach(s -> sbOut.append(s).append(", "));
// logger.info(sbOut.toString());
if(normalize) {
result = (List normalize(result);
// logger.info("normalized :: " + result.size());
StringBuilder sb = new StringBuilder();
result.forEach(s -> sb.append(s).append(", "));
// logger.info(sb.toString());
}
if(removeStopWords) {
result = SetOperations.complement(result, stopWords);
// logger.info("stopwords removed :: " + result.size());
StringBuilder sb = new StringBuilder();
result.forEach(s -> sb.append(s).append(", "));
// logger.info(sb.toString());
}
// logger.info("---------");
return result;
}
private Collection normalize(Collection result) {
try {
result = stemmer.stem(result, Stemmer.GERMAN);
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException e) {
e.printStackTrace();
}
return result;
}
private void add(final String input, Collection result) {
List list = Arrays.asList(input.toLowerCase().split(delimiter));
for (String s : list) {
if (s.trim().length() > 0) {
result.add(s.trim());
}
}
}
} | java | 14 | 0.671479 | 84 | 26.808989 | 89 | starcoderdata |
function processWeather(data) {
if (!data || !data.main || typeof data.main.temp === "undefined") {
// Did not receive usable new data.
// Maybe this needs a better check?
return;
}
var temperature = roundValue(data.main.temp);
var weatherType = getIcon(data.weather[0].icon);
var description = data.weather[0]["description"];
var wrapper = document.createElement("div");
var large = document.createElement("div");
large.className = "large light";
var weatherIcon = document.createElement("span");
weatherIcon.className = "wi weathericon " + weatherType;
large.appendChild(weatherIcon);
var temperatureD = document.createElement("span");
temperatureD.className = "bright";
temperatureD.innerHTML = " " + temperature + "°C";
large.appendChild(temperatureD);
wrapper.appendChild(large);
var descriptionD = document.createElement("div");
descriptionD.className = "description";
descriptionD.innerHTML = description;
wrapper.appendChild(descriptionD);
return wrapper;
} | javascript | 10 | 0.676796 | 71 | 30.057143 | 35 | inline |
private JavaResponseInterface internalProcessCall(JavaRequestInterface proxy_request_object, HttpServletResponse response) throws IOException {
try {
////////////////////////////////////////////////////////////////////////////////
// Perform as much as possible of the "heavy" stuff outside of synchronization
////////////////////////////////////////////////////////////////////////////////
if (server_configuration == null) {
returnInternalFailure(response, "Service " + service_name + " not started yet!");
return null;
}
////////////////////////////////////////////////////////////////////
// Insert request into queues etc.
////////////////////////////////////////////////////////////////////
Caller ci = processRequest(response, proxy_request_object);
///////////////////////////////////////////////////
// Now process the action of the request part
///////////////////////////////////////////////////
if (ci.transactRequest()) {
////////////////////////////////////////////////////////
// Success! Now process the action of the response part
////////////////////////////////////////////////////////
ci.transactResponse();
}
return ci instanceof ProxyRequest ? ((ProxyRequest) ci).request_descriptor.java_response : ((RequestDescriptor) ci).java_response;
} catch (ServletException e) {
throw new IOException(e);
}
} | java | 13 | 0.380256 | 143 | 51.967742 | 31 | inline |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/controls/throbber.h"
#include "base/bind.h"
#include "base/location.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/animation/tween.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/paint_throbber.h"
#include "ui/gfx/paint_vector_icon.h"
#include "ui/gfx/vector_icons_public.h"
#include "ui/native_theme/common_theme.h"
#include "ui/native_theme/native_theme.h"
#include "ui/resources/grit/ui_resources.h"
#include "ui/views/resources/grit/views_resources.h"
namespace views {
// The default diameter of a Throbber. If you change this, also change
// kCheckmarkDipSize.
static const int kDefaultDiameter = 16;
// The size of the checkmark, in DIP. This magic number matches the default
// diamater plus padding inherent in the checkmark SVG.
static const int kCheckmarkDipSize = 18;
Throbber::Throbber() : checked_(false) {
}
Throbber::~Throbber() {
Stop();
}
void Throbber::Start() {
if (IsRunning())
return;
start_time_ = base::TimeTicks::Now();
const int kFrameTimeMs = 30;
timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(kFrameTimeMs),
base::Bind(&Throbber::SchedulePaint, base::Unretained(this)));
SchedulePaint(); // paint right away
}
void Throbber::Stop() {
if (!IsRunning())
return;
timer_.Stop();
SchedulePaint();
}
void Throbber::SetChecked(bool checked) {
if (checked == checked_)
return;
checked_ = checked;
SchedulePaint();
}
gfx::Size Throbber::GetPreferredSize() const {
return gfx::Size(kDefaultDiameter, kDefaultDiameter);
}
void Throbber::OnPaint(gfx::Canvas* canvas) {
SkColor color = GetNativeTheme()->GetSystemColor(
ui::NativeTheme::kColorId_ThrobberSpinningColor);
if (!IsRunning()) {
if (checked_) {
canvas->Translate(gfx::Vector2d((width() - kCheckmarkDipSize) / 2,
(height() - kCheckmarkDipSize) / 2));
gfx::PaintVectorIcon(canvas, gfx::VectorIconId::CHECK_CIRCLE,
kCheckmarkDipSize, color);
}
return;
}
base::TimeDelta elapsed_time = base::TimeTicks::Now() - start_time_;
gfx::PaintThrobberSpinning(canvas, GetContentsBounds(), color, elapsed_time);
}
bool Throbber::IsRunning() const {
return timer_.IsRunning();
}
// Smoothed throbber ---------------------------------------------------------
// Delay after work starts before starting throbber, in milliseconds.
static const int kStartDelay = 200;
// Delay after work stops before stopping, in milliseconds.
static const int kStopDelay = 50;
SmoothedThrobber::SmoothedThrobber()
: start_delay_ms_(kStartDelay), stop_delay_ms_(kStopDelay) {
}
SmoothedThrobber::~SmoothedThrobber() {}
void SmoothedThrobber::Start() {
stop_timer_.Stop();
if (!IsRunning() && !start_timer_.IsRunning()) {
start_timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(start_delay_ms_), this,
&SmoothedThrobber::StartDelayOver);
}
}
void SmoothedThrobber::StartDelayOver() {
Throbber::Start();
}
void SmoothedThrobber::Stop() {
if (!IsRunning())
start_timer_.Stop();
stop_timer_.Stop();
stop_timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(stop_delay_ms_), this,
&SmoothedThrobber::StopDelayOver);
}
void SmoothedThrobber::StopDelayOver() {
Throbber::Stop();
}
} // namespace views | c++ | 19 | 0.670482 | 80 | 26.380597 | 134 | starcoderdata |
def get_sampler(sampler_name, rbfsampler_gamma, nystroem_gamma):
'''
Parameters
----------
sampler_name : str
One of ['identity', 'rbf', 'nystroem']
Returns
-------
Transformer
Something on which you can call fit and transform
'''
if sampler_name == 'identity':
s = FunctionTransformer(None, validate=False)
elif sampler_name == 'nystroem':
s = Nystroem(gamma=nystroem_gamma)
elif sampler_name == 'rbf':
s = RBFSampler(gamma=rbfsampler_gamma)
else:
raise ValueError('This sampler ({}) is not supported'.format(sampler_name))
# raise ValueError(f'This sampler ({sampler_name}) is not supported')
return s | python | 12 | 0.61236 | 83 | 31.409091 | 22 | inline |
def add_upstream_ids(table_a, id_a, table_b, id_b, upstream_ids_col):
"""note downstream ids
"""
db = pgdata.connect()
schema_a, table_a = db.parse_table_name(table_a)
schema_b, table_b = db.parse_table_name(table_b)
# ensure that any existing values get removed
db.execute(f"ALTER TABLE {schema_a}.{table_a} DROP COLUMN IF EXISTS {upstream_ids_col}")
temp_table = table_a + "_tmp"
db[f"{schema_a}.{temp_table}"].drop()
db.execute(f"CREATE TABLE {schema_a}.{temp_table} (LIKE {schema_a}.{table_a})")
db.execute(f"ALTER TABLE {schema_a}.{temp_table} ADD COLUMN {upstream_ids_col} integer[]")
groups = sorted([g[0] for g in db.query(f"SELECT DISTINCT watershed_group_code from {schema_a}.{table_a}")])
query = sql.SQL(db.queries["02_add_upstream_ids"]).format(
schema_a=sql.Identifier(schema_a),
schema_b=sql.Identifier(schema_b),
temp_table=sql.Identifier(temp_table),
table_a=sql.Identifier(table_a),
table_b=sql.Identifier(table_b),
id_a=sql.Identifier(id_a),
id_b=sql.Identifier(id_b),
upstr_ids_col=sql.Identifier(upstream_ids_col)
)
# run each group in parallel
func = partial(execute_parallel, query)
n_processes = multiprocessing.cpu_count() - 1
pool = multiprocessing.Pool(processes=n_processes)
pool.map(func, groups)
pool.close()
pool.join()
# drop source table, rename new table, re-create indexes
db[f"{schema_a}.{table_a}"].drop()
db.execute(f"ALTER TABLE {schema_a}.{temp_table} RENAME TO {table_a}")
create_indexes(f"{schema_a}.{table_a}")
db.execute(f"ALTER TABLE {schema_a}.{table_a} ADD PRIMARY KEY ({id_a})") | python | 13 | 0.64758 | 112 | 47.428571 | 35 | inline |
#ifndef ROXLU_AMF0_NUMBER_H
#define ROXLU_AMF0_NUMBER_H
#include
class BitStream;
struct AMF0Number : public AMFType {
AMF0Number(BitStream& bs);
void print();
void read();
void write();
double value;
};
#endif | c | 10 | 0.750693 | 104 | 20.235294 | 17 | starcoderdata |
def purge_server(self, master_token: str, output: bool = True,
retries: int = RETRIES) -> Response:
"""
Remove all jobs, items and optionally delete all output files from
the server.
:param master_token: master authentication token for the server
:param output: deletes output file if true
:param retries: number of retries for this request
:return: the server response
"""
session = requests_retry_session(retries=retries)
params = {'token': master_token, 'output': output}
url = self.make_param_url('purge', params)
return session.get(url=url) | python | 8 | 0.622926 | 74 | 43.266667 | 15 | inline |
package log
import (
"flag"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type Config struct {
Level string
Format string
}
func (conf *Config) RegisterFlags(f *flag.FlagSet) {
f.StringVar(&conf.Level, "log.level", "error", "log level")
f.StringVar(&conf.Format, "log.format", "console", "(TODO) log formatter")
}
func (conf *Config) Build() (*Logger, error) {
encConf := zapcore.EncoderConfig{
TimeKey: "ts",
LevelKey: "level",
NameKey: "logger",
CallerKey: "caller",
MessageKey: "msg",
StacktraceKey: "stacktrace",
EncodeLevel: zapcore.LowercaseLevelEncoder,
EncodeTime: zapcore.ISO8601TimeEncoder,
EncodeDuration: zapcore.StringDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
}
configLevel, err := zap.ParseAtomicLevel(conf.Level)
if err != nil {
return nil, err
}
zapConf := zap.Config{
Level: configLevel,
Development: true,
DisableStacktrace: true,
Encoding: conf.Format,
EncoderConfig: encConf,
OutputPaths: []string{"stderr"},
ErrorOutputPaths: []string{"stderr"},
}
// add caller skip 1 to prevent zap from reporting logger as the source of the log line (caller)
baseLogger, err := zapConf.Build(zap.AddCallerSkip(1))
if err != nil {
return nil, err
}
zap.RedirectStdLog(baseLogger)
return New(baseLogger), nil
} | go | 13 | 0.668826 | 97 | 23.368421 | 57 | starcoderdata |
def line2ktuple(line):
parts=line.strip().split('&')
cmd=(parts[0].lstrip())[1:] #strip off leading quote
kwd=etc.getparms(parts[1:])
#do the substitutions
try:
obsmode=kwd['instrument']
except KeyError:
obsmode=kwd.get('obsmode','None')
#fix the CDBS specification
try:
kwd['spectrum']=kwd['spectrum'].replace('/cdbs',os.environ['PYSYN_CDBS'])
kwd['spectrum']=kwd['spectrum'].replace('/usr/stsci/stdata',
os.environ['PYSYN_CDBS'])
except KeyError:
kwd['spectrum']=None
#Construct the name and pattern
ktuple=(cmd,obsmode,kwd['spectrum'])
return ktuple | python | 11 | 0.561111 | 81 | 30.347826 | 23 | inline |
from configparser import ConfigParser
from types import FunctionType
from functools import wraps
import os
import logging
import argparse
def params_str(*args, **kwargs):
args_str = ', '.join(str(arg) for arg in args)
if kwargs:
kwargs_str = ', '.join(f"{key}={val}" for key, val in kwargs.items())
args_str += f", {kwargs_str}"
return args_str
def func_logger(func, cls=None):
@wraps(func)
def wrapper(*args, **kwargs):
params = params_str(*args, **kwargs)
cls_name = f"{cls.__name__}." if cls else ''
try:
result = func(*args, **kwargs)
logging.debug(f"{cls_name}{func.__name__}"
f"({params}) -> {result}")
except Exception as e:
logging.error(e)
raise e
return result
return wrapper
def cls_logger(func):
def wrapper(cls):
methods = [y for x, y in cls.__dict__.items() if not x.startswith('__')
and type(y) == FunctionType]
for method in methods:
setattr(cls, method.__name__,
func(method, cls))
return cls
return wrapper
def parse_args(argument_parser):
argument_parser.add_argument('-c', '--config', help='Specifying a configuration file', action='store',
metavar='FILE', dest='configuration_file', type=str)
argument_parser.add_argument('-d', '--dir', action='store',
help='Specifies a subdirectory of the current directory where the pos.json and '
'alive.csv files are to be saved', metavar='DIR', dest='directory', type=str)
argument_parser.add_argument('-l', '--log', help='Specifies the level of events to be logged.',
metavar='LEVEL', dest='log_level', type=str,
choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'])
argument_parser.add_argument('-r', '--rounds', action='store', help='Specifies the number of turns.', metavar='NUM',
type=int, dest='rounds_number')
argument_parser.add_argument('-s', '--sheep', action='store',
help='Specifies the number of sheep.', metavar='NUM', type=int,
dest='sheep_number')
argument_parser.add_argument('-w', '--wait', action='store',
help='Specifies that after displaying basic information about the simulation state '
'at the end of each round, the rest of the simulation should be stopped until '
'the user presses a key.',
dest='wait', type=bool)
arguments = argument_parser.parse_args()
parameters = {
'round_number': 50,
'sheep_number': 15,
'init_pos_limit': 10.0,
'wolf_move_dist': 1,
'sheep_move_dist': 0.5,
'wait': False,
'directory': '',
'log': None
}
if arguments.configuration_file:
parameters['init_pos_limit'], parameters['sheep_move_dist'], parameters['wolf_move_dist'] = config_parsing(
arguments.configuration_file)
if arguments.directory:
parameters['directory'] = arguments.directory
if not os.path.exists(arguments.directory):
os.makedirs(arguments.directory)
if arguments.log_level:
logs_path = os.path.join(parameters['directory'], 'chase.log')
logging.basicConfig(filename=logs_path,
filemode='w', datefmt='%H:%M:%S', level=arguments.log_level,
format='%(asctime)s,%(msecs)d :: %(levelname)-8s '
':: %(message)s')
if arguments.rounds_number:
parameters['round_number'] = arguments.rounds_number if arguments.rounds_number > 0 else 50
if arguments.sheep_number:
parameters['sheep_number'] = arguments.sheep_number if arguments.sheep_number > 0 else 15
if arguments.wait:
parameters['wait'] = arguments.wait
return parameters
@func_logger
def config_parsing(filename):
config_parser = ConfigParser()
config_parser.read(filename)
terrain = config_parser['Terrain']
init_pos_limit = terrain.getfloat('InitPosLimit')
if init_pos_limit != 0:
if init_pos_limit < 0:
init_pos_limit = abs(init_pos_limit)
logging.warning(
f"{config_parsing.__name__} -> The absolute value was taken from the value you entered (InitPosLimit).")
else:
msg = "Number must be not zero"
logging.error(f"{config_parsing.__name__} -> {msg}")
raise ValueError(msg)
movement = config_parser['Movement']
sheep_move_dist = movement.getfloat('SheepMoveDist')
wolf_move_dist = movement.getfloat('WolfMoveDist')
try:
sheep_move_dist = check_positive_float(sheep_move_dist)
wolf_move_dist = check_positive_float(wolf_move_dist)
except argparse.ArgumentTypeError as e:
logging.error(f"{config_parsing.__name__} -> {e} ")
raise e
return init_pos_limit, sheep_move_dist, wolf_move_dist
@func_logger
def check_positive_int(argument):
try:
number = int(argument)
except ValueError as e:
logging.error(f"{check_positive_int.__name__} -> {e}")
raise e
if number <= 0:
msg = "Number(argument) must be positive value"
logging.error(f"{check_positive_int.__name__} -> {msg}")
raise argparse.ArgumentTypeError(msg)
return number
@func_logger
def check_positive_float(argument):
try:
number = float(argument)
except ValueError as e:
logging.error(f"{check_positive_int.__name__} -> {e}")
raise e
if number <= 0:
msg = "Number(argument) must be positive value"
logging.error(f"{check_positive_int.__name__} -> {msg}")
raise argparse.ArgumentTypeError(msg)
return number
@func_logger
def check_bool(argument):
if argument != 'True' and argument != 'False':
msg = "Argument must be bool value(True or False)."
logging.error(f"{check_positive_int.__name__} -> {msg}")
raise argparse.ArgumentTypeError(msg)
else:
return bool(argument) | python | 15 | 0.57748 | 120 | 38.197531 | 162 | starcoderdata |
<?php
/**
* This file is part of the Liquid package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @package Liquid
*/
namespace Liquid\Cache;
use Liquid\Cache;
use Liquid\LiquidException;
/**
* Implements cache stored in Apc.
*/
class Apc extends Cache
{
/**
* Constructor.
*
* It checks the availability of apccache.
*
* @param array $options
*
* @throws LiquidException if APC cache extension is not loaded or is disabled.
*/
public function __construct(array $options = array()) {
parent::__construct($options);
if (!extension_loaded('apc'))
throw new LiquidException('LiquidCacheApc requires PHP apc extension to be loaded.');
}
/**
* {@inheritdoc}
*/
public function read($key, $unserialize = true) {
return apc_fetch($this->prefix . $key);
}
/**
* {@inheritdoc}
*/
public function exists($key) {
apc_fetch($this->prefix . $key, $success);
return $success;
}
/**
* {@inheritdoc}
*/
public function write($key, $value, $serialize = true) {
return apc_store($this->prefix . $key, $value, $this->expire);
}
/**
* {@inheritdoc}
*/
public function flush($expiredOnly = false) {
return apc_clear_cache('user');
}
} | php | 12 | 0.651835 | 88 | 18.409091 | 66 | starcoderdata |
<?php
namespace carlescliment\QueryBuilder;
class QueryBuilder
{
protected $em;
protected $selectClause;
protected $fromClause;
protected $joins = array();
protected $wheres = array();
protected $havings = array();
protected $orders = array();
protected $limit;
protected $offset;
protected $count;
protected $model_filters = array();
public function __construct(Database $em)
{
$this->em = $em;
}
public function select($select_clause)
{
$this->selectClause = new SelectClause($select_clause);
return $this;
}
public function from($entity, $alias)
{
$this->fromClause = new FromClause($entity, $alias);
return $this;
}
public function join($entity, $alias, $on, $join_type = 'JOIN')
{
$sTableHash = $this->getTableAliasHash( $entity, $alias );
if ( isset( $this->joins[ $sTableHash ] ) ) {
$this->joins[$sTableHash]->addCondition( $on );
}
else {
$this->joins[$sTableHash] = new JoinClause($entity, $alias, $on, $join_type);
}
return $this;
}
protected function getTableAliasHash( $sTable, $sAlias ) {
return md5( $sTable . '#' . $sAlias );
}
public function leftJoin($entity, $alias, $on)
{
return $this->join($entity, $alias, $on, 'LEFT JOIN');
}
public function whereAny( array $aParameters ) {
$this->wheres[] = WhereClauseFactory::build( $aParameters );
return $this;
}
public function where($entity, $value)
{
$this->wheres[] = WhereClauseFactory::build($entity, $value);
return $this;
}
public function having($entity, $value)
{
$this->havings[] = WhereClauseFactory::build($entity, $value);
return $this;
}
/**
* @return string
*/
public function peek() {
$oQuery = $this->em->createQuery( $this->buildQueryString() );
$this->setQueryParameters( $oQuery );
return $oQuery->getQuery();
}
/** Alias for where */
public function andWhere($entity, $value)
{
return $this->where($entity, $value);
}
public function orderBy($field, $order = 'ASC')
{
$this->orders[md5($field)] = new OrderByClause($field, $order);
return $this;
}
public function clearOrderBy() {
$this->orders = array();
return $this;
}
public function limit($limit)
{
$this->limit = $limit;
return $this;
}
public function offset($offset)
{
$this->offset = $offset;
return $this;
}
public function count( $count_field )
{
$this->selectClause->count( $count_field );
return $this;
}
public function executeIgnoreLimit()
{
return $this->execute(false);
}
public function execute( $applyLimit = true )
{
$query_str = $this->buildQueryString();
$query = $this->em->createQuery($query_str);
$this->setQueryParameters($query);
if ( $applyLimit ) {
$this->applyLimitToQuery($query);
}
return $this->selectClause->isCount() ? $query->getSingleScalarResult() : $query->getResult();
}
/**
* @return mixed
*/
public function rowCountNoLimit() {
$sQuery = sprintf( 'SELECT COUNT(*) FROM ( %s ) AS `sub_ct`', $this->peek() );
$oQuery = $this->em->createQuery( $sQuery );
return $oQuery->getSingleScalarResult();
}
protected function applyLimitToQuery($query) {
if ($this->limit) {
$query->setMaxResults($this->limit);
}
if ($this->offset) {
$query->setFirstResult($this->offset);
}
}
protected function buildQueryString()
{
$query = "$this->selectClause $this->fromClause";
$query .= $this->joinsToString();
$query .= $this->wheresToString();
$query .= $this->havingsToString();
$query .= $this->orderByToString();
return $query;
}
protected function joinsToString()
{
return empty($this->joins) ? '' : ' ' . implode(' ', $this->joins);
}
protected function wheresToString()
{
return empty($this->wheres) ? '' : ' WHERE ' . implode(' AND ', $this->wheres);
}
protected function havingsToString()
{
return empty($this->havings) ? '' : ' HAVING ' . implode(' AND ', $this->havings);
}
protected function orderByToString()
{
return empty($this->orders) ? '' : ' ORDER BY ' . implode(', ', $this->orders);
}
protected function setQueryParameters($query)
{
foreach ($this->wheres as $where) {
$where->addQueryParameters($query);
}
foreach ($this->havings as $having) {
$having->addQueryParameters($query);
}
}
public function getModelFilters()
{
return $this->model_filters;
}
public function addModelFilter( $sKey, $sValue )
{
$this->model_filters[$sKey] = array( $sKey, $sValue );
}
public function hasModelFilters()
{
return !empty( $this->model_filters );
}
} | php | 14 | 0.644405 | 96 | 19.097778 | 225 | starcoderdata |
package agency.statical;
/**
* @author wty
* @create 2020-03-05 17:02
*/
public class PersonProxy implements Person {
private Person person;
public PersonProxy(Person person) {
this.person = person;
}
@Override
public void work(String work) {
System.out.println("静态前置通知");
person.work(work);
System.out.println("静态后置通知");
}
@Override
public void introduce() {
System.out.println("静态前置通知");
person.introduce();
System.out.println("静态前置通知");
}
} | java | 9 | 0.61512 | 44 | 19.785714 | 28 | starcoderdata |
/* file init_positions.c */
// c code for init_positions subroutine
#include
#include "init_positions.h"
void init_positions(double **coord, int nAtoms, double *box) {
double cbrt(double x); // cube root function
int iBoxD; // integer box dimension
double fBoxD; // float box dimension
int x, y, z;
double xPos, yPos, zPos;
int atomCount;
// determine how many bins to divide the box into
iBoxD = (int) cbrt((double) nAtoms);
if (iBoxD*iBoxD*iBoxD < nAtoms) {
iBoxD++;
}
// determine the size of the bins
fBoxD = 3.55; // Density??
*box = iBoxD*fBoxD; // calculate the box dimension
// add a particle in each bin
atomCount = 0;
for(x=0;x<iBoxD;x++) {
xPos = (x+0.5)*fBoxD;
for(y=0;y<iBoxD;y++) {
yPos = (y+0.5)*fBoxD;
for(z=0; z<iBoxD; z++) {
if (atomCount < nAtoms) {
zPos = (z+0.5)*fBoxD;
coord[atomCount][0]=xPos; // Units: Angstrom
coord[atomCount][1]=yPos;
coord[atomCount][2]=zPos;
atomCount++;
} else {
break;
}
}
if (atomCount>=nAtoms) {
break;
}
}
}
} | c | 16 | 0.575221 | 62 | 21.156863 | 51 | starcoderdata |
<?php
declare(strict_types=1);
namespace Tests\Setono\SyliusClimatePartnerPlugin\Behat\Page\Shop\Cart;
use Sylius\Behat\Page\Shop\Cart\SummaryPageInterface as BaseSummaryPageInterface;
interface SummaryPageInterface extends BaseSummaryPageInterface
{
public function applyClimateOffset(): void;
public function removeClimateOffset(): void;
} | php | 6 | 0.822542 | 81 | 26.8 | 15 | starcoderdata |
def is_list_node(xpath, yang_parser, xmlns_info):
"""Whether the node is list
Args:
xpath: The leaf-node's xpath.(without prefix).
yang_parser: The yang_handler.
xmlns_info: The xmlns_info.Saving all nodes's xmlns information.
Returns:
A bool.
"""
feature = xpath.split("/")[1]
if not yang_parser.ctx.modules:
return False
# get module's root and augment_flag.
feature_info_list = get_feature_info(xpath, yang_parser, xmlns_info)
feature_info = feature_info_list[0]
augment_flag = feature_info_list[1]
if not feature_info:
logging.error("module %s is not provided in yang directory", feature)
return False
if augment_flag:
# get xpath's root when augment.
leaf = get_xpaths_node_of_augment(xpath, feature_info)
else:
# get xpath's root.
leaf = get_xpaths_node(xpath, feature_info)
if not leaf:
logging.warning("xpath %s has no correspond leaf find in yang files", xpath)
return False
if leaf.keyword == "list":
return True
return False | python | 10 | 0.626118 | 84 | 29.243243 | 37 | inline |
package us.ihmc.quadrupedCommunication.networkProcessing.stepTeleop;
import java.util.concurrent.atomic.AtomicReference;
import controller_msgs.msg.dds.AbortWalkingMessage;
import controller_msgs.msg.dds.GroundPlaneMessage;
import controller_msgs.msg.dds.HighLevelStateChangeStatusMessage;
import controller_msgs.msg.dds.PlanarRegionsListMessage;
import controller_msgs.msg.dds.QuadrupedBodyPathPlanMessage;
import controller_msgs.msg.dds.QuadrupedFootstepStatusMessage;
import controller_msgs.msg.dds.QuadrupedSteppingStateChangeMessage;
import controller_msgs.msg.dds.QuadrupedTeleopDesiredVelocity;
import controller_msgs.msg.dds.QuadrupedXGaitSettingsPacket;
import us.ihmc.commons.Conversions;
import us.ihmc.graphicsDescription.yoGraphics.YoGraphicsListRegistry;
import us.ihmc.quadrupedCommunication.networkProcessing.OutputManager;
import us.ihmc.quadrupedCommunication.networkProcessing.QuadrupedRobotDataReceiver;
import us.ihmc.quadrupedCommunication.networkProcessing.QuadrupedToolboxController;
import us.ihmc.quadrupedPlanning.QuadrupedXGaitSettingsReadOnly;
import us.ihmc.quadrupedPlanning.footstepChooser.PointFootSnapperParameters;
import us.ihmc.yoVariables.registry.YoRegistry;
public class QuadrupedStepTeleopController extends QuadrupedToolboxController
{
private final QuadrupedStepTeleopManager teleopManager;
private final AtomicReference controllerStateChangeMessage = new AtomicReference<>();
private final AtomicReference steppingStateChangeMessage = new AtomicReference<>();
public QuadrupedStepTeleopController(QuadrupedXGaitSettingsReadOnly defaultXGaitSettings, PointFootSnapperParameters pointFootSnapperParameters,
OutputManager statusOutputManager, QuadrupedRobotDataReceiver robotDataReceiver, YoRegistry parentRegistry,
YoGraphicsListRegistry graphicsListRegistry, long tickTimeMs)
{
super(robotDataReceiver, statusOutputManager, parentRegistry);
teleopManager = new QuadrupedStepTeleopManager(defaultXGaitSettings, pointFootSnapperParameters, robotDataReceiver.getReferenceFrames(),
Conversions.millisecondsToSeconds(tickTimeMs), graphicsListRegistry, registry);
}
public void setPaused(boolean pause)
{
teleopManager.setPaused(pause);
if(pause)
{
reportMessage(new AbortWalkingMessage());
}
}
public void processBodyPathPlanMessage(QuadrupedBodyPathPlanMessage message)
{
teleopManager.processBodyPathPlanMessage(message);
}
public void processFootstepStatusMessage(QuadrupedFootstepStatusMessage message)
{
teleopManager.processFootstepStatusMessage(message);
}
public void processHighLevelStateChangeMessage(HighLevelStateChangeStatusMessage message)
{
controllerStateChangeMessage.set(message);
}
public void processSteppingStateChangeMessage(QuadrupedSteppingStateChangeMessage message)
{
steppingStateChangeMessage.set(message);
}
public void processPlanarRegionsListMessage(PlanarRegionsListMessage message)
{
teleopManager.processPlanarRegionsListMessage(message);
}
public void processGroundPlaneMessage(GroundPlaneMessage message)
{
teleopManager.processGroundPlaneMessage(message);
}
public void processXGaitSettingsPacket(QuadrupedXGaitSettingsPacket packet)
{
teleopManager.processXGaitSettingsPacket(packet);
}
public void processTimestamp(long timestampInNanos)
{
teleopManager.processTimestamp(timestampInNanos);
}
public void processTeleopDesiredVelocity(QuadrupedTeleopDesiredVelocity message)
{
teleopManager.setDesiredVelocity(message.getDesiredXVelocity(), message.getDesiredYVelocity(), message.getDesiredYawVelocity());
}
public void setShiftPlanBasedOnStepAdjustment(boolean shift)
{
teleopManager.setShiftPlanBasedOnStepAdjustment(shift);
}
@Override
public boolean initializeInternal()
{
teleopManager.initialize();
return true;
}
@Override
public void updateInternal()
{
teleopManager.update();
reportMessage(teleopManager.getStepListMessage());
reportMessage(teleopManager.getBodyOrientationMessage());
}
@Override
public boolean isDone()
{
if (controllerStateChangeMessage.get() == null)
return false;
return controllerStateChangeMessage.get().getEndHighLevelControllerName() != HighLevelStateChangeStatusMessage.WALKING;
}
} | java | 10 | 0.789361 | 147 | 36.448 | 125 | starcoderdata |
function(result){
// validate inputs and print debug
var invalid = utils.validateInputs(bengt.userData, result.meta.fields);
if (invalid) {
return cb(invalid.join());
}
if (bengt.userData.debug) {
return console.log('DEBUG:', result);
}
var data = result.data,
headers = utils.getHeaders(bengt.userData, result.meta.fields),
groupBy = bengt.userData.groupBy,
out;
if (groupBy) {
out = bengt.computeByGroup(groupBy, data, headers);
} else {
out = bengt.computeAll(data, headers);
}
cb(null, out);
} | javascript | 11 | 0.572555 | 77 | 25.458333 | 24 | inline |
func (c *Core) finalizeRedeemAction(t *trackedTrade, match *matchTracker, coinID []byte) error {
_, _, proof, auth := match.parts()
if len(auth.RedeemSig) != 0 {
return fmt.Errorf("'redeem' already sent for match %v", match.id)
}
errs := newErrorSet("")
// Attempt to send `redeem` request and validate server ack.
// Not necessary for revoked matches.
var needsResolution bool
if !proof.IsRevoked() {
msgRedeem := &msgjson.Redeem{
OrderID: t.ID().Bytes(),
MatchID: match.id.Bytes(),
CoinID: coinID,
Secret: proof.Secret,
}
ack := new(msgjson.Acknowledgement)
// The DEX may wait up to its configured broadcast timeout, but we will
// retry on timeout or other error.
timeout := t.broadcastTimeout() / 4
if err := t.dc.signAndRequest(msgRedeem, msgjson.RedeemRoute, ack, timeout); err != nil {
var msgErr *msgjson.Error
needsResolution = errors.As(err, &msgErr) && msgErr.Code == msgjson.SettlementSequenceError
ack.Sig = nil // in case of partial unmarshal
errs.add("error sending 'redeem' message for match %s: %v", match.id, err)
} else if err := t.dc.acct.checkSig(msgRedeem.Serialize(), ack.Sig); err != nil {
ack.Sig = nil // don't record an invalid signature
errs.add("'redeem' ack signature error for match %s: %v", match.id, err)
}
// Update the match db data with the redeem details.
if len(ack.Sig) != 0 {
auth.RedeemSig = ack.Sig
auth.RedeemStamp = encode.UnixMilliU(time.Now())
}
}
if match.Match.Side == order.Taker {
match.SetStatus(order.MatchComplete)
proof.TakerRedeem = coinID
} else {
if len(auth.RedeemSig) > 0 {
// As maker, this is the end. However, this diverges from server,
// which is still needs taker's redeem.
match.SetStatus(order.MatchComplete)
} else {
match.SetStatus(order.MakerRedeemed)
}
proof.MakerRedeem = coinID
}
if err := t.db.UpdateMatch(&match.MetaMatch); err != nil {
errs.add("error storing redeem details in database for match %s, coin %s: %v",
match.id, coinIDString(t.wallets.toAsset.ID, coinID), err)
}
// With updated swap data, attempt match status resolution.
if needsResolution {
go c.resolveMatchConflicts(t.dc, map[order.OrderID]*matchStatusConflict{
t.ID(): {
trade: t,
matches: []*matchTracker{match},
},
})
}
return errs.ifAny()
} | go | 18 | 0.681583 | 96 | 33.701493 | 67 | inline |
#ifndef PARSER_TERM_H
#define PARSER_TERM_H
#include <memory>
#include <vector>
#include "../../util/exceptions.hpp"
#include "../../expr/expression.hpp"
#include "../../its/itsproblem.hpp"
namespace parser {
// typedef for readability
class Term;
typedef std::shared_ptr<Term> TermPtr;
/*
* Represents a parsed term, consisting of function applications, arithmetic and variables.
*/
class Term {
public:
EXCEPTION(CannotConvertToGinacException, CustomException);
enum TermType {
BinaryOperation,
FunctionApplication,
Variable,
Number
};
public:
virtual ~Term() {}
// Returns the type of this term
virtual TermType getType() const = 0;
// Returns true iff this term does not contain any function symbols
virtual bool isArithmeticExpression() const = 0;
// Returns true iff this term is a function application whose arguments are arithmetic expressions
virtual bool isFunappOnArithmeticExpressions() const = 0;
// Collects all variables that occur somewhere in this term to the given set
virtual void collectVariables(VarSet &set) const = 0;
// Translates this term into a ginac expression
// The ITSProblem instance is used to map VariableIdx to ginac symbols
virtual Expr toGinacExpression() const = 0;
};
/**
* Represents a binary arithmetic operation.
*/
class TermBinOp : public Term {
public:
enum Operation {
Addition,
Subtraction,
Multiplication,
Division,
Power
};
TermBinOp(const TermPtr &l, const TermPtr &r, Operation type) : lhs(l), rhs(r), op(type) {}
TermType getType() const override { return Term::BinaryOperation; }
Operation getOperation() const { return op; }
TermPtr getLhs() { return lhs; }
TermPtr getRhs() { return rhs; }
bool isArithmeticExpression() const override;
bool isFunappOnArithmeticExpressions() const override { return false; }
void collectVariables(VarSet &set) const override;
Expr toGinacExpression() const override;
private:
TermPtr lhs, rhs;
Operation op;
};
/**
* Represents a function application. The function symbol is stored as string.
*/
class TermFunApp : public Term {
public:
TermFunApp(std::string functionSymbol, const std::vector<TermPtr> &args) : name(functionSymbol), args(args) {}
TermType getType() const override { return Term::FunctionApplication; }
std::string getName() const { return name; }
int getArity() const { return args.size(); }
const std::vector<std::shared_ptr<Term>>& getArguments() const { return args; }
bool isArithmeticExpression() const override { return false; }
bool isFunappOnArithmeticExpressions() const override;
void collectVariables(VarSet &set) const override;
Expr toGinacExpression() const override;
private:
std::string name;
std::vector<std::shared_ptr<Term>> args;
};
/**
* Represents a variable, which is stored as VariableIdx.
*/
class TermVariable : public Term {
public:
TermVariable(Var var) : var(var) {}
TermType getType() const override { return Term::Variable; }
Var getVar() const { return var; }
bool isArithmeticExpression() const override { return true; }
bool isFunappOnArithmeticExpressions() const override { return false; }
void collectVariables(VarSet &set) const override { set.insert(var); }
Expr toGinacExpression() const override { return var; }
private:
Var var;
};
/**
* Represents any kind of number, which is stored as GiNaC::numeric.
*/
class TermNumber : public Term {
public:
TermNumber(GiNaC::numeric number) : num(number) {}
TermType getType() const override { return Term::Number; }
GiNaC::numeric getNumber() const { return num; }
bool isArithmeticExpression() const override { return true; }
bool isFunappOnArithmeticExpressions() const override { return false; }
void collectVariables(VarSet &) const override {}
Expr toGinacExpression() const override { return num; }
private:
GiNaC::numeric num;
};
/**
* A class to represent a relation consisting of two terms and a relational operator.
*/
class Relation {
public:
enum Operator {
RelationEqual,
RelationNotEqual,
RelationGreater,
RelationGreaterEqual,
RelationLess,
RelationLessEqual
};
Relation(TermPtr lhs, TermPtr rhs, Operator type) : lhs(lhs), rhs(rhs), op(type) {}
TermPtr getLhs() const { return lhs; }
TermPtr getRhs() const { return rhs; }
Operator getOperator() const { return op; }
Rel toGinacExpression() const;
private:
TermPtr lhs, rhs;
Operator op;
};
}
#endif //PARSER_TERM_H
| c++ | 15 | 0.68827 | 114 | 25.144444 | 180 | research_code |
tests/without/extract.py
# -*- coding: utf-8 -*-
import tweepy
import time
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
class StreamListener(tweepy.StreamListener):
"""tweepy.StreamListener is a class provided by tweepy used to access
the Twitter Streaming API to collect tweets in real-time.
"""
def on_connect(self):
"""Called when the connection is made"""
print("You're connected to the streaming server!!")
def on_error(self, status_code):
"""This is called when an error occurs"""
print('!Error!: ' + repr(status_code))
return False
def on_data(self, data):
#print(data)
try:
##print(data)
texto =data.split('{"id":')[1].split(',"')[0]+' '+data.split(',"text":"')[1].split('"')[0]+'\n'
print(texto)
saveFile = open('extdData.txt', 'a')
#saveFile.write(complet)
saveFile.write(texto)
saveFile.write('\n')
saveFile.close()
time.sleep(3)
return True
except BaseException:
print ('failed ondata,')
#time.sleep(5)
return True
if __name__ == "__main__":
# authorization tokens
consumer_key = "*******************"
consumer_secret = "7y********************"
access_token = "1***************************"
access_token_secret = "**************************"
# complete authorization and initialize API endpoint
auth1 = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth1.set_access_token(access_token, access_token_secret)
#https://boundingbox.klokantech.com/ (format -> CSV)
#location = [-47.736915,-23.227718,-46.738258,-22.640884] #Mais que a Região Metropolitana de Campinas
#location = [-160.161542, 18.776344, -154.641396, 22.878623] #Hawaii
stream_listener = StreamListener(api=tweepy.API(wait_on_rate_limit=True))
stream = tweepy.Stream(auth=auth1, listener=stream_listener)
tweets = stream.filter(locations=[-47.736915,-23.227718,-46.738258,-22.640884]) | python | 19 | 0.636049 | 105 | 29.681818 | 66 | starcoderdata |
#include "ghost/sparsemat.h"
#include "ghost/util.h"
#include "ghost/locality.h"
#include "ghost/bincrs.h"
#ifdef GHOST_HAVE_COLPACK
#include "ColPack/ColPackHeaders.h"
#endif
extern "C" ghost_error ghost_sparsemat_perm_color(ghost_context *ctx, ghost_sparsemat *mat)
{
#ifdef GHOST_HAVE_COLPACK
GHOST_INFO_LOG("Create permutation from coloring");
ghost_error ret = GHOST_SUCCESS;
ghost_lidx *curcol = NULL;
uint32_t** adolc = new uint32_t*[ctx->row_map->dim];
std::vector colvec = NULL;
uint32_t *adolc_data = NULL;
ColPack::GraphColoring *GC=new ColPack::GraphColoring();
bool oldperm = false;
//ghost_permutation *oldperm = NULL;
int me, i, j;
ghost_gidx *rpt = NULL;
ghost_lidx *rptlocal = NULL;
ghost_gidx *col = NULL;
ghost_lidx *collocal = NULL;
ghost_lidx nnz = 0, nnzlocal = 0;
int64_t pos=0;
ghost_lidx ncols_halo_padded = ctx->row_map->dim;
if (ctx->flags & GHOST_PERM_NO_DISTINCTION) {
ncols_halo_padded = ctx->col_map->dimpad;
}
nnz = SPM_NNZ(mat);
GHOST_CALL_GOTO(ghost_rank(&me,ctx->mpicomm),err,ret);
GHOST_CALL_GOTO(ghost_malloc((void **)&rpt,(ctx->row_map->ldim[me]+1) * sizeof(ghost_gidx)),err,ret);
GHOST_CALL_GOTO(ghost_malloc((void **)&rptlocal,(ctx->row_map->ldim[me]+1) * sizeof(ghost_lidx)),err,ret);
GHOST_CALL_GOTO(ghost_malloc((void **)&collocal,nnz * sizeof(ghost_lidx)),err,ret);
rpt[0] = 0;
rptlocal[0] = 0;
for (ghost_lidx i=0; i i++) {
rptlocal[i+1] = rptlocal[i];
ghost_lidx orig_row = i;
if (ctx->row_map->loc_perm) {
orig_row = ctx->row_map->loc_perm_inv[i];
}
ghost_lidx * col = &mat->col[mat->chunkStart[orig_row]];
ghost_lidx orig_row_len = mat->chunkStart[orig_row+1]-mat->chunkStart[orig_row];
for(int j=0; j<orig_row_len; ++j) {
if (col[j] < mat->context->row_map->dim) {
collocal[nnzlocal] = col[j];
nnzlocal++;
rptlocal[i+1]++;
}
}
}
adolc_data = new uint32_t[nnzlocal+ctx->row_map->dim];
for (i=0;i
{
adolc[i]=&(adolc_data[pos]);
adolc_data[pos++]=rptlocal[i+1]-rptlocal[i];
for (j=rptlocal[i];j<rptlocal[i+1];j++)
{
adolc_data[pos++]=collocal[j];
}
}
GC->BuildGraphFromRowCompressedFormat(adolc, ctx->row_map->dim);
COLPACK_CALL_GOTO(GC->DistanceTwoColoring(),err,ret);
if (GC->CheckDistanceTwoColoring(2)) {
GHOST_ERROR_LOG("Error in coloring!");
ret = GHOST_ERR_COLPACK;
goto err;
}
ctx->ncolors = GC->GetVertexColorCount();
if (!ctx->row_map->loc_perm) {
GHOST_CALL_GOTO(ghost_malloc((void **)ctx->row_map->loc_perm,sizeof(ghost_map)),err,ret);
//ctx->row_map->loc_perm->method = GHOST_PERMUTATION_UNSYMMETRIC; //you can also make it symmetric
GHOST_CALL_GOTO(ghost_malloc((void **)ctx->row_map->loc_perm,sizeof(ghost_gidx)*ctx->row_map->dim),err,ret);
GHOST_CALL_GOTO(ghost_malloc((void **)ctx->row_map->loc_perm_inv,sizeof(ghost_gidx)*ctx->row_map->dim),err,ret);
GHOST_CALL_GOTO(ghost_malloc((void **)ctx->col_map->loc_perm,sizeof(ghost_gidx)*ncols_halo_padded),err,ret);
GHOST_CALL_GOTO(ghost_malloc((void **)ctx->col_map->loc_perm_inv,sizeof(ghost_gidx)*ncols_halo_padded),err,ret);
for(int i=0; i<ncols_halo_padded; ++i) {
ctx->col_map->loc_perm[i] = i;
ctx->col_map->loc_perm_inv[i] = i;
}
#ifdef GHOST_HAVE_CUDA
GHOST_CALL_GOTO(ghost_cu_malloc((void **)ctx->row_map->loc_perm->cu_perm,sizeof(ghost_gidx)*ctx->row_map->dim),err,ret);
#endif
} else if(ctx->row_map->loc_perm == ctx->col_map->loc_perm) { // symmetrix permutation
oldperm = true; //ctx->row_map->loc_perm;
// ctx->row_map->loc_perm->method = GHOST_PERMUTATION_UNSYMMETRIC;//change to unsymmetric
GHOST_CALL_GOTO(ghost_malloc((void **)ctx->col_map->loc_perm,sizeof(ghost_gidx)*ncols_halo_padded),err,ret);
GHOST_CALL_GOTO(ghost_malloc((void **)ctx->col_map->loc_perm_inv,sizeof(ghost_gidx)*ncols_halo_padded),err,ret);
for(int i=0; i<ncols_halo_padded; ++i) {
ctx->col_map->loc_perm[i] = ctx->row_map->loc_perm[i];
ctx->col_map->loc_perm_inv[i] = ctx->row_map->loc_perm_inv[i];
}
} else {
oldperm = true; //ctx->row_map->loc_perm;
}
GHOST_CALL_GOTO(ghost_malloc((void **)&ctx->color_ptr,(ctx->ncolors+1)*sizeof(ghost_lidx)),err,ret);
GHOST_CALL_GOTO(ghost_malloc((void **)&curcol,(ctx->ncolors)*sizeof(ghost_lidx)),err,ret);
memset(curcol,0,ctx->ncolors*sizeof(ghost_lidx));
colvec = GC->GetVertexColorsPtr();
for (i=0;i {
ctx->color_ptr[i] = 0;
}
for (i=0;i {
ctx->color_ptr[(*colvec)[i]+1]++;
}
for (i=1;i {
ctx->color_ptr[i] += ctx->color_ptr[i-1];
}
if (oldperm) {
for (i=0;i {
int idx = ctx->row_map->loc_perm_inv[i];
ctx->row_map->loc_perm[idx] = curcol[(*colvec)[i]] + ctx->color_ptr[(*colvec)[i]];
//ctx->row_map->loc_perm[i] = ctx->row_map->loc_perm_inv[curcol[(*colvec)[i]] + ctx->color_ptr[(*colvec)[i]]];
curcol[(*colvec)[i]]++;
}
} else {
for (i=0;i {
ctx->row_map->loc_perm[i] = curcol[(*colvec)[i]] + ctx->color_ptr[(*colvec)[i]];
curcol[(*colvec)[i]]++;
}
}
for (i=0;i {
ctx->row_map->loc_perm_inv[ctx->row_map->loc_perm[i]] = i;
}
goto out;
err:
out:
delete [] adolc_data;
delete [] adolc;
delete GC;
free(curcol);
free(rpt);
free(col);
free(rptlocal);
free(collocal);
return ret;
#else
UNUSED(mat);
UNUSED(ctx);
GHOST_ERROR_LOG("ColPack not available!");
return GHOST_ERR_NOT_IMPLEMENTED;
#endif
} | c++ | 18 | 0.563483 | 128 | 33.961111 | 180 | starcoderdata |
using Newtonsoft.Json;
using RazorEngine;
using RazorEngine.Templating;
using System;
using System.IO;
using System.Linq;
namespace ScrumJet
{
internal class Program
{
private static void Main(string[] args)
{
var configFile = "config.json";
if (!File.Exists(configFile))
{
Console.WriteLine("Missing configuration file named 'config.json'.");
return;
}
var configContent = File.ReadAllText(configFile);
var config = JsonConvert.DeserializeObject
var workItems = TfsQuery.GetWorkItems(config.Server, config.ProjectCollection, config.AreaPath, config.IterationPath);
var vm = new ViewModel();
vm.Initialize(workItems);
//var vm = TestViewModel.GetTestViewModel();
vm.WorkItems = vm.WorkItems
.OrderBy(wi => wi.ParentId != 0 ? wi.ParentId : wi.Id)
.ToList();
// Razor stuff
var template = File.ReadAllText(@"Template.cshtml");
var r = Engine.Razor.RunCompile(template, "templateKey", typeof(ViewModel), vm);
File.WriteAllText(@"index.html", r);
}
}
} | c# | 18 | 0.589764 | 130 | 27.886364 | 44 | starcoderdata |
<?php declare(strict_types=1);
namespace Dms\Web\Expressive\Renderer\Form\Field;
use Dms\Core\Form\Field\Type\FieldType;
use Dms\Core\Form\IField;
use Dms\Core\Form\IFieldOptions;
use Dms\Core\Form\IFieldType;
use Dms\Web\Expressive\Renderer\Form\FormRenderingContext;
use Dms\Web\Expressive\Renderer\Form\IFieldRendererWithActions;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response;
use Zend\Diactoros\Response\JsonResponse;
/**
* The select-box options field renderer
*
* @author
*/
class SelectOptionsFieldRender extends OptionsFieldRender implements IFieldRendererWithActions
{
/**
* Gets the expected class of the field type for the field.
*
* @return array
*/
public function getFieldTypeClasses() : array
{
return [FieldType::class];
}
protected function canRender(FormRenderingContext $renderingContext, IField $field, IFieldType $fieldType) : bool
{
return $fieldType->has(FieldType::ATTR_OPTIONS)
&& !$fieldType->get(FieldType::ATTR_SHOW_ALL_OPTIONS);
}
protected function renderField(
FormRenderingContext $renderingContext,
IField $field,
IFieldType $fieldType
) : string {
/**
* @var IFieldOptions $options
*/
$options = $fieldType->get(FieldType::ATTR_OPTIONS);
if ($options->canFilterOptions()) {
$remoteDataUrl = $renderingContext->getFieldActionUrl($field) . '/load-options';
try {
$initialValue = $field->getUnprocessedInitialValue();
$option = $initialValue === null ? null : $options->getOptionForValue($initialValue);
} catch (\Exception $e) {
$option = null;
}
return $this->renderView(
$field,
'dms::components.field.select.remote-data-input',
[
FieldType::ATTR_OPTIONS => 'options',
],
[
'remoteDataUrl' => $remoteDataUrl,
'remoteMinChars' => min(3, max(1, (int)log10($options->count()))),
'option' => $option,
]
);
} else {
return $this->renderView(
$field,
'dms::components.field.select.input',
[
FieldType::ATTR_OPTIONS => 'options',
]
);
}
}
/**
* @param FormRenderingContext $renderingContext
* @param IField $field
* @param Request $request
* @param string $actionName
* @param array $data
*
* @return Response
*/
public function handleAction(FormRenderingContext $renderingContext, IField $field, ServerRequestInterface $request, string $actionName = null, array $data)
{
if (ends_with($request->url(), '/load-options') && $request->has('query')) {
/**
* @var IFieldOptions $options
*/
$options = $field->getType()->get(FieldType::ATTR_OPTIONS);
$data = [];
foreach ($options->getFilteredOptions((string)$request->input('query')) as $option) {
if (!$option->isDisabled()) {
$data[] = ['val' => $option->getValue(), 'label' => $option->getLabel()];
}
}
return new JsonResponse($data);
}
$response = new Response('php://memory', 404);
// $response->getBody()->write($message);
return $response;
}
} | php | 25 | 0.550776 | 160 | 31.219298 | 114 | starcoderdata |
package com.elytradev.probe.api;
import java.util.List;
/**
* Capability representing an object's ability to provide detailed information to some kind of probe or UI element. The
* simple case is something like WAILA, HWYLA, or TheOneProbe. However, this API could be used by snap-on monitor
* blocks, remote monitoring systems, or data-based automation. Picture this: "activate redstone when bar labeled
* 'temperature' is greater than 80%". Structured data is very useful data.
*
* interface addresses how you get the data. What you do with it is up to you.
*
* and other devices should gather data only on the server Side. Implementors are encouraged to ignore
* clientside probe requests.
*/
public interface IProbeDataProvider {
public void provideProbeData(List data);
} | java | 8 | 0.766423 | 119 | 44.666667 | 18 | starcoderdata |
'use strict';
const fs = require('fs-extra');
const path = require('path');
const episodesDir = 'episodes';
module.exports = class FileReader {
constructor () {
}
read() {
return this.getEpisodes()
.then( (episodes) => {
return this.getContents(episodes);
})
}
// ファイル一覧を取得
getEpisodes() {
return new Promise( (resolve) => {
fs.readdir(episodesDir, (err, files) => {
if (err) reject(err);
resolve(files);
})
})
}
// すべてのファイルを読み込み
getContents(episodes) {
return Promise.all( episodes.map( (name) => {
return this.getContent(name)
}))
}
// ファイル読み込み
getContent(name) {
return new Promise( (resolve, reject) => {
fs.readFile(path.join(episodesDir, name), 'utf8', (err, data) => {
if (err) reject(err);
resolve({
name: name, // ファイル名
title: this.getTitle(data), // タイトル
data: data // すべてのテキスト
});
})
})
}
// タイトル(最初の見出し行)を取得
getTitle(data) {
let headers = new RegExp(/^#.*/, 'm').exec(data);
return headers ? headers[0].replace(/^#* /, '') : '';
}
}; | javascript | 24 | 0.466616 | 78 | 22.981818 | 55 | starcoderdata |
package com.andreamontanari.placeholder;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends Activity {
GPSTracker gps;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_settings:
showInfo();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void beginLocation(View v) {
gps = new GPSTracker(this);
if(gps.canGetLocation()){
Intent intent = new Intent(this, LocatingActivity.class);
startActivity(intent);
}else {
gps.showSettingsAlert();
}
}
public void showInfo() {
Intent intent = new Intent(this, InformationActivity.class);
startActivity(intent);
}
public void showGPShint(View v) {
LayoutInflater layoutInflater = LayoutInflater.from(this);
View hintView = layoutInflater.inflate(R.layout.gpshint, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set prompts.xml to be the layout file of the alertdialog builder
alertDialogBuilder.setView(hintView);
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
} | java | 14 | 0.680149 | 79 | 26.948052 | 77 | starcoderdata |
from combination.data_structures import Comparable
from combination.equipment_combination import EquipmentCombination
class ScoredCombination(Comparable["ScoredCombination"]):
def __init__(self, score: int, combination: EquipmentCombination):
self.score = score
self.combination = combination
def __lt__(self, other: "ScoredCombination") -> bool:
return self.score < other.score | python | 8 | 0.748908 | 70 | 37.166667 | 12 | starcoderdata |
package main.model.domain;
/**
*
* @author Jamie
*
* This interface represents something that can supply an army with 'upkeep'
* supplies.
*/
public interface SupplyTrain {
/**
* Offers an army to a SupplyTrain to give the train a chance to restock the
* offered army. The train may do nothing.
* @param countyArmy - the army to consider re-supplying
*/
public void supplyYourArmy (Army army);
/**
* Instructs the domain that the army is disbanding in the home domain
* @param countyArmy - the army to be disbanded
*/
public void disbandAtHome(Army army);
/**
* Instructs the domain that the army is disbanding outside the home domain
* @param countyArmy - the army to be disbanded
*/
public void disbandRemotely(Army army);
} | java | 6 | 0.701031 | 77 | 22.515152 | 33 | starcoderdata |
using NMF.Expressions;
using NMF.Synchronizations.Inconsistencies;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace NMF.Synchronizations
{
///
/// Denotes a synchronization job to synchronize properties
///
/// <typeparam name="TLeft">The LHS type of elements
/// <typeparam name="TRight">The RHS type of elements
/// <typeparam name="TValue">The value type of the property synchronization
internal class PropertySynchronizationJob<TLeft, TRight, TValue> : ISynchronizationJob<TLeft, TRight>
{
private readonly ObservingFunc<TLeft, TValue> leftFunc;
private readonly ObservingFunc<TRight, TValue> rightFunc;
private readonly Func<TLeft, TValue> leftGetter;
private readonly Func<TRight, TValue> rightGetter;
private readonly Action<TLeft, TValue> leftSetter;
private readonly Action<TRight, TValue> rightSetter;
private readonly bool isEarly;
///
/// Creates a new property synchronization job
///
/// <param name="leftSelector">The LHS selector
/// <param name="rightSelector">The RHS selector
/// <param name="isEarly">TRue, if the property synchronization should be executed immediately when the correspondence is established, otherwise false
public PropertySynchronizationJob(Expression<Func<TLeft, TValue>> leftSelector, Expression<Func<TRight, TValue>> rightSelector, bool isEarly)
{
if (leftSelector == null) throw new ArgumentNullException("leftSelector");
if (rightSelector == null) throw new ArgumentNullException("rightSelector");
leftFunc = new ObservingFunc<TLeft, TValue>(leftSelector);
rightFunc = new ObservingFunc<TRight, TValue>(rightSelector);
leftGetter = leftSelector.Compile();
rightGetter = rightSelector.Compile();
var leftSetterExpression = SetExpressionRewriter.CreateSetter(leftSelector);
if (leftSetterExpression != null)
{
leftSetter = leftSetterExpression.Compile();
}
else
{
throw new ArgumentException("The expression is read-only", "leftSelector");
}
var rightSetterExpression = SetExpressionRewriter.CreateSetter(rightSelector);
if (rightSetterExpression != null)
{
rightSetter = rightSetterExpression.Compile();
}
else
{
throw new ArgumentException("The expression is read-only", "rightSelector");
}
this.isEarly = isEarly;
}
/// <inheritdoc />
public bool IsEarly
{
get
{
return isEarly;
}
}
private IDisposable PerformTwoWay(TLeft left, TRight right, ISynchronizationContext context)
{
var leftEx3 = leftFunc.InvokeReversable(left);
leftEx3.Successors.SetDummy();
var rightEx3 = rightFunc.InvokeReversable(right);
rightEx3.Successors.SetDummy();
switch (context.Direction)
{
case SynchronizationDirection.CheckOnly:
return new IncrementalPropertyConsistencyCheck rightEx3, context);
case SynchronizationDirection.LeftToRight:
case SynchronizationDirection.LeftToRightForced:
rightEx3.Value = leftEx3.Value;
break;
case SynchronizationDirection.LeftWins:
if (leftEx3.Value != null)
{
rightEx3.Value = leftEx3.Value;
}
else
{
leftEx3.Value = rightEx3.Value;
}
break;
case SynchronizationDirection.RightToLeft:
case SynchronizationDirection.RightToLeftForced:
leftEx3.Value = rightEx3.Value;
break;
case SynchronizationDirection.RightWins:
if (rightEx3.Value != null)
{
leftEx3.Value = rightEx3.Value;
}
else
{
rightEx3.Value = leftEx3.Value;
}
break;
default:
throw new InvalidOperationException();
}
var dependency = new BidirectionalPropertySynchronization rightEx3);
return dependency;
}
private IDisposable PerformOneWay(TLeft left, TRight right, ISynchronizationContext context)
{
IDisposable dependency = null;
switch (context.Direction)
{
case SynchronizationDirection.CheckOnly:
throw new NotSupportedException("Check only is not supported for partial change propagation.");
case SynchronizationDirection.LeftToRight:
case SynchronizationDirection.LeftToRightForced:
var leftEx1 = leftFunc.Observe(left);
leftEx1.Successors.SetDummy();
rightSetter(right, leftEx1.Value);
dependency = new PropertySynchronization val => rightSetter(right, val));
break;
case SynchronizationDirection.RightToLeft:
case SynchronizationDirection.RightToLeftForced:
var rightEx2 = rightFunc.Observe(right);
rightEx2.Successors.SetDummy();
leftSetter(left, rightEx2.Value);
dependency = new PropertySynchronization val => leftSetter(left, val));
break;
case SynchronizationDirection.LeftWins:
case SynchronizationDirection.RightWins:
TValue leftVal;
TValue rightVal;
if (context.Direction == SynchronizationDirection.LeftWins)
{
var leftEx4 = leftFunc.Observe(left);
leftEx4.Successors.SetDummy();
leftVal = leftEx4.Value;
rightVal = rightGetter(right);
dependency = new PropertySynchronization val => rightSetter(right, val));
}
else
{
var rightEx4 = rightFunc.Observe(right);
rightEx4.Successors.SetDummy();
leftVal = leftGetter(left);
rightVal = rightEx4.Value;
dependency = new PropertySynchronization val => leftSetter(left, val));
}
var test = context.Direction == SynchronizationDirection.LeftWins ?
typeof(TValue).IsValueType || leftVal != null :
!(typeof(TValue).IsValueType || rightVal != null);
if (test)
{
rightSetter(right, leftVal);
}
else
{
leftSetter(left, rightVal);
}
break;
default:
throw new InvalidOperationException();
}
return dependency;
}
private void PerformNoChangePropagation(TLeft left, TRight right, SynchronizationDirection direction, ISynchronizationContext context)
{
switch (direction)
{
case SynchronizationDirection.CheckOnly:
var leftValue = leftGetter(left);
var rightValue = rightGetter(right);
if (!EqualityComparer rightValue))
{
context.Inconsistencies.Add(new PropertyInequality<TLeft, TRight, TValue>(left, leftSetter, leftValue, right, rightSetter, rightValue));
}
break;
case SynchronizationDirection.LeftToRight:
case SynchronizationDirection.LeftToRightForced:
rightSetter(right, leftGetter(left));
break;
case SynchronizationDirection.LeftWins:
var val1 = leftGetter(left);
if (val1 != null)
{
rightSetter(right, val1);
}
else
{
leftSetter(left, rightGetter(right));
}
break;
case SynchronizationDirection.RightToLeft:
case SynchronizationDirection.RightToLeftForced:
leftSetter(left, rightGetter(right));
break;
case SynchronizationDirection.RightWins:
var val2 = rightGetter(right);
if (val2 != null)
{
leftSetter(left, val2);
}
else
{
rightSetter(right, leftGetter(left));
}
break;
default:
throw new InvalidOperationException();
}
}
/// <inheritdoc />
public IDisposable Perform(SynchronizationComputation<TLeft, TRight> computation, SynchronizationDirection direction, ISynchronizationContext context)
{
var left = computation.Input;
var right = computation.Opposite.Input;
switch (context.ChangePropagation)
{
case Transformations.ChangePropagationMode.None:
PerformNoChangePropagation(left, right, direction, context);
return null;
case Transformations.ChangePropagationMode.OneWay:
return PerformOneWay(left, right, context);
case Transformations.ChangePropagationMode.TwoWay:
return PerformTwoWay(left, right, context);
default:
throw new InvalidOperationException();
}
}
}
} | c# | 21 | 0.538426 | 166 | 42.269076 | 249 | starcoderdata |
static decl_base_sptr
maybe_strip_qualification(const qualified_type_def_sptr t,
read_context &ctxt)
{
if (!t)
return t;
decl_base_sptr result = t;
type_base_sptr u = t->get_underlying_type();
environment* env = t->get_environment();
if (t->get_cv_quals() & qualified_type_def::CV_CONST
&& (is_reference_type(u)))
{
// Let's strip only the const qualifier. To do that, the "const"
// qualified is turned into a no-op "none" qualified.
result.reset(new qualified_type_def
(u, t->get_cv_quals() & ~qualified_type_def::CV_CONST,
t->get_location()));
ctxt.schedule_type_for_late_canonicalization(is_type(result));
}
else if (t->get_cv_quals() & qualified_type_def::CV_CONST
&& env->is_void_type(u))
{
// So this type is a "const void". Let's strip the "const"
// qualifier out and make this just be "void", so that a "const
// void" type and a "void" type compare equal after going through
// this function.
result = is_decl(u);
}
else if (is_array_type(u) || is_typedef_of_array(u))
{
array_type_def_sptr array;
scope_decl * scope = 0;
if ((array = is_array_type(u)))
{
scope = array->get_scope();
ABG_ASSERT(scope);
array = is_array_type(clone_array_tree(array));
schedule_array_tree_for_late_canonicalization(array, ctxt);
add_decl_to_scope(array, scope);
t->set_underlying_type(array);
u = t->get_underlying_type();
}
else if (is_typedef_of_array(u))
{
scope = is_decl(u)->get_scope();
ABG_ASSERT(scope);
typedef_decl_sptr typdef =
is_typedef(clone_array_tree(is_typedef(u)));
schedule_array_tree_for_late_canonicalization(typdef, ctxt);
ABG_ASSERT(typdef);
add_decl_to_scope(typdef, scope);
t->set_underlying_type(typdef);
u = t->get_underlying_type();
array = is_typedef_of_array(u);
}
else
ABG_ASSERT_NOT_REACHED;
ABG_ASSERT(array);
// We should not be editing types that are already canonicalized.
ABG_ASSERT(!array->get_canonical_type());
type_base_sptr element_type = array->get_element_type();
if (qualified_type_def_sptr qualified = is_qualified_type(element_type))
{
// We should not be editing types that are already canonicalized.
ABG_ASSERT(!qualified->get_canonical_type());
qualified_type_def::CV quals = qualified->get_cv_quals();
quals |= t->get_cv_quals();
qualified->set_cv_quals(quals);
result = is_decl(u);
}
else
{
qualified_type_def_sptr qual_type
(new qualified_type_def(element_type,
t->get_cv_quals(),
t->get_location()));
add_decl_to_scope(qual_type, is_decl(element_type)->get_scope());
array->set_element_type(qual_type);
ctxt.schedule_type_for_late_canonicalization(is_type(qual_type));
result = is_decl(u);
}
}
return result;
} | c++ | 21 | 0.634843 | 78 | 31.258427 | 89 | inline |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.eql.action;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.Version;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.document.DocumentField;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.core.Tuple;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.RandomObjects;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.ToXContentObject;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentParser;
import org.elasticsearch.xcontent.XContentType;
import org.elasticsearch.xpack.eql.AbstractBWCWireSerializingTestCase;
import org.elasticsearch.xpack.eql.action.EqlSearchResponse.Event;
import org.elasticsearch.xpack.eql.action.EqlSearchResponse.Sequence;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Supplier;
import static org.elasticsearch.common.xcontent.XContentHelper.toXContent;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertToXContentEquivalent;
public class EqlSearchResponseTests extends AbstractBWCWireSerializingTestCase {
public void testFromXContent() throws IOException {
XContentType xContentType = randomFrom(XContentType.values()).canonical();
EqlSearchResponse response = randomEqlSearchResponse(xContentType);
boolean humanReadable = randomBoolean();
BytesReference originalBytes = toShuffledXContent(response, xContentType, ToXContent.EMPTY_PARAMS, humanReadable);
EqlSearchResponse parsed;
try (XContentParser parser = createParser(xContentType.xContent(), originalBytes)) {
parsed = EqlSearchResponse.fromXContent(parser);
}
assertToXContentEquivalent(originalBytes, toXContent(parsed, xContentType, humanReadable), xContentType);
}
private static class RandomSource implements ToXContentObject {
private final String key;
private final String value;
RandomSource(Supplier randomStringSupplier) {
this.key = randomStringSupplier.get();
this.value = randomStringSupplier.get();
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(key, value);
builder.endObject();
return builder;
}
@Override
public int hashCode() {
return Objects.hash(key, value);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
RandomSource other = (RandomSource) obj;
return Objects.equals(key, other.key) && Objects.equals(value, other.value);
}
public BytesReference toBytes(XContentType type) {
try (XContentBuilder builder = XContentBuilder.builder(type.xContent())) {
toXContent(builder, ToXContent.EMPTY_PARAMS);
return BytesReference.bytes(builder);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
static List randomEvents(XContentType xType) {
int size = randomIntBetween(1, 10);
List hits = null;
if (randomBoolean()) {
hits = new ArrayList<>();
for (int i = 0; i < size; i++) {
BytesReference bytes = new RandomSource(() -> randomAlphaOfLength(10)).toBytes(xType);
Map<String, DocumentField> fetchFields = new HashMap<>();
int fieldsCount = randomIntBetween(0, 5);
for (int j = 0; j < fieldsCount; j++) {
fetchFields.put(randomAlphaOfLength(10), randomDocumentField(xType).v1());
}
if (fetchFields.isEmpty() && randomBoolean()) {
fetchFields = null;
}
hits.add(new Event(String.valueOf(i), randomAlphaOfLength(10), bytes, fetchFields));
}
}
if (randomBoolean()) {
return hits;
}
return null;
}
private static Tuple<DocumentField, DocumentField> randomDocumentField(XContentType xType) {
switch (randomIntBetween(0, 2)) {
case 0:
String fieldName = randomAlphaOfLengthBetween(3, 10);
Tuple List tuple = RandomObjects.randomStoredFieldValues(random(), xType);
DocumentField input = new DocumentField(fieldName, tuple.v1());
DocumentField expected = new DocumentField(fieldName, tuple.v2());
return Tuple.tuple(input, expected);
case 1:
List listValues = randomList(1, 5, () -> randomList(1, 5, ESTestCase::randomInt));
DocumentField listField = new DocumentField(randomAlphaOfLength(5), listValues);
return Tuple.tuple(listField, listField);
case 2:
List objectValues = randomList(
1,
5,
() -> Map.of(
randomAlphaOfLength(5),
randomInt(),
randomAlphaOfLength(5),
randomBoolean(),
randomAlphaOfLength(5),
randomAlphaOfLength(10)
)
);
DocumentField objectField = new DocumentField(randomAlphaOfLength(5), objectValues);
return Tuple.tuple(objectField, objectField);
default:
throw new IllegalStateException();
}
}
@Override
protected EqlSearchResponse createTestInstance() {
return randomEqlSearchResponse(XContentType.JSON);
}
@Override
protected Writeable.Reader instanceReader() {
return EqlSearchResponse::new;
}
public static EqlSearchResponse randomEqlSearchResponse(XContentType xContentType) {
TotalHits totalHits = null;
if (randomBoolean()) {
totalHits = new TotalHits(randomIntBetween(100, 1000), TotalHits.Relation.EQUAL_TO);
}
return createRandomInstance(totalHits, xContentType);
}
public static EqlSearchResponse createRandomEventsResponse(TotalHits totalHits, XContentType xType) {
EqlSearchResponse.Hits hits = null;
if (randomBoolean()) {
hits = new EqlSearchResponse.Hits(randomEvents(xType), null, totalHits);
}
if (randomBoolean()) {
return new EqlSearchResponse(hits, randomIntBetween(0, 1001), randomBoolean());
} else {
return new EqlSearchResponse(
hits,
randomIntBetween(0, 1001),
randomBoolean(),
randomAlphaOfLength(10),
randomBoolean(),
randomBoolean()
);
}
}
public static EqlSearchResponse createRandomSequencesResponse(TotalHits totalHits, XContentType xType) {
int size = randomIntBetween(1, 10);
List seq = null;
if (randomBoolean()) {
List randoms = getKeysGenerators();
seq = new ArrayList<>();
for (int i = 0; i < size; i++) {
List joins = null;
if (randomBoolean()) {
joins = Arrays.asList(randomFrom(randoms).get());
}
seq.add(new EqlSearchResponse.Sequence(joins, randomEvents(xType)));
}
}
EqlSearchResponse.Hits hits = null;
if (randomBoolean()) {
hits = new EqlSearchResponse.Hits(null, seq, totalHits);
}
if (randomBoolean()) {
return new EqlSearchResponse(hits, randomIntBetween(0, 1001), randomBoolean());
} else {
return new EqlSearchResponse(
hits,
randomIntBetween(0, 1001),
randomBoolean(),
randomAlphaOfLength(10),
randomBoolean(),
randomBoolean()
);
}
}
private static List getKeysGenerators() {
List randoms = new ArrayList<>();
randoms.add(() -> generateRandomStringArray(6, 11, false));
randoms.add(() -> randomArray(0, 6, Integer[]::new, () -> randomInt()));
randoms.add(() -> randomArray(0, 6, Long[]::new, () -> randomLong()));
randoms.add(() -> randomArray(0, 6, Boolean[]::new, () -> randomBoolean()));
return randoms;
}
public static EqlSearchResponse createRandomInstance(TotalHits totalHits, XContentType xType) {
int type = between(0, 1);
switch (type) {
case 0:
return createRandomEventsResponse(totalHits, xType);
case 1:
return createRandomSequencesResponse(totalHits, xType);
default:
return null;
}
}
@Override
protected EqlSearchResponse mutateInstanceForVersion(EqlSearchResponse instance, Version version) {
List mutatedEvents = mutateEvents(instance.hits().events(), version);
List sequences = instance.hits().sequences();
List mutatedSequences = null;
if (sequences != null) {
mutatedSequences = new ArrayList<>(sequences.size());
for (Sequence s : sequences) {
mutatedSequences.add(new Sequence(s.joinKeys(), mutateEvents(s.events(), version)));
}
}
return new EqlSearchResponse(
new EqlSearchResponse.Hits(mutatedEvents, mutatedSequences, instance.hits().totalHits()),
instance.took(),
instance.isTimeout(),
instance.id(),
instance.isRunning(),
instance.isPartial()
);
}
private List mutateEvents(List original, Version version) {
if (original == null || original.isEmpty()) {
return original;
}
List mutatedEvents = new ArrayList<>(original.size());
for (Event e : original) {
mutatedEvents.add(new Event(e.index(), e.id(), e.source(), version.onOrAfter(Version.V_7_13_0) ? e.fetchFields() : null));
}
return mutatedEvents;
}
} | java | 18 | 0.613852 | 134 | 39.251799 | 278 | starcoderdata |
package com.codeardi.hc20qualification.solver;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class Library {
private int id;
private int signUpDays;
private int booksPerDay;
private int totalDays;
private List books;
private Set globalScannedBooks;
private List scannedBooks = new ArrayList<>();
public Library(int id, int signUpDays, int booksPerDay, int totalDays, List books,
Set globalScannedBooks) {
this.id = id;
this.signUpDays = signUpDays;
this.booksPerDay = booksPerDay;
this.totalDays = totalDays;
ArrayList inputBooks = new ArrayList<>(books);
inputBooks.sort(Comparator.reverseOrder());
this.books = inputBooks;
this.globalScannedBooks = globalScannedBooks;
}
public List getBooks() {
return books;
}
public int getId() {
return id;
}
public int getSignUpDays() {
return signUpDays;
}
public List getScannedBooks() {
return scannedBooks;
}
public int getScannedBooksScore() {
return scannedBooks.stream()
.mapToInt(Book::getScore)
.sum();
}
public void scanBooks(int idleDays) {
long scannableBooks = getScannableBooks(idleDays);
for (int i = 0; i < scannableBooks; i++) {
if (!globalScannedBooks.contains(books.get(i))) {
scannedBooks.add(books.get(i));
}
}
globalScannedBooks.addAll(scannedBooks);
}
public long updateRemainingBooksAndReturnScore(int idleDays, Set scannedBooks) {
long scannableBooks = getScannableBooks(idleDays);
int totalBooksScore = 0;
final Iterator bookIterator = books.iterator();
while (bookIterator.hasNext() && scannableBooks > 0) {
final Book book = bookIterator.next();
if (scannedBooks.contains(book)) {
bookIterator.remove();
} else {
totalBooksScore += book.getScore();
scannableBooks--;
}
}
return totalBooksScore;
}
private long getScannableBooks(int idleDays) {
long scanningDays = Math.max(0, totalDays - idleDays - signUpDays);
return Math.min(scanningDays * booksPerDay, (long) books.size());
}
} | java | 14 | 0.6204 | 92 | 27.089888 | 89 | starcoderdata |
<?php
declare(strict_types=1);
namespace MHN\Mitglieder;
/**
* Auflistung aller E-Mail-Adressen für die Wahlleitung
*
* @author
* @license https://creativecommons.org/publicdomain/zero/1.0/ CC0 1.0
*/
use MHN\Mitglieder\Auth;
use MHN\Mitglieder\Tpl;
use MHN\Mitglieder\Service\Db;
require_once '../lib/base.inc.php';
Auth::intern();
Tpl::set('htmlTitle', 'Wahlleitung');
Tpl::set('title', 'Wahlleitung');
if (!Auth::hatRecht('wahlleitung')) {
die('Fehlende Rechte.');
}
$emails = Db::getInstance()->query('SELECT email FROM mitglieder WHERE aktiviert = true ORDER BY email')->getColumn();
Tpl::pause();
header('Content-Type: text/plain; charset=utf-8');
echo implode("\r\n", $emails); | php | 8 | 0.698827 | 118 | 20.914286 | 35 | starcoderdata |
package com.krishagni.catissueplus.core.upgrade;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import liquibase.change.custom.CustomTaskChange;
import liquibase.database.Database;
import liquibase.database.jvm.JdbcConnection;
import liquibase.exception.CustomChangeException;
import liquibase.exception.SetupException;
import liquibase.exception.ValidationErrors;
import liquibase.resource.ResourceAccessor;
public class CpPpidFormatUpdater implements CustomTaskChange {
@Override
public String getConfirmationMessage() {
return "Collection Protocol PPID format updated successfully";
}
@Override
public void setUp() throws SetupException {
}
@Override
public void setFileOpener(ResourceAccessor resourceAccessor) {
}
@Override
public ValidationErrors validate(Database database) {
return new ValidationErrors();
}
@Override
public void execute(Database database) throws CustomChangeException {
JdbcConnection dbConnection = (JdbcConnection) database.getConnection();
Statement statement = null;
Statement updateStmt = null;
ResultSet rs = null;
try {
statement = dbConnection.createStatement();
updateStmt = dbConnection.createStatement();
rs = statement.executeQuery(GET_ALL_PPID_FORMAT_SQL);
while (rs.next()) {
Long cpId = rs.getLong("identifier");
String ppidFormat = rs.getString("ppid_format");
if (StringUtils.isBlank(ppidFormat)) {
continue;
}
String newFormat = getNewFormat(ppidFormat);
updateStmt.executeUpdate(String.format(UPDATE_PPID_FORMAT_SQL, newFormat, cpId));
}
} catch (Exception e) {
throw new CustomChangeException("Error when updating ppid format: ", e);
} finally {
try { rs.close(); } catch (Exception e) {}
try { statement.close(); } catch (Exception e) {}
try { updateStmt.close(); } catch (Exception e) {}
}
}
private String getNewFormat(String existingFormat) {
Matcher matcher = pattern.matcher(existingFormat);
if (matcher.find()) {
existingFormat = existingFormat.replace(matcher.group(), String.format(PPID_FORMAT, matcher.group(1)));
}
return existingFormat;
}
private Pattern pattern = Pattern.compile("%0(.+?)d");
private static final String PPID_FORMAT = "%%CP_UID(%s)%%";
private static final String GET_ALL_PPID_FORMAT_SQL = "select identifier, ppid_format from catissue_collection_protocol";
private static final String UPDATE_PPID_FORMAT_SQL = "update catissue_collection_protocol set ppid_format = '%s' where identifier = %d";
} | java | 15 | 0.748257 | 137 | 29.965909 | 88 | starcoderdata |
#########################################################################
#
# Copyright (c) 2003-2004
# Copyright (C) 2004-2013 OpenERP SA (
#
# This library 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 2.1 of the License, or (at your option) any later version.
#
# This library 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 this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# See: http://www.gnu.org/licenses/lgpl.html
#
#############################################################################
import os
import uno
import unohelper
import string
import tempfile
import base64
import sys
reload(sys)
sys.setdefaultencoding("utf8")
from com.sun.star.task import XJobExecutor
if __name__<>"package":
from lib.gui import *
from LoginTest import *
from lib.error import *
from lib.tools import *
from lib.logreport import *
from lib.rpc import *
database="test"
uid = 3
class ExportToRML( unohelper.Base, XJobExecutor ):
def __init__(self, ctx):
self.ctx = ctx
self.module = "openerp_report"
self.version = "0.1"
LoginTest()
if not loginstatus and __name__=="package":
exit(1)
desktop=getDesktop()
doc = desktop.getCurrentComponent()
docinfo=doc.getDocumentInfo()
global url
self.sock=RPCSession(url)
# Read Data from sxw file
tmpsxw = tempfile.mktemp('.'+"sxw")
if not doc.hasLocation():
mytype = Array(makePropertyValue("MediaType","application/vnd.sun.xml.writer"),)
doc.storeAsURL("file://"+tmpsxw,mytype)
data = read_data_from_file( get_absolute_file_path( doc.getURL()[7:] ) )
file_type = doc.getURL()[7:].split(".")[-1]
if docinfo.getUserFieldValue(2) == "":
ErrorDialog("Please Save this file on server","Use Send To Server Option in Odoo Report Menu","Error")
exit(1)
filename = self.GetAFileName()
if not filename:
exit(1)
global passwd
self.password =
try:
res = self.sock.execute(database, uid, self.password, 'ir.actions.report.xml', 'sxwtorml',base64.encodestring(data),file_type)
if res['report_rml_content']:
write_data_to_file(get_absolute_file_path(filename), res['report_rml_content'])
except Exception,e:
import traceback,sys
info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
self.logobj.log_write('ExportToRML',LOG_ERROR, info)
ErrorDialog("Cannot save the file to the hard drive.", "Exception: %s." % e, "Error" )
def GetAFileName(self):
sFilePickerArgs = Array(10)
oFileDialog = createUnoService("com.sun.star.ui.dialogs.FilePicker")
oFileDialog.initialize(sFilePickerArgs)
oFileDialog.appendFilter("Odoo Report File Save To ....","*.rml")
f_path = "OpenERP-"+ os.path.basename( tempfile.mktemp("","") ) + ".rml"
initPath = tempfile.gettempdir()
oUcb = createUnoService("com.sun.star.ucb.SimpleFileAccess")
if oUcb.exists(initPath):
oFileDialog.setDisplayDirectory('file://' + ( os.name == 'nt' and '/' or '' ) + initPath )
oFileDialog.setDefaultName(f_path )
sPath = oFileDialog.execute() == 1 and oFileDialog.Files[0] or ''
oFileDialog.dispose()
sPath = sPath[7:]
if sPath.startswith('localhost/'):
slash = int(os.name == 'nt')
sPath = sPath[9 + slash:]
return sPath
if __name__<>"package" and __name__=="__main__":
ExportToRML(None)
elif __name__=="package":
g_ImplementationHelper.addImplementation( ExportToRML, "org.openoffice.openerp.report.exporttorml", ("com.sun.star.task.Job",),)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: | python | 17 | 0.619636 | 138 | 37.704348 | 115 | starcoderdata |
'use strict';
angular.module('sphynxApp')
.factory('data', function () {
// default initialization
var nateObj = {
type: 'histogram',
twoD: true,
pointLabels: []
};
function transpose (arr) {
var transposed = [];
var i, ii;
for (i = 0, ii = arr[0].length; i < ii; i++) {
transposed.push([]);
}
for (i = 0, ii = arr.length; i < ii; i++) {
for (var j = 0, jj = arr[i].length; j < jj; j++) {
transposed[j][i] = arr[i][j];
}
}
return transposed;
}
function clean2D (arr) {
var clean = [];
for (var i = 0, ii = arr.length; i < ii; i++) {
var temp = [];
for (var j = 0, jj= arr[i].length; j < jj; j++) {
if(arr[i][j].trim().length > 0) {
temp.push(arr[i][j].trim());
}
}
if(temp.length > 0){
clean.push(temp);
}
}
return clean;
}
function makeNate (arr) {
var nonNum = /\D/;
var pointLabelFlag = false;
var axisHash = {
'0' : 'X',
'1' : 'Y',
'2' : 'Z',
'3' : 'size',
'4' : 'color'
};
for (var i = 0, ii = arr.length; i < ii; i++) {
var count = 0;
for (var j = 0, jj = arr[i].length; j < jj; j++) {
if(arr[i][j].match(nonNum)) {
count++;
}
}
if (count > 1) {
nateObj.pointLabels = arr[i];
pointLabelFlag = true;
} else if (count === 1) {
var axisKey = arr[i].shift();
nateObj[axisKey] = arr[i];
} else {
var k = i;
if (pointLabelFlag) {
k = i-1;
}
nateObj[axisHash[k]] = arr[i];
}
}
return nateObj;
}
function set (rawData, type, twoD) {
nateObj.type = type || 'histogram';
nateObj.twoD = twoD;
return makeNate(clean2D(transpose(Papa.parse(rawData).data)));
}
// Public API here
return {
nateObj: nateObj,
set: set
};
}); | javascript | 20 | 0.432111 | 68 | 22.58427 | 89 | starcoderdata |
package com.secarta.httpsec.util;
import java.io.*;
/**
* A buffer for streams that uses an in-memory array, or a file depending on a
* maximum size that you can set.
*
* I'll say it again: { buffer.release(); } Keep repeating it to yourself till it sticks.
*/
public class SmartBuffer {
public static boolean DEBUG = false;
static final int MEMORY_LIMIT = 16384;
private ByteArrayOutputStream byte_buffer;
private File file_buffer;
private int mem_limit;
private OutputStream output;
public SmartBuffer() {
this( MEMORY_LIMIT );
}
public SmartBuffer( int mem_limit ) {
this.mem_limit = mem_limit;
byte_buffer = new ByteArrayOutputStream();
if ( DEBUG ) System.out.println( this + " created" );
}
public InputStream getInputStream() {
if ( file_buffer == null && byte_buffer == null ) throw new IllegalStateException( "already released" );
if ( file_buffer == null ) {
return new ByteArrayInputStream( byte_buffer.toByteArray() );
} else {
try {
return new FileInputStream( file_buffer );
} catch ( IOException e ) {
release();
throw new IllegalStateException( "error opening \"" + file_buffer + "\" for reading: " + e );
}
}
}
public OutputStream getOutputStream() throws IOException {
if ( file_buffer == null && byte_buffer == null ) throw new IllegalStateException( "already released" );
if ( output == null ) {
if ( file_buffer == null ) {
output = new FilterOutputStream( byte_buffer ) {
public void write( int b ) throws IOException {
check( 1 );
super.write( b );
}
public void write( byte[] b ) throws IOException {
write( b, 0, b.length );
}
public void write( byte[] b, int off, int len ) throws IOException {
check( len );
super.write( b, off, len );
}
void check( int len ) {
if ( file_buffer != null ) return;
if ( ( byte_buffer.size() + len ) > mem_limit ) {
if ( DEBUG ) System.out.println( SmartBuffer.this + " store to disk" );
try {
file_buffer = File.createTempFile( "buffer-", ".tmp" );
file_buffer.deleteOnExit();
if ( DEBUG ) System.out.println( SmartBuffer.this + " created temp file " + file_buffer );
out = new FileOutputStream( file_buffer );
byte_buffer.writeTo( out );
} catch ( IOException e ) {
release();
throw new IllegalStateException( "error creating file buffer: " + e );
}
}
}
};
} else {
try {
output = new FileOutputStream( file_buffer );
} catch ( IOException e ) {
release();
throw new IllegalStateException( "error opening \"" + file_buffer + "\" for writing: " + e );
}
}
}
return output;
}
public long length() {
if ( file_buffer == null && byte_buffer == null ) return -1;
return file_buffer == null ? byte_buffer.size() : file_buffer.length();
}
public void release() {
try { output.close(); } catch ( Exception e ) {}
if ( file_buffer == null && byte_buffer == null ) return;
if ( DEBUG ) System.out.println( this + " released" );
if ( file_buffer != null ) file_buffer.delete();
file_buffer = null;
byte_buffer = null;
}
public String toString() {
return "SmartBuffer@" + hashCode() + "[ " + ( file_buffer == null ? "memory" : "disk" ) + " " + length() + " ]";
}
} | java | 26 | 0.483788 | 122 | 38.694444 | 108 | starcoderdata |
package org.innovateuk.ifs.assessment.service;
import org.innovateuk.ifs.assessment.resource.*;
import org.innovateuk.ifs.commons.rest.RestResult;
import java.util.List;
/**
* Interface for CRUD operations on {@link org.innovateuk.ifs.assessment.resource.AssessmentResource} related data.
*/
public interface AssessmentRestService {
RestResult getById(long id);
RestResult getAssignableById(long id);
RestResult getRejectableById(long id);
RestResult getByUserAndCompetition(long userId, long competitionId);
RestResult getByUserAndApplication(long userId, long applicationId);
RestResult countByStateAndCompetition(AssessmentState state, long competitionId);
RestResult countByStateAndAssessmentPeriod(AssessmentState state, long assessmentPeriodId);
RestResult getTotalScore(long id);
RestResult recommend(long id, AssessmentFundingDecisionOutcomeResource assessmentFundingDecision);
RestResult getApplicationFeedback(long applicationId);
RestResult rejectInvitation(long id, AssessmentRejectOutcomeResource assessmentRejectOutcomeResource);
RestResult acceptInvitation(long id);
RestResult withdrawAssessment(long id);
RestResult unsubmitAssessment(long id);
RestResult submitAssessments(AssessmentSubmissionsResource assessmentSubmissions);
RestResult createAssessment(AssessmentCreateResource assessmentCreateResource);
RestResult createAssessments(List assessmentCreateResources);
} | java | 8 | 0.822572 | 117 | 36.893617 | 47 | starcoderdata |
#!/bin/python
# -*- coding: utf-8 -*-
# @File : service.py
# @Author: wangms
# @Date : 2019/12/18
import os
import pickle
import socket
import time
import zlib
import traceback
from datetime import datetime, timedelta
from core.model import Catalog, Image
from core.service import NoteService
from .model import SyncInfo, db
from common import fetch_logger, NoteStatusEnum, SyncStatusEnum
from .sync_utils.base_sync_utils import BaseSyncUtils
logger = fetch_logger(logger_name="IdeaNoteSync", log_filename="sync.log")
class SyncService(object):
def __init__(self, sync_utils: BaseSyncUtils):
self.sync_utils = sync_utils
self.client_id = socket.gethostname()
self.sync_interval = timedelta(seconds=10)
def run(self):
"""
> 比较latest_version_info中的client_id是否和自己相同
> client_id不相同
> 本地版本是否小于最新版本
> 本地版本小于最新版本,开始以下应用日志过程
> Note的note.sync_status是否等于SyncStatusEnum.need_sync
> 是,把同步过来的Note的内容append到原content末尾,并更新状态为SyncStatusEnum.need_sync,并增加本地的版本id
> 不是,就直接把同步过来的Note的内容写入当前的content字段,并增加本地的版本id
> 本地版本等于最新版本
> 本地有变更数据等待push
> 是,version_info文件中的change_time是否过期
> 是,先更新version_info文件的中client_id为本地client_id,change_time为当前系统时间,等待下一轮检查
> 否,等待下一轮检查
> client_id相同
> 本地有变更数据等待push
> 检查version_info文件的change_time是否过期
> 是,更新change_time为当前时间,等待下一轮检查
> 否, push变更日志,并更新对应Note的sync_status=SyncStatusEnum.has_sync,并增加本地和version_info文件中的版本id
TODO: 1. 接下来计划去掉总的version_id, 每个note各自维护自己的version_id,有变更就push
:return:
"""
while True:
local_version_info = SyncInfo.query.first()
try:
not_push_change = Catalog.query.filter(Catalog.sync_status == SyncStatusEnum.need_sync.value).all()
logger.debug(f"waiting for pushing change log: {not_push_change}")
latest_version_info = self.sync_utils.load_version_info()
change_time = datetime.fromisoformat(latest_version_info["change_time"])
latest_version = int(latest_version_info["latest_version"])
if self.client_id != latest_version_info["client_id"]:
if local_version_info.current_version < latest_version:
local_version_info.latest_version = latest_version
local_version_info.modification_time = datetime.now()
db.session.commit()
for ver in range(local_version_info.current_version + 1, latest_version + 1):
note_info = self.sync_utils.load_note_info(ver)
if note_info:
self.apply_change(note_info)
local_version_info.current_version = latest_version
local_version_info.modification_time = datetime.now()
db.session.commit()
else:
# 已经处于同步状态
if len(not_push_change) > 0 and change_time + self.sync_interval * 3 < datetime.now():
# 如果有未push得变更并且其他client在180秒之内没有push变更,就先修改latest_version_info,等待下一轮遍历
latest_version_info["client_id"] = self.client_id
latest_version_info["change_time"] = datetime.now().isoformat()
self.sync_utils.dump_version_info(latest_version_info)
else:
if len(not_push_change) > 0:
if change_time + self.sync_interval * 1.5 < datetime.now():
# 如果latest_version_info中的client是自己,但chnage_time太久远,先更新change_time,等待下一轮遍历
latest_version_info["change_time"] = datetime.now().isoformat()
self.sync_utils.dump_version_info(latest_version_info)
else:
for note in not_push_change:
# 如果latest_version_info中的client是自己,change_time在self.sync_interval内,并且有未提交的变更,就直接push
latest_version += 1
self.push_change(note.id, latest_version)
latest_version_info["latest_version"] = latest_version
latest_version_info["change_time"] = datetime.now().isoformat()
self.sync_utils.dump_version_info(latest_version_info)
local_version_info.current_version = latest_version
local_version_info.latest_version = latest_version
local_version_info.modification_time = datetime.now()
db.session.commit()
except Exception as e:
logger.error(e)
logger.error(traceback.format_exc())
logger.error("网盘同步线程退出")
time.sleep(self.sync_interval.total_seconds())
def apply_change(self, note_info):
note = pickle.loads(note_info.get("note"))
local_note = Catalog.query.filter(Catalog.id == note.id).first()
if local_note and local_note.sync_status == SyncStatusEnum.need_sync.value:
local_content = NoteService.fetch_note(note.id)
remote_content = zlib.decompress(note.content).decode("utf8")
content = f"{local_content}\n{'>' * 100}\n{remote_content}"
note.content = zlib.compress(content.encode("utf8"))
note.sync_status = SyncStatusEnum.need_sync.value
note.status = NoteStatusEnum.need_merge.value
note.modification_time = datetime.now()
else:
note.sync_status = SyncStatusEnum.has_sync.value # 标记未同步状态
db.session.merge(note)
for i in note_info.get("images"):
image = pickle.loads(i)
db.session.merge(image)
db.session.commit()
logger.info(f"Succeed in applying change log: <title={note.title}, version={note_info.get('version')}>")
return True
def push_change(self, note_id, version):
note_info = {}
note = Catalog.query.filter_by(id=note_id).first()
note_info["note"] = pickle.dumps(note)
note_info["images"] = []
for image in Image.query.filter_by(note_id=note_id).all():
note_info["images"].append(pickle.dumps(image))
note_info["id"] = note.id
note_info["title"] = note.title
note_info["client_id"] = self.client_id
note_info["version"] = version
note_info["timestamp"] = datetime.now()
note_info["status"] = note.status
self.sync_utils.dump_note_info(note_info)
note.sync_status = SyncStatusEnum.has_sync.value # 标记未同步状态
db.session.commit()
logger.info(f"Succeed in pushing change log: <title={note.title}, version={version}>")
return True | python | 25 | 0.572549 | 116 | 46.6 | 150 | starcoderdata |
<?php
declare(strict_types=1);
namespace BinSoul\Net\Mqtt\Exception;
use Exception;
/**
* Will be thrown if the end of a stream is reached but more bytes were requested.
*/
class EndOfStreamException extends Exception
{
} | php | 3 | 0.742857 | 82 | 15.333333 | 15 | starcoderdata |
<?php
/**
* @author
* @link https://skeeks.com/
* @copyright (c) 2010 SkeekS
* @date 11.03.2018
*/
namespace skeeks\yii2\config;
use skeeks\yii2\form\IHasForm;
use yii\base\Model;
use yii\base\ModelEvent;
use yii\db\ActiveRecord;
use yii\db\AfterSaveEvent;
/**
* @property ConfigBehavior $configBehavior
*
* Class ConfigModel
* @package skeeks\yii2\config
*/
class ConfigModel extends Model implements IHasForm
{
/**
* @see Builder
* @return array
*/
public function builderFields()
{
return [];
}
/**
* @see Builder
* @return array
*/
public function builderModels()
{
return [];
}
/**
* @var ConfigBehavior
*/
public $_configBehavior;
/**
* @return ConfigBehavior
*/
public function getConfigBehavior()
{
return $this->_configBehavior;
}
/**
* @return ConfigBehavior
*/
public function setConfgiBehavior(ConfigBehavior $configBehavior)
{
$this->_configBehavior = $configBehavior;
return $this;
}
/**
* @var array attribute values indexed by attribute names
*/
private $_attributes = [];
/**
* @var array|null old attribute values indexed by attribute names.
* This is `null` if the record [[isNewRecord|is new]].
*/
private $_oldAttributes;
/**
* @param $insert
* @return bool
*/
public function beforeSave($insert)
{
$event = new ModelEvent();
$this->trigger($insert ? ActiveRecord::EVENT_BEFORE_INSERT : ActiveRecord::EVENT_BEFORE_UPDATE, $event);
return $event->isValid;
}
/**
* @param $insert
* @param $changedAttributes
*/
public function afterSave($insert, $changedAttributes)
{
$this->trigger($insert ? ActiveRecord::EVENT_AFTER_INSERT : ActiveRecord::EVENT_AFTER_UPDATE, new AfterSaveEvent([
'changedAttributes' => $changedAttributes,
]));
}
/**
* @return bool
*/
public function beforeDelete()
{
$event = new ModelEvent();
$this->trigger(ActiveRecord::EVENT_BEFORE_DELETE, $event);
return $event->isValid;
}
/**
*
*/
public function afterDelete()
{
$this->trigger(ActiveRecord::EVENT_AFTER_DELETE);
}
/**
* Returns a value indicating whether the model has an attribute with the specified name.
* @param string $name the name of the attribute
* @return bool whether the model has an attribute with the specified name.
*/
public function hasAttribute($name)
{
return isset($this->_attributes[$name]) || in_array($name, $this->attributes(), true);
}
/**
* Returns the named attribute value.
* If this record is the result of a query and the attribute is not loaded,
* `null` will be returned.
* @param string $name the attribute name
* @return mixed the attribute value. `null` if the attribute is not set or does not exist.
* @see hasAttribute()
*/
public function getAttribute($name)
{
return isset($this->_attributes[$name]) ? $this->_attributes[$name] : null;
}
} | php | 15 | 0.59374 | 122 | 18.638554 | 166 | starcoderdata |
void hec2hrp_state::mx40_io_port_w(offs_t offset, uint8_t data)
{
offset &= 0xff;
/* Bank switching on several address */
if (offset == 0x40) /* Port page 0*/
m_bank[2]->set_entry(HECTORMX_BANK_PAGE0);
else
if (offset == 0x41) /* Port page 1*/
{
m_bank[2]->set_entry(HECTORMX_BANK_PAGE1);
m_hector_flag_80c = false;
}
else
if (offset == 0x44) /* Port page 2 => 42 on MX80*/
m_bank[2]->set_entry(HECTORMX_BANK_PAGE2);
else
if (offset == 0x49) /* Port screen resolution*/
m_hector_flag_80c = false;/* No 80c in 40c !*/
} | c++ | 13 | 0.634011 | 63 | 26.1 | 20 | inline |
#include "bits/stdc++.h"
#define Rep(i,n) for(int i=0;i<n;i++)
#define For(i,n1,n2) for(int i=n1;i<n2;i++)
#define REP(i,n) for(ll i=0;i<n;i++)
#define FOR(i,n1,n2) for(ll i=n1;i<n2;i++)
#define put(a) cout<<a<<endl;
#define all(a) (a).begin(),(a).end()
#define SORT(c) sort((c).begin(),(c).end())
#define TDARRAY(int,a,n,m) vector<vector<int>> a(n,vector<int>(m,0));
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
template<class T> inline bool chmax(T& a, T b) {if(a<b){a=b;return 1;}return 0;}
template<class T> inline bool chmin(T& a, T b) {if(a>b){a=b;return 1;}return 0;}
class Modulo{
public:
ll val;
static const ll mod = 1e9+7;
vector<ll> factable = {1};
vector<ll> invtable = {1};
ll pro(ll x,ll y){return ((x%mod)*(y%mod))%mod;}
ll sum(ll x,ll y){return ((x%mod)+(y%mod))%mod;}
ll dif(ll x,ll y){ll d =((x%mod)-(y%mod))%mod;if(d>=0){return d;}else{return d+mod;}}
ll quo(ll x, ll y){return pro(x,pow(y,mod-2));}
ll pow(ll x,ll y){
if(y<=0){return 1;}
if(y%2==0){ll d = pow(x,y/2);return ((d%mod)*(d%mod))%mod;}
else{return (x*pow(x,y-1))%mod;}
}
void operator=(ll n){this->val = n%mod;}
ll operator+(ll n){return sum(this->val,n);}
ll operator-(ll n){return dif(this->val,n);}
ll operator*(ll n){return pro(this->val,n);}
ll operator/(ll n){return quo(this->val,n);}
void operator+=(ll n){this->val = sum(this->val,n);}
void operator-=(ll n){this->val = dif(this->val,n);}
void operator*=(ll n){this->val = pro(this->val,n);}
void operator/=(ll n){this->val = quo(this->val,n);}
ll fac(ll x){
//x! mod mod
if(factable.size()<=x){
ll s = factable.size();
FOR(i,s,x+1){
factable.push_back(pro(i,factable.back()));
invtable.push_back(quo(1,factable.back()));
}
}
if(x<0) return 1;
else return factable[x];
}
ll facinv(ll x){
if(invtable.size()<=x){
ll s = invtable.size();
FOR(i,s,x+1){
factable.push_back(pro(i,factable.back()));
invtable.push_back(quo(1,factable.back()));
}
}
if(x<0) return 1;
else return invtable[x];
}
ll com(ll x,ll y){
//xCy mod mod = x!/((x-y)!*y!) mod mod
if(x-y<y)return com(x,x-y);
return pro(fac(x),pro(facinv(x-y),facinv(y)));
}
};
string s;
ll q=0;
ll sa[100005];
ll sb[100005];
ll sc[100005];
ll fa[100005];
ll fb[100005];
ll fc[100005];
ll det(char a,char b,char c){
//i<j<k and s[i]==a and s[j]==b and s[k]==cを満たすi,j,kの場合の数を返す
ll rtn = 0;
return rtn;
}
int main(){
cin >> s;
ll n = s.size();
vector<ll> fa,fb,fc,fq;
vector<ll> sa(n+1,0),sb(n+1,0),sc(n+1,0),sq(n+1,0);
REP(i,n){
if(s[i]=='A'){
fa.push_back(i);
sa[i+1] = sa[i]+1;
}else{
sa[i+1] = sa[i];
}
if(s[i]=='B'){
fb.push_back(i);
sb[i+1] = sb[i]+1;
}else{
sb[i+1] = sb[i];
}
if(s[i]=='C'){
fc.push_back(i);
sc[i+1] = sc[i]+1;
}else{
sc[i+1] = sc[i];
}
if(s[i]=='?'){
fq.push_back(i);
sq[i+1] = sq[i]+1;
q++;
}else{
sq[i+1] = sq[i];
}
}
vector<ll> sbc(n+1,0),sqc(n+1,0),sbq(n+1,0),sqq(n+1,0);
REP(i,n){
if(s[i]=='B'){
sbc[i+1] = sbc[i]+sc[n]-sc[i+1];
sbq[i+1] = sbq[i]+sq[n]-sq[i+1];
}else{
sbc[i+1] = sbc[i];
sbq[i+1] = sbq[i];
}
if(s[i]=='?'){
sqc[i+1] = sqc[i]+sc[n]-sc[i+1];
sqq[i+1] = sqq[i]+sq[n]-sq[i+1];
}else{
sqc[i+1] = sqc[i];
sqq[i+1] = sqq[i];
}
}
Modulo res;
res = 0;
Modulo abc;
abc = 0;
REP(i,fa.size()){
abc += sbc[n]-sbc[fa[i]+1];
}
abc*=abc.pow(3,q);
res+=abc.val;
Modulo qbc;
qbc = 0;
REP(i,fq.size()){
qbc += sbc[n]-sbc[fq[i]+1];
}
qbc*=qbc.pow(3,q-1);
res+=qbc.val;
Modulo aqc;
aqc = 0;
REP(i,fa.size()){
aqc += sqc[n]-sqc[fa[i]+1];
}
aqc*=aqc.pow(3,q-1);
res+=aqc.val;
Modulo abq;
abq = 0;
REP(i,fa.size()){
abq += sbq[n]-sbq[fa[i]+1];
}
abq*=abq.pow(3,q-1);
res+=abq.val;
Modulo aqq;
aqq = 0;
REP(i,fa.size()){
aqq += sqq[n]-sqq[fa[i]+1];
}
aqq*=aqq.pow(3,q-2);
res+=aqq.val;
Modulo qbq;
qbq = 0;
REP(i,fq.size()){
qbq += sbq[n]-sbq[fq[i]+1];
}
qbq*=qbq.pow(3,q-2);
res+=qbq.val;
Modulo qqc;
qqc = 0;
REP(i,fq.size()){
qqc += sqc[n]-sqc[fq[i]+1];
}
qqc*=qqc.pow(3,q-2);
res+=qqc.val;
Modulo qqq;
qqq = 0;
REP(i,fq.size()){
qqq += sqq[n]-sqq[fq[i]+1];
}
qqq*=qqq.pow(3,q-3);
res+=qqq.val;
put(res.val);
return 0;
}
| c++ | 15 | 0.452938 | 89 | 23.82439 | 205 | codenet |
/**
* Created by Glenn on 2015-08-13.
*/
import maps from 'googlemaps';
import { RoutingEngine as RoutingEngineInterface } from '../routing-engine';
/**
*
* @implements {RoutingEngine}
*/
const GoogleMapsRoutingEngine = stampit()
.init(({ instance }) => {
const { routingManager, viewer } = instance;
/* region private properties */
/*
*
*/
let placesService;
/*
*
*/
let routingService;
/* endregion private properties */
/* region privileged methods */
_.assign(instance, {
/**
*
* @param query
* @returns {Promise}
*/
searchPlaces(query) {
const defer = $.Deferred();
const { bottom, right, top, left } = viewer.getBoundingBox();
placesService.textSearch({
query,
bounds: new google.maps.LatLngBounds(
new google.maps.LatLng(bottom, right),
new google.maps.LatLng(top, left)
),
}, (results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
const places = _.map(results, (item) => {
const { geometry, name, formatted_address } = item;
const { location } = geometry;
return {
icon: 'mc-icon-routing-typeaddress',
lat : location.lat(),
lng : location.lng(),
name: `${name}, ${formatted_address}`,
};
});
defer.resolve(places);
} else {
defer.reject({ message: status });
}
});
return defer.promise();
},
/**
*
* @returns {Promise}
*/
calculateRoute() {
const defer = $.Deferred();
const waypoints = routingManager.getValidWaypoints();
const start = waypoints.shift();
const end = waypoints.pop();
const { tollroad, motorway, boatFerry } = routingManager.getRouteFeatures();
const request = {
avoidTolls : (tollroad < 0),
avoidHighways: (motorway < 0),
avoidFerries : (boatFerry < 0),
travelMode : google.maps.TravelMode.DRIVING,
origin : new google.maps.LatLng(start.lat, start.lng),
destination : new google.maps.LatLng(end.lat, end.lng),
waypoints : _.map(waypoints, (waypoint) => ({
location: new google.maps.LatLng(waypoint.lat, waypoint.lng),
stopover: true,
})),
};
routingService.route(request, (response, status) => {
if (status === google.maps.DirectionsStatus.OK) {
const route = response.routes[0];
const routingResult = {
path : [],
legs : [],
summary : {},
maneuvers: [],
};
const { path, legs, summary, maneuvers } = routingResult;
_.forEach(route.legs, (leg) => {
const { distance, duration } = leg;
legs.push({
firstPointIndex: path.length,
length : distance.value,
traveltime : duration.value,
});
_.forEach(leg.steps, (step) => {
const { instructions, maneuver } = step;
maneuvers.push({
instruction : instructions,
baseCssAction: 'adp-maneuver',
action : maneuver,
});
_.forEach(step.path, (latLng) => {
path.push({
lat: parseFloat(latLng.lat().toFixed(8)),
lng: parseFloat(latLng.lng().toFixed(8)),
});
});
});
});
_.assign(summary, _.transform(legs, (result, leg) => {
const { traveltime, length } = leg;
result.duration = result.duration + traveltime;
result.distance = result.distance + length;
}), { duration: 0, distance: 0 });
defer.resolve(routingResult);
} else {
defer.reject({ message: status });
}
});
return defer.promise();
},
});
/* endregion privileged methods */
/* region init code */
placesService = new google.maps.places.PlacesService(viewer.getNativeObject());
routingService = new google.maps.DirectionsService();
/* endregion init code */
});
const RoutingEngine = stampit.compose(RoutingEngineInterface, GoogleMapsRoutingEngine);
export { RoutingEngine as default, RoutingEngine }; | javascript | 19 | 0.503574 | 87 | 27.650602 | 166 | starcoderdata |
from js import print_div
from RobotRaconteur.Client import *
from matplotlib import pyplot as plt
import matplotlib
print_div("matplotlib backend: " + str(matplotlib.get_backend()))
plt.figure()
plt.plot([1,2,3])
plt.show()
print_div("Done?")
plt.clf()
async def test_plot():
a=0
while True:
a+=0.1
plt.clf()
plt.plot([a,2,3])
await RRN.AsyncSleep(0.1,None)
RR.WebLoop.run(test_plot()) | python | 9 | 0.626638 | 65 | 18.913043 | 23 | starcoderdata |
package martin.bryant.csu660;
public class Call implements FLANG {
FLANG fun;
FLANG arg;
public Call(FLANG fun, FLANG arg) {
this.fun = fun;
this.arg = arg;
}
public FLANG eval() throws Exception {
if (fun instanceof Fun) {
Fun temp = (Fun) fun;
temp = (Fun)temp.subst(temp.id,arg);
System.out.println(">> Subst "+temp.id.toString()+" -> "+arg.toString()+"\n"+temp.toString());
return temp.eval();
}
throw new Exception("'call' expects a function, got: "+fun.toString());
}
public FLANG subst(Id from, FLANG to) {
return new Call(fun.subst(from,to),arg.subst(from,to));
}
public String toString() {
return "(Call "+fun.toString()+" "+arg.toString()+")";
}
} | java | 17 | 0.539663 | 106 | 26.733333 | 30 | starcoderdata |
package com.fwkj.fw_mvp_root.view;
import android.os.Bundle;
import android.view.View;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.fwkj.fw_mvp_root.R;
import com.fwkj.fw_mvp_root.component.DaggerMainActivityComponent;
import com.fwkj.fw_mvp_root.component.MainActivityModule;
import com.fwkj.fw_mvp_root.contract.MainActivityContract;
import com.fwkj.fw_mvp_root.presenter.MainActivityPresenter;
import com.fwkj.fw_root_library.BaseActivity;
import com.fwkj.fw_root_library.component.DelegateComponent;
import com.fwkj.fw_root_library.utils.LinearLayoutDecoration;
import com.fwkj.fw_root_library.widget.FTitle;
import com.gyf.immersionbar.ImmersionBar;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
public class MainActivity extends BaseActivity implements MainActivityContract.view {
@Inject
MainActivityPresenter mMainActivityPresenter;
private RecyclerView mRcy;
private FTitle mTitle;
@Override
public void initView(Bundle savedInstanceState) {
ImmersionBar.with(this).init();
mRcy = findViewById(R.id.rcy);
mTitle = findViewById(R.id.title);
mTitle.pullAnimator();
mMainActivityPresenter.getCode();
}
@Override
public void initEvent() {
mRcy.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
mRcy.addItemDecoration(new LinearLayoutDecoration(20, RecyclerView.VERTICAL));
HomeAdapter adapter = new HomeAdapter(R.layout.adapter_home);
List strings = new ArrayList<>();
strings.add("有对话框的请求");
strings.add("无对话框的请求");
strings.add("关闭标题对话");
adapter.setNewData(strings);
mRcy.setAdapter(adapter);
adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
switch (position) {
case 0:
mMainActivityPresenter.netDialog();
mMainActivityPresenter.getCode();
break;
case 1:
mMainActivityPresenter.noNetDialog();
break;
case 2:
mTitle.closePull();
break;
default:
}
}
});
}
@Override
public void initComponent(DelegateComponent component) {
DaggerMainActivityComponent.builder()
.delegateComponent(component)
.mainActivityModule(new MainActivityModule(this))
.build()
.inject(this);
}
@Override
public int initLayout() {
return R.layout.activity_mainactivity;
}
public class HomeAdapter extends BaseQuickAdapter<String, BaseViewHolder> {
public HomeAdapter(int layoutResId) {
super(layoutResId);
}
@Override
protected void convert(BaseViewHolder helper, String item) {
helper.setText(R.id.btn, item);
}
}
} | java | 16 | 0.654332 | 91 | 33.05 | 100 | starcoderdata |
'use strict';
QUnit.module('dependency-workers.js');
var results = [null, 'first result', 'second result'];
QUnit.test('Simple scenario without web workers', function(assert) {
var workers = new dependencyWorkers.DependencyWorkers(createSimpleInputRetreiver(assert));
var done = assert.async();
workers.startTaskPromise({keyProp:2}).then(function(result) {
assert.equal(result, results[2], 'Correctness of second task result');
done();
});
});
QUnit.test('SchedulerDependencyWorkers without web workers', function(assert) {
var workers = new dependencyWorkers.SchedulerDependencyWorkers(new dependencyWorkers.DependencyWorkersTaskScheduler(1), createSimpleInputRetreiver(assert));
var done = assert.async();
workers.startTaskPromise({keyProp:2}).then(function(result) {
assert.equal(result, results[2], 'Correctness of second task result');
done();
});
});
QUnit.test('Abort without dependent task', function(assert) {
var scheduler = new dependencyWorkers.DependencyWorkersTaskScheduler(1);
var dummyJobCallbacks;
scheduler.enqueueJob(function dummyJob(resource, jobContext, callbacks) {
dummyJobCallbacks = callbacks;
}, { calculatePriority: function() { return 1; } }); // Enqueue the single free slot so next jobs will hold
var priority = 1;
var done = assert.async(4);
var task2;
var workers = new dependencyWorkers.SchedulerDependencyWorkers(scheduler, {
taskStarted: function(task) {
switch (task.key.keyProp) {
case 1: task.dataReady(results[1], 1);
break;
case 2: task2 = task;
break;
case 3: assert.equal(task.key.keyProp, 3, 'taskKey should be 1, 2 or 3');
task.registerTaskDependency({keyProp: 1});
task.registerTaskDependency({keyProp: 2});
break;
}
task.on('dependencyTaskData', function() {
assert.fail('Data not expected to be returned as job expected to be aborted');
});
task.on('custom', function(eventName) {
if (eventName === 'aborting') {
done();
}
});
},
getWorkerTypeOptions: function(taskType) {
if (taskType !== 1 && taskType !== 2) {
assert.equal(taskType, 3, 'taskType should be 1, 2 or 3');
}
// Return non-null worker props so will not be recognized as no-worker-needed
// and then the scheduler will be bypassed. However the worker props will never
// be used because task is aborted before scheduling
return {};
},
getKeyAsString: function(key) {
return key.keyProp;
}
});
var taskContext = workers.startTask({keyProp:3}, {
onData: assert.fail,
onTerminated: function(isAborted) {
assert.equal(isAborted, true, 'Task expected to abort');
done();
},
priorityCalculator: function() { return priority; }
});
priority = -1;
dummyJobCallbacks.jobDone();
});
function createSimpleInputRetreiver(assert) {
return {
taskStarted: function(task) {
if (task.key.keyProp === 1) {
task.dataReady(results[1], 1);
task.terminate();
} else {
assert.equal(task.key.keyProp, 2, 'taskKey should be 1 or 2');
task.registerTaskDependency({keyProp: 1});
task.on('allDependTasksTerminated', function() {
assert.equal(task.dependTaskResults.length, 1, 'dependTaskResults of second task should be of length 1');
assert.equal(task.dependTaskResults[0], results[1], 'dependTaskResults[0] of second task should be the result of first task');
task.dataReady(results[2], 2);
task.terminate();
});
}
},
getWorkerTypeOptions: function(taskType) {
if (taskType !== 1) {
assert.equal(taskType, 2, 'taskType should be 1 or 2');
}
return null;
},
getKeyAsString: function(key) {
return key.keyProp;
}
}
} | javascript | 24 | 0.574145 | 160 | 38.097345 | 113 | starcoderdata |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace NextGenSoftware.OASIS.API.Providers.EOSIOOASIS.Entities.DTOs.GetBlock
{
public class GetBlockHeaderResponseDto
{
[JsonProperty("timestamp")]
public DateTime Timestamp { get; set; }
[JsonProperty("producer")]
public string Producer { get; set; }
[JsonProperty("confirmed")]
public int Confirmed { get; set; }
[JsonProperty("previous")]
public string Previous { get; set; }
[JsonProperty("transaction_mroot")]
public string TransactionMroot { get; set; }
[JsonProperty("action_mroot")]
public string ActionMroot { get; set; }
[JsonProperty("schedule_version")]
public int ScheduleVersion { get; set; }
[JsonProperty("new_producers")]
public GetBlockNewProducersResponseDto NewProducers { get; set; }
[JsonProperty("header_extensions")]
public List HeaderExtensions { get; set; }
[JsonProperty("new_protocol_features")]
public List NewProtocolFeatures { get; set; }
[JsonProperty("producer_signature")]
public string ProducerSignature { get; set; }
[JsonProperty("transactions")]
public List Transactions { get; set; }
[JsonProperty("block_extensions")]
public List BlockExtensions { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("block_num")]
public int BlockNum { get; set; }
[JsonProperty("ref_block_prefix")]
public int RefBlockPrefix { get; set; }
}
} | c# | 11 | 0.639723 | 92 | 29.403509 | 57 | starcoderdata |
package com.example.administrator.gobang;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
/**
* User: Administrator
* Time: 2016/5/6 21:00 00
* Annotation:
*/
public class GobangPanel extends View {
private int mPanelWidth;
private float mLineHeight;
private int MAX_LINE = 10;
public boolean mIsGameOver;
public boolean mIsWhiteWinner;
private Paint mPaint = new Paint ();
private Bitmap mWhitePiece;
private Bitmap mBlackPiece;
private float radioPieceOfLineHeight = 3 * 1.0f / 4;//控制棋子的大小的比例
private boolean mIsWhite = true;//判定黑白棋那一个该下,白棋先手
private ArrayList mWhiteArray = new ArrayList<> ();//储存白棋坐标
private ArrayList mBlackArray = new ArrayList<> ();//储存黑棋坐标
private OnGameOverListener mOnGameOverListener;
public void setOnGameOverListener(OnGameOverListener mOnGameOverListener)
{
this.mOnGameOverListener = mOnGameOverListener;
}
public GobangPanel (Context context, AttributeSet attrs) {
super (context, attrs);
init ();
}
public void init () {
mPaint.setColor (0x88000000);//灰色,半透明
mPaint.setAntiAlias (true);//抗锯齿
mPaint.setDither (true);//??
mPaint.setStyle (Paint.Style.STROKE);//画线
mWhitePiece = BitmapFactory.decodeResource (getResources (), R.drawable.stone_w2);
mBlackPiece = BitmapFactory.decodeResource (getResources (), R.drawable.stone_b1);
}
//捕获用户手势
@Override
public boolean onTouchEvent (MotionEvent event) {
if (mIsGameOver) {
return false;
}
int action = event.getAction ();
if(action == MotionEvent.ACTION_UP) {
int x = (int) event.getX ();
int y = (int) event.getY ();
Point p = getValidPoint(x, y);
//判断当前点是否已经有棋子了
if (mWhiteArray.contains (p) || mBlackArray.contains (p)) {
return false;
}
if(mIsWhite) {
mWhiteArray.add (p);
}else {
mBlackArray.add (p);
}
invalidate ();//请求重绘,
mIsWhite = !mIsWhite;
}
return true;
}
//让棋子落在精确的坐标上
public Point getValidPoint (int x, int y) {
return new Point ((int)(x / mLineHeight), (int)(y / mLineHeight));
}
@Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode (widthMeasureSpec);
int heightSize = MeasureSpec.getSize (heightMeasureSpec);
int heightMode = MeasureSpec.getMode (heightMeasureSpec);
int width = Math.min (widthSize, heightSize);
//当width等于0时,为了防止视图不显示,所以改变最小值
if(widthMode == MeasureSpec.UNSPECIFIED) {
width = heightSize;
}else if (heightMode == MeasureSpec.UNSPECIFIED){
width = widthSize;
}
setMeasuredDimension (width, width);
}
//当宽高确定后,值被改变时,调用
//关于尺寸的编写
@Override
protected void onSizeChanged (int w, int h, int oldw, int oldh) {
super.onSizeChanged (w, h, oldw, oldh);
mPanelWidth = w;
mLineHeight = mPanelWidth * 1.0f / MAX_LINE;
int pieceWidth = (int) (mLineHeight * radioPieceOfLineHeight);
mWhitePiece = Bitmap.createScaledBitmap (mWhitePiece, pieceWidth, pieceWidth, false);
mBlackPiece = Bitmap.createScaledBitmap (mBlackPiece, pieceWidth, pieceWidth, false);
}
//绘制棋盘
@Override
protected void onDraw (Canvas canvas) {
super.onDraw (canvas);
drawBoard (canvas);
drawPieces (canvas);
checkGameOver ();
checkTie();
}
private void checkTie () {
if(mBlackArray.size () + mWhiteArray.size () >= MAX_LINE * MAX_LINE) {
if (mOnGameOverListener != null) {
mOnGameOverListener.onGameTie ();
}
}
}
private void checkGameOver () {
boolean whiteWin = GobangJudge.checkFiveInLine (mWhiteArray);
boolean blackWin = GobangJudge.checkFiveInLine (mBlackArray);
if(whiteWin || blackWin) {
mIsGameOver = true;
mIsWhiteWinner = whiteWin;
if(mOnGameOverListener != null) {
mOnGameOverListener.onGameWin (mIsWhiteWinner);
}
String text = mIsWhiteWinner ? "白棋胜" : "黑棋胜" ;
}
}
public void drawPieces (Canvas canvas) {
for(int i = 0, n = mWhiteArray.size (); i < n; i++) {
Point whitePoint = mWhiteArray.get (i);
canvas.drawBitmap (mWhitePiece,
(whitePoint.x + (1 - radioPieceOfLineHeight) / 2) * mLineHeight,
(whitePoint.y + (1 - radioPieceOfLineHeight) / 2) * mLineHeight,
null);
}
for(int i = 0, n = mBlackArray.size (); i < n; i++) {
Point blackPoint = mBlackArray.get (i);
canvas.drawBitmap (mBlackPiece,
(blackPoint.x + (1 - radioPieceOfLineHeight) / 2) * mLineHeight,
(blackPoint.y + (1 - radioPieceOfLineHeight) / 2) * mLineHeight,
null);
}
}
public void drawBoard (Canvas canvas) {
int w = mPanelWidth;
float lineHeight = mLineHeight;
for(int i = 0; i < MAX_LINE; i++) {
//画棋盘的横线
int startX = (int)(lineHeight / 2);
int endX = (int)(w - lineHeight / 2);
int y = (int) ((0.5 + i) * lineHeight);
canvas.drawLine (startX, y, endX, y, mPaint);
//画棋盘的纵线
int startY = (int)(lineHeight / 2);
int endY = (int)(w - lineHeight / 2);
int x = (int) ((0.5 + i) * lineHeight);
canvas.drawLine (x, startY, x, endY, mPaint);
}
}
public void restart() {
mWhiteArray.clear ();
mBlackArray.clear ();
mIsGameOver = false;
mIsWhiteWinner = false;
invalidate ();
}
public static final String INSTANCE = "instance";
public static final String INSTANCE_GAME_OVER = "instance_game_over";
public static final String INSTANCE_WHITE_ARRAY = "instance_white_array";
public static final String INSTANCE_BLACK_ARRAY = "instance_black_array";
@Override
protected Parcelable onSaveInstanceState () {
Bundle bundle = new Bundle ();
bundle.putParcelable (INSTANCE, super.onSaveInstanceState ());
bundle.putBoolean (INSTANCE_GAME_OVER, mIsGameOver);
bundle.putParcelableArrayList (INSTANCE_WHITE_ARRAY, mWhiteArray);
bundle.putParcelableArrayList (INSTANCE_BLACK_ARRAY, mBlackArray);
return bundle;
}
@Override
protected void onRestoreInstanceState (Parcelable state) {
if(state instanceof Bundle) {
Bundle bundle = (Bundle) state;
mIsGameOver = bundle.getBoolean (INSTANCE_GAME_OVER);
mWhiteArray = bundle.getParcelableArrayList (INSTANCE_WHITE_ARRAY);
mBlackArray = bundle.getParcelableArrayList (INSTANCE_BLACK_ARRAY);
super.onRestoreInstanceState (bundle.getParcelable (INSTANCE));
return ;
}
super.onRestoreInstanceState (state);
}
/**
* 悔棋功能
*/
public void regret()
{
if(mIsWhiteWinner)
{
if(mBlackArray.size() > 0)
{
mBlackArray.remove(mBlackArray.size() - 1);
mIsWhiteWinner = !mIsWhiteWinner;
}
}
else
{
if(mWhiteArray.size() > 0)
{
mWhiteArray.remove(mWhiteArray.size() - 1);
mIsWhiteWinner = !mIsWhiteWinner;
}
}
invalidate ();
}
} | java | 14 | 0.593962 | 93 | 29.435424 | 271 | starcoderdata |
/**
* 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.
*
* 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.
*/
/**
* 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 io.journalkeeper.core.state;
import java.net.URI;
import java.util.List;
import java.util.Map;
/**
* @author LiYue
* Date: 2019/11/21
*/
public class PersistInternalState {
private URI preferredLeader = null;
private Map<Integer /* partition */, Long /* lastIncludedIndex of the partition */> partitionIndices;
private long lastIncludedIndex;
private int lastIncludedTerm;
private List configNew;
private List configOld;
private boolean jointConsensus;
private long configEpoch = ConfigState.EPOCH_UNKNOWN;
private long minOffset;
private long snapshotTimestamp;
public long getConfigEpoch() {
return configEpoch;
}
public void setConfigEpoch(long configEpoch) {
this.configEpoch = configEpoch;
}
public URI getPreferredLeader() {
return preferredLeader;
}
public void setPreferredLeader(URI preferredLeader) {
this.preferredLeader = preferredLeader;
}
public Map<Integer, Long> getPartitionIndices() {
return partitionIndices;
}
public void setPartitionIndices(Map<Integer, Long> partitionIndices) {
this.partitionIndices = partitionIndices;
}
public long getLastIncludedIndex() {
return lastIncludedIndex;
}
public void setLastIncludedIndex(long lastIncludedIndex) {
this.lastIncludedIndex = lastIncludedIndex;
}
public int getLastIncludedTerm() {
return lastIncludedTerm;
}
public void setLastIncludedTerm(int lastIncludedTerm) {
this.lastIncludedTerm = lastIncludedTerm;
}
public List getConfigNew() {
return configNew;
}
public void setConfigNew(List configNew) {
this.configNew = configNew;
}
public List getConfigOld() {
return configOld;
}
public void setConfigOld(List configOld) {
this.configOld = configOld;
}
public boolean isJointConsensus() {
return jointConsensus;
}
public void setJointConsensus(boolean jointConsensus) {
this.jointConsensus = jointConsensus;
}
InternalState toInternalState() {
ConfigState configState;
if (isJointConsensus()) {
configState = new ConfigState(configOld, configNew, configEpoch);
} else {
configState = new ConfigState(configNew, configEpoch);
}
InternalState internalState = new InternalState();
internalState.setConfigState(configState);
internalState.setPartitionIndices(getPartitionIndices());
internalState.setPreferredLeader(getPreferredLeader());
internalState.setLastIncludedTerm(getLastIncludedTerm());
internalState.setLastIncludedIndex(getLastIncludedIndex());
internalState.setMinOffset(getMinOffset());
internalState.setSnapshotTimestamp(getSnapshotTimestamp());
return internalState;
}
PersistInternalState fromInternalState(InternalState internalState) {
ConfigState configState = internalState.getConfigState();
setJointConsensus(configState.isJointConsensus());
setConfigNew(configState.getConfigNew());
setConfigOld(configState.getConfigOld());
setConfigEpoch(configState.getEpoch());
setLastIncludedIndex(internalState.getLastIncludedIndex());
setLastIncludedTerm(internalState.getLastIncludedTerm());
setPartitionIndices(internalState.getPartitionIndices());
setPreferredLeader(internalState.getPreferredLeader());
setMinOffset(internalState.getMinOffset());
setSnapshotTimestamp(internalState.getSnapshotTimestamp());
return this;
}
public long getMinOffset() {
return minOffset;
}
public void setMinOffset(long minOffset) {
this.minOffset = minOffset;
}
public long getSnapshotTimestamp() {
return snapshotTimestamp;
}
public void setSnapshotTimestamp(long snapshotTimestamp) {
this.snapshotTimestamp = snapshotTimestamp;
}
@Override
public String toString() {
return "PersistInternalState{" +
"preferredLeader=" + preferredLeader +
", partitionIndices=" + partitionIndices +
", lastIncludedIndex=" + lastIncludedIndex +
", lastIncludedTerm=" + lastIncludedTerm +
", configNew=" + configNew +
", configOld=" + configOld +
", jointConsensus=" + jointConsensus +
", minOffset=" + minOffset +
", snapshotTimestamp=" + snapshotTimestamp +
'}';
}
} | java | 26 | 0.687412 | 105 | 32.489474 | 190 | starcoderdata |
#pragma once
#include
#include
// no free
template <typename T>
struct SimpleTypeAllocator {
struct ChunkT {
int n;
std::unique_ptr<unsigned char> values;
explicit ChunkT(size_t size) : n(0), values(new unsigned char[sizeof(T) * size]) {
}
};
int chunkSize;
std::stack chunks;
explicit SimpleTypeAllocator(int chunkSize) : chunkSize(chunkSize) {
}
~SimpleTypeAllocator() {
}
T* allocate() {
if (chunks.empty() || chunks.top()->n >= chunkSize)
chunks.push(std::make_unique
return reinterpret_cast + sizeof(T) * chunks.top()->n++);
}
template <typename... Args>
T* construct(Args&&... args) {
return ::new (allocate()) T(std::forward
}
void destroy(T* obj) {
obj->~T();
}
}; | c | 17 | 0.575269 | 96 | 21.682927 | 41 | starcoderdata |
class GUI: public DrawableComp
{
friend class Scene;
friend class GUIOperateHandler;
public:
GUI(int x, int y, int textureNum, const char* imgFile, Canvas* canvas = NULL);
GUI(int x, int y, int drawIndex, Canvas* canvas = NULL); //for textureNum == 1, used by Lable
GUI(int textureNum, const char* imgFile, Canvas* canvas = NULL);
//full version
//picture mode
GUI(const char* name, int x, int y, int drawIndex,
int textureNum, const char* imgFile, steg::Canvas* canvas);
//color mode
GUI(const char* name, int x, int y, int drawIndex,
SDL_Point picSize, SDL_Color color, float transparency, steg::Canvas* canvas);
//get color picture
GUI(int x, int y, SDL_Point picSize, SDL_Color color, float transparency, Canvas* canvas = NULL); //make a copy of color
~GUI();
bool IsSelectable();
bool IsSelected();
virtual void SetExtraTrans(float extraTrans);
virtual float GetExtraTrans();
SDL_Point GetDrawSize();
SDL_Point GetEntireSize();
void ResetFollowingCanvas(Canvas* newFollowingCanvas);
protected:
// GUILayer layer; //smaller number is drawn first
int drawIndex; //the order to be drawn in a canvas, smaller number is drawn first
SDL_Color* color = NULL; //是否为NULL,以和无texture的gui区别开来
SDL_Point colorTextureSize = SDL_Point{0, 0};
float colorTextureTransparency = 1.0f;
SDL_Point drawSize;
SDL_Point entireSize;
SDL_Point sourceStartPoint;
float extraTrans; //extra transparency apply to RenderCopy, inner use, from 0.0 to 1.0
Uint8 textureAlpha;
bool selectable;
bool selected;
virtual DBG_Status HandleEvent(SDL_Event event);
virtual DBG_Status InitInScene(Scene *scene);
virtual DBG_Status DumpOutOfScene();
virtual DBG_Status Update(Uint32 deltTick);
virtual SDL_Rect GetAbsDestRect(int* x = NULL, int* y = NULL, int* w = NULL, int* h = NULL);
virtual SDL_Rect CutSrcRect(SDL_Rect srcRect, SDL_Point destSize); //裁剪sourceRect以适应destRect
// virtual DBG_Status LoadTexture();
virtual DBG_Status OnSelected();
virtual DBG_Status OnUnSelected();
private:
bool lastVisible = false;
//this followingCanvas is used in Update() to set extra transparency
//by default, the followingCanvas is the attachedPlatform
//but for scroll bar's components, their followingCanvas should be the canvas controled by the scroll bar
//rather than their attachedPlatform
DrawableComp* followingCanvas = NULL;
} | c | 10 | 0.698576 | 126 | 33.175676 | 74 | inline |
namespace Securo.GlobalPlatform.Model
{
public class ScpInfo
{
public byte ScpIdentifier { get; set; }
public byte ImplementationOptions {get;set;}
}
} | c# | 8 | 0.655556 | 52 | 21.625 | 8 | starcoderdata |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller{
public function __construct(){
parent::__construct();
//echo "This is initialisation
$this->load->model("Login_model");
}
public function index(){
//echo "hello this is index function"
$data=array(
'title' => "HOME",
'page'=>"home_view.php"
);
// echo "you have successfully logged-in
//print_r($this->input->post());
//$this->load->view('template',$data);
}
public function one(){
$data=array(
'title' => "HOME",
'page'=>"home_view.php"
//'page'=>"admin.php"
);
if(isset($_SESSION['officer_id'])){
$id=$this->get_officers($_SESSION["officer_id"]);
// print_r($id);
$_SESSION['id']=$id[0][0]['id'];
if(!empty($id[1])){
//this imply form has been submitted
echo "variable set is set";
$data['set']=$id[1];
$data['value']=$id[2][0];
//retrieving the data
//$this->
}
}
//$this->load->helper('form');
$data['page']=$this->display($data['page']);
//echo "hello";
$this->load->view('template',$data);
//echo "hello this is one
// echo "helo these are the parameters : $p1, $p2";
}
public function display($page){
/* uncomment to restrict visting officers link directly
*/
if ($this->session->userdata('officer_id'))
return $page;
else{
$page="login_view.php";
return $page;
}
}
public function two(){
$data=array(
'title' => "HOME",
'page'=>"home_report.php"
);
//echo "success reporting officer";
$data['page']=$this->display($data['page']);
$this->load->view('template',$data);
}
public function three(){
$data=array(
'title' => "HOME",
'page'=>"home_review.php"
);
//echo "success revewing officer";
$data['page']=$this->display($data['page']);
$this->load->view('template',$data);
}
public function new_insert(){
// validation of some input fields
$_POST['id']=$this->session->userdata('id');
$_POST['set']=1;
//print_r($_POST);
$config=array(
array(
'field' => 'fname',
'label' => 'Name',
'rules' => 'required|alpha',
'errors' => array(
'required' => 'You have not provided %s.'
)
),
array(
'field' => 'lname',
'label' => 'Name',
'rules' => 'alpha',
),
array(
'field' => 'description',
'label' => 'Description',
'rules' => 'alpha_dash|alpha_numeric_spaces'
),
array(
'field' => 'target[]',
'label' => 'TARGET',
'rules' => 'alpha_dash|alpha_numeric_spaces'
),
array(
'field' => 'achievement[]',
'label' => 'ACHIEVEMENTS',
'rules' => 'alpha_dash|alpha_numeric_spaces'
),
array(
'field' => 'shortfalls',
'label' => 'shortfalls',
'rules' => 'alpha_dash|alpha_numeric_spaces'
),
array(
'field' => 'higher_achievement',
'label' => 'HIGHER ACHIEVEMENTS',
'rules' => 'alpha_dash|alpha_numeric_spaces'
)
);
$this->form_validation->set_rules($config);
$this->form_validation->set_rules('description','Description','alpha_dash|alpha_numeric_spaces');
if($this->form_validation->run() == FALSE){
$data['errors']= validation_errors();
print_r($data['errors']);
}
else{
echo "your form has been sent";
$this->Login_model->insert_personaldatas($_POST);
echo "your response has been recorded";
$_SESSION['personal_datas']=1;
redirect('home/one');
}
}
public function get_officers($officer_id){
$id[0]=$this->Login_model->get_id($officer_id);
// print_r($id[0]);
// echo "
$id[1]=$this->Login_model->checkset($id[0][0]['id']);
// print_r($id[1]);
// echo "
$id[2]=$this->Login_model->get_personaldatas($id[0][0]['id']);
// print_r($id[2]);
// echo "
// print_r($id[2]);
return $id;
}
public function admin(){
$q=$this->db->get();
}
}
?> | php | 15 | 0.466333 | 103 | 28.072727 | 165 | starcoderdata |
#!/usr/bin/python
# Copyright (c) 2013, 2014-2017 Oracle and/or its affiliates. All rights reserved.
DOCUMENTATION = '''
---
module: oc
short_description: OC External Inventory Script
description:
Generates inventory that Ansible can understand by making API requests
Oracle Public Cloud Compute via a python client used to call the OPC REST services.
When run against a specific host, this script returns the following variables
based on the data obtained from the Python REST client:
- opc_name
- opc_id
- opc_status
- opc_shape
- opc_image
- opc_description
- opc_platform
- opc_uuid
- opc_private_ip
- opc_public_ip
- opc_nat
- opc_seclists
- opc_tags
- opc_vcable
- opc_zone
- opc_instance_orchestration
- ansible_ssh_host
When run in --list mode, instances are grouped by the following categories:
- region:
region where the current service is located, i.e. us2, em2, em3
- zone:
zone group name examples are z26, z26 etc. Zones are bounded to regions
- instance tags:
An entry is created for each tag. For example, if you have two instances
with a common tag called 'foo', they will both be grouped together under
the 'tag_foo' name.
- shape
types follow based on the shape, like OC1, OC3, OC1M
- running status:
group name prefixed with 'status_' (e.g. status_running, status_stopped,..)version_added: ""
options:
action:
description:
- Action to be executed against the oracle cloud object
required: false
default: list
choices: ['create', 'list', 'update', 'delete']
endpoint:
description:
- Oracle Cloud Endpoint
required: true
default: null
user:
description:
- Oracle cloud user only required is cookie is not present.
required: false
default: null
password:
description:
- Oracle cloud password only required is cookie is not present.
required: false
default: null
cookie:
description:
- Oracle cloud authentication cookie.
required: false
default: null
resourcename:
description:
- Resource name associated with object we are working with.
required: false
default: null
requirements: [oraclecomputecloud]
author: " / (Oracle Cloud Solutions A-Team)"
notes:
- Simple notes
...
'''
EXAMPLES = '''
Execute uname on all instances in your domain which are in running state
$ ansible -i oc.py status_running -m shell -a "/bin/uname -a"
Use the OPC inventory script to print out instance specific information
$ contrib/inventory/oc.py --host my_instance
'''
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
__author__ = " (Oracle Cloud Solutions A-Team)"
__copyright__ = "Copyright (c) 2013, 2014-2017 Oracle and/or its affiliates. All rights reserved."
__ekitversion__ = "@VERSION@"
__ekitrelease__ = "@RELEASE@"
__version__ = "1.0.0.0"
__date__ = "@BUILDDATE@"
__status__ = "Development"
__module__ = "oc"
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
__requires__ = ['pycrypto>=2.6']
try:
import pkg_resources
except ImportError:
# Use pkg_resources to find the correct versions of libraries and set
# sys.path appropriately when there are multiversion installs. We don't
# fail here as there is code that better expresses the errors where the
# library is used.
pass
USER_AGENT_PRODUCT="Ansible-oc_inventory_plugin"
USER_AGENT_VERSION="v1"
import sys
import os
import argparse
import ConfigParser
from time import time
try:
import json
except ImportError:
import simplejson as json
class OCInventory(object):
def _empty_inventory(self):
return {"_meta": {"hostvars": {}}}
def __init__(self, refresh_cache=False):
# Initialise empty inventory
self.inventory = self._empty_inventory()
# Read settings and parse args
self.parse_cli_args()
self.read_settings()
# Get REST Connection Driver
self.driver = Driver()
# Initialise data
data_to_print = {}
# Refresh Cache if stale
if refresh_cache:
self.do_api_calls_update_cache()
elif self.args.refresh_cache:
self.do_api_calls_update_cache()
elif not self.is_cache_valid():
self.do_api_calls_update_cache() | python | 11 | 0.616901 | 99 | 28.967532 | 154 | starcoderdata |
@SuppressWarnings(value = "unchecked")
@Override
protected void addTo(List collection, String key, Object value) {
int index = Integer.parseInt(key);
int size = collection.size();
// in case the key doesn't come in sorted order
if (collection.size() <= index) {
for (int i = 0; i < index - size + 1; i++)
collection.add(null);
}
collection.set(index, value);
} | java | 9 | 0.593897 | 68 | 34.583333 | 12 | inline |
public int[] sampleJ(int u, int i, int j) {
int[] sampleTriple = new int[4];
sampleTriple[0] = u;
sampleTriple[1] = i;
sampleTriple[2] = j;
boolean item_is_positive = data.boolMatrix.getBool(u,i);
if (item_is_positive == false) System.err.println("This error should never happen!");
do
// get another random as long as it was at least once bought
sampleTriple[2] = random.nextInt(numItems);
while (data.boolMatrix.getBool(u,sampleTriple[2]) == item_is_positive);
// set xscale
sampleTriple[3] = 1;
return sampleTriple;
} | java | 9 | 0.660808 | 87 | 31.588235 | 17 | inline |
package com.digital.builditbigger.api;
import android.test.AndroidTestCase;
public class JokeAsyncTaskNullTest extends AndroidTestCase {
public void test() {
try {
JokeAsyncTask endpointsAsyncTask = new JokeAsyncTask(new OnJokeReceiveListener() {
@Override
public void onGetJoke(String joke) {
assertNotNull(joke);
}
});
endpointsAsyncTask.execute();
} catch (Exception e) {
fail(e.getMessage());
}
}
} | java | 16 | 0.652108 | 134 | 25.6 | 25 | starcoderdata |
import numpy as np
from ..utils import get_g
class IndirectBias():
""" The class for computing indirect bias between a pair of words.
"""
def __init__(self, E, g=None):
"""
Args:
E (WE class object): Word embeddings object.
kwargs:
g (np.array): Gender direction.
"""
if g is None:
g = get_g(E)
assert len(g) == E.dim
self.g = g
self.E = E
def _pair_idb(self, w, v, g):
"""
Args:
w (np.array): The first word vector.
v (np.array): The second word vector.
g (np.array): Gender direction.
Returns:
idb (float): The indirect bias between the embeddings of
`w` and `v`.
"""
w_orth = w - (np.dot(w, g)) * g
v_orth = v - (np.dot(v, g)) * g
dots = np.dot(w, v)
orth_dots = np.dot(w_orth, v_orth)
idb = (dots - orth_dots / (np.linalg.norm(w_orth) * np.linalg.norm(v_orth))) / (dots )
return idb
def fix(self, w, eps=1e-3):
"""
Args:
w (np.array): word vector
kwargs:
eps (float): threshold. If the difference between the norm
of `w` and 1, is greater than `eps`. Then
normalize `w`.
Returns:
The normalized `w`.
"""
norm = np.linalg.norm(w)
if np.abs(norm - 1) > eps:
w /= norm
return w
def compute(self, w, v):
"""
Args:
w (str): One of a pair of words.
v (str): The other word from the pair.
Returns:
The indirect bias between the embeddings of `w` and `v`.
"""
if isinstance(w, str): w = self.E.v(w)
if isinstance(v, str): v = self.E.v(v)
w = self.fix(w)
v = self.fix(v)
return self._pair_idb(w, v, self.g) | python | 16 | 0.45222 | 94 | 27.383562 | 73 | starcoderdata |
namespace transforms {
using block_graph::BlockGraph;
using block_graph::TransformPolicyInterface;
using block_graph::transforms::NamedBlockGraphTransformImpl;
// A PE BlockGraph transform for adding/updating the a debug directory entry
// of a given type.
class AddDebugDirectoryEntryTransform
: public NamedBlockGraphTransformImpl<AddDebugDirectoryEntryTransform> {
public:
// Configures this transform.
//
// @param type the type of the debug directory entry to search for.
// @param always_add if this is true a new debug directory entry will always
// be created, otherwise a new one will be created only if none already
// exists.
AddDebugDirectoryEntryTransform(DWORD type, bool always_add)
: type_(type), always_add_(always_add), added_(false), block_(NULL),
offset_(-1) {
}
// Adds or finds the debug data directory of the given type.
//
// @param policy The policy object restricting how the transform is applied.
// @param block_graph The block graph to transform.
// @param dos_header_block The DOS header block of the block graph.
// @returns true on success, false otherwise.
virtual bool TransformBlockGraph(
const TransformPolicyInterface* policy,
BlockGraph* block_graph,
BlockGraph::Block* dos_header_block) OVERRIDE;
// Returns true if a new debug directory entry was created.
bool added() const { return added_; }
// Access the block containing the found or created debug directory entry.
//
// @returns the block housing the debug directory entry.
BlockGraph::Block* block() const { return block_; }
// Access the offset of the found or created debug directory entry.
//
// @returns the offset into the block of the debug directory entry.
BlockGraph::Offset offset() const { return offset_; }
// The transform name.
static const char kTransformName[];
private:
// The type of the debug directory entry to find or add.
DWORD type_;
// If this is true a new debug directory entry will always be added, even if
// there exists another one.
bool always_add_;
// These member variables hold state after the transform has been applied.
// Indicates if a new directory entry was added.
bool added_;
// Stores the block housing the debug data directory entries.
BlockGraph::Block* block_;
// Stores the offset into the block of the found or created debug data
// directory entry.
BlockGraph::Offset offset_;
DISALLOW_COPY_AND_ASSIGN(AddDebugDirectoryEntryTransform);
};
} | c | 13 | 0.727813 | 78 | 35.071429 | 70 | inline |
package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.hardware.Gamepad;
public class MechEthan implements MechOperator
{
//TODO find actual limits
private final int LIFT_LOWER_LIMIT = 0;
private final int LIFT_UPPER_LIMIT = 500;
//TODO find actual limits
private final int EXTEND_LOWER_LIMIT = 0;
private final int EXTEND_UPPER_LIMIT = 1000;
private Gamepad gamepad;
private boolean yTracker;
private boolean isIntakeDeployed;
public MechEthan(Gamepad gamepad)
{
this.gamepad = gamepad;
yTracker = false;
isIntakeDeployed = true;
}
@Override
public int liftPosition()
{
return (int)(-gamepad.left_stick_y * LIFT_UPPER_LIMIT);
}
@Override
public int extendPosition()
{
return (int)(-gamepad.right_stick_y * LIFT_UPPER_LIMIT);
}
@Override
public boolean runIntake()
{
return gamepad.b;
}
@Override
public boolean reverseIntake()
{
return false;
}
@Override
public int tiltIntakePosition()
{
return 0;
}
} | java | 11 | 0.633126 | 64 | 18.701754 | 57 | starcoderdata |
"use strict";
class AbstractFramePlayer {
constructor(src, element,offset,videoChunkSize) {
this.onTimeUpdates = [];
}
static newFramePlayer(element, options,offset,videoChunkSize) {
if (options.images)
return new ImageFramePlayer(options.images, element,offset,videoChunkSize);
else throw new Error("Unknown Frame Player specified - [" + type + "], currently only support 'video' and 'image'");
}
get videoWidth() {
return 0;
}
get videoHeight() {
return 0;
}
get duration() {
return 0;
}
get currentTime() {
return 0;
}
set currentTime(val) {
}
get paused() {
return false
}
pause() {
}
play() {
}
rewindStep() {}
/**
* Events:
* - playing
* - pause
* - loadedmetadata
* - abort
* - timeupdate
* - buffering
*/
onPlaying(callback) {}
onPause(callback) {}
onLoadedMetadata(callback) {}
onAbort(callback) {}
onBuffering(callback) {}
nextFrame() {}
previousFrame() {}
fit() {}
onTimeUpdate(callback) {
this.onTimeUpdates.push(callback);
}
triggerTimerUpdateHandler() {
this.triggerCallbacks(this.onTimeUpdates);
}
triggerCallbacks(handlers) {
for (var i = 0; i < handlers.length; i++) {
handlers[i]();
}
}
}
class ImageFramePlayer extends AbstractFramePlayer {
constructor(images, element,offset,videoChunkSize) {
super(images, element,offset,videoChunkSize);
// image list
$(element).imgplay({rate: 15, controls: false, pageSize: 100, center: true, onLoading: (isLoading) => {
if (this.onBuffering){
this.onBuffering(isLoading);
}
}});
this.offset = offset;
this.videoChunkSize = videoChunkSize;
this.imgPlayer = $(element).data('imgplay');
this.imgPlayer.toFrame(0);
this.onPauseHandlers = [];
this.onPlayingHandlers = [];
// hack but we don't want to trigger ready until we have frame 0 loaded and can read the height
var image = new Image();
image.onload = () => {
if (this.onLoadedMetadata) {
this.onLoadedMetadata();
this.hasInit = true;
}
var css = {
width: '100%'
};
$(element).css(css);
this.imgPlayer.fitCanvas();
this.imgPlayer.toFrame(0);
}
image.src = this.imgPlayer.frames[0].src;
}
get videoWidth() {
var dim = imgDimensions[this.imgPlayer.getCurrentFrame()];
return dim[0];
}
get videoHeight() {
var dim = imgDimensions[this.imgPlayer.getCurrentFrame()];
return dim[1];
}
get viewWidth() {
return this.imgPlayer.getDrawnWidth();
}
get viewHeight() {
return this.imgPlayer.getDrawnHeight();
}
get duration() {
//TODO figure out why -1 fixed the issue of having the imgplayer repeat the last picture
return this.imgPlayer.getTotalFrames()-1;
}
get currentTime() {
return this.imgPlayer.getCurrentFrame() + this.offset;
}
set currentTime(val) {
val = val - this.offset;
val = Math.min(this.duration, val);
val = Math.max(0, val);
this.imgPlayer.toFrame(Math.floor(val));
this.triggerTimerUpdateHandler();
}
get paused() {
return !this.imgPlayer.isPlaying();
}
pause() {
this.imgPlayer.pause();
this.triggerCallbacks(this.onPauseHandlers);
}
play() {
this.imgPlayer.play();
this.triggerCallbacks(this.onPlayingHandlers);
}
rewindStep() {
this.previousFrame();
}
nextFrame() {
this.currentTime = this.currentTime + 1
}
previousFrame() {
return this.currentTime = this.currentTime - 1;
}
fit() {
this.imgPlayer.fitCanvas();
}
/**
* Events:
* - playing
* - pause
* - loadedmetadata
* - abort
* - timeupdate
*/
onPlaying(callback) {
this.onPlayingHandlers.push(callback);
if (!this.paused && callback)
callback();
}
onPause(callback) {
this.onPauseHandlers.push(callback);
}
onLoadedMetadata(callback) {
this.onLoadedMetadata = callback;
if (this.hasInit)
callback();
}
onAbort(callback) {
this.onAbort = callback;
}
onBuffering(callback) {
this.onBuffering = callback;
}
}
void ImageFramePlayer;
void AbstractFramePlayer; | javascript | 17 | 0.553849 | 124 | 21.530806 | 211 | starcoderdata |
using System;
class HexadecimalToBinary
{
static void Main()
{
string hexNumber = Console.ReadLine();
char[] hexNumberCharArray = hexNumber.ToCharArray();
string[] hexNumberArray = new string[hexNumberCharArray.Length];
for (int i = 0; i < hexNumberCharArray.Length; i++)
{
hexNumberArray[i] = hexNumberCharArray[i].ToString();
}
for (int i = 0; i < hexNumberArray.Length; i++)
{
hexNumberArray[i]=ConvertToBase2(hexNumberArray[i]);
}
for (int i = 0; i < hexNumberArray.Length; i++)
{
Console.Write(hexNumberArray[i]);
}
Console.WriteLine();
}
static string ConvertToBase2(string hexNumber)
{
switch(hexNumber)
{
case "A":
hexNumber = "10"; break;
case "B":
hexNumber = "11"; break;
case "C":
hexNumber = "12"; break;
case "D":
hexNumber = "13"; break;
case "E":
hexNumber = "14"; break;
case "F":
hexNumber = "15"; break;
}
int intHexNumber = int.Parse(hexNumber);
string reversedBinary = "";
while (intHexNumber > 0)
{
reversedBinary += intHexNumber % 2;
intHexNumber = intHexNumber / 2;
}
char[] reversedBinaryArray = reversedBinary.ToCharArray();
Array.Reverse(reversedBinaryArray);
string binaryNumber = "";
for (int i = 0; i < reversedBinaryArray.Length; i++)
{
binaryNumber += reversedBinaryArray[i];
}
return binaryNumber;
}
} | c# | 15 | 0.509815 | 72 | 25.661538 | 65 | starcoderdata |
# Copyright (c) 2016 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from datetime import datetime
from decimal import Decimal
from numbers import Number
from typing import Any
import ipaddr
from psycopg2._range import DateTimeTZRange
from sqlalchemy import String, TypeDecorator, Integer, DateTime, literal
from sqlalchemy.dialects.postgresql import MACADDR, INET
from sqlalchemy.dialects.postgresql.ranges import TSTZRANGE
from pycroft.helpers.interval import Interval
from pycroft.helpers.net import mac_regex
from pycroft.model.exc import PycroftModelException
# NOTES
# In the type decorators below, `dialect` will be `sqlalchemy.dialects.postgresql.base.PGDialect`.
class _IPType(TypeDecorator):
impl = String(50)
cache_ok = True
def load_dialect_impl(self, dialect):
if dialect.name == 'postgresql':
return dialect.type_descriptor(INET)
else:
return dialect.type_descriptor(self.impl)
def process_bind_param(self, value, dialect):
if value is None:
return value
return str(value)
class IPAddress(_IPType):
def python_type(self):
return ipaddr._BaseIP
def process_result_value(self, value, dialect):
if value is None:
return value
return ipaddr.IPAddress(value)
class IPNetwork(_IPType):
def python_type(self):
return ipaddr._BaseNet
def process_result_value(self, value, dialect):
if value is None:
return value
return ipaddr.IPNetwork(value)
class MACAddress(TypeDecorator):
impl = String(10)
cache_ok = True
def load_dialect_impl(self, dialect):
if dialect.name == 'postgresql':
return dialect.type_descriptor(MACADDR)
else:
return dialect.type_descriptor(self.impl)
def process_result_value(self, value, dialect):
if dialect.name == 'postgresql':
return value
return "{}:{}:{}:{}:{}:{}".format(value[0:2], value[2:4], value[4:6],
value[6:8], value[8:10], value[10:12])
def process_bind_param(self, value, dialect):
if value is None:
return value
m = mac_regex.match(value)
if m is None:
raise ValueError(f'"{value}" is not a valid MAC address.')
groups = m.groupdict()
return "".join((groups["byte1"], groups["byte2"], groups["byte3"],
groups["byte4"], groups["byte5"], groups["byte6"]))
def python_type(self):
return str
class Money(TypeDecorator):
impl = Integer
cache_ok = True
def python_type(self):
return Decimal
@staticmethod
def process_bind_param(value, dialect):
if not isinstance(value, Number):
raise ValueError("{} is not a valid money amount".format(
repr(value)))
cents = Decimal(value).scaleb(2)
if int(cents) != cents:
raise ValueError("{} is not a valid money amount".format(
Decimal(value)))
else:
return int(cents)
@staticmethod
def process_result_value(value, dialect):
return Decimal(value).scaleb(-2)
class TsTzRange(TypeDecorator):
impl = TSTZRANGE
cache_ok = True
def python_type(self):
return Interval
def process_literal_param(self, value, dialect):
if value is None:
return None
return f"'{str(value)}'"
def process_bind_param(self, value: Interval | None, dialect) -> str | None:
# gets PY TYPE, returns DB TYPE
if value is None:
return None
return str(value)
def process_result_value(self, value: DateTimeTZRange | None, dialect)\
-> Interval | None:
if value is None:
return None
if not isinstance(value, DateTimeTZRange):
# see https://github.com/sqlalchemy/sqlalchemy/discussions/6942
raise PycroftModelException(
f"Unable to deserialize TsTzRange value {value!r} of type {type(value)}."
" Usually, this value should've been deserialized by psycopg2 into a"
" DatetimeTzRange. Did you make a mistake in your query?"
" Note that you may have to use `cast(…, TsTzRange)` to let sqlalchemy know"
" of the return type –– even if you specified the type in `literal()` already!"
)
return Interval.from_explicit_data(value.lower, value.lower_inc,
value.upper, value.upper_inc)
class comparator_factory(TSTZRANGE.Comparator):
def contains(self, other: Any, **kwargs) -> None:
"""Provide the functionality of the `@>` operator for Intervals.
:param other: can be an interval, a tz-aware datetime,
or column-like sql expressions with these types.
If any `.contains()` call does not work, you can add support here.
"""
if other is None:
raise PycroftModelException('You cannot use `.contains()` with `null` (`None`)!')
op = self.op('@>', is_comparison=True)
if isinstance(other, datetime):
if not other.tzinfo:
raise PycroftModelException(
'You cannot use `.contains()` with a non-timezone-aware datetime'
f' ({other})!'
)
return op(literal(other, type_=DateTimeTz))
return op(other)
def overlaps(self, other: Any, **kwargs):
"""Provide the functionality of the `&&` operator for Intervals. """
if other is None:
raise PycroftModelException(
'You cannot use `.overlaps()`/`&` with `null` (`None`)!'
)
return self.op('&&', is_comparison=True)(other)
__and__ = overlaps
class InvalidMACAddressException(PycroftModelException, ValueError):
pass
class DateTimeTz(DateTime):
def __init__(self):
super().__init__(timezone=True) | python | 17 | 0.601404 | 98 | 31.811518 | 191 | starcoderdata |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the PyMVPA package for the
# copyright and license terms.
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
"""Unit tests for some Fx and Compound learners"""
import numpy as np
from mvpa2.testing import *
from mvpa2.base.learner import Learner, CompoundLearner, ChainLearner, CombinedLearner
from mvpa2.base.node import Node, CompoundNode, ChainNode, CombinedNode
from mvpa2.datasets.base import AttrDataset
class FxNode(Node):
def __init__(self, f, space="targets", pass_attr=None, postproc=None, **kwargs):
super(FxNode, self).__init__(space, pass_attr, postproc, **kwargs)
self.f = f
def _call(self, ds):
cp = ds.copy()
cp.samples = self.f(ds.samples)
return cp
class FxyLearner(Learner):
def __init__(self, f):
super(FxyLearner, self).__init__()
self.f = f
self.x = None
def _train(self, ds):
self.x = ds.samples
def _call(self, ds):
cp = ds.copy()
cp.samples = self.f(self.x)(ds.samples)
return cp
class CompoundTests(unittest.TestCase):
def test_compound_node(self):
data = np.asarray([[1, 2, 3, 4]], dtype=np.float_).T
ds = AttrDataset(data, sa=dict(targets=[0, 0, 1, 1]))
add = lambda x: lambda y: x + y
mul = lambda x: lambda y: x * y
add2 = FxNode(add(2))
mul3 = FxNode(mul(3))
assert_array_equal(add2(ds).samples, data + 2)
add2mul3 = ChainNode([add2, mul3])
assert_array_equal(add2mul3(ds), (data + 2) * 3)
add2_mul3v = CombinedNode([add2, mul3], "v")
add2_mul3h = CombinedNode([add2, mul3], "h")
assert_array_equal(add2_mul3v(ds).samples, np.vstack((data + 2, data * 3)))
assert_array_equal(add2_mul3h(ds).samples, np.hstack((data + 2, data * 3)))
def test_compound_learner(self):
data = np.asarray([[1, 2, 3, 4]], dtype=np.float_).T
ds = AttrDataset(data, sa=dict(targets=[0, 0, 1, 1]))
train = ds[ds.sa.targets == 0]
test = ds[ds.sa.targets == 1]
dtrain = train.samples
dtest = test.samples
sub = FxyLearner(lambda x: lambda y: x - y)
assert_false(sub.is_trained)
sub.train(train)
assert_array_equal(sub(test).samples, dtrain - dtest)
div = FxyLearner(lambda x: lambda y: x / y)
div.train(train)
assert_array_almost_equal(div(test).samples, dtrain / dtest)
div.untrain()
subdiv = ChainLearner((sub, div))
assert_false(subdiv.is_trained)
subdiv.train(train)
assert_true(subdiv.is_trained)
subdiv.untrain()
assert_raises(RuntimeError, subdiv, test)
subdiv.train(train)
assert_array_almost_equal(subdiv(test).samples, dtrain / (dtrain - dtest))
sub_div = CombinedLearner((sub, div), "v")
assert_true(sub_div.is_trained)
sub_div.untrain()
subdiv.train(train)
assert_true(sub_div.is_trained)
assert_array_almost_equal(
sub_div(test).samples, np.vstack((dtrain - dtest, dtrain / dtest))
)
def suite(): # pragma: no cover
return unittest.makeSuite(CompoundTests)
if __name__ == "__main__": # pragma: no cover
from . import runner
runner.run() | python | 14 | 0.573043 | 86 | 30.318584 | 113 | starcoderdata |
// Import express
const express = require("express");
// Import Product Controller
const {
getObjetPerduById,
getObjetsPerdus,
updateObjetPerdu,
updateObjetPerdubyId,
createObjetPerdu,
deleteObjetPerdu,
getObjetPerduByIdUser,
getObjetPerduByIdObjet
} = require("../controllers/objetperdu.controller");
// Init express router
const router = express.Router();
router.get('/objetsperdus/:longitude/:latitude/:rayon',getObjetsPerdus);
router.get('/objetsperdus/:id',getObjetPerduByIdObjet);
router.get('/objetsperdus/suggestions/:id',getObjetPerduById);
router.post('/objetsperdus', createObjetPerdu);
router.put('/objetsperdus/:id',updateObjetPerdu);
router.patch('/objetperdu/:id',updateObjetPerdubyId)
router.delete('/objetsperdus/:id', deleteObjetPerdu);
router.get('/objetsperdus/user/:id', getObjetPerduByIdUser);
module.exports= router; | javascript | 10 | 0.767465 | 114 | 26.833333 | 36 | starcoderdata |
package org.jmisb.api.klv.st0806.poiaoi;
import static org.testng.Assert.*;
import java.util.HashMap;
import java.util.Map;
import org.jmisb.api.common.KlvParseException;
import org.jmisb.api.klv.IKlvKey;
import org.jmisb.api.klv.IKlvValue;
import org.jmisb.api.klv.LoggerChecks;
import org.testng.annotations.Test;
/** Tests for the ST0806 POI LS. */
public class RvtPoiLocalSetTest extends LoggerChecks {
public RvtPoiLocalSetTest() {
super(RvtPoiLocalSet.class);
}
@Test
public void parseTag1() throws KlvParseException {
byte[] bytes = new byte[] {0x01, 0x02, 0x02, 0x04};
RvtPoiLocalSet poiLocalSet = new RvtPoiLocalSet(bytes, 0, bytes.length);
assertNotNull(poiLocalSet);
assertEquals(poiLocalSet.getTags().size(), 1);
checkPoiAoiNumberExample(poiLocalSet);
assertEquals(poiLocalSet.getDisplayableValue(), "516");
}
@Test
public void parseRequiredTags() throws KlvParseException {
final byte[] bytes =
new byte[] {
0x01,
0x02,
0x02,
0x04,
0x02,
0x04,
(byte) 0x85,
(byte) 0xa1,
(byte) 0x5a,
(byte) 0x39,
0x03,
0x04,
(byte) 0x53,
(byte) 0x27,
(byte) 0x3F,
(byte) 0xD4
};
RvtPoiLocalSet poiLocalSet = new RvtPoiLocalSet(bytes, 0, bytes.length);
assertNotNull(poiLocalSet);
assertEquals(poiLocalSet.getDisplayName(), "Point of Interest");
assertEquals(poiLocalSet.getDisplayableValue(), "516");
assertEquals(poiLocalSet.getTags().size(), 3);
checkPoiAoiNumberExample(poiLocalSet);
checkPoiAoiLatitudeExample(poiLocalSet);
checkPoiAoiLongitudeExample(poiLocalSet);
}
@Test
public void parseTagsWithUnknownTag() throws KlvParseException {
final byte[] bytes =
new byte[] {
0x0B,
0x02,
(byte) 0x80,
(byte) 0xCA, // No such tag
0x01,
0x02,
0x02,
0x04,
0x02,
0x04,
(byte) 0x85,
(byte) 0xa1,
(byte) 0x5a,
(byte) 0x39,
0x03,
0x04,
(byte) 0x53,
(byte) 0x27,
(byte) 0x3F,
(byte) 0xD4
};
verifyNoLoggerMessages();
RvtPoiLocalSet poiLocalSet = new RvtPoiLocalSet(bytes, 0, bytes.length);
verifySingleLoggerMessage("Unknown RVT POI Metadata tag: 11");
assertNotNull(poiLocalSet);
assertEquals(poiLocalSet.getDisplayName(), "Point of Interest");
assertEquals(poiLocalSet.getDisplayableValue(), "516");
assertEquals(poiLocalSet.getTags().size(), 3);
checkPoiAoiNumberExample(poiLocalSet);
checkPoiAoiLatitudeExample(poiLocalSet);
checkPoiAoiLongitudeExample(poiLocalSet);
}
public static void checkPoiAoiNumberExample(RvtPoiLocalSet poiLocalSet) {
assertTrue(poiLocalSet.getTags().contains(RvtPoiMetadataKey.PoiAoiNumber));
IRvtPoiAoiMetadataValue v = poiLocalSet.getField(RvtPoiMetadataKey.PoiAoiNumber);
assertEquals(v.getDisplayName(), "POI/AOI Number");
assertEquals(v.getDisplayableValue(), "516");
assertTrue(v instanceof PoiAoiNumber);
PoiAoiNumber number = (PoiAoiNumber) v;
assertNotNull(number);
assertEquals(number.getNumber(), 516);
}
public static void checkPoiAoiLatitudeExample(RvtPoiLocalSet poiLocalSet) {
assertTrue(poiLocalSet.getTags().contains(RvtPoiMetadataKey.PoiLatitude));
IRvtPoiAoiMetadataValue v = poiLocalSet.getField(RvtPoiMetadataKey.PoiLatitude);
assertEquals(v.getDisplayName(), "POI Latitude");
assertEquals(v.getDisplayableValue(), "-86.0412\u00B0");
assertTrue(v instanceof PoiLatitude);
PoiLatitude lat = (PoiLatitude) v;
assertEquals(lat.getDegrees(), -86.0412, 0.0001);
assertEquals(
lat.getBytes(), new byte[] {(byte) 0x85, (byte) 0xa1, (byte) 0x5a, (byte) 0x39});
}
public static void checkPoiAoiLongitudeExample(RvtPoiLocalSet poiLocalSet) {
assertTrue(poiLocalSet.getTags().contains(RvtPoiMetadataKey.PoiLongitude));
IRvtPoiAoiMetadataValue v = poiLocalSet.getField(RvtPoiMetadataKey.PoiLongitude);
assertEquals(v.getDisplayName(), "POI Longitude");
assertEquals(v.getDisplayableValue(), "116.9344\u00B0");
assertTrue(v instanceof PoiLongitude);
PoiLongitude lon = (PoiLongitude) v;
assertEquals(lon.getDegrees(), 116.9344, 0.0001);
assertEquals(
lon.getBytes(), new byte[] {(byte) 0x53, (byte) 0x27, (byte) 0x3F, (byte) 0xD4});
}
@Test
public void createUnknownTag() throws KlvParseException {
final byte[] bytes = new byte[] {0x03};
verifyNoLoggerMessages();
IRvtPoiAoiMetadataValue value =
RvtPoiLocalSet.createValue(RvtPoiMetadataKey.Undefined, bytes);
verifySingleLoggerMessage("Unrecognized RVT POI tag: Undefined");
assertNull(value);
}
@Test
public void constructFromMap() throws KlvParseException {
Map<RvtPoiMetadataKey, IRvtPoiAoiMetadataValue> values = buildPoiValues();
RvtPoiLocalSet poiLocalSet = new RvtPoiLocalSet(values);
assertNotNull(poiLocalSet);
assertEquals(poiLocalSet.getDisplayName(), "Point of Interest");
assertEquals(poiLocalSet.getDisplayableValue(), "My Point (516)");
assertEquals(poiLocalSet.getTags().size(), 4);
checkPoiAoiNumberExample(poiLocalSet);
checkPoiAoiLatitudeExample(poiLocalSet);
checkPoiAoiLongitudeExample(poiLocalSet);
byte[] expectedBytes =
new byte[] {
(byte) 0x01,
(byte) 0x02,
(byte) 0x02,
(byte) 0x04, // T:1, L:2, V: 0x0204
(byte) 0x02,
(byte) 0x04,
(byte) 0x85,
(byte) 0xa1,
(byte) 0x5a,
(byte) 0x39, // T: 2, L:4, V: -86.0412
(byte) 0x03,
(byte) 0x04,
(byte) 0x53,
(byte) 0x27,
(byte) 0x3F,
(byte) 0xD4, // T: 3, L:4, V: 116.9344
(byte) 0x09,
(byte) 0x08,
(byte) 0x4D,
(byte) 0x79,
(byte) 0x20,
(byte) 0x50,
(byte) 0x6F,
(byte) 0x69,
(byte) 0x6e,
(byte) 0x74 // T:9, L: 8, V: "My Point"
};
assertEquals(poiLocalSet.getBytes(), expectedBytes);
}
@Test
public void checkLabelOnly() {
Map<RvtPoiMetadataKey, IRvtPoiAoiMetadataValue> values = new HashMap<>();
IRvtPoiAoiMetadataValue label =
new RvtPoiAoiTextString(RvtPoiAoiTextString.POI_AOI_LABEL, "Test Label1");
values.put(RvtPoiMetadataKey.PoiAoiLabel, label);
RvtPoiLocalSet poiLocalSet = new RvtPoiLocalSet(values);
assertEquals(poiLocalSet.getDisplayableValue(), "Test Label1");
}
@Test
public void checkSourceIdOnly() {
Map<RvtPoiMetadataKey, IRvtPoiAoiMetadataValue> values = new HashMap<>();
IRvtPoiAoiMetadataValue sourceId =
new RvtPoiAoiTextString(RvtPoiAoiTextString.POI_AOI_SOURCE_ID, "Some Source");
values.put(RvtPoiMetadataKey.PoiAoiSourceId, sourceId);
RvtPoiLocalSet poiLocalSet = new RvtPoiLocalSet(values);
IKlvValue value = poiLocalSet.getField((IKlvKey) RvtPoiMetadataKey.PoiAoiSourceId);
assertTrue(value instanceof RvtPoiAoiTextString);
RvtPoiAoiTextString textString = (RvtPoiAoiTextString) value;
assertEquals(textString.getDisplayableValue(), "Some Source");
assertEquals(poiLocalSet.getDisplayableValue(), "[POI Local Set]");
}
/**
* Basic test values for POI Local Set.
*
* @return Map ready to drop into the value constructor.
* @throws KlvParseException if parsing goes wrong.
*/
public static Map<RvtPoiMetadataKey, IRvtPoiAoiMetadataValue> buildPoiValues()
throws KlvParseException {
Map<RvtPoiMetadataKey, IRvtPoiAoiMetadataValue> values = new HashMap<>();
IRvtPoiAoiMetadataValue poiNumberBytes =
RvtPoiLocalSet.createValue(RvtPoiMetadataKey.PoiAoiNumber, new byte[] {0x02, 0x04});
values.put(RvtPoiMetadataKey.PoiAoiNumber, poiNumberBytes);
final byte[] latBytes = new byte[] {(byte) 0x85, (byte) 0xa1, (byte) 0x5a, (byte) 0x39};
IRvtPoiAoiMetadataValue lat =
RvtPoiLocalSet.createValue(RvtPoiMetadataKey.PoiLatitude, latBytes);
values.put(RvtPoiMetadataKey.PoiLatitude, lat);
final byte[] lonBytes = new byte[] {(byte) 0x53, (byte) 0x27, (byte) 0x3F, (byte) 0xD4};
IRvtPoiAoiMetadataValue lon =
RvtPoiLocalSet.createValue(RvtPoiMetadataKey.PoiLongitude, lonBytes);
values.put(RvtPoiMetadataKey.PoiLongitude, lon);
IRvtPoiAoiMetadataValue label =
new RvtPoiAoiTextString(RvtPoiAoiTextString.POI_AOI_LABEL, "My Point");
values.put(RvtPoiMetadataKey.PoiAoiLabel, label);
return values;
}
} | java | 12 | 0.593143 | 100 | 41.076596 | 235 | starcoderdata |
<?php
namespace Cloudson\Phartitura\Project;
class VersionHeapTest extends \PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function should_test_if_last_version_is_devmaster()
{
$heap = new VersionHeap;
$heap->insert(['version' => 'dev-master', 'time' => '2013-09-30 00:00:00']);
$heap->insert(['version' => '1.0.0', 'time' => '2013-09-01 00:00:00']);
$heap->insert(['version' => '2.0.0', 'time' => '2013-09-03 00:00:00']);
$version = $this->bottom($heap);
$this->assertEquals('dev-master', $version['version']);
$heap = new VersionHeap;
$heap->insert(['version' => '1.0.0', 'time' => '2013-09-01 00:00:00']);
$heap->insert(['version' => 'dev-master', 'time' => '2013-09-30 00:00:00']);
$heap->insert(['version' => '2.0.0', 'time' => '2013-09-03 00:00:00']);
$version = $this->bottom($heap);
$this->assertEquals('dev-master', $version['version']);
}
/**
* @test
*/
public function should_test_if_priority_by_timestamp_is_correct()
{
$heap = new VersionHeap;
$heap->insert(['version' => 'dev-master', 'time' => '2013-09-30 00:00:00']);
$heap->insert(['version' => '1.0.0', 'time' => '2013-09-01 00:00:00']);
$heap->insert(['version' => '2.0.0', 'time' => '2013-09-03 00:00:00']);
$version = $heap->current();
$this->assertEquals('2.0.0', $version['version']);
}
/**
* @test
*/
public function should_test_if_priority_by_tag_is_correct()
{
$heap = new VersionHeap;
$heap->insert(['version' => 'dev-master', 'time' => '2013-09-01 00:00:00']);
$heap->insert(['version' => '2.0.0', 'time' => '2013-09-01 00:00:00']);
$heap->insert(['version' => '1.0.0', 'time' => '2013-09-01 00:00:00']);
$version = $heap->current();
$this->assertEquals('2.0.0', $version['version']);
}
private function bottom(VersionHeap $heap)
{
foreach ($heap as $v) {}
return $v;
}
} | php | 12 | 0.52298 | 84 | 29.411765 | 68 | starcoderdata |
import okonf.connectors
import okonf.facts
import okonf.utils
from okonf.facts.multiple import Sequence, Collection
assert Sequence
assert Collection
assert okonf.utils | python | 4 | 0.837838 | 53 | 19.555556 | 9 | starcoderdata |
/*
* Copyright (c) 2015 - 10 - 13 10 : 46 :$second
* @author wupeiji It will be
* @Email
*/
package com.wpj.wx;
import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
import com.mangofactory.swagger.models.dto.ApiInfo;
import com.mangofactory.swagger.plugin.EnableSwagger;
import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;
import com.wpj.wx.util.FileUploadConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import javax.annotation.Resource;
@SpringBootApplication
@EnableCaching
@EnableAutoConfiguration
@EnableScheduling //定时任务
@EnableSwagger
@EnableWebSecurity
public class App extends WebMvcConfigurerAdapter
{
@Autowired
FileUploadConfiguration fileUploaderConfiguration;
@Resource
private SpringSwaggerConfig springSwaggerConfig;
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String location = "file:" + fileUploaderConfiguration.getPathToUploadFolder();
registry.addResourceHandler("/images/**").addResourceLocations(location);
}
@Bean
@ConfigurationProperties("fileUpload")
public FileUploadConfiguration uploaderConfiguration() {
return new FileUploadConfiguration();
}
@Bean // Don't forget the @Bean annotation
public SwaggerSpringMvcPlugin customImplementation() {
return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
.apiInfo(apiInfo())
.includePatterns("/(?!error).*")
;
}
private ApiInfo apiInfo() {
// ApiInfo(String title, String description, String termsOfServiceUrl, String contact, String license, String licenseUrl)
ApiInfo apiInfo = new ApiInfo("Rest API.作者吴培基",
"前端API接口文档",
"https://github.com/BigDuck",
"
"Apache LICENSE-2.0",
"http://www.apache.org/licenses/LICENSE-2.0"
);
return apiInfo;
}
/**
* 为了启用自己定义的错误处理
* @param dispatcherServlet
* @return
*/
@Bean
public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) {
ServletRegistrationBean registration = new ServletRegistrationBean(
dispatcherServlet);
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
return registration;
}
} | java | 11 | 0.743953 | 122 | 35.451613 | 93 | starcoderdata |
def inclayer(self):
"""#
# '=' Increment layer
#
self.evt=='='
"""
N = len(self.L.display['layerset'])
index = self.L.display['layerset'].index(self.L.display['activelayer'])
self.L.display['activelayer'] = self.L.display['layerset'][(index+1) % N]
self.current_layer = self.L.display['activelayer']
print self.current_layer
self.update_state() | python | 10 | 0.550926 | 81 | 35.083333 | 12 | inline |
from bisect import bisect
t=int(input())
while(t>0):
t=t-1
n,d=map(int,input().split())
l=[]
l=[int(i) for i in str(n)]
l.sort()
len1=len(l)
index=bisect(l,d)
if(index==len(l)):
l=[str(i) for i in l]
print(''.join(l))
else:
l=l[0:index]
len2=len(l)
o=len1-len2
while(o>0):
l.append(d)
o=o-1
l=[str(i) for i in l]
print(''.join(l)) | python | 12 | 0.411765 | 32 | 18.541667 | 24 | starcoderdata |
function(evt) {
switch (evt.settingName) {
case 'accessibility.screenreader':
this.buildLanguageList();
break;
case 'language.current':
// the 2nd parameter is to reset the current enabled layouts
KeyboardHelper.changeDefaultLayouts(evt.settingValue, true);
break;
}
} | javascript | 11 | 0.639394 | 68 | 29.090909 | 11 | inline |
//Gates: 32
//Wires: 96
//Input Width X 32
//Input Width Y 32
//Output Width Z 32
//CreateFunction
ArrayRef<Type *> args = {Type::getInt32Ty(F->getContext()),Type::getInt32Ty(F->getContext())};
std::string FunctionName = "Extern_binary_32bit_and";
FunctionCallee c = M.getOrInsertFunction(FunctionName,FunctionType::get(llvm::IntegerType::getInt32Ty(F->getContext()),args, false));
auto func = cast
func->addFnAttr("Gate");
if (c.getCallee()->hasNUsesOrMore(1)) {
} else {
Function::arg_iterator argNames = func->arg_begin();
Value *x = argNames++;
x->setName("x");
Value *y = argNames++;
y->setName("y");
BasicBlock *block = BasicBlock::Create(F->getContext(), "entry", func);
IRBuilder<> builder(block);
//Begin disassembling
Value* XInput0to31bits[32];
for (int j=0; j<32;j++){
XInput0to31bits[j] = builder.CreateLShr(x, u_int64_t(j), "ShiftedTo"+std::to_string(j) + "BitX", true);
XInput0to31bits[j] = builder.CreateTruncOrBitCast(XInput0to31bits[j],Type::getInt1Ty(F->getContext()));
}
Value* YInput0to31bits[32];
for (int j=0; j<32;j++){
YInput0to31bits[j] = builder.CreateLShr(y, u_int64_t(j), "ShiftedTo"+std::to_string(j) + "BitY", true);
YInput0to31bits[j] = builder.CreateTruncOrBitCast(YInput0to31bits[j],Type::getInt1Ty(F->getContext()));
}
//Inline gates
Value* W_64 = builder.CreateAnd(XInput0to31bits[0], YInput0to31bits[0]);
Value* W_65 = builder.CreateAnd(XInput0to31bits[1], YInput0to31bits[1]);
Value* W_66 = builder.CreateAnd(XInput0to31bits[2], YInput0to31bits[2]);
Value* W_67 = builder.CreateAnd(XInput0to31bits[3], YInput0to31bits[3]);
Value* W_68 = builder.CreateAnd(XInput0to31bits[4], YInput0to31bits[4]);
Value* W_69 = builder.CreateAnd(XInput0to31bits[5], YInput0to31bits[5]);
Value* W_70 = builder.CreateAnd(XInput0to31bits[6], YInput0to31bits[6]);
Value* W_71 = builder.CreateAnd(XInput0to31bits[7], YInput0to31bits[7]);
Value* W_72 = builder.CreateAnd(XInput0to31bits[8], YInput0to31bits[8]);
Value* W_73 = builder.CreateAnd(XInput0to31bits[9], YInput0to31bits[9]);
Value* W_74 = builder.CreateAnd(XInput0to31bits[10], YInput0to31bits[10]);
Value* W_75 = builder.CreateAnd(XInput0to31bits[11], YInput0to31bits[11]);
Value* W_76 = builder.CreateAnd(XInput0to31bits[12], YInput0to31bits[12]);
Value* W_77 = builder.CreateAnd(XInput0to31bits[13], YInput0to31bits[13]);
Value* W_78 = builder.CreateAnd(XInput0to31bits[14], YInput0to31bits[14]);
Value* W_79 = builder.CreateAnd(XInput0to31bits[15], YInput0to31bits[15]);
Value* W_80 = builder.CreateAnd(XInput0to31bits[16], YInput0to31bits[16]);
Value* W_81 = builder.CreateAnd(XInput0to31bits[17], YInput0to31bits[17]);
Value* W_82 = builder.CreateAnd(XInput0to31bits[18], YInput0to31bits[18]);
Value* W_83 = builder.CreateAnd(XInput0to31bits[19], YInput0to31bits[19]);
Value* W_84 = builder.CreateAnd(XInput0to31bits[20], YInput0to31bits[20]);
Value* W_85 = builder.CreateAnd(XInput0to31bits[21], YInput0to31bits[21]);
Value* W_86 = builder.CreateAnd(XInput0to31bits[22], YInput0to31bits[22]);
Value* W_87 = builder.CreateAnd(XInput0to31bits[23], YInput0to31bits[23]);
Value* W_88 = builder.CreateAnd(XInput0to31bits[24], YInput0to31bits[24]);
Value* W_89 = builder.CreateAnd(XInput0to31bits[25], YInput0to31bits[25]);
Value* W_90 = builder.CreateAnd(XInput0to31bits[26], YInput0to31bits[26]);
Value* W_91 = builder.CreateAnd(XInput0to31bits[27], YInput0to31bits[27]);
Value* W_92 = builder.CreateAnd(XInput0to31bits[28], YInput0to31bits[28]);
Value* W_93 = builder.CreateAnd(XInput0to31bits[29], YInput0to31bits[29]);
Value* W_94 = builder.CreateAnd(XInput0to31bits[30], YInput0to31bits[30]);
Value* W_95 = builder.CreateAnd(XInput0to31bits[31], YInput0to31bits[31]);
//Begin reassembly
Value * retV = builder.CreateZExtOrTrunc(W_64,builder.getIntNTy(32));
Value * temp = builder.CreateZExtOrTrunc(W_65, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 1, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_66, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 2, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_67, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 3, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_68, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 4, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_69, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 5, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_70, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 6, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_71, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 7, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_72, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 8, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_73, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 9, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_74, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 10, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_75, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 11, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_76, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 12, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_77, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 13, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_78, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 14, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_79, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 15, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_80, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 16, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_81, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 17, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_82, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 18, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_83, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 19, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_84, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 20, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_85, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 21, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_86, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 22, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_87, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 23, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_88, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 24, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_89, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 25, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_90, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 26, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_91, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 27, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_92, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 28, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_93, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 29, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_94, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 30, "");
retV = builder.CreateXor(retV, temp,"");
temp = builder.CreateZExtOrTrunc(W_95, builder.getIntNTy(32));
temp = builder.CreateShl(temp, 31, "");
retV = builder.CreateXor(retV, temp,"");
builder.CreateRet(retV);
} | c | 15 | 0.731681 | 133 | 50.302469 | 162 | starcoderdata |
public void sendSouth() {
//log.info("Send South PathID: {}", this.getPathID());
//log.info("Send to physical switches for PhysicalPath [" + this.getFlowID() + "]");
Node dstNode = this.getDstSwitch();
if(isValidFlowMod(dstNode)) {
log.info("SendSouth Dst switch for {} ", this.getPathInfo());
if(dstNode.getMplsFlowAdd() != null){
dstNode.getSwitch().sendMsg(new OVXMessage(dstNode.getMplsFlowAdd()), dstNode.getSwitch());
dstNode.setMplsFlowAdd(null);
}
dstNode.getSwitch().sendMsg(new OVXMessage(dstNode.getMplsFlowMod()), dstNode.getSwitch());
}
//if(this.isOriginalPath) {
if (this.getIntermediate().size() != 0) {
for (Node node : this.getIntermediate()) {
if(isValidFlowMod(node)) {
log.info("SendSouth Inter switches for {} ", this.getPathInfo());
if(node.getMplsFlowAdd() != null){
node.getSwitch().sendMsg(new OVXMessage(node.getMplsFlowAdd()), node.getSwitch());
node.setMplsFlowAdd(null);
}
node.getSwitch().sendMsg(new OVXMessage(node.getMplsFlowMod()), node.getSwitch());
}
}
}
//}
Node srcNode = this.getSrcSwitch();
if(isValidFlowMod(srcNode)) {
log.info("SendSouth src switch for {} ", this.getPathInfo());
if(this.getPhysicalFlow().getSrcSwitch().getSwitch() != null && this.isPrimaryPath()){
// Physical Flow: main path
srcNode = this.getPhysicalFlow().getSrcSwitch();
log.info("SrcNode: physicalFlow");
sendSouthGroup(srcNode);
log.info("Meter: Start");
sendSouthMeter(srcNode);
log.info("Meter: End");
srcNode.getSwitch().sendMsg(new OVXMessage(srcNode.getMplsFlowMod()), srcNode.getSwitch());
}
else if(this.getPhysicalFlow().getSrcSwitch().getSwitch() != null){
// Physical Flow: secondary path
; // nothing
}
else if(srcNode.getMplsFlowAdd() != null){
// Original sequence
srcNode.getSwitch().sendMsg(new OVXMessage(srcNode.getMplsFlowAdd()), srcNode.getSwitch());
srcNode.setMplsFlowAdd(null);
srcNode.getSwitch().sendMsg(new OVXMessage(srcNode.getMplsFlowMod()), srcNode.getSwitch());
}
}
} | java | 18 | 0.55094 | 104 | 45.296296 | 54 | inline |
#region Apache License
//-----------------------------------------------------------------------
// <copyright file="PageRegistration.cs" company="StrixIT">
// Copyright 2015 StrixIT. Author MA MSc.
//
// 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.
//
//-----------------------------------------------------------------------
#endregion Apache License
using StrixIT.Platform.Web;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace StrixIT.Platform.Modules.Cms
{
public static class PageRegistration
{
#region Private Fields
private static IPageRegistrator _registrator;
#endregion Private Fields
#region Public Properties
///
/// Gets the list of loaded content locators.
///
public static IList ContentLocators
{
get
{
return Registrator.ContentLocators;
}
}
///
/// Gets or sets the page registrator.
///
public static IPageRegistrator Registrator
{
get
{
if (_registrator != null)
{
return _registrator;
}
return new PageRegistrator();
}
set
{
_registrator = value;
}
}
#endregion Public Properties
#region Public Methods
///
/// Gets a value indicating whether a custom file page is registered for a url.
///
/// <param name="location">The url to check the file page registration for
/// if a file page is registered for the url, false otherwise
public static bool IsLocationRegistered(string location)
{
return Registrator.IsLocationRegistered(location);
}
///
/// Locates all custom page files for use when registering pages.
///
public static void LocatePages()
{
Registrator.LocatePages();
}
///
/// Registers all pages for which a file page is located with the Cms.
///
/// <param name="httpContext">
/// The HttpContext to use for rendering the page during the registration process
///
/// <param name="routeData">
/// The RouteData to use for rendering the page during the registration process
///
public static void RegisterAllPages(HttpContextBase httpContext, RouteData routeData)
{
Registrator.RegisterAllPages(httpContext, routeData);
}
///
/// Registers a page for which a file page is located with the Cms.
///
/// <param name="httpContext">
/// The HttpContext to use for rendering the page during the registration process
///
/// <param name="routeData">
/// The RouteData to use for rendering the page during the registration process
///
/// <param name="pagePath">The file page path to register
public static void RegisterPage(HttpContextBase httpContext, RouteData routeData, string pagePath)
{
Registrator.RegisterPage(httpContext, routeData, pagePath);
}
///
/// Registers custom content used on a custom page.
///
/// <param name="helper">The html helper to use
/// <param name="options">The options of the content
/// content locator for this url
public static ContentLocator RegisterUrl(HtmlHelper helper, DisplayOptions options)
{
return Registrator.RegisterUrl(helper, options);
}
#endregion Public Methods
}
} | c# | 12 | 0.579186 | 106 | 32.350365 | 137 | starcoderdata |
package main
import (
"testing"
)
func TestMeminfo(t *testing.T){
minfo := NewMeminfo()
for k,v := range minfo{
t.Log(k,v)
}
t.Log(minfo.Totle().MB())
t.Log(minfo.MemTotle().MB())
t.Log(minfo.SwapTotle().MB())
t.Log(minfo.MemFree().MB())
t.Log(minfo.MemUsed().MB())
t.Log(minfo.BufferCache().MB())
t.Log(minfo.MIBMem())
t.Log(minfo.MIBSwap())
} | go | 10 | 0.631579 | 32 | 17.05 | 20 | starcoderdata |
#load "../../common.cake"
var TARGET = Argument ("t", Argument ("target", "Default"));
var GLIDE_VERSION = "4.9.0";
var GLIDE_NUGET_VERSION = GLIDE_VERSION;
var GLIDE_URL = $"https://repo.maven.apache.org/maven2/com/github/bumptech/glide/glide/{GLIDE_VERSION}/glide-{GLIDE_VERSION}.aar";
var GIFDECODER_VERSION = GLIDE_VERSION;
var GIFDECODER_NUGET_VERSION = GIFDECODER_VERSION;
var GIFDECODER_URL = $"https://repo.maven.apache.org/maven2/com/github/bumptech/glide/gifdecoder/{GIFDECODER_VERSION}/gifdecoder-{GIFDECODER_VERSION}.aar";
var DISKLRUCACHE_VERSION = GLIDE_VERSION;
var DISKLRUCACHE_NUGET_VERSION = DISKLRUCACHE_VERSION;
var DISKLRUCACHE_URL = $"https://repo.maven.apache.org/maven2/com/github/bumptech/glide/disklrucache/{DISKLRUCACHE_VERSION}/disklrucache-{DISKLRUCACHE_VERSION}.jar";
var RECYCLERVIEW_VERSION = GLIDE_VERSION;
var RECYCLERVIEW_NUGET_VERSION = RECYCLERVIEW_VERSION;
var RECYCLERVIEW_URL = $"https://repo.maven.apache.org/maven2/com/github/bumptech/glide/recyclerview-integration/{RECYCLERVIEW_VERSION}/recyclerview-integration-{RECYCLERVIEW_VERSION}.aar";
Task ("externals")
.WithCriteria (!FileExists ("./externals/guava.jar"))
.Does (() =>
{
if (!DirectoryExists ("./externals/"))
CreateDirectory ("./externals");
// Download Dependencies
DownloadFile (GLIDE_URL, "./externals/glide.aar");
DownloadFile(GIFDECODER_URL, "./externals/gifdecoder.aar");
DownloadFile(DISKLRUCACHE_URL, "./externals/disklrucache.jar");
DownloadFile(RECYCLERVIEW_URL, "./externals/recyclerview-integration.aar");
// Update .csproj nuget versions
XmlPoke("./source/Xamarin.Android.Glide/Xamarin.Android.Glide.csproj", "/Project/PropertyGroup/PackageVersion", GLIDE_NUGET_VERSION);
XmlPoke("./source/Xamarin.Android.Glide.DiskLruCache/Xamarin.Android.Glide.DiskLruCache.csproj", "/Project/PropertyGroup/PackageVersion", DISKLRUCACHE_NUGET_VERSION);
XmlPoke("./source/Xamarin.Android.Glide.GifDecoder/Xamarin.Android.Glide.GifDecoder.csproj", "/Project/PropertyGroup/PackageVersion", GIFDECODER_NUGET_VERSION);
XmlPoke("./source/Xamarin.Android.Glide.RecyclerViewIntegration/Xamarin.Android.Glide.RecyclerViewIntegration.csproj", "/Project/PropertyGroup/PackageVersion", RECYCLERVIEW_NUGET_VERSION);
});
Task("libs")
.IsDependentOn("externals")
.Does(() =>
{
MSBuild("./source/Xamarin.Android.Glide.sln", c => {
c.Configuration = "Release";
c.Restore = true;
c.MaxCpuCount = 0;
c.Properties.Add("DesignTimeBuild", new [] { "false" });
});
});
Task("nuget")
.IsDependentOn("libs")
.Does(() =>
{
MSBuild ("./source/Xamarin.Android.Glide.sln", c => {
c.Configuration = "Release";
c.MaxCpuCount = 0;
c.Targets.Clear();
c.Targets.Add("Pack");
c.Properties.Add("PackageOutputPath", new [] { MakeAbsolute(new FilePath("./output")).FullPath });
c.Properties.Add("PackageRequireLicenseAcceptance", new [] { "true" });
c.Properties.Add("DesignTimeBuild", new [] { "false" });
});
});
Task("samples")
.IsDependentOn("nuget");
Task ("clean")
.Does (() =>
{
if (DirectoryExists ("./externals/"))
DeleteDirectory ("./externals", true);
});
RunTarget (TARGET); | c# | 28 | 0.73453 | 189 | 37.036585 | 82 | starcoderdata |
private void visitForReadRecord(OperatorNode<SequenceOperator> target) {
switch(target.getOperator()) {
case SCAN:
case INSERT:
case UPDATE:
case UPDATE_ALL:
case DELETE:
case DELETE_ALL:
case EMPTY:
case EVALUATE:
case NEXT:
case PIPE:
case DISTINCT:
case LIMIT:
case OFFSET:
case SLICE:
case MERGE:
case TIMEOUT:
case PAGE:
case ALL:
case MULTISOURCE:
case FALLBACK:
// no row-level inputs
return;
case PROJECT: {
OperatorNode<SequenceOperator> input = target.getArgument(0);
RowTypeVisitor rowTypeVisitor = new RowTypeVisitor(RowType.getSequenceType(input));
List<OperatorNode<ProjectOperator>> projection = target.getArgument(1);
for(OperatorNode<ProjectOperator> op : projection) {
switch(op.getOperator()) {
case FIELD: {
OperatorNode<ExpressionOperator> expr = op.getArgument(0);
expr.visit(rowTypeVisitor);
break;
}
case MERGE_RECORD: {
RowType.setReadRecordType(op, RowType.getSequenceType(input));
break;
}
default:
throw new UnsupportedOperationException("Unknown ProjectOperator: " + op);
}
}
break;
}
case FILTER:
case EXTRACT: {
OperatorNode<SequenceOperator> input = target.getArgument(0);
RowTypeVisitor rowTypeVisitor = new RowTypeVisitor(RowType.getSequenceType(input));
OperatorNode<ExpressionOperator> expr = target.getArgument(1);
expr.visit(rowTypeVisitor);
break;
}
case SORT: {
OperatorNode<SequenceOperator> input = target.getArgument(0);
RowTypeVisitor rowTypeVisitor = new RowTypeVisitor(RowType.getSequenceType(input));
List<OperatorNode<SortOperator>> comparator = target.getArgument(1);
for(OperatorNode<SortOperator> op : comparator) {
OperatorNode<ExpressionOperator> order = op.getArgument(0);
order.visit(rowTypeVisitor);
}
break;
}
case JOIN:
case LEFT_JOIN: {
// left right joinCondition
OperatorNode<ExpressionOperator> joinCondition = target.getArgument(2);
RowType leftSide = RowType.getLeftType(target);
RowType rightSide = RowType.getRightType(target);
RowTypeVisitor leftVisitor = new RowTypeVisitor(leftSide);
RowTypeVisitor rightVisitor = new RowTypeVisitor(rightSide);
for(JoinExpression expr : JoinExpression.parse(joinCondition)) {
expr.left.visit(leftVisitor);
expr.right.visit(rightVisitor);
}
break;
}
default:
throw new UnsupportedOperationException("Unknown SequenceOperator: %s" + target);
}
} | java | 18 | 0.510256 | 102 | 42.345679 | 81 | inline |
package collections.map;
import org.junit.Test;
import java.util.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
public class SimpleHashMapTest {
private SimpleHashMap<Integer, String> hashMap = new SimpleHashMap<>();
@Test
public void addRecordToMapTest() {
hashMap.insert(1, "one");
hashMap.insert(2, "two");
hashMap.insert(3, "three");
assertThat(hashMap.size(), is(3));
}
@Test
public void whenAddEqualKeyThenAddNewValue() {
hashMap.insert(1, "one");
hashMap.insert(1, "two");
assertThat(hashMap.get(1), is("two"));
}
@Test
public void deleteRecordTest() {
hashMap.insert(1, "one");
assertThat(hashMap.isEmpty(), is(false));
assertThat(hashMap.size(), is(1));
assertThat(hashMap.delete(1), is(true));
assertThat(hashMap.isEmpty(), is(true));
assertThat(hashMap.size(), is(0));
}
@Test
public void iteratorTest() {
hashMap.insert(1, "one");
hashMap.insert(2, "two");
Iterator<SimpleHashMap.Node<Integer, String>> iterator = this.hashMap.iterator();
assertThat(hashMap.iterator().hasNext(), is(true));
SimpleHashMap.Node<Integer, String> node = iterator.next();
assertThat(node.getKey(), is(1));
assertThat(node.getValue(), is("one"));
assertThat(iterator.hasNext(), is(true));
node = iterator.next();
assertThat(node.getKey(), is(2));
assertThat(node.getValue(), is("two"));
assertThat(iterator.hasNext(), is(false));
}
} | java | 9 | 0.628902 | 97 | 31.641509 | 53 | starcoderdata |
using System.ComponentModel.Composition;
using MinoriEditorShell.Commands;
using MinoriEditorShell.Platforms.Wpf.Commands;
using MinoriEditorShell.Platforms.Wpf.MenuDefinitionCollection;
using MinoriEditorShell.Platforms.Wpf.Menus;
using MinoriEditorShell.Properties;
namespace MinoriEditorShell.Platforms.Wpf.Commands
{
public static class MesMenuDefinitions
{
[Export]
public static MesMenuItemDefinition FileNewMenuItem = new MesTextMenuItemDefinition(
MesMenuDefinitionsCollection.FileNewOpenMenuGroup, 0, Resources.FileNewCommandText);
[Export]
public static MesMenuItemGroupDefinition FileNewCascadeGroup = new MesMenuItemGroupDefinition(
FileNewMenuItem, 0);
[Export]
public static MesMenuItemDefinition FileNewMenuItemList = new MesCommandMenuItemDefinition
FileNewCascadeGroup, 0);
[Export]
public static MesMenuItemDefinition FileOpenMenuItem = new MesCommandMenuItemDefinition
MesMenuDefinitionsCollection.FileNewOpenMenuGroup, 1);
[Export]
public static MesMenuItemDefinition FileCloseMenuItem = new MesCommandMenuItemDefinition
MesMenuDefinitionsCollection.FileCloseMenuGroup, 0);
[Export]
public static MesMenuItemDefinition FileSaveMenuItem = new MesCommandMenuItemDefinition
MesMenuDefinitionsCollection.FileSaveMenuGroup, 0);
[Export]
public static MesMenuItemDefinition FileSaveAsMenuItem = new MesCommandMenuItemDefinition
MesMenuDefinitionsCollection.FileSaveMenuGroup, 1);
[Export]
public static MesMenuItemDefinition FileSaveAllMenuItem = new MesCommandMenuItemDefinition
MesMenuDefinitionsCollection.FileSaveMenuGroup, 1);
[Export]
public static MesMenuItemDefinition FileExitMenuItem = new MesCommandMenuItemDefinition
MesMenuDefinitionsCollection.FileExitOpenMenuGroup, 0);
[Export]
public static MesMenuItemDefinition WindowDocumentList = new MesCommandMenuItemDefinition
MesMenuDefinitionsCollection.WindowDocumentListMenuGroup, 0);
[Export]
public static MesMenuItemDefinition ViewFullscreenItem = new MesCommandMenuItemDefinition
MesMenuDefinitionsCollection.ViewPropertiesMenuGroup, 0);
}
} | c# | 13 | 0.781093 | 140 | 47.807018 | 57 | starcoderdata |
#include
#include "storage.h"
using namespace std;
auto_ptr sql_conn_factory()
{
cout << "INFO - sql_conn_factory()\n";
return auto_ptr AA_SqlConnection);
}
AA_SqlConnection::AA_SqlConnection()
{
cout << "INFO - constructing SQL connection object\n";
}
AA_SqlConnection::~AA_SqlConnection()
{
cout << "INFO - cleaning up SQL connection object\n";
}
void AA_SqlConnection::get_data()
{
cout << "INFO - get_data() - getting data from Sql conn\n";
} | c++ | 8 | 0.687379 | 61 | 18.846154 | 26 | starcoderdata |
package demo
import (
"context"
"fmt"
"math/big"
ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/spf13/cobra"
"github.com/celer-network/go-rollup/utils"
"github.com/celer-network/rollup-contracts/bindings/go/sidechain"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
)
func transferToContract() error {
ethClientInfo, err := initEthClientInfo()
if err != nil {
return err
}
sidechainClient := ethClientInfo.sidechainClient
privateKey := ethClientInfo.privateKey
auth := ethClientInfo.auth
ctx := context.Background()
testTokenAddress := common.HexToAddress(viper.GetString(configMainchainContractsTestToken))
tokenMapperAddress := common.HexToAddress(viper.GetString(configSidechainContractsTokenMapper))
tokenMapper, err := sidechain.NewTokenMapper(tokenMapperAddress, sidechainClient)
if err != nil {
return err
}
senderAddress := auth.From
sidechainErc20Address, err := tokenMapper.MainchainTokenToSidechainToken(&bind.CallOpts{}, testTokenAddress)
if err != nil {
return err
}
sidechainErc20, err := sidechain.NewSidechainERC20(sidechainErc20Address, sidechainClient)
if err != nil {
return err
}
log.Print("Deploying DummyApp")
dummyAppAddress, tx, _, err := sidechain.DeployDummyApp(auth, sidechainClient, sidechainErc20Address)
if err != nil {
return err
}
receipt, err := utils.WaitMined(ctx, sidechainClient, tx, 0)
if err != nil {
return err
}
if receipt.Status != ethtypes.ReceiptStatusSuccessful {
return fmt.Errorf("Deployment tx %x failed", receipt.TxHash)
}
log.Printf("Deployed DummyApp at %s\n", dummyAppAddress.Hex())
sidechainErc20, err = sidechain.NewSidechainERC20(sidechainErc20Address, sidechainClient)
if err != nil {
return err
}
nonce, err := sidechainErc20.TransferNonces(&bind.CallOpts{}, senderAddress)
if err != nil {
return err
}
dummyApp, err := sidechain.NewDummyApp(dummyAppAddress, sidechainClient)
amount := new(big.Int)
amount.SetString(viper.GetString(flagAmount), 10)
playerOneSig, err := utils.SignPackedData(
privateKey,
[]string{"address", "address", "address", "uint256", "uint256"},
[]interface{}{
senderAddress,
dummyAppAddress,
testTokenAddress,
amount,
nonce,
},
)
auth.GasLimit = 2000000
log.Info().Msg("Transferring tokens to the deployed contract")
tx, err = dummyApp.PlayerOneDeposit(auth, playerOneSig)
if err != nil {
return err
}
receipt, err = utils.WaitMined(ctx, sidechainClient, tx, 0)
if err != nil {
return err
}
if receipt.Status != ethtypes.ReceiptStatusSuccessful {
return fmt.Errorf("Transfer to contract tx %x failed", receipt.TxHash)
}
return nil
}
func TransferToContractCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "transfer-to-contract",
Short: "Deploy a dummy contract on the sidechain and transfer token to it",
RunE: func(cmd *cobra.Command, args []string) error {
return transferToContract()
},
PreRunE: func(cmd *cobra.Command, args []string) error {
err := cmd.MarkFlagRequired(flagKeystore)
if err != nil {
return err
}
err = cmd.MarkFlagRequired(flagAmount)
if err != nil {
return err
}
err = viper.BindPFlag(flagKeystore, cmd.Flags().Lookup(flagKeystore))
if err != nil {
return err
}
err = viper.BindPFlag(flagAmount, cmd.Flags().Lookup(flagAmount))
if err != nil {
return err
}
return nil
},
}
cmd.Flags().String(flagKeystore, "", "Path to keystore file")
cmd.Flags().String(flagAmount, "", "Transfer amount")
return cmd
} | go | 20 | 0.724515 | 109 | 27.146154 | 130 | starcoderdata |
<?php
namespace FondOfSpryker\Zed\MimicCustomerAccount\Business;
use Generated\Shared\Transfer\QuoteTransfer;
use Generated\Shared\Transfer\SaveOrderTransfer;
use Spryker\Zed\Kernel\Business\AbstractFacade;
/**
* @method \FondOfSpryker\Zed\MimicCustomerAccount\Business\MimicCustomerAccountBusinessFactory getFactory()
*/
class MimicCustomerAccountFacade extends AbstractFacade implements MimicCustomerAccountFacadeInterface
{
/**
* {@inheritDoc}
*
* @param \Generated\Shared\Transfer\QuoteTransfer $quoteTransfer
* @param \Generated\Shared\Transfer\SaveOrderTransfer $saveOrderTransfer
*
* @return void
*/
public function saveOrderForceRegisterCustomer(QuoteTransfer $quoteTransfer, SaveOrderTransfer $saveOrderTransfer): void
{
$this->getFactory()
->createCheckoutForceRegisterCustomerOrderSaver()
->saveOrderForceRegisterCustomer($quoteTransfer, $saveOrderTransfer);
}
/**
* {@inheritDoc}
*
* @param \Generated\Shared\Transfer\QuoteTransfer $quoteTransfer
* @param \Generated\Shared\Transfer\SaveOrderTransfer $saveOrderTransfer
*
* @return void
*/
public function saveOrderUpdateGuestCart(QuoteTransfer $quoteTransfer, SaveOrderTransfer $saveOrderTransfer): void
{
$this->getFactory()
->createCheckoutUpdateGuestCartOrderSaver()
->saveOrderUpdateGuestCart($quoteTransfer, $saveOrderTransfer);
}
} | php | 10 | 0.732519 | 124 | 33.255814 | 43 | starcoderdata |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.