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 |
---|---|---|---|---|---|---|---|
<?php
use yii\widgets\ActiveForm;
use yii\helpers\Html;
$form=ActiveForm::begin();
echo $form->field($u,'name');
echo $form->field($u,'pass');
echo Html::submitButton('Вход',['class'=>'btn btn-success']);
ActiveForm::end();
?> | php | 8 | 0.665217 | 61 | 18.25 | 12 | starcoderdata |
#include "Controller/UnitController.h"
#include
#include
using namespace ACC::Controller;
using ACC::Measures::Temperature;
using ACC::Measures::Humidity;
using ACC::Devices::AirConditionerStatus;
void UnitController::process() {
if (display.hasAirConditioningManagementStatusChangeRequest()) {
EEPROM.put(Persistence::Address::acManagementEnabled, display.getRequestedAirConditioningManagementStatus());
display.setAirConditioningSectionVisibility(isAcManagementEnabled());
}
if (display.hasTargetPrimaryTemperatureChangeRequest()) {
EEPROM.put(Persistence::Address::targetTemperature, display.getRequestedPrimaryTargetTemperature());
display.setTargetPrimaryTemperature(getTargetTemperature());
}
if (lastTemperatureUpdate.getMinAgeSeconds() >= temperatureUpdateInterval) {
if (isAcManagementEnabled()) {
toggleAirConditioning();
}
updateDisplayData();
lastTemperatureUpdate = timeSource.currentTimestamp();
}
if (lastEvaluationTimestamp.getMinAgeSeconds() >= statusEvaluationInterval) {
if (isAcManagementEnabled()) {
evaluateAirConditioningStatus();
}
lastEvaluationTimestamp = timeSource.currentTimestamp();
}
}
void UnitController::toggleAirConditioning() {
TargetTemperature targetTemperature = getTargetTemperature();
Temperature temperature = temperatureSensor.measureTemperature();
AirConditionerStatus previousStatus = airConditioner.getStatus();
if (targetTemperature.isTemperatureAboveRange(temperature)) {
airConditioner.turnOn();
}
if (targetTemperature.isTemperatureBellowRange(temperature)) {
airConditioner.turnOff();
}
if (previousStatus != airConditioner.getStatus()) {
// we successfully attempted turning AC On or Off, re-evaluate AC status comparing against current measures
lastEvaluationTimestamp = timeSource.currentTimestamp();
refTemperature = temperature;
}
}
void UnitController::evaluateAirConditioningStatus() {
TargetTemperature targetTemperature = getTargetTemperature();
Temperature temperature = temperatureSensor.measureTemperature();
if (targetTemperature.isTemperatureAboveRange(temperature) && !(temperature < refTemperature)) {
// AC should be on, but the temperature has not fallen significantly in last interval
airConditioner.turnOn(true);
}
if (targetTemperature.isTemperatureBellowRange(temperature) && temperature < refTemperature) {
// AC should be off, but the temperature is still significantly falling
airConditioner.turnOff(true);
}
refTemperature = temperature;
}
void UnitController::updateDisplayData() {
TargetTemperature targetTemperature = getTargetTemperature();
Temperature temperature = temperatureSensor.measureTemperature();
Humidity humidity = humiditySensor.measureHumidity();
Devices::AirConditionerStatus airConditionerStatus = airConditioner.getStatus();
display.setPrimaryTemperature(
temperature,
targetTemperature.isWarningTemperature(temperature) && isAcManagementEnabled()
);
display.setAirConditioningSectionVisibility(isAcManagementEnabled());
display.setTargetPrimaryTemperature(targetTemperature);
display.setAirConditionerStatus(airConditionerStatus);
display.setPrimaryHumidity(humidity);
}
TargetTemperature UnitController::getTargetTemperature() {
double value;
EEPROM.get(Persistence::Address::targetTemperature, value);
return TargetTemperature(value);
}
bool UnitController::isAcManagementEnabled() {
bool value;
EEPROM.get(Persistence::Address::acManagementEnabled, value);
return value;
} | c++ | 10 | 0.748748 | 117 | 35.471154 | 104 | starcoderdata |
bool PacketTraceGen::sendPacket(PacketPtr packet)
{
if (params()->system->isMemAddr(packet->getAddr())) {
if (system->isAtomicMode()) {
port.sendAtomic(packet);
receivePacket(packet);
return true;
}
const bool packet_sent = port.sendTimingReq(packet);
if (!packet_sent) {
// Save this packet and try sending it again later.
retryPacket = packet;
retryTick = curTick();
return false; // packet not sent
}
} else {
DPRINTF(PacketTraceGen, "Suppressed %s 0x%x\n", packet->cmdString(),
packet->getAddr());
suppressedPackets++;
delete packet->req;
delete packet;
packet = nullptr;
}
return true; // packet was sent/suppressed
} | c++ | 11 | 0.553398 | 76 | 25.612903 | 31 | inline |
import numpy as np
from .optics import make_optics
from .controllers import Openloop, Integrator
from .experiments import Experiment, make_air, make_ustep, make_sine
optics = make_optics()
# Some predefined experiments
short_wait = Experiment(make_air, 1, optics)
med_wait = Experiment(make_air, 10, optics)
long_wait = Experiment(make_air, 100, optics)
ustep_tilt = Experiment(make_ustep, 1, optics, tilt_amp=0.005, tip_amp=0.0)
ustep_tip = Experiment(make_ustep, 1, optics, tilt_amp=0.0, tip_amp=0.005)
sine_one = Experiment(make_sine, 10, optics, amp=0.002, ang=np.pi/4, f=1)
sine_five = Experiment(make_sine, 10, optics, amp=0.002, ang=np.pi/4, f=5)
# and some controllers from the controller submodule
ol = Openloop()
integ = Integrator()
# Some pairings of experiments with controllers (zero-argument runnable functions from the Python interpreter)
olnone = lambda: med_wait.run(ol)
olsin1 = lambda: sine_one.run(ol)
olsin5 = lambda: sine_five.run(ol)
intnone = lambda: med_wait.run(integ)
intsin1 = lambda: sine_one.run(integ)
intsin5 = lambda: sine_five.run(integ)
# uconvert_ratio removed 2021-11-17 at commit just after 6a207e3 | python | 8 | 0.747378 | 110 | 35.935484 | 31 | starcoderdata |
"""
Edit:
2013-11-26 added direction, probability, hypothetical, etc. to Word and children
"""
from functools import total_ordering
@total_ordering
class Word(object):
def __init__(self, word, begin, end, _type='term', offset=0):
self.word_ = word
self.begin_ = begin
self.end_ = end
self.type_ = _type.lower()
self.offset_ = offset
self.certainty_ = 4 # 0-4 (neg to affm)
self.hypothetical_ = False # for status only
self.other_ = False # for status only
self.historical_ = False # for status only
self.direction_ = 0
def get_absolute_begin(self):
return self.begin() + self.offset_
def get_absolute_end(self):
return self.end() + self.offset_
def is_negated(self, normal=True):
if normal:
return self.certainty_ == 0
else:
return not self.negated_
def is_improbable(self):
return self.certainty_ == 1
def is_possible(self):
return self.certainty_ == 2
def is_probable(self):
return self.certainty_ == 3
def is_affirmed(self):
return self.certainty_ == 4
def get_certainty(self):
return self.certainty_
def set_certainty(self, level):
self.certainty_ = level
def is_hypothetical(self):
return self.hypothetical_
def is_historical(self):
return self.historical_
def is_not_patient(self):
return self.other_
def negate(self):
self.certainty_ = 0
def improbable(self):
if self.certainty_ > 1: # added 20140109
self.certainty_ = 1
def possible(self):
if self.certainty_ > 2: # added 20140109
self.certainty_ = 2
def probable(self):
if self.certainty_ > 3: # added 20140109
self.certainty_ = 3
def hypothetical(self):
self.hypothetical_ = True
def historical(self):
self.historical_ = True
def other_subject(self):
self.other_ = True
def direction(self):
return self.direction_
def begin(self):
return self.begin_
def set_begin(self, begin):
self.begin_ = begin
def end(self):
return self.end_
def set_end(self, end):
self.end_ = end
def word(self):
return str(self.word_)
def type(self):
return self.type_
def __len__(self):
return self.end_ - self.begin_
''' Comparisons defined by relative location
in the sentence. First term < last term. '''
def __gt__(self, other):
return self.begin_ > other.begin_ and self.end_ > other.end_ # must account for eq implementation
def __eq__(self, other):
""" equal if any overlap in indices """
return (self.begin_ == other.begin_ or
self.end_ == other.end_ or
(self.begin_ > other.begin_ and self.end_ < other.end_) or
(self.begin_ < other.begin_ and self.end_ > other.end_)
)
def __unicode__(self):
return str(self.word_)
def __str__(self):
return str(self).encode('utf-8')
def __repr__(self):
return ('<' + str(self.word_) + ',' + str(self.begin_) + ':' +
str(self.end_) +
(',NEG' if self.is_negated() else ',POS' if self.is_possible else '') +
', <' + self.type_ + '>>')
class Term(Word):
def __init__(self, word, begin, end, _type, id_, offset=0):
super(Term, self).__init__(word, begin, end, _type, offset)
self.id_ = id_
def id(self):
return self.id_
def id_as_list(self):
if isinstance(self.id_, list):
return self.id_
else:
return [self.id_]
def add_term(self, other):
self.id_ = self.id_as_list() + other.id_as_list()
class Concept(Term):
def __init__(self, word, begin, end, id_, cat, certainty=4,
hypothetical=0, historical=0, not_patient=0, offset=0):
"""
For backwards compatibility:
certainty used to be neg(ated), boolean
hypothetical used to be pos(sible), boolean
"""
super(Concept, self).__init__(word, begin, end, "concept", id_, offset=offset)
self.cat_ = cat
if isinstance(certainty, bool): # old way
neg = certainty
pos = hypothetical
if neg:
self.negate()
if pos:
self.possible()
else: # new way
self.set_certainty(certainty)
if hypothetical:
self.hypothetical()
if historical:
self.historical()
if not_patient:
self.other_subject()
def cat(self):
return self.cat_
class Negation(Word):
def __init__(self, word, begin, end, _type='negn', direction=0, offset=0):
super(Negation, self).__init__(word, begin, end, _type, offset=offset)
self.direction_ = direction
self.negate()
def find_terms(terms, text, offset=0):
"""
Paramters:
terms - list of (term,id) where unique id for each term
:param terms:
:param text:
:param offset:
"""
results = []
for term, id_ in terms:
for m in term.finditer(text):
results.append(Term(term, m.start(), m.end(), 'term', id_, offset=offset))
return sorted(results)
def clean_terms(terms):
"""
remove terms that are subsumed by other terms
:param terms:
"""
terms.sort(reverse=False)
if len(terms) < 2:
return terms
i = 1
curr = 0
while True:
if terms[curr] == terms[i]:
if len(terms[curr]) > len(terms[i]):
del terms[i]
elif len(terms[curr]) < len(terms[i]):
del terms[curr]
curr = i - 1
elif terms[curr].begin() == terms[i].begin() and terms[curr].end() == terms[i].end():
terms[curr].add_term(terms[i])
del terms[i]
else: # keep both representations
curr = i
i += 1
else:
curr = i
i += 1
if i >= len(terms):
return terms
def add_words(terms, text, offset=0):
"""
Adds fill words between concepts (i.e., terms) from the text
based on begin and end offsets.
NB: Ignores extraneous words before and after concepts
since these do not play any role in combining terms
or determining negation.
:param terms:
:param text:
:param offset:
"""
curr = 0
words = []
for term in sorted(terms):
if term.begin() > curr:
for word in text[curr:term.begin()].split():
words.append(Word(word, curr + 1, curr + 1 + len(word), offset=offset))
curr = curr + 1 + len(word)
curr = term.end()
# ignoring extraneous words at end of sentence
return words | python | 20 | 0.53927 | 106 | 25.771863 | 263 | starcoderdata |
#include "http.h"
#include "memory_pool.h"
#define Queue_Depth 8192
#define accept 0
#define read 1
#define write 2
#define prov_buf 3
#define uring_timer 4
struct io_uring *get_ring();
void init_io_uring();
void submit_and_wait();
void add_read_request(http_request_t *request);
void add_accept(struct io_uring *ring,
int fd,
struct sockaddr *client_addr,
socklen_t *client_len,
http_request_t *req);
void add_write_request(void *usrbuf, http_request_t *r);
void add_provide_buf(int bid);
void uring_cq_advance(int count);
void uring_queue_exit();
void *get_bufs(int bid); | c | 6 | 0.660061 | 56 | 24.230769 | 26 | starcoderdata |
#include
extern int jb,ib;
extern char nameBLE,becon,beconchk;
char commandset_BLE[15][25]={
"AT+RENEW",
"AT+RESET",
"AT+MARJ0x1234",
"AT+MINO0xFA01",
"AT+ADVI5",
"AT+NAMECDACHYD",
"AT+ADTY3",
"AT+IBEA1",
"AT+DELO2",
"AT+PWRM0"
};
char checkset_BLE[15][25]={
"OK+RENEW",
"OK+RESET",
"OK+Set:0x1234",
"OK+Set:0xFA01",
"OK+Set:5",
"OK+Set:CDACHYD",
"OK+Set:3",
"OK+Set:1",
"OK+DELO2",
"OK+Set:0",
"OK+WAKE"
};
void set_Becon(char str[][9])
{
int loop=0;
int p=0;
for(int bec=2;bec<4;bec++){
char atib[]="AT+IBE";
char atibr[]="OK+Set:0x";
sprintf(becon,"%s%d%s",atib,bec,str[p]);
sprintf(beconchk,"%s%s",atibr,str[p]);
while(loop!=1)
{
UARTSend_ble(becon, strlen(becon));
for(ib=0;ib<0x100000;ib++);
if(check_Ok_ble(beconchk))
loop=1;
}
loop=0;
p++;
}
while(loop!=1)
{
//AT+RESET
UARTSend_ble(commandset_BLE[1], strlen(commandset_BLE[1]));
for(ib=0;ib<0100000;ib++);
if(check_Ok_ble(checkset_BLE[1]))
loop=1;
}
loop=0;
memset(nameBLE,0,sizeof(nameBLE));
jb=0;
char wkup[]=" Welcome to CDAC THE WAKEUP CALL AND THIS IS THIS IS IRON MAN AND HE IS SMART BUT BATMAN IS DETECTIVE I LIKE DETECTIVES!\r\n";
//wakeup through above string
for(ib=0;ib<20;ib++)
UARTSend_ble(wkup, strlen(wkup));
} | c | 12 | 0.496887 | 149 | 17.119048 | 84 | starcoderdata |
function hsv2hsl(hsv) {
var h = hsv[0],
s = hsv[1] / 100,
v = hsv[2] / 100,
sl, l;
l = (2 - s) * v;
sl = s * v;
sl /= (l <= 1) ? l : 2 - l;
sl = sl || 0;
l /= 2;
return [h, sl * 100, l * 100];
}
module.exports = hsv2hsl; | javascript | 19 | 0.487261 | 59 | 18.6875 | 16 | starcoderdata |
bool CPVRChannel::SetStreamURL(const std::string &strStreamURL)
{
CSingleLock lock(m_critSection);
if (m_strStreamURL != strStreamURL)
{
/* update the stream url */
m_strStreamURL = StringUtils::Format("%s", strStreamURL.c_str());
SetChanged();
m_bChanged = true;
return true;
}
return false;
} | c++ | 11 | 0.66055 | 69 | 19.5 | 16 | inline |
namespace KitchenRP.Domain.Models
{
public static class Roles
{
public const string Admin = "admin";
public const string Moderator = "moderator";
public const string User = "user";
}
} | c# | 10 | 0.631818 | 52 | 23.555556 | 9 | starcoderdata |
#include "clar_libgit2.h"
#include "git2/sys/filter.h"
#include "crlf.h"
static git_repository *g_repo = NULL;
void test_filter_query__initialize(void)
{
g_repo = cl_git_sandbox_init("crlf");
cl_git_mkfile("crlf/.gitattributes",
"*.txt text\n"
"*.bin binary\n"
"*.crlf text eol=crlf\n"
"*.lf text eol=lf\n"
"*.binident binary ident\n"
"*.ident text ident\n"
"*.identcrlf ident text eol=crlf\n"
"*.identlf ident text eol=lf\n"
"*.custom custom ident text\n");
}
void test_filter_query__cleanup(void)
{
cl_git_sandbox_cleanup();
}
static int filter_for(const char *filename, const char *filter)
{
git_filter_list *fl;
int filtered;
cl_git_pass(git_filter_list_load(
&fl, g_repo, NULL, filename, GIT_FILTER_TO_WORKTREE, 0));
filtered = git_filter_list_contains(fl, filter);
git_filter_list_free(fl);
return filtered;
}
void test_filter_query__filters(void)
{
cl_assert_equal_i(1, filter_for("text.txt", "crlf"));
cl_assert_equal_i(0, filter_for("binary.bin", "crlf"));
cl_assert_equal_i(1, filter_for("foo.lf", "crlf"));
cl_assert_equal_i(0, filter_for("foo.lf", "ident"));
cl_assert_equal_i(1, filter_for("id.ident", "crlf"));
cl_assert_equal_i(1, filter_for("id.ident", "ident"));
cl_assert_equal_i(0, filter_for("id.binident", "crlf"));
cl_assert_equal_i(1, filter_for("id.binident", "ident"));
}
void test_filter_query__autocrlf_true_implies_crlf(void)
{
cl_repo_set_bool(g_repo, "core.autocrlf", true);
cl_assert_equal_i(1, filter_for("not_in_gitattributes", "crlf"));
cl_assert_equal_i(1, filter_for("foo.txt", "crlf"));
cl_assert_equal_i(0, filter_for("foo.bin", "crlf"));
cl_assert_equal_i(1, filter_for("foo.lf", "crlf"));
cl_repo_set_bool(g_repo, "core.autocrlf", false);
cl_assert_equal_i(0, filter_for("not_in_gitattributes", "crlf"));
cl_assert_equal_i(1, filter_for("foo.txt", "crlf"));
cl_assert_equal_i(0, filter_for("foo.bin", "crlf"));
cl_assert_equal_i(1, filter_for("foo.lf", "crlf"));
}
void test_filter_query__unknown(void)
{
cl_assert_equal_i(1, filter_for("foo.custom", "crlf"));
cl_assert_equal_i(1, filter_for("foo.custom", "ident"));
cl_assert_equal_i(0, filter_for("foo.custom", "custom"));
}
void test_filter_query__custom(void)
{
git_filter custom = { GIT_FILTER_VERSION };
cl_git_pass(git_filter_register(
"custom", &custom, 42));
cl_assert_equal_i(1, filter_for("foo.custom", "crlf"));
cl_assert_equal_i(1, filter_for("foo.custom", "ident"));
cl_assert_equal_i(1, filter_for("foo.custom", "custom"));
git_filter_unregister("custom");
} | c | 9 | 0.663518 | 66 | 27.233333 | 90 | starcoderdata |
[Test]
public void GetBytes ()
{
byte[] random = new byte [25];
// The C code doesn't throw an exception yet.
_algo.GetBytes (random);
} | c# | 11 | 0.605263 | 48 | 20.857143 | 7 | inline |
package com.skymanlab.weighttraining.management.user.data;
import java.io.Serializable;
public class UserTraining implements Serializable {
// constant
public static final String LEVEL = "level";
public static final String THREE_MAJOR_MEASUREMENTS = "threeMajorMeasurements";
public static final String SQUAT = "squat";
public static final String DEADLIFT = "deadlift";
public static final String BENCH_PRESS = "benchPress";
// instance variable
private String level;
private int squat;
private int deadlift;
private int benchPress;
// getter, setter
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public int getSquat() {
return squat;
}
public void setSquat(int squat) {
this.squat = squat;
}
public int getDeadlift() {
return deadlift;
}
public void setDeadlift(int deadlift) {
this.deadlift = deadlift;
}
public int getBenchPress() {
return benchPress;
}
public void setBenchPress(int benchPress) {
this.benchPress = benchPress;
}
} | java | 8 | 0.651399 | 83 | 21.673077 | 52 | starcoderdata |
package worker
import (
"github.com/adjust/rmq"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"time"
)
type Configuration struct {
QueueAddr string `json:"queue_addr"`
QueueName string `json:"queue_name"`
StoreQueueName string `json:"store_queue_name"`
NbConsumer int `json:"nb_consumer"`
}
type Consumer struct {
name string
count int
before time.Time
conf *Configuration
plugins []*plugin
}
func NewConsumer(tag int, c *Configuration, p []*plugin) *Consumer {
return &Consumer{
name: fmt.Sprintf("worker-%d", tag),
count: 0,
before: time.Now(),
conf: c,
plugins: p,
}
}
func NewConfiguration(path string) (*Configuration, error) {
f, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
var c Configuration
if err = json.Unmarshal(f, &c); err != nil {
return nil, err
}
return &c, nil
}
func (c *Consumer) Consume(del rmq.Delivery) {
c.count++
// start the logic to perform YM checks
m := del.Payload()
res, err := c.plugins[0].SendEmail(m)
if err != nil {
log.Printf("consumer: %s - unable to check email: %v", c.name, err)
}
fmt.Println("plugin name: ", res.Name)
fmt.Println("version: ", res.Version)
fmt.Println("exec time: ", res.ExecTime)
fmt.Println("score: ", res.Score)
fmt.Println("headers to add: ", res.Headers)
del.Ack()
// now we can store the email if its ready to be sent
if ok := c.storeEmail(m); !ok {
log.Printf("consumer: %s - unable to store email", c.name)
}
}
func (c *Consumer) storeEmail(m string) bool {
connection := rmq.OpenConnection("emailsService", "tcp", c.conf.QueueAddr, 1)
queue := connection.OpenQueue(c.conf.StoreQueueName)
return queue.Publish(m)
}
// StartWorker will start a worker in order to consume DB with consumers
func StartWorker(confPath string) error {
conf, err := NewConfiguration(confPath)
if err != nil {
return err
}
// We should create the pipeline here
plugins := []*plugin{NewPlugin("spamassassin-plugin:12800")}
connection := rmq.OpenConnection("emailsService", "tcp", conf.QueueAddr, 1)
queue := connection.OpenQueue(conf.QueueName)
queue.StartConsuming(1000, 500*time.Millisecond)
host, _ := os.Hostname()
for i := 0; i < conf.NbConsumer; i++ {
log.Printf("adding consumer: %d to worker: %s\n", i, host)
queue.AddConsumer(host, NewConsumer(i, conf, plugins))
}
select {}
} | go | 13 | 0.678147 | 78 | 24.673684 | 95 | starcoderdata |
class Solution(object):
def minMoves(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
m = 0xFFFFFFFF
count = 0
for n in nums:
m = min([m, n])
count += n
return count - len(nums) * m | python | 12 | 0.426523 | 36 | 22.333333 | 12 | starcoderdata |
<?php
return array(
/**
* Menu items and titles
*/
'messageboard:board' => "Tablón de mensajes",
'messageboard:messageboard' => "tablón de mensajes",
'messageboard:viewall' => "Ver todo",
'messageboard:postit' => "Post",
'messageboard:history:title' => "Historial",
'messageboard:none' => "No hay nada en este tablón de mensajes",
'messageboard:num_display' => "Número de mensajes a mostrar",
'messageboard:desc' => "este es un tablón de mensajes en el que puedes poner contenido y otros usuarios pueden comentar.",
'messageboard:user' => "Tablón de mensajes de %s",
'messageboard:replyon' => 'responder en',
'messageboard:history' => "historial",
'messageboard:owner' => 'Tablón de mensajes de %s',
'messageboard:owner_history' => 'Posts de %s en el tablón de mensajes %s',
/**
* Message board widget river
*/
'river:messageboard:user:default' => "%s ha publicado en el tablón de mensajes %s",
/**
* Status messages
*/
'messageboard:posted' => "Se ha publicado en tu tablón de mensajes exitosamente.",
'messageboard:deleted' => "Se ha borrado el mensaje.",
/**
* Email messages
*/
'messageboard:email:subject' => 'Tienes nuevos comentarios en el tablón de mensajes',
'messageboard:email:body' => "Tienes comentarios en tu tablón de mensajes %s. Leelo:
%s
Para ver los comentarios en tu tablón de mensajes, haz click a continuación:
%s
Para ver el perfil de %s, haz click a continuación:
%s
No se puede responder a este email.",
/**
* Error messages
*/
'messageboard:blank' => "Es necesario poner algo en el campo del mensaje antes de guardar.",
'messageboard:notfound' => "No se pudo encontrar el elemento especificado.",
'messageboard:notdeleted' => "No se pudo borrar este mensaje.",
'messageboard:somethingwentwrong' => "Algo salió mal al guardar el mensaje. Asegúrate de haberlo escrito.",
'messageboard:failure' => "Ocurrió un error desconocido al guardar el mensaje. Intenta de nuevo.",
); | php | 5 | 0.702961 | 130 | 29.794118 | 68 | starcoderdata |
def _parse_req_map_annotation(self, annotation, tree):
"""
This method is used to parse the data within the parenthesis of the
request mapping annotation. ex. @RequestMapping(<here>)
:param annotation: The javalang.tree.Annotation object
:param tree: The Javalang tree
:return: An endpoint dictionary for the ReqMap
"""
params = annotation.element
# Create an empty Dict that will later be returned
endpoint_dict = {
'endpoints': set(),
'methods': set(),
'params': [],
'headers': []
}
# Process the parameter passed into the ReqMap into a Dictionary
parameters = self._parse_anno_args_to_dict(params)
# Resolve the values within the dictionary to python values
resolved_parameters = self._resolve_values_in_dict(parameters, tree)
# We've resolved the values now let's make an endpoint for it
if 'value' in resolved_parameters:
if type(resolved_parameters['value']) is list:
endpoint_dict['endpoints'] = endpoint_dict['endpoints'] | set(resolved_parameters['value'])
else:
endpoint_dict['endpoints'].add(resolved_parameters['value'])
if 'method' in resolved_parameters:
if type(resolved_parameters['method']) is list:
endpoint_dict['methods'] = endpoint_dict['methods'] | set(resolved_parameters['method'])
else:
endpoint_dict['methods'].add(resolved_parameters['method'])
if 'params' in resolved_parameters:
if type(resolved_parameters['params']) is not list:
resolved_parameters['params'] = [resolved_parameters['params']]
for param in resolved_parameters['params']:
param_dict = {}
if '=' in param:
param_dict['name'] = param.split('=')[0]
param_dict['value'] = param.split('=')[1]
else:
param_dict['name'] = param
endpoint_dict['params'].append(param_dict)
if 'headers' in resolved_parameters:
if type(resolved_parameters['headers']) is not list:
resolved_parameters['headers'] = [resolved_parameters['headers']]
for header in resolved_parameters['headers']:
header_dict = {}
if '=' in header:
header_dict['name'] = header.split('=')[0]
header_dict['value'] = header.split('=')[1]
else:
header_dict['name'] = header
endpoint_dict['headers'].append(header_dict)
# Add methods for shorthand mappings
if (hasattr(annotation, 'name') and
annotation.name.endswith('Mapping') and
annotation.name != 'RequestMapping'):
method = annotation.name[:-len('Mapping')]
endpoint_dict['methods'].add(method.upper())
return endpoint_dict | python | 15 | 0.556744 | 107 | 43.710145 | 69 | inline |
/*
* Copyright (c) 2018, hiwepy (https://github.com/hiwepy).
* All Rights Reserved.
*/
package hitool.core.compress;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import hitool.core.lang3.CharsetUtils;
/*
* .bz2文件压缩解压工具
*/
public abstract class BZip2Utils extends CompressUtils {
protected static final CharSequence EXT = ".bz2";
/*
* 压缩字符串
*
* @param text
* @return
* @throws IOException
*/
public static String compressString(String text) throws IOException {
if (text == null || text.length() == 0) {
return text;
}
return CharsetUtils.newStringUtf8(BZip2Utils.compress(text.getBytes()));
}
/*
* 压缩字节码
*
* @param databytes
* @return
* @throws IOException
*/
public static byte[] compress(byte[] databytes) throws IOException {
byte[] outBytes = null;
try (InputStream input = new ByteArrayInputStream(databytes);
ByteArrayOutputStream output = new ByteArrayOutputStream();) {
// 压缩
BZip2Utils.compress(input, output);
// 获取压缩后的结果
outBytes = output.toByteArray();
}
return outBytes;
}
/*
* 文件压缩
*
* @param file
* @param delete
* 是否删除原始文件
* @throws IOException
*/
public static void compress(File file) throws IOException {
BZip2Utils.compress(file, true);
}
/*
* 文件压缩
*
* @param srcFile
* @param delete:是否删除原始文件
* @throws Exception
*/
public static void compress(File srcFile, boolean delete) throws IOException {
File destFile = new File(srcFile.getParentFile(), FilenameUtils.getBaseName(srcFile.getName()) + EXT);
// 压缩
BZip2Utils.compress(srcFile, destFile);
if (delete) {
srcFile.delete();
}
}
public static void compress(File srcFile, File destFile) throws IOException {
try (InputStream input = new FileInputStream(srcFile);
OutputStream output = new FileOutputStream(destFile);) {
// 压缩
BZip2Utils.compress(input, output);
}
}
public static void compress(InputStream in, OutputStream out) throws IOException {
try (InputStream input = new BufferedInputStream(in, DEFAULT_BUFFER_SIZE);
BZip2CompressorOutputStream output = new BZip2CompressorOutputStream(new BufferedOutputStream(out, DEFAULT_BUFFER_SIZE));) {
IOUtils.copy(input, output);
output.finish();
output.flush();
}
}
/*
* 文件压缩
*
* @param filePath
* @throws Exception
*/
public static void compress(String filePath) throws IOException {
BZip2Utils.compress(filePath, true);
}
/*
* 文件压缩
*
* @param filePath
* @param delete
* :是否删除原始文件
* @throws Exception
*/
public static void compress(String filePath, boolean delete) throws IOException {
BZip2Utils.compress(new File(filePath), delete);
}
/*
* 字节解压缩
*
* @param databytes
* @return
* @throws Exception
*/
public static byte[] decompress(byte[] databytes) throws IOException {
byte[] outBytes = null;
try (InputStream input = new ByteArrayInputStream(databytes);
ByteArrayOutputStream output = new ByteArrayOutputStream();) {
// 解压缩
BZip2Utils.decompress(input, output);
// 获取解压后的数据
outBytes = output.toByteArray();
}
return outBytes;
}
/*
* 文件解压缩
*
* @param file
* @throws Exception
*/
public static void decompress(File file) throws IOException {
BZip2Utils.decompress(file, true);
}
/*
* 文件解压缩
*
* @param srcFile
* @param delete
* :是否删除原始文件
* @throws Exception
*/
public static void decompress(File srcFile, boolean delete) throws IOException {
// 解压缩
BZip2Utils.decompress(srcFile, srcFile.getParentFile());
if (delete) {
srcFile.delete();
}
}
public static void decompress(File srcFile, File destDir) throws IOException {
File destFile = new File(destDir, FilenameUtils.getBaseName(srcFile.getName()) + EXT);
try(InputStream input = new FileInputStream(srcFile);
OutputStream output = new FileOutputStream(destFile);) {
BZip2Utils.decompress(input, output);
}
}
/*
* 数据流解压缩
*
* @param in
* @param out
* @throws Exception
*/
public static void decompress(InputStream in, OutputStream out) throws IOException {
try (InputStream input = new BZip2CompressorInputStream(new BufferedInputStream(in, DEFAULT_BUFFER_SIZE));
OutputStream output = new BufferedOutputStream(out, DEFAULT_BUFFER_SIZE);) {
IOUtils.copy(input, output);
output.flush();
}
}
/*
* 文件解压缩
*
* @param filePath
* @throws Exception
*/
public static void decompress(String filePath) throws Exception {
BZip2Utils.decompress(filePath, true);
}
/*
* 文件解压缩
*
* @param filePath
* @param delete
* :是否删除原始文件
* @throws Exception
*/
public static void decompress(String filePath, boolean delete) throws IOException {
BZip2Utils.decompress(new File(filePath), delete);
}
} | java | 14 | 0.700887 | 128 | 22.762332 | 223 | starcoderdata |
from functools import wraps
from inspect import getfullargspec
from typing import get_type_hints
# Each port has two gpio pins associated with it
# Default pin for each class is "1"
# Convert Port for use with standard BCM pins
Port = {
"A0": {"1": 0, "2": 1},
"A1": {"1": 2, "2": 3},
"A2": {"1": 4, "2": 5},
"A3": {"1": 6, "2": 7},
"D0": {"1": 22, "2": 23},
"D1": {"1": 24, "2": 25},
"D2": {"1": 26, "2": 27},
"D3": {"1": 5, "2": 6},
"D4": {"1": 7, "2": 8},
"D5": {"1": 10, "2": 11},
"D6": {"1": 12, "2": 13},
"D7": {"1": 15, "2": 16},
}
def get_pin_for_port(port_name, pin_number=1):
assert port_name in Port
assert pin_number in (1, 2)
return Port[port_name][str(pin_number)]
def validate_input(obj, **kwargs):
hints = get_type_hints(obj)
for attr_name, attr_type in hints.items():
if attr_name == "return":
continue
attr_type_arr = [attr_type]
if hasattr(attr_type, "__args__"):
attr_type_arr = attr_type.__args__
has_errors = True
for attr_subtype in attr_type_arr:
# if we use a default value on the method, it won't be in kwargs
if attr_name not in kwargs or isinstance(kwargs[attr_name], attr_subtype):
has_errors = False
break
if has_errors:
raise TypeError(f"Argument '{attr_name}' is not of type {attr_type}")
def type_check(decorator):
@wraps(decorator)
def wrapped_decorator(*args, **kwargs):
# translate *args into **kwargs
func_args = getfullargspec(decorator)[0]
kwargs.update(dict(zip(func_args, args)))
validate_input(decorator, **kwargs)
return decorator(**kwargs)
return wrapped_decorator | python | 13 | 0.552836 | 86 | 28 | 62 | starcoderdata |
def test_plot_parameter_uncertainty(self):
if sys.version_info >= (3, 6):
posterior = spotpy.analyser.get_posterior(self.hymod_results,percentage=10)
#assertAlmostEqual tests on after comma accuracy, therefor we divide both by 100
self.assertAlmostEqual(len(posterior)/100, self.rep*0.001, 1)
self.assertEqual(type(posterior), type(np.array([])))
spotpy.analyser.plot_parameter_uncertainty(posterior,
hymod_setup().evaluation(),
fig_name=self.fig_name)
# approximately 8855 KB is the size of an empty matplotlib.pyplot.plot, so
# we expecting a plot with some content without testing the structure of the plot, just
# the size
self.assertGreaterEqual(os.path.getsize(self.fig_name), 8855) | python | 13 | 0.588683 | 99 | 64.714286 | 14 | inline |
def labels(self, threshold, segment=True, exclude_border=0):
"""
Label connected regions of intensities larger than a threshold
This method is a simple wrapper around scipy.measurements.label()
Parameters
----------
threshold : float
Lower bound defining the connected regions to be labeled.
segment : bool, optional
If True, watershed segmentation is used to further divide connected
regions into basins associated with each local maxima.
exclude_border : int
See `skimage.feature.peak_local_max`. Only relevant if
`subsegment == True`r.
Returns
-------
ndarray
Array of labels corresponding to the regions.
integer
Total number of labeled regions.
"""
data = self.unmasked_data
isfin = numpy.isfinite(data)
data[~isfin] = numpy.amin(data[isfin])
regions = (data > threshold)
if segment:
local_max = peak_local_max(data, indices=False,
exclude_border=0,
footprint=numpy.ones((3, 3)),
labels=regions)
markers = measurements.label(local_max)[0]
labels = watershed(-data, markers, mask=regions)
if exclude_border > 0:
# Remove basins originating from edge peaks
diff = numpy.zeros_like(local_max)
for i in range(local_max.ndim):
local_max = local_max.swapaxes(0, i)
diff = diff.swapaxes(0, i)
diff[:exclude_border] = local_max[:exclude_border]
diff[-exclude_border:] = local_max[-exclude_border:]
diff = diff.swapaxes(0, i)
local_max = local_max.swapaxes(0, i)
for l in numpy.sort(labels[diff])[::-1]:
labels[labels == l] = 0
labels[labels > l] -= 1
ulabels = numpy.unique(labels)
n = ulabels[ulabels != 0].size
else:
data_thres = numpy.zeros_like(data)
data_thres[regions] = data[regions]
labels, n = measurements.label(data_thres)
return labels, n | python | 14 | 0.519695 | 79 | 40.438596 | 57 | inline |
def _locate(self, x):
'''
Given a set of color data values, return their
corresponding colorbar data coordinates.
'''
if isinstance(self.norm, (colors.NoNorm, colors.BoundaryNorm)):
b = self._boundaries
xn = x
else:
# Do calculations using normalized coordinates so
# as to make the interpolation more accurate.
b = self.norm(self._boundaries, clip=False).filled()
xn = self.norm(x, clip=False).filled()
# The rest is linear interpolation with extrapolation at ends.
ii = np.searchsorted(b, xn)
i0 = ii - 1
itop = (ii == len(b))
ibot = (ii == 0)
i0[itop] -= 1
ii[itop] -= 1
i0[ibot] += 1
ii[ibot] += 1
db = np.take(b, ii) - np.take(b, i0)
y = self._y
dy = np.take(y, ii) - np.take(y, i0)
z = np.take(y, i0) + (xn - np.take(b, i0)) * dy / db
return z | python | 13 | 0.50763 | 71 | 32.931034 | 29 | inline |
def test_discover_and_request_capabilities(self):
discovered_devices = False
app = self.app
def discover_result(devices: [Device]):
nonlocal discovered_devices, app
discovered_devices = True
assert len(devices) > 0
for device in devices:
# assume capability request can be sent to a discovered device.
assert app.request_capabilities(device)
self.app.discover(discover_result)
self.assertTrue(discovered_devices) | python | 10 | 0.620561 | 79 | 34.733333 | 15 | inline |
<?php
namespace App\Controllers\Admin;
use App\Controllers\BaseController;
use \App\Models\LoginModel;
use Config\Services; //session işlemleri için ekle
use \App\Models\AyarModel;
use CodeIgniter\API\ResponseTrait;
class Ayar extends BaseController
{
public function __construct()
{
$this->session = Services::session();
}
public function index()
{
$data['site'] = $site = $this->request->getGet('site');
$data['dil'] = $dil = $this->request->getGet('dil');
$data['promo'] = $promo = $this->request->getGet("promo");
$data['sil'] = $sil = $this->request->getGet("sil");
$data['ayardb'] = $ayarDB = new AyarModel();
if(!empty($sil))
{
$a = $ayarDB->where(['anahtar'=>$sil])->delete();
if($a)
{
return redirect()->to(base_url("admin/ayar/index?promo=".$promo."&site=".$site."&dil=".$dil))->with('success',"Silme İşlemi Başarılı");
}
}
//pdata[site][img][arkaplan]
$this->upload("arkaplan",'arkaplan',$site,$dil);
$this->upload("logo",'logo',$site,$dil);
$this->upload("reklam1",'reklam1',$site,$dil);
$this->upload("reklam2",'reklam2',$site,$dil);
$this->upload("reklam3",'reklam3',$site,$dil);
$this->savePost("baslik","baslik",$site,$dil);
$this->savePost("description","description",$site,$dil);
$this->savePost("reklam1url","reklam1url",$site,$dil);
$this->savePost("reklam2url","reklam2url",$site,$dil);
$this->savePost("reklam3url","reklam3url",$site,$dil);
$this->savePost("css","css",$site,$dil);
$this->savePost("js","js",$site,$dil);
$this->savePost("bgcolor","bgcolor",$site,$dil);
$this->savePost("bglink","bglink",$site,$dil);
$this->savePost("ydomain","ydomain",$site,$dil);
$this->savePost("yurl","yurl",$site,$dil);
$this->upload("mobile_reklam1",'mobile_reklam1',$site,$dil);
$this->savePost("mobile_reklam1url","mobile_reklam1url",$site,$dil);
$this->upload("mobile_reklam2",'mobile_reklam2',$site,$dil);
$this->savePost("mobile_reklam2url","mobile_reklam2url",$site,$dil);
$this->upload("mobile_reklam3",'mobile_reklam3',$site,$dil);
$this->savePost("mobile_reklam3url","mobile_reklam3url",$site,$dil);
$this->savePost("bahisyap_btn","bahisyap_btn",$site,$dil);
if($promo=='false')
{
$title = 'Site Ayarları';
}else{
$title = 'Reklam Ayarları';
}
return \admin_('ayar',$data,$title);
}
function savePost($postname=null,$dbName=null,$site=null,$dil=null)
{
$post = $this->request->getPost($postname);
$ayarDB = new AyarModel();
if(!empty($post))
{
$where = ['anahtar'=>$dbName,'site'=>$site,'dil'=>$dil];
$row = $ayarDB->row_count($where);
$save['anahtar'] = $dbName;
$save['deger'] = $post;
$save['site'] = $site;
$save['dil'] = $dil;
$save['tip'] = 'site';
if(\count($row)==0)
{
$ayarDB->save($save);
}else{
$ayarDB->where($where)->update($row[0]['id'],$save);
}
}else{
echo "";
}
}
function upload($filename,$dbName=null,$site=null,$dil = null)
{
$ayarDB = new AyarModel();
helper(['text','inflector']);
$name = $this->request->getFile($filename);
if (isset($name) && !empty($name->getName())) {
$imageName = strtolower( \convert_accented_characters(\underscore($name->getName())));
print_r($imageName);
$uploadStatus= $name->move(ROOTPATH.'public_html/uploads/setting',$imageName);
print_r($uploadStatus);
if($uploadStatus)
{
$where = ['anahtar'=>$dbName,'site'=>$site,'dil'=>$dil];
$row = $ayarDB->row_count($where);
$save['anahtar'] = $dbName;
$save['deger'] = $imageName;
$save['site'] = $site;
$save['dil'] = $dil;
$save['tip'] = 'site';
if(count($row) == 0)
{
$ayarDB->save($save);
}else{
\unlink(ROOTPATH.'public_html/uploads/setting/'.$row[0]['deger']);
$ayarDB->where($where)->update($row[0]['id'],$save);
}
}
}else{
return "null";
}
}
}
?> | php | 23 | 0.482744 | 152 | 30.823529 | 153 | starcoderdata |
D3DIMContext3D(IDirect3D* pd3d, const IID& iid, Surface* psurface) :
m_pd3d(pd3d),
m_psurface(psurface)
{
//
// Initialize the state
//
Matrix mat;
mat.SetIdentity();
m_pstate = new State(mat, NULL);
//
// create the d3d device
//
DDCall(m_psurface->GetDDS()->QueryInterface(iid, (void**)&m_pd3dd));
//
// set a viewport
//
DDCall(m_pd3d->CreateViewport(&m_pd3dview, NULL));
DDCall(m_pd3dd->AddViewport(m_pd3dview));
D3DVIEWPORT view;
view.dwSize = sizeof(D3DVIEWPORT);
view.dwX = 0;
view.dwY = 0;
view.dwWidth = m_psurface->GetRect().XSize();
view.dwHeight = m_psurface->GetRect().YSize();
view.dvScaleX = (float)(m_psurface->GetRect().XSize() / 2);
view.dvScaleY = view.dvScaleX;
view.dvMaxX = 1;
view.dvMaxY = (float)m_psurface->GetRect().YSize() / (float)m_psurface->GetRect().XSize();
view.dvMinZ = 0;
view.dvMaxZ = 1;
/*
view.dwSize = sizeof(D3DVIEWPORT);
view.dwX = 0;
view.dwY = 0;
view.dwWidth = (int)m_psurface->GetRect().XSize();
view.dwHeight = (int)m_psurface->GetRect().YSize();
view.dvScaleX = 1;
view.dvScaleY = 1;
view.dvMaxX = view.dwWidth / 2.0f;
view.dvMaxY = view.dwHeight / 2.0f;
view.dvMinZ = 0;
view.dvMaxZ = 1;
*/
DDCall(m_pd3dview->SetViewport(&view));
//
// create a matrix
//
DDCall(m_pd3dd->CreateMatrix(&m_hmatrixWorld));
DDCall(m_pd3dd->CreateMatrix(&m_hmatrixProjection));
DDCall(m_pd3dd->CreateMatrix(&m_hmatrixView));
//
// make a material
//
D3DMATERIAL material;
material.dwSize = sizeof(material);
material.diffuse = D3DColor(1, 1, 1, 0);
material.ambient = D3DColor(1, 1, 1, 0);
material.specular = D3DColor(0, 0, 0, 0);
material.emissive = D3DColor(0, 0, 0, 0);
material.power = 1;
material.hTexture = NULL;
material.dwRampSize = 0;
DDCall(m_pd3d->CreateMaterial(&m_pmat, NULL));
DDCall(m_pmat->SetMaterial(&material));
DDCall(m_pmat->GetHandle(m_pd3dd, &m_hmat));
//DDCall(m_pd3dview->SetBackground(m_hmatBack));
//
// Create the execute buffer
//
m_pexec = new ExecuteBuffer(m_pd3dd, m_pd3dview);
} | c++ | 12 | 0.524806 | 100 | 27.677778 | 90 | inline |
/**********************************************************************
// @@@ START COPYRIGHT @@@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
// @@@ END COPYRIGHT @@@
**********************************************************************/
#include
#include "SortAlgo.h"
//-----------------------------------------------------------------------
// Constructor.
//-----------------------------------------------------------------------
SortAlgo::SortAlgo(ULng32 runsize, ULng32 recsize,
NABoolean doNotAllocRec, ULng32 keysize,
SortScratchSpace* scratch, Lng32 explainNodeId, ExBMOStats *bmoStats)
{
sendNotDone_ = TRUE_L;
runSize_ = runsize;
recSize_ = recsize;
doNotallocRec_ = doNotAllocRec;
keySize_ = keysize;
scratch_ = scratch;
numCompares_ = 0L;
internalSort_ = TRUE_L;
explainNodeId_ = explainNodeId;
bmoStats_ = bmoStats;
}
//-----------------------------------------------------------------------
// Name : getNumOfCompares
//
// Parameters :
//
// Description : This function retrieves number of comparisons.
//
// Return Value : unsigned long numCompares_
//
//-----------------------------------------------------------------------
ULng32 SortAlgo::getNumOfCompares() const
{
return numCompares_;
}
//-----------------------------------------------------------------------
// Name : getScratch
//
// Parameters :
//
// Description : This function retrieves the scratch space pointer.
//
// Return Value : ScratchSpace* scratch
//
//-----------------------------------------------------------------------
SortScratchSpace* SortAlgo::getScratch() const
{
return scratch_;
}
Lng32 SortAlgo::getRunSize() const
{
return runSize_;
}
//-----------------------------------------------------------------------
// Name : keyCompare
//
// Parameters :
//
// Description : This function is used to compare two keys and is
// independent of the sort algorithm itself. Note the use
// of the overloaded operators for key comparision.
//
// Return Value :
// KEY1_IS_SMALLER
// KEY1_IS_GREATER
// KEYS_ARE_EQUAL
//-----------------------------------------------------------------------
short SortAlgo :: compare(char* key1, char* key2)
{
Int32 result;
//numCompares_ ++;
if (key1 && key2 ) {
result = str_cmp(key1,key2,(Int32)keySize_);
//return (memcmp(key1,key2,(int)keySize_));
return result;
}
else {
if (key1 == NULL && key2 == NULL) return KEYS_ARE_EQUAL;
if (key1 == NULL) return KEY1_IS_SMALLER;
/*if (key2 == NULL)*/ return KEY1_IS_GREATER;
};
return 0;
} | c++ | 11 | 0.511912 | 88 | 26.76378 | 127 | starcoderdata |
pub fn member(&self, element: &T) -> bool {
match self {
Tree::Empty => false,
// A more straightforward implementation of this match is to handle 3 cases:
//
// 1. If element is smaller than the root of the subtree, then recursively
// search its left subtree.
// 2. If element is larger than the root of the subtree, then recursively
// search its right subtree.
// 3. Otherwise the element is equal to the root of the subtree.
//
// That performs approximately 2 * d comparisons (d is the depth of
// the tree).
//
// The following alternative implementation, as suggested by Andersson's
// paper on binary search trees in 1991, only takes d + 1 comparisons.
Tree::NonEmpty(ref node) => {
if *element < node.element {
node.left.member(element)
} else {
node.right.memb(element, &node.element)
}
},
}
} | rust | 16 | 0.520252 | 88 | 41.769231 | 26 | inline |
package it.proconsole.utility.pairone.rest.controller;
import it.proconsole.utility.pairone.core.model.Team;
import it.proconsole.utility.pairone.core.repository.TeamRepository;
import it.proconsole.utility.pairone.rest.exception.TeamNotFoundException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/team")
public class TeamController {
private final TeamRepository teamRepository;
public TeamController(TeamRepository datastoreTeamRepository) {
this.teamRepository = datastoreTeamRepository;
}
@GetMapping("/{teamId}")
public Team getTeam(@PathVariable Long teamId) {
return teamRepository.findById(teamId).orElseThrow(() -> new TeamNotFoundException(teamId));
}
@PostMapping
public Team saveTeam(@RequestBody Team team) {
return teamRepository.save(team);
}
@ExceptionHandler(TeamNotFoundException.class)
public ResponseEntity notFound(TeamNotFoundException e) {
return ResponseEntity.notFound().build();
}
} | java | 11 | 0.816084 | 96 | 36.657895 | 38 | starcoderdata |
using System;
using Fable.Remoting.DotnetClient;
using CSharpClientDefs;
using TinyTest;
using Microsoft.FSharp.Core;
namespace CSharpClientTests
{
class Program
{
static int Main(string[] args)
{
var proxy = Proxy.CreateFromBuilder funcName) => {
return $"http://localhost:8080/api/{typeName}/{funcName}";
});
Test.Module("CSharp Client Tests");
Test.CaseAsync("IServer.echoLongInGenericUnion", async () =>
{
var input = Maybe
var output = await proxy.Call(server => server.echoLongInGenericUnion, input);
Test.Equal(input, output);
});
Test.CaseAsync("IServer.echoRecord works", async () =>
{
var input = new Record("one", 20, FSharpOption
var output = await proxy.Call(server => server.echoRecord, input);
Test.Equal(input, output);
});
Test.CaseAsync("IServer.multiArgFunc", async () =>
{
var output = await proxy.Call(server => server.multiArgFunc, "hello", 10, false);
Test.Equal(15, output);
});
Test.CaseAsync("IServer.pureAsync", async () =>
{
var output = await proxy.Call(server => server.pureAsync);
Test.Equal(42, output);
});
return Test.Report();
}
}
} | c# | 24 | 0.542804 | 97 | 31.897959 | 49 | starcoderdata |
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('shipping_line')
op.drop_table('shipping')
op.drop_table('receiving_line')
op.drop_table('receiving')
op.drop_table('inventory_transaction_line')
op.drop_table('inventory_transaction')
### end Alembic commands ### | python | 7 | 0.666667 | 63 | 36.444444 | 9 | inline |
package abot
import (
"fmt"
"strconv"
"strings"
)
func (a *app) findAuth(id int) (uid int, err error) {
err = a.db.Get(&uid, "SELECT uid FROM tgauth WHERE tgkey=?", id)
return
}
type shortuser struct {
ID string `db:"id"`
UID int `db:"uid"`
}
func (a *app) findByPhone(phone string) (users []shortuser, err error) {
if len(phone) < 11 {
return users, fmt.Errorf("phone to short")
}
ip, _ := strconv.Atoi(phone)
if ip == 0 {
return users, fmt.Errorf("phone not number")
}
phone = strings.TrimPrefix(phone, "+")
phone = strings.TrimPrefix(phone, "7")
err = a.db.Select(&users, fmt.Sprintf(`SELECT u.id, u.uid
FROM users u
JOIN users_pi pi ON pi.uid = u.uid
WHERE pi.phone like '%%%s%%' OR pi._tgphone like '%%%s%%'`, phone, phone))
return
} | go | 10 | 0.634367 | 75 | 21.114286 | 35 | starcoderdata |
namespace TransactionWebService2
{
public class DataPoint
{
public int DataPointId { get; set; }
public string Value { get; set; }
}
} | c# | 6 | 0.66 | 44 | 19.1 | 10 | starcoderdata |
import os
import random
class RandomTextGenerator(object):
def __init__(self, limit=20):
self.limit = limit # limit of word counts
self.brain = {"**": {"**": 0}}
self.file_flag = True
def train(self, filename):
titles = []
if self.read_file(filename, titles):
self.file_flag = True
return
for title in titles:
words = title.split() # a list of words in the title
curr_w = words[0]
# add start word
if curr_w in self.brain["**"].keys():
self.brain["**"][curr_w] += 1
else:
self.brain["**"][curr_w] = 1
self.brain["**"]["**"] += 1
for i in range(1, len(words)):
prev_w = words[i-1]
curr_w = words[i]
if prev_w not in self.brain.keys():
self.brain[prev_w] = {"**": 1, curr_w: 1}
else:
self.brain[prev_w]["**"] += 1
if curr_w not in self.brain[prev_w].keys():
self.brain[prev_w][curr_w] = 1
else:
self.brain[prev_w][curr_w] += 1
self.file_flag = False
return
def read_file(self, filename, titles_list):
if os.path.isfile(filename):
with open(filename, "r") as rFile:
for line in rFile:
titles_list.append(line.strip("\n"))
return False
else:
print("No such file.")
return True
def generate_title(self):
if self.file_flag:
print("Can't generate title due to file reading failure.")
return
new_title = ""
curr_w = ""
word_count = 1
# find starting word first
prob = random.randint(1, self.brain["**"]["**"])
counter = 0
for w in self.brain["**"].keys():
if w != "**":
counter += self.brain["**"][w]
if prob <= counter:
curr_w = w
new_title += w
break
while curr_w in self.brain.keys() and word_count < self.limit:
counter = 0
word_count += 1
prob = random.randint(1, self.brain[curr_w]["**"])
for w in self.brain[curr_w].keys():
if w != "**":
counter += self.brain[curr_w][w]
if prob <= counter:
curr_w = w
new_title += " " + w
break
return new_title
def generate_multiple(self, text_number):
if self.file_flag:
print("Can't generate title due to file reading failure.")
return
return [self.generate_title() for i in range(text_number)] | python | 20 | 0.442995 | 70 | 28.714286 | 98 | starcoderdata |
from numpy import *
from numpy.random import randint, randn
from time import time
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
# Returns mean of bootstrap samples
def stat(data):
return mean(data)
# Bootstrap algorithm
def bootstrap(data, statistic, R):
t = zeros(R); n = len(data); inds = arange(n); t0 = time()
# non-parametric bootstrap
for i in range(R):
t[i] = statistic(data[randint(0,n,n)])
# analysis
print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :")
print("original bias std. error")
print("%8g %8g %14g %15g" % (statistic(data), std(data),\
mean(t), \
std(t)))
return t
x = loadtxt("Energies.dat")
datapoints = len(x)
# bootstrap returns the data sample
t = bootstrap(x, stat, datapoints)
# the histogram of the bootstrapped data
n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
# add a 'best fit' line
y = mlab.normpdf( binsboot, mean(t), std(t))
lt = plt.plot(binsboot, y, 'r--', linewidth=1)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.axis([2.99, 3.01, 0, max(binsboot)])
plt.grid(True)
plt.show() | python | 12 | 0.346837 | 179 | 42.94 | 50 | starcoderdata |
namespace Gw2Sharp.WebApi.V2.Models
{
///
/// Represents the selected stats on equipment items.
///
public class EquipmentItemStats : IIdentifiable
{
///
/// The itemstat id.
/// Can be resolved against <see cref="IGw2WebApiV2Client.Itemstats"/>.
///
public int Id { get; set; }
///
/// The item attributes.
///
public ItemAttributes Attributes { get; set; } = new ItemAttributes();
}
} | c# | 8 | 0.568841 | 79 | 28.052632 | 19 | starcoderdata |
using SolastaModApi.Infrastructure;
using UnityEngine;
using UnityEngine.AddressableAssets;
using static RuleDefinitions;
namespace SolastaModApi.Extensions
{
///
/// This helper extensions class was automatically generated.
/// If you find a problem please report at https://github.com/SolastaMods/SolastaModApi/issues.
///
[TargetType(typeof(EffectParticleParameters))]
public static class EffectParticleParametersExtensions
{
public static T SetActiveEffectCellEndParticleReference T entity, AssetReference value)
where T : EffectParticleParameters
{
entity.SetField("activeEffectCellEndParticleReference", value);
return entity;
}
public static T SetActiveEffectCellParticleReference T entity, AssetReference value)
where T : EffectParticleParameters
{
entity.SetField("activeEffectCellParticleReference", value);
return entity;
}
public static T SetActiveEffectCellStartParticleReference T entity, AssetReference value)
where T : EffectParticleParameters
{
entity.SetField("activeEffectCellStartParticleReference", value);
return entity;
}
public static T SetActiveEffectSurfaceEndParticleReference T entity, AssetReference value)
where T : EffectParticleParameters
{
entity.SetField("activeEffectSurfaceEndParticleReference", value);
return entity;
}
public static T SetActiveEffectSurfaceParticleReference T entity, AssetReference value)
where T : EffectParticleParameters
{
entity.SetField("activeEffectSurfaceParticleReference", value);
return entity;
}
public static T SetActiveEffectSurfaceStartParticleReference T entity, AssetReference value)
where T : EffectParticleParameters
{
entity.SetField("activeEffectSurfaceStartParticleReference", value);
return entity;
}
public static T SetApplyEmissionColorOnWeapons T entity, bool value)
where T : EffectParticleParameters
{
entity.SetField("applyEmissionColorOnWeapons", value);
return entity;
}
public static T SetCasterParticleReference T entity, AssetReference value)
where T : EffectParticleParameters
{
entity.SetField("casterParticleReference", value);
return entity;
}
public static T SetCasterQuickSpellParticleReference T entity, AssetReference value)
where T : EffectParticleParameters
{
entity.SetField("casterQuickSpellParticleReference", value);
return entity;
}
public static T SetCasterSelfParticleReference T entity, AssetReference value)
where T : EffectParticleParameters
{
entity.SetField("casterSelfParticleReference", value);
return entity;
}
public static T SetConditionEndParticleReference T entity, AssetReference value)
where T : EffectParticleParameters
{
entity.SetField("conditionEndParticleReference", value);
return entity;
}
public static T SetConditionParticleReference T entity, AssetReference value)
where T : EffectParticleParameters
{
entity.SetField("conditionParticleReference", value);
return entity;
}
public static T SetConditionStartParticleReference T entity, AssetReference value)
where T : EffectParticleParameters
{
entity.SetField("conditionStartParticleReference", value);
return entity;
}
public static T SetEffectParticleReference T entity, AssetReference value)
where T : EffectParticleParameters
{
entity.SetField("effectParticleReference", value);
return entity;
}
public static T SetEmissionColor T entity, Color value)
where T : EffectParticleParameters
{
entity.SetField("emissionColor", value);
return entity;
}
public static T SetEmissionColorFadeInDuration T entity, float value)
where T : EffectParticleParameters
{
entity.SetField("emissionColorFadeInDuration", value);
return entity;
}
public static T SetEmissionColorFadeOutDuration T entity, float value)
where T : EffectParticleParameters
{
entity.SetField("emissionColorFadeOutDuration", value);
return entity;
}
public static T SetEmissiveBorderCellEndParticleReference T entity, AssetReference value)
where T : EffectParticleParameters
{
entity.SetField("emissiveBorderCellEndParticleReference", value);
return entity;
}
public static T SetEmissiveBorderCellParticleReference T entity, AssetReference value)
where T : EffectParticleParameters
{
entity.SetField("emissiveBorderCellParticleReference", value);
return entity;
}
public static T SetEmissiveBorderCellStartParticleReference T entity, AssetReference value)
where T : EffectParticleParameters
{
entity.SetField("emissiveBorderCellStartParticleReference", value);
return entity;
}
public static T SetEmissiveBorderSurfaceEndParticleReference T entity, AssetReference value)
where T : EffectParticleParameters
{
entity.SetField("emissiveBorderSurfaceEndParticleReference", value);
return entity;
}
public static T SetEmissiveBorderSurfaceParticleReference T entity, AssetReference value)
where T : EffectParticleParameters
{
entity.SetField("emissiveBorderSurfaceParticleReference", value);
return entity;
}
public static T SetEmissiveBorderSurfaceStartParticleReference T entity, AssetReference value)
where T : EffectParticleParameters
{
entity.SetField("emissiveBorderSurfaceStartParticleReference", value);
return entity;
}
public static T SetImpactParticleReference T entity, AssetReference value)
where T : EffectParticleParameters
{
entity.SetField("impactParticleReference", value);
return entity;
}
public static T SetTargetParticleReference T entity, AssetReference value)
where T : EffectParticleParameters
{
entity.SetField("targetParticleReference", value);
return entity;
}
public static T SetZoneParticleReference T entity, AssetReference value)
where T : EffectParticleParameters
{
entity.SetField("zoneParticleReference", value);
return entity;
}
}
} | c# | 12 | 0.650815 | 110 | 36.494949 | 198 | starcoderdata |
package org.hitlabnz.sensor_fusion_demo.permission;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.util.ArrayList;
import java.util.List;
/**
* 封装权限申请
*/
public class PermissionRequest extends Activity {
private static final String TAG = "PermissionRequest";
private static final int REQUEST_PERMISSION_CODE = 1; //默认请求权限的requestCode为1
private PermissionListener mListener;
/**
* 请求申请权限
* 默认请求权限的requestCode为1
* @param permissions 要申请的权限数组
* @param permissionListener 权限申请结果监听者
*/
public void requestRuntimePermission(Context context, String[] permissions, PermissionListener permissionListener){
mListener = permissionListener;
//存放permissions中当前未被授予的权限
List permissionList = new ArrayList<>();
//遍历权限数组,检测所需权限是否已被授予,若该权限尚未授予,添加到permissionList中
for (String permission : permissions) {
if(ContextCompat.checkSelfPermission(context,permission) != PackageManager.PERMISSION_GRANTED){
if(!permissionList.contains(permission)){
permissionList.add(permission);
}
}
}
if(!permissionList.isEmpty()){
//有权限尚未授予,去授予权限
ActivityCompat.requestPermissions((Activity) context,permissionList.toArray(new String[permissionList.size()]),REQUEST_PERMISSION_CODE);
}else{
//权限都被授予了
if(mListener != null){
mListener.onGranted(); //权限都被授予了回调
Log.d(TAG,"权限都授予了");
}
}
}
/**
* 申请权限结果返回
* @param requestCode 请求码
* @param permissions 所有申请的权限集合
* @param grantResults 权限申请的结果
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode){
case REQUEST_PERMISSION_CODE:
if(grantResults.length > 0){ //有权限申请
//存储被用户拒绝的权限
List deniedPermissionList = new ArrayList<>();
//有权限被拒绝,分类出被拒绝的权限
for (int i = 0; i < grantResults.length; i++) {
String permission = permissions[i];
int grantResult = grantResults[i];
if(grantResult != PackageManager.PERMISSION_GRANTED){
if(!deniedPermissionList.contains(permission)){
deniedPermissionList.add(permission);
}
}
}
if(deniedPermissionList.isEmpty()){
//没有被拒绝的权限
if(mListener != null){
mListener.onGranted();
Log.d(TAG,"权限都授予了");
}
}else{
//有被拒绝的权限
if(mListener != null){
mListener.onDenied(deniedPermissionList);
Log.e(TAG,"有权限被拒绝了");
}
}
}
break;
}
}
} | java | 4 | 0.563074 | 148 | 35.272727 | 99 | starcoderdata |
/*
* This file is part of the Avalon programming language
*
* Copyright (c) 2018
*
* 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.
*/
#ifndef AVALON_AST_PROG_H_
#define AVALON_AST_PROG_H_
#include
#include
/* Symtable */
#include "representer/symtable/scope.hpp"
#include "representer/symtable/fqn.hpp"
/* AST */
#include "representer/ast/decl/decl.hpp"
#include "representer/ast/program.hpp"
namespace avalon {
class program {
public:
/**
* the default contructor expects the scope bound to the program
*/
program();
/**
* set_fqn
* sets the fqn within which this program lives
*/
void set_fqn(fqn& l_fqn);
/**
* get_fqn
* returns the fqn within which this program lives
*/
fqn& get_fqn();
/**
* set_scope
* specify the scope bound to this program
*/
void set_scope(std::shared_ptr l_scope);
/**
* get_scope
* return the scope bound to this program
*/
std::shared_ptr get_scope();
/**
* add_declaration
* a program is made of different types of declarations:
* - import declarations
* - namespace declarations
*
* a program sits at the top of the AST and it holds a series of those declarations.
*/
void add_declaration(std::shared_ptr declaration);
/**
* get_declarations
* for futher processing, this function is called to get all the declarations that
* make up a program.
*/
std::vector >& get_declarations();
/**
* is_builtin
* sets and returns a boolean indicating whether this program contains builtin declarations
*/
void is_builtin(bool is_builtin_);
bool is_builtin();
private:
/*
* the fqn to this program
*/
fqn m_fqn;
/*
* scope introduced by the program, i.e. global scope
*/
std::shared_ptr m_scope;
/*
* a vector of declarations representing declarations as they were found
*/
std::vector > m_declarations;
/*
* a boolean flag indicating whether this program contains builtin declarations so we can import declarations from it directly
*/
bool m_is_builtin;
};
}
#endif | c++ | 15 | 0.621756 | 134 | 29.183333 | 120 | starcoderdata |
public static long getDateFromDslashMslashY(String date) {
int index = date.indexOf('/');
String days = date.substring(0, index);
int day = Integer.parseInt(days);
int mindex = date.indexOf('/', index + 1);
String month = date.substring(index + 1, mindex);
int mon = Integer.parseInt(month);
String year = date.substring(mindex + 1);
int iyear = Integer.parseInt(year);
if (iyear < 2000) {
iyear = iyear + 2000;
}
Calendar cal = Calendar.getInstance();
//reset the calendar
cal.set(Calendar.HOUR, 6);
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.DAY_OF_MONTH, day);
cal.set(Calendar.MONTH, mon - 1);
cal.set(Calendar.YEAR, iyear);
return cal.getTime().getTime();
} | java | 8 | 0.591837 | 58 | 36.434783 | 23 | inline |
/*******************************************************************************
* Copyright (c) 2000, 2012 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.debug.jdi.tests;
import java.util.Iterator;
import java.util.List;
import com.sun.jdi.ClassLoaderReference;
import com.sun.jdi.ReferenceType;
/**
* Tests for JDI com.sun.jdi.ClassLoaderReference.
*/
public class ClassLoaderReferenceTest extends AbstractJDITest {
private ClassLoaderReference fClassLoader;
/**
* Creates a new test.
*/
public ClassLoaderReferenceTest() {
super();
}
/**
* Init the fields that are used by this test only.
*/
@Override
public void localSetUp() {
// Get the class loader of org.eclipse.debug.jdi.tests.program.MainClass
fClassLoader = getClassLoaderReference();
}
/**
* Run all tests and output to standard output.
* @param args
*/
public static void main(java.lang.String[] args) {
new ClassLoaderReferenceTest().runSuite(args);
}
/**
* Gets the name of the test case.
* @see junit.framework.TestCase#getName()
*/
@Override
public String getName() {
return "com.sun.jdi.ClassLoaderReference";
}
/**
* Test JDI definedClasses().
*/
public void testJDIDefinedClasses() {
Iterator defined = fClassLoader.definedClasses().iterator();
int i = 0;
while (defined.hasNext()) assertTrue(Integer.toString(i++), defined.next() instanceof ReferenceType);
}
/**
* Test JDI visibleClasses().
*/
public void testJDIVisibleClasses() {
List visible = fClassLoader.visibleClasses();
Iterator defined = fClassLoader.definedClasses().iterator();
while (defined.hasNext()) {
ReferenceType next = (ReferenceType) defined.next();
assertTrue(next.name(), visible.contains(next));
}
}
} | java | 12 | 0.627984 | 121 | 29.759494 | 79 | starcoderdata |
#include "initi2c.h"
#include
#include
#include "driver/i2c.h"
void i2c_master_init()
{
int i2c_master_port = I2C_EXAMPLE_MASTER_NUM;
i2c_config_t conf;
conf.mode = I2C_MODE_MASTER;
conf.sda_io_num = I2C_EXAMPLE_MASTER_SDA_IO;
conf.sda_pullup_en = GPIO_PULLUP_ENABLE;
conf.scl_io_num = I2C_EXAMPLE_MASTER_SCL_IO;
conf.scl_pullup_en = GPIO_PULLUP_ENABLE;
conf.master.clk_speed = I2C_EXAMPLE_MASTER_FREQ_HZ;
i2c_param_config(i2c_master_port, &conf);
i2c_driver_install(i2c_master_port, conf.mode,
I2C_EXAMPLE_MASTER_RX_BUF_DISABLE,
I2C_EXAMPLE_MASTER_TX_BUF_DISABLE, 0);
}
void scani2c(){
int i;
bool ads1115=0;
esp_err_t espRc;
printf(" 0 1 2 3 4 5 6 7 8 9 a b c d e f\n");
printf("00: ");
for (i=3; i< 0x78; i++) {
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
i2c_master_start(cmd);
i2c_master_write_byte(cmd, (i << 1) | I2C_MASTER_WRITE, 1 /* expect ack */);
i2c_master_stop(cmd);
espRc = i2c_master_cmd_begin(I2C_NUM_0, cmd, 10/portTICK_PERIOD_MS);
if (i%16 == 0) {
printf("\n%.2x:", i);
}
if (espRc == 0) {
printf(" %.2x", i);
} else {
printf(" --");
}
if(espRc==0&&i==0x48){
ads1115=1;
}
//ESP_LOGD(tag, "i=%d, rc=%d (0x%x)", i, espRc, espRc);
i2c_cmd_link_delete(cmd);
}
printf("\n");
if(ads1115==1){
printf("ads1115 detected\n");
}
} | c | 12 | 0.584083 | 78 | 26.264151 | 53 | starcoderdata |
using System;
using System.Diagnostics;
using System.IO;
using Lucene.Net.Util;
namespace Lucene.Net.Analysis.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
///
/// Acts like a forever growing <see cref="T:char[]"/> as you read
/// characters into it from the provided reader, but
/// internally it uses a circular buffer to only hold the
/// characters that haven't been freed yet. This is like a
/// PushbackReader, except you don't have to specify
/// up-front the max size of the buffer, but you do have to
/// periodically call <see cref="FreeBefore"/>.
///
public sealed class RollingCharBuffer
{
private TextReader reader;
private char[] buffer = new char[512];
// Next array index to write to in buffer:
private int nextWrite;
// Next absolute position to read from reader:
private int nextPos;
// How many valid chars (wrapped) are in the buffer:
private int count;
// True if we hit EOF
private bool end;
///
/// Clear array and switch to new reader.
public void Reset(TextReader reader)
{
this.reader = reader;
nextPos = 0;
nextWrite = 0;
count = 0;
end = false;
}
///
/// Absolute position read. NOTE: pos must not jump
/// ahead by more than 1! Ie, it's OK to read arbitarily
/// far back (just not prior to the last <see cref="FreeBefore(int)"/>,
/// but NOT ok to read arbitrarily far
/// ahead. Returns -1 if you hit EOF.
///
public int Get(int pos)
{
//System.out.println(" Get pos=" + pos + " nextPos=" + nextPos + " count=" + count);
if (pos == nextPos)
{
if (end)
{
return -1;
}
if (count == buffer.Length)
{
// Grow
var newBuffer = new char[ArrayUtil.Oversize(1 + count, RamUsageEstimator.NUM_BYTES_CHAR)];
//System.out.println(Thread.currentThread().getName() + ": cb grow " + newBuffer.length);
Array.Copy(buffer, nextWrite, newBuffer, 0, buffer.Length - nextWrite);
Array.Copy(buffer, 0, newBuffer, buffer.Length - nextWrite, nextWrite);
nextWrite = buffer.Length;
buffer = newBuffer;
}
if (nextWrite == buffer.Length)
{
nextWrite = 0;
}
int toRead = buffer.Length - Math.Max(count, nextWrite);
int readCount = reader.Read(buffer, nextWrite, toRead);
if (readCount <= 0)
{
end = true;
return -1;
}
int ch = buffer[nextWrite];
nextWrite += readCount;
count += readCount;
nextPos += readCount;
return ch;
}
else
{
// Cannot read from future (except by 1):
Debug.Assert(pos < nextPos);
// Cannot read from already freed past:
Debug.Assert(nextPos - pos <= count, "nextPos=" + nextPos + " pos=" + pos + " count=" + count);
return buffer[GetIndex(pos)];
}
}
// For assert:
private bool InBounds(int pos)
{
return pos >= 0 && pos < nextPos && pos >= nextPos - count;
}
private int GetIndex(int pos)
{
int index = nextWrite - (nextPos - pos);
if (index < 0)
{
// Wrap:
index += buffer.Length;
Debug.Assert(index >= 0);
}
return index;
}
public char[] Get(int posStart, int length)
{
Debug.Assert(length > 0);
Debug.Assert(InBounds(posStart), "posStart=" + posStart + " length=" + length);
//System.out.println(" buffer.Get posStart=" + posStart + " len=" + length);
int startIndex = GetIndex(posStart);
int endIndex = GetIndex(posStart + length);
//System.out.println(" startIndex=" + startIndex + " endIndex=" + endIndex);
var result = new char[length];
if (endIndex >= startIndex && length < buffer.Length)
{
Array.Copy(buffer, startIndex, result, 0, endIndex - startIndex);
}
else
{
// Wrapped:
int part1 = buffer.Length - startIndex;
Array.Copy(buffer, startIndex, result, 0, part1);
Array.Copy(buffer, 0, result, buffer.Length - startIndex, length - part1);
}
return result;
}
///
/// Call this to notify us that no chars before this
/// absolute position are needed anymore.
///
public void FreeBefore(int pos)
{
Debug.Assert(pos >= 0);
Debug.Assert(pos <= nextPos);
int newCount = nextPos - pos;
Debug.Assert(newCount <= count, "newCount=" + newCount + " count=" + count);
Debug.Assert(newCount <= buffer.Length, "newCount=" + newCount + " buf.length=" + buffer.Length);
count = newCount;
}
}
} | c# | 22 | 0.524001 | 111 | 35.610169 | 177 | starcoderdata |
import FormSolution from '@lblod/ember-mu-dynamic-forms/models/form-solution' ;
import { belongsTo } from 'ember-data/relationships';
export default FormSolution.extend({
//Add the relation to the model of which the dynamic form will belong.
//e.g. company: belongsTo('company'),
}); | javascript | 3 | 0.768817 | 82 | 45.5 | 8 | starcoderdata |
/**
* @file AddressToLineTest.cpp
* @brief AddressToLine class tester.
* @author zer0
* @date 2017-06-06
*/
#include
#include
using namespace libtbag;
using namespace libtbag::debug;
using namespace libtbag::debug::st;
using namespace libtbag::debug::st::unix;
TEST(AddressToLineTest, Default)
{
ASSERT_TRUE(true);
} | c++ | 6 | 0.727483 | 50 | 19.619048 | 21 | starcoderdata |
using JT808.Protocol.Extensions;
using JT808.Protocol.MessageBody;
using JT808.Protocol.Interfaces;
using System;
using JT808.Protocol.MessagePack;
namespace JT808.Protocol.Formatters.MessageBodyFormatters
{
public class JT808_0x8300_Formatter : IJT808MessagePackFormatter
{
public JT808_0x8300 Deserialize(ref JT808MessagePackReader reader, IJT808Config config)
{
JT808_0x8300 jT808_0X8300 = new JT808_0x8300();
jT808_0X8300.TextFlag = reader.ReadByte();
jT808_0X8300.TextInfo = reader.ReadRemainStringContent();
return jT808_0X8300;
}
public void Serialize(ref JT808MessagePackWriter writer, JT808_0x8300 value, IJT808Config config)
{
writer.WriteByte(value.TextFlag);
writer.WriteString(value.TextInfo);
}
}
} | c# | 13 | 0.711579 | 105 | 35.538462 | 26 | starcoderdata |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models
from utils import device, args
from utils import make_directory
TRANSFER_MODEL_PATH = make_directory("../transfer_models/")
class LeNetEmbeddingNet(nn.Module):
def __init__(self, embedding_dim=32):
super(LeNetEmbeddingNet, self).__init__()
self.embedding_dim = embedding_dim
self.batchnorm1 = nn.BatchNorm2d(32)
self.batchnorm2 = nn.BatchNorm2d(64)
self.batchnorm3 = nn.BatchNorm2d(128)
self.batchnorm4 = nn.BatchNorm1d(256)
self.convnet = nn.Sequential(nn.Conv2d(3, 32, 5),
self.batchnorm1,
nn.ReLU(),
nn.MaxPool2d(2, stride=2),
nn.Conv2d(32, 64, 5),
self.batchnorm2,
nn.ReLU(),
nn.MaxPool2d(2, stride=2),
nn.Conv2d(64, 128, 2),
self.batchnorm3,
nn.ReLU(),
nn.MaxPool2d(2, stride=2)
)
self.fc = nn.Sequential(nn.Linear(512, 256),
self.batchnorm4,
nn.ReLU(),
nn.Linear(256, 64),
nn.ReLU(),
nn.Linear(64, self.embedding_dim)
)
for m in self.modules():
if isinstance(m, nn.Conv2d):
torch.nn.init.xavier_uniform_(m.weight)
def forward(self, x):
output = self.convnet(x)
output = output.view(output.size()[0], -1)
output = self.fc(output)
if args.normalize:
return F.normalize(output)
return output
def get_embedding(self, x):
return self.forward(x)
class ResNetEmbeddingNet(nn.Module):
def __init__(self, embedding_dim=2):
super(ResNetEmbeddingNet, self).__init__()
self.embedding_dim = embedding_dim
self.resnet18 = models.resnet18(pretrained=False)
self.resnet18.fc = nn.Linear(512, self.embedding_dim)
def forward(self, x):
output = self.resnet18(x)
if args.normalize:
return F.normalize(output)
return output
def get_embedding(self, x):
return self.forward(x)
def change_embedding_dim(self, emb_dim):
self.embedding_dim = emb_dim
self.backbone_net.embedding_dim = emb_dim
class TripletNet(nn.Module):
def __init__(self, backbone_net):
super(TripletNet, self).__init__()
self.backbone_net = backbone_net
self.embedding_dim = backbone_net.embedding_dim
def forward(self, anchor, pos, neg):
anchor = self.backbone_net(anchor)
pos = self.backbone_net(pos)
neg = self.backbone_net(neg)
return anchor, pos, neg
def get_embedding(self, x):
return self.backbone_net(x)
def change_embedding_dim(self, emb_dim):
self.embedding_dim = emb_dim
self.backbone_net.embedding_dim = emb_dim
def initialize_model(model_name, embedding_dim):
if model_name == "lenet":
backbone_net = LeNetEmbeddingNet(embedding_dim)
elif model_name == "resnet":
backbone_net = ResNetEmbeddingNet(embedding_dim)
else:
raise ValueError("Model not defined")
return TripletNet(backbone_net).to(device)
def freeze_conv_layers(model):
if args.model == "lenet":
model = freeze_lenet_conv_layers(model)
elif args.model == "resnet":
model = freeze_resnet_conv_layers(model)
else:
raise ValueError("Model not defined")
return model
def freeze_lenet_conv_layers(model):
for param in model.backbone_net.convnet.parameters():
param.requires_grad = False
return model
def freeze_resnet_conv_layers(model):
for name, param in model.backbone_net.named_parameters():
if "layer4" in name or "fc" in name:
pass
else:
param.requires_grad = False
return model
def freeze_layers(old_model, model):
if args.continuous_learning_method == "finetune":
model = freeze_conv_layers(model)
elif args.continuous_learning_method == "lfl":
model = freeze_conv_layers(model)
for param in old_model.parameters():
param.requires_grad = False
if args.freeze:
if args.continuous_learning_method != "naive":
model = freeze_conv_layers(model)
return old_model, model | python | 14 | 0.556669 | 65 | 31.815068 | 146 | starcoderdata |
// MultiplicationTable.js
// Bouya
// A program used to generate a mutilplication table
// Run: node MultiplicationTable.js
const rl = require ("readline").createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("Enter number = ", function(base){
rl.close();
for(var i=1; i<=12; i++) {
console.log(`${base} x ${i} = `, base * i)
}
}) | javascript | 8 | 0.652742 | 52 | 23 | 16 | starcoderdata |
var gutil = require('gulp-util');
var fs = require('fs');
/**
* Build up the given src file(s), to be passed to Gulp.
*
* @param {string|array} src
* @param {string} baseDir
* @param {string} search
*/
var buildGulpSrc = function(src, baseDir, search) {
if (src) {
return prefixDirToFiles(baseDir, src);
}
return [baseDir + '/' + search];
};
/**
* Prefix a directory path to an array of files.
*
* @param {string} dir
* @param {string|array} files
*/
var prefixDirToFiles = function(dir, files) {
if ( ! Array.isArray(files)) files = [files];
return files.map(function(file) {
file = file.replace(dir, '');
return [dir, file].join('/').replace('//', '/');
});
};
/**
* Log an action to the console for user feedback.
*
* @param {string} message
* @param {mixed} files
*/
var logTask = function(message, files) {
var isFileList = Array.isArray(files);
files = isFileList ? files : [files];
gutil.log(gutil.colors.white(message + ':', files));
if (isFileList) {
assertFilesExist(files);
}
};
/**
* Log a missing file event to the console.
*
* @param {string} file
*/
var logMissingFile = function(file) {
return gutil.log(gutil.colors.bgRed('File not found: ' + file));
};
/**
* Assert that all files in an array exist.
*
* @param {array} files
*/
var assertFilesExist = function(files) {
files.forEach(function(file) {
// We're not interested in working with
// paths that areregular expressions.
if(/\*/.test(file)) return;
fs.exists(file, function(found) {
if ( ! found) {
logMissingFile(file);
}
});
});
};
module.exports = {
buildGulpSrc: buildGulpSrc,
prefixDirToFiles: prefixDirToFiles,
logTask: logTask
}; | javascript | 17 | 0.596883 | 71 | 20.153846 | 91 | starcoderdata |
//--------------------------------------------------------------------------
/*! \file post_wu_vars_in_post_learn/model.cc
\brief model definition file that is part of the feature testing
suite of minimal models with known analytic outcomes that are used for continuous integration testing.
*/
//--------------------------------------------------------------------------
#include
#include "modelSpec.h"
//----------------------------------------------------------------------------
// PreNeuron
//----------------------------------------------------------------------------
class PreNeuron : public NeuronModels::Base
{
public:
DECLARE_MODEL(PreNeuron, 0, 0);
SET_THRESHOLD_CONDITION_CODE("true");
SET_NEEDS_AUTO_REFRACTORY(false);
};
IMPLEMENT_MODEL(PreNeuron);
//----------------------------------------------------------------------------
// PostNeuron
//----------------------------------------------------------------------------
class PostNeuron : public NeuronModels::Base
{
public:
DECLARE_MODEL(PostNeuron, 0, 0);
SET_THRESHOLD_CONDITION_CODE("$(t) >= (scalar)$(id) && fmodf($(t) - (scalar)$(id), 10.0f)< 1e-4");
SET_NEEDS_AUTO_REFRACTORY(false);
};
IMPLEMENT_MODEL(PostNeuron);
//----------------------------------------------------------------------------
// WeightUpdateModel
//----------------------------------------------------------------------------
class WeightUpdateModel : public WeightUpdateModels::Base
{
public:
DECLARE_WEIGHT_UPDATE_MODEL(WeightUpdateModel, 0, 1, 0, 1);
SET_VARS({{"w", "scalar"}});
SET_POST_VARS({{"s", "scalar"}});
SET_LEARN_POST_CODE("$(w)= $(s);\n");
SET_POST_SPIKE_CODE("$(s) = $(t);\n");
};
IMPLEMENT_MODEL(WeightUpdateModel);
void modelDefinition(ModelSpec &model)
{
model.setDT(1.0);
model.setName("post_wu_vars_in_post_learn");
model.addNeuronPopulation 10, {}, {});
model.addNeuronPopulation 10, {}, {});
auto *syn = model.addSynapsePopulation<WeightUpdateModel, PostsynapticModels::DeltaCurr>(
"syn", SynapseMatrixType::SPARSE_INDIVIDUALG, NO_DELAY, "pre", "post",
{}, WeightUpdateModel::VarValues(0.0), {}, WeightUpdateModel::PostVarValues(std::numeric_limits
{}, {},
initConnectivity
syn->setBackPropDelaySteps(20);
model.setPrecision(GENN_FLOAT);
} | c++ | 15 | 0.505092 | 122 | 30.883117 | 77 | starcoderdata |
#pragma once
#include
#include
#include
#include
#include "texture_provider.hpp"
#include "scene.hpp"
#include "../thread_pool.hpp"
namespace myrt
{
class pathtracer
{
public:
constexpr static unsigned buffer_binding_bvh_nodes = 0;
constexpr static unsigned buffer_binding_bvh_indices = 1;
constexpr static unsigned buffer_binding_indices = 2;
constexpr static unsigned buffer_binding_vertices = 3;
constexpr static unsigned buffer_binding_normals = 4;
constexpr static unsigned buffer_binding_drawables = 5;
constexpr static unsigned buffer_binding_sdf_data = 9;
constexpr static unsigned buffer_binding_sdf_drawable = 10;
constexpr static unsigned buffer_binding_global_bvh_nodes = 6;
constexpr static unsigned buffer_binding_global_bvh_indices = 7;
constexpr static unsigned buffer_binding_materials = 8;
struct cubemap_texture {
std::uint32_t cubemap;
std::uint32_t sampler;
};
constexpr static auto max_uniform_distribution_value = 0x0ffffffu;
constexpr static auto random_number_count = 1 << 10;
~pathtracer();
void sample_to_framebuffer(scene& scene, std::uint32_t target_framebuffer, GLenum attachment);
void sample_to_display(scene& scene, int width, int height);
void set_projection(rnu::mat4 matrix);
void set_view(rnu::mat4 matrix);
void set_cubemap(std::optional cubemap);
void set_lens_radius(float radius);
void set_bokeh_texture(std::optional bokeh);
void set_focus(float focus);
void set_max_bounces(int bounces);
void set_enable_russian_roulette(bool enable);
void set_sdf_marching_steps(int steps);
void set_sdf_marching_epsilon(float eps);
void reload_shaders(scene& scene);
bool is_compiling() const;
void invalidate_texture();
void invalidate_counter();
[[nodiscard]] int sample_count() const noexcept;
private:
void bind_scene(scene& scene) const;
void sample_internal(scene& scene, std::uint32_t target_framebuffer, int width, int height);
void initialize(scene& scene);
void deinitialize();
void repopulate_random_texture();
bool m_is_initialized = false;
std::optional m_program = std::nullopt;
std::atomic_uint m_compiling_program = 0;
std::uint32_t m_framebuffer = 0;
std::uint32_t m_vertex_array = 0;
std::uint32_t m_cubemap = 0;
std::uint32_t m_cubemap_sampler = 0;
std::uint32_t m_bokeh = 0;
texture_provider_t m_texture_provider;
bool m_enable_russian_roulette = false;
int m_sample_counter = 0;
float m_lens_radius = 100.f;
float m_last_width = 0;
float m_last_height = 0;
float m_focus = 5.0f;
int m_max_bounces = 8;
int m_sdf_marching_steps = 400;
float m_sdf_marching_epsilon = 0.75e-6f;
scene const* m_last_scene = nullptr;
std::shared_ptr m_last_sample_texture;
std::shared_ptr m_current_sample_texture;
std::shared_ptr m_random_texture;
std::atomic_bool m_is_compiling = false;
rnu::mat4 m_view_matrix;
rnu::mat4 m_projection_matrix;
std::mt19937 m_random_engine;
};
} | c++ | 14 | 0.692236 | 98 | 31.867347 | 98 | starcoderdata |
WirelessTypes::SamplingMode SyncNodeConfig::samplingMode()
{
try
{
//try to read the value from the pending config
return m_networkInfo->getPendingConfig().samplingMode();
}
catch(Error_NoData&)
{
//read the value from eeprom
return m_eepromHelper.read_samplingMode();
}
} | c++ | 10 | 0.558511 | 68 | 28 | 13 | inline |
package de.lordz.java.tools.tdm;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import de.lordz.java.tools.tdm.common.DateTimeHelper;
import de.lordz.java.tools.tdm.common.LocalizationProvider;
import de.lordz.java.tools.tdm.entities.Customer;
import de.lordz.java.tools.tdm.entities.IEntityId;
import de.lordz.java.tools.tdm.entities.Trip;
import de.lordz.java.tools.tdm.entities.TripType;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import com.github.lgooddatepicker.components.DatePicker;
/**
* Panel to hold and handle trip data.
*
* @author lordzomat
*
*/
public class TripDataPanel extends GridBagDataPanelBase {
private static final long serialVersionUID = -6656227064606325111L;
private JComboBox comboBoxCustomer;
private JComboBox comboBoxTripType;
private DatePicker datePicker;
private JTextArea textAreaDescription;
private ArrayList currentCustomerEntities;
private ArrayList currentTripTypeEntities;
private Trip currentTrip;
private boolean editMode;
private boolean listenersInitialized;
/**
* Initializes a new instance of the class.
*/
public TripDataPanel() {
super(new int[] {100, 250}, new int[] {20, 20, 20, 160}, new double[]{0.0, 1.0}, new double[]{0.0, 1.0, 1.0, 1.0});
this.comboBoxCustomer = new JComboBox
var prototypeCustomer = new Customer();
prototypeCustomer.setName("##########");
// used to get a fixed size of the combo box so it does not expand with it's content.
this.comboBoxCustomer.setPrototypeDisplayValue(prototypeCustomer);
AddLabel(0, 0, LocalizationProvider.getString("tripbasicinfo.label.customer"));
AddInput(1, 0, this.comboBoxCustomer, GridBagConstraints.HORIZONTAL);
this.comboBoxTripType = new JComboBox
var prototypeTripType = new TripType();
prototypeTripType.setName("##########");
this.comboBoxTripType.setPrototypeDisplayValue(prototypeTripType);
AddLabel(0, 1, LocalizationProvider.getString("tripbasicinfo.label.triptype"));
AddInput(1, 1, this.comboBoxTripType, GridBagConstraints.HORIZONTAL);
this.datePicker = DateTimeHelper.createDatePicker();
AddLabel(0, 2, LocalizationProvider.getString("tripbasicinfo.label.date"));
AddInput(1, 2, this.datePicker, GridBagConstraints.NONE);
var scrollPane = new JScrollPane();
scrollPane.setPreferredSize(new Dimension(250, 160));
this.textAreaDescription = new JTextArea();
this.textAreaDescription.setColumns(10);
scrollPane.setViewportView(this.textAreaDescription);
AddLabel(0, 3, LocalizationProvider.getString("tripbasicinfo.label.description"));
AddInput(1, 3, scrollPane, GridBagConstraints.BOTH);
}
/**
* Reloads referenced data e.g. customers and trip types.
*
* @param customerEntities The list containing all customers.
* @param tripTypes The list containing all trip types.
*/
public void reloadReferenceData(Collection customerEntities, Collection tripTypes) {
if (customerEntities != null) {
this.comboBoxCustomer.removeAllItems();
this.currentCustomerEntities = new ArrayList
if (customerEntities != null) {
for (Customer customerEntity : customerEntities) {
this.comboBoxCustomer.addItem(customerEntity);
}
}
}
if (tripTypes != null) {
this.comboBoxTripType.removeAllItems();
this.currentTripTypeEntities = new ArrayList
if (tripTypes != null) {
for (TripType tripType : tripTypes) {
this.comboBoxTripType.addItem(tripType);
}
}
}
}
/**
* Fills in the trip entity data.
*
* @param customer The entity from which the data is taken.
*/
public void fillFromEnity(Trip entity) {
if (entity != null) {
int customerId = entity.getCustomerId();
setSelectedComboBoxItem(this.comboBoxCustomer, this.currentCustomerEntities, customerId, e -> e.getId());
int tripTypeId = entity.getTripTypeId();
setSelectedComboBoxItem(this.comboBoxTripType, this.currentTripTypeEntities, tripTypeId, e -> e.getId());
this.textAreaDescription.setText(entity.getDescription());
var localDate = entity.getLocalDate();
if (localDate != null) {
this.datePicker.setDate(localDate);
} else {
this.datePicker.clear();
}
} else {
entity = new Trip();
}
if (this.editMode) {
this.currentTrip = entity;
setSelectedCustomer();
setSelectedTripType();
if (!this.listenersInitialized) {
ComboBoxAutoCompletion.enable(this.comboBoxCustomer);
this.textAreaDescription.getDocument().addDocumentListener(
new EntityTextChangeDocumentListener((value) -> this.currentTrip.setDescription(value)));
this.comboBoxCustomer.addActionListener(e -> setSelectedCustomer());
this.comboBoxTripType.addActionListener(e -> setSelectedTripType());
this.datePicker.addDateChangeListener(e -> setTimeOfTrip());
this.listenersInitialized = true;
}
this.comboBoxCustomer.requestFocusInWindow();
}
}
/**
* Specifies if the text of text components is editable or not.
*
* @param editable If true the text fields can be edited.
*/
public void setEditable(boolean editable) {
this.editMode = editable;
this.comboBoxCustomer.setEnabled(editable);
this.comboBoxTripType.setEnabled(editable);
this.datePicker.setEnabled(editable);
this.textAreaDescription.setEditable(editable);
var border = BorderFactory.createLineBorder(Color.LIGHT_GRAY);
this.textAreaDescription.setBorder(BorderFactory.createCompoundBorder(border, BorderFactory.createEmptyBorder(2, 2, 2, 2)));
}
private void setSelectedCustomer() {
setSelectedComboBoxItem(this.comboBoxCustomer, Customer.class, id -> this.currentTrip.setCustomerId(id));
}
private void setSelectedTripType() {
setSelectedComboBoxItem(this.comboBoxTripType, TripType.class, id -> this.currentTrip.setTripTypeId(id));
}
private <T extends IEntityId> void setSelectedComboBoxItem(JComboBox comboBox, Class<? extends T> type, Consumer setId) {
if (comboBox != null && setId != null) {
var selectedItem = comboBox.getSelectedItem();
if (selectedItem != null && type.isInstance(selectedItem)) {
var entity = type.cast(selectedItem);
if (entity != null) {
setId.accept(entity.getId());
}
}
}
}
private void setTimeOfTrip() {
if (this.datePicker.isTextFieldValid()) {
this.currentTrip.setTimeOfTrip(DateTimeHelper.toSortableDateTime(this.datePicker.getDate()));
}
}
private void setSelectedComboBoxItem(JComboBox comboBox, List list, int selectedId, Function<T, Integer> getEntityId) {
if (list != null && selectedId > 0) {
boolean customerFound = false;
for (int i = 0; i < list.size() && !customerFound; i++) {
var item = list.get(i);
if (item != null && getEntityId.apply(item) == selectedId) {
comboBox.setSelectedIndex(i);
customerFound = true;
}
}
} else if (selectedId == 0) {
comboBox.setSelectedIndex(-1);
}
}
} | java | 17 | 0.644628 | 137 | 40.331683 | 202 | starcoderdata |
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import javax.swing.event.MouseInputListener;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
DefaultListModel model = new DefaultListModel<>();
model.addElement("11\n1");
model.addElement("222222222222222\n222222222222222");
model.addElement("3333333333333333333\n33333333333333333333\n33333333333333333");
model.addElement("444");
add(new JScrollPane(new JList {
private transient MouseInputListener handler;
@Override public void updateUI() {
removeMouseListener(handler);
removeMouseMotionListener(handler);
super.updateUI();
setFixedCellHeight(-1);
handler = new CellButtonsMouseListener<>(this);
addMouseListener(handler);
addMouseMotionListener(handler);
setCellRenderer(new ButtonsRenderer<>(model));
}
}));
setPreferredSize(new Dimension(320, 240));
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class CellButtonsMouseListener extends MouseInputAdapter {
private int prevIndex = -1;
private JButton prevButton;
private final JList list;
protected CellButtonsMouseListener(JList list) {
super();
this.list = list;
}
@Override public void mouseMoved(MouseEvent e) {
// JList list = (JList e.getComponent();
Point pt = e.getPoint();
int index = list.locationToIndex(pt);
if (!list.getCellBounds(index, index).contains(pt)) {
if (prevIndex >= 0) {
rectRepaint(list, list.getCellBounds(prevIndex, prevIndex));
}
prevButton = null;
return;
}
ListCellRenderer<? super E> lcr = list.getCellRenderer();
if (index >= 0 && lcr instanceof ButtonsRenderer) {
ButtonsRenderer renderer = (ButtonsRenderer lcr;
JButton button = getButton(list, pt, index);
renderer.button = button;
if (Objects.nonNull(button)) {
repaintCell(renderer, button, index);
} else {
repaintPrevButton(renderer, index);
}
prevButton = button;
}
prevIndex = index;
}
private void repaintCell(ButtonsRenderer renderer, JButton button, int index) {
button.getModel().setRollover(true);
renderer.rolloverIndex = index;
if (!Objects.equals(button, prevButton)) {
rectRepaint(list, list.getCellBounds(prevIndex, index));
}
}
private void repaintPrevButton(ButtonsRenderer renderer, int index) {
renderer.rolloverIndex = -1;
if (prevIndex == index) {
if (Objects.nonNull(prevButton)) {
rectRepaint(list, list.getCellBounds(prevIndex, prevIndex));
}
} else {
rectRepaint(list, list.getCellBounds(index, index));
}
prevIndex = -1;
}
@Override public void mousePressed(MouseEvent e) {
// JList list = (JList e.getComponent();
Point pt = e.getPoint();
int index = list.locationToIndex(pt);
if (index >= 0) {
JButton button = getButton(list, pt, index);
ListCellRenderer<? super E> renderer = list.getCellRenderer();
if (Objects.nonNull(button) && renderer instanceof ButtonsRenderer) {
ButtonsRenderer r = (ButtonsRenderer renderer;
r.pressedIndex = index;
r.button = button;
rectRepaint(list, list.getCellBounds(index, index));
}
}
}
@Override public void mouseReleased(MouseEvent e) {
// JList list = (JList e.getComponent();
Point pt = e.getPoint();
int index = list.locationToIndex(pt);
if (index >= 0) {
JButton button = getButton(list, pt, index);
ListCellRenderer<? super E> renderer = list.getCellRenderer();
if (Objects.nonNull(button) && renderer instanceof ButtonsRenderer) {
ButtonsRenderer r = (ButtonsRenderer renderer;
r.pressedIndex = -1;
r.button = null;
button.doClick();
rectRepaint(list, list.getCellBounds(index, index));
}
}
}
private static void rectRepaint(JComponent c, Rectangle rect) {
Optional.ofNullable(rect).ifPresent(c::repaint);
}
private static JButton getButton(JList list, Point pt, int index) {
E proto = list.getPrototypeCellValue();
ListCellRenderer<? super E> cr = list.getCellRenderer();
Component c = cr.getListCellRendererComponent(list, proto, index, false, false);
Rectangle r = list.getCellBounds(index, index);
c.setBounds(r);
// c.doLayout(); // may be needed for other layout managers (eg. FlowLayout) // *1
pt.translate(-r.x, -r.y);
// Component b = SwingUtilities.getDeepestComponentAt(c, pt.x, pt.y);
// if (b instanceof JButton) {
// return (JButton) b;
// } else {
// return null;
// }
return Optional.ofNullable(SwingUtilities.getDeepestComponentAt(c, pt.x, pt.y))
.filter(JButton.class::isInstance).map(JButton.class::cast).orElse(null);
}
}
class ButtonsRenderer extends JPanel implements ListCellRenderer {
private static final Color EVEN_COLOR = new Color(0xE6_FF_E6);
private final JTextArea textArea = new JTextArea();
private final JButton deleteButton = new JButton("delete");
private final JButton copyButton = new JButton("copy");
private final List buttons = Arrays.asList(deleteButton, copyButton);
private int targetIndex;
protected int pressedIndex = -1;
protected int rolloverIndex = -1;
protected JButton button;
protected ButtonsRenderer(DefaultListModel model) {
super(new BorderLayout()); // *1
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 0));
setOpaque(true);
textArea.setLineWrap(true);
textArea.setOpaque(false);
add(textArea);
deleteButton.addActionListener(e -> {
boolean oneOrMore = model.getSize() > 1;
if (oneOrMore) {
model.remove(targetIndex);
}
});
copyButton.addActionListener(e -> model.add(targetIndex, model.get(targetIndex)));
Box box = Box.createHorizontalBox();
buttons.forEach(b -> {
b.setFocusable(false);
b.setRolloverEnabled(false);
box.add(b);
box.add(Box.createHorizontalStrut(5));
});
add(box, BorderLayout.EAST);
}
@Override public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
d.width = 0; // VerticalScrollBar as needed
return d;
}
@Override public Component getListCellRendererComponent(JList<? extends E> list, E value, int index, boolean isSelected, boolean cellHasFocus) {
textArea.setText(Objects.toString(value, ""));
this.targetIndex = index;
if (isSelected) {
setBackground(list.getSelectionBackground());
textArea.setForeground(list.getSelectionForeground());
} else {
setBackground(index % 2 == 0 ? EVEN_COLOR : list.getBackground());
textArea.setForeground(list.getForeground());
}
buttons.forEach(ButtonsRenderer::resetButtonStatus);
if (Objects.nonNull(button)) {
if (index == pressedIndex) {
button.getModel().setSelected(true);
button.getModel().setArmed(true);
button.getModel().setPressed(true);
} else if (index == rolloverIndex) {
button.getModel().setRollover(true);
}
}
return this;
}
private static void resetButtonStatus(AbstractButton button) {
ButtonModel model = button.getModel();
model.setRollover(false);
model.setArmed(false);
model.setPressed(false);
model.setSelected(false);
}
} | java | 18 | 0.673477 | 146 | 33.008032 | 249 | starcoderdata |
using System.Collections.Generic;
using System.Linq;
public class Smartphone : IPhone, IWWW
{
//private List phoneNumbers;
//private List sites;
//public Smartphone(List phoneNumbers, List sites)
//{
// this.PhoneNumbers = phoneNumbers;
// this.Sites = sites;
//}
//public List PhoneNumbers
//{
// get { return this.phoneNumbers; }
// set { this.phoneNumbers = value; }
//}
//public List Sites
//{
// get { return this.sites; }
// set { this.sites = value; }
//}
public string Calling(string phoneNumber)
{
if (!phoneNumber.Any(c => char.IsDigit(c)))
return "Invalid number!";
return $"Calling... {phoneNumber}";
}
public string Browsing(string site)
{
if (site.Any(c => char.IsDigit(c)))
return "Invalid URL!";
return $"Browsing: {site}!";
}
} | c# | 14 | 0.566701 | 70 | 22.585366 | 41 | starcoderdata |
Template.createJob.jobsCollection = function () {
return Jobs;
};
/**
* Markdown Editor dupport for Job Descriptions
*/
if (typeof Template.editor.created == 'undefined') {
Template.editor.created = function() {
this.editor = false;
};
Template.editor.rendered = function() {
if (!this.editor) {
var converter = {
makeHtml: function(text) { return marked(text); }
};
var editor = new Markdown.Editor(converter);
editor.run();
this.editor = true;
}
$('#edit-btn').tooltip({placement: 'bottom'})
$('#preview-btn').tooltip({placement: 'bottom'})
$('table').addClass('table table-striped table-bordered table-hover');
}
Template.editor.events({
'click a': function(e) {
// always follow links
e.stopPropagation();
},
'click #preview-btn': function(e, t) {
e.preventDefault();
var description = $('#innerEditor').text();
$('#wmd-input').hide();
$('#preview-btn').hide();
$('#wmd-preview').show();
$('#edit-btn').show();
$('table').addClass('table table-striped table-bordered table-hover');
},
'click #edit-btn': function(e) {
e.preventDefault();
$('#wmd-preview').hide();
$('#edit-btn').hide();
$('#wmd-input').show();
$('#preview-btn').show();
},
});
} else {
console.log('create_job: not rendering Markdown Editor!');
} | javascript | 18 | 0.526693 | 80 | 26.446429 | 56 | starcoderdata |
/********************************************************************
*
* 36. What will the following program display? (Some should be
* traced and require a calculator.)
*
*
* (Assume the user enters George Washington.)
*
*
*
* January 6th 2018
*
********************************************************************/
#include
#include
#include
using namespace std;
int main()
{
string userInput;
cout << endl;
cout << "What is your name? ";
getline(cin, userInput);
cout << "Hello " << userInput << endl;
cout << endl;
return 0;
} | c++ | 8 | 0.493088 | 69 | 19.34375 | 32 | starcoderdata |
package algorithm.leetcode;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* 删除字符串中的所有相邻重复项
*
* 给出由小写字母组成的字符串S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。
*
* 在 S 上反复执行重复项删除操作,直到无法继续删除。
*
* 在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。
*
*
* 示例:
*
* 输入:"abbaca"
* 输出:"ca"
* 解释:
* 例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。
*
*
* 提示:
*
* 1 <= S.length <= 20000
* S 仅由小写英文字母组成。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string
*/
@Slf4j
public class RemoveDuplicates {
public String removeDuplicates(String S) {
int len = S.length();
if (len == 1) {
return S;
}
Deque stack = new ArrayDeque<>();
for (int i = len - 1; i >= 0; i--) {
Character c = S.charAt(i);
if (stack.isEmpty() || stack.peek() != c) {
stack.push(c);
} else {
while (!stack.isEmpty() && stack.peek() == c) {
stack.pop();
}
}
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) {
sb.append(stack.pop());
}
return sb.toString();
}
@Test
public void test() {
String S = "abbaca";
String removeDuplicates = removeDuplicates(S);
log.info(removeDuplicates);
}
} | java | 15 | 0.548667 | 116 | 21.058824 | 68 | starcoderdata |
static QCLI_Command_Status_t StopTXRXTest(uint32_t Parameter_Count, QCLI_Parameter_t *Parameter_List)
{
uint32_t ElapsedTime;
uint32_t Bandwidth;
QCLI_Command_Status_t ret_val;
/* First, check that valid Bluetooth Stack ID exists. */
if(BLE_Demo_Context.BluetoothStackID)
{
if(CurrentTest != CURRENT_TEST_NONE)
{
/* Do not display statistics if an RX Test was specified (with */
/* no BD_ADDR specified). */
if(ConnectionHandle != QAPI_BLE_HCI_CONNECTION_HANDLE_INVALID_VALUE)
{
EndTime = qurt_timer_get_ticks();
ElapsedTime = qurt_timer_convert_ticks_to_time(EndTime - StartTime, QURT_TIME_MSEC) / 1000;
if(ElapsedTime)
{
Bandwidth = NumberBytes/ElapsedTime;
QCLI_Printf(BLE_Demo_Context.QCLI_Handle, "Test Time : %u\n", ElapsedTime);
QCLI_Printf(BLE_Demo_Context.QCLI_Handle, "Number Bytes : %u\n", NumberBytes);
QCLI_Printf(BLE_Demo_Context.QCLI_Handle, "Bytes/Second : %u\n", Bandwidth);
QCLI_Printf(BLE_Demo_Context.QCLI_Handle, "KBytes/Second: %u\n", Bandwidth/1024);
QCLI_Printf(BLE_Demo_Context.QCLI_Handle, "KBits/Second : %u\n", (Bandwidth*8)/1024);
}
}
QCLI_Printf(BLE_Demo_Context.QCLI_Handle, "Test Complete.\n");
if(CurrentTest == CURRENT_TEST_PERIODIC)
{
/* Stop the timer. */
qapi_Timer_Stop(BLE_Demo_Context.Timer);
/* Clean up the timer. */
qapi_Timer_Undef(BLE_Demo_Context.Timer);
BLE_Demo_Context.TransmitPeriod = 0;
QCLI_Printf(BLE_Demo_Context.QCLI_Handle, "Timer stopped.\n");
}
ConnectionHandle = QAPI_BLE_HCI_CONNECTION_HANDLE_INVALID_VALUE;
CurrentTest = CURRENT_TEST_NONE;
NumberOutstandingACLPackets = 0;
}
else
QCLI_Printf(BLE_Demo_Context.QCLI_Handle, "No Test in progress.\n");
/* Flag success to the caller. */
ret_val = QCLI_STATUS_SUCCESS_E;
}
else
{
/* No valid Bluetooth Stack ID exists. */
ret_val = QCLI_STATUS_ERROR_E;
}
return(ret_val);
} | c | 17 | 0.533225 | 104 | 37.578125 | 64 | inline |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class EscreveAutoComplete {
var $funcoes_basicas_ci_lib = "<?php
/**
\n* @property CI_DB_active_record \$db
\n* @property CI_DB_forge \$dbforge
\n* @property CI_Benchmark \$benchmark
\n* @property CI_Calendar \$calendar
\n* @property CI_Cart \$cart
\n* @property CI_Config \$config
\n* @property CI_Controller \$controller
\n* @property CI_Email \$email
\n* @property CI_Encrypt \$encrypt
\n* @property CI_Exceptions \$exceptions
\n* @property CI_Form_validation \$form_validation
\n* @property CI_Ftp \$ftp
\n* @property CI_Hooks \$hooks
\n* @property CI_Image_lib \$image_lib
\n* @property CI_Input \$input
\n* @property CI_Language \$language
\n* @property CI_Loader \$load
\n* @property CI_Log \$log
\n* @property CI_Model \$model
\n* @property CI_Output \$output
\n* @property CI_Pagination \$pagination
\n* @property CI_Parser \$parser
\n* @property CI_Profiler \$profiler
\n* @property CI_Router \$router
\n* @property CI_Session \$session
\n* @property CI_Sha1 \$sha1
\n* @property CI_Table \$table
\n* @property CI_Trackback \$trackback
\n* @property CI_Typography \$typography
\n* @property CI_Unit_test \$unit_test
\n* @property CI_Upload \$upload
\n* @property CI_URI \$uri
\n* @property CI_User_agent \$user_agent
\n* @property CI_Validation \$validation
\n* @property CI_Xmlrpc \$xmlrpc
\n* @property CI_Xmlrpcs \$xmlrpcs
\n* @property CI_Zip \$zip
\n*
\n* Add addtional libraries you wish
\n* to use in your controllers here
\n* @property SessaoModel \$SessaoModel";
var $funcoes_basicas_ci_model =" \n*/
class CI_Controller {};
\n/**
\n* @property CI_DB_query_builder \$db
\n* @property CI_DB_forge \$dbforge
\n* @property CI_Config \$config
\n* @property CI_Loader \$load
\n* @property CI_Session \$session
\n*
\n* Add addtional libraries you wish
\n* to use in your models here.
\n*";
function pre_add_escreve_auto_complete($modelOrControll){
if($modelOrControll !== 'SessionsModel' &&$modelOrControll!=='Sessions')
return "\n* @property $modelOrControll $$modelOrControll";
}
function escreve_auto_complete($entrada) {
$retorno = $this->funcoes_basicas_ci_lib. $entrada . " ".
$this->funcoes_basicas_ci_model."
\n* @property ConversaoLib \$conversaolib
\n* @property GeradorDeCodigo \$geradorDeCodigos
\n* @property MobileDetect \$mobiledetect
\n* @property Curl \$curl
\n* @property EnviaEmailLib \$enviaemailib
\n* @property Util \$util
\n* @property CalculaPlano \$calculaplano
\n* @property Pagarme \$pagarme
*/
class CI_Model {};
?>";
return $retorno;
}
} | php | 13 | 0.681403 | 76 | 30.102273 | 88 | starcoderdata |
<?php
$lang['module_home']='Domestico';
$lang['module_customers']='Clienti';
$lang['module_customers_desc']='Aggiungere, aggiornare, eliminare e ricerca clienti';
$lang['module_suppliers']='Fornitori';
$lang['module_suppliers_desc']='Aggiungere, aggiornare, eliminare e fornitori della ricerca';
$lang['module_employees']='Operatori';
$lang['module_employees_desc']='Aggiungere, aggiornare, eliminare e di ricerca gli operatori';
$lang['module_sales']='Vendite';
$lang['module_sales_desc']='Processa vendite e ritorni';
$lang['module_reports']='Riepiloghi';
$lang['module_reports_desc']='Visualizza e generare riepiloghi';
$lang['module_items']='Prodotti';
$lang['module_items_desc']='Aggiungere, aggiornare, eliminare e ricerca prodotti';
$lang['module_config']='Configurazione';
$lang['module_config_desc']='Modifica configurazione';
$lang['module_receivings']='ricevente';
$lang['module_receivings_desc']='Processa Ordini di acquisto';
$lang['module_giftcards']='Carte regalo';
$lang['module_giftcards_desc']='Aggiungere, aggiornare, cancellare e consultare carte regalo';
$lang['module_item_kits']='Gruppo prodotti';
$lang['module_item_kits_desc']='Aggiungere, aggiornare, cancellare e consultare Gruppo Prodotti';
$lang['module_action_add_update'] = 'Aggiungi, Aggiorna';
$lang['module_action_delete'] = 'Elimina';
$lang['module_action_search_customers'] = 'Cerca Clienti';
$lang['module_action_search_items'] = 'Cerca Prodotti';
$lang['module_action_search_item_kits'] = 'Cerca Gruppo Prodotti';
$lang['module_action_search_suppliers'] = 'Cerca fornitori';
$lang['module_see_cost_price'] = 'Mostra costo aquisto';
$lang['module_action_search_employees'] = 'Cerca Operatori';
$lang['module_edit_sale_price'] = 'Modifica prezzo vendita';
$lang['module_edit_sale'] = 'Modifica Vendita';
$lang['module_give_discount'] = 'Offri Sconto';
$lang['module_locations'] = 'Sedi';
$lang['module_locations_desc'] = 'Aggiungere, aggiornare, eliminare e Ricerca posizioni';
$lang['module_action_search_giftcards'] = 'Cerca Buoni Regalo';
$lang['module_action_delete_sale'] = 'Elimina Vendita';
$lang['module_action_delete_suspended_sale'] = 'Elimina Vendita sospeso';
$lang['module_action_search_locations'] = 'Ricerca posizioni';
$lang['module_action_assign_all_locations'] = 'Assegnare tutte le sedi';
$lang['module_action_delete_taxes'] = 'Elimina Tasse';
$lang['statistics'] = 'Statistica';
$lang['module_expenses_desc'] = 'Aggiungere, Update, Delete, e ricerca delle spese';
$lang['module_messages'] = 'Messaggi';
$lang['module_messages_desc'] = 'Inviare, ricevere e visualizzare i messaggi';
$lang['module_expenses'] = 'Spese';
$lang['module_action_edit_receiving'] = 'Modifica di ricezione';
$lang['module_action_delete_receiving'] = 'Eliminare la ricezione';
$lang['module_edit_sale_cost_price'] = 'Modifica vendita prezzo di costo';
$lang['module_edit_customer_points'] = 'Modifica cliente punti / Numero di vendite fino sconto';
$lang['module_edit_giftcard_value'] = 'Modifica valore Giftcard';
$lang['module_price_rules'] = 'Regole Prezzo';
$lang['module_price_rules_desc'] = 'Aggiungere, aggiornare, cancellare e consultare regole sui prezzi';
$lang['module_action_search_price_rules'] = 'Regole avanzata Price';
$lang['module_action_view_price_rules'] = 'Gestire Regole Prezzo';
$lang['module_action_add_update_price_rule'] = 'Modifica regola Prezzo';
$lang['module_action_delete_price_rule'] = 'Elimina regola Prezzo';
$lang['module_price_rules.php'] = 'Regole Prezzo';
$lang['module_action_search_sales'] = 'Cerca vendite';
$lang['deliveries_add_update'] = 'Aggiungi le consegne';
$lang['deliveries_edit'] = 'Modifica le consegne';
$lang['deliveries_delete'] = 'Elimina le consegne';
$lang['deliveries_search'] = 'Ricerca delle consegne';
$lang['module_deliveries'] = 'Le consegne';
$lang['module_deliveries_desc'] = 'Aggiungi, aggiornamento, eliminazione e ricerche';
$lang['module_deleted_customers'] = 'Clienti eliminati';
$lang['module_deleted_employees'] = 'Dipendenti';
$lang['module_deleted_items'] = 'Elementi eliminati';
$lang['module_deleted_item_kits'] = 'Kit di kit eliminati';
$lang['module_deleted_price_rules'] = 'Regole del prezzo eliminato';
$lang['module_deleted_deliveries_orders'] = 'Ordini di consegna eliminati';
$lang['module_deleted_expenses'] = 'Spese eliminate';
$lang['module_deleted_giftcards'] = 'Carte regalo cancellate';
$lang['module_deleted_locations'] = 'Località eliminate';
?> | php | 5 | 0.731091 | 103 | 49.91954 | 87 | starcoderdata |
define([
'core/js/adapt',
'./serializers/default',
'./serializers/questions',
'core/js/enums/completionStateEnum'
], function(Adapt, serializer, questions, COMPLETION_STATE) {
// Implements Adapt session statefulness
var AdaptStatefulSession = _.extend({
_config: null,
_shouldStoreResponses: true,
_shouldRecordInteractions: true,
// Session Begin
initialize: function(callback) {
this._onWindowUnload = this.onWindowUnload.bind(this);
this.getConfig();
this.getLearnerInfo();
// Restore state asynchronously to prevent IE8 freezes
this.restoreSessionState(function() {
// still need to defer call because AdaptModel.check*Status functions are asynchronous
_.defer(this.setupEventListeners.bind(this));
callback();
}.bind(this));
},
getConfig: function() {
this._config = Adapt.config.has('_spoor') ? Adapt.config.get('_spoor') : false;
this._shouldStoreResponses = (this._config && this._config._tracking && this._config._tracking._shouldStoreResponses);
// Default should be to record interactions, so only avoid doing that if _shouldRecordInteractions is set to false
if (this._config && this._config._tracking && this._config._tracking._shouldRecordInteractions === false) {
this._shouldRecordInteractions = false;
}
},
/**
* Replace the hard-coded _learnerInfo data in _globals with the actual data from the LMS
* If the course has been published from the AT, the _learnerInfo object won't exist so we'll need to create it
*/
getLearnerInfo: function() {
var globals = Adapt.course.get('_globals');
if (!globals._learnerInfo) {
globals._learnerInfo = {};
}
_.extend(globals._learnerInfo, Adapt.offlineStorage.get("learnerinfo"));
},
saveSessionState: function() {
var sessionPairs = this.getSessionState();
Adapt.offlineStorage.set(sessionPairs);
},
restoreSessionState: function(callback) {
var sessionPairs = Adapt.offlineStorage.get();
var hasNoPairs = _.keys(sessionPairs).length === 0;
var doSynchronousPart = function() {
if (sessionPairs.questions && this._shouldStoreResponses) questions.deserialize(sessionPairs.questions);
if (sessionPairs._isCourseComplete) Adapt.course.set('_isComplete', sessionPairs._isCourseComplete);
if (sessionPairs._isAssessmentPassed) Adapt.course.set('_isAssessmentPassed', sessionPairs._isAssessmentPassed);
callback();
}.bind(this);
if (hasNoPairs) return callback();
// Asynchronously restore block completion data because this has been known to be a choke-point resulting in IE8 freezes
if (sessionPairs.completion) {
serializer.deserialize(sessionPairs.completion, doSynchronousPart);
} else {
doSynchronousPart();
}
},
getSessionState: function() {
var sessionPairs = {
"completion": serializer.serialize(),
"questions": (this._shouldStoreResponses === true ? questions.serialize() : ""),
"_isCourseComplete": Adapt.course.get("_isComplete") || false,
"_isAssessmentPassed": Adapt.course.get('_isAssessmentPassed') || false
};
return sessionPairs;
},
// Session In Progress
setupEventListeners: function() {
$(window).on('beforeunload unload', this._onWindowUnload);
if (this._shouldStoreResponses) {
this.listenTo(Adapt.components, 'change:_isInteractionComplete', this.onQuestionComponentComplete);
}
if (this._shouldRecordInteractions) {
this.listenTo(Adapt, 'questionView:recordInteraction', this.onQuestionRecordInteraction);
}
this.listenTo(Adapt.blocks, 'change:_isComplete', this.onBlockComplete);
this.listenTo(Adapt, {
'assessment:complete': this.onAssessmentComplete,
'app:languageChanged': this.onLanguageChanged,
'tracking:complete': this.onTrackingComplete
});
},
removeEventListeners: function () {
$(window).off('beforeunload unload', this._onWindowUnload);
this.stopListening();
},
reattachEventListeners: function() {
this.removeEventListeners();
this.setupEventListeners();
},
onBlockComplete: function(block) {
this.saveSessionState();
},
onQuestionComponentComplete: function(component) {
if (!component.get("_isQuestionType")) return;
this.saveSessionState();
},
onTrackingComplete: function(completionData) {
this.saveSessionState();
var completionStatus = completionData.status.asLowerCase;
// The config allows the user to override the completion state.
switch (completionData.status) {
case COMPLETION_STATE.COMPLETED:
case COMPLETION_STATE.PASSED: {
if (!this._config._reporting._onTrackingCriteriaMet) {
Adapt.log.warn("No value defined for '_onTrackingCriteriaMet', so defaulting to '" + completionStatus + "'");
} else {
completionStatus = this._config._reporting._onTrackingCriteriaMet;
}
break;
}
case COMPLETION_STATE.FAILED: {
if (!this._config._reporting._onAssessmentFailure) {
Adapt.log.warn("No value defined for '_onAssessmentFailure', so defaulting to '" + completionStatus + "'");
} else {
completionStatus = this._config._reporting._onAssessmentFailure;
}
}
}
Adapt.offlineStorage.set("status", completionStatus);
},
onAssessmentComplete: function(stateModel) {
Adapt.course.set('_isAssessmentPassed', stateModel.isPass);
this.saveSessionState();
this.submitScore(stateModel);
},
onQuestionRecordInteraction:function(questionView) {
var responseType = questionView.getResponseType();
// If responseType doesn't contain any data, assume that the question
// component hasn't been set up for cmi.interaction tracking
if(_.isEmpty(responseType)) return;
var id = questionView.model.get('_id');
var response = questionView.getResponse();
var result = questionView.isCorrect();
var latency = questionView.getLatency();
Adapt.offlineStorage.set("interaction", id, response, result, latency, responseType);
},
/**
* when the user switches language, we need to:
* - reattach the event listeners as the language change triggers a reload of the json, which will create brand new collections
* - get and save a fresh copy of the session state. as the json has been reloaded, the blocks completion data will be reset (the user is warned that this will happen by the language picker extension)
* - check to see if the config requires that the lesson_status be reset to 'incomplete'
*/
onLanguageChanged: function () {
this.reattachEventListeners();
this.saveSessionState();
if (this._config._reporting && this._config._reporting._resetStatusOnLanguageChange === true) {
Adapt.offlineStorage.set("status", "incomplete");
}
},
submitScore: function(stateModel) {
if (this._config && !this._config._tracking._shouldSubmitScore) return;
if (stateModel.isPercentageBased) {
Adapt.offlineStorage.set("score", stateModel.scoreAsPercent, 0, 100);
} else {
Adapt.offlineStorage.set("score", stateModel.score, 0, stateModel.maxScore);
}
},
// Session End
onWindowUnload: function() {
this.removeEventListeners();
}
}, Backbone.Events);
return AdaptStatefulSession;
}); | javascript | 23 | 0.591813 | 208 | 38.759091 | 220 | starcoderdata |
const puppeteer = require('puppeteer');
require('dotenv').config();
const config = {
headless: process.env.HEADLESS === 'true' ? true : false,
slowMo: +process.env.SLOWMO,
args: process.env.ARGS.split(','),
};
//console.log('Now the process.env values are:', config);
const videoLinkFinder = async (videoURL) => {
try {
console.log('Collecting Video Playlist Links, Please wait...');
const topic = videoURL.split('/').reverse()[1];
const browser = await puppeteer.launch(config);
const page = await browser.newPage();
await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/60.0.3112.113 Safari/537.36');
//await page.on('response', (r) => console.log(r.remoteAddress()));
await page.setViewport({ width: 1366, height: 720 });
console.log('%o', 'I am trying to login your credentials, Please wait...');
await page.goto(process.env.RESOURCE_LOGIN_URL, {
waitUntil: 'load',
timeout: 5000000,
});
await page.waitFor(2000);
console.log('PASSWORD && USER_EMAIL', process.env.USER_PASSWORD, process.env.USER_EMAIL);
await page.type('input[name="email"]', process.env.USER_EMAIL);
await page.type('input[name="password"]', process.env.USER_PASSWORD);
const signInBtn = await page.$x("//form[@data-newrelic-id='authForm']//button[contains(text(), 'Sign In')]");
console.log('sign in Btn button found on page', signInBtn.length);
if (signInBtn.length > 0) {
await signInBtn[0].click();
}
console.log('%o', 'Logged in successfully, Please wait...');
await page.waitFor(2000);
await page.goto(videoURL, {
waitUntil: 'load',
timeout: 6000000,
});
await page.waitFor(2000);
const selector = 'a';
await page.waitForSelector(selector);
const links = await page.$$eval(selector, (am) => am.filter((e) => e.href).map((e) => e.href));
let filteredLinks = links.filter((e) => {
if (e.includes(topic)) {
return e;
}
});
await browser.close();
console.log('[videoLinkFinder] Link found====', filteredLinks.length);
filteredLinks.sort();
return {
linkArr: filteredLinks.slice(2, filteredLinks.length),
topic: topic,
};
//return filteredLinks.slice(filteredLinks.length - 2, filteredLinks.length);
} catch (err) {
console.error(err);
}
};
module.exports = { videoLinkFinder }; | javascript | 29 | 0.674668 | 144 | 35.453125 | 64 | starcoderdata |
from flask import Flask, render_template, request
import berry.script.template_updater
import berry.berry as berry
import json
app = Flask(__name__, static_url_path="")
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html')
@app.route('/wifi/list')
def get_wifi_list():
""" Scan available wifi list.
Usage: /wifi/list
Returns: json
[
{
"ssid": string, // Wifi name
"frequency": string, // 2.4Ghz: 2, 5Ghz: 5
"intensity": string, // 0 ~ 70
"psk-requirement": string // public: off, private: on
},
]
"""
return json.dumps(berry.wifi_list(), indent=4, ensure_ascii=False)
@app.route('/wifi/info')
def get_wifi_current():
""" SSID, intensity of connected wifi.
Usage: /wifi/info
Returns:
connected: json {"ssid": string, "intensity": string}
not connected: string "Not connected"
"""
return json.dumps(berry.wifi_current())
@app.route('/wifi/is-known/
def is_wifi_known(ssid):
""" Check if ssid is known.
Usage: /wifi/known/wifi_name
Returns: json: boolean
"""
return json.dumps(berry.wifi_is_known(ssid))
@app.route('/wifi/connect/known', methods=['POST'])
def wifi_connect_known():
""" Connect to ssid via psw with auto reconnect option.
Usage: /wifi/connect/known
body:
{
"ssid": "wifi name",
"opt": true/false
}
Returns: json
{
"status": boolean, // connected: true, failed: false
"ssid": string, // connected: Wifi name, failed: null
"ip-address": string // connected: 172.xx.xx.xx, failed: null
}
"""
input_data = request.get_json()
ssid = input_data["ssid"]
auto_reconnect = input_data["opt"]
return json.dumps(berry.wifi_connect(True, ssid, None, auto_reconnect), indent=4, ensure_ascii=False)
@app.route('/wifi/connect/unknown', methods=['POST'])
def wifi_connect_unknown():
""" Connect to ssid via psw with auto reconnect option.
Usage: /wifi/connect/unknown
body:
{
"ssid": "wifi name",
"psw": "password",
"opt": true/false
}
Returns: json
{
"status": boolean, // connected: true, failed: false
"ssid": string, // connected: Wifi name, failed: null
"ip-address": string // connected: 172.xx.xx.xx, failed: null
}
"""
input_data = request.get_json()
ssid = input_data["ssid"]
psw = input_data["psw"]
auto_reconnect = input_data["opt"]
return json.dumps(berry.wifi_connect(False, ssid, psw, auto_reconnect), indent=4, ensure_ascii=False)
@app.route('/ble')
def get_ble_list():
""" Scan available Modi ble uuid.
Usage: /ble
Returns: json
['MODI_uuid': string, ] // MODI_403D8B7C
"""
return json.dumps(berry.ble_list())
@app.route('/modi/list')
def get_modi_list():
""" Scan connected Modi list.
Usage: /modi/list
Returns:
disconnected: string "No Modi"
connected: json
[
{
"Module": string, // "network"
"Uuid": int, // 2813171425
"Id": int, // 1761
"Is-up-to-date": boolean // false
},
]
"""
return json.dumps(berry.modi_list(), indent=4)
@app.route('/modi/update')
def run_modi_update():
""" Check and run update Modi modules if needed.
Usage: /modi/update
Returns:
disconnected: string "No Modi"
connected: json
[
{
"Module": string, // "network"
"Id": int, // 1761
},
]
"""
return json.dumps(berry.modi_update(), indent=4)
@app.route('/power-off')
def power_off():
""" Shutdown the machine.
Usage: /power-off
Returns: None
"""
return berry.power_off()
@app.route('/power-reboot')
def power_reboot():
""" Reboot the machine.
Usage: /power-reboot
Returns: None
"""
return berry.power_reboot()
def run():
app.run(debug=True, host='0.0.0.0', port=5000)
if __name__ == '__main__':
run() | python | 9 | 0.527199 | 105 | 22.634921 | 189 | starcoderdata |
import React from 'react'
import PropTypes from 'prop-types'
const Link = ({title, description, url}) => (
<li className="link">
<img className="link__thumb" />
<h2 className="link__title">{title}
<p className="link__description"> {description}
<a className="link__url" target="_blank" > {url}
)
Link.propTypes = {
title: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
url: PropTypes.string.isRequired
}
export default Link | javascript | 10 | 0.668 | 57 | 22.809524 | 21 | starcoderdata |
import React from "react";
import { Button, Paper, Tooltip } from "@material-ui/core";
import HomeIcon from "@material-ui/icons/Home";
import { withStyles } from "@material-ui/core/styles";
const styles = (theme) => ({
paper: {
marginBottom: theme.spacing(1),
},
button: {
minWidth: "unset",
},
});
/**
* @summary Resets map to initial zoom level, centrum coordinate and active layers.
*
* @param {object} props
* @returns {object} React
*/
class MapResetter extends React.PureComponent {
// TODO: Also reset layers to default visibility!
handleClick = (e) => {
const { map } = this.props;
if (map !== undefined) {
const view = map.getView();
const { zoom, center } = this.props.mapConfig.map;
view.animate({ zoom, center });
}
};
render() {
const { classes } = this.props;
return (
<Tooltip title="Återställ kartan till startläget">
<Paper className={classes.paper}>
<Button
aria-label="Återställ kartan till startläget"
className={classes.button}
onClick={this.handleClick}
>
<HomeIcon />
);
}
}
export default withStyles(styles)(MapResetter); | javascript | 17 | 0.610106 | 83 | 24.018868 | 53 | starcoderdata |
public void SaveMapParametersWithDialog()
{
// Create generic name at current directory
string filePath = Path.Combine(Directory.GetCurrentDirectory(), "map_appearance.sc4cart");
filePath = Helper.GenerateFilename(filePath);
using (SaveFileDialog fileDialog = new SaveFileDialog())
{
fileDialog.Title = "Save SC4Cartographer map properties";
fileDialog.InitialDirectory = Directory.GetCurrentDirectory();
fileDialog.FileName = Path.GetFileName(filePath);
fileDialog.RestoreDirectory = true;
//fileDialog.CheckFileExists = true;
fileDialog.CheckPathExists = true;
fileDialog.Filter = "SC4Cartographer properties file (*.sc4cart)|*.sc4cart";
if (fileDialog.ShowDialog(this) == DialogResult.OK)
{
SaveMapParameters(fileDialog.FileName);
}
}
} | c# | 13 | 0.588294 | 102 | 47.047619 | 21 | inline |
package com.alibaba.tesla.appmanager.server.repository.mapper;
import com.alibaba.tesla.appmanager.server.repository.domain.RtAppInstanceDO;
import com.alibaba.tesla.appmanager.server.repository.domain.RtAppInstanceDOExample;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface RtAppInstanceDOMapper {
long countByExample(RtAppInstanceDOExample example);
int deleteByExample(RtAppInstanceDOExample example);
int deleteByPrimaryKey(Long id);
int insertSelective(RtAppInstanceDO record);
List selectByExample(RtAppInstanceDOExample example);
List selectByExampleAndOption(
@Param("example") RtAppInstanceDOExample example,
@Param("key") String key,
@Param("value") String value);
RtAppInstanceDO selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") RtAppInstanceDO record, @Param("example") RtAppInstanceDOExample example);
} | java | 10 | 0.783862 | 124 | 34.931034 | 29 | starcoderdata |
const void*
ProgGLES2::ConstBuf::Instance() const
{
if (frame != CurFrame)
{
inst = nullptr;
*lastInst = nullptr;
}
if (!inst)
{
#if RHI_GL__USE_STATIC_CONST_BUFFER_OPTIMIZATION
// try to make 'static'
if (ProgGLES2::ConstBuf::CurFrame - lastmodifiedFrame > 3 && altData.size() < altData.capacity() - 1)
{
isStatic = true;
}
if (isStatic)
{
inst = data;
// try to release some alt-data
for (unsigned i = 0; i != altData.size(); ++i)
{
if (CurFrame - altDataAllocationFrame[i] > 5)
{
::free(altData[i]);
altData.erase(altData.begin() + i);
altDataAllocationFrame.erase(altDataAllocationFrame.begin() + i);
break;
}
}
}
else
{
#endif
inst = _GLES2_DefaultConstRingBuffer.Alloc(count * 4);
memcpy(inst, data, 4 * count * sizeof(float));
#if RHI_GL__USE_STATIC_CONST_BUFFER_OPTIMIZATION
}
#endif
frame = CurFrame;
#if RHI_GL__DEBUG_CONST_BUFFERS
++instCount;
#endif
}
#if RHI_GL__USE_STATIC_CONST_BUFFER_OPTIMIZATION
isUsedInDrawCall = true;
#endif
return inst;
} | c++ | 18 | 0.495947 | 109 | 23.690909 | 55 | inline |
//===-- PlatformDarwinTest.cpp --------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "Plugins/Platform/MacOSX/PlatformDarwin.h"
#include "llvm/ADT/StringRef.h"
#include
using namespace lldb;
using namespace lldb_private;
struct PlatformDarwinTester : public PlatformDarwin {
public:
using PlatformDarwin::FindComponentInPath;
using PlatformDarwin::GetCompatibleArch;
};
TEST(PlatformDarwinTest, TestParseVersionBuildDir) {
llvm::VersionTuple V;
llvm::StringRef D;
std::tie(V, D) = PlatformDarwin::ParseVersionBuildDir("1.2.3 (test1)");
EXPECT_EQ(llvm::VersionTuple(1, 2, 3), V);
EXPECT_EQ("test1", D);
std::tie(V, D) = PlatformDarwin::ParseVersionBuildDir("2.3 (test2)");
EXPECT_EQ(llvm::VersionTuple(2, 3), V);
EXPECT_EQ("test2", D);
std::tie(V, D) = PlatformDarwin::ParseVersionBuildDir("3 (test3)");
EXPECT_EQ(llvm::VersionTuple(3), V);
EXPECT_EQ("test3", D);
std::tie(V, D) = PlatformDarwin::ParseVersionBuildDir("1.2.3 (test");
EXPECT_EQ(llvm::VersionTuple(1, 2, 3), V);
EXPECT_EQ("test", D);
std::tie(V, D) = PlatformDarwin::ParseVersionBuildDir("2.3.4 test");
EXPECT_EQ(llvm::VersionTuple(2, 3, 4), V);
EXPECT_EQ("", D);
std::tie(V, D) = PlatformDarwin::ParseVersionBuildDir("3.4.5");
EXPECT_EQ(llvm::VersionTuple(3, 4, 5), V);
}
TEST(PlatformDarwinTest, FindComponentInPath) {
EXPECT_EQ("/path/to/foo",
PlatformDarwinTester::FindComponentInPath("/path/to/foo/", "foo"));
EXPECT_EQ("/path/to/foo",
PlatformDarwinTester::FindComponentInPath("/path/to/foo", "foo"));
EXPECT_EQ("/path/to/foobar", PlatformDarwinTester::FindComponentInPath(
"/path/to/foobar", "foo"));
EXPECT_EQ("/path/to/foobar", PlatformDarwinTester::FindComponentInPath(
"/path/to/foobar", "bar"));
EXPECT_EQ("",
PlatformDarwinTester::FindComponentInPath("/path/to/foo", "bar"));
}
TEST(PlatformDarwinTest, GetCompatibleArchARM64) {
const ArchSpec::Core core = ArchSpec::eCore_arm_arm64;
EXPECT_STREQ("arm64", PlatformDarwinTester::GetCompatibleArch(core, 0));
EXPECT_STREQ("armv7", PlatformDarwinTester::GetCompatibleArch(core, 1));
EXPECT_STREQ("armv4", PlatformDarwinTester::GetCompatibleArch(core, 10));
EXPECT_STREQ("arm", PlatformDarwinTester::GetCompatibleArch(core, 11));
EXPECT_STREQ("thumbv7", PlatformDarwinTester::GetCompatibleArch(core, 12));
EXPECT_STREQ("thumbv4t", PlatformDarwinTester::GetCompatibleArch(core, 21));
EXPECT_STREQ("thumb", PlatformDarwinTester::GetCompatibleArch(core, 22));
EXPECT_EQ(nullptr, PlatformDarwinTester::GetCompatibleArch(core, 23));
}
TEST(PlatformDarwinTest, GetCompatibleArchARMv7f) {
const ArchSpec::Core core = ArchSpec::eCore_arm_armv7f;
EXPECT_STREQ("armv7f", PlatformDarwinTester::GetCompatibleArch(core, 0));
EXPECT_STREQ("armv7", PlatformDarwinTester::GetCompatibleArch(core, 1));
EXPECT_STREQ("arm", PlatformDarwinTester::GetCompatibleArch(core, 6));
EXPECT_STREQ("thumbv7f", PlatformDarwinTester::GetCompatibleArch(core, 7));
}
TEST(PlatformDarwinTest, GetCompatibleArchARMv7k) {
const ArchSpec::Core core = ArchSpec::eCore_arm_armv7k;
EXPECT_STREQ("armv7k", PlatformDarwinTester::GetCompatibleArch(core, 0));
EXPECT_STREQ("armv7", PlatformDarwinTester::GetCompatibleArch(core, 1));
EXPECT_STREQ("arm", PlatformDarwinTester::GetCompatibleArch(core, 6));
EXPECT_STREQ("thumbv7k", PlatformDarwinTester::GetCompatibleArch(core, 7));
}
TEST(PlatformDarwinTest, GetCompatibleArchARMv7s) {
const ArchSpec::Core core = ArchSpec::eCore_arm_armv7s;
EXPECT_STREQ("armv7s", PlatformDarwinTester::GetCompatibleArch(core, 0));
EXPECT_STREQ("armv7", PlatformDarwinTester::GetCompatibleArch(core, 1));
EXPECT_STREQ("arm", PlatformDarwinTester::GetCompatibleArch(core, 6));
EXPECT_STREQ("thumbv7s", PlatformDarwinTester::GetCompatibleArch(core, 7));
}
TEST(PlatformDarwinTest, GetCompatibleArchARMv7m) {
const ArchSpec::Core core = ArchSpec::eCore_arm_armv7m;
EXPECT_STREQ("armv7m", PlatformDarwinTester::GetCompatibleArch(core, 0));
EXPECT_STREQ("armv7", PlatformDarwinTester::GetCompatibleArch(core, 1));
EXPECT_STREQ("arm", PlatformDarwinTester::GetCompatibleArch(core, 6));
EXPECT_STREQ("thumbv7m", PlatformDarwinTester::GetCompatibleArch(core, 7));
}
TEST(PlatformDarwinTest, GetCompatibleArchARMv7em) {
const ArchSpec::Core core = ArchSpec::eCore_arm_armv7em;
EXPECT_STREQ("armv7em", PlatformDarwinTester::GetCompatibleArch(core, 0));
EXPECT_STREQ("armv7", PlatformDarwinTester::GetCompatibleArch(core, 1));
EXPECT_STREQ("arm", PlatformDarwinTester::GetCompatibleArch(core, 6));
EXPECT_STREQ("thumbv7em", PlatformDarwinTester::GetCompatibleArch(core, 7));
}
TEST(PlatformDarwinTest, GetCompatibleArchARMv7) {
const ArchSpec::Core core = ArchSpec::eCore_arm_armv7;
EXPECT_STREQ("armv7", PlatformDarwinTester::GetCompatibleArch(core, 0));
EXPECT_STREQ("armv6m", PlatformDarwinTester::GetCompatibleArch(core, 1));
EXPECT_STREQ("arm", PlatformDarwinTester::GetCompatibleArch(core, 5));
EXPECT_STREQ("thumbv7", PlatformDarwinTester::GetCompatibleArch(core, 6));
}
TEST(PlatformDarwinTest, GetCompatibleArchARMv6m) {
const ArchSpec::Core core = ArchSpec::eCore_arm_armv6m;
EXPECT_STREQ("armv6m", PlatformDarwinTester::GetCompatibleArch(core, 0));
EXPECT_STREQ("armv6", PlatformDarwinTester::GetCompatibleArch(core, 1));
EXPECT_STREQ("arm", PlatformDarwinTester::GetCompatibleArch(core, 4));
EXPECT_STREQ("thumbv6m", PlatformDarwinTester::GetCompatibleArch(core, 5));
}
TEST(PlatformDarwinTest, GetCompatibleArchARMv6) {
const ArchSpec::Core core = ArchSpec::eCore_arm_armv6;
EXPECT_STREQ("armv6", PlatformDarwinTester::GetCompatibleArch(core, 0));
EXPECT_STREQ("armv5", PlatformDarwinTester::GetCompatibleArch(core, 1));
EXPECT_STREQ("arm", PlatformDarwinTester::GetCompatibleArch(core, 3));
EXPECT_STREQ("thumbv6", PlatformDarwinTester::GetCompatibleArch(core, 4));
}
TEST(PlatformDarwinTest, GetCompatibleArchARMv5) {
const ArchSpec::Core core = ArchSpec::eCore_arm_armv5;
EXPECT_STREQ("armv5", PlatformDarwinTester::GetCompatibleArch(core, 0));
EXPECT_STREQ("armv4", PlatformDarwinTester::GetCompatibleArch(core, 1));
EXPECT_STREQ("arm", PlatformDarwinTester::GetCompatibleArch(core, 2));
EXPECT_STREQ("thumbv5", PlatformDarwinTester::GetCompatibleArch(core, 3));
}
TEST(PlatformDarwinTest, GetCompatibleArchARMv4) {
const ArchSpec::Core core = ArchSpec::eCore_arm_armv4;
EXPECT_STREQ("armv4", PlatformDarwinTester::GetCompatibleArch(core, 0));
EXPECT_STREQ("arm", PlatformDarwinTester::GetCompatibleArch(core, 1));
EXPECT_STREQ("thumbv4t", PlatformDarwinTester::GetCompatibleArch(core, 2));
EXPECT_STREQ("thumb", PlatformDarwinTester::GetCompatibleArch(core, 3));
} | c++ | 9 | 0.729407 | 80 | 43.186335 | 161 | starcoderdata |
<?php
namespace WP_Rocket\Optimization\JS;
use WP_Rocket\Logger\Logger;
use MatthiasMullie\Minify as Minifier;
/**
* Minify JS files
*
* @since 3.1
* @author
*/
class Minify extends Abstract_JS_Optimization {
/**
* Minifies JS files
*
* @since 3.1
* @author
*
* @param string $html HTML content.
* @return string
*/
public function optimize( $html ) {
Logger::info( 'JS MINIFICATION PROCESS STARTED.', [ 'js minification process' ] );
$html_nocomments = $this->hide_comments( $html );
$scripts = $this->find( ' $html_nocomments );
if ( ! $scripts ) {
Logger::debug( 'No ` tags found.', [ 'js minification process' ] );
return $html;
}
Logger::debug( 'Found ' . count( $scripts ) . ' tags.', [
'js minification process',
'tags' => $scripts,
] );
foreach ( $scripts as $script ) {
global $wp_scripts;
if ( preg_match( '/[-.]min\.js/iU', $script[2] ) ) {
Logger::debug( 'Script is already minified.', [
'js minification process',
'tag' => $script[0],
] );
continue;
}
if ( $this->is_external_file( $script[2] ) ) {
Logger::debug( 'Script is external.', [
'js minification process',
'tag' => $script[0],
] );
continue;
}
if ( $this->is_minify_excluded_file( $script ) ) {
Logger::debug( 'Script is excluded.', [
'js minification process',
'tag' => $script[0],
] );
continue;
}
// Don't minify jQuery included in WP core since it's already minified but without .min in the filename.
if ( ! empty( $wp_scripts->registered['jquery-core']->src ) && false !== strpos( $script[2], $wp_scripts->registered['jquery-core']->src ) ) {
Logger::debug( 'jQuery script is already minified.', [
'js minification process',
'tag' => $script[0],
] );
continue;
}
$minify_url = $this->replace_url( $script[2] );
if ( ! $minify_url ) {
Logger::error( 'Script minification failed.', [
'js minification process',
'tag' => $script[0],
] );
continue;
}
$replace_script = str_replace( $script[2], $minify_url, $script[0] );
$replace_script = str_replace( '<script', '<script data-minify="1"', $replace_script );
$html = str_replace( $script[0], $replace_script, $html );
Logger::info( 'Script minification succeeded.', [
'js minification process',
'url' => $minify_url,
] );
}
return $html;
}
/**
* Creates the minify URL if the minification is successful
*
* @since 2.11
* @author
*
* @param string $url Original file URL.
* @return string|bool The minify URL if successful, false otherwise
*/
protected function replace_url( $url ) {
if ( empty( $url ) ) {
return false;
}
$unique_id = md5( $url . $this->minify_key );
$filename = preg_replace( '/\.js$/', '-' . $unique_id . '.js', ltrim( rocket_realpath( rocket_extract_url_component( $url, PHP_URL_PATH ) ), '/' ) );
$minified_file = $this->minify_base_path . $filename;
$minified_url = $this->get_minify_url( $filename );
if ( rocket_direct_filesystem()->exists( $minified_file ) ) {
Logger::debug( 'Minified JS file already exists.', [
'js minification process',
'path' => $minified_file,
] );
return $minified_url;
}
$file_path = $this->get_file_path( $url );
if ( ! $file_path ) {
Logger::error( 'Couldn’t get the file path from the URL.', [
'js minification process',
'url' => $url,
] );
return false;
}
$minified_content = $this->minify( $file_path );
if ( ! $minified_content ) {
Logger::error( 'No minified content.', [
'js minification process',
'path' => $minified_file,
] );
return false;
}
$save_minify_file = $this->write_file( $minified_content, $minified_file );
if ( ! $save_minify_file ) {
Logger::error( 'Minified JS file could not be created.', [
'js minification process',
'path' => $minified_file,
] );
return false;
}
Logger::debug( 'Minified JS file successfully created.', [
'js minification process',
'path' => $minified_file,
] );
return $minified_url;
}
/**
* Minifies the content
*
* @since 2.11
* @author
*
* @param string|array $file File to minify.
* @return string|bool Minified content, false if empty
*/
protected function minify( $file ) {
$file_content = $this->get_file_content( $file );
if ( ! $file_content ) {
return false;
}
$minifier = $this->get_minifier( $file_content );
$minified_content = $minifier->minify();
if ( empty( $minified_content ) ) {
return false;
}
return $minified_content;
}
/**
* Returns a new minifier instance
*
* @since 3.1
* @author
*
* @param string $file_content Content to minify.
* @return Minifier\JS
*/
protected function get_minifier( $file_content ) {
return new Minifier\JS( $file_content );
}
} | php | 20 | 0.589199 | 152 | 24.142157 | 204 | starcoderdata |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Logic
{
///
/// 开始节点
///
public class StartNode : LogicNodeBase
{
}
} | c# | 5 | 0.656716 | 51 | 16.866667 | 15 | starcoderdata |
#ifndef FORCE_DEBUG
#define NDEBUG
#endif
#include
#include "base/CommandLineParser.h"
#include "aligns/KmerAlignCore.h"
#include "analysis/DNAVector.h"
#include
#include "base/FileParser.h"
#include "analysis/KmerTable.h"
//===================================================================
//========================================================================
//========================================================================
bool Irregular(char l)
{
if (l == 'A' || l == 'C' || l == 'G' || l == 'T')
return false;
//cout << "Irregular char: " << l << endl;
return true;
}
int FindPartner(svec & ids, const string & name)
{
char tmp[256];
strcpy(tmp, name.c_str());
tmp[strlen(tmp)-1] = '1';
IDS dummy;
dummy.SetName(tmp);
int index = BinSearch(ids, dummy);
return index;
}
int main(int argc,char** argv)
{
commandArg aStringCmmd("-i","read fasta file");
commandArg fStringCmmd("-f","fasta file");
commandArg oStringCmmd("-o","fasta output");
commandArg kCmmd("-k","kmer size", 24);
commandArg strandCmmd("-doublestrand","not strand-specific", false);
//commandArg cCmmd("-nc","do not fully connected graph", false);
commandLineParser P(argc,argv);
P.SetDescription("Assembles k-mer sequences.");
P.registerArg(aStringCmmd);
P.registerArg(fStringCmmd);
P.registerArg(oStringCmmd);
P.registerArg(kCmmd);
P.registerArg(strandCmmd);
//P.registerArg(cCmmd);
P.parse();
string aString = P.GetStringValueFor(aStringCmmd);
string fString = P.GetStringValueFor(fStringCmmd);
string oString = P.GetStringValueFor(oStringCmmd);
int k = P.GetIntValueFor(kCmmd);
bool bStrand = P.GetBoolValueFor(strandCmmd);
int i, j;
//vecbasevector contigBases;
vecDNAVector dna;
dna.Read(fString);
vecDNAVector seq;
seq.Read(aString);
KmerSequence kmers(k, &seq);;
kmers.Add(seq);
long long m = kmers.GetBoundValue();
vecDNAVector out;
//dna.Read(fString);
svec used;
used.resize(seq.isize(), 0);
int offset = seq[0].isize();
int broken = 0;
int extra = 25;
for (i=0; i<dna.isize(); i++) {
DNAVector one = dna[i];
double all = 0.;
broken = 0;
//cout << "Sequence length: " << one.isize() << endl;
svec reads;
for (j=0; j<=one.isize()-k; j++) {
DNAVector sub;
sub.SetToSubOf(one, j, k);
long long n1, n2;
svec ids;
int edge = 0;
kmers.BasesToNumberCountPlus(ids, n1, sub, edge);
for (int x=0; x<ids.isize(); x++) {
if (used[ids[x].ID()] > 0)
continue;
double ff = FracAlign(one, j, seq[ids[x].ID()], ids[x].Start());
if (ff > 0.95) {
used[ids[x].ID()] = 1;
ids[x].SetEdge(j);
ids[x].SetName(seq.Name(ids[x].ID()));
reads.push_back(ids[x]);
}
}
if (bStrand) {
sub.ReverseComplement();
kmers.BasesToNumberCountPlus(ids, n2, sub, edge);
}
all += n1 + n2;
}
Sort(reads);
for (j=0; j<reads.isize(); j++) {
const char * p = reads[j].Name().c_str();
//cout << "Considering " << p << endl;
if (p[strlen(p)-1] != '2')
continue;
int idx = FindPartner(reads, p);
if (idx == -1)
continue;
//cout << "Not found." << endl;
//cout << "Found partner for " << p << endl;
offset = seq[j].isize();
int start = reads[j].Edge()+offset+extra;
int end = reads[idx].Edge()-extra;
//cout << "Span from " << start-offset << " to " << end << "\t" << end - start + offset << "\t" << p << "\t" << reads[idx].Name() << endl;
for (int x = start; x<end; x++) {
if (one.Qual(x) < 100)
one.SetQual(x, one.Qual(x)+1);
}
}
int baldStart = -2;
int lastBaldStart = 0;
char tmp[256];
//cout << "Printing" << endl;
for (int x=0; x<one.isize(); x++) {
//cout << x << "\t" << one.Qual(x) << endl;
if (one.Qual(x) > 0) {
if (baldStart == -2)
baldStart = -1;
//cout << "baldStart=" << baldStart << endl;
if (baldStart >= 0) {
int middle = (x+baldStart)/2;
sprintf(tmp, "%s_part_%d", dna.Name(i).c_str(), broken);
broken++;
DNAVector piece;
cout << "Found Break: start=" << lastBaldStart << " to=" << middle-lastBaldStart+k/2 << " middle=" << middle << endl;
piece.SetToSubOf(one, lastBaldStart, middle-lastBaldStart+k/2);
out.push_back(piece, tmp);
baldStart = -1;
lastBaldStart = middle-k/2;
}
} else {
if (baldStart == -1)
baldStart = x;
}
}
sprintf(tmp, "%s_part_%d", dna.Name(i).c_str(), broken);
broken++;
DNAVector piece2;
piece2.SetToSubOf(one, lastBaldStart, one.isize()-lastBaldStart);
out.push_back(piece2, tmp);
/*
double cov = all/(double)one.isize();
char tmp[128];
sprintf(tmp, "%f", cov);
string name = dna.Name(i);
name += "_cov_";
name += tmp;
dna.SetName(i, name);
*/
}
out.Write(oString);
return 0;
} | c++ | 20 | 0.551994 | 144 | 22.213953 | 215 | starcoderdata |
import React from 'react';
import PropTypes from 'prop-types';
import glamorous from 'glamorous';
import {colors} from '../constants';
const Container = glamorous.div({
display: 'flex',
flexDirection: 'column',
boxShadow: '2px 2px 0 0 rgba(0, 0, 0, 0.25)',
transition: '0.3s',
marginTop: '10px'
});
const Header = glamorous.div({
width: '100%',
backgroundColor: colors.dark,
color: colors.light,
paddingLeft: '15px',
lineHeight: '2em',
boxSizing: 'border-box',
textAlign: 'left'
});
const Body = glamorous.div({
width:'100%',
boxSizing: 'border-box',
backgroundColor: colors.light
});
const Card = ({header, children}) => (
{children}
);
Card.propTypes = {
header: PropTypes.string,
children: PropTypes.node
};
export default Card; | javascript | 6 | 0.619554 | 49 | 19.933333 | 45 | starcoderdata |
static int WriteInitialHeaderMarker (TRI_datafile_t* datafile,
TRI_voc_fid_t fid,
TRI_voc_size_t maximalSize) {
// create the header
TRI_df_header_marker_t header;
TRI_InitMarkerDatafile((char*) &header, TRI_DF_MARKER_HEADER, sizeof(TRI_df_header_marker_t));
header.base._tick = (TRI_voc_tick_t) fid;
header._version = TRI_DF_VERSION;
header._maximalSize = maximalSize;
header._fid = fid;
// reserve space and write header to file
TRI_df_marker_t* position;
int res = TRI_ReserveElementDatafile(datafile, header.base._size, &position, 0);
if (res == TRI_ERROR_NO_ERROR) {
res = TRI_WriteCrcElementDatafile(datafile, position, &header.base, false);
}
return res;
} | c++ | 11 | 0.632184 | 96 | 34.636364 | 22 | inline |
@Override
public void preGetOp(ObserverContext<RegionCoprocessorEnvironment> e,
Get get, List<Cell> results) throws IOException {
// ^^ RegionObserverExample
LOG.debug("Got preGet for row: " + Bytes.toStringBinary(get.getRow()));
// vv RegionObserverExample
if (Bytes.equals(get.getRow(), FIXED_ROW)) { // co RegionObserverExample-1-Check Check if the request row key matches a well known one.
Put put = new Put(get.getRow());
put.addColumn(FIXED_ROW, FIXED_ROW, // co RegionObserverExample-2-Cell Create cell indirectly using a Put instance.
Bytes.toBytes(System.currentTimeMillis()));
CellScanner scanner = put.cellScanner();
scanner.advance();
Cell cell = scanner.current(); // co RegionObserverExample-3-Current Get first cell from Put using the CellScanner instance.
// ^^ RegionObserverExample
LOG.debug("Had a match, adding fake cell: " + cell);
// vv RegionObserverExample
results.add(cell); // co RegionObserverExample-4-Create Create a special KeyValue instance containing just the current time on the server.
}
} | java | 12 | 0.710692 | 144 | 57.631579 | 19 | inline |
def _check_test_linear3(self, ml):
""" Simple linear model (without any noise) """
df = ml.datasets.dataset
epsilon = 0.001
for xi in ['x1', 'x2', 'x3']:
self.assertTrue(abs(df[xi].mean()) < epsilon)
self.assertTrue(abs(df[xi].std() - 1) < epsilon)
# Check feature feature importance
fidf = ml.dataset_feature_importance.results.df
self.assertEqual('x1', fidf.index[0])
self.assertEqual('x2', fidf.index[1])
self.assertEqual('x3', fidf.index[2])
# Check model search results
mrdf = ml.model_results.df
modsearch_best = mrdf.index[0]
modsearch_first = mrdf.iloc[0]
self.assertTrue(modsearch_best.startswith("sklearn.linear_model.LinearRegression"))
self.assertEqual(modsearch_first.train, 0.0)
self.assertEqual(modsearch_first.validation, 0.0)
detailed_table_results_by_model = ml.dataset_feature_importance.detailed_table_results_by_model
self.assertTrue('RandomForest' in detailed_table_results_by_model.keys())
self.assertTrue('ExtraTrees' in detailed_table_results_by_model.keys())
self.assertTrue('GradientBoosting' in detailed_table_results_by_model.keys())
self.assertTrue('importance_permutation' in detailed_table_results_by_model['RandomForest'][0])
self.assertTrue('importance_dropcol' in detailed_table_results_by_model['RandomForest'][1])
self.assertTrue('importance_permutation' in detailed_table_results_by_model['ExtraTrees'][0])
self.assertTrue('importance_dropcol' in detailed_table_results_by_model['ExtraTrees'][1])
self.assertTrue('importance_permutation' in detailed_table_results_by_model['GradientBoosting'][0])
self.assertTrue('importance_dropcol' in detailed_table_results_by_model['GradientBoosting'][1]) | python | 15 | 0.677939 | 107 | 61.133333 | 30 | inline |
define( function () {
return '<div unselectable="on" class="fui-colorpicker-container">\n' +
'<div unselectable="on" class="fui-colorpicker-toolbar">\n' +
'<div unselectable="on" class="fui-colorpicker-preview"> +
'<div unselectable="on" class="fui-colorpicker-clear">$clearText +
' +
'<div unselectable="on" class="fui-colorpicker-title">$commonText +
'<div unselectable="on" class="fui-colorpicker-commoncolor">\n' +
'helper.forEach( commonColor, function ( index, colors ) {\n' +
'<div unselectable="on" class="fui-colorpicker-colors fui-colorpicker-colors-line$index">\n' +
'helper.forEach( colors, function( i, color ) {\n' +
'<span unselectable="on" class="fui-colorpicker-item" style="background-color: $color; border-color: #{color.toLowerCase() == \'#ffffff\' ? \'#eeeeee\': color};" data-color="$color"> +
'});\n' +
' +
'} );\n' +
' +
'<div unselectable="on" class="fui-colorpicker-title">$standardText +
'<div unselectable="on" class="fui-colorpicker-standardcolor fui-colorpicker-colors">\n' +
'helper.forEach( standardColor, function ( i, color ) {\n' +
'<span unselectable="on" class="fui-colorpicker-item" style="background-color: $color; border-color: $color;" data-color="$color"> +
'} );\n' +
' +
'
} ); | javascript | 25 | 0.672821 | 194 | 53.2 | 25 | starcoderdata |
import numpy as np
import matplotlib.pyplot as plt
from fealpy.mg.DarcyForchheimerP0P1 import DarcyForchheimerP0P1
from fealpy.mesh.adaptive_tools import mark
from fealpy.tools.show import showmultirate, show_error_table
from fealpy.pde.darcy_forchheimer_2d import LShapeRSinData
from fealpy.pde.darcy_forchheimer_2d import DarcyForchheimerdata1
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
box = [-1,1,-1,1]
mu = 1
rho = 1
beta = 10
alpha = 1/beta
tol = 1e-6
maxN = 2000
p = 1
n = 0
pde = LShapeRSinData (mu, rho, beta, alpha, tol, maxN)
mesh = pde.init_mesh(n)
integrator1 = mesh.integrator(p+2)
integrator0 = mesh.integrator(p+1)
theta = 0.35
errorType = ['$|| u - u_h||_0$','$|| p - p_h||$', '$||\\nabla p - \\nabla p_h||_0$']
maxit = 4
errorMatrix = np.zeros((len(errorType), maxit), dtype=np.float)
Ndof = np.zeros(maxit,dtype = np.int)
for i in range(maxit):
print('step:', i)
fem = DarcyForchheimerP0P1(pde, mesh, integrator0, integrator1)
fem.solve()
if i == 1:
break
# print(fem.solve())
NC = mesh.number_of_cells()
NN = mesh.number_of_edges()
Ndof[i] = 2*NC+NN
errorMatrix[0, i] = fem.get_uL2_error()
errorMatrix[1, i] = fem.get_pL2_error()
errorMatrix[2, i] = fem.get_H1_error()
# eta1
# eta2
# markedCell = mark(eta, theta=theta)
# if i < maxit -1:
# markedCell = mark(eta, theta=theta)
# mesh.bisect(markedCell)
#mesh.add_plot(plt, cellcolor='w')
#
#showmultirate(plt, 0, Ndof, errorMatrix, errorType)
#plt.show()
| python | 8 | 0.669713 | 84 | 26.357143 | 56 | research_code |
package ru.job4j.auto.web.user;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import ru.job4j.auto.model.User;
import ru.job4j.auto.service.UserService;
import ru.job4j.auto.to.UserTo;
import ru.job4j.auto.web.AuthorizedUser;
import ru.job4j.auto.web.DataController;
import ru.job4j.auto.web.converter.ModelConverter;
import javax.validation.Valid;
@RestController
@RequestMapping(value = AdminController.URL, produces = MediaType.APPLICATION_JSON_VALUE)
public class AdminController extends AbstractUserController {
public static final String URL = DataController.AJAX_URL + "/admin/users";
private final ModelConverter converter;
public AdminController(UserService service, ModelConverter converter) {
super(service);
this.converter = converter;
}
@PostMapping
public ResponseEntity create(@Valid User user, @AuthenticationPrincipal AuthorizedUser auth) {
User created = super.create(user);
UserTo to = converter.asUserTo(created, auth);
return ResponseEntity.created(to.getUrl()).contentType(MediaType.APPLICATION_JSON).body(to);
}
@PostMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void update(@PathVariable int id, @Valid User user) {
super.update(user, id);
}
@Override
@PutMapping("/{id}/enabled")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void enable(@PathVariable int id, @RequestBody boolean enabled) {
super.enable(id, enabled);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable int id, @AuthenticationPrincipal AuthorizedUser auth) {
super.delete(id);
if (auth.id() == id) {
SecurityContextHolder.clearContext();
}
}
} | java | 10 | 0.739472 | 106 | 35.627119 | 59 | starcoderdata |
module.exports = [
'supplier',
'preparer',
'collector',
'patentee',
'collector',
'inventor',
'depicted',
'sitter',
'subject',
'owner',
'recipient'
]; | javascript | 3 | 0.663934 | 71 | 16.428571 | 14 | starcoderdata |
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _possibleConstructorReturn from "@babel/runtime/helpers/esm/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/esm/getPrototypeOf";
import _get from "@babel/runtime/helpers/esm/get";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import { Layer, project32, picking } from '@deck.gl/core';
import { Model, Geometry } from '@luma.gl/core';
import vs from './arc-layer-vertex.glsl';
import fs from './arc-layer-fragment.glsl';
var DEFAULT_COLOR = [0, 0, 0, 255];
var defaultProps = {
getSourcePosition: {
type: 'accessor',
value: function value(x) {
return x.sourcePosition;
}
},
getTargetPosition: {
type: 'accessor',
value: function value(x) {
return x.targetPosition;
}
},
getSourceColor: {
type: 'accessor',
value: DEFAULT_COLOR
},
getTargetColor: {
type: 'accessor',
value: DEFAULT_COLOR
},
getWidth: {
type: 'accessor',
value: 1
},
getHeight: {
type: 'accessor',
value: 1
},
getTilt: {
type: 'accessor',
value: 0
},
greatCircle: false,
widthUnits: 'pixels',
widthScale: {
type: 'number',
value: 1,
min: 0
},
widthMinPixels: {
type: 'number',
value: 0,
min: 0
},
widthMaxPixels: {
type: 'number',
value: Number.MAX_SAFE_INTEGER,
min: 0
}
};
var ArcLayer = function (_Layer) {
_inherits(ArcLayer, _Layer);
function ArcLayer() {
_classCallCheck(this, ArcLayer);
return _possibleConstructorReturn(this, _getPrototypeOf(ArcLayer).apply(this, arguments));
}
_createClass(ArcLayer, [{
key: "getShaders",
value: function getShaders() {
return _get(_getPrototypeOf(ArcLayer.prototype), "getShaders", this).call(this, {
vs: vs,
fs: fs,
modules: [project32, picking]
});
}
}, {
key: "initializeState",
value: function initializeState() {
var attributeManager = this.getAttributeManager();
attributeManager.addInstanced({
instanceSourcePositions: {
size: 3,
type: 5130,
fp64: this.use64bitPositions(),
transition: true,
accessor: 'getSourcePosition'
},
instanceTargetPositions: {
size: 3,
type: 5130,
fp64: this.use64bitPositions(),
transition: true,
accessor: 'getTargetPosition'
},
instanceSourceColors: {
size: this.props.colorFormat.length,
type: 5121,
normalized: true,
transition: true,
accessor: 'getSourceColor',
defaultValue: DEFAULT_COLOR
},
instanceTargetColors: {
size: this.props.colorFormat.length,
type: 5121,
normalized: true,
transition: true,
accessor: 'getTargetColor',
defaultValue: DEFAULT_COLOR
},
instanceWidths: {
size: 1,
transition: true,
accessor: 'getWidth',
defaultValue: 1
},
instanceHeights: {
size: 1,
transition: true,
accessor: 'getHeight',
defaultValue: 1
},
instanceTilts: {
size: 1,
transition: true,
accessor: 'getTilt',
defaultValue: 0
}
});
}
}, {
key: "updateState",
value: function updateState(_ref) {
var props = _ref.props,
oldProps = _ref.oldProps,
changeFlags = _ref.changeFlags;
_get(_getPrototypeOf(ArcLayer.prototype), "updateState", this).call(this, {
props: props,
oldProps: oldProps,
changeFlags: changeFlags
});
if (changeFlags.extensionsChanged) {
var gl = this.context.gl;
if (this.state.model) {
this.state.model["delete"]();
}
this.setState({
model: this._getModel(gl)
});
this.getAttributeManager().invalidateAll();
}
}
}, {
key: "draw",
value: function draw(_ref2) {
var uniforms = _ref2.uniforms;
var viewport = this.context.viewport;
var _this$props = this.props,
widthUnits = _this$props.widthUnits,
widthScale = _this$props.widthScale,
widthMinPixels = _this$props.widthMinPixels,
widthMaxPixels = _this$props.widthMaxPixels,
greatCircle = _this$props.greatCircle;
var widthMultiplier = widthUnits === 'pixels' ? viewport.metersPerPixel : 1;
this.state.model.setUniforms(uniforms).setUniforms({
greatCircle: greatCircle,
widthScale: widthScale * widthMultiplier,
widthMinPixels: widthMinPixels,
widthMaxPixels: widthMaxPixels
}).draw();
}
}, {
key: "_getModel",
value: function _getModel(gl) {
var positions = [];
var NUM_SEGMENTS = 50;
for (var i = 0; i < NUM_SEGMENTS; i++) {
positions = positions.concat([i, 1, 0, i, -1, 0]);
}
var model = new Model(gl, Object.assign({}, this.getShaders(), {
id: this.props.id,
geometry: new Geometry({
drawMode: 5,
attributes: {
positions: new Float32Array(positions)
}
}),
isInstanced: true
}));
model.setUniforms({
numSegments: NUM_SEGMENTS
});
return model;
}
}]);
return ArcLayer;
}(Layer);
export { ArcLayer as default };
ArcLayer.layerName = 'ArcLayer';
ArcLayer.defaultProps = defaultProps;
//# sourceMappingURL=arc-layer.js.map | javascript | 30 | 0.583143 | 94 | 25.437209 | 215 | starcoderdata |
fn main() {
// We do argument parsing manually... which might not be the best idea,
// because it's annoying to extend it. It's probably the best to use `clap`
// or something like that from the very beginning.
let args: Vec<_> = std::env::args().skip(1).take(3).collect();
if args.len() != 2 {
Color::Red.with(|| {
println!("You have to specify the players as command line parameters!");
println!("");
println!(" ttt <cross-player> <circle-player>");
println!("");
println!("Player: one of 'human', 'random' or 'smart'.");
});
}
let mut cross = get_player(&args[0]).unwrap_or_else(|| process::exit(1));
let mut circle = get_player(&args[1]).unwrap_or_else(|| process::exit(1));
// Pass a mutable reference to the box contents into the main function
game::play(&mut *circle, &mut *cross);
} | rust | 15 | 0.584158 | 84 | 42.333333 | 21 | inline |
@Override
public String format(LogRecord log) {
String s = log.getMessage();
boolean isCoded = true;
int colon = s.indexOf(":");
if (colon >= 0) {
String preamble = s.substring(0, colon);
for (char c : preamble.toCharArray()) {
if (Character.isLowerCase(c))
isCoded = false;
}
}
if (isCoded || s.contains("<--") || s.contains("-->")) {
// strip and remember opcode
String opcode = s.substring(0, s.indexOf(" "));
// collect from ip address onwards
s = s.substring(s.indexOf("/") + 1);
// strip and remember ip address
String ip = s.substring(0, s.indexOf(" "));
// collect remainder of message
s = s.substring(s.indexOf(" ") + 1).trim();
if (opcode.equals("-->") || opcode.equals("<--")) {
s = String.format("%-15s %10s %s", ip, opcode,
s);
} else
s = String.format("%-15s %10s %s", ip,
opcode, s);
}
return String.format("%.80s%n", s);
} | java | 14 | 0.557188 | 59 | 30.8 | 30 | inline |
# TODO: move this file into ocfweb.component.session?
from urllib.parse import urlencode
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from ocflib.account.search import user_is_group
from ocfweb.component.session import is_logged_in
from ocfweb.component.session import logged_in_user
def login_required(function):
def _decorator(request, *args, **kwargs):
if is_logged_in(request):
return function(request, *args, **kwargs)
request.session['login_return_path'] = request.get_full_path()
return HttpResponseRedirect(reverse('login'))
return _decorator
def group_account_required(function):
def _decorator(request, *args, **kwargs):
try:
user = logged_in_user(request)
except KeyError:
user = None
if user and user_is_group(logged_in_user(request)):
return function(request, *args, **kwargs)
return render(
request, 'group_accounts_only.html', {
'user': user,
}, status=403,
)
return _decorator
def calnet_required(fn):
"""Decorator for views that require CalNet auth
Checks if "calnet_uid" is in the request.session dictionary. If the value
is not a valid uid, the user is rediected to CalNet login view.
"""
def wrapper(request, *args, **kwargs):
calnet_uid = request.session.get('calnet_uid')
if calnet_uid:
return fn(request, *args, **kwargs)
else:
return HttpResponseRedirect(
'{calnet_login}?{params}'.format(
calnet_login=reverse('calnet_login'),
params=urlencode({REDIRECT_FIELD_NAME: request.get_full_path()}),
),
)
return wrapper | python | 20 | 0.635086 | 85 | 29.492063 | 63 | starcoderdata |
#include <bits/stdc++.h>
#define loop(n) for (int ngtkana_is_genius = 0; ngtkana_is_genius < int(n); ngtkana_is_genius++)
#define rep(i, begin, end) for(int i = int(begin); i < int(end); i++)
#define lint long long
auto cmn = [](auto& a, auto b){if (a > b) {a = b; return true;} return false;};
auto cmx = [](auto& a, auto b){if (a < b) {a = b; return true;} return false;};
void debug_impl() { std::cerr << std::endl; }
template <typename Head, typename... Tail>
void debug_impl(Head head, Tail... tail){
std::cerr << " " << head;
debug_impl(tail...);
}
#define debug(...) std::cerr << std::boolalpha << "[" << #__VA_ARGS__ << "]:";\
debug_impl(__VA_ARGS__);\
std::cerr << std::noboolalpha;
template <typename Value, typename BinaryOp>
class valued_union_find_tree
{
int n;
std::vector<Value> table;
std::vector<int> prt;
BinaryOp op;
Value id;
public:
valued_union_find_tree (int n, BinaryOp op, Value id, Value init) :
n(n), table(n, init), prt(n, -1), op(op), id(id)
{}
bool is_root (int x) const {return prt.at(x) < 0;}
int size (int x) const {return -prt.at(find(x));}
bool same (int x, int y) const {return find(x) == find(y);}
int find (int x) const
{
while (!is_root(x)) x = prt.at(x);
return x;
}
auto collect () const {return prt;}
// Returns `true` if x and y are newly connected.
// y becomes the partent.
bool unite (int x, int y)
{
if ((x = find(x)) == (y = find(y))) return false;
if (size(x) > size(y)) std::swap(x, y);
prt.at(y) += prt.at(x);
prt.at(x) = y;
table.at(y) = op(table.at(y), table.at(x));
table.at(x) = id;
return true;
}
auto get (int x) const {return table.at(find(x));}
auto collect_vals () const
{
std::vector<Value> ret(n);
for (auto i = 0; i < n; i++)
{
ret.at(i) = get(i);
}
return ret;
}
void set (int x, Value val) {table.at(find(x)) = val;}
void add (int x, Value val) {set(x, get(x) + val);}
};
template <typename Value, typename BinaryOp>
auto make_valued_union_find_tree(int n, BinaryOp op, Value id, Value init)
{
return valued_union_find_tree<Value, BinaryOp>(n, op, id, init);
}
int main()
{
std::cin.tie(0); std::cin.sync_with_stdio(false);
int n, h, w;
std::cin >> n >> h >> w;
auto queries = std::vector<std::tuple<int, int, int>>(n);
rep(i, 0, n)
{
int x, y, a;
std::cin >> x >> y >> a;
x--, y--, y += h;
queries.at(i) = std::make_tuple(a, x, y);
}
auto uf = make_valued_union_find_tree
(
h + w,
[](auto x, auto y){return x + y + 1;},
0,
0
);
std::sort(queries.begin(), queries.end());
std::reverse(queries.begin(), queries.end());
auto sat = [&] (int x) -> bool
{
auto dif = uf.get(x) - uf.size(x);
assert(dif == -1 || dif == 0);
return dif == 0;
};
lint ret = 0;
for (auto tuple : queries)
{
int a, x, y;
std::tie(a, x, y) = tuple;
if (!uf.same(x, y) && (!sat(x) || !sat(y)))
{
uf.unite(x, y);
ret += a;
}
else if (uf.same(x, y) && !sat(x))
{
assert(!sat(y));
uf.set(y, uf.get(y) + 1);
ret += a;
}
}
std::cout << ret << std::endl;
return 0;
} | c++ | 15 | 0.524719 | 96 | 26.032787 | 122 | codenet |
package soot.jimple.infoflow.methodSummary.xml;
public class XMLMetaDataConstants {
// xml meta data summary tree
/*
* <summaryMetaData> <exclusiveModels> <exclusiveModel> </exclusiveModel> ...
* </exclusiveModels> </summaryMetaData>
*/
public static final String TREE_SUMMARY_META_DATA = "summaryMetaData";
public static final String TREE_EXCLUSIVE_MODELS = "exclusiveModels";
public static final String TREE_EXCLUSIVE_MODEL = "exclusiveModel";
public static final String ATTRIBUTE_FORMAT_VERSION = "fileFormatVersion";
public static final String ATTRIBUTE_TYPE = "type";
public static final String ATTRIBUTE_NAME = "name";
public static final String VALUE_CLASS = "class";
public static final String VALUE_PACKAGE = "package";
}
| java | 6 | 0.762983 | 78 | 36.55 | 20 | research_code |
//
// Basic scheme interpreter
//
// Copyright 2012 (
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "scheme.h"
symbols* scheme::vsymbols(NULL);
object* scheme::evaluate(object* exp, environment* env)
{
if (util::is_atom(exp))
{
if (exp == NULL || util::is_string(exp) || util::is_number(exp)) // constant
{
return exp;
}
else if (vsymbols->get((std::string)*((sstring*)exp)) != NULL) // symbol
{
return vsymbols->get((std::string)*((sstring*)exp));
}
else
{
return env->lookup((std::string)*((sstring*)exp));
}
}
else if (util::is // application
{
return apply((std::string)*((sstring*)((pair*)exp)->car), ((pair*)exp)->cdr, env);
}
else
{
throw scheme_exception(util::format("Unknown expression type -- %s.", ((std::string)*((sstring*)exp)).c_str()));
}
}
object* scheme::apply(std::string method, pair* arguments, environment *env)
{
if (vsymbols->get(method) != NULL && util::is
{
std::string specials[] = {"if", "define", "cond", "macro", "quote", "lambda"};
bool eval = array::index_of(specials, 6, method) == -1;
std::list args = scheme::va_list(arguments, env, eval);
return ((native*)vsymbols->get(method))->invoke(args, env);
}
else if (util::is
{
closure* proc = (closure*)env->lookup(method);
std::list args = scheme::va_list(arguments, env, true);
return proc->invoke(args, env);
}
/*else if (util::is
{
_macro* proc = (_macro*)env->lookup(method);
return proc->invoke(arguments, env);
}*/
else
{
throw scheme_exception(util::format("unknown procedure type -- %s", method.c_str()));
}
}
std::list scheme::va_list(pair *args, environment *env, bool eval)
{
if (args == NULL)
return std::list
object* car = eval ? evaluate(args->car, env) : args->car;
std::list lst;
lst.push_back(car);
std::list cdrs = scheme::va_list(args->cdr, env, eval);
while (cdrs.size() > 0) {
object* o = cdrs.front();
lst.push_back(o);
cdrs.pop_front();
}
return lst;
}
int scheme::read_input(std::istream *in, std::ostream *out, environment* env)
{
std::string exp = "";
while (!in->eof()) {
std::string input = "";
if (exp == "" && out != NULL) *out << "> ";
getline(*in, input);
for (int i = 0; i < input.length(); i++)
{
exp += input[i];
int lp = util::count(exp, '(');
int rp = util::count(exp, ')');
int qn = util::count(exp, '"');
if (lp == rp && (qn % 2) == 0 && exp.length() > 1)
{
try
{
object *result = scheme::evaluate(parser::parse(exp), env);
if (result != NULL && out != NULL)
*out << ">> " << result->to_string() << std::endl;
}
catch (scheme_exception& e) {
std::cerr << "exception: " << e.what() << std::endl;
}
exp = "";
}
else if (rp > lp)
{
std::cerr << "unexpected close-parenthesis." << std::endl;
exp = "";
}
}
}
if (!exp.empty()) {
std::cerr << "unexpected end in expression" << std::endl;
return -1;
}
return 0;
}
int main()
{
scheme::vsymbols = symbols::get_instance();
environment *env = new environment(std::list std::list NULL);
std::cout << "Scheme interpreter 0.010 by JLPC" << std::endl;
scheme::read_input(&std::cin, &std::cout, env);
delete env;
delete scheme::vsymbols;
return EXIT_SUCCESS;
} | c++ | 21 | 0.631031 | 114 | 26.387879 | 165 | starcoderdata |
public static void RemoveKeysInRange(AnimationCurve curve, float beginTime, float endTime)
{
// Loop backwards so key removals don't mess up order
for (int i = curve.length - 1; i >= 0; i--)
{
if (curve[i].time >= beginTime && curve[i].time < endTime)
{
curve.RemoveKey(i);
}
}
} | c# | 13 | 0.472019 | 90 | 36.454545 | 11 | inline |
## Discrete Choice Models Overview
from __future__ import print_function
import numpy as np
import statsmodels.api as sm
# ## Data
#
# Load data from Spector and Mazzeo (1980). Examples follow Greene's Econometric Analysis Ch. 21 (5th Edition).
spector_data = sm.datasets.spector.load()
spector_data.exog = sm.add_constant(spector_data.exog, prepend=False)
# Inspect the data:
print(spector_data.exog[:5,:])
print(spector_data.endog[:5])
# ## Linear Probability Model (OLS)
lpm_mod = sm.OLS(spector_data.endog, spector_data.exog)
lpm_res = lpm_mod.fit()
print('Parameters: ', lpm_res.params[:-1])
# ## Logit Model
logit_mod = sm.Logit(spector_data.endog, spector_data.exog)
logit_res = logit_mod.fit(disp=0)
print('Parameters: ', logit_res.params)
# Marginal Effects
margeff = logit_res.get_margeff()
print(margeff.summary())
# As in all the discrete data models presented below, we can print(a nice summary of results:
print(logit_res.summary())
# ## Probit Model
probit_mod = sm.Probit(spector_data.endog, spector_data.exog)
probit_res = probit_mod.fit()
probit_margeff = probit_res.get_margeff()
print('Parameters: ', probit_res.params)
print('Marginal effects: ')
print(probit_margeff.summary())
# ## Multinomial Logit
# Load data from the American National Election Studies:
anes_data = sm.datasets.anes96.load()
anes_exog = anes_data.exog
anes_exog = sm.add_constant(anes_exog, prepend=False)
# Inspect the data:
print(anes_data.exog[:5,:])
print(anes_data.endog[:5])
# Fit MNL model:
mlogit_mod = sm.MNLogit(anes_data.endog, anes_exog)
mlogit_res = mlogit_mod.fit()
print(mlogit_res.params)
# ## Poisson
#
# Load the Rand data. Note that this example is similar to Cameron and Trivedi's `Microeconometrics` Table 20.5, but it is slightly different because of minor changes in the data.
rand_data = sm.datasets.randhie.load()
rand_exog = rand_data.exog.view(float, type=np.ndarray).reshape(len(rand_data.exog), -1)
rand_exog = sm.add_constant(rand_exog, prepend=False)
# Fit Poisson model:
poisson_mod = sm.Poisson(rand_data.endog, rand_exog)
poisson_res = poisson_mod.fit(method="newton")
print(poisson_res.summary())
# ## Negative Binomial
#
# The negative binomial model gives slightly different results.
mod_nbin = sm.NegativeBinomial(rand_data.endog, rand_exog)
res_nbin = mod_nbin.fit(disp=False)
print(res_nbin.summary())
# ## Alternative solvers
#
# The default method for fitting discrete data MLE models is Newton-Raphson. You can use other solvers by using the ``method`` argument:
mlogit_res = mlogit_mod.fit(method='bfgs', maxiter=100)
print(mlogit_res.summary()) | python | 9 | 0.732342 | 180 | 23.454545 | 110 | starcoderdata |
"""
Définit page de l'appliation web qui affiche une carte des accidents, qu'on peut filtrer selon les conditions de lumière et les conditions atmosphériques
"""
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from apps.app import app
from datavisualization.affichage import Viewer
from data.transcription import transcription
vis = Viewer()
lum_dropdown = [{'label':i,'value':transcription['lum'].index(i)+1} for i in transcription['lum']]
lum_dropdown.insert(0,{'label':'Aucun','value':0})
atm_dropdown = [{'label':i,'value':transcription['atm'].index(i)+1} for i in transcription['atm']]
atm_dropdown.insert(0,{'label':'Aucun','value':0})
layout = html.Div([
html.H3('Carte des accidents en 2018',style={'margin-top':'30px'}),
html.Div([
html.Div([
html.Label("Année"),
dcc.Dropdown(
id='dropdown_carte',
options=[{'label':year,'value':year} for year in range(2005,2019)],
value=2018
)
]),
html.Div([
html.Label("Luminosité"),
dcc.Dropdown(id='lum_name',options=lum_dropdown,value=0),
]),
html.Div([
html.Label("Conditions atmosphériques"),
dcc.Dropdown(id='atm_name',options=atm_dropdown,value=0)
])
]),
dcc.Graph(id='carte_accidents')
])
@app.callback(
Output("carte_accidents","figure"),
[Input("dropdown_carte","value"),Input("lum_name","value"),Input('atm_name','value')])
def update_carte(year,filtre_lum,filtre_atm):
return vis.carte_accidents(year,{'atm':filtre_atm,'lum':filtre_lum}) | python | 19 | 0.636898 | 153 | 35.234043 | 47 | starcoderdata |
namespace PushSharp.Core
{
using System;
public interface IServiceConnectionFactory where TNotification : INotification
{
IServiceConnection Create();
}
} | c# | 6 | 0.75 | 97 | 21.909091 | 11 | starcoderdata |
package app
import (
"database/sql"
"fmt"
"strings"
)
type Hostinfo struct {
DBUser,
DBPassword,
DBName,
DBHost,
DBPort,
DBChar string
}
/**
连接数据库
*/
func connectMysql(host *Hostinfo) (db *sql.DB, err error) {
if host.DBPort == "" {
host.DBPort = "3306"
}
if host.DBChar == "" {
host.DBChar = "utf8"
}
if host.DBHost != "" {
host.DBHost = "tcp(" + host.DBHost + ":" + host.DBPort + ")"
}
dbStr := fmt.Sprintf("%s:%s@%s/%s?%s",
host.DBUser,
host.DBPassword,
host.DBHost,
host.DBName,
host.DBChar,
)
db, err = sql.Open("mysql", dbStr)
return
}
/**
数据库字段批量加前缀
*/
func FieldAddPrev(prev, fieldStr string) string {
fieldArr := strings.Split(fieldStr, ",")
prev = prev + "."
var newFieldArr []string
for _, v := range fieldArr {
newFieldArr = append(newFieldArr, prev+v)
}
newFieldStr := strings.Join(newFieldArr, ",")
return newFieldStr
} | go | 12 | 0.62183 | 62 | 13.868852 | 61 | starcoderdata |
// **************************************** Lavio Engine ****************************************
// **************************** Copyright (c) 2017 All Rights Reserved **************************
// ***************************** ( **************************
//#include "../stdafx.h"
#include "../Source/IO/Utilities/FileUtility.cpp"
#include "../OpenGL.h"
#include "GLShader.h"
#include "../../Debug/Debugging/Log.h"
#include
namespace Lavio
{
namespace OpenGL
{
namespace Graphics
{
GLShader::GLShader(const char *vertPath, const char *fragPath) :
IShader(vertPath, fragPath)
{
mShaderID = GLShader::Load();
}
GLShader::~GLShader()
{
glDeleteProgram(mShaderID);
}
unsigned int GLShader::Load()
{
GLuint program = glCreateProgram();
GLuint vertex = glCreateShader(GL_VERTEX_SHADER);
GLuint fragment = glCreateShader(GL_FRAGMENT_SHADER);
std::string vertSourceString = IO::FileUtility::ReadFile(mVertPath);
std::string fragSourceString = IO::FileUtility::ReadFile(mFragPath);
const char *vertSource = vertSourceString.c_str();
const char *fragmentSource = fragSourceString.c_str();
//load vertex shader
glShaderSource(vertex, 1, &vertSource, nullptr);
glCompileShader(vertex);
GLint result;
glGetShaderiv(vertex, GL_COMPILE_STATUS, &result);
if (result == GL_FALSE)
{
GLint length;
glGetShaderiv(vertex, GL_INFO_LOG_LENGTH, &length);
std::vector error(length);
glGetShaderInfoLog(vertex, length, &length, &error[0]);
std::string *text = new std::string("Shader Error -> Failed to compile vertex shader! /n");
text->append(&error[0]);
Log::DebugLog(text, true);
glDeleteShader(vertex);
return 0;
}
//load fragment shader
glShaderSource(fragment, 1, &fragmentSource, nullptr);
glCompileShader(fragment);
glGetShaderiv(fragment, GL_COMPILE_STATUS, &result);
if (result == GL_FALSE)
{
GLint length;
glGetShaderiv(fragment, GL_INFO_LOG_LENGTH, &length);
std::vector error(length);
glGetShaderInfoLog(fragment, length, &length, &error[0]);
std::string *text = new std::string("Shader Error -> Failed to compile fragment shader! /n");
text->append(&error[0]);
Log::DebugLog(text, true);
glDeleteShader(fragment);
return 0;
}
//attach shaders to program
glAttachShader(program, vertex);
glAttachShader(program, fragment);
glLinkProgram(program);
glValidateProgram(program);
//clean up
glDeleteShader(vertex);
glDeleteShader(fragment);
std::string *text = new std::string("Success Loading Shader : ");
text->append(std::to_string(program));
Log::DebugLog(text, true);
return program;
}
int GLShader::GetUniformLocation(const char *name)
{
return glGetUniformLocation(GLuint(mShaderID), name);
}
void GLShader::SetUniform(const char *name, float value)
{
glUniform1f(GLint(GetUniformLocation(const_cast value);
}
void GLShader::SetUniform(const char *name, int value)
{
glUniform1i(GLint(GetUniformLocation(const_cast value);
}
void GLShader::SetUniform(const char *name, const Vector2 &value)
{
glUniform2f(GLint(GetUniformLocation(const_cast value.x, value.y);
}
void GLShader::SetUniform(const char *name, const Vector3 &value)
{
glUniform3f(GLint(GetUniformLocation(const_cast value.x, value.y, value.z);
}
void GLShader::SetUniform(const char *name, const Vector4 &value)
{
glUniform4f(GLint(GetUniformLocation(const_cast value.x, value.y, value.z, value.w);
}
void GLShader::SetUniform(const char *name, const Matrix4x4 &matrix)
{
glUniformMatrix4fv(GLint(GetUniformLocation(const_cast 1, GL_FALSE, matrix.elements);
}
void GLShader::SetUniform(const char *name, float *values, int count)
{
glUniform1fv(GetUniformLocation(name), count, values);
}
void GLShader::SetUniform(const char *name, int *values, int count)
{
glUniform1iv(GetUniformLocation(name), count, values);
}
void GLShader::Enable() const
{
glUseProgram(GLuint(mShaderID));
}
void GLShader::Disable() const
{
glUseProgram(0);
}
}
}
} | c++ | 21 | 0.642857 | 107 | 27.632258 | 155 | starcoderdata |
#ifndef LITE_WINDOW_H
#define LITE_WINDOW_H
class LiteWindow {
public:
LiteWindow() {}
virtual ~LiteWindow() {}
int IsValid() { return 0; }
void MakeCurrent() {}
void Create(int x = -1, int y = -1, const char* display = NULL) {}
};
#endif | c | 9 | 0.68125 | 68 | 21.857143 | 14 | starcoderdata |
package liquibase.configuration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* This wraps all the {@link ProvidedValue}s to return the overall value returned from the collection of {@link ConfigurationValueProvider}s.
* Returned by {@link LiquibaseConfiguration#getCurrentConfiguredValue(ConfigurationValueConverter, ConfigurationValueObfuscator, String...)}
*/
public class ConfiguredValue {
private static final NoValueProvider NO_VALUE_PROVIDER = new NoValueProvider();
private final List providedValues = new ArrayList<>();
private final String key;
private final ConfigurationValueObfuscator valueObfuscator;
private final ConfigurationValueConverter valueConverter;
protected ConfiguredValue(String key, ConfigurationValueConverter converter, ConfigurationValueObfuscator obfuscator) {
this.key = key;
this.valueObfuscator = obfuscator;
if (converter == null) {
this.valueConverter = (value -> (DataType) value);
} else {
this.valueConverter = converter;
}
}
public DataType getValue() {
final ProvidedValue providedValue = getProvidedValue();
if (providedValue == null) {
return null;
}
return valueConverter.convert(providedValue.getValue());
}
public DataType getValueObfuscated() {
final DataType rawValue = getValue();
if (valueObfuscator != null) {
return valueObfuscator.obfuscate(rawValue);
}
return rawValue;
}
/**
* Returns the "winning" value across all the possible {@link ConfigurationValueProvider}.
* A {@link ProvidedValue} is always returned, even if the value was not configured.
*
* @see #found()
*/
public ProvidedValue getProvidedValue() {
return getProvidedValues().get(0);
}
public boolean wasDefaultValueUsed() {
for (ProvidedValue providedValue : this.getProvidedValues()) {
if (providedValue.getProvider() != null && providedValue.getProvider() instanceof ConfigurationDefinition.DefaultValueProvider) {
return true;
}
}
return false;
}
/**
* Replaces the current configured value with a higher-precedence one.
* If a null value is passed, do nothing.
*/
public void override(ProvidedValue details) {
if (details == null) {
return;
}
this.providedValues.add(0, details);
}
/**
* @return a full list of where the configuration value was set and/or overridden.
*/
public List getProvidedValues() {
if (providedValues.size() == 0) {
return Collections.singletonList(NO_VALUE_PROVIDER.getProvidedValue(new String[] {key}));
}
return Collections.unmodifiableList(providedValues);
}
/**
* @return true if a value was found across the providers.
*/
public boolean found() {
return providedValues.size() > 0;
}
/**
* Used to track configuration with no value set
*/
private static final class NoValueProvider extends AbstractConfigurationValueProvider {
@Override
public int getPrecedence() {
return -1;
}
@Override
public ProvidedValue getProvidedValue(String... keyAndAliases) {
return new ProvidedValue(keyAndAliases[0], keyAndAliases[0], null, "No configured value found", this);
}
}
} | java | 14 | 0.655697 | 143 | 31 | 113 | starcoderdata |
/* Copied from http://web.engr.oregonstate.edu/~mjb/cs575/Projects/proj01.html */
#include "settings.h"
#define Z00 0.
#define Z10 1.
#define Z20 0.
#define Z30 0.
#define Z01 1.
#define Z11 6.
#define Z21 1.
#define Z31 0.
#define Z02 0.
#define Z12 1.
#define Z22 0.
#define Z32 4.
#define Z03 3.
#define Z13 2.
#define Z23 3.
#define Z33 3.
float
Height(int iu, int iv) // iu,iv = 0 .. NUMS-1
{
float u = (float) iu / (float) (NUMS - 1);
float v = (float) iv / (float) (NUMS - 1);
// the basis functions:
float bu0 = (1. - u) * (1. - u) * (1. - u);
float bu1 = 3. * u * (1. - u) * (1. - u);
float bu2 = 3. * u * u * (1. - u);
float bu3 = u * u * u;
float bv0 = (1. - v) * (1. - v) * (1. - v);
float bv1 = 3. * v * (1. - v) * (1. - v);
float bv2 = 3. * v * v * (1. - v);
float bv3 = v * v * v;
// finally, we get to compute something:
float height = bu0 * (bv0 * Z00 + bv1 * Z01 + bv2 * Z02 + bv3 * Z03)
+ bu1 * (bv0 * Z10 + bv1 * Z11 + bv2 * Z12 + bv3 * Z13)
+ bu2 * (bv0 * Z20 + bv1 * Z21 + bv2 * Z22 + bv3 * Z23)
+ bu3 * (bv0 * Z30 + bv1 * Z31 + bv2 * Z32 + bv3 * Z33);
return height;
} | c++ | 14 | 0.470032 | 81 | 23.862745 | 51 | starcoderdata |
def table_example():
"""Demonstration function that creates and populates a table object.
This function is for demonstration purposes only; it shows
the basics of how to make and output a table. It creates
a new table object, names it, populates some columns of data
and then adds some graph definitions before outputting the
formatted table to stdout."""
print "\nExample making a new table from scratch:\n"
# Make a new (empty) table object
tbl = table("A table with random data")
# Add three columns called "x", "x^2" and "1/x"
tbl.addcolumn("x")
tbl.addcolumn("x^2")
tbl.addcolumn("1/x")
# Add some rows of data
for i in range(0,10):
row = dict()
row["x"] = i
row["x^2"] = i*i
if i != 0:
row["1/x"] = 1.0/float(i)
else:
row["1/x"] = "?"
tbl.add_data(row)
# Define some graphs
tbl.definegraph("Y = X(squared)",("x","x^2"))
tbl.definegraph("Y = 1/X",("x","1/x"))
tbl.definegraph("All data",("x","x^2","1/x"))
# Print out the data as a simple "table" and in loggraph markup
print tbl.show()
print tbl.loggraph() | python | 12 | 0.63894 | 70 | 32.181818 | 33 | inline |
const asks = [
{ price: 34, amount: 89 },
{ price: 34, amount: 89 },
{ price: 89, amount: 76 },
];
const bids = [
{ price: 34, amount: 89 },
{ price: 34, amount: 89 },
{ price: 89, amount: 76 },
];
export { asks, bids }; | javascript | 5 | 0.594771 | 70 | 20.857143 | 14 | starcoderdata |
using System;
using System.Web.Http;
using System.Collections.Generic;
namespace ClassesAndInterfaces
{
public class WeaponsController : ApiController
{
IWeaponRepository weaponRepository;
public WeaponsController (IWeaponRepository weaponRepository)
{
this.weaponRepository = weaponRepository;
}
[Route("weapons")]
public IHttpActionResult GetAllWeapons()
{
IEnumerable allweapons = this.weaponRepository.GetAll();
return Ok(allweapons);
}
[Route("weapons/{weaponid}/getrandomdamage")]
public IHttpActionResult GetRandomDamageForWeapon(int weaponid)
{
return Ok(this.weaponRepository.GetWeapon(weaponid).GetRandomDamage());
}
}
} | c# | 17 | 0.655431 | 83 | 25.7 | 30 | starcoderdata |
/*****************************************************************************
FreqSplitter5.h
Author: 2016
The group delay depends on the splitting frequency. Approximate figures:
GD(<fsplit) is close to fs / (fsplit * 2) samples
GD(~fsplit) doubles relatively to GD(~DC)
GD(>fsplit) gets down quickly to almost 0.
--- Legal stuff ---
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://sam.zoy.org/wtfpl/COPYING for more details.
*Tab=3***********************************************************************/
#pragma once
#if ! defined (mfx_pi_cdsp_FreqSplitter5_HEADER_INCLUDED)
#define mfx_pi_cdsp_FreqSplitter5_HEADER_INCLUDED
#if defined (_MSC_VER)
#pragma warning (4 : 4250)
#endif
/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
#include "mfx/dsp/iir/SplitAp5.h"
#include "mfx/piapi/PluginInterface.h"
#include
namespace mfx
{
namespace pi
{
namespace cdsp
{
class FreqSplitter5
{
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
public:
void clear_buffers ();
void set_sample_freq (double sample_freq);
void set_split_freq (float freq);
void copy_z_eq (const FreqSplitter5 &other);
void process_block (int chn, float dst_l_ptr [], float dst_h_ptr [], const float src_ptr [], int nbr_spl);
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
protected:
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
private:
typedef std::array <
dsp::iir::SplitAp5, piapi::PluginInterface::_max_nbr_chn
> SplitArray;
SplitArray _band_split_arr; // One per channel
/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
private:
bool operator == (const FreqSplitter5 &other) const = delete;
bool operator != (const FreqSplitter5 &other) const = delete;
}; // class FreqSplitter5
} // namespace cdsp
} // namespace pi
} // namespace mfx
//#include "mfx/pi/cdsp/FreqSplitter5.hpp"
#endif // mfx_pi_cdsp_FreqSplitter5_HEADER_INCLUDED
/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ | c | 18 | 0.533603 | 117 | 21.454545 | 110 | starcoderdata |
Subsets and Splits