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 |
---|---|---|---|---|---|---|---|
// Package pool is a wrapper for Pooled HTTP clients.
// See net/http/client.go.
//
// This is the higher-level Pooled Client interface.
// The lower-level Client implementation is in client.go.
// The lowest-level implementation is in transport.go.
package pool
import (
"net/http"
"time"
)
// Client is a an interface common with http.Client
//
// Use it as a function argument when you want to take in an http.Client
// or a pool.PClient because you can operate on either type's Do method
// interchangeably.
type Client interface {
Do(req *http.Request) (*http.Response, error)
}
// A PClient is a pooled HTTP client. A pre-configured *http.Client should
// be passed in to this package's NewPClient() function to get a PClient.
//
// PClients are http.Clients wrapped to extend higher-level functionality.
// A PClient can, and should, be used like a usual http.Client.
//
// Pooling functionality is handled autonomously under the hood.
// PClient can have an upper bound set for the number of connections it
// will make. They can also be set to rate limit the requests-per-second
// the PClient can perform.
//
// PClients have a Do() method that may help make converting existing
// projects to use this easier. The implementation may not have to change
// to gain the benefits, only the initial type.
//
// The PClient's Transport typically has internal state (cached TCP
// connections), so PClients should be reused instead of created as
// needed. PClients are safe for concurrent use by multiple goroutines.
//
// For all the interesting details, see client.go.
type PClient struct {
client *http.Client
maxPoolSize int
cSemaphore chan int
reqPerSecond int
rateLimiter <-chan time.Time
}
// NewPClient returns a *PClient that wraps an *http.Client and sets the
// maximum pool size as well as the requests per second as integers.
//
// A zero for maxPoolSize will set no limit
// A zero for reqPerSec will set no limit
func NewPClient(stdClient *http.Client, maxPoolSize int, reqPerSec int) *PClient {
var semaphore chan int = nil
if maxPoolSize > 0 {
semaphore = make(chan int, maxPoolSize) // Buffered channel to act as a semaphore
}
var emitter <-chan time.Time = nil
if reqPerSec > 0 {
emitter = time.NewTicker(time.Second / time.Duration(reqPerSec)).C // x req/s == 1s/x req (inverse)
}
return &PClient{
client: stdClient,
maxPoolSize: maxPoolSize,
cSemaphore: semaphore,
reqPerSecond: reqPerSec,
rateLimiter: emitter,
}
}
// Do is a method that 'overloads' the http.Client Do method for drop-in
// compatibility with existing codebases.
func (c *PClient) Do(req *http.Request) (*http.Response, error) {
return c.DoPool(req)
}
// DoPool does the required synchronization with channels to
// perform the request in accordance to the PClient's maximum pool size
// and requests-per-second rate limiter.
//
// Caller should close resp.Body when done reading from it.
//
// It is an exported function in case a direct call to this method is
// desired
func (c *PClient) DoPool(req *http.Request) (*http.Response, error) {
if c.maxPoolSize > 0 {
c.cSemaphore <- 1 // Grab a connection from our pool
defer func() {
<-c.cSemaphore // Defer release our connection back to the pool
}()
}
if c.reqPerSecond > 0 {
<-c.rateLimiter // Block until a signal is emitted from the rateLimiter
}
// Perform the normal request using the underlying http.Client
resp, err := c.client.Do(req)
if err != nil {
return &http.Response{}, err
}
// resp.Body intentionally not closed
return resp, nil
} | go | 13 | 0.728988 | 101 | 31.1875 | 112 | starcoderdata |
import numpy as np
import math
import jsonpickle
jsonpickle_default_skel = None
class RadialBasisDof(object):
def __init__(self, skel, dof, w=0.0, s=0.1, x=0.0):
self.skel = skel
if isinstance(dof, str):
self.index = self.skel.dof_index(dof)
else:
self.index = dof
# Fetch the kernel parameters
# self.w = w # weight
# self.s = s # standard deviation
# self.x = x # center
self.set_params([w, s, x])
def num_params(self):
return 3
def params(self):
return np.array([self.w, self.s, self.x])
def set_params(self, params):
(self.w, self.s, self.x) = tuple(np.array(params))
def eval(self, t):
vec = np.zeros(self.skel.ndofs)
vec[self.index] = 1.0
(w, s, x) = (self.w, self.s, self.x)
value = w * math.exp(-(1.0) / (2.0 * s * s) * (t - x) * (t - x))
return value * vec
def __getstate__(self):
data = dict(self.__dict__)
del data['skel']
return data
def __setstate__(self, data):
self.__dict__.update(data)
self.skel = jsonpickle_default_skel
class MutableMotion(object):
def __init__(self, skel, ref):
self.skel = skel
self.ref = ref
# Init internal variables
self.basis = []
self.h = self.skel.world.dt
# Initialize basis
self.init_basis()
def init_basis(self):
joints = ['j_pelvis_rot_z', 'j_pelvis_pos_x', 'j_pelvis_pos_y',
'j_thigh_left_z', 'j_shin_left', 'j_heel_left_1',
'j_thigh_right_z', 'j_shin_right', 'j_heel_right_1']
for j in joints:
self.add_basis(j, 0.0, 0.1, 0.05)
self.add_basis(j, 0.0, 0.1, 0.2)
self.add_basis(j, 0.0, 0.5, 0.3)
self.add_basis(j, 0.0, 0.1, 0.5)
self.add_basis(j, 0.0, 0.1, 0.7)
self.add_basis(j, 0.0, 0.1, 0.95)
def add_basis(self, dof, w0=0.0, s0=0.1, x0=0.0):
b = RadialBasisDof(self.skel, dof, w0, s0, x0)
self.basis.append(b)
def num_params(self):
return len(self.basis) * 3
def params(self):
params = np.zeros(self.num_params())
for i, b in enumerate(self.basis):
params[3 * i:3 * i + 3] = b.params()
return params
def set_params(self, params):
for i, b in enumerate(self.basis):
b.set_params(params[3 * i:3 * i + 3])
def pose_at(self, t):
frame_index = int(t / self.h)
frame_index = min(frame_index, self.ref.num_frames - 1)
pose = self.ref.pose_at(frame_index, self.skel.id)
for b in self.basis:
pose += b.eval(t)
return pose
def ref_pose_at_frame(self, frame_index):
frame_index = min(frame_index, self.ref.num_frames - 1)
pose = self.ref.pose_at(frame_index, self.skel.id)
return pose
def ref_velocity_at_frame(self, frame_index):
if frame_index == 0:
return self.velocity_at_first()
elif frame_index == self.ref.num_frames - 1:
return self.velocity_at_last()
elif frame_index > self.ref.num_frames - 1:
return np.zeros(self.skel.ndofs)
h = self.h
q0 = self.ref.pose_at(frame_index - 1, self.skel.id)
q2 = self.ref.pose_at(frame_index + 1, self.skel.id)
vel = (-0.5 * q0 + 0.5 * q2) / h
return vel
def velocity_at_first(self):
""" Backward finite difference with 2 accuracy """
h = self.h
q0 = self.ref.pose_at(0, self.skel.id)
q1 = self.ref.pose_at(1, self.skel.id)
q2 = self.ref.pose_at(2, self.skel.id)
vel = (-1.5 * q0 + 2.0 * q1 - 0.5 * q2) / h
return vel
def velocity_at_last(self):
""" Backward finite difference with 2 accuracy """
h = self.h
q0 = self.ref.pose_at(-3, self.skel.id)
q1 = self.ref.pose_at(-2, self.skel.id)
q2 = self.ref.pose_at(-1, self.skel.id)
vel = (0.5 * q0 - 2.0 * q1 + 1.5 * q2) / h
return vel
def __getstate__(self):
data = dict(self.__dict__)
del data['skel']
del data['ref']
return data
def __setstate__(self, data):
self.__dict__.update(data)
def save(self, filename):
with open(filename, 'w+') as fout:
frozen = jsonpickle.encode(self)
fout.write(frozen)
def load(self, filename):
global jsonpickle_default_skel
jsonpickle_default_skel = self.skel
with open(filename, 'r') as fin:
frozen = fin.read()
dup = jsonpickle.decode(frozen)
self.__dict__.update(dup.__dict__) | python | 16 | 0.530227 | 72 | 29.935065 | 154 | starcoderdata |
bool SyncConfigIOContext::decrypt(const string& in, string& out)
{
// Handy constants.
const size_t IV_LENGTH = SymmCipher::KEYLENGTH;
const size_t MAC_LENGTH = 32;
const size_t METADATA_LENGTH = IV_LENGTH + MAC_LENGTH;
// Is the file too short to be valid?
if (in.size() <= METADATA_LENGTH)
{
return false;
}
// For convenience (format: <data><iv><hmac>)
const byte* data = reinterpret_cast<const byte*>(&in[0]);
const byte* iv = &data[in.size() - METADATA_LENGTH];
const byte* mac = &data[in.size() - MAC_LENGTH];
byte cmac[MAC_LENGTH];
// Compute HMAC on file.
mSigner.add(data, in.size() - MAC_LENGTH);
mSigner.get(cmac);
// Is the file corrupt?
if (memcmp(cmac, mac, MAC_LENGTH))
{
return false;
}
// Try and decrypt the file.
return mCipher.cbc_decrypt_pkcs_padding(data,
in.size() - METADATA_LENGTH,
iv,
&out);
} | c++ | 11 | 0.531163 | 72 | 28.888889 | 36 | inline |
using System.Collections.Generic;
using System.Linq;
namespace ActuarialMaths.NonLife.ClaimsReserving.Model
{
///
/// A cumulative run-off triangle based on an abstract base run-off triangle.
///
public class CumulativeTriangle : Triangle
{
///
/// Constructor for an empty run-off triangle.
///
public CumulativeTriangle() : base() { }
///
/// Constructor for a run-off triangle containing only zeroes for a given number of periods.
///
public CumulativeTriangle(int periods) : base(periods) { }
///
/// Adds a sequence of claims to the run-off triangle.
///
/// <param name="values">Claims to be appended to the triangle.
///
/// It is assumed that the claims to be added are amounts paid in the corresponding period,
/// i.e. for the cumulative triangle the claims are added to the claims of the previous period before being appended to the triangle.
/// It is assumed that claims to be added are all claims paid in a fixed year. They are ordered
/// by the relative settlement period in ascending order, e.g.: There are three claims to be added for the year 2019. They are ordered as follows:
/// 1. Claim occured in 2019 and was paid in 2019 (relative settlement year = 0)
/// 2. Claim occured in 2018 and was paid in 2019 (relative settlement year = 1)
/// 3. Claim occured in 2017 and was paid in 2019 (relative settlement year = 2)
///
public override void AddClaims(IEnumerable values)
{
IEnumerable cumulated = (Periods == 0) ? values : values.Zip(GetDiagonal().Prepend(0m), (x, y) => x + y);
base.AddClaims(cumulated);
}
}
} | c# | 19 | 0.635269 | 154 | 46.775 | 40 | starcoderdata |
package for_game
import (
"game_server/easygo"
"game_server/pb/share_message"
"github.com/astaxie/beego/logs"
)
//玩家在线管理器,主要存放在线玩家当前在那个大厅上
type PlayerOnlineManager struct {
PlayerList map[PLAYER_ID]int32 //在线玩家列表[PLAYER_ID]SERVER_ID
CutrList map[PLAYER_ID]bool //切后台玩家列表[PLAYER_ID]SERVER_ID
OutReturnList map[PLAYER_ID]interface{} //玩家切后台时间信息列表
Mutex easygo.Mutex
}
func NewPlayerOnlineManager() *PlayerOnlineManager {
p := &PlayerOnlineManager{}
p.PlayerList = make(map[PLAYER_ID]int32)
p.CutrList = make(map[PLAYER_ID]bool)
p.OutReturnList = make(map[PLAYER_ID]interface{})
return p
}
//玩家上线
func (self *PlayerOnlineManager) PlayerOnline(playerId PLAYER_ID, serverId int32) {
self.Mutex.Lock()
defer self.Mutex.Unlock()
self.PlayerList[playerId] = serverId
logs.Info("玩家上线了:", serverId, playerId)
}
//玩家下线
func (self *PlayerOnlineManager) PlayerOffline(playerId PLAYER_ID) {
self.Mutex.Lock()
defer self.Mutex.Unlock()
delete(self.PlayerList, playerId)
delete(self.CutrList, playerId)
}
func (self *PlayerOnlineManager) GetPlayerServerId(playerId PLAYER_ID) int32 {
self.Mutex.Lock()
defer self.Mutex.Unlock()
return self.PlayerList[playerId]
}
func (self *PlayerOnlineManager) GetAllOnlinePlayers() *share_message.PlayerOnlineInfo {
self.Mutex.Lock()
defer self.Mutex.Unlock()
onLines := &share_message.PlayerOnlineInfo{}
for pid, sid := range self.PlayerList {
p := &share_message.PlayerState{
PlayerId: easygo.NewInt64(pid),
ServerId: easygo.NewInt32(sid),
}
onLines.OnLines = append(onLines.OnLines, p)
}
return onLines
}
//检测玩家是否在线
func (self *PlayerOnlineManager) CheckPlayerIsOnLine(playerId PLAYER_ID) bool {
self.Mutex.Lock()
defer self.Mutex.Unlock()
if self.PlayerList[playerId] != 0 {
return true
}
return false
}
//设置玩家切后台状态
func (self *PlayerOnlineManager) SetPlayerIsCutBackstage(playerId PLAYER_ID, b bool) {
self.Mutex.Lock()
defer self.Mutex.Unlock()
self.CutrList[playerId] = b
}
//检测玩家是否切后台
func (self *PlayerOnlineManager) CheckPlayerIsCutBackstage(playerId PLAYER_ID) bool {
self.Mutex.Lock()
defer self.Mutex.Unlock()
return self.CutrList[playerId]
}
func (self *PlayerOnlineManager) SetPlayerOutReturnTime(playerId PLAYER_ID, state string, time int64) {
self.Mutex.Lock()
defer self.Mutex.Unlock()
switch result := self.OutReturnList[playerId].(type) {
case nil:
self.OutReturnList[playerId] = make(map[string]int64)
self.OutReturnList[playerId].(map[string]int64)[state] = time
case map[string]int64:
result[state] = time
}
}
func (self *PlayerOnlineManager) GetPlayerOutReturnTime(playerId PLAYER_ID, state string) int64 {
self.Mutex.Lock()
defer self.Mutex.Unlock()
switch result := self.OutReturnList[playerId].(type) {
case nil:
return 0
case map[string]int64:
return result[state]
}
return 0
} | go | 14 | 0.74548 | 103 | 25.62963 | 108 | starcoderdata |
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
import pytest
from reranking.reranker import Reranker
class TestReranking:
@pytest.fixture
def genders(self) -> List[str]:
np.random.seed(seed=43)
genders: List[str] = np.random.choice(
["male"] * 70 + ["female"] * 30, 100, replace=False
).tolist()
return genders
@pytest.mark.parametrize(
"item_attributes, distribution",
[
([1, 2, 3], {1: 0.3, 2: 0.4, 3: 0.5}), # sum of distibution larger than 1
([1, 2, 3], {4: 0.3, 5: 0.4, 6: 0.3}), # no intersection
([4, 5], {4: 0.3, 5: 0.4, 6: 0.3}), # distr contains item attr
],
)
def test_exception_returns(
self, item_attributes: List[Any], distribution: Dict[Any, float]
) -> None:
r = Reranker(item_attributes, distribution)
with pytest.raises((NameError, ValueError)):
r._format_alg_input()
default_ranking = list(range(len(item_attributes)))
reranking = r()
assert default_ranking == reranking
@pytest.mark.parametrize(
"item_attributes, distribution, max_na, expected_item_attr, expected_distr_key, expected_data, expected_p",
[
(
[2, 4, 5],
{4: 0.3, 5: 0.4, 6: 0.3},
None,
["masked", 4, 5],
["masked", 4, 5],
{(0, 0): 0, (1, 0): 1, (2, 0): 2},
[0.3, 0.3, 0.4],
), # mask both
(
[4, 5, 6],
{4: 0.3, 5: 0.4, 6: 0.3},
None,
[4, 5, 6],
[4, 5, 6],
{(0, 0): 0, (1, 0): 1, (2, 0): 2},
[0.3, 0.4, 0.3],
), # mask nothing
(
[4, 5, 6, 7],
{4: 0.3, 5: 0.4, 6: 0.3},
None,
[4, 5, 6, "masked"],
[
4,
5,
6,
],
{(0, 0): 0, (1, 0): 1, (2, 0): 2, (3, 0): 3},
[0.3, 0.4, 0.3, 0.0],
), # mask item attr
(
[2, 3, 4],
{2: 0.3, 3: 0.2, 4: 0.1, 5: 0.1, 6: 0.1},
3,
[2, 3, "masked"],
[2, 3, "masked"],
{(0, 0): 0, (1, 0): 1, (2, 0): 2},
[0.3, 0.2, 0.5],
), # max_na constraint case 1
(
[1, 2, 3, 4],
{2: 0.3, 3: 0.2, 4: 0.1, 5: 0.1, 6: 0.1},
3,
["masked", 2, 3, "masked"],
[2, 3, "masked"],
{(0, 0): 0, (0, 1): 3, (1, 0): 1, (2, 0): 2},
[0.5, 0.3, 0.2],
), # max_na constraint case 2
],
)
def test__format_alg_input(
self,
item_attributes: List[Any],
distribution: Dict[Any, float],
max_na: Optional[int],
expected_item_attr: List[Any],
expected_distr_key: List[Any],
expected_data: Dict[Tuple[int, int], int],
expected_p: List[float],
) -> None:
r = Reranker(item_attributes, distribution, max_na=max_na)
# test masking
acutal_item_attr, acutal_distr = r._mask_item_attr_and_distr()
assert set(expected_item_attr) == set(acutal_item_attr)
assert set(expected_distr_key) == set(acutal_distr)
# test algorithm inputs
_, actual_data, actual_p = r._format_alg_input()
assert expected_data == actual_data
np.testing.assert_almost_equal(expected_p, actual_p)
@pytest.mark.parametrize(
"distribution, k_max, algorithm",
[
# test performce
({"female": 0.5, "male": 0.5}, 10, "det_greedy"),
({"female": 0.0, "male": 1.0}, 10, "det_greedy"),
({"female": 0.5, "male": 0.5}, 10, "det_cons"),
({"female": 0.0, "male": 1.0}, 10, "det_cons"),
({"female": 0.5, "male": 0.5}, 10, "det_relaxed"),
({"female": 0.0, "male": 1.0}, 10, "det_relaxed"),
({"female": 0.5, "male": 0.5}, 10, "det_const_sort"),
({"female": 0.0, "male": 1.0}, 10, "det_const_sort"),
# test edge conditions
({"female": 0.5, "male": 0.5}, 70, "det_greedy"),
({"female": 0.5, "male": 0.5}, 100, "det_greedy"),
({"female": 0.5, "male": 0.5}, 70, "det_cons"),
({"female": 0.5, "male": 0.5}, 100, "det_cons"),
({"female": 0.5, "male": 0.5}, 70, "det_relaxed"),
({"female": 0.5, "male": 0.5}, 100, "det_relaxed"),
({"female": 0.5, "male": 0.5}, 70, "det_const_sort"),
({"female": 0.5, "male": 0.5}, 100, "det_const_sort"),
],
)
def test_algorithms(
self,
genders: List[Any],
distribution: Dict[Any, float],
k_max: int,
algorithm: str,
) -> None:
ranker = Reranker(genders, distribution)
reranking = ranker(algorithm=algorithm, k_max=k_max)
re_features = [genders[i] for i in reranking]
acutal_male = re_features.count("male")
actual_female = re_features.count("female")
if k_max == 70: # not enough items for female
assert acutal_male == k_max - genders.count("female")
assert actual_female == genders.count("female")
elif k_max == 100: # result distribution should be the overall distribution
assert acutal_male == genders.count("male")
assert actual_female == genders.count("female")
else: # enough item for each attribute
assert acutal_male == distribution["male"] * k_max
assert actual_female == distribution["female"] * k_max | python | 16 | 0.449201 | 115 | 36.018868 | 159 | starcoderdata |
package dev.sheldan.abstracto.remind.command;
import dev.sheldan.abstracto.core.command.UtilityModuleDefinition;
import dev.sheldan.abstracto.core.command.condition.AbstractConditionableCommand;
import dev.sheldan.abstracto.core.command.config.CommandConfiguration;
import dev.sheldan.abstracto.core.command.config.HelpInfo;
import dev.sheldan.abstracto.core.command.config.Parameter;
import dev.sheldan.abstracto.core.command.execution.CommandContext;
import dev.sheldan.abstracto.core.command.execution.CommandResult;
import dev.sheldan.abstracto.core.command.execution.ContextConverter;
import dev.sheldan.abstracto.core.config.FeatureDefinition;
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
import dev.sheldan.abstracto.core.service.ChannelService;
import dev.sheldan.abstracto.core.service.management.UserInServerManagementService;
import dev.sheldan.abstracto.core.utils.FutureUtils;
import dev.sheldan.abstracto.remind.config.RemindFeatureDefinition;
import dev.sheldan.abstracto.remind.model.database.Reminder;
import dev.sheldan.abstracto.remind.model.template.commands.ReminderModel;
import dev.sheldan.abstracto.remind.service.ReminderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@Component
@Slf4j
public class Remind extends AbstractConditionableCommand {
public static final String REMINDER_EMBED_KEY = "remind_response";
@Autowired
private ReminderService remindService;
@Autowired
private ChannelService channelService;
@Autowired
private UserInServerManagementService userInServerManagementService;
@Override
public CompletableFuture executeAsync(CommandContext commandContext) {
List parameters = commandContext.getParameters().getParameters();
Duration remindTime = (Duration) parameters.get(0);
String text = (String) parameters.get(1);
AUserInAServer aUserInAServer = userInServerManagementService.loadOrCreateUser(commandContext.getAuthor());
ReminderModel remindModel = (ReminderModel) ContextConverter.fromCommandContext(commandContext, ReminderModel.class);
remindModel.setRemindText(text);
Reminder createdReminder = remindService.createReminderInForUser(aUserInAServer, text, remindTime, commandContext.getMessage());
remindModel.setReminder(createdReminder);
log.info("Notifying user {} about reminder being scheduled.", commandContext.getAuthor().getId());
return FutureUtils.toSingleFutureGeneric(channelService.sendEmbedTemplateInTextChannelList(REMINDER_EMBED_KEY, remindModel, commandContext.getChannel()))
.thenApply(aVoid -> CommandResult.fromSuccess());
}
@Override
public CommandConfiguration getConfiguration() {
List parameters = new ArrayList<>();
parameters.add(Parameter.builder().name("duration").type(Duration.class).templated(true).build());
parameters.add(Parameter.builder().name("remindText").type(String.class).templated(true).remainder(true).build());
HelpInfo helpInfo = HelpInfo.builder().templated(true).hasExample(true).build();
return CommandConfiguration.builder()
.name("remind")
.async(true)
.module(UtilityModuleDefinition.UTILITY)
.templated(true)
.supportsEmbedException(true)
.causesReaction(false)
.parameters(parameters)
.help(helpInfo)
.build();
}
@Override
public FeatureDefinition getFeature() {
return RemindFeatureDefinition.REMIND;
}
} | java | 4 | 0.766551 | 161 | 46.833333 | 84 | starcoderdata |
using Skclusive.Mobx.Observable;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Skclusive.Mobx.StateTree.Tests
{
public interface IUserSnapshot
{
string Id { set; get; }
string Name { set; get; }
}
public interface IUser : IUserSnapshot
{
}
internal class UserSnapshot : IUserSnapshot
{
public string Id { set; get; }
public string Name { set; get; }
}
internal class UserProxy : ObservableProxy<IUser, INode>, IUser
{
public override IUser Proxy => this;
public UserProxy(IObservableObject<IUser, INode> target) : base(target)
{
}
public string Id
{
get => Read
set => Write(nameof(Id), value);
}
public new string Name
{
get => Read
set => Write(nameof(Name), value);
}
}
public partial class TestTypes
{
public readonly static IObjectType<IUserSnapshot, IUser> UserType = Types
.Object<IUserSnapshot, IUser>("IUser")
.Proxy(x => new UserProxy(x))
.Snapshot(() => new UserSnapshot())
.Mutable(o => o.Id, Types.Identifier)
.Mutable(o => o.Name, Types.String);
public readonly static IObjectType<string, IUser> UserRefType = Types
.Object<string, IUser>("IUser")
.Proxy(x => new UserProxy(x))
.Snapshot(() => "")
.Mutable(o => o.Id, Types.Identifier)
.Mutable(o => o.Name, Types.String);
}
} | c# | 22 | 0.540142 | 81 | 25.46875 | 64 | starcoderdata |
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "outputId"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
void InValidateFastQParser(string nodeName)
{
// Gets the expected sequence from the Xml
string filePath = utilityObj.xmlUtil.GetTextValue(
nodeName, Constants.FilePathNode);
string outputId = null;
// Create a FastQ Parser object.
FastQParser fastQParserObj = new FastQParser(filePath);
fastQParserObj.AutoDetectFastQFormat = true;
IEnumerable<ISequence> parse = null;
try
{
parse = fastQParserObj.Parse();
outputId = parse.ElementAt(0).ID;
Assert.Fail();
}
catch (FileFormatException)
{
ApplicationLog.WriteLine(
"FastQ Parser P2 : Successfully validated the exception");
Console.WriteLine(
"FastQ Parser P2 : Successfully validated the exception");
}
} | c# | 12 | 0.593443 | 247 | 45.961538 | 26 | inline |
the link below to send an AJAX request to the server. The response data is properly encoded on the server.
function sendRequest() {
$.ajax({
type: "POST",
url: '@Url.Action("EncodeAjaxResponseCallback", "HtmlEncoding")',
success: function (response) {
$("#content").html(response);
}
});
}
<a href="javascript:sendRequest()">Send Ajax Request
<p id="content"> | c# | 10 | 0.558882 | 120 | 33.928571 | 14 | starcoderdata |
def since_to_timedelta(cls, since: str) -> timedelta:
"""Convert a `since` field to a timedelta.
Args:
since (str): Contains an integer followed by a unit letter: 'd' for days, 'h' for hours, 'm' for minutes
Returns:
timedelta: [description]
"""
unit = since[-1]
# days, hours, or minutes
assert(unit in ['d', 'h', 'm'])
days = int(since[0:-1]) if unit == 'd' else 0
hours = int(since[0:-1]) if unit == 'h' else 0
minutes = int(since[0:-1]) if unit == 'm' else 0
return timedelta(days=days, hours=hours, minutes=minutes) | python | 11 | 0.545741 | 116 | 38.6875 | 16 | inline |
using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.Udon;
namespace UdonSharp.Tests
{
public class EditorClientSetColor : UdonSharpBehaviour
{
void Start()
{
Material meshMaterial = GetComponent
#if UNITY_EDITOR
meshMaterial.SetColor("_Color", Color.red);
#else
meshMaterial.SetColor("_Color", Color.blue);
#endif
}
}
} | c# | 15 | 0.674651 | 74 | 20.782609 | 23 | starcoderdata |
// UXKit headers, derived from reverse engineering by (@kirb)
// This is free and unencumbered software released into the public domain. Refer to LICENSE.md.
@interface UXImageView : UXView
@property (retain, nonatomic) NSImage *image;
- (instancetype)initWithImage:(NSImage *)image;
- (void)sizeToFit;
- (void)setFrameSize:(CGSize)frameSize;
@property (readonly) CGSize intrinsicContentSize;
@property (retain, nonatomic) NSString *accessibilityLabel;
- (void)viewWillMoveToWindow:(NSWindow *)window;
- (void)viewDidChangeBackingProperties;
@end | c | 12 | 0.782677 | 95 | 30.75 | 20 | starcoderdata |
package org.bian.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.bian.dto.BQQualificationRetrieveOutputModelQualificationInstanceRecordQualificationTaskRecord;
import javax.validation.Valid;
/**
* BQQualificationRetrieveOutputModelQualificationInstanceRecord
*/
public class BQQualificationRetrieveOutputModelQualificationInstanceRecord {
private String qualificationType = null;
private String publicDirectoryReference = null;
private String specialistAgencyServiceReference = null;
private BQQualificationRetrieveOutputModelQualificationInstanceRecordQualificationTaskRecord qualificationTaskRecord = null;
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The type of qualification check (e.g. PEP/watch list checks, credit worthiness, legal jeopardy)
* @return qualificationType
**/
public String getQualificationType() {
return qualificationType;
}
public void setQualificationType(String qualificationType) {
this.qualificationType = qualificationType;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to an external verification source (e.g. for registered address/location verification)
* @return publicDirectoryReference
**/
public String getPublicDirectoryReference() {
return publicDirectoryReference;
}
public void setPublicDirectoryReference(String publicDirectoryReference) {
this.publicDirectoryReference = publicDirectoryReference;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to an external verification service (e.g. to perform background verification checks)
* @return specialistAgencyServiceReference
**/
public String getSpecialistAgencyServiceReference() {
return specialistAgencyServiceReference;
}
public void setSpecialistAgencyServiceReference(String specialistAgencyServiceReference) {
this.specialistAgencyServiceReference = specialistAgencyServiceReference;
}
/**
* Get qualificationTaskRecord
* @return qualificationTaskRecord
**/
public BQQualificationRetrieveOutputModelQualificationInstanceRecordQualificationTaskRecord getQualificationTaskRecord() {
return qualificationTaskRecord;
}
public void setQualificationTaskRecord(BQQualificationRetrieveOutputModelQualificationInstanceRecordQualificationTaskRecord qualificationTaskRecord) {
this.qualificationTaskRecord = qualificationTaskRecord;
}
} | java | 8 | 0.810705 | 236 | 33.82716 | 81 | starcoderdata |
public void map(Object key, Text value, Context context)
throws IOException, InterruptedException {
int which_center = 0;
stringToDoubleArray (value.toString(), dimension, point);
// get the vectors of the k cluster centers
// emit a key-value pair
// emitKey : cluster id that the input point belongs to
// value : the input point and the squared error of the current point
// with the coses center
//context.write (emitKey, valudde);
// TODO
// ------------------------------------------------------
//
// ------------------------------------------------------
emitKey.set (which_center);
context.write (emitKey, emitval);
} | java | 8 | 0.490397 | 81 | 40.157895 | 19 | inline |
# -*- encoding: utf-8 -*-
"""
去重且保留顺序
"""
def dedupe(items):
pool = set()
for item in items:
if item not in pool:
yield item
pool.add(item)
# 读文件去除重复行
with open('file', 'r') as f:
for line in dedupe(f):
pass | python | 10 | 0.541401 | 46 | 13.272727 | 22 | starcoderdata |
#include "Fraction.h"
#include
#include
#include
#include
#include
#include
int Fraction::Count = 0;
Fraction::Fraction():Fraction(1,1){
Count++;
}
Fraction::Fraction(int x,int y):x(x),y(y){
Count++;
}
Fraction::Fraction(const Fraction& fraction):Fraction(fraction.x,fraction.y){
Count++;
}
Fraction::~Fraction(){
std::cout<<"Fraction has been deleted"<<std::endl;
}
Fraction Fraction::operator+(Fraction a){
int y1=this->y;
int y2=a.x;
bool flag = true;
for(int i =1;i
if(this->y%i == 0){
for(int j =1; j<=a.y&&flag;j++){
if(a.y%j == 0){
if(this->y/i == a.y/j){
flag=false;
y1=i;
y2=j;
}
}
}
}
}
return Fraction(y1*a.x + y2*this->x, y1*a.y);
}
Fraction Fraction::operator-(Fraction a){
int y1=this->y;
int y2=a.x;
bool flag = true;
for(int i =1;i
if(this->y%i == 0){
for(int j =1; j<=a.y&&flag;j++){
if(a.y%j == 0){
if(this->y/i == a.y/j){
flag=false;
y1=i;
y2=j;
}
}
}
}
}
return Fraction(y1*a.x - y2*this->x, y1*a.y);
}
Fraction Fraction::operator*(Fraction a){
return Fraction(a.x * this->x, a.y * this->y);
}
Fraction Fraction::operator/(Fraction a){
return Fraction(a.y * this->x,a.x * this->y);
}
void Fraction::printDouble(){
std::cout
}
void Fraction::reduce(){
int xy = this->x < this->y? x: y;
for(int i=2;i<=xy;i++){
if(this->x%i == 0){
if(this->y%i== 0){
this->x = x/i;
this->y = y/i;
i--;
}
}
}
}
int Fraction::gcd(int a, int b){
while (a!=0 && b!=0)
if (a>b)
a=a%b;
else b=b%a;
return a+b;
}
void Fraction::printAsFraction(double decimal_fraction){
int temp = gcd(abs(decimal_fraction * 1000000), 1000000);
int x = (decimal_fraction * 1000000)/temp;
int y = 1000000 / temp;
std::cout << decimal_fraction << " = " << x << "/" << y <<std::endl;
}
void Fraction::printAsFraction(char* decimal_fraction){
double x = atof(decimal_fraction);
int temp = gcd(abs(x * 1000000), 1000000);
x = (x * 1000000) / temp;
int y = 1000000 / temp;
std::cout << decimal_fraction << " = " << x << "/" << y << std::endl;
} | c++ | 16 | 0.481495 | 77 | 22.947368 | 114 | starcoderdata |
#ifndef IMEMORYVIEW_H
#define IMEMORYVIEW_H
#include "location/location_defines.h"
#include "mem_defines.h"
class IMemoryView {
public:
IMemoryView() = default;
virtual ~IMemoryView() = default;
DISABLE_COPY_AND_MOVE(IMemoryView)
virtual Location getByte(const address_type address) = 0;
virtual Location getWord(const address_type address) = 0;
};
#endif // IMEMORYVIEW_H | c | 10 | 0.741379 | 69 | 22.882353 | 17 | starcoderdata |
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2018 NVIDIA Corporation. All rights reserved.
#ifndef RENDER_VOLUME_H
#define RENDER_VOLUME_H
#include "Apex.h"
namespace nvidia
{
namespace apex
{
PX_PUSH_PACK_DEFAULT
class IofxAsset;
class IofxActor;
/**
\brief An object which "owns" a volume of world space.
Any particles which enter the
owned volume will be migrated to an IOFX actor owned by this object (if the
particle's IOFX asset is affected by this volume).
When volumes overlap, their relative priorities break the tie. If multiple volumes
have the same priority, the tie breaker goes to the volume that owns the particle.
*/
class RenderVolume : public ApexInterface
{
public:
/// Returns AABB covering all objects in this render volume, it's updated each frame during Scene::fetchResults().
virtual physx::PxBounds3 getBounds() const = 0;
/// Returns true if the volume affects all IOFX assets
virtual bool getAffectsAllIofx() const = 0;
/// Adds IOFX asset to volume's list of affected IOFX assets, returns false on failure
virtual bool addIofxAsset(IofxAsset& iofx) = 0;
/// Moves the render volume while maintaining its dimensions
virtual void setPosition(const PxVec3& pos) = 0;
/// Directly assigns a new AABB ownership volume
virtual void setOwnershipBounds(const PxBounds3& b) = 0;
/// Retrieves the configured AABB bounds of the volume. Call getBounds() for the "live" bounds.
virtual PxBounds3 getOwnershipBounds() const = 0;
/** \brief Retrieve list of IOFX actors owned by this volume (one per IOFX Asset per IOS actor)
*
* Returns count of 0 if empty. Returned pointer is undefined when count is 0.
*
* The bounds of each of these IOFX is guaranteed to be within the bounds of the volume itself.
* Calling the updateRenderResources and dispatchRenderResources() methods of the volume will
* implicitly call the same methods of each of these IOFX actors, so there is no need to iterate
* over them for rendering purposes, unless you require special logic per IOFX.
*
* It is not necessary to release these actors, they will be released automatically when their
* volume, their IOFX Asset, or their host IOS actor are released.
*
* This call is not thread-safe. The returned buffer is only valid until the next APEX API
* call that steps the simulation or modifies the number of IOFX actors in a scene.
*/
virtual IofxActor* const* lockIofxActorList(uint32_t& count) = 0;
/**
\brief Unlock IOFX actors which where locked by calling lockIofxActorList
\see RenderVolume::lockIofxActorList
*/
virtual void unlockIofxActorList() = 0;
/** \brief Retrieve list of volume's affected IOFX assets.
*
* Returns count of 0 if empty or volume affects all IOFX assets. Returned pointer is
* undefined when count is 0.
*
* The returned buffer not thread-safe, and is only valid until the next APEX API
* call that steps the simulation or modifies the number of IOFX assets in a scene.
*/
virtual IofxAsset* const* getIofxAssetList(uint32_t& count) const = 0;
virtual PxVec3 getPosition() const = 0; ///< Returns center of ownership bounds
virtual uint32_t getPriority() const = 0; ///< Returns priority of volume
/** \brief Returns true if this volume affects the specified IOFX asset
*
* Callers must acquire render lock of the volume before calling
* this function, for thread safety.
*/
virtual bool affectsIofxAsset(const IofxAsset& iofx) const = 0;
protected:
virtual ~RenderVolume() {}
};
PX_POP_PACK
}
} // namespace nvidia
#endif // RENDER_VOLUME_H | c | 17 | 0.746509 | 115 | 38.726563 | 128 | starcoderdata |
import { createActions } from 'reduxsauce'
const { Types, Creators } = createActions({
saveNewProblem: ['data'],
setProblemData: ['data'],
viewHistoricProblem: ['id'],
viewNewProblem: ['data'],
})
export const ProblemSolverTypes = Types
export default Creators | javascript | 7 | 0.723906 | 43 | 23.75 | 12 | starcoderdata |
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponseRedirect
from django.utils.encoding import force_text
from django.views.generic import DetailView
def all_valid(formsets):
"""Returns true if every formset in formsets is valid."""
valid = True
for formset in formsets:
if not formset.is_valid():
valid = False
return valid
class DetailWithInlineView(DetailView):
template_name = "detail_with_inline_view.html"
inlines = []
model = None
success_url = ""
def get_context_data(self, **kwargs):
context = super(DetailWithInlineView, self).get_context_data(**kwargs)
inlines = self.construct_inlines()
context.update({"inlines": inlines})
return context
def get_inlines(self):
"""
Returns the inline formset classes
"""
return self.inlines
def forms_valid(self, inlines):
"""
If the form and formsets are valid, save the associated models.
"""
for formset in inlines:
formset.save()
return HttpResponseRedirect(self.get_success_url())
def forms_invalid(self, inlines):
"""
If the form or formsets are invalid, re-render the context data with the
data-filled form and formsets and errors.
"""
return self.render_to_response(self.get_context_data(inlines=inlines))
def construct_inlines(self):
"""
Returns the inline formset instances
"""
inline_formsets = []
for inline_class in self.get_inlines():
inline_instance = inline_class(self.model, self.request, self.object, self.kwargs, self)
inline_formset = inline_instance.construct_formset()
inline_formsets.append(inline_formset)
return inline_formsets
def post(self, request, *args, **kwargs):
"""
Handles POST requests, instantiating a form and formset instances with the passed
POST variables and then checked for validity.
"""
self.object = self.get_object()
self.get_context_data()
inlines = self.construct_inlines()
if all_valid(inlines):
return self.forms_valid(inlines)
return self.forms_invalid(inlines)
# PUT is a valid HTTP verb for creating (with a known URL) or editing an
# object, note that browsers only support POST for now.
def put(self, *args, **kwargs):
return self.post(*args, **kwargs)
def get_success_url(self):
"""
Returns the supplied success URL.
"""
if self.success_url:
# Forcing possible reverse_lazy evaluation
url = force_text(self.success_url)
else:
raise ImproperlyConfigured(
"No URL to redirect to. Provide a success_url.")
return url | python | 12 | 0.625994 | 100 | 31.875 | 88 | starcoderdata |
<?php
use Illuminate\Container\Container;
if (! function_exists('environment_file_path')) {
/**
* Get application environment file path.
*
* For both Laravel and Lumen framework.
*
* @param string $helper
* @param string $envFile
*
* @return string
*/
function environment_file_path($helper = 'environmentFilePath', $envFile = '.env'): string
{
$app = Container::getInstance();
if (method_exists($app, $helper)) {
return $app->{$helper}();
}
// Lumen
return $app->basePath($envFile);
}
} | php | 11 | 0.558966 | 94 | 21.107143 | 28 | starcoderdata |
ULIB_EXPORT
PVOID
AutoChkMalloc(
ULONG bytes
)
{
PVOID p;
LONG status;
LARGE_INTEGER timeout = { -10000, -1 }; // 100 ns resolution
while (InterlockedCompareExchange(&InUse, 1, 0) != 0)
NtDelayExecution(FALSE, &timeout);
if (HeapLeft == -1) {
SYSTEM_PERFORMANCE_INFORMATION PerfInfo;
SYSTEM_BASIC_INFORMATION BasicInfo;
ULONG64 dwi;
ULONG64 user_addr_space;
status = NtQuerySystemInformation(
SystemBasicInformation,
&(BasicInfo),
sizeof(BasicInfo),
NULL
);
if (!NT_SUCCESS(status)) {
InterlockedDecrement(&InUse);
KdPrintEx((DPFLTR_AUTOCHK_ID, DPFLTR_ERROR_LEVEL,
"AutoChkMalloc: NtQuerySystemInformation(SystemBasicInfo) failed %x\n", status));
return NULL;
}
status = NtQuerySystemInformation(
SystemPerformanceInformation,
&(PerfInfo),
sizeof(PerfInfo),
NULL
);
if (!NT_SUCCESS(status)) {
InterlockedDecrement(&InUse);
KdPrintEx((DPFLTR_AUTOCHK_ID, DPFLTR_ERROR_LEVEL,
"AutoChkMalloc: NtQuerySystemInformation(SystemPerformanceInfo) failed %x\n", status));
return NULL;
}
KdPrintEx((DPFLTR_AUTOCHK_ID, DPFLTR_INFO_LEVEL,
"AutoChkMalloc: Pagesize %x\n", BasicInfo.PageSize));
KdPrintEx((DPFLTR_AUTOCHK_ID, DPFLTR_INFO_LEVEL,
"AutoChkMalloc: Min User Addr %Ix\n", (ULONG64)BasicInfo.MinimumUserModeAddress));
KdPrintEx((DPFLTR_AUTOCHK_ID, DPFLTR_INFO_LEVEL,
"AutoChkMalloc: Max User Addr %Ix\n", (ULONG64)BasicInfo.MaximumUserModeAddress));
KdPrintEx((DPFLTR_AUTOCHK_ID, DPFLTR_INFO_LEVEL,
"AutoChkMalloc: AvailablePages %x\n", PerfInfo.AvailablePages));
user_addr_space = BasicInfo.MaximumUserModeAddress - BasicInfo.MinimumUserModeAddress;
dwi = BasicInfo.PageSize;
dwi *= PerfInfo.AvailablePages;
if (user_addr_space < dwi)
dwi = user_addr_space; // can't go beyond available user address space
if (dwi == -1) {
dwi -= 1;
}
KdPrintEx((DPFLTR_AUTOCHK_ID, DPFLTR_INFO_LEVEL, "AutoChkMalloc: DWI %I64x\n", dwi));
//
// The following magic number is simply a reserve subtracted off
// the heap total to give the system some head room during the
// AUTOCHK phase
//
if (dwi <= (100ul * 1024ul)) {
HeapLeft = 0;
} else {
HeapLeft = dwi - dwi/10;
}
KdPrintEx((DPFLTR_AUTOCHK_ID, DPFLTR_INFO_LEVEL,
"AutoChkMalloc: HeapLeft %I64x\n", HeapLeft));
}
if (bytes > HeapLeft) {
ULONG64 heapLeft = HeapLeft;
status = InterlockedDecrement(&InUse);
DebugAssert(status == 0);
KdPrintEx((DPFLTR_AUTOCHK_ID, DPFLTR_ERROR_LEVEL,
"AutoChkMalloc: Out of memory: Avail %I64x, Asked %x\n",
heapLeft, bytes));
return (NULL);
}
p = RtlAllocateHeap(RtlProcessHeap(), 0, bytes);
if (p) {
HeapLeft -= bytes;
status = InterlockedDecrement(&InUse);
} else {
ULONG64 heapLeft = HeapLeft;
status = InterlockedDecrement(&InUse);
KdPrintEx((DPFLTR_AUTOCHK_ID, DPFLTR_ERROR_LEVEL,
"AutoChkMalloc: Out of memory possibly due to fragmentation: Avail %I64x, Asked %x\n",
heapLeft, bytes));
}
DebugAssert(status == 0);
return p;
} | c++ | 15 | 0.532438 | 110 | 32.034483 | 116 | inline |
public override bool StripStuff(LinkedListNode<OTStmt> link)
{
// strip behind-the-scenes info from all the sub-blocks.
bool rc = tryblock.StripStuff(null);
foreach (OTStmtBegCatBlk catblk in catches)
{
rc |= catblk.StripStuff(null);
}
if (finblock != null)
rc |= finblock.StripStuff(null);
if (rc)
return true;
// change:
// try {
// ...
// }
// to:
// {
// ...
// }
// note that an empty catch () { } has meaning so can't be stripped
// empty finally { } blocks strips itself from the try
if ((catches.Count == 0) && (finblock == null) && (link != null))
{
link.List.AddAfter(link, tryblock);
tryblock = null;
link.List.Remove(link);
return true;
}
return false;
} | c# | 11 | 0.373322 | 83 | 35.151515 | 33 | inline |
/*
*
* This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file.
*
* Copyright 2007-2019 Broadcom Inc. All rights reserved.
*
* File: mirror.c
* Purpose: Common Mirror API
*/
#include
#include
#include
#include
#include
#include
#include
/*
* Function:
* bcm_mirror_destination_t_init
* Purpose:
* Initialize a mirror destination structure
* Parameters:
* mirror_dest - pointer to the bcm_mirror_destination_t structure.
* Returns:
* NONE
*/
void
bcm_mirror_destination_t_init(bcm_mirror_destination_t *mirror_dest)
{
if (NULL != mirror_dest) {
sal_memset (mirror_dest, 0, sizeof(bcm_mirror_destination_t));
mirror_dest->stat_id2 = -1;
}
return;
}
/*
* Function:
* bcm_mirror_port_info_t_init
* Purpose:
* Initialize a mirror port info structure
* Parameters:
* mirror_info - pointer to the bcm_mirror_port_info_t structure.
* Returns:
* NONE
*/
void
bcm_mirror_port_info_t_init(bcm_mirror_port_info_t *info)
{
if (NULL != info) {
sal_memset (info, 0, sizeof(bcm_mirror_port_info_t));
}
return;
}
/*
* Function:
* bcm_mirror_options_t_init
* Purpose:
* Initialize a mirror options structure
* Parameters:
* options - pointer to the bcm_mirror_options_t structure.
* Returns:
* NONE
*/
void
bcm_mirror_options_t_init(bcm_mirror_options_t *options)
{
if (NULL != options) {
sal_memset (options, 0, sizeof(bcm_mirror_options_t));
/* Enable mirroring by default*/
options->forward_strength = 1;
options->copy_strength = 1 ;
}
return;
}
/*
* Function:
* bcm_mirror_pkt_header_updates_t_init
* Purpose:
* Initialize a mirror pkt header updates structure
* Parameters:
* updates - pointer to the bcm_mirror_pkt_header_updates_t structure.
* Returns:
* NONE
*/
void
bcm_mirror_pkt_header_updates_t_init(bcm_mirror_pkt_header_updates_t *updates)
{
if (NULL != updates) {
sal_memset (updates, 0, sizeof(bcm_mirror_pkt_header_updates_t));
}
return;
}
/*
* Function:
* bcm_mirror_header_info_t_init
* Purpose:
* Initialize a mirror header information structure
* Parameters:
* updates - pointer to the bcm_mirror_header_info_t structure.
* Returns:
* NONE
*/
void
bcm_mirror_header_info_t_init(bcm_mirror_header_info_t *mirror_header_info)
{
if (NULL != mirror_header_info) {
sal_memset (mirror_header_info, 0, sizeof(bcm_mirror_header_info_t));
}
return;
}
/*
* Function:
* bcm_mirror_payload_zero_info_t_init
* Purpose:
* Initialize a payload zero info structure
* Parameters:
* info - Pointer to the bcm_mirror_payload_zero_info_t structure
* Returns:
* NONE
*/
void
bcm_mirror_payload_zero_info_t_init(bcm_mirror_payload_zero_info_t *info)
{
if (NULL != info) {
sal_memset(info, 0, sizeof(bcm_mirror_payload_zero_info_t));
}
return;
}
/*
* Function:
* bcm_mirror_payload_zero_offsets_t_init
* Purpose:
* Initialize a payload zero offset structure
* Parameters:
* info - Pointer to the bcm_mirror_payload_zero_offsets_t structure
* Returns:
* NONE
*/
void
bcm_mirror_payload_zero_offsets_t_init(bcm_mirror_payload_zero_offsets_t *offset)
{
if (NULL != offset) {
offset->l2_offset = -1;
offset->l3_offset = -1;
offset->udp_offset = -1;
}
return;
} | c | 10 | 0.636116 | 134 | 21.284848 | 165 | starcoderdata |
<?php
namespace App\Interfaces;
use Illuminate\Database\Eloquent\Collection;
/**
* Interface RepositoryInterface
* @package App\Repository
*/
interface RepositoryInterface {
/**
* Create New Entity
*
* @param array $entityData
* @return Entity
*/
public function create(array $entityData);
/**
* Get Entity by ID
* @param $entity_id
* @return Entity
*/
public function findById($entity_id);
/**
* Get All objects in an Entity
* @return Entity List
*/
public function findAll();
} | php | 8 | 0.611888 | 46 | 16.90625 | 32 | starcoderdata |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnManager : MonoBehaviour {
public List Spawners = new List
public GameObject GoodBlockObject;
public GameObject BadBlockObject;
public float BadBlockFrequency = 2f;
public float BadBlockFrequencyDecrease = 0.1f;
public float BadBlockFrequencyMin = 0.1f;
private float _currentTimer = 0f;
private bool _spawnerActive = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update()
{
if (_spawnerActive)
{
if(_currentTimer >= BadBlockFrequency)
{
//Spawn bad Block at random Spawner
int _randomSpawner = (int) UnityEngine.Random.Range(0, Spawners.Count);
Spawners[_randomSpawner].OverrideNextObjectToSpawn = BadBlockObject;
_currentTimer = 0f;
BadBlockFrequency -= BadBlockFrequencyDecrease;
BadBlockFrequency = Mathf.Max(BadBlockFrequency, BadBlockFrequencyMin);
}else
{
_currentTimer += Time.deltaTime;
}
}
}
public void StartSpawner()
{
_spawnerActive = true;
InitializeSpawners();
}
private void InitializeSpawners()
{
foreach (Spawner s in Spawners)
{
s.ObjectToSpawn = GoodBlockObject;
s.IsSpawning = true;
}
}
public void StopSpawning()
{
_spawnerActive = false;
foreach (Spawner s in Spawners)
{
s.ObjectToSpawn = GoodBlockObject;
s.IsSpawning = false;
s.gameObject.SetActive(false);
}
}
} | c# | 18 | 0.592778 | 87 | 24 | 72 | starcoderdata |
const Sequelize = require('sequelize');
module.exports = {
accounts: {
schema: {
id: {
type: Sequelize.STRING,
primaryKey: true,
},
name: Sequelize.STRING,
currencyCode: Sequelize.STRING,
balance: Sequelize.FLOAT,
availableAmount: Sequelize.FLOAT,
blockedAmount: Sequelize.FLOAT,
},
cacheOnInit: true,
},
transactions: {
schema: {
id: {
type: Sequelize.STRING,
primaryKey: true,
},
accountID: Sequelize.STRING,
madeOn: Sequelize.STRING,
amount: Sequelize.FLOAT,
currencyCode: Sequelize.STRING,
description: Sequelize.STRING,
mode: Sequelize.STRING,
category: Sequelize.STRING,
},
cacheOnInit: true,
},
}; | javascript | 12 | 0.504663 | 45 | 25.805556 | 36 | starcoderdata |
#ifndef __UTILITY_MEMORY_ADV_ALLOCATOR__
#define __UTILITY_MEMORY_ADV_ALLOCATOR__
#include
namespace utility
{
namespace memory
{
template<typename _T>
using allocator = basic_allocator
}
}
#endif // ! __UTILITY_MEMORY_ADV_ALLOCATOR__ | c++ | 12 | 0.699029 | 44 | 17.176471 | 17 | starcoderdata |
void update() {
int8_t vX, vY;
if (slowmoTimeout % 2 && !player)
return;
// move item with the map
if (gameFrames % MOVE_MAP_INTERVAL == 0)
x -= 1;
if (type == WEAPON_STDGUN) {
vX = 5;
vY = 0;
} else if (type == WEAPON_ROCKET) {
vX = 4 + pT.lvlWeapon[WEAPON_ROCKET];
vY = 0;
} else if (type == WEAPON_LASER) {
vX = 10;
vY = 0;
} else if (type == WEAPON_MG) {
vX = 4;
vY = 0;
if (state != 0) {
if (gameFrames % state == 0) {
if (state % 2) {
vY = 1;
} else {
vY = -1;
}
}
}
} else if (type == WEAPON_FLAME) {
vX = 4;
vY = 0;
state += 4;
// the range increases with a higher level, also by enemys!!
if (state > 4 * (15 + pT.lvlWeapon[WEAPON_FLAME])) {
active = false;
}
} else if (type == WEAPON_SMALL_ROCKET) {
vX = 2;
vY = 0;
if (state != 0) {
// the smaller the value that is divided, the more vertical the ememys shoot
if (gameFrames % abs(80 / state) == 0 )
vY = state / abs(state);
}
}
if (!player) {
vX = vX * -1;
}
x += vX;
y += vY;
} | c | 24 | 0.412254 | 84 | 18.369231 | 65 | inline |
void humanBody(){
glColor3f(1,0.87,0.77);
glPushMatrix();
glRotatef(-10,0,0,1);
DrawEllipse(10,50,0,0); //left leg
glPopMatrix();
glPushMatrix();
glRotatef(10,0,0,1);
DrawEllipse(10,50,25,-7); //right leg
glPopMatrix();
DrawEllipse(20,50,12,70); //center torso
glPushMatrix();
glRotatef(60,0,0,1);
DrawEllipse(40,10,60,55); // left arm
glPopMatrix();
glPushMatrix();
glRotatef(-60,0,0,1);
DrawEllipse(40,10,-50,75);// right arm
glPopMatrix();
DrawEllipse(15,25,12,135); //head
glPushMatrix();
glColor3f(1,0,0);
glBegin(GL_LINES);
glVertex2f(12,30); // center blood vessel
glVertex2f(12,120);
glVertex2f(12,118); // left line
glVertex2f(-8,90);
glVertex2f(-8,90); // left arm
glVertex2f(-30,60);
glVertex2f(12,118); // right vessel
glVertex2f(50,65);
glVertex2f(12,35); // right down blood vessel
glVertex2f(25,10);
glVertex2f(25,10); // right down calf blood vessel
glVertex2f(30,-20);
glVertex2f(12,35); // left down blood vessel
glVertex2f(2,10);
// left down blood vessel
glVertex2f(2,10);
glVertex2f(-5,-30);
glEnd();
} | c++ | 6 | 0.570079 | 55 | 20.542373 | 59 | inline |
/** @jsx jsx */
import { jsx } from 'theme-ui'
import { Paper } from '@material-ui/core'
import { Grid } from '@material-ui/core'
import Typography from '@material-ui/core/Typography'
import FormDialog from './form-dialog'
import * as React from 'react'
const EventList = ({ events, book }) => {
return (
{events.map(event => (
<Grid item xs={12} key={event.id}>
<Paper
sx={{
margin: 'auto',
cursor: 'pointer',
'&:hover': {
zIndex: 100,
},
}}
>
<Grid item xs={12} sm container>
<Grid item xs container direction="column" spacing={2}>
<Grid item xs>
<Typography gutterBottom variant="subtitle1">
{event.summary}
<Typography variant="body2" gutterBottom>
{event.start.dateTime} - {event.end.dateTime}
<Typography variant="body2">{event.location}
<Grid item>
<FormDialog onSubmit={book} event={event} />
<Grid item>
<Typography variant="subtitle1">$19.00
<Typography variant="subtitle2">{event.id}
))}
)
}
const TimeGrid = props => {
return (
<Grid spacing={3} container>
<EventList {...props} />
)
}
export default TimeGrid | javascript | 22 | 0.480588 | 75 | 28.310345 | 58 | starcoderdata |
<?php
//打开指定目录
/**
* 遍历目录函数,只读取目录中的最外层的内容
* @param string $path
* @return array
*/
function readDirectory($path)
{
$arr = [];
$handle = opendir($path);
while (($item = readdir($handle)) !== false) {
//.和..这2个特殊目录
if ($item != "." && $item != "..") {
if (is_file($path . "/" . $item)) {
$arr['file'][] = $item;
}
if (is_dir($path . "/" . $item)) {
$arr['dir'][] = $item;
}
}
}
closedir($handle);
return $arr;
}
/**
* 得到文件夹大小
* @param string $path
* @return int
*/
function dirSize($path)
{
$sum = 0;
global $sum;
$handle = opendir($path);
while (($item = readdir($handle)) !== false) {
if ($item != "." && $item != "..") {
if (is_file($path . "/" . $item)) {
$sum += filesize($path . "/" . $item);
}
if (is_dir($path . "/" . $item)) {
$func = __FUNCTION__;
$func($path . "/" . $item);
}
}
}
closedir($handle);
return $sum;
} | php | 17 | 0.480044 | 47 | 16.686275 | 51 | starcoderdata |
/* -*- indent-tabs-mode: t -*- */
#ifndef MPI3_MESSAGE_HPP
#define MPI3_MESSAGE_HPP
#include "../mpi3/detail/iterator_traits.hpp"
#include "../mpi3/detail/value_traits.hpp"
#include
namespace boost {
namespace mpi3 {
class message {
public:
MPI_Message impl_; // NOLINT(misc-non-private-member-variables-in-classes) TODO(correaa)
MPI_Message operator&() const {return impl_;} // NOLINT(google-runtime-operator) design
template<class It, typename Size>
auto receive_n(
It it,
detail::contiguous_iterator_tag /*contiguous*/,
detail::basic_tag /*basic*/,
Size count
) {
int s = MPI_Mrecv(detail::data(it), count, detail::basic_datatype<typename std::iterator_traits &impl_, MPI_STATUS_IGNORE);
if(s != MPI_SUCCESS) {throw std::runtime_error{"cannot message receive"};}
}
template<class It, typename Size>
auto receive_n(It it, Size count) {
return receive_n(
it,
detail::iterator_category_t
detail::value_category_t<typename std::iterator_traits
count
);
}
template<class It>
auto receive(
It first, It last,
detail::random_access_iterator_tag /*random_access*/
) {
return receive_n(first, std::distance(first, last));
}
template<class It>
auto receive(It first, It last) {
return receive(
first, last,
detail::iterator_category_t
);
}
};
} // end namespace mpi3
} // end namespace boost
//#ifdef _TEST_MPI3_MESSAGE
//#include "../mpi3/main.hpp"
//namespace mpi3 = boost::mpi3;
//int mpi3::main(int, char*[], mpi3::communicator world){
//}
//#endif
#endif | c++ | 26 | 0.673267 | 145 | 22.085714 | 70 | starcoderdata |
package com.github.fridujo.rabbitmq.mock.exchange;
public interface TypedMockExchangeCreator extends MockExchangeCreator {
String getType();
} | java | 5 | 0.815642 | 71 | 24.571429 | 7 | starcoderdata |
"""Module contains an approximate garbage score estimator
See ags_.
"""
from typing import Optional, List, Union
from FaceEngine import IAGSEstimatorPtr # pylint: disable=E0611,E0401
from lunavl.sdk.detectors.facedetector import FaceDetection
from lunavl.sdk.errors.errors import LunaVLError
from lunavl.sdk.errors.exceptions import CoreExceptionWrap, assertError
from ..base import BaseEstimator, ImageWithFaceDetection
from ..estimators_utils.extractor_utils import validateInputByBatchEstimator
class AGSEstimator(BaseEstimator):
"""
Approximate garbage score estimator.
"""
# pylint: disable=W0235
def __init__(self, coreEstimator: IAGSEstimatorPtr):
"""
Init.
Args:
coreEstimator: core estimator
"""
super().__init__(coreEstimator)
# pylint: disable=W0221
@CoreExceptionWrap(LunaVLError.EstimationAGSError)
def estimate(
self, detection: Optional[FaceDetection] = None, imageWithFaceDetection: Optional[ImageWithFaceDetection] = None
) -> float:
"""
Estimate ags for single image/detection.
Args:
detection: face detection
imageWithFaceDetection: image with face detection
Returns:
estimated ags, float in range[0,1]
Raises:
LunaSDKException: if estimation failed
ValueError: if image and detection are None
"""
if detection is None:
if imageWithFaceDetection is None:
raise ValueError("image and boundingBox or detection must be not None")
error, ags = self._coreEstimator.estimate(
imageWithFaceDetection.image.coreImage, imageWithFaceDetection.boundingBox.coreEstimation
)
else:
error, ags = self._coreEstimator.estimate(detection.image.coreImage, detection.boundingBox.coreEstimation)
assertError(error)
return ags
@CoreExceptionWrap(LunaVLError.EstimationAGSError)
def estimateBatch(self, detections: Union[List[FaceDetection], List[ImageWithFaceDetection]]) -> List[float]:
"""
Estimate ags for list of detections.
Args:
detections: face detection list or list of image with its face detection
Returns:
list of estimated ags, float in range[0,1]
Raises:
LunaSDKException: if estimation failed
ValueError: if empty image list and empty detection list or images count not match bounding boxes count
"""
coreImages = [detection.image.coreImage for detection in detections]
boundingBoxEstimations = [detection.boundingBox.coreEstimation for detection in detections]
validateInputByBatchEstimator(self._coreEstimator, coreImages, boundingBoxEstimations)
error, agsList = self._coreEstimator.estimate(coreImages, boundingBoxEstimations)
assertError(error)
return agsList | python | 15 | 0.684779 | 120 | 35.134146 | 82 | starcoderdata |
## import numpy, panda, statsmodels
import pandas as pd
import numpy as np
from sklearn import linear_model
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib as mpl
mpl.use('TkAgg') # backend adjustment
import matplotlib.pyplot as plt
## read csv dataset
url = "https://raw.githubusercontent.com/sashaboulouds/statistics/master/data/costsalary.csv"
costsalary = pd.read_csv(url, sep=";", header=0)
df = pd.DataFrame(costsalary)
## set data
y = pd.DataFrame(costsalary, columns = ['Salary'])
x = pd.DataFrame(costsalary, columns = ['Costs'])
## descriptive statistics
print x.describe()
print y.describe()
## model
model = linear_model.LinearRegression()
model.fit(x,y)
predictions = model.predict(x)
coefficients = []
coefficients.append(model.intercept_)
coefficients.append(model.coef_)
print coefficients
print("Mean squared error: %.2f" % mean_squared_error(x, y))
print('R2 score: %.2f' % r2_score(x, y))
## plot
plt.scatter(x, y, color='black')
plt.plot(x, predictions, color='red')
plt.savefig("plot1.png")
plt.clf()
## residuals
residuals = y-model.predict(x)
print "Residuals mean: " + str(int(residuals.mean()))
plt.plot(residuals)
plt.savefig("residuals.png")
plt.clf() | python | 9 | 0.73491 | 93 | 25.085106 | 47 | starcoderdata |
package adapter.classAdapter;
/**
* 类适配器
* 通过多重继承目标接口和被适配者类方式来实现适配
*/
public class ClassAdapterDemo {
public static void main(String[] args) {
//通过适配器创建一个VGA对象,这个适配器实际是使用的是USB的showPPT()方法
VGA a=new AdapterUSB2VGA();
//进行投影
Projector p1=new Projector();
p1.projection(a);
}
} | java | 9 | 0.636364 | 52 | 17.333333 | 18 | starcoderdata |
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// package build -- go2cs converted at 2020 October 09 05:20:01 UTC
// import "go/build" ==> using build = go.go.build_package
// Original source: C:\Go\src\go\build\syslist.go
using static go.builtin;
namespace go {
namespace go
{
public static partial class build_package
{
// List of past, present, and future known GOOS and GOARCH values.
// Do not remove from this list, as these are used for go/build filename matching.
private static readonly @string goosList = (@string)"aix android darwin dragonfly freebsd hurd illumos js linux nacl netbsd openbsd plan9 solaris windows zos ";
private static readonly @string goarchList = (@string)"386 amd64 amd64p32 arm armbe arm64 arm64be ppc64 ppc64le mips mipsle mips64 mips64le mips64p32 mips64p32le ppc riscv riscv64 s390 s390x sparc sparc64 wasm ";
}
}} | c# | 13 | 0.730503 | 220 | 43.043478 | 23 | starcoderdata |
package org.firstinspires.ftc.teamcode.TeleOp;
import com.qualcomm.hardware.rev.RevBlinkinLedDriver;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import org.firstinspires.ftc.robotcore.external.navigation.DistanceUnit;
import org.firstinspires.ftc.teamcode.VhisolaHardware;
@TeleOp
//@Disabled
public class VhisolaOp extends LinearOpMode {
VhisolaHardware robot = new VhisolaHardware();
//private double power = .5;
@Override
public void runOpMode(){
robot.init(hardwareMap);
//ALREADY IN HWMAP????
robot.fpd.setDirection(DcMotorSimple.Direction.FORWARD);
robot.bpd.setDirection(DcMotorSimple.Direction.FORWARD);
robot.fsd.setDirection(DcMotorSimple.Direction.REVERSE);
robot.bsd.setDirection(DcMotorSimple.Direction.REVERSE);
robot.fpd.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
robot.bpd.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
robot.fsd.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
robot.bsd.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
//robot.bpd.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
//robot.bsd.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
telemetry.addData("Status:", "Run time dudes");
telemetry.update();
waitForStart();
while(opModeIsActive()){
drive();
gamepadLocal();
spin();
wobbleLifter();
wobbleHand();
intakeMaki();
slice();
shoot();
resetBECounters();
getDistance();
telemetry.addData("sideways movement pos: ", (robot.bpd.getCurrentPosition()/ robot.COUNTS_PER_INCH_BE));
telemetry.addData("for/back movement pos: ", (-robot.bsd.getCurrentPosition()/ robot.COUNTS_PER_INCH_BE));
telemetry.addData("the reset button is dpad up or down", "");
telemetry.addData("cm: ", robot.plsWork.getDistance(DistanceUnit.CM)); //add to telemetry update
telemetry.update();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
public void drive(){
if(gamepad1.right_stick_x < 0.2 && gamepad1.right_stick_x > -0.2 && gamepad1.right_stick_y < -0.5) { //forward
robot.fpd.setPower(gamepad1.right_stick_y);
robot.bpd.setPower(gamepad1.right_stick_y);
robot.fsd.setPower(gamepad1.right_stick_y);
robot.bsd.setPower(gamepad1.right_stick_y);
telemetry.addData("for","");
} else if(gamepad1.right_stick_x > -0.2 && gamepad1.right_stick_x < 0.2 && gamepad1.right_stick_y > 0.5){ //backwards
robot.fpd.setPower(gamepad1.right_stick_y);
robot.bpd.setPower(gamepad1.right_stick_y);
robot.fsd.setPower(gamepad1.right_stick_y);
robot.bsd.setPower(gamepad1.right_stick_y);
telemetry.addData("back","");
} else if (gamepad1.right_stick_x > 0.5 && (gamepad1.right_stick_y > -0.25 && gamepad1.right_stick_y < 0.25) ){ //star
robot.fsd.setPower(gamepad1.right_stick_x);
robot.bsd.setPower(-gamepad1.right_stick_x);
robot.fpd.setPower(-gamepad1.right_stick_x);
robot.bpd.setPower(gamepad1.right_stick_x);
telemetry.addData("star","");
} else if ((gamepad1.right_stick_x < -0.5 && gamepad1.right_stick_y > -0.25 && gamepad1.right_stick_y < 0.25) ) { //port
robot.fsd.setPower(gamepad1.right_stick_x);
robot.bsd.setPower(-gamepad1.right_stick_x);
robot.fpd.setPower(-gamepad1.right_stick_x);
robot.bpd.setPower(gamepad1.right_stick_x);
telemetry.addData("port","");
/*}else if((gamepad1.right_stick_x > -1 && gamepad1.right_stick_x < -0.2) && (gamepad1.right_stick_y < -.25 && gamepad1.right_stick_y > -1)){ //front port (left)
robot.fpd.setPower(0.0);
robot.bpd.setPower(gamepad1.right_stick_y);
robot.bsd.setPower(0.0);
robot.fsd.setPower(gamepad1.right_stick_y);
telemetry.addData("fp","");
}else if(gamepad1.right_stick_x > 0.2 && gamepad1.right_stick_x < 1 && gamepad1.right_stick_y > -1 && gamepad1.right_stick_y < -0.25){ //front star (right)
robot.fpd.setPower(gamepad1.right_stick_y);
robot.bpd.setPower(0.0);
robot.bsd.setPower(gamepad1.right_stick_y);
robot.fsd.setPower(0.0);
telemetry.addData("fs","");
}else if(gamepad1.right_stick_x > -1 && gamepad1.right_stick_x < -0.25 && gamepad1.right_stick_y > 0.25 && gamepad1.right_stick_y < 1){ //back port
robot.fpd.setPower(gamepad1.right_stick_y);
robot.bpd.setPower(0.0);
robot.bsd.setPower(gamepad1.right_stick_y);
robot.fsd.setPower(0.0);
telemetry.addData("bp","");
}else if(gamepad1.right_stick_x > 0.2 && gamepad1.right_stick_x < 1 && gamepad1.right_stick_y < 1 && gamepad1.right_stick_y > 0.25){ //back star
robot.fpd.setPower(0.0);
robot.bpd.setPower(gamepad1.right_stick_y);
robot.bsd.setPower(0.0);
robot.fsd.setPower(gamepad1.right_stick_y);
telemetry.addData("bs","");
*/
} else{
robot.fpd.setPower(0.0);
robot.bpd.setPower(0.0);
robot.fsd.setPower(0.0);
robot.bsd.setPower(0.0);
}
telemetry.update();
} //gamepad 1 -- no controller change
public void gamepadLocal(){
telemetry.addData("gamepad1 X;", gamepad1.right_stick_x );
telemetry.addData("gamepad1 Y;", gamepad1.right_stick_y );
telemetry.update();
}
public void spin(){
if(gamepad1.left_stick_x > 0.86 && gamepad1.left_stick_y > -0.5 && gamepad1.left_stick_y < 0.5){ //clockwise
robot.fpd.setPower(-gamepad1.left_stick_x);
robot.bpd.setPower(-gamepad1.left_stick_x);
robot.fsd.setPower(gamepad1.left_stick_x);
robot.bsd.setPower(gamepad1.left_stick_x);
}else if(gamepad1.left_stick_x < -0.86 && gamepad1.left_stick_y > -0.5 && gamepad1.left_stick_y < 0.5 ){ //counterclockwise
robot.fpd.setPower(-gamepad1.left_stick_x);
robot.bpd.setPower(-gamepad1.left_stick_x);
robot.fsd.setPower(gamepad1.left_stick_x);
robot.bsd.setPower(gamepad1.left_stick_x);
}
}
public void wobbleHand(){
if(gamepad1.x) { //open servo
robot.blueFruit.setPosition(robot.openBlue);
robot.greyFruit.setPosition(robot.openGrey);
}else if(gamepad1.b) { //closed servo
robot.blueFruit.setPosition(robot.closedBlue);
robot.greyFruit.setPosition(robot.closedGrey);
}
}
public void wobbleLifter(){
if(gamepad1.y){ //lift hopefully
robot.wobbleMotor.setPower(robot.wobbleSpeed);
} else if(gamepad1.a){ //placed down hopefully
robot.wobbleMotor.setPower(-(robot.wobbleSpeed));
} else {
robot.wobbleMotor.setPower(0.0);
}
}
public void intakeMaki(){
if(gamepad1.left_trigger != 0){ //eat
robot.intakeTop.setPower(robot.intakeTopSpeed);
robot.intakeBottom.setPower(robot.intakeSpeed);
} else if(gamepad1.right_trigger != 0){ //spit out
robot.intakeTop.setPower(-(robot.intakeTopSpeed));
robot.intakeBottom.setPower(-(robot.intakeSpeed));
} else {
robot.intakeTop.setPower(0.0);
robot.intakeBottom.setPower(0.0);
}
}
public void slice(){
if( gamepad1.right_bumper) {
robot.butterKnife.setPosition(robot.butterShoot);
sleep(50);
} else{
robot.butterKnife.setPosition(robot.butterStop);
}
}
public void shoot(){
if(gamepad1.left_bumper){
//robot.shooty.setVelocity(robot.shootVelo);
robot.shooty.setPower(.74); //.72
}
else{
robot.shooty.setPower(0);
}
}
public void resetBECounters(){
if(gamepad1.dpad_down || gamepad1.dpad_up){
robot.bpd.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
robot.bsd.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
robot.bpd.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
robot.bsd.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
}
}
public void getDistance()
{
telemetry.addData("cm: ", robot.plsWork.getDistance(DistanceUnit.CM));
if (robot.plsWork.getDistance(DistanceUnit.CM) < 6.3) { //3 rings 5-6
robot.led.setPattern(RevBlinkinLedDriver.BlinkinPattern.GREEN);
} else if (robot.plsWork.getDistance(DistanceUnit.CM) < 7.7) { //2 rings 7.3 - 8
robot.led.setPattern(RevBlinkinLedDriver.BlinkinPattern.YELLOW);
} else if (robot.plsWork.getDistance(DistanceUnit.CM) < 8.7) { //1 rings 8-9
robot.led.setPattern(RevBlinkinLedDriver.BlinkinPattern.RED);
} else {
robot.led.setPattern(RevBlinkinLedDriver.BlinkinPattern.WHITE);
}
}
} | java | 15 | 0.5862 | 172 | 34.263538 | 277 | starcoderdata |
// --------------------------------------------------------
// Copyright:
// Date: 8.4.2019
// Url: http://lexical.fi
// --------------------------------------------------------
using Lexical.Localization.Exp;
using Lexical.Localization.Internal;
using System;
using System.Globalization;
using System.Text;
using System.Threading;
namespace Lexical.Localization.StringFormat
{
public partial class CSharpFormat
{
///
/// Lazily parsed format string that uses C# String.Format notation.
///
public class CSharpString : IString
{
///
/// Parsed arguments. Set in <see cref="Build"/>.
///
IPlaceholder[] placeholders;
///
/// String as sequence of parts. Set in <see cref="Build"/>.
///
IStringPart[] parts;
///
/// Parse status. Set in <see cref="Build"/>.
///
LineStatus status;
///
/// Get the original format string.
///
public string Text { get; internal set; }
///
/// Get parse status.
///
public LineStatus Status { get { if (status == LineStatus.StringFormatFailedNoResult) Build(); return status; } }
///
/// Format string broken into sequence of text and argument parts.
///
public IStringPart[] Parts { get { if (status == LineStatus.StringFormatFailedNoResult) Build(); return parts; } }
///
/// Get placeholders.
///
public IPlaceholder[] Placeholders { get { if (status == LineStatus.StringFormatFailedNoResult) Build(); return placeholders; } }
///
/// (optional) Get associated format provider. This is typically a plurality rules and originates from a localization file.
///
public virtual IFormatProvider FormatProvider => null;
///
/// Associated string format instance
///
public IStringFormat StringFormat { get; protected set; }
///
/// Create format string that parses formulation <paramref name="text"/> lazily.
///
/// <param name="text">
/// <param name="stringFormat">
public CSharpString(string text, IStringFormat stringFormat)
{
Text = text;
status = text == null ? LineStatus.StringFormatFailedNull : LineStatus.StringFormatFailedNoResult;
this.StringFormat = stringFormat;
}
///
/// Parse string
///
protected void Build()
{
StructList8 parts = new StructList8
// Create parser
CSharpFormat.CSharpParser parser = new CSharpFormat.CSharpParser(this);
// Read parts
while (parser.HasMore)
{
IStringPart part = parser.ReadNext();
if (part != null) parts.Add(part);
}
// Unify text parts
for (int i = 1; i < parts.Count;)
{
if (parts[i - 1] is TextPart left && parts[i] is TextPart right)
{
parts[i - 1] = TextPart.Unify(left, right);
parts.RemoveAt(i);
}
else i++;
}
// Create parts array
var partArray = new IStringPart[parts.Count];
parts.CopyTo(partArray, 0);
// Set PartsArrayIndex
for (int i = 0; i < partArray.Length; i++)
{
if (partArray[i] is TextPart textPart) textPart.PartsIndex = i;
else if (partArray[i] is Placeholder argPart) argPart.PartsIndex = i;
}
// Create arguments array
int argumentCount = 0;
for (int i = 0; i < parts.Count; i++) if (parts[i] is IPlaceholder) argumentCount++;
var placeholdersArray = new IPlaceholder[argumentCount];
int j = 0;
for (int i = 0; i < parts.Count; i++) if (parts[i] is Placeholder argPart) placeholdersArray[j++] = argPart;
Array.Sort(placeholdersArray, FormatStringPartComparer.Default);
for (int i = 0; i < placeholdersArray.Length; i++) ((Placeholder)placeholdersArray[i]).PlaceholderIndex = i;
// Write status.
Thread.MemoryBarrier();
this.placeholders = placeholdersArray;
this.parts = partArray;
this.status = parser.status;
}
///
/// Calculate hashcode
///
///
public override int GetHashCode()
=> FormatStringComparer.Default.GetHashCode(this);
///
/// Compare for equality
///
/// <param name="obj">
///
public override bool Equals(object obj)
=> obj is IString other ? FormatStringComparer.Default.Equals(this, other) : false;
///
/// Format string.
///
///
public override string ToString()
=> Text;
///
/// Generic text part implementation of <see cref="IString"/>.
///
public class TextPart : IStringTextPart
{
///
/// Unify two text parts
///
/// <param name="leftPart">
/// <param name="rightPart">
///
internal static TextPart Unify(TextPart leftPart, TextPart rightPart)
=> new TextPart(leftPart.String, leftPart.Index, rightPart.Index - leftPart.Index + rightPart.Length);
///
/// The 'parent' format string.
///
public IString String { get; internal set; }
///
/// Part type
///
public StringPartKind Kind => StringPartKind.Text;
///
/// Start index of first character of the argument in the format string.
///
public int Index { get; internal set; }
///
/// Length of characters in the format string.
///
public int Length { get; internal set; }
///
/// The text part as it appears in the format string.
///
public string Text => String.Text.Substring(Index, Length);
///
/// Index in Parts array.
///
public int PartsIndex { get; internal set; }
///
/// Unescaped text
///
protected string unescapedText;
///
/// Unescaped text
///
public string UnescapedText => unescapedText ?? (unescapedText = Unescape());
///
/// Create text part.
///
/// <param name="formatString">
/// <param name="index">first character index
/// <param name="length">character length
public TextPart(IString formatString, int index, int length)
{
String = formatString;
Index = index;
Length = length;
}
///
/// Unescape text sequence
///
///
protected string Unescape()
{
StringBuilder sb = new StringBuilder(Length);
String s = String.Text;
int end = Index + Length;
for (int i = Index; i < end; i++)
{
char c = s[i];
if (c == '\\' && i < end - 1)
{
char n = s[i + 1];
if (n == '\\' || n == '{' || n == '}') continue;
}
sb.Append(c);
}
return sb.ToString();
}
///
/// Calculate hashcode
///
///
public override int GetHashCode()
=> FormatStringPartComparer.Default.GetHashCode(this);
///
/// Compare for equality
///
/// <param name="obj">
///
public override bool Equals(object obj)
=> FormatStringPartComparer.Default.Equals(obj);
///
/// The text part as it appears in the format string.
///
public override string ToString() => String.Text.Substring(Index, Length);
}
///
/// Version of format string that carries an associated format provider.
///
public class WithFormatProvider : CSharpString
{
///
/// (optional) Associated format provider.
///
IFormatProvider formatProvider;
///
/// (optional) Get associated format provider. This is typically a plurality rules and originates from a localization file.
///
public override IFormatProvider FormatProvider => formatProvider;
///
/// Create lazily parsed format string that carries a <paramref name="formatProvider"/>.
///
/// <param name="text">
/// <param name="stringFormat">
/// <param name="formatProvider">
public WithFormatProvider(string text, IStringFormat stringFormat, IFormatProvider formatProvider) : base(text, stringFormat)
{
this.formatProvider = formatProvider;
}
}
}
}
} | c# | 23 | 0.465605 | 141 | 37.601351 | 296 | starcoderdata |
# coding=utf-8
# Copyright 2021 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Natural Questions Open: A Benchmark for Open Domain Question Answering."""
import json
import tensorflow as tf
import tensorflow_datasets.public_api as tfds
_CITATION = """
@inproceedings{orqa,
title = {Latent Retrieval for Weakly Supervised Open Domain Question Answering},
author = { and and
year = {2019},
month = {01},
pages = {6086-6096},
booktitle = {Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics},
doi = {10.18653/v1/P19-1612}
}
@article{47761,
title = {Natural Questions: a Benchmark for Question Answering Research},
author = { and and and and and and and and and and and and and and and and and
year = {2019},
journal = {Transactions of the Association of Computational Linguistics}
}
"""
_DOWNLOAD_URL_FMT = 'https://raw.githubusercontent.com/google-research-datasets/natural-questions/a7a113c9fdc2d9986d624bd43b8a18d6d5779eaa/nq_open/NQ-open.{split}.jsonl'
_DESCRIPTION = """
The NQ-Open task, introduced by Lee et.al. 2019, is an open domain question \
answering benchmark that is derived from Natural Questions. The goal is to \
predict an English answer string for an input English question. All questions \
can be answered using the contents of English Wikipedia.
"""
_URL = 'https://github.com/google-research-datasets/natural-questions/tree/master/nq_open'
class NaturalQuestionsOpen(tfds.core.GeneratorBasedBuilder):
"""Natural Questions Open: A Benchmark for Open Domain Question Answering."""
VERSION = tfds.core.Version('1.0.0')
def _info(self):
return tfds.core.DatasetInfo(
builder=self,
description=_DESCRIPTION,
features=tfds.features.FeaturesDict({
'question': tf.string,
'answer': tfds.features.Sequence(tf.string)
}),
supervised_keys=None,
homepage=_URL,
citation=_CITATION,
)
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
file_paths = dl_manager.download({
'train': _DOWNLOAD_URL_FMT.format(split='train'),
'validation': _DOWNLOAD_URL_FMT.format(split='dev'),
})
return [
tfds.core.SplitGenerator(
name=split, gen_kwargs={'file_path': file_path})
for split, file_path in file_paths.items()
]
def _generate_examples(self, file_path):
"""Parses split file and yields examples."""
with tf.io.gfile.GFile(file_path) as f:
for i, line in enumerate(f):
yield i, json.loads(line) | python | 16 | 0.704888 | 205 | 34.747253 | 91 | starcoderdata |
package co.edu.uniandes.csw.eventos.resources;
import co.edu.uniandes.csw.eventos.dtos.UsuarioDTO;
import co.edu.uniandes.csw.eventos.dtos.UsuarioDetailDTO;
import co.edu.uniandes.csw.eventos.ejb.UsuarioLogic;
import co.edu.uniandes.csw.eventos.entities.UsuarioEntity;
import co.edu.uniandes.csw.eventos.exceptions.BusinessLogicException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
/**
*
* @author
*/
@Path("usuarios")
@Produces("application/json")
@Consumes("application/json")
@RequestScoped
public class UsuarioResource {
private static final Logger LOGGER = Logger.getLogger(UsuarioResource.class.getName());
@Inject
private UsuarioLogic usuarioLogic;
/**
*
* @param usuario
* @return
* @throws BusinessLogicException
*/
@POST
public UsuarioDTO createUsuario(UsuarioDTO usuario) throws BusinessLogicException {
LOGGER.log(Level.INFO, "UsuarioResource createUsuario: input: {0}", usuario.toString());
UsuarioDTO usuarioDTO = new UsuarioDTO(usuarioLogic.createUsuario(usuario.toEntity()));
LOGGER.log(Level.INFO, "UsuarioResource createUsuario: output: {0}", usuarioDTO.toString());
return usuarioDTO;
}
/**
* obitene
* @return
*/
@GET
public List getUsuarios() {
LOGGER.info("UsuarioResource getUsuarios: input: void");
List listaUsuarios = listEntity2DTO(usuarioLogic.getUsuarios());
LOGGER.log(Level.INFO, "UsuarioResource getUsuarios: output: {0}", listaUsuarios.toString());
return listaUsuarios;
}
/**
*
* @param usuariosId
* @return
* @throws WebApplicationException
*/
@GET
@Path("{usuariosId: \\d+}")
public UsuarioDetailDTO getUsuario(@PathParam("usuariosId") Long usuariosId) throws WebApplicationException {
LOGGER.log(Level.INFO, "UsuarioResource getUsuario: input: {0}", usuariosId);
UsuarioEntity usuarioEntity = usuarioLogic.getUsuario(usuariosId);
if (usuarioEntity == null) {
throw new WebApplicationException("El recurso /usuarios/" + usuariosId + " no existe.", 404);
}
UsuarioDetailDTO detailDTO = new UsuarioDetailDTO(usuarioEntity);
LOGGER.log(Level.INFO, "UsuarioResource getUsuario: output: {0}", detailDTO.toString());
return detailDTO;
}
/**
* Actualiza el usuario con el id recibido en la URL con la información que se
* recibe en el cuerpo de la petición.
*
* @param usuariosId Identificador del usuario que se desea actualizar. Este
* debe ser una cadena de dígitos.
* @param usuario {@link UsuarioDetailDTO} El usuario que se desea guardar.
* @return JSON {@link UsuarioDetailDTO} - El usuario guardado.
* @throws WebApplicationException {@link WebApplicationExceptionMapper} -
* Error de lógica que se genera cuando no se encuentra el usuario a
* actualizar.
*/
@PUT
@Path("{usuariosId: \\d+}")
public UsuarioDetailDTO updateUsuario(@PathParam("usuariosId") Long usuariosId, UsuarioDetailDTO usuario) throws WebApplicationException {
LOGGER.log(Level.INFO, "UsuarioResource updateUsuario: input: id:{0} , editorial: {1}", new Object[]{usuariosId, usuario.toString()});
usuario.setId(usuariosId);
if (usuarioLogic.getUsuario(usuariosId) == null) {
throw new WebApplicationException("El recurso /usuarios/" + usuariosId + " no existe.", 404);
}
UsuarioDetailDTO detailDTO = new UsuarioDetailDTO(usuarioLogic.updateUsuario(usuariosId, usuario.toEntity()));
LOGGER.log(Level.INFO, "UsuarioResource updateUsuario: output: {0}", detailDTO.toString());
return detailDTO;
}
/**
* Borra el usuario con el id asociado recibido en la URL.
*
* @param usuariosId Identificador del usuario que se desea borrar. Este debe
* ser una cadena de dígitos.
* @throws co.edu.uniandes.csw.eventos.exceptions.BusinessLogicException
* si el usuario tiene eventos asociados
* @throws WebApplicationException {@link WebApplicationExceptionMapper}
* Error de lógica que se genera cuando no se encuentra el usuario a borrar.
*/
@DELETE
@Path("{usuariosId: \\d+}")
public void deleteUsuario(@PathParam("usuariosId") Long usuariosId) throws BusinessLogicException {
LOGGER.log(Level.INFO, "UsuarioResource deleteUsuario: input: {0}", usuariosId);
if (usuarioLogic.getUsuario(usuariosId) == null) {
throw new WebApplicationException("El recurso /usuarios/" + usuariosId + " no existe.", 404);
}
usuarioLogic.deleteUsuario(usuariosId);
LOGGER.info("UsuarioResource deleteUsuario: output: void");
}
/**
* Conexión con el servicio de eventos para un usuario.
* {@link UsuarioEventosResource}
*
* Este método conecta la ruta de /usuarios con las rutas de /eventos que
* dependen del usuario, es una redirección al servicio que maneja el segmento
* de la URL que se encarga de los eventos.
*
* @param usuariosId El ID del usuario con respecto al cual se accede al
* servicio.
* @return El servicio de Eventos para ese usuario en paricular.
*/
@Path("{usuariosId: \\d+}/eventos")
public Class getUsuarioEventosResource(@PathParam("usuariosId") Long usuariosId) {
if (usuarioLogic.getUsuario(usuariosId) == null) {
throw new WebApplicationException("El recurso /usuarios/" + usuariosId + " no existe.", 404);
}
return UsuarioEventosResource.class;
}
/**
* Conexión con el servicio de entradas para un usuario.
* {@link UsuarioEntradasResource}
*
* Este método conecta la ruta de /usuarios con las rutas de /entradas que
* dependen del usuario, es una redirección al servicio que maneja el segmento
* de la URL que se encarga de las entradas.
*
* @param usuariosId El ID del usuario con respecto al cual se accede al
* servicio.
* @return El servicio de Entradas para ese usuario en paricular.
*/
@Path("{usuariosId: \\d+}/entradas")
public Class getUsuarioEntradasResource(@PathParam("usuariosId") Long usuariosId) {
if (usuarioLogic.getUsuario(usuariosId) == null) {
throw new WebApplicationException("El recurso /usuarios/" + usuariosId + " no existe.", 404);
}
return UsuarioEntradasResource.class;
}
/**
* Conexión con el servicio de facturas para un usuario.
* {@link UsuarioFacturasResource}
*
* Este método conecta la ruta de /usuarios con las rutas de /facturas que
* dependen del usuario, es una redirección al servicio que maneja el segmento
* de la URL que se encarga de las facturas.
*
* @param usuariosId El ID del usuario con respecto al cual se accede al
* servicio.
* @return El servicio de Facturas para ese usuario en paricular.
*/
@Path("{usuariosId: \\d+}/facturas")
public Class getUsuarioFacturasResource(@PathParam("usuariosId") Long usuariosId) {
if (usuarioLogic.getUsuario(usuariosId) == null) {
throw new WebApplicationException("El recurso /usuarios/" + usuariosId + " no existe.", 404);
}
return UsuarioFacturasResource.class;
}
/**
* Conexión con el servicio de calificaciones para un usuario.
* {@link UsuarioCalificacionesResource}
*
* Este método conecta la ruta de /usuarios con las rutas de /calificaciones que
* dependen del usuario, es una redirección al servicio que maneja el segmento
* de la URL que se encarga de las calificaciones.
*
* @param usuariosId El ID del usuario con respecto al cual se accede al
* servicio.
* @return El servicio de Calificaciones para ese usuario en paricular.
*/
@Path("{usuariosId: \\d+}/calificaciones")
public Class getUsuarioCalificacionesResource(@PathParam("usuariosId") Long usuariosId) {
if (usuarioLogic.getUsuario(usuariosId) == null) {
throw new WebApplicationException("El recurso /usuarios/" + usuariosId + " no existe.", 404);
}
return UsuarioCalificacionesResource.class;
}
/**
* Conexión con el servicio de mediosDePago para un usuario.
* {@link UsuarioMediosDePagoResource}
*
* Este método conecta la ruta de /usuarios con las rutas de /mediosDePago que
* dependen del usuario, es una redirección al servicio que maneja el segmento
* de la URL que se encarga de las mediosDePago.
*
* @param usuariosId El ID del usuario con respecto al cual se accede al
* servicio.
* @return El servicio de MediosDePago para ese usuario en paricular.
*/
@Path("{usuariosId: \\d+}/mediosDePago")
public Class getUsuarioMediosDePagoResource(@PathParam("usuariosId") Long usuariosId) {
if (usuarioLogic.getUsuario(usuariosId) == null) {
throw new WebApplicationException("El recurso /usuarios/" + usuariosId + " no existe.", 404);
}
return UsuarioMediosDePagoResource.class;
}
/**
* Convierte una lista de UsuarioEntity a una lista de UsuarioDTO.
*
* @param entityList Lista de UsuarioEntity a convertir.
* @return Lista de UsuarioDTO convertida.
*/
private List listEntity2DTO(List entityList) {
List list = new ArrayList<>();
for (UsuarioEntity entity : entityList) {
list.add(new UsuarioDetailDTO(entity));
}
return list;
}
} | java | 13 | 0.666159 | 142 | 40.375 | 248 | starcoderdata |
def vectorize(self, sequence):
""" Convert sequence of word-indices into one-hot vector
"""
out = [0] * self.vocab_size
for x in sequence:
if x == 0:
break
try:
out[x] += 1
except:
pass
return out | python | 10 | 0.421875 | 64 | 25.75 | 12 | inline |
using LocksContinued.Locks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace LocksContinued.WorkStealing
{
public class WorkSharingThread
{
Dictionary<int, Queue queue;
Random random;
const int THRESHOLD = 42;
public WorkSharingThread(Dictionary<int, Queue myQueue)
{
queue = myQueue;
random = new Random();
}
public void Run()
{
int me = Thread.CurrentThread.ManagedThreadId;
while (true)
{
Task task;
lock (queue[me])
{
task = queue[me].Dequeue();
}
if (task != null) task.Start();
int size = queue[me].Count;
if (random.Next(size + 1) == size)
{
int victim = queue.Keys.ToList()[random.Next(queue.Keys.Count)];
int min = (victim <= me) ? victim : me;
int max = (victim <= me) ? me : victim;
lock (queue[min])
{
lock (queue[max])
{
Balance(queue[min], queue[max]);
}
}
}
}
}
private void Balance(Queue q0, Queue q1)
{
var qMin = (q0.Count < q1.Count) ? q0 : q1;
var qMax = (q0.Count < q1.Count) ? q1 : q0;
int diff = qMax.Count - qMin.Count;
if (diff > THRESHOLD)
while (qMax.Count > qMin.Count)
qMin.Enqueue(qMax.Dequeue());
}
}
} | c# | 23 | 0.458065 | 84 | 30.525424 | 59 | starcoderdata |
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt
import numpy as np
import math
x=[2,
2,
2,
4,
4,
5,
6,
6,
6,
7,
8,
]
y=[
8,
6,
16,
16,
13,
16,
16,
15,
14,
16,
16,
]
z=[79.07,
52.61,
61.18,
247.92,
3.04,
5.28,
0.25,
0.11,
0.11,
0.25,
0.25
]
z=[math.log10(ele) for ele in z]
x=np.array(x)
y=np.array(y)
z=np.array(z)
fig=plt.figure()
ax=Axes3D(fig)
ax.scatter(x,y,z)
plt.show() | python | 6 | 0.626238 | 39 | 7.265306 | 49 | starcoderdata |
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
int n[]=new int[6];
Scanner sc = new Scanner(System.in);
for(int i=0;i<6;i++){
n[i]=sc.nextInt();
}
String s = sc.next();
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='N'){
n=north(n);
}else if(s.charAt(i)=='S'){
n=south(n);
}else if(s.charAt(i)=='E'){
n=east(n);
}else if(s.charAt(i)=='W'){
n=west(n);
}
}
System.out.println(n[0]);
}
public static int[] north(int[] n){
int temp = n[0];
n[0]=n[1];
n[1]=n[5];
n[5]=n[4];
n[4]=temp;
return n;
}
public static int[] south(int[] n){
int temp = n[0];
n[0]=n[4];
n[4]=n[5];
n[5]=n[1];
n[1]=temp;
return n;
}
public static int[] west(int[] n){
int temp = n[0];
n[0]=n[2];
n[2]=n[5];
n[5]=n[3];
n[3]=temp;
return n;
}
public static int[] east(int[] n){
int temp = n[0];
n[0]=n[3];
n[3]=n[5];
n[5]=n[2];
n[2]=temp;
return n;
}
}
| java | 16 | 0.432384 | 41 | 19.071429 | 56 | codenet |
Relation GetAndOpenNewTableRel(const Relation rel, LOCKMODE lockmode)
{
Relation newtable_rel = NULL;
Oid newtable_relid = InvalidOid;
Oid data_redis_namespace;
char new_tablename[NAMEDATALEN];
errno_t errorno = EOK;
errorno = memset_s(new_tablename, NAMEDATALEN, 0, NAMEDATALEN);
securec_check_c(errorno, "\0", "\0");
RelationGetNewTableName(rel, (char*)new_tablename);
data_redis_namespace = get_namespace_oid("data_redis", false);
newtable_relid = get_relname_relid(new_tablename, data_redis_namespace);
if (!OidIsValid(newtable_relid)) {
/* ERROR case, should never come here */
ereport(ERROR,
(errcode(ERRCODE_DATA_EXCEPTION),
errmsg("new table %s is not found when do cluster resizing table \"%s\"",
new_tablename,
RelationGetRelationName(rel))));
}
newtable_rel = relation_open(newtable_relid, lockmode);
elog(LOG,
"New temp table %s for relation %s under cluster resizing is valid.",
new_tablename,
RelationGetRelationName(rel));
return newtable_rel;
} | c++ | 14 | 0.647215 | 89 | 36.733333 | 30 | inline |
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.keywordRadioButton:
// do operations specific to this selection
SEARCH_OPTION = SEARCH_BY_KEYWORD;
break;
case R.id.geoRadioButton:
// do operations specific to this selection
SEARCH_OPTION = SEARCH_BY_GEOLOCATION;
pickLocation();
break;
case R.id.bodyRadioButton:
// do operations specific to this selection
SEARCH_OPTION = SEARCH_BY_BODYLOCATION;
break;
}
} | java | 9 | 0.449749 | 67 | 45.882353 | 17 | inline |
import React from 'react';
import { observer } from 'mobx-react';
import { Grid, WhiteSpace } from 'antd-mobile';
// url前缀
import { PUBLIC_URL } from '@config';
// less样式
import './index.less';
// 热门推荐
@observer
class Index extends React.Component {
render() {
const { hotList=[] } = this.props;
return (
<div className='dm_HotThisWeek'>
<WhiteSpace size="md" />
<div className='title'>
<img src={ require('@img/svg/hot.svg') } alt='hot' />
热门推荐
<Grid data={ hotList } activeStyle={ false }
columnNum={ 2 }
isCarousel
renderItem={ item => (
<div className='dm_HotThisWeek_products'
onClick={() => {
this.props.history.push(`/views/products/detail/${item.id}`);
}}
>
<img src={ PUBLIC_URL + item.mainPicture } alt='mainPicture' />
item.description }
<p style={{ color: '#1890ff' }}>{ item.price ? Number(item.price).toFixed(2) : 0 }
)}
/>
);
}
}
export default Index; | javascript | 24 | 0.408203 | 122 | 33.931818 | 44 | starcoderdata |
package io.github.soju06.hotreload;
import io.github.soju06.filesystems.watch.WatchDaemon;
import io.github.soju06.hotreload.utility.ChatUtility;
import io.github.soju06.hotreload.utility.HotReloadUtility;
import io.github.soju06.hotreload.utility.PluginUtility;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.plugin.InvalidDescriptionException;
import org.bukkit.plugin.InvalidPluginException;
import org.bukkit.plugin.Plugin;
import javax.annotation.Nullable;
import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.TimeZone;
import java.util.UUID;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class HotReloadDaemon extends WatchDaemon {
private long holdTime = System.currentTimeMillis();
private Plugin plugin;
private UUID threadId;
private int reloadCount = 0;
public HotReloadDaemon(Plugin plugin, File file) {
super(file);
this.plugin = plugin;
}
public Plugin getPlugin() {
return plugin;
}
public String getName() {
return plugin.getName();
}
public int getReloadCount() {
return reloadCount;
}
public void addReloadCount() {
reloadCount++;
}
@Override
public void onModify(File file) {
if (file.getPath().equals(getPath())) {
hold_run(false, null);
}
}
void hold_run(boolean schedule, @Nullable UUID threadId) {
if (threadId != null && threadId != this.threadId) return;
var now = System.currentTimeMillis();
var cooldownValue = HotReload.getInstance().getConfig().get("reload-cool-down");
var cooldown = (cooldownValue != null ? (cooldownValue instanceof Integer ? (int)cooldownValue : HotReloadUtility.tryParseInt(cooldownValue.toString(), 1)) : 1) * 1000;
var hold = now - holdTime;
var use = hold >= cooldown;
if (!schedule) {
if (hold >= cooldown * 5.7) use = false;
holdTime = now;
ChatUtility.sendChat(ChatColor.LIGHT_PURPLE + "plug-in files have been changed: " + plugin.getName());
if (!use) {
var tid = this.threadId = UUID.randomUUID();
Bukkit.getScheduler().scheduleSyncDelayedTask(HotReload.getInstance(), ()->hold_run(true, tid), (cooldown + 200) / 50);
}
}
if (use) {
try {
PluginUtility.unload(plugin);
plugin = PluginUtility.load(getFile());
ChatUtility.sendChat("Plug-in has been loaded: " + plugin.getName(), ChatColor.GREEN);
addReloadCount();
PluginUtility.enable(plugin);
ChatUtility.sendChat("Plug-ins have been enabled: " + plugin.getName(), ChatColor.AQUA);
} catch (InvalidPluginException e) {
ChatUtility.sendError("The plugin is invalid: " + plugin.getName() + "\n " + e.getMessage());
e.printStackTrace();
} catch (InvalidDescriptionException e) {
ChatUtility.sendError("Plug-in description is invalid: " + plugin.getName() + "\n " + e.getMessage());
e.printStackTrace();
}
}
}
} | java | 16 | 0.638782 | 176 | 35.376344 | 93 | starcoderdata |
<?php
namespace App\Yahoo\Responses\Leagues;
use App\Contracts\Yahoo\ResponseInterface;
use Illuminate\Support\Collection;
use Psr\Http\Message\ResponseInterface as GuzzleResponse;
class SettingsResponse implements ResponseInterface
{
/**
* @var GuzzleResponse
*/
protected $response;
/**
* @var Collection
*/
protected $simpleResponse;
/**
* @param GuzzleResponse $response
* @return $this
*/
public function setResponse(\Psr\Http\Message\ResponseInterface $response)
{
$this->response = $response;
return $this;
}
/**
* @return Collection
*/
public function simpleResponse() : Collection
{
return $this->buildSimpleResponse();
}
/**
* @return Collection
*/
protected function buildSimpleResponse()
{
$this->simpleResponse = new Collection();
$response = json_decode($this->response->getBody()->getContents(), true);
$settings = $response['fantasy_content']['league'][1]['settings'][0];
$settings = array_merge($settings, $response['fantasy_content']['league'][0]);
return new Collection([$settings]);
}
} | php | 14 | 0.634631 | 86 | 22.314815 | 54 | starcoderdata |
package us.ihmc.imageProcessing.segmentation;
import georegression.struct.point.Point2D_I32;
import org.ddogleg.struct.FastQueue;
import boofcv.struct.PointIndex_I32;
/**
* @author
*/
public class SimplifyPolygon {
public static FastQueue process( FastQueue vertexes) {
if( vertexes.size() < 4 )
return vertexes;
FastQueue ret = new FastQueue
int N = vertexes.size();
for( int i = 1; i < N+1; i++ ) {
Point2D_I32 a = vertexes.get(i-1);
Point2D_I32 b = vertexes.get(i%N);
Point2D_I32 c = vertexes.get((i+1)%N);
double distAC = a.distance(c);
double distABC = a.distance(b) + b.distance(c);
if( distAC >= distABC*0.1 ) {
ret.grow().set(b);
} else {
System.out.println("simplified");
}
}
return ret;
}
} | java | 14 | 0.596254 | 95 | 23.641026 | 39 | starcoderdata |
using System;
using Xunit;
using LambdaExpressionBuilder;
using System.Collections.Generic;
using System.Linq;
using Shouldly;
namespace LambdaExpressionBuilder.Tests
{
public class LambdaExpressionBuilder_Tests
{
[Fact]
public void LambdaExpressionBuilder_Test()
{
var builder = ExpressionBuilder.BuildFor
builder = builder.Where(x => x.Int == 1);
var source = new List
{
new TestClass() { Int = 0 },
new TestClass() { Int = 1, String = "S" },
new TestClass() { Int = 1, String = "B" }
};
var src = source.AsQueryable().Where(builder).ToList();
src.Count.ShouldBe(2);
}
[Fact]
public void LambdaExpressionBuilder_Test2()
{
var builder = ExpressionBuilder.BuildFor
builder = builder.Where(x => x.Int == 1);
builder = builder.Where(x => x.String == "S");
var source = new List
{
new TestClass() { Int = 0 },
new TestClass() { Int = 1, String = "S" },
new TestClass() { Int = 1, String = "B" }
};
var src = source.AsQueryable().Where(builder).ToList();
src.Count.ShouldBe(1);
}
[Fact]
public void LambdaExpressionBuilder_Test3()
{
var builder = ExpressionBuilder.BuildFor
builder = builder.Where((TestClass2 x, IQueryable y) => y.Contains(x.TestClass));
var source = new List
{
new TestClass() { Int = 0 },
new TestClass() { Int = 1, String = "S" },
new TestClass() { Int = 1, String = "B" }
};
var source2 = new List
{
new TestClass2(source[0]) { Int = 2 },
new TestClass2(source[1]) { Int = 3, String = "C" },
new TestClass2(source[2]) { Int = 3, String = "E" },
new TestClass2(new TestClass(2, "N") { Int = 3, String = "F" }),
new TestClass2(new TestClass(3, "O") { Int = 3, String = "G" }),
new TestClass2(new TestClass(4, "P") { Int = 3, String = "I" })
};
var src = source2.AsQueryable().Where(builder, source.AsQueryable()).ToList();
var srcDirect = source2.Where(x => source.Contains(x.TestClass)).ToList();
src.Count.ShouldBe(srcDirect.Count);
}
[Fact]
public void LambdaExpressionBuilder_Test4()
{
var builder = ExpressionBuilder.BuildFor
builder = builder.Where((TestClass2 x, IQueryable y) => y.Contains(x.TestClass));
builder = builder.Where((TestClass2 x, IQueryable y) => x.Int != 3);
var source = new List
{
new TestClass() { Int = 0 },
new TestClass() { Int = 1, String = "S" },
new TestClass() { Int = 1, String = "B" }
};
var source2 = new List
{
new TestClass2(source[0]) { Int = 2 },
new TestClass2(source[1]) { Int = 3, String = "C" },
new TestClass2(source[2]) { Int = 3, String = "E" },
new TestClass2(new TestClass(2, "N") { Int = 3, String = "F" }),
new TestClass2(new TestClass(3, "O") { Int = 3, String = "G" }),
new TestClass2(new TestClass(4, "P") { Int = 3, String = "I" })
};
var src = source2.AsQueryable().Where(builder, source.AsQueryable()).ToList();
var srcDirect = source2.Where(x => x.Int != 3 && source.Contains(x.TestClass)).ToList();
src.Count.ShouldBe(srcDirect.Count);
}
[Fact]
public void LambdaExpressionBuilder_Test5()
{
var builder = ExpressionBuilder.BuildFor
builder = builder.Where((TestClass2 x, IQueryable y) => y.Contains(x.TestClass));
builder = builder.Where(x => x.Int != 3);
var source = new List
{
new TestClass() { Int = 0 },
new TestClass() { Int = 1, String = "S" },
new TestClass() { Int = 1, String = "B" }
};
var source2 = new List
{
new TestClass2(source[0]) { Int = 2 },
new TestClass2(source[1]) { Int = 3, String = "C" },
new TestClass2(source[2]) { Int = 3, String = "E" },
new TestClass2(new TestClass(2, "N") { Int = 3, String = "F" }),
new TestClass2(new TestClass(3, "O") { Int = 3, String = "G" }),
new TestClass2(new TestClass(4, "P") { Int = 3, String = "I" })
};
var src = source2.AsQueryable().Where(builder, source.AsQueryable()).ToList();
var srcDirect = source2.Where(x => x.Int != 3 && source.Contains(x.TestClass)).ToList();
src.Count.ShouldBe(srcDirect.Count);
}
[Fact]
public void LambdaExpressionBuilder_Test6()
{
var builder = ExpressionBuilder.BuildFor
builder = builder.Where((TestClass2 x, IQueryable y) => y.Contains(x.TestClass));
builder = builder.Where(x => x.Int != 3);
var source = new List
{
new TestClass() { Int = 0 },
new TestClass() { Int = 1, String = "S" },
new TestClass() { Int = 1, String = "B" }
};
var source2 = new List
{
new TestClass2(source[0]) { Int = 2 },
new TestClass2(source[1]) { Int = 3, String = "C" },
new TestClass2(source[2]) { Int = 3, String = "E" },
new TestClass2(new TestClass(2, "N") { Int = 3, String = "F" }),
new TestClass2(new TestClass(3, "O") { Int = 3, String = "G" }),
new TestClass2(new TestClass(4, "P") { Int = 3, String = "I" })
};
var src = source2.AsQueryable().Where(builder, source.AsQueryable()).ToList();
var srcDirect = source2.Where(x => x.Int != 3 && source.Contains(x.TestClass)).ToList();
src.Count.ShouldBe(srcDirect.Count);
}
[Fact]
public void LambdaExpressionBuilder_Test7()
{
var builder = ExpressionBuilder.BuildFor
builder = builder.Where((TestClass2 x, IQueryable y) => y.Contains(x.TestClass));
builder = builder.Where(x => x.Int != 3);
builder = builder.Where((TestClass2 x, IQueryable y) => true);
var source = new List
{
new TestClass() { Int = 0 },
new TestClass() { Int = 1, String = "S" },
new TestClass() { Int = 1, String = "B" }
};
var source2 = new List
{
new TestClass2(source[0]) { Int = 2 },
new TestClass2(source[1]) { Int = 3, String = "C" },
new TestClass2(source[2]) { Int = 3, String = "E" },
new TestClass2(new TestClass(2, "N") { Int = 3, String = "F" }),
new TestClass2(new TestClass(3, "O") { Int = 3, String = "G" }),
new TestClass2(new TestClass(4, "P") { Int = 3, String = "I" })
};
var src = source2.AsQueryable().Where(builder, source.AsQueryable()).ToList();
var srcDirect = source2.Where(x => x.Int != 3 && source.Contains(x.TestClass)).ToList();
src.Count.ShouldBe(srcDirect.Count);
}
}
} | c# | 22 | 0.50312 | 104 | 40.739583 | 192 | starcoderdata |
//
// VisualDProjReader.cs
//
// Author:
//
//
// Copyright (c) 2013
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using MonoDevelop.Projects.Extensions;
using MonoDevelop.Core;
using System.Collections.Generic;
using MonoDevelop.Projects;
using System.Xml;
using System.IO;
using System.Text;
namespace MonoDevelop.D.Projects.VisualD
{
public class VisualDProjFormat : IFileFormat
{
#region Properties
public const string visualDExt = ".visualdproj";
public bool CanReadFile(FilePath file, Type expectedObjectType)
{
return file.Extension.Equals (visualDExt, StringComparison.InvariantCultureIgnoreCase);
}
public bool SupportsFramework(Core.Assemblies.TargetFramework framework)
{
return false;
}
public bool SupportsMixedFormats
{
get { return true; }
}
#endregion
public VisualDProjFormat ()
{
}
public FilePath GetValidFormatName (object obj, FilePath fileName)
{
return fileName.ChangeExtension (visualDExt);
}
public bool CanWriteFile (object obj)
{
return obj is VisualDProject;
}
public IEnumerable GetCompatibilityWarnings(object obj)
{
yield return string.Empty;
}
public List GetItemFiles(object obj)
{
return new List
}
public void WriteFile (FilePath file, object obj, IProgressMonitor monitor)
{
try
{
using (var x = new XmlTextWriter(file, Encoding.UTF8))
Write(obj as VisualDProject, x);
}
catch (Exception ex)
{
monitor.ReportError("Couldn't write project file", ex);
}
}
static void Write(VisualDProject prj, XmlWriter x)
{
x.WriteStartDocument();
x.WriteStartElement("DProject");
x.WriteElementString("ProjectGuid", prj.ItemId);
foreach (VisualDPrjConfig config in prj.Configurations)
{
x.WriteStartElement("Config");
x.WriteAttributeString("name", config.Name);
x.WriteAttributeString("platform", config.Platform);
foreach (var kv in config.Properties)
x.WriteElementString(kv.Key, kv.Value);
x.WriteEndElement();
}
//TODO: Files
x.WriteEndDocument();
x.Close();
}
public object ReadFile (FilePath file, Type expectedType, IProgressMonitor monitor)
{
VisualDProject prj = null;
using (var s = File.OpenText (file))
using (var r = new XmlTextReader (s))
prj = Read (file, r);
if (typeof(Project).IsSubclassOf (expectedType))
return prj;
if (typeof(Solution).IsSubclassOf (expectedType)) {
var sln = new Solution ();
sln.Name = prj.Name;
sln.RootFolder.AddItem (prj);
return sln;
}
return prj;
}
static string GetPath(Stack folderStack, string filename = null)
{
var sb = new StringBuilder(256);
bool isAbs = false;
var backup = new Stack
while (folderStack.Count > 0)
{
var p = folderStack.Pop();
backup.Push(p);
if (!string.IsNullOrWhiteSpace(p))
{
if (!Path.IsPathRooted(p))
sb.Append(Path.DirectorySeparatorChar).Append(p);
else
{
isAbs = true;
sb.Clear().Append(p);
}
}
}
while (backup.Count > 0)
folderStack.Push(backup.Pop());
// Might be an absolute path on non-Windows systems!
if (!isAbs && sb.Length > 0 && sb[0] == Path.DirectorySeparatorChar)
sb.Remove(0, 1);
if (!string.IsNullOrWhiteSpace(filename))
{
if (filename.StartsWith(sb.ToString()))
sb.Clear();
if (!Path.IsPathRooted(filename))
sb.Append(Path.DirectorySeparatorChar).Append(filename);
else
{
isAbs = true;
sb.Clear().Append(filename);
}
}
// Might be an absolute path on non-Windows systems!
if (!isAbs && sb.Length > 0 && sb[0] == Path.DirectorySeparatorChar)
sb.Remove(0, 1);
return sb.ToString();
}
public static VisualDProject Read(FilePath file, XmlReader x)
{
var prj = new VisualDProject ();
prj.FileName = file;
var folderStack = new Stack
string path;
while (x.Read())
{
if (x.NodeType == XmlNodeType.Element)
switch (x.LocalName)
{
case "ProjectGuid":
prj.ItemIdToAssign = x.ReadString();
break;
case "Config":
VisualDPrjConfig.ReadAndAdd(prj, x.GetAttribute("name"), x.GetAttribute("platform"), x.ReadSubtree());
break;
case "Folder":
if (folderStack.Count == 0)
{
// Somehow, the very root Folder node gets merely ignored..somehow
folderStack.Push(string.Empty);
break;
}
folderStack.Push(Building.ProjectBuilder.EnsureCorrectPathSeparators(x.GetAttribute("name") ?? string.Empty));
path = GetPath(folderStack);
if(!string.IsNullOrWhiteSpace(path))
prj.AddDirectory(path);
break;
case "File":
var filePath = Building.ProjectBuilder.EnsureCorrectPathSeparators(x.GetAttribute("path"));
//TODO: Custom tools that are executed right before building..gosh!
if (!string.IsNullOrWhiteSpace(filePath) && !string.IsNullOrWhiteSpace(path = GetPath(folderStack, filePath)))
prj.AddFile(Path.IsPathRooted(path) ? path : prj.BaseDirectory.Combine(path).ToString(), BuildAction.Compile);
break;
}
if (x.NodeType == XmlNodeType.EndElement && x.LocalName == "Folder")
folderStack.Pop();
}
return prj;
}
public void ConvertToFormat(object obj)
{
}
}
} | c# | 27 | 0.68029 | 118 | 25.465306 | 245 | starcoderdata |
using CodingMuscles.CSharpInnoSetup.Converter;
using CodingMuscles.CSharpInnoSetup.Script.Constructs.Collection.Customizable.Configuration;
using System;
using System.ComponentModel;
using System.IO;
using System.Linq.Expressions;
namespace CodingMuscles.CSharpInnoSetup.Script.Constructs.Collection.Customizable
{
///
/// Inno Setup <a href="https://jrsoftware.org/ishelp/topic_dirssection.htm">Documentation
///
public sealed class FolderEntry : ICommonParameters, ICustomizable, IPredicated
{
///
/// Inno Setup <a href="https://jrsoftware.org/ishelp/topic_dirssection.htm">Documentation
///
[DoubleQuote]
public DirectoryInfo Name { get; private set; }
///
/// Inno Setup <a href="https://jrsoftware.org/ishelp/topic_dirssection.htm">Documentation
///
[DoubleQuote]
[Alias("Attribs")]
[TypeConverter(typeof(EnumToStringConverter
public FileSystemAttribute Attributes { get; private set; }
///
/// Inno Setup <a href="https://jrsoftware.org/ishelp/topic_dirssection.htm">Documentation
///
[Alias("Perissions")]
public AclPermission Permission { get; private set; }
///
/// Inno Setup <a href="https://jrsoftware.org/ishelp/topic_dirssection.htm">Documentation
///
[TypeConverter(typeof(EnumToStringConverter
public FolderFlags Flags { get; private set; }
///
public Expression Languages { get; private set; }
///
public Version MinVersion { get; private set; }
///
public Version OnlyBelowVersion { get; private set; }
///
public Expression Components { get; private set; }
///
public Expression Tasks { get; private set; }
///
public Expression<Func<string, bool>> Check { get; private set; }
///
/// Creates and initializes instances of a <see cref="FolderEntry"/>
///
public class Builder : IBuilder ICommonParametersBuilder IPredicatedBuilder ICustomizableBuilder
{
private readonly FolderEntry _folder;
///
/// Create an instance of the <see cref="Builder"/>
///
/// new builder instance
public static Builder Create() => new Builder();
/// <see cref="FolderEntry.Name"/>
public Builder Name(DirectoryInfo name)
{
_folder.Name = name;
return this;
}
/// <see cref="FolderEntry.Name"/>
public Builder Name(string name)
{
_folder.Name = new DirectoryInfo(name);
return this;
}
/// <see cref="FolderEntry.Permission"/>
public Builder Permission(AclPermission permission)
{
_folder.Permission = permission;
return this;
}
/// <see cref="FolderEntry.Flags"/>
public Builder Flags(FolderFlags flags)
{
_folder.Flags = flags;
return this;
}
///
public Builder Languages(Expression languages)
{
_folder.Languages = languages;
return this;
}
///
public Builder MinVersion(Version minVersion)
{
_folder.MinVersion = minVersion;
return this;
}
///
public Builder OnlyBelowVersion(Version onlyBelowVersion)
{
_folder.OnlyBelowVersion = onlyBelowVersion;
return this;
}
///
public Builder Check(Expression<Func<string, bool>> check)
{
_folder.Check = check;
return this;
}
///
public Builder Components(Expression components)
{
_folder.Components = components;
return this;
}
///
public Builder Tasks(Expression tasks)
{
_folder.Tasks = tasks;
return this;
}
///
public Builder Tasks(Expression task)
{
_folder.Tasks = Expression.Lambda task.Body)); ;
return this;
}
///
public Builder Languages(Expression language)
{
_folder.Languages = Expression.Lambda language.Body)); ;
return this;
}
///
public FolderEntry Build() => _folder;
private Builder()
{
_folder = new FolderEntry();
}
}
private FolderEntry()
{
}
}
} | c# | 19 | 0.542355 | 147 | 32.123529 | 170 | starcoderdata |
import Component from '@ember/component';
import {computed} from '@ember/object';
import {get} from '@ember/object';
export default Component.extend({
themes: null,
sortedThemes: computed('[email protected]', function () {
let themes = this.themes.map((t) => {
let theme = {};
let themePackage = get(t, 'package');
theme.model = t;
theme.name = get(t, 'name');
theme.label = themePackage ? `${themePackage.name}` : theme.name;
theme.version = themePackage ? `${themePackage.version}` : '1.0';
theme.package = themePackage;
theme.active = get(t, 'active');
theme.isDeletable = !theme.active;
return theme;
});
let duplicateThemes = [];
themes.forEach((theme) => {
let duplicateLabels = themes.filterBy('label', theme.label);
if (duplicateLabels.length > 1) {
duplicateThemes.pushObject(theme);
}
});
duplicateThemes.forEach((theme) => {
if (theme.name !== 'casper') {
theme.label = `${theme.label} (${theme.name})`;
}
});
// "(default)" needs to be added to casper manually as it's always
// displayed and would mess up the duplicate checking if added earlier
let casper = themes.findBy('name', 'casper');
if (casper) {
casper.label = `${casper.label} (default)`;
casper.isDefault = true;
casper.isDeletable = false;
}
// sorting manually because .sortBy('label') has a different sorting
// algorithm to [...strings].sort()
return themes.sort((themeA, themeB) => {
let a = themeA.label.toLowerCase();
let b = themeB.label.toLowerCase();
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
});
}).readOnly()
}); | javascript | 24 | 0.512518 | 78 | 30.338462 | 65 | starcoderdata |
<?php
namespace App\Console;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected $commands = [
\Laravel\Passport\Console\KeysCommand::class,
Commands\BsInstallCommand::class,
Commands\OptionsCacheCommand::class,
Commands\PluginDisableCommand::class,
Commands\PluginEnableCommand::class,
Commands\SaltRandomCommand::class,
Commands\UpdateCommand::class,
];
} | php | 12 | 0.712851 | 58 | 25.210526 | 19 | starcoderdata |
var _16 = {
elem: 'svg',
attrs: {
xmlns: 'http://www.w3.org/2000/svg',
viewBox: '0 0 32 32',
width: 16,
height: 16,
},
content: [
{
elem: 'path',
attrs: {
d:
'M28 8V5a1 1 0 0 0-1-1h-6a1 1 0 0 0-1 1v3a2 2 0 0 0-2 2v2h-4v-2a2 2 0 0 0-2-2V5a1 1 0 0 0-1-1H5a1 1 0 0 0-1 1v3a2 2 0 0 0-2 2v12a2 2 0 0 0 1 1.72V27a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1v-3.28A2 2 0 0 0 14 22v-2h4v2a2 2 0 0 0 1 1.72V27a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1v-3.28A2 2 0 0 0 30 22V10a2 2 0 0 0-2-2zM11 26H5v-2h6zm1-4H4V10h2V6h4v4h2zm2-4v-4h4v4zm13 8h-6v-2h6zm1-4h-8V10h2V6h4v4h2z',
},
},
],
name: 'binoculars',
size: 16,
};
export default _16; | javascript | 11 | 0.587169 | 390 | 30.173913 | 23 | starcoderdata |
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see
#include "main.h"
template<typename MatrixType> void matrixVisitor(const MatrixType& p)
{
typedef typename MatrixType::Scalar Scalar;
int rows = p.rows();
int cols = p.cols();
// construct a random matrix where all coefficients are different
MatrixType m;
m = MatrixType::Random(rows, cols);
for(int i = 0; i < m.size(); i++)
for(int i2 = 0; i2 < i; i2++)
while(m(i) == m(i2)) // yes, ==
m(i) = ei_random
Scalar minc = Scalar(1000), maxc = Scalar(-1000);
int minrow=0,mincol=0,maxrow=0,maxcol=0;
for(int j = 0; j < cols; j++)
for(int i = 0; i < rows; i++)
{
if(m(i,j) < minc)
{
minc = m(i,j);
minrow = i;
mincol = j;
}
if(m(i,j) > maxc)
{
maxc = m(i,j);
maxrow = i;
maxcol = j;
}
}
int eigen_minrow, eigen_mincol, eigen_maxrow, eigen_maxcol;
Scalar eigen_minc, eigen_maxc;
eigen_minc = m.minCoeff(&eigen_minrow,&eigen_mincol);
eigen_maxc = m.maxCoeff(&eigen_maxrow,&eigen_maxcol);
VERIFY(minrow == eigen_minrow);
VERIFY(maxrow == eigen_maxrow);
VERIFY(mincol == eigen_mincol);
VERIFY(maxcol == eigen_maxcol);
VERIFY_IS_APPROX(minc, eigen_minc);
VERIFY_IS_APPROX(maxc, eigen_maxc);
VERIFY_IS_APPROX(minc, m.minCoeff());
VERIFY_IS_APPROX(maxc, m.maxCoeff());
}
template<typename VectorType> void vectorVisitor(const VectorType& w)
{
typedef typename VectorType::Scalar Scalar;
int size = w.size();
// construct a random vector where all coefficients are different
VectorType v;
v = VectorType::Random(size);
for(int i = 0; i < size; i++)
for(int i2 = 0; i2 < i; i2++)
while(v(i) == v(i2)) // yes, ==
v(i) = ei_random
Scalar minc = Scalar(1000), maxc = Scalar(-1000);
int minidx=0,maxidx=0;
for(int i = 0; i < size; i++)
{
if(v(i) < minc)
{
minc = v(i);
minidx = i;
}
if(v(i) > maxc)
{
maxc = v(i);
maxidx = i;
}
}
int eigen_minidx, eigen_maxidx;
Scalar eigen_minc, eigen_maxc;
eigen_minc = v.minCoeff(&eigen_minidx);
eigen_maxc = v.maxCoeff(&eigen_maxidx);
VERIFY(minidx == eigen_minidx);
VERIFY(maxidx == eigen_maxidx);
VERIFY_IS_APPROX(minc, eigen_minc);
VERIFY_IS_APPROX(maxc, eigen_maxc);
VERIFY_IS_APPROX(minc, v.minCoeff());
VERIFY_IS_APPROX(maxc, v.maxCoeff());
}
void test_eigen2_visitor()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( matrixVisitor(Matrix<float, 1, 1>()) );
CALL_SUBTEST_2( matrixVisitor(Matrix2f()) );
CALL_SUBTEST_3( matrixVisitor(Matrix4d()) );
CALL_SUBTEST_4( matrixVisitor(MatrixXd(8, 12)) );
CALL_SUBTEST_5( matrixVisitor(Matrix 20)) );
CALL_SUBTEST_6( matrixVisitor(MatrixXi(8, 12)) );
}
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_7( vectorVisitor(Vector4f()) );
CALL_SUBTEST_4( vectorVisitor(VectorXd(10)) );
CALL_SUBTEST_4( vectorVisitor(RowVectorXd(10)) );
CALL_SUBTEST_8( vectorVisitor(VectorXf(33)) );
}
} | c++ | 14 | 0.646701 | 85 | 30.358779 | 131 | starcoderdata |
const format = new Intl.DateTimeFormat('en', {
year: 'numeric',
month: 'short',
day: '2-digit'
})
export const formatTime = time => {
const [
{ value: month },
,
{ value: day },
,
{ value: year }
] = format.formatToParts(time)
return {
day,
month,
year
}
}
export const sortByTime = (list, asc = true) =>
list.sort((itemA, itemB) =>
asc ? itemB.date - itemA.date : itemA.date - itemB.date
)
export const formatDateStringField = (list, fieldToFormat) =>
list.map(item => ({
...item,
[fieldToFormat]: new Date(item[fieldToFormat])
})) | javascript | 14 | 0.583748 | 61 | 17.84375 | 32 | starcoderdata |
#include <bits/stdc++.h>
using namespace std;
int main(int argc, char const *argv[])
{
string s;
cin>>s;
int ans=0,f=0,f2=0;
reverse(s.begin(), s.end());
for (auto i = s.begin(); i != s.end(); ++i)
{
int d=(*i)-'0';
if (f==1)
{
d++;
f=0;
}
if (d<=4)
{
ans+=d;
}
else if (d==5)
{
++i;
auto j=i;
--i;
if (j!=s.end()&&(*j)-'0'>=5)
{
ans+=10-d;
f=1;
}
else
{
ans+=d;
}
}
else
{
ans+=10-d;
f=1;
}
}
cout<<ans+f<<endl;
return 0;
}
| c++ | 16 | 0.415534 | 44 | 10.444444 | 45 | codenet |
(function () {
var scroll;
var scrollTime;
var startTime;
window.addEventListener('click', function (event) {
if (startTime) {
return;
}
// Scan for parent "button" element since it can contain other child elements, like svg in our case
var target = event.target;
do {
scrollTime = target.getAttribute('data-back-to-top-button-time');
if (isNumeric(scrollTime)) {
scroll = window.pageYOffset;
requestAnimationFrame(scroller);
break;
}
} while (target !== this && (target = target.parentElement)) // Don't scan higher than element to which the listener is assigned and not higher than
}, false);
function scroller (timestamp) {
startTime || (startTime = timestamp);
timestamp = (timestamp - startTime) / +scrollTime; // Convert to time fraction
if (!window.pageYOffset || timestamp >= 1) {
window.scrollTo(0, 0);
startTime = 0;
return;
}
window.scrollTo(0, scroll * (1 - ease(timestamp)));
requestAnimationFrame(scroller);
}
function isNumeric (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function ease (k) {
return 0.5 * (1 - Math.cos(Math.PI * k));
}
})(); | javascript | 13 | 0.625911 | 159 | 28.404762 | 42 | starcoderdata |
public string GetUserEmail()
{
if(string.IsNullOrEmpty(m_AccessToken)){
throw new InvalidOperationException("Invalid state, you need to call 'GetAccessToken' method first.");
}
string url = "https://www.googleapis.com/userinfo/email";
string timestamp = GenerateTimeStamp();
string nonce = GenerateNonce();
// Build signature base.
StringBuilder xxx = new StringBuilder();
xxx.Append("oauth_consumer_key=" + UrlEncode(m_ConsumerKey));
xxx.Append("&oauth_nonce=" + UrlEncode(nonce));
xxx.Append("&oauth_signature_method=" + UrlEncode("HMAC-SHA1"));
xxx.Append("&oauth_timestamp=" + UrlEncode(timestamp));
xxx.Append("&oauth_token=" + UrlEncode(m_AccessToken));
xxx.Append("&oauth_version=" + UrlEncode("1.0"));
string signatureBase = "GET" + "&" + UrlEncode(url) + "&" + UrlEncode(xxx.ToString());
// Calculate signature.
string signature = ComputeHmacSha1Signature(signatureBase,m_ConsumerSecret,m_AccessTokenSecret);
//Build Authorization header.
StringBuilder authHeader = new StringBuilder();
authHeader.Append("Authorization: OAuth ");
authHeader.Append("oauth_version=\"1.0\", ");
authHeader.Append("oauth_nonce=\"" + nonce + "\", ");
authHeader.Append("oauth_timestamp=\"" + timestamp + "\", ");
authHeader.Append("oauth_consumer_key=\"" + m_ConsumerKey + "\", ");
authHeader.Append("oauth_token=\"" + UrlEncode(m_AccessToken) + "\", ");
authHeader.Append("oauth_signature_method=\"HMAC-SHA1\", ");
authHeader.Append("oauth_signature=\"" + UrlEncode(signature) + "\"");
// Create web request and read response.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.Headers.Add(authHeader.ToString());
using(WebResponse response = request.GetResponse()){
using(StreamReader reader = new StreamReader(response.GetResponseStream())){
foreach(string parameter in HttpUtility.UrlDecode(reader.ReadToEnd()).Split('&')){
string[] name_value = parameter.Split('=');
if(string.Equals(name_value[0],"email",StringComparison.InvariantCultureIgnoreCase)){
m_Email = name_value[1];
}
}
}
}
return m_Email;
} | c# | 18 | 0.552399 | 118 | 51.176471 | 51 | inline |
package net.snakefangox.fasterthanc.gui.parts;
import io.netty.buffer.Unpooled;
import net.fabricmc.fabric.api.network.ClientSidePacketRegistry;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.util.math.BlockPos;
import net.snakefangox.fasterthanc.Networking;
import spinnery.widget.WTextField;
public class WTargetingTextBox extends WTextField {
int id = 0;
BlockPos pos = new BlockPos(0,0,0);
WTargetingTextBox twin;
boolean isPitch = false;
@Override
public void onCharTyped(char character, int keyCode) {
super.onCharTyped(character, keyCode);
try {
float value = Float.valueOf(getText());
float twinValue = Float.valueOf(twin.getText());
PacketByteBuf passedData = new PacketByteBuf(Unpooled.buffer());
passedData.writeBlockPos(pos);
passedData.writeInt(id);
passedData.writeFloat(isPitch ? value : twinValue);
passedData.writeFloat(isPitch ? twinValue : value);
ClientSidePacketRegistry.INSTANCE.sendToServer(Networking.ANZIMITH_TO_SERVER, passedData);
}catch (Exception e) {}
}
public int getId() {
return id;
}
public WTargetingTextBox setId(int id) {
this.id = id;
return this;
}
public BlockPos getPos() {
return pos;
}
public WTargetingTextBox setPos(BlockPos pos) {
this.pos = pos;
return this;
}
public WTargetingTextBox setTwin(WTargetingTextBox twin) {
this.twin = twin;
return this;
}
public WTargetingTextBox setPitch(boolean pitch) {
isPitch = pitch;
return this;
}
} | java | 13 | 0.750337 | 93 | 24.118644 | 59 | starcoderdata |
#pragma once
#include
namespace oi {
DEnum(SLHeaderVersion, u8,
Undefined = 0, v1 = 1
);
enum class SLHeaderFlags {
NONE = 0,
USE_DEFAULT = 1
};
struct SLHeader {
char header[4];
u8 version; //SLHeaderVersion_s
u8 perChar; //SLHeaderFlags_s
u8 keys;
u8 flags;
u16 names;
u16 length;
};
struct SLFile {
SLHeader header;
String keyset;
std::vector names;
u32 size;
SLFile(String keyset, std::vector names);
SLFile();
u32 lookup(String name);
};
struct oiSL {
static bool read(String path, SLFile &file);
static bool read(Buffer data, SLFile &file);
static Buffer write(SLFile &file); //Creates new buffer
static bool write(String path, SLFile &file);
};
} | c | 12 | 0.659211 | 57 | 13.092593 | 54 | starcoderdata |
import os
import pathlib
from shutil import copyfile
from py_gardener.InternalTestBase import InternalTestBase
class TestDocker(InternalTestBase):
def test_docker(self):
""" Test that tests are run inside a Docker container """
if len(self.DOCKER) > 0:
assert os.path.exists(os.path.join("/.dockerenv")), (
'Please run in Docker using ". manage.sh"')
def test_copy_docker_files(self):
""" Test to copy lambda files into directory """
if self.ROOT_DIR is None:
return
for type_ in self.DOCKER:
base = os.path.join(
os.path.dirname(__file__),
"resources",
"docker",
type_
)
copyfile(
os.path.join(base, 'manage.sh'),
os.path.join(self.ROOT_DIR, 'manage.sh')
)
pathlib.Path(os.path.join(self.ROOT_DIR, 'docker')).mkdir(
parents=True,
exist_ok=True
)
copyfile(
os.path.join(base, 'Dockerfile'),
os.path.join(self.ROOT_DIR, 'docker', 'Dockerfile')
) | python | 15 | 0.516345 | 70 | 31.243243 | 37 | starcoderdata |
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue';
import App from './App';
import router from './router';
// 导入store
import store from './store/index';
//引入elementui
import Element from 'element-ui';
// 导入语言国际化插件
import VueI18n from 'vue-i18n';
// 图片放大
import VueDirectiveImagePreviewer from 'vue-directive-image-previewer';
// 导入语言包
import LangZhCH from '@/assets/js/i18n/zh-cn';
import LangEn from '@/assets/js/i18n/en-us';
//自定义全局组件
import components from './components';
// 全局过滤器
import '@/filters/filters';
//字体图标
import '@/assets/fonts/font-awesome-4.7.0/css/font-awesome.min.css';
//css
import 'element-ui/lib/theme-chalk/index.css';
import 'vue-directive-image-previewer/dist/assets/style.css';
import '@/assets/styles/reset.css';
import '@/assets/styles/common.less';
import '@/assets/styles/theme.default.less';
Vue.use(Element, { size: 'mini', zIndex: 3000 });
Object.keys(components).forEach((key) => {
Vue.component(key, components[key]);
});
Vue.use(VueDirectiveImagePreviewer, {
background: 'rgba(0,0,0,.5)'
});
Vue.use(VueI18n);
/**
* 配置语言国际化和自定义语言包
*/
const i18n = new VueI18n({
locale: 'zhCNS',
messages: {
'enUS': LangEn,
'zhCNS': LangZhCH
}
});
// this.$i18n.locale='zhCNS' 动态切换语言
Vue.config.productionTip = false;
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
i18n,
components: { App },
template: '
}); | javascript | 8 | 0.684411 | 80 | 23.292308 | 65 | starcoderdata |
// keep handlers isolated from actual request response data
// all handlers will have the last parameter as helpers
const {createHandler} = require('../lib/create-handler');
exports.fetchUser = createHandler(async (id, helpers) => {
// helpers.db // get db
const user = await helpers.db('users').where({id: id});
return user;
}); | javascript | 15 | 0.7 | 59 | 33 | 10 | starcoderdata |
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkDumpCanvas_DEFINED
#define SkDumpCanvas_DEFINED
#include "SkCanvas.h"
#ifdef SK_DEBUG
/** This class overrides all the draw methods on SkCanvas, and formats them
as text, and then sends that to a Dumper helper object.
Typical use might be to dump a display list to a log file to see what is
being drawn.
*/
class SkDumpCanvas : public SkCanvas {
public:
class Dumper;
explicit SkDumpCanvas(Dumper* = 0);
virtual ~SkDumpCanvas();
enum Verb {
kNULL_Verb,
kSave_Verb,
kRestore_Verb,
kMatrix_Verb,
kClip_Verb,
kDrawPaint_Verb,
kDrawPoints_Verb,
kDrawOval_Verb,
kDrawRect_Verb,
kDrawRRect_Verb,
kDrawDRRect_Verb,
kDrawPath_Verb,
kDrawBitmap_Verb,
kDrawText_Verb,
kDrawPicture_Verb,
kDrawVertices_Verb,
kDrawPatch_Verb,
kDrawData_Verb, // obsolete
kDrawAnnotation_Verb,
kCull_Verb
};
/** Subclasses of this are installed on the DumpCanvas, and then called for
each drawing command.
*/
class Dumper : public SkRefCnt {
public:
virtual void dump(SkDumpCanvas*, SkDumpCanvas::Verb, const char str[],
const SkPaint*) = 0;
private:
typedef SkRefCnt INHERITED;
};
Dumper* getDumper() const { return fDumper; }
void setDumper(Dumper*);
int getNestLevel() const { return fNestLevel; }
protected:
void willSave() override;
SaveLayerStrategy getSaveLayerStrategy(const SaveLayerRec&) override;
void willRestore() override;
void didConcat(const SkMatrix&) override;
void didSetMatrix(const SkMatrix&) override;
void onDrawDRRect(const SkRRect&, const SkRRect&, const SkPaint&) override;
virtual void onDrawText(const void* text, size_t byteLength, SkScalar x, SkScalar y,
const SkPaint&) override;
virtual void onDrawPosText(const void* text, size_t byteLength, const SkPoint pos[],
const SkPaint&) override;
virtual void onDrawPosTextH(const void* text, size_t byteLength, const SkScalar xpos[],
SkScalar constY, const SkPaint&) override;
virtual void onDrawTextOnPath(const void* text, size_t byteLength, const SkPath& path,
const SkMatrix* matrix, const SkPaint&) override;
virtual void onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
const SkPaint& paint) override;
virtual void onDrawPatch(const SkPoint cubics[12], const SkColor colors[4],
const SkPoint texCoords[4], SkXfermode* xmode,
const SkPaint& paint) override;
void onDrawPaint(const SkPaint&) override;
void onDrawPoints(PointMode, size_t count, const SkPoint pts[], const SkPaint&) override;
void onDrawRect(const SkRect&, const SkPaint&) override;
void onDrawOval(const SkRect&, const SkPaint&) override;
void onDrawRRect(const SkRRect&, const SkPaint&) override;
void onDrawPath(const SkPath&, const SkPaint&) override;
void onDrawBitmap(const SkBitmap&, SkScalar left, SkScalar top, const SkPaint*) override;
void onDrawBitmapRect(const SkBitmap&, const SkRect* src, const SkRect& dst, const SkPaint*,
SrcRectConstraint) override;
void onDrawImage(const SkImage*, SkScalar left, SkScalar top, const SkPaint*) override;
void onDrawImageRect(const SkImage*, const SkRect* src, const SkRect& dst,
const SkPaint*, SrcRectConstraint) override;
void onDrawBitmapNine(const SkBitmap&, const SkIRect& center, const SkRect& dst,
const SkPaint*) override;
void onDrawVertices(VertexMode vmode, int vertexCount,
const SkPoint vertices[], const SkPoint texs[],
const SkColor colors[], SkXfermode* xmode,
const uint16_t indices[], int indexCount,
const SkPaint&) override;
void onClipRect(const SkRect&, SkRegion::Op, ClipEdgeStyle) override;
void onClipRRect(const SkRRect&, SkRegion::Op, ClipEdgeStyle) override;
void onClipPath(const SkPath&, SkRegion::Op, ClipEdgeStyle) override;
void onClipRegion(const SkRegion&, SkRegion::Op) override;
void onDrawPicture(const SkPicture*, const SkMatrix*, const SkPaint*) override;
void onDrawAnnotation(const SkRect&, const char key[], SkData* value) override;
static const char* EdgeStyleToAAString(ClipEdgeStyle edgeStyle);
private:
Dumper* fDumper;
int fNestLevel; // for nesting recursive elements like pictures
void dump(Verb, const SkPaint*, const char format[], ...);
typedef SkCanvas INHERITED;
};
/** Formats the draw commands, and send them to a function-pointer provided
by the caller.
*/
class SkFormatDumper : public SkDumpCanvas::Dumper {
public:
SkFormatDumper(void (*)(const char text[], void* refcon), void* refcon);
// override from baseclass that does the formatting, and in turn calls
// the function pointer that was passed to the constructor
virtual void dump(SkDumpCanvas*, SkDumpCanvas::Verb, const char str[],
const SkPaint*) override;
private:
void (*fProc)(const char*, void*);
void* fRefcon;
typedef SkDumpCanvas::Dumper INHERITED;
};
/** Subclass of Dumper that dumps the drawing command to SkDebugf
*/
class SkDebugfDumper : public SkFormatDumper {
public:
SkDebugfDumper();
private:
typedef SkFormatDumper INHERITED;
};
#endif
#endif | c | 12 | 0.658503 | 96 | 33.755952 | 168 | starcoderdata |
from flask import Flask, render_template, url_for, request, redirect
from models import db, Transaction
from forms import AddTransactionForm, DeleteTransactionForm
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///transactions.db'
db.init_app(app)
@app.route('/')
def index():
transactions = Transaction.query.all()
return render_template('index.html', transactions=transactions)
@app.route('/add', methods=['GET', 'POST'])
def add():
form = AddTransactionForm(request.form)
if request.method == 'POST' and form.validate():
with app.app_context():
transaction = Transaction(date=form.date.data,
kind=form.kind.data,
category=form.category.data,
sub_category=form.sub_category.data,
description=form.description.data,
amount=form.amount.data)
db.session.add(transaction)
db.session.commit()
return redirect(url_for('index'))
return render_template('add.html', form=form)
@app.route('/delete', methods=['GET', 'POST'])
def delete():
form = DeleteTransactionForm(request.form)
if request.method == 'POST' and form.validate():
with app.app_context():
transaction = Transaction.query.get_or_404(form.transaction_id.data)
db.session.delete(transaction)
db.session.commit()
return redirect(url_for('index'))
return render_template('delete.html', form=form)
if __name__ == '__main__':
app.run(debug=True) | python | 15 | 0.596154 | 80 | 37.697674 | 43 | starcoderdata |
#pragma once
#include
#include "Common/Shapes/ASkybox.h"
#include "OpenGL/Core/VertexBufferObject.h"
/// This is a class for creating and rendering a skybox
/// Modified by - for the Graphics Coursework n City, University of London
/// Stripped down of any texture information and hardcoded paths
class GLSkybox : public ASkybox
{
private:
unsigned int m_vao;
CVertexBufferObject m_vbo;
public:
GLSkybox();
~GLSkybox();
virtual void Render();
virtual void Create();
virtual void Release();
}; | c | 7 | 0.756432 | 81 | 21.423077 | 26 | starcoderdata |
int askNumFahrenheit() {//begin fahrenheit function
int fahrenheit;
printf("Enter a temperature in Fahrenheit:\n");
scanf_s("%i", &fahrenheit);
return fahrenheit;//return fahrenheit value
} | c | 7 | 0.725 | 51 | 26.857143 | 7 | inline |
import AltInstance from 'lib/AltInstance';
import IngredientsSource from '../sources/IngredientsSource';
class IngredientsActions {
constructor() {
this.generateActions('setIngredients');
}
fetchIngredients() {
IngredientsSource.fetch()
.then(this.actions.setIngredients)
.catch((errorMessage) => {
console.warn('Error message');
});
}
}
export default AltInstance.createActions(IngredientsActions); | javascript | 14 | 0.706278 | 61 | 22.473684 | 19 | starcoderdata |
/* !!!! GENERATED FILE - DO NOT EDIT !!!! */
/*
* Copyright (c) 2014 liblcf authors
* This file is released under the MIT License
* http://opensource.org/licenses/MIT
*/
#ifndef LCF_RPG_EVENT_H
#define LCF_RPG_EVENT_H
// Headers
#include
#include
#include "rpg_eventpage.h"
/**
* RPG::Event class.
*/
namespace RPG {
class Event {
public:
Event();
int ID;
std::string name;
int x;
int y;
std::vector pages;
};
}
#endif | c | 10 | 0.657303 | 58 | 14.705882 | 34 | starcoderdata |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.myapp.struts.admin;
import com.myapp.struts.LoginActionForm;
import com.myapp.struts.hbm.Login;
import com.myapp.struts.hbm.LoginDAO;
import java.util.List;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
/**
*
* @author System Administrator
*/
public class SecurityAction extends org.apache.struts.action.Action {
/* forward name="success" path="" */
private static final String SUCCESS = "success";
String staff_id;
String user_name;
String question;
String ans;
List rs;
String institute_id;
String role;
/**
* This is the action called from the Struts framework.
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request we are processing.
* @param response The HTTP Response we are processing.
* @throws java.lang.Exception
*/
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
SecurityActionForm login=(SecurityActionForm)form;
staff_id=login.getStaff_id();
user_name=login.getUser_id();
question=login.getQuestion();
ans=login.getAns();
HttpSession session=request.getSession();
institute_id=(String)session.getAttribute("institute_id");
role=(String)session.getAttribute("login_role");
// System.out.println(staff_id+question+ans);
LoginDAO logindao = new LoginDAO();
Login loginDetails = new Login();
String userid = (String)session.getAttribute("user_id");
System.out.println(userid);
List loginList = logindao.getUser(userid);
if(!loginList.isEmpty()){
loginDetails = (Login)loginList.get(0);
//loginDetails.setUserId(staff_id);
//loginDetails.setUserName(user_name);
loginDetails.setQuestion(question);
loginDetails.setAns(ans);
logindao.update(loginDetails);
if(loginDetails.getRole().equalsIgnoreCase("insti-admin"))
return mapping.findForward("success");
if(loginDetails.getRole().equalsIgnoreCase("Election Manager"))
{ //request.setAttribute("msg","Requested Page is being developed");
return mapping.findForward("electionmanager");}
if(loginDetails.getRole().equalsIgnoreCase("voter"))
{ //request.setAttribute("msg","Requested Page is being developed");
return mapping.findForward("voter");}
if(loginDetails.getRole().equalsIgnoreCase("candidate"))
{ //request.setAttribute("msg","Requested Page is being developed");
return mapping.findForward("candidate");}
}
return mapping.findForward("failure");
}
} | java | 13 | 0.658974 | 82 | 31.284314 | 102 | starcoderdata |
"use strict";
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 NEM
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
exports.__esModule = true;
var PublicAccount_1 = require("../account/PublicAccount");
var MosaicId_1 = require("./MosaicId");
var MosaicLevy_1 = require("./MosaicLevy");
/**
* A mosaic definition describes an asset class. Some fields are mandatory while others are optional.
* The properties of a mosaic definition always have a default value and only need to be supplied if they differ from the default value.
*/
var MosaicDefinition = /** @class */ (function () {
/**
* constructor
* @param creator
* @param id
* @param description
* @param properties
* @param levy
* @param metaId
*/
function MosaicDefinition(creator, id, description, properties, levy, metaId) {
this.creator = creator;
this.id = id;
this.description = description;
this.properties = properties;
this.levy = levy;
this.metaId = metaId;
}
/**
* @internal
* @param dto
* @returns {MosaicDefinition}
*/
MosaicDefinition.createFromMosaicDefinitionDTO = function (dto) {
var levy = dto.levy;
return new MosaicDefinition(PublicAccount_1.PublicAccount.createWithPublicKey(dto.creator), MosaicId_1.MosaicId.createFromMosaicIdDTO(dto.id), dto.description, MosaicProperties.createFromMosaicProperties(dto.properties), levy.mosaicId === undefined ? undefined : MosaicLevy_1.MosaicLevy.createFromMosaicLevyDTO(levy));
};
/**
* @internal
* @param dto
* @returns {MosaicDefinition}
*/
MosaicDefinition.createFromMosaicDefinitionMetaDataPairDTO = function (dto) {
var levy = dto.mosaic.levy;
return new MosaicDefinition(PublicAccount_1.PublicAccount.createWithPublicKey(dto.mosaic.creator), MosaicId_1.MosaicId.createFromMosaicIdDTO(dto.mosaic.id), dto.mosaic.description, MosaicProperties.createFromMosaicProperties(dto.mosaic.properties), levy.mosaicId === undefined ? undefined : MosaicLevy_1.MosaicLevy.createFromMosaicLevyDTO(levy), dto.meta.id);
};
/**
* @internal
* @returns {{description: string, id: MosaicId, levy: (MosaicLevyDTO|{}), properties: MosaicProperty[], creator: string}}
*/
MosaicDefinition.prototype.toDTO = function () {
return {
description: this.description,
id: this.id,
levy: this.levy != undefined ? this.levy.toDTO() : null,
properties: this.properties.toDTO(),
creator: this.creator.publicKey
};
};
return MosaicDefinition;
}());
exports.MosaicDefinition = MosaicDefinition;
/**
* Each mosaic definition comes with a set of properties.
* Each property has a default value which will be applied in case it was not specified.
* Future release may add additional properties to the set of available properties
*/
var MosaicProperties = /** @class */ (function () {
/**
* constructor
* @param divisibility
* @param initialSupply
* @param supplyMutable
* @param transferable
*/
function MosaicProperties(divisibility, initialSupply, transferable, supplyMutable) {
if (divisibility === void 0) { divisibility = 0; }
if (initialSupply === void 0) { initialSupply = 1000; }
if (transferable === void 0) { transferable = true; }
if (supplyMutable === void 0) { supplyMutable = false; }
this.initialSupply = initialSupply;
this.supplyMutable = supplyMutable;
this.transferable = transferable;
this.divisibility = divisibility;
}
/**
* @internal
*/
MosaicProperties.prototype.toDTO = function () {
return [
{
name: "divisibility",
value: this.divisibility.toString()
},
{
name: "initialSupply",
value: this.initialSupply.toString()
},
{
name: "supplyMutable",
value: this.supplyMutable.toString()
},
{
name: "transferable",
value: this.transferable.toString()
},
];
};
/**
* @internal
* @param dto
* @returns {MosaicProperty}
*/
MosaicProperties.createFromMosaicProperties = function (mosaicProperties) {
return new MosaicProperties(Number(mosaicProperties[0].value), Number(mosaicProperties[1].value), (mosaicProperties[3].value == "true"), (mosaicProperties[2].value == "true"));
};
return MosaicProperties;
}());
exports.MosaicProperties = MosaicProperties; | javascript | 19 | 0.660289 | 367 | 39.485915 | 142 | starcoderdata |
import os
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
from sklearn import svm
from sklearn.model_selection import cross_validate
from DataPrep import DATA
from ATLAS import ATLAS
from sklearn.decomposition import PCA
Atlas = ATLAS()
FileDir = os.getcwd()+'/PCA/'
FigName = "Brain_PCA"
file_object = open(FileDir+'PCA_Log.txt', "a")
Data = DATA()
Data.Train_Test(0.8,1234)
Data.Add_MRI("brain")
Data.Split_Data()
PCA_space = np.arange(1,30)*3
Train_Best = []
Valid_Best = []
Test_Best = []
MaxCs = []
for comp in PCA_space:
pca = PCA(n_components=comp)
pca.fit(Data.features_train[:,5:])
X_train_pca = pca.transform(Data.features_train[:,5:])
X_test_pca = pca.transform(Data.features_test[:,5:])
train = np.hstack((X_train_pca,Data.features_train[:,0:5]))
test = np.hstack((X_test_pca,Data.features_test[:,0:5]))
print("Training....")
train_score = []
test_score = []
C_space = np.logspace(-7,3,30)
for C in C_space:
SVM = svm.SVC(kernel='linear', C=C)
cvs = cross_validate(SVM,train,Data.labels_train, cv=4,return_train_score=True)
train_score.append(np.mean(cvs["train_score"]))
test_score.append(np.mean(cvs["test_score"]))
# print("C="+str(C)+"Train"+str(np.mean(cvs["train_score"]))+"Valid"+str(np.mean(cvs["test_score"])))
maxC = C_space[test_score.index(max(test_score))]
SVM = svm.SVC(kernel='linear', C=maxC)
SVM.fit(train,Data.labels_train)
pred_test=SVM.predict(test)
Train_Best.append(train_score[test_score.index(max(test_score))])
Valid_Best.append(max(test_score))
Test_Best.append(accuracy_score(pred_test,Data.labels_test))
MaxCs.append(maxC)
print("PCA = "+str(comp))
print("Max Acc = "+str(np.around(max(test_score),4))+", with C = "+str(maxC)+" Test Acc = "+str(accuracy_score(pred_test,Data.labels_test)))
file_object.write(str(comp)+','+str(maxC)+','+str(max(test_score))+','+str(accuracy_score(pred_test,Data.labels_test))+'\n')
plt.plot(PCA_space,Train_Best)
plt.plot(PCA_space,Valid_Best)
plt.plot(PCA_space,Test_Best)
plt.xlabel("PCA components")
plt.ylabel("Accuracy")
plt.legend(["Train","Valid","Test"])
plt.savefig(FileDir+FigName) | python | 17 | 0.668419 | 144 | 30.273973 | 73 | starcoderdata |
uint32_t vertex_for_edge(Lookup& lookup, std::vector<float>& vertices, uint32_t first, uint32_t second, float radius)
{
Lookup::key_type key(first, second);
if (key.first > key.second)
std::swap(key.first, key.second);
auto inserted = lookup.insert({ key, vertices.size() / 8 });
if (inserted.second)//The vertex doesnt exist
{
glm::vec3 edge0 = GetPosition(vertices, first);
glm::vec3 edge1 = GetPosition(vertices, second);
glm::vec3 point = radius * normalize(edge0 + edge1);
vertices.push_back(point.x);
vertices.push_back(point.y);
vertices.push_back(point.z);
vertices.push_back(0.0f); vertices.push_back(1.0f); vertices.push_back(0.0f);//Normal
vertices.push_back(0.0f); vertices.push_back(0.0f);//Texture Coordinate
}
return inserted.first->second;
} | c++ | 11 | 0.687732 | 117 | 34.130435 | 23 | inline |
boolean initAPI() {
_stateMachine.setState(EngineState.INITIALIZING_API);
// Determine the locale for logging
boolean localeInitialized = _configManager.determineLogLocale();
if (!localeInitialized) {
_stateMachine.setState(EngineState.API_INITIALIZATION_FAILED);
return false;
}
// Set the log filter
boolean logFilterSetOK = _configManager.determineLogFilter();
if (! logFilterSetOK) {
_stateMachine.setState(EngineState.API_INITIALIZATION_FAILED);
return false;
}
// Check that the runtime properties were correct
if (!_configManager.propertiesRead()) {
_stateMachine.setState(EngineState.API_INITIALIZATION_FAILED);
return false;
}
// Determine the current runtime properties
PropertyReader properties = _configManager.getRuntimeProperties();
// Determine at what level should the stack traces be displayed
String stackTraceAtMessageLevel = properties.get(LOG_STACK_TRACE_AT_MESSAGE_LEVEL);
if ("true".equals(stackTraceAtMessageLevel)) {
org.znerd.logdoc.Library.setStackTraceAtMessageLevel(true);
} else if ("false".equals(stackTraceAtMessageLevel)) {
org.znerd.logdoc.Library.setStackTraceAtMessageLevel(false);
} else if (stackTraceAtMessageLevel != null) {
// XXX: Report this error in some way
_stateMachine.setState(EngineState.API_INITIALIZATION_FAILED);
return false;
}
boolean succeeded = false;
try {
// Determine filter for incoming diagnostic context IDs
_contextIDPattern = determineContextIDPattern(properties);
// Initialize the diagnostic context ID generator
_contextIDGenerator.init(properties);
// Initialize the API
_api.init(properties);
// Initialize the default calling convention for this API
_conventionManager.init(properties);
succeeded = true;
// Missing required property
} catch (MissingRequiredPropertyException exception) {
Log.log_3411(exception.getPropertyName(), exception.getDetail());
// Invalid property value
} catch (InvalidPropertyValueException exception) {
Log.log_3412(exception.getPropertyName(),
exception.getPropertyValue(),
exception.getReason());
// Initialization of API failed for some other reason
} catch (InitializationException exception) {
Log.log_3413(exception);
// Other error
} catch (Throwable exception) {
Log.log_3414(exception);
// Always leave the object in a well-known state
} finally {
if (succeeded) {
_stateMachine.setState(EngineState.READY);
} else {
_stateMachine.setState(EngineState.API_INITIALIZATION_FAILED);
}
}
return succeeded;
} | java | 12 | 0.652321 | 89 | 33.325581 | 86 | inline |
using System;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
namespace IScenePlugin
{
///
/// Controllable orbital camera.
///
public interface ICamera
{
///
/// Gets or sets the render aspect ratio.
///
float AspectRatio { get; set; }
///
/// Gets the DirectX device instance.
///
Device Device { get; }
///
/// Gets the distance between camera location and target location.
///
float Distance { get; }
///
/// Gets or sets the far plan distance.
///
float Far { get; set; }
///
/// Gets or sets the field of view angle, in degrees.
///
float FieldOfView { get; set; }
///
/// Moves (travels) the camera.
///
/// <param name="direction">Directional vector, representing the movement offset to apply to the current camera location.
void Move(Vector3 direction);
///
/// Gets or sets the near plan distance.
///
float Near { get; set; }
///
/// Gets or sets the camera location.
///
Vector3 Position { get; set; }
///
/// Resets the camera default parameters.
///
void Reset();
///
/// Gets the camera right vector (vector perpendicular to view and up vectors).
///
Vector3 RightVector { get; }
///
/// Rotates the camera around the target.
///
/// <param name="ry">Rotating movement offset around the Y axis (horizontal move).
/// <param name="rx">Rotating movement offset around the X axis (vertical move).
void Rotate(float ry, float rx);
///
/// Gets or sets the target location.
///
Vector3 Target { get; set; }
///
/// Gets the head vector.
///
Vector3 Up { get; }
///
/// Updates the camera.
///
void Update();
///
/// Updates the camera.
///
/// <param name="e">Mouse related data to determine new camera parameters.
void Update(MouseEventArgs e);
///
/// Gets of sets the camera head behavior.
///
bool UpFree { get; set; }
///
/// Gets the up normal vector.
///
Vector3 UpVector { get; }
///
/// Gets the view normal vector (targeting vector).
///
Vector3 ViewVector { get; }
///
/// Zooms the view in or out.
///
/// <param name="zoom">Zoom offset to apply to the current zoom.
void Zoom(float zoom);
}
} | c# | 8 | 0.628749 | 131 | 27.479167 | 96 | starcoderdata |
import {NavLink} from 'react-router-dom';
const CustomNavLink = ({ children, ...props }) => (
<NavLink {...props}
className={({isActive}) => (isActive
? 'inline-flex items-center px-1 pt-1 border-b-2 ' +
'text-sm font-medium leading-5 focus:outline-none transition ' +
'duration-150 ease-in-out border-indigo-400 text-gray-900 focus:border-indigo-700'
: 'inline-flex items-center px-1 pt-1 border-b-2 text-sm ' +
'font-medium leading-5 focus:outline-none transition duration-150 ' +
'ease-in-out border-transparent text-gray-500 hover:text-gray-700 ' +
'hover:border-gray-300 focus:text-gray-700 focus:border-gray-300')
}>
{children}
)
export default CustomNavLink | javascript | 13 | 0.677665 | 88 | 40.473684 | 19 | starcoderdata |
using System;
using System.Threading;
namespace Flowmap
{
internal class ArrayThreadedInfo
{
public ArrayThreadedInfo(int start, int length, global::System.Threading.ManualResetEvent resetEvent)
{
this.start = start;
this.length = length;
this.resetEvent = resetEvent;
}
public int start;
public int length;
public global::System.Threading.ManualResetEvent resetEvent;
}
} | c# | 12 | 0.746269 | 103 | 18.142857 | 21 | starcoderdata |
"""Save the vorticity field as a 2D array in HDF5 files.
PetIBM saves the vorticity at a 3D array even if the solution is 2D.
Thus, we have to re-write the vorticity solution as a 2D array.
Create a XDMF file to visualize the 2D field with VisIt.
"""
import sys
import pathlib
import numpy
import yaml
import petibmpy
name = 'wz' # name of the field variable
# Get directories.
simudir = pathlib.Path(__file__).absolute().parents[1]
datadir = simudir / 'output' / 'solution'
outdir = simudir / 'output' / 'postprocessing' / name
outdir.mkdir(parents=True, exist_ok=True)
# Read 3D grid and write 2D grid.
gridpath = simudir / 'output' / 'grid.h5'
x, y = petibmpy.read_grid_hdf5(gridpath, name)
gridpath = outdir / 'grid.h5'
petibmpy.write_grid_hdf5(gridpath, name, x, y)
# Get temporal parameters.
filepath = simudir / 'config.yaml'
with open(filepath, 'r') as infile:
config = yaml.load(infile, Loader=yaml.FullLoader)['parameters']
dt = config['dt']
states = sorted([int(p.stem) for p in datadir.iterdir()])
for state in states:
print('[time step {}]'.format(state))
filename = '{:0>7}.h5'.format(state)
filepath = datadir / filename
data = petibmpy.read_field_hdf5(filepath, name)
filepath = outdir / filename
petibmpy.write_field_hdf5(filepath, name, data)
# Write XDMF file to visualize field with VisIt.
filepath = outdir / (name + '.xmf')
petibmpy.write_xdmf(filepath, outdir, gridpath, name, dt, states=states) | python | 10 | 0.715227 | 72 | 29.959184 | 49 | starcoderdata |
export function highScoreLi (index, gameLog) {
return `
+ 1}
`
} | javascript | 7 | 0.544444 | 53 | 23.636364 | 11 | starcoderdata |
func (s *server) SayHello(ctx context.Context, req *helloworld.HelloRequest) (resp *helloworld.HelloReply, err error) {
resp = &helloworld.HelloReply{}
resp.Message = "Hello " + req.Name
if rand.Intn(10) < 7 { // will fail 70% of the time
err = errors.New("random failure simulated")
}
time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond) // random delay
return
} | go | 11 | 0.712401 | 119 | 41.222222 | 9 | inline |
@Test
// Calling ScannerSupplier.plus() just to make sure it throws the right exception
@SuppressWarnings("CheckReturnValue")
public void plusDoesntAllowDuplicateChecks() {
ScannerSupplier ss1 =
ScannerSupplier.fromBugCheckerClasses(ArrayEquals.class, StaticAccessedFromInstance.class);
ScannerSupplier ss2 = ScannerSupplier.fromBugCheckerClasses(ArrayEquals.class);
try {
ss1.plus(ss2);
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).contains("ArrayEquals");
}
} | java | 12 | 0.738819 | 99 | 36.333333 | 15 | inline |
import os
from PyPDF2 import PdfFileReader, PdfFileWriter
import pandas as pd
def pdf_splitter(path):
fname = os.path.splitext(os.path.basename(path))[0]
df = pd.read_csv('AllAwardees.tsv', index_col=None, sep='\t').fillna(value=' ')
df.index = df.index.rename("I")
user_names = [f'submission_{rec["I"]}.pdf' for rec in df.to_records()]
pdf = PdfFileReader(path)
for page in range(pdf.getNumPages()-1):
pdf_writer = PdfFileWriter()
pdf_writer.addPage(pdf.getPage(page))
output_filename = user_names[page]
with open(output_filename, 'wb') as out:
pdf_writer.write(out)
print('Created: {}'.format(output_filename))
def _fname(rec):
return '_'.join(str(rec['First Name']).split()+str(rec['Last Name']).split())
if __name__ == '__main__':
path = './AwardsWithAbstracts.pdf'
pdf_splitter(path) | python | 13 | 0.629797 | 83 | 28.533333 | 30 | starcoderdata |
var native = require('./build/Release/node_disk.node');
function callDiskInfo(path, callback) {
native.getDiskInfo(path, callback);
}
function callDiskInfoPromise(path) {
if(typeof Promise !== 'function') {
throw new Exception('Promise not exists. Please use callback.');
return;
}
return new Promise(function(resolve, reject){
callDiskInfo(path, function(err, result){
if(err) reject(result && result.message);
else resolve(result);
});
});
}
exports.getDisk = function(path, callback) {
var param_num = arguments.length;
var param_err = false;
var arg_type = typeof path;
var promise = null;
switch(param_num) {
case 0: promise = callDiskInfoPromise('');break;
case 1:
arg_type === 'function' ? callDiskInfo('', path) :
arg_type === 'string' ? (promise = callDiskInfoPromise(path)) : (param_err = true);
break;
case 2: arg_type == 'string' && typeof callback === 'function' ?
callDiskInfo(path, callback) : (param_err = true);
break;
default: param_err = true;
}
if(param_err) throw new Exception('Param error.');
if(promise) return promise;
}; | javascript | 21 | 0.676056 | 86 | 28.128205 | 39 | starcoderdata |
<?php
/**
*
* @author:
* @licence: GPL
*
*/
namespace IDCI\Bundle\SimpleScheduleBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* This entity is based on Property Named STATUS of the RFC2445
*
* Purpose: This property defines the overall status or confirmation for the calendar component.
*
* @ORM\Table(name="status")
* @ORM\Entity(repositoryClass="IDCI\Bundle\SimpleScheduleBundle\Repository\StatusRepository")
*/
class Status
{
// Status values for "EVENT"
const EVENT_CANCELLED = "CANCELLED"; // Indicates event was cancelled.
const EVENT_CONFIRMED = "CONFIRMED"; // Indicates event is definite.
const EVENT_TENTATIVE = "TENTATIVE"; // Indicates event is tentative.
// Status values for "TODO"
const TODO_CANCELLED = "CANCELLED"; // Indicates to-do was cancelled.
const TODO_COMPLETED = "COMPLETED"; // Indicates to-do completed.
const TODO_IN_PROCESS = "IN-PROCESS"; // Indicates to-do in process of
const TODO_NEEDS_ACTION = "NEEDS-ACTION"; // Indicates to-do needs action.
//Status values for "JOURNAL".
const JOURNAL_CANCELLED = "CANCELLED"; // Indicates journal is removed.
const JOURNAL_DRAFT = "DRAFT"; // Indicates journal is draft.
const JOURNAL_FINAL = "FINAL"; // Indicates journal is final.
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string", length=64, nullable=true)
*/
protected $value;
/**
* @ORM\Column(type="string", length=64, nullable=true)
* @Assert\Choice(choices = {"Event","Todo","Journal"}, message = "Choose a valid CalendarEntity.")
*/
protected $discr;
/**
* @ORM\OneToMany(targetEntity="CalendarEntity", mappedBy="status")
*/
protected $calendarEntities;
/**
* Constructor
*/
public function __construct()
{
$this->calendarEntities = new \Doctrine\Common\Collections\ArrayCollection();
}
public function __toString()
{
return $this->getValue();
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set value
*
* @param string $value
* @return Status
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
/**
* Get value
*
* @return string
*/
public function getValue()
{
return $this->value;
}
/**
* Set discr
*
* @param string $discr
* @return Status
*/
public function setDiscr($discr)
{
$this->discr = $discr;
return $this;
}
/**
* Get discr
*
* @return string
*/
public function getDiscr()
{
return $this->discr;
}
/**
* Add calendarEntities
*
* @param \IDCI\Bundle\SimpleScheduleBundle\Entity\CalendarEntity $calendarEntities
* @return Status
*/
public function addCalendarEntitie(\IDCI\Bundle\SimpleScheduleBundle\Entity\CalendarEntity $calendarEntities)
{
$this->calendarEntities[] = $calendarEntities;
return $this;
}
/**
* Remove calendarEntities
*
* @param \IDCI\Bundle\SimpleScheduleBundle\Entity\CalendarEntity $calendarEntities
*/
public function removeCalendarEntitie(\IDCI\Bundle\SimpleScheduleBundle\Entity\CalendarEntity $calendarEntities)
{
$this->calendarEntities->removeElement($calendarEntities);
}
/**
* Get calendarEntities
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getCalendarEntities()
{
return $this->calendarEntities;
}
} | php | 11 | 0.595648 | 116 | 22.951515 | 165 | starcoderdata |
package com.somecompany;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import java.util.LinkedHashMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("dev")
public class CustomerReservationReportTest {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate testRestTemplate;
@Test
public void shouldBeAbleToCatchValidationExceptionWhenGetCustomerReservationReportThroughAPICallWithQuestionMarkAppended() {
ResponseEntity responseEntity = testRestTemplate.exchange(
"http://localhost:" + port + "/api/reservation/report?", HttpMethod.GET, null,
new ParameterizedTypeReference {
});
// Assertion
assertEquals("BAD_REQUEST", ((LinkedHashMap<String, String>) responseEntity.getBody()).get("status"));
assertThat(((LinkedHashMap<String, String>) responseEntity.getBody()).get("message")
.contains("Required String parameter 'reportName' is not present"));
}
@Test
public void shouldBeAbleToCatchValidationExceptionWhenGetCustomerReservationReportThroughAPICallWhereStartDateIsIncomplete() {
ResponseEntity responseEntity = testRestTemplate.exchange(
"http://localhost:" + port + "/api/reservation/report?startDate", HttpMethod.GET, null,
new ParameterizedTypeReference {
});
// Assertion
assertEquals("BAD_REQUEST", ((LinkedHashMap<String, String>) responseEntity.getBody()).get("status"));
assertThat(((LinkedHashMap<String, String>) responseEntity.getBody()).get("message")
.contains("Start date must have the pattern 'YYYY-MM-DD'"));
}
@Test
public void shouldBeAbleToCatchValidationExceptionWhenGetCustomerReservationReportThroughAPICallWhereStartDateIsEmpty() {
ResponseEntity responseEntity = testRestTemplate.exchange(
"http://localhost:" + port + "/api/reservation/report?startDate=", HttpMethod.GET, null,
new ParameterizedTypeReference {
});
// Assertion
assertEquals("BAD_REQUEST", ((LinkedHashMap<String, String>) responseEntity.getBody()).get("status"));
assertThat(((LinkedHashMap<String, String>) responseEntity.getBody()).get("message")
.contains("Start date must have the pattern 'YYYY-MM-DD'"));
}
@Test
public void shouldBeAbleToCatchValidationExceptionWhenGetCustomerReservationReportThroughAPICallWhereEndDateIsIncomplete() {
ResponseEntity responseEntity = testRestTemplate.exchange(
"http://localhost:" + port + "/api/reservation/report?endDate", HttpMethod.GET, null,
new ParameterizedTypeReference {
});
// Assertion
assertEquals("BAD_REQUEST", ((LinkedHashMap<String, String>) responseEntity.getBody()).get("status"));
assertThat(((LinkedHashMap<String, String>) responseEntity.getBody()).get("message")
.contains("End date must have the pattern 'YYYY-MM-DD'"));
}
@Test
public void shouldBeAbleToCatchValidationExceptionWhenGetCustomerReservationReportThroughAPICallWhereEndDateIsEmpty() {
ResponseEntity responseEntity = testRestTemplate.exchange(
"http://localhost:" + port + "/api/reservation/report?endDate=", HttpMethod.GET, null,
new ParameterizedTypeReference {
});
// Assertion
assertEquals("BAD_REQUEST", ((LinkedHashMap<String, String>) responseEntity.getBody()).get("status"));
assertThat(((LinkedHashMap<String, String>) responseEntity.getBody()).get("message")
.contains("End date must have the pattern 'YYYY-MM-DD'"));
}
@Test
public void shouldBeAbleToCatchValidationExceptionWhenGetCustomerReservationReportThroughAPICallWhereStartDatePatternNotMatch() {
ResponseEntity responseEntity = testRestTemplate.exchange(
"http://localhost:" + port + "/api/reservation/report?startDate=20201106", HttpMethod.GET, null,
new ParameterizedTypeReference {
});
// Assertion
assertEquals("BAD_REQUEST", ((LinkedHashMap<String, String>) responseEntity.getBody()).get("status"));
assertThat(((LinkedHashMap<String, String>) responseEntity.getBody()).get("message")
.contains("Start date must have the pattern 'YYYY-MM-DD'"));
}
@Test
public void shouldBeAbleToCatchValidationExceptionWhenGetCustomerReservationReportThroughAPICallWhereEndDatePatternNotMatch() {
ResponseEntity responseEntity = testRestTemplate.exchange(
"http://localhost:" + port + "/api/reservation/report?endDate=20201106", HttpMethod.GET, null,
new ParameterizedTypeReference {
});
// Assertion
assertEquals("BAD_REQUEST", ((LinkedHashMap<String, String>) responseEntity.getBody()).get("status"));
assertThat(((LinkedHashMap<String, String>) responseEntity.getBody()).get("message")
.contains("End date must have the pattern 'YYYY-MM-DD'"));
}
} | java | 14 | 0.697667 | 133 | 48.641667 | 120 | starcoderdata |
static int ParseArgs(string[] args)
{
if (args.Length !=2 && args.Length != 3)
{
PrintUsage();
return -1;
}
else
{
string endpoint = args[0].ToLower();
string password = args[1];
string encryptionMode = args.Length == 3 ? args[2].ToLower() : "";
if (encryptionMode != "aes" && encryptionMode != "rc4" && encryptionMode != "xor")
{
Console.WriteLine($"Invalid encryption mode provided: '{encryptionMode}'.\nValid options: AES | RC4 | XOR.");
return -1;
}
try
{
// Finish parsing information
string[] epInfo = endpoint.Split(":");
string dns = epInfo[0];
int port = int.Parse(epInfo[1]);
CryptoServiceAlgorithm alg = CryptoServiceAlgorithm.Disabled;
// Set crypto mode
if (encryptionMode == "aes")
alg = CryptoServiceAlgorithm.AES;
else if (encryptionMode == "rc4")
alg = CryptoServiceAlgorithm.RC4;
else if (encryptionMode == "xor")
alg = CryptoServiceAlgorithm.XOR;
// Create new client
Client client = new Client(Protocol.FFTSI, dns, port, Hashing.SHA(password), alg);
// Listen to events
client.Disconnected += Client_Disconnected;
client.PacketReceived += Client_PacketReceived;
client.Ready += Client_Ready;
// Connect
client.Connect(1024 * 1024); // TODO: Make buffer size an optional parameter
if (client.Connected)
{
System.Diagnostics.Process.GetCurrentProcess().WaitForExit();
}
}
catch (Exception ex)
{
Logger.Error(ex.Message);
return -1;
}
}
return 0;
} | c# | 18 | 0.431838 | 129 | 36.295082 | 61 | inline |
#include
using namespace std;
#include "bng/bng.h"
#include "../shared/test_utils.h"
int main() {
string file_name = get_test_bngl_file_name(__FILE__);
BNG::BNGConfig bng_config;
BNG::BNGEngine bng_engine(bng_config);
BNG::BNGData& bng_data = bng_engine.get_data();
// load the test BNG file
int num_errors = BNG::parse_bngl_file(file_name, bng_data);
release_assert(num_errors == 0);
// we must initialize the bng_engine now
bng_engine.initialize();
// create Species A, the simplest way is to use the BNGL parser for it
BNG::Species A(bng_engine.get_data());
num_errors = BNG::parse_single_cplx_string("A", bng_data, A);
release_assert(num_errors == 0);
// finalize the species add A to to the species list
A.finalize_species(bng_config, false);
BNG::species_id_t A_id = bng_engine.get_all_species().find_or_add(A);
// get unimol rxn class, it must exist
BNG::RxnClass* rxn_class = bng_engine.get_all_rxns().get_unimol_rxn_class(A_id);
release_assert(rxn_class != nullptr);
// the products might not have been computed, make sure that they are
rxn_class->init_rxn_pathways_and_rates();
// check that we got back B as the only possible product
release_assert(rxn_class->pathways.size() == 1);
const BNG::RxnClassPathway& pathway = rxn_class->pathways[0];
release_assert(pathway.product_species_w_indices.size() == 1);
BNG::species_id_t prod_id = pathway.product_species_w_indices[0].product_species_id;
const BNG::Species& product = bng_engine.get_all_species().get(prod_id);
release_assert(product.name == "B");
} | c++ | 10 | 0.692356 | 86 | 31.571429 | 49 | starcoderdata |
cmd_t get_command() {
//#if (USE_TUX_CONTROLLER == 0) /* use keyboard control with arrow keys */
static int state = 0; /* small FSM for arrow keys */
//#endif
static cmd_t command = CMD_NONE;
cmd_t pushed = CMD_NONE;
int ch;
int tux_input; /* Flagged to 1 to indicate a key has been pressed. This takes precedence over keyboard. */
tux_input = 0;
/* Read all characters from stdin. */
while ((ch = getc(stdin)) != EOF) {
/* Backquote is used to quit the game. */
if (ch == '`')
return CMD_QUIT;
/* TUX controller takes precedence over control inputs, so check for inputs here first. */
/*
ioctl(fd, TUX_BUTTONS, &buttons);
printf("OUTPUT: %d\n\n",buttons);*/
/* return cmd if tux controller input occurs. */
/* if(((TUX_RIGHT ^ buttons) & TUX_RIGHT) == TUX_RIGHT){
pushed = CMD_RIGHT;
buttons = buttons - TUX_RIGHT;
}
if(((TUX_UP & buttons) & TUX_UP) == TUX_UP){
pushed = CMD_UP;
buttons = buttons - TUX_UP;
}
if(((TUX_DOWN & buttons) & TUX_DOWN) == TUX_DOWN){
pushed = CMD_DOWN;
buttons = buttons - TUX_DOWN;
}
if(((TUX_LEFT & buttons) & TUX_LEFT) == TUX_LEFT){
pushed = CMD_LEFT;
buttons = buttons - TUX_LEFT;
}
if(((TUX_A & buttons) & TUX_A) == TUX_A) {
pushed = CMD_MOVE_LEFT;
buttons = buttons - TUX_A;
}
if(((TUX_B & buttons) & TUX_B) == TUX_B) {
pushed = CMD_ENTER;
buttons = buttons - TUX_B;
}
if(((TUX_C & buttons) & TUX_C) == TUX_C) {
pushed = CMD_MOVE_RIGHT;
buttons = buttons - TUX_C;
}
if(((TUX_START & buttons) & TUX_START) == TUX_START) {
pushed = CMD_QUIT;
}
return pushed;*/
/*
* Arrow keys deliver the byte sequence 27, 91, and 'A' to 'D';
* we use a small finite state machine to identify them.
*
* Insert, home, and page up keys deliver 27, 91, '2'/'1'/'5' and
* then a tilde. We recognize the digits and don't check for the
* tilde.
*/
switch (state) {
case 0:
if (27 == ch) {
state = 1;
}
else if (valid_typing(ch)) {
typed_a_char(ch);
}
else if (10 == ch || 13 == ch) {
pushed = CMD_TYPED;
}
break;
case 1:
if (91 == ch) {
state = 2;
}
else {
state = 0;
if (valid_typing(ch)) {
/*
* Note that we may be discarding an ESC(27), but
* we don't use that as typed input anyway.
*/
typed_a_char(ch);
}
else if (10 == ch || 13 == ch) {
pushed = CMD_TYPED;
}
}
break;
case 2:
if (ch >= 'A' && ch <= 'D') {
switch (ch) {
case 'A': pushed = CMD_UP; break;
case 'B': pushed = CMD_DOWN; break;
case 'C': pushed = CMD_RIGHT; break;
case 'D': pushed = CMD_LEFT; break;
}
state = 0;
}
else if (ch == '1' || ch == '2' || ch == '5') {
switch (ch) {
case '2': pushed = CMD_MOVE_LEFT; break;
case '1': pushed = CMD_ENTER; break;
case '5': pushed = CMD_MOVE_RIGHT; break;
}
state = 3; /* Consume a '~'. */
}
else {
state = 0;
if (valid_typing(ch)) {
/*
* Note that we may be discarding an ESC(27) and
* a bracket(91), but we don't use either as
* typed input anyway.
*/
typed_a_char(ch);
}
else if (10 == ch || 13 == ch) {
pushed = CMD_TYPED;
}
}
break;
case 3:
state = 0;
if ('~' == ch) {
/* Consume it silently. */
}
else if (valid_typing(ch)) {
typed_a_char(ch);
}
else if (10 == ch || 13 == ch) {
pushed = CMD_TYPED;
}
break;
}
}
#if (USE_TUX_CONTROLLER == 0) /* use keyboard control with arrow keys */
#else /* USE_TUX_CONTROLLER */
/* Tux controller mode; still need to support typed commands. */
if (valid_typing(ch)) {
typed_a_char(ch);
}
else if (10 == ch || 13 == ch) {
pushed = CMD_TYPED;
}
#endif /* USE_TUX_CONTROLLER */
/*
* Once a direction is pushed, that command remains active
* until a turn is taken.
*/
if (pushed == CMD_NONE) {
command = CMD_NONE;
}
return pushed;
} | c | 19 | 0.38649 | 127 | 33.036585 | 164 | inline |
/* -*- c++ -*- -------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
Contributing author: (Temple U)
------------------------------------------------------------------------- */
#ifndef LMP_THR_DATA_H
#define LMP_THR_DATA_H
#if defined(_OPENMP)
#include
#endif
#include "timer.h"
namespace LAMMPS_NS {
// per thread data accumulators
// there should be one instance
// of this class for each thread.
class ThrData {
friend class FixOMP;
friend class ThrOMP;
public:
ThrData(int tid, class Timer *t);
~ThrData() { delete _timer; _timer = NULL; };
void check_tid(int); // thread id consistency check
int get_tid() const { return _tid; }; // our thread id.
// inline wrapper, to make this more efficient
// when per-thread timers are off
void timer(enum Timer::ttype flag) { if (_timer) _stamp(flag); };
double get_time(enum Timer::ttype flag);
// erase accumulator contents and hook up force arrays
void init_force(int, double **, double **, double *, double *, double *);
// give access to per-thread offset arrays
double **get_f() const { return _f; };
double **get_torque() const { return _torque; };
double *get_de() const { return _de; };
double *get_drho() const { return _drho; };
// setup and erase per atom arrays
void init_adp(int, double *, double **, double **); // ADP (+ EAM)
void init_cdeam(int, double *, double *, double *); // CDEAM (+ EAM)
void init_eam(int, double *); // EAM
void init_eim(int, double *, double *); // EIM (+ EAM)
void init_pppm(int, class Memory *);
void init_pppm_disp(int, class Memory *);
// access methods for arrays that we handle in this class
double **get_lambda() const { return _lambda; };
double **get_mu() const { return _mu; };
double *get_D_values() const { return _D_values; };
double *get_fp() const { return _fp; };
double *get_rho() const { return _rho; };
double *get_rhoB() const { return _rhoB; };
void *get_rho1d() const { return _rho1d; };
void *get_drho1d() const { return _drho1d; };
void *get_rho1d_6() const { return _rho1d_6; };
void *get_drho1d_6() const { return _drho1d_6; };
private:
double eng_vdwl; // non-bonded non-coulomb energy
double eng_coul; // non-bonded coulomb energy
double eng_bond; // bond energy
double eng_angle; // angle energy
double eng_dihed; // dihedral energy
double eng_imprp; // improper energy
double eng_kspce; // kspace energy
double virial_pair[6]; // virial contribution from non-bonded
double virial_bond[6]; // virial contribution from bonds
double virial_angle[6]; // virial contribution from angles
double virial_dihed[6]; // virial contribution from dihedrals
double virial_imprp[6]; // virial contribution from impropers
double virial_kspce[6]; // virial contribution from kspace
double *eatom_pair;
double *eatom_bond;
double *eatom_angle;
double *eatom_dihed;
double *eatom_imprp;
double *eatom_kspce;
double **vatom_pair;
double **vatom_bond;
double **vatom_angle;
double **vatom_dihed;
double **vatom_imprp;
double **vatom_kspce;
// per thread segments of various force or similar arrays
// these are maintained by atom styles
double **_f;
double **_torque;
double *_erforce;
double *_de;
double *_drho;
// these are maintained by individual pair styles
double **_mu, **_lambda; // ADP (+ EAM)
double *_rhoB, *_D_values; // CDEAM (+ EAM)
double *_rho; // EAM
double *_fp; // EIM (+ EAM)
// this is for pppm/omp
void *_rho1d;
void *_drho1d;
// this is for pppm/disp/omp
void *_rho1d_6;
void *_drho1d_6;
// my thread id
const int _tid;
// timer info
int _timer_active;
class Timer *_timer;
private:
void _stamp(enum Timer::ttype flag);
public:
// compute global per thread virial contribution from global forces and positions
void virial_fdotr_compute(double **, int, int, int);
double memory_usage();
// disabled default methods
private:
ThrData() : _tid(-1), _timer(NULL) {};
};
////////////////////////////////////////////////////////////////////////
// helper functions operating on data replicated for thread support //
////////////////////////////////////////////////////////////////////////
// generic per thread data reduction for continous arrays of nthreads*nmax size
void data_reduce_thr(double *, int, int, int, int);
}
#endif | c | 12 | 0.602255 | 83 | 32.620915 | 153 | starcoderdata |
# -*- coding: utf-8 -*-
"""1st.findsalgorithm.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1KA_fp3hlM3qaQ5TwRakNTWnt8nD96dND
1. **Implement and demonstrate the FIND-S algorithm for finding the most specific hypothesis based on a given set of training data samples. Read the training data from a .CSV file.**
"""
import csv
num_attributes = 6
a = []
print("\n The Given Training Data Set \n")
with open('enjoysport.csv', 'r') as csvfile:
next(csvfile)
for row in csv.reader(csvfile):
a.append(row)
print(a)
print("\n The initial value of hypothesis: ")
hypothesis = ['0'] * num_attributes
print(hypothesis)
for j in range(0, num_attributes):
hypothesis[j] = a[0][j];
print(hypothesis)
print("\n Find S: Finding a Maximally Specific Hypothesis\n")
for i in range(0, len(a)):
if a[i][num_attributes] == 'yes':
for j in range(0, num_attributes):
if a[i][j]!= hypothesis[j]:
hypothesis[j] = '?'
else:
hypothesis[j]= a[i][j]
print(" For Training instance No:{0} the hypothesis is ".format(i), hypothesis)
print("\n The Maximally Specific Hypothes is for a given Training Examples :\n")
print(hypothesis) | python | 14 | 0.661994 | 182 | 28.204545 | 44 | starcoderdata |
package com.mercadopago.android.testlib;
import androidx.test.core.app.ApplicationProvider;
import java.io.InputStream;
public final class MockTestUtils {
private MockTestUtils() {
}
public static String getBody(final int rawId) {
String body = "";
final InputStream inputStream = ApplicationProvider.getApplicationContext().getResources().openRawResource(rawId);
try {
final byte[] b = new byte[inputStream.available()];
inputStream.read(b);
body = new String(b);
} catch (final Exception ignored) {
}
return body;
}
} | java | 11 | 0.67364 | 122 | 30.217391 | 23 | starcoderdata |
#include <bits/stdc++.h>
using namespace std;
#define INF_LL (int64)1e18
#define INF (int32)1e9
#define REP(i, n) for(int i = 0;i < (n);i++)
#define FOR(i, a, b) for(int i = (a);i < (b);i++)
#define all(x) x.begin(),x.end()
#define fs first
#define sc second
using int32 = int_fast32_t;
using uint32 = uint_fast32_t;
using int64 = int_fast64_t;
using uint64 = uint_fast64_t;
using PII = pair<int32, int32>;
using PLL = pair<int64, int64>;
const double eps = 1e-6;
template<typename A, typename B>inline void chmin(A &a, B b){if(a > b) a = b;}
template<typename A, typename B>inline void chmax(A &a, B b){if(a < b) a = b;}
// const int64 mod = 1e9+7;
int64 N, mod;
int64 fact[3030], inv[3030];
int64 dp[3030][3030] = {};
int64 mpow(int64 a, int64 b, int64 m){
if(b == 0) return 1;
if(b%2) return a*mpow(a, b-1, m)%m;
int64 ret = mpow(a, b/2, m);
return ret*ret%m;
}
int64 comb(int64 a, int64 b){
return fact[a]*inv[b]%mod*inv[a-b]%mod;
}
void init(){
fact[0] = 1;
REP(i, 3029) fact[i+1] = (fact[i]*(i+1))%mod;
REP(i, 3030) inv[i] = mpow(fact[i], mod-2, mod);
REP(i, 3030) dp[i][0] = 1;
FOR(i, 1, 3030){
FOR(j, 1, 3030){
dp[i][j] = dp[i-1][j]*(j+1)+dp[i-1][j-1];
dp[i][j] %= mod;
}
}
}
int64 f(int64 x){
int64 ret = 0;
int64 p = mpow(2, (N-x), mod);
int64 pa = 1;
int64 pb = mpow(2, mpow(2, N-x, mod-1), mod);
FOR(i, 0, x+1){
ret += dp[x][i]*pa%mod*pb%mod;
ret %= mod;
pa = pa*p%mod;
}
return ret;
}
int main(void){
cin >> N >> mod;
init();
int64 res = 0;
REP(i, N+1){
if(i%2) res = (res-comb(N, i)*f(i)%mod+mod)%mod;
else res = (res+f(i)*comb(N, i)%mod)%mod;
}
cout << res << endl;
} | c++ | 15 | 0.575092 | 78 | 20.285714 | 77 | codenet |
BOOL
HandleDeviceChange(
HWND hWnd,
DWORD evtype,
PDEV_BROADCAST_HANDLE dhp
)
{
UINT i;
DEV_BROADCAST_HANDLE filter;
PDEVICE_INFO deviceInfo = NULL;
PLIST_ENTRY thisEntry;
HANDLE tempHandle;
//
// Walk the list to get the deviceInfo for this device
// by matching the handle given in the notification.
//
for(thisEntry = ListHead.Flink; thisEntry != &ListHead;
thisEntry = thisEntry->Flink)
{
deviceInfo = CONTAINING_RECORD(thisEntry, DEVICE_INFO, ListEntry);
if(dhp->dbch_handle == deviceInfo->hDevice) {
break;
}
deviceInfo = NULL;
}
if(!deviceInfo) {
MessageBox(hWnd, TEXT("Unknown Device"), TEXT("Error"), MB_OK);
return FALSE;
}
switch (evtype)
{
case DBT_DEVICEQUERYREMOVE:
Display(TEXT("Query Remove (Handle Notification)"),
deviceInfo->DeviceName);
//
// Close the handle so that target device can
// get removed. Do not unregister the notification
// at this point, because you want to know whether
// the device is successfully removed or not.
//
tempHandle = deviceInfo->hDevice;
CloseDeviceHandles(deviceInfo);
//
// Since we use the handle to locate the deviceinfo, we
// will reset the handle to the original value and
// clear it in the the remove_pending message callback.
// ugly hack..
//
deviceInfo->hDevice = tempHandle;
break;
case DBT_DEVICEREMOVECOMPLETE:
Display(TEXT("Remove Complete (Handle Notification):%ws"),
deviceInfo->DeviceName);
//
// Device is removed so close the handle if it's there
// and unregister the notification
//
if (deviceInfo->hHandleNotification) {
UnregisterDeviceNotification(deviceInfo->hHandleNotification);
deviceInfo->hHandleNotification = NULL;
}
CloseDeviceHandles(deviceInfo);
//
// Unlink this deviceInfo from the list and free the memory
//
RemoveEntryList(&deviceInfo->ListEntry);
HeapFree (GetProcessHeap(), 0, deviceInfo);
break;
case DBT_DEVICEREMOVEPENDING:
Display(TEXT("Remove Pending (Handle Notification):%ws"),
deviceInfo->DeviceName);
//
// Device is removed so close the handle if it's there
// and unregister the notification
//
if (deviceInfo->hHandleNotification) {
UnregisterDeviceNotification(deviceInfo->hHandleNotification);
deviceInfo->hHandleNotification = NULL;
deviceInfo->hDevice = INVALID_HANDLE_VALUE;
}
//
// Unlink this deviceInfo from the list and free the memory
//
RemoveEntryList(&deviceInfo->ListEntry);
HeapFree (GetProcessHeap(), 0, deviceInfo);
break;
case DBT_DEVICEQUERYREMOVEFAILED :
Display(TEXT("Remove failed (Handle Notification):%ws"),
deviceInfo->DeviceName);
//
// Remove failed. So reopen the device and register for
// notification on the new handle. But first we should unregister
// the previous notification.
//
if (deviceInfo->hHandleNotification) {
UnregisterDeviceNotification(deviceInfo->hHandleNotification);
deviceInfo->hHandleNotification = NULL;
}
deviceInfo->hDevice = CreateFile(deviceInfo->DevicePath,
GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_EXISTING, 0, NULL);
if(deviceInfo->hDevice == INVALID_HANDLE_VALUE) {
Display(TEXT("Failed to reopen the device: %ws"),
deviceInfo->DeviceName);
//
// Unlink this deviceInfo from the list and free the memory
//
RemoveEntryList(&deviceInfo->ListEntry);
HeapFree (GetProcessHeap(), 0, deviceInfo);
break;
}
//
// Register handle based notification to receive pnp
// device change notification on the handle.
//
memset (&filter, 0, sizeof(filter)); //zero the structure
filter.dbch_size = sizeof(filter);
filter.dbch_devicetype = DBT_DEVTYP_HANDLE;
filter.dbch_handle = deviceInfo->hDevice;
deviceInfo->hHandleNotification =
RegisterDeviceNotification(hWnd, &filter, 0);
Display(TEXT("Reopened device %ws"), deviceInfo->DeviceName);
break;
default:
Display(TEXT("Unknown (Handle Notification)"),
deviceInfo->DeviceName);
break;
}
return TRUE;
} | c | 14 | 0.547257 | 77 | 32.417219 | 151 | inline |
package com.example.demo.common.exception.util;
/**
* 常量类
*/
public interface ErrorConstants {
public static final String RE_DELIMERS = "\\s*[,;]\\s*";
// 异常错误码
String ERROR_CODE = "errorCode";
// 默认异常错误码
String DEFAULT_ERROR_CODE = "000000";
// 异常提示信息
String ERROR_MSG = "errorMsg";
// 默认异常提示信息
String DEFAULT_ERROR_MSG = "业务异常未定义!";
// 默认省份编码
String DEFAULT_PROVINCECODE = "000";
/***
* 系统异常相关的全局常量
*
*/
interface SYSTEM {
/**
* 系统严重告警
*/
String TERRIBLE = "050000";
/**
* 系统主要异常
*/
String PRINCIPAL = "040000";
/**
* 异常类型无法实例化
*/
String PRINCIPAL_CLASSNOTFOUND= "041000";
/**
* 系统一般异常
*/
String COMMON = "030000";
/**
* 系统提示异常
*/
String TIP = "020000";
/**
* 系统未知异常
*/
String UNKNOWN = "010000";
/**
* Dubbo类异常前缀
* 051000:未知异常;
* 051001:Dubbo调用网络异常;
* 051002:Dubbo调用超时异常
* 051003:用户自定义Dubbo异常;
* 051004:没有服务提供者或者服务提供者被禁用;
* 051005:Dubbo序列化异常;
*/
String DUBBO_PREFIX = "05100";
/**
* JDK类异常前缀
*/
String JDK_PREFIX = "05200";
/**
* NullPointerException
*/
String JDK_NPE = "052001";
/**
* IndexOutOfBoundsException
*/
String JDK_IOBE = "052002";
/**
* ArithmeticException
*/
String JDK_ARIE = "052003";
/**
* MissingResourceException
*/
String JDK_MRE = "052004";
/**
* ConcurrentModificationException
*/
String JDK_CME = "052005";
/**
* ClassCastException
*/
String JDK_CCE = "052006";
/**
* NoSuchElementException
*/
String JDK_NSE = "052007";
/**
* UnsupportedOperationException
*/
String JDK_UOE = "052008";
/**
* IllegalStateException
*/
String JDK_ISE = "052009";
/**
* IllegalArgumentException
*/
String JDK_IAE = "052010";
/**
* NoSuchMethodException
*/
String JDK_NSME = "052011";
/**
* 其他异常前缀
*/
String OTHER_PREFIX = "05300";
}
/***
* DB异常相关的全局常量
*
*/
interface DATABASE {
// 数据访问异常前缀
String DATAACCESS_CLASS = "org.springframework.dao";
String DATAACCESS_JDBC_CLASS = "org.springframework.jdbc";
// 数据访问异常
String DATAACCESS = "250000";
// 事务处理异常前缀
String TRANSACTION_CLASS = "org.springframework.transaction";
// 事务处理异常
String TRANSACTION = "251000";
}
} | java | 8 | 0.472479 | 69 | 20.992481 | 133 | starcoderdata |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.