code
stringlengths 0
29.6k
| language
stringclasses 9
values | AST_depth
int64 3
30
| alphanumeric_fraction
float64 0.2
0.86
| max_line_length
int64 13
399
| avg_line_length
float64 5.02
139
| num_lines
int64 7
299
| source
stringclasses 4
values |
---|---|---|---|---|---|---|---|
package util
import (
"regexp"
"strings"
)
const (
// UUIDPattern is regex of UUID
UUIDPattern = "^[0-9a-f]{8}(-[0-9a-f]{4}){4}[0-9a-f]{8}$"
// MD5Pattern is regex for md5
MD5Pattern = "^[a-f0-9]{32}$"
)
// IsValidString will check if string in string pointer is valid
func IsValidString(str *string) bool {
if str == nil {
return false
}
if strings.Trim(*str, " ") == "" {
return false
}
return true
}
// IsValidUUID will check if string is standard uuid or not
func IsValidUUID(str string) bool {
match, _ := regexp.MatchString(UUIDPattern, str)
return match
}
// IsValidMD5 will check if string is standard md5 or not
func IsValidMD5(str string) bool {
match, _ := regexp.MatchString(MD5Pattern, str)
return match
}
// IsInSlice will check if check is in container or not
func IsInSlice(check interface{}, container []interface{}) bool {
for _, v := range container {
if v == check {
return true
}
}
return false
} | go | 9 | 0.673554 | 65 | 19.595745 | 47 | starcoderdata |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class UserManager extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('userAccount_model');
}
public function index()
{
$users = $this->userAccount_model->getAllUser(0);
$count = count($users);
$users = array(
'allusers' => $users,
'num_users' => $count
);
$this->load->view('userManager_view', $users, FALSE);
}
public function addUser()
{
$user_name = addslashes($this->input->post('username'));
$fullname = addslashes($this->input->post('full_name'));
$gender = addslashes($this->input->post('gender'));
$email = addslashes($this->input->post('email'));
if($this->input->post('permission') != null){
$permission = 1;
} else {
$permission = 0;
}
$password = md5(addslashes($this->input->post('password')));
$rePassword = md5(addslashes($this->input->post('re_password')));
$check1 = $this->userAccount_model->checkEmailExists($email);
$check2 = $this->userAccount_model->checkUserExists($user_name);
if($password != $rePassword){
echo ' khẩu không trùng khớp!")
redirect($_SERVER['HTTP_REFERER'],'refresh');
} else {
if ($check1) {
echo ' đã tồn tại!")
redirect($_SERVER['HTTP_REFERER'],'refresh');
}
if ($check2){
echo ' đã tồn tại!")
redirect($_SERVER['HTTP_REFERER'],'refresh');
}
if (!$check1 && !$check2 ){
$result = $this->userAccount_model->addAccountToDatabase($user_name, $gender, $email, $fullname, $password, $permission);
if($result){
echo ' successfully!")
redirect(base_url(). 'UserManager','refresh');
}
}
}
}
public function findUser()
{
$name = $this->input->post('keyword');
$permission = $this->input->post('permission');
$result = array();
if($name == ''){
$result = $this->userAccount_model->getAllUser($permission);
} else {
$result = $this->userAccount_model->findUserByName($name, $permission);
}
$result = json_encode($result);
echo $result;
}
public function deleteUser()
{
$user_id = $this->input->post('user_id');
$this->userAccount_model->deleteUser($user_id);
}
public function editUser($user_id)
{
$data = $this->userAccount_model->getUserDetail($user_id);
$this->load->view('editUser_view', $data[0], FALSE);
}
public function saveChange($user_id)
{
$full_name = $this->input->post('full_name');
$user_name = $this->input->post('username');
$gender = $this->input->post('gender');
$email = $this->input->post('email');
$permission = $this->input->post('permission');
$avatar = $this->input->post('avatar');
if($this->userAccount_model->saveUser($user_id, $full_name, $user_name, $gender, $email, $permission, $avatar)){
echo ' changes are saved!")
redirect(base_url(). 'UserManager','refresh');
} else {
echo ' or username existed!")
redirect(base_url().'UserAccount/editUser/' . $user_id ,'refresh');
}
}
}
/* End of file UserManager.php */
/* Location: ./application/controllers/UserManager.php */ | php | 19 | 0.60292 | 137 | 30.431193 | 109 | starcoderdata |
package main
import (
"fmt"
"nss/xncs/chainmaker/sdkop"
sdk "chainmaker.org/chainmaker-sdk-go"
"sync"
"time"
"strconv"
"flag"
)
func Init(){
//1. 注册转账智能合约
sdkop.ContractInstance()
//2. 注册新用户
sdkop.RegisterUser();
}
func Invoke(){
//fmt.Println("====================== 3)查询钱包地址 ======================")
addr1 := sdkop.UserContractAssetQuery(sdkop.Client1,sdkop.Client2,true) //true 为1 ,else 0
//fmt.Printf("client1 address: %s\n", addr1)
addr2 := sdkop.UserContractAssetQuery(sdkop.Client1,sdkop.Client2,false)
//fmt.Printf("client2 address: %s\n", addr2)
//fmt.Println("====================== 给用户分别发币10000000 ======================")
amount := "10000000"
sdkop.UserContractAssetInvoke(sdkop.Client1,"issue_amount", amount, addr1, true)
sdkop.UserContractAssetInvoke(sdkop.Client1,"issue_amount", amount, addr2, true)
//fmt.Printf("%v 余额 %v\n",addr1,sdkop.GetBalance(addr1))
//fmt.Printf("%v 余额 %v\n",addr1,sdkop.GetBalance(addr2))
sdkop.UserContractAssetInvoke(sdkop.Client1,"transfer", "100", addr2, true)
//fmt.Printf("%v 余额 %v\n",addr1,sdkop.GetBalance(addr1))
//fmt.Printf("%v 余额 %v\n",addr1,sdkop.GetBalance(addr2))
//fmt.Printf("hello")
}
func init(){
}
var Max_Count = 10000 //循环次数 每个并发循环次数
const MAX_CONNECT = 100 //连接网关数 并发数
var wg = sync.WaitGroup{}
//0 不需要,1需要
var winit=flag.Int("init",0,"是否需要初始化(安装链码,注册用户)")
var winvoke=flag.Int("invoke",0,"是否需要测试链码调用")
var wtest=flag.Int("test",1,"性能测试")
func invoceChaincode(client1,client2 *sdk.ChainClient){
//addr1 := sdkop.UserContractAssetQuery(true) //true 为node1 ,else node0
//fmt.Printf("client1 address: %s\n", addr1)
addr2 := sdkop.UserContractAssetQuery(client1,client2,false)
for i := 0; i < Max_Count; i++ {
sdkop.UserContractAssetInvoke(client1,"transfer", "1", addr2, false) //最后一个参数为是否同步获取交易结果?
}
wg.Done()
}
func TpsTest(){
clients1:=make([]*sdk.ChainClient,MAX_CONNECT)
clients2:=make([]*sdk.ChainClient,MAX_CONNECT)
for i:=0;i<MAX_CONNECT;i++{
clients1[i]=sdkop.Connect_chain(1)
clients2[i]=sdkop.Connect_chain(2)
}
fmt.Println("============ application-golang starts ============")
wg.Add(MAX_CONNECT)
for i := 0; i < MAX_CONNECT; i++ {
go invoceChaincode(clients1[i],clients2[i])
}
timeStart := time.Now().UnixNano()
wg.Wait()
timeCount := Max_Count * MAX_CONNECT
timeEnd := time.Now().UnixNano()
count := float64(timeCount)
timeResult := float64((timeEnd-timeStart)/1e6) / 1000.0
fmt.Println("Throughput:", timeCount, "Duration:", strconv.FormatFloat(timeResult, 'g', 30, 32)+" s", "TPS:", count/timeResult)
}
func main(){
flag.Parse()
if 1==*winit {
Init()
}
if 1==*winvoke{
Invoke()
}
if 1==*wtest{
TpsTest()
}
} | go | 11 | 0.658981 | 128 | 24.377358 | 106 | starcoderdata |
using DataStructures;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DSA.UnitTests.LinkedList.RemoveLast
{
[TestFixture]
public class RemoveLastShould
{
[Test]
public void RemoveTheLastelement()
{
var list = new MyLinkedList
var firstNode = new Node { Value = 3 };
var secondNode = new Node { Value = 4 };
list.Append(firstNode);
list.Append(secondNode);
list.RemoveLast();
Assert.AreSame(list.Head, firstNode);
Assert.AreEqual(list.Count, 1);
}
}
} | c# | 15 | 0.603542 | 59 | 23.466667 | 30 | starcoderdata |
<?php foreach($services as $service):?>
<a href="
<div class="col-md-3 col-sm-6 col-xs-12 col-2">
<div class="service-wrap">
<i class="fa fa-building">
<?php endforeach; ?> | php | 6 | 0.438596 | 90 | 37.066667 | 15 | starcoderdata |
package com.revolsys.core.test.geometry.test.model;
import org.junit.Test;
import com.revolsys.testapi.GeometryAssert;
public class MultiPolygonTest {
@Test
public void testFromFile() {
GeometryAssert.doTestGeometry(getClass(), "MultiPolygon.csv");
}
} | java | 10 | 0.7603 | 66 | 19.538462 | 13 | starcoderdata |
import bl2sdk
class CritOnly(bl2sdk.BL2MOD):
Name = "Crits Only"
Description = "Only crits deal damage.\nEnemies that do not have a crit spot still can normally be damaged.\nWritten by Juso"
def HandleDamage(self, caller, function, params):
#check if the damaged target actually has a crit spot
if any(str(tmp.bCriticalHit)=="True" for tmp in caller.BodyClass.HitRegionList):
#let the game decide where we hit the target
HitInfo = (params.HitInfo.Material, params.HitInfo.PhysMaterial, params.HitInfo.Item, params.HitInfo.LevelIndex, params.HitInfo.BoneName, params.HitInfo.HitComponent)
BodyHitRegionDefinition = caller.GetHitRegionForTakenDamage(params.InstigatedBy, HitInfo)
#if the hit bodyregion is a crit spot return true -> deal damage
if str(BodyHitRegionDefinition.bCriticalHit) == "True":
return True
else:
return False
#If the damaged enemy doesent have any critspots, then deal damage
return True
def Enable(self):
bl2sdk.RegisterHook("WillowGame.WillowPawn.TakeDamage", "TakeDamageHook", DamageHook)
def Disable(self):
bl2sdk.RemoveHook("WillowGame.WillowPawn.TakeDamage", "TakeDamageHook")
CritOnlyInstance = CritOnly()
def DamageHook(caller: bl2sdk.UObject, function: bl2sdk.UFunction, params: bl2sdk.FStruct) -> bool:
return CritOnlyInstance.HandleDamage(caller, function, params)
bl2sdk.Mods.append(CritOnlyInstance) | python | 12 | 0.713733 | 178 | 43.314286 | 35 | starcoderdata |
def Remove(self):
"""Remove the rbd device.
"""
rbd_pool = self.params[constants.LDP_POOL]
rbd_name = self.unique_id[1]
if not self.minor and not self.Attach():
# The rbd device doesn't exist.
return
# First shutdown the device (remove mappings).
self.Shutdown()
# Remove the actual Volume (Image) from the RADOS cluster.
cmd = self.__class__.MakeRbdCmd(self.params, ["rm", "-p", rbd_pool,
rbd_name])
result = utils.RunCmd(cmd)
if result.failed:
base.ThrowError("Can't remove Volume from cluster with rbd rm: %s - %s",
result.fail_reason, result.output) | python | 9 | 0.577424 | 78 | 31.952381 | 21 | inline |
package com.clayton.crud;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private SQLiteDatabase db = null;
private SimpleCursorAdapter adt = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Criar Banco Dados
db = openOrCreateDatabase("crud.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
String clientes = "CREATE TABLE IF NOT EXISTs clientes (_id INTEGER PRIMARY KEY autoincrement, " +
"nome text, email text)";
db.execSQL(clientes);
try {
//Testa a conexão com banco
/*AlertDialog.Builder dlg = new AlertDialog.Builder(this);
dlg.setMessage("Banco Criado com sucesso! ");
dlg.setNeutralButton("Ok", null);
dlg.show();*/
} catch (SQLException ex) {
AlertDialog.Builder dlg = new AlertDialog.Builder(this);
dlg.setMessage("Erro ao criar o banco! " + ex.getMessage());
dlg.setNeutralButton("Ok", null);
dlg.show();
}
Button btnCliente = (Button) findViewById(R.id.btn_cliente);
btnCliente.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getBaseContext(), CadastroActivity.class));
}
});
final EditText txtBusca = (EditText) findViewById(R.id.txtBuscar);
txtBusca.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
//Preecher Listview
String[] busca = new String[]{"%" + txtBusca.getText().toString() + "%"};
Cursor cursor = db.query("clientes", new String[]{"_id", "nome", "email"}, " nome LIKE ?", busca, null, null, "_id ASC", null);
adt.changeCursor(cursor);
return false;
}
});
}
@Override
public void onResume(){
super.onResume();
// Preencher o ListView
Cursor cursor = db.rawQuery("SELECT _id, nome, email FROM clientes ORDER BY _id ASC", null);
String[] campos = {"_id", "nome"};
int[] ids = {R.id.txvID, R.id.txvNOME};
adt = new SimpleCursorAdapter(getBaseContext(), R.layout.model_clientes, cursor, campos, ids, 0);
ListView ltwDados = (ListView) findViewById(R.id.ltw_dados);
ltwDados.setAdapter(adt);
ltwDados.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView adapterView, View view, int position, long id) {
Cursor retornaCursosr = (Cursor) adt.getItem(position);
Intent it = new Intent(getBaseContext(), EditarActivity.class);
it.putExtra("codigo", retornaCursosr.getInt(0));
it.putExtra("nome", retornaCursosr.getString(1));
it.putExtra("email", retornaCursosr.getString(2));
startActivity(it);
}
});
}
} | java | 21 | 0.612003 | 143 | 36.99 | 100 | starcoderdata |
func (d *Dispenser) Get(ctx context.Context, namespace, name string, gvk schema.GroupVersionKind) (*Turbinado, error) {
lister, err := d.getLister(ctx, gvk)
if err != nil {
return nil, err
}
// Get the duck resource with this namespace/name
runtimeObj, err := lister.ByNamespace(namespace).Get(name)
if err != nil {
logging.FromContext(ctx).Errorw("unable to get duck type", zap.String("gvk", gvk.String()), zap.String("key", namespace+"/"+name))
return nil, err
}
var ok bool
var resource kmeta.OwnerRefable
if resource, ok = runtimeObj.DeepCopyObject().(kmeta.OwnerRefable); !ok {
return nil, errors.New("runtime object is not convertible to kmeta.OwnerRefable type")
}
return &Turbinado{
Resource: resource,
Prefix: d.prefix,
}, nil
} | go | 13 | 0.707953 | 132 | 31 | 24 | inline |
<?php
/*
FELICITY BANK PORT - DSJAS
==========================
Welcome to the DSJAS theme port of Felicity Bank!
Felicity bank is an open source and free template for making
fake banking sites. This port is an exact replica of the site
ported to the DSJAS theme API, allowing for dynamically changing
the name, branding etc.
Almost nothing has been changed about the original, but some features
had to be removed due to their conflict with existing modules or
other plugins.
Please check out the Felicity Bank GitHub page here: https://github.com/0xB9/Felicity-Bank-Inc.
For more information of theming and creating your own themes, please refer to the
API documentation for themes and plugins.
*/
require_once THEME_API . "General.php";
require_once THEME_API . "Accounts.php";
?>
<nav class="navbar navbar-expand-sm navbar-light bg-light border" style="height: 8vh; width: 100%;">
<div class="container">
<a href="/" class="navbar-brand"><?php echo getBankName(); ?>
<button class="navbar-toggler" data-toggle="collapse" data-target="#navbarMenu">
<span class="navbar-toggler-icon">
<div class="collapse navbar-collapse" id="navbarMenu">
<ul class="navbar-nav ml-auto">
<li class="nav-link">
<a href="/About">About Us
<li class="nav-link">
<a href="/Invest">Investing
<li class="nav-link">
<a href="https://en.wikipedia.org/wiki/Technical_support_scam" target="_blank">Report Fraud
<li class="nav-link">
<a href="/Contact">Contact
<?php if (shouldAppearLoggedIn()) { ?>
<li class="nav-link">
<a href="/user/Logout?logout=1">Logout
<?php } ?>
<?php addModuleDescriptor("nav-items"); ?>
<?php addModuleDescriptor("navbar"); ?>
<div style="height: 3vh;"> | php | 6 | 0.568816 | 115 | 32.661538 | 65 | starcoderdata |
auto FilterSDLEvent(const SDL_Event* event) -> int {
try {
// If this event is coming from this thread, handle it immediately.
if (std::this_thread::get_id() == g_app_globals->main_thread_id) {
auto app = static_cast_check_type<SDLApp*>(g_app);
assert(app);
if (app) {
app->HandleSDLEvent(*event);
}
return false; // We handled it; sdl doesn't need to keep it.
} else {
// Otherwise just let SDL post it to the normal queue.. we process this
// every now and then to pick these up.
return true; // sdl should keep this.
}
} catch (const std::exception& e) {
BA_LOG_ONCE(std::string("Exception in inline SDL-Event handling: ")
+ e.what());
throw;
}
} | c++ | 14 | 0.596282 | 77 | 34.904762 | 21 | inline |
export default {
warehouseTypes: [
{
value: 1,
label: '中心仓'
},
{
value: 2,
label: '门店仓'
}
],
wmsSwitch: [
{ value: 1, label: '是' },
{ value: 0, label: '否' }
],
mappingAssignTypes: [
{
value: 1,
label: '按比例'
},
{
value: 3,
label: '共享'
}
],
showCategoryOptions: [
{
value: 1,
label: '后台类目'
},
{
value: 2,
label: '前台类目'
},
{
value: 4,
label: '商家类目'
},
{
value: 6,
label: '店铺类目'
}
],
categoryOptions: [
{
value: 1,
label: '后台类目'
},
{
value: 2,
label: '前台类目'
}
]
} | javascript | 8 | 0.373004 | 29 | 11.527273 | 55 | starcoderdata |
<?php
namespace Chemem\Bingo\Functional\Tests\Functional;
use Chemem\Bingo\Functional as f;
use Chemem\Bingo\Functional\Transducer as t;
class TransduceTest extends \PHPUnit\Framework\TestCase
{
public function contextProvider()
{
return [
[
f\flip(f\compose)(
t\map(function (int $x) {
return $x + 3;
}),
t\map(function (int $x) {
return $x ** 2;
}),
t\filter(function (int $x) {
return $x % 2 === 0;
})
),
function ($acc, $val, $idx) {
return f\extend($acc, [$idx => $val]);
},
[
'foo' => 1,
'bar' => 3,
'baz' => 4,
],
[],
['foo' => 16, 'bar' => 36],
],
[
f\flip(f\compose)(
t\map('strtoupper'),
t\reject(function (string $str) {
return \mb_strlen($str, 'utf-8') > 3;
}),
t\map(function (string $str) {
return f\concat('-', ...\str_split($str));
})
),
function ($acc, $val, $idx) {
return f\extend($acc, [$idx => $val]);
},
['foo', 'bar', 'baz', 'foo-bar'],
[],
['F-O-O', 'B-A-R', 'B-A-Z'],
],
[
f\composeRight(
t\map(function (int $x) {
return $x ** 2;
}),
t\reject(function (int $x) {
return $x > 20;
})
),
function ($acc, $val) {
return $acc + $val;
},
[3, 7, 1, 9],
0,
10,
],
];
}
/**
* @dataProvider contextProvider
*/
public function testtransduceEffectivelyPipelinesListOperations($transducer, $step, $list, $acc, $res)
{
$transduced = f\transduce($transducer, $step, $list, $acc);
$this->assertEquals($res, $transduced);
}
} | php | 27 | 0.436326 | 104 | 22.365854 | 82 | starcoderdata |
// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef CONTAINERS_ARCHIVE_BUFFER_STREAM_HPP_
#define CONTAINERS_ARCHIVE_BUFFER_STREAM_HPP_
#include
#include "containers/archive/archive.hpp"
// Reads from a buffer without taking ownership over it
class buffer_read_stream_t : public read_stream_t {
public:
// Note: These are implemented in the header file because inlining them in
// combination with `deserialize_varint_uint64()` yields significant performance
// gains due to its frequent use in datum_string_t and other datum
// deserialization functions. (measured on GCC 4.8)
// If we end up compiling with whole-program link-time optimization some day,
// we can probably move this back to a .cc file.
explicit buffer_read_stream_t(const char *buf, size_t size, int64_t offset = 0)
: pos_(offset), buf_(buf), size_(size) {
guarantee(pos_ >= 0);
guarantee(static_cast <= size_);
}
virtual ~buffer_read_stream_t() { }
virtual MUST_USE int64_t read(void *p, int64_t n) {
int64_t num_left = size_ - pos_;
int64_t num_to_read = n < num_left ? n : num_left;
memcpy(p, buf_ + pos_, num_to_read);
pos_ += num_to_read;
return num_to_read;
}
int64_t tell() const { return pos_; }
private:
int64_t pos_;
const char *buf_;
size_t size_;
DISABLE_COPYING(buffer_read_stream_t);
};
#endif // CONTAINERS_ARCHIVE_BUFFER_STREAM_HPP_ | c++ | 14 | 0.656208 | 84 | 30.208333 | 48 | starcoderdata |
import abc
from concurrent.futures import (
Executor, Future, ThreadPoolExecutor, as_completed, wait, FIRST_COMPLETED
)
from threading import RLock
from typing import Dict, List
class Task(abc.ABC):
def __init__(self, context):
self.context = context
@abc.abstractmethod
def execute(self, *args, **kwargs):
pass
@abc.abstractmethod
def on_done(self, result):
pass
@abc.abstractmethod
def on_error(self, error):
pass
@abc.abstractmethod
def cleanup(self):
pass
def complete(self, future: Future):
try:
self.on_done(future.result())
except Exception as error:
self.on_error(error)
finally:
self.cleanup()
class TaskList:
executor: Executor
tasks: Dict[int, Task]
futures: List[Future]
def __init__(self, executor: Executor = None):
self.executor = executor or ThreadPoolExecutor(max_workers=32)
self.tasks = {}
self.futures = []
self.lock = RLock()
def submit(self, task: Task, *args, **kwargs):
with self.lock:
future = self.executor.submit(task.execute, *args, **kwargs)
self.futures.append(future)
self.tasks[id(future)] = task
def wait_any(self) -> List[Task]:
with self.lock:
completed_tasks = []
completed, _ = wait(self.futures, return_when=FIRST_COMPLETED)
for future in completed:
self.futures.remove(future)
task = self.tasks.pop(id(future))
task.complete(future)
completed_tasks.append(task)
return completed_tasks
def wait_all(self) -> List[Task]:
with self.lock:
for future in as_completed(self.futures):
self.tasks[id(future)].complete(future)
self.tasks = {}
self.futures = []
return list(self.tasks.values())
@property
def empty(self) -> bool:
return len(self.tasks) == 0 | python | 15 | 0.580553 | 77 | 26.246753 | 77 | starcoderdata |
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char *argv[]) {
// read inputs
int N;
vector<pair<string, pair<int, int>>> pairs;
cin >> N;
// printf("%d\n", N);
for (int i = 0; i < N; i++) {
string cs;
int p;
cin >> cs >> p;
pairs.push_back(make_pair(cs, make_pair(-p, i + 1))); // NOTE : negation
// cout << cs << " " << p << endl;
}
// solve
sort(pairs.begin(), pairs.end());
for (const pair<string, pair<int, int>> &pair : pairs) {
cout << pair.second.second << "\n";
}
return 0;
}
| c++ | 13 | 0.558383 | 77 | 19.875 | 32 | codenet |
namespace BillingService.Services.BehaviourService;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;
using Backend.Core.Services.LoggerService;
using MediatR;
[ExcludeFromCodeCoverage]
public class LoggingBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : notnull
{
private readonly ILoggerService _logger;
public LoggingBehaviour(ILoggerService logger) => _logger = logger;
public async Task Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate next)
{
_logger.LogInformation($"Begin: Handle {typeof(TRequest).Name}");
var response = await next();
_logger.LogInformation($"Finish: Handle {typeof(TResponse).Name}");
return response;
}
} | c# | 14 | 0.762651 | 134 | 35.130435 | 23 | starcoderdata |
package ru.project.quiz.domain.dto.ituser;
import ru.project.quiz.domain.enums.ituser.PermissionType;
import java.util.Set;
public class RoleDTO {
private long id;
private String name;
private Set permissions;
public RoleDTO(String name, Set permissions) {
this.name = name;
this.permissions = permissions;
}
public RoleDTO() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set getPermissions() {
return permissions;
}
public void setPermissions(Set permissions) {
this.permissions = permissions;
}
} | java | 8 | 0.630409 | 66 | 18.883721 | 43 | starcoderdata |
package org.highmed.dsf.bpe.service;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.highmed.dsf.bpe.delegate.AbstractServiceDelegate;
import org.highmed.dsf.bpe.variables.ConstantsFeasibility;
import org.highmed.dsf.bpe.variables.FeasibilityQueryResult;
import org.highmed.dsf.bpe.variables.FeasibilityQueryResults;
import org.highmed.dsf.bpe.variables.FeasibilityQueryResultsValues;
import org.highmed.dsf.fhir.client.FhirWebserviceClientProvider;
import org.highmed.dsf.fhir.organization.OrganizationProvider;
import org.highmed.dsf.fhir.task.TaskHelper;
import org.highmed.openehr.client.OpenEhrClient;
import org.highmed.openehr.model.structure.ResultSet;
import org.springframework.beans.factory.InitializingBean;
public class ExecuteQueries extends AbstractServiceDelegate implements InitializingBean
{
private final OpenEhrClient openehrClient;
private final OrganizationProvider organizationProvider;
public ExecuteQueries(FhirWebserviceClientProvider clientProvider, OpenEhrClient openehrClient,
TaskHelper taskHelper, OrganizationProvider organizationProvider)
{
super(clientProvider, taskHelper);
this.openehrClient = openehrClient;
this.organizationProvider = organizationProvider;
}
@Override
public void afterPropertiesSet() throws Exception
{
super.afterPropertiesSet();
Objects.requireNonNull(openehrClient, "openehrClient");
Objects.requireNonNull(organizationProvider, "organizationProvider");
}
@Override
protected void doExecute(DelegateExecution execution) throws Exception
{
// <groupId, query>
@SuppressWarnings("unchecked")
Map<String, String> queries = (Map<String, String>) execution.getVariable(ConstantsFeasibility.VARIABLE_QUERIES);
Boolean needsConsentCheck = (Boolean) execution.getVariable(ConstantsFeasibility.VARIABLE_NEEDS_CONSENT_CHECK);
Boolean needsRecordLinkage = (Boolean) execution.getVariable(ConstantsFeasibility.VARIABLE_NEEDS_RECORD_LINKAGE);
boolean idQuery = Boolean.TRUE.equals(needsConsentCheck) || Boolean.TRUE.equals(needsRecordLinkage);
List results = queries.entrySet().stream()
.map(entry -> executeQuery(entry.getKey(), entry.getValue(), idQuery)).collect(Collectors.toList());
execution.setVariable(ConstantsFeasibility.VARIABLE_QUERY_RESULTS,
FeasibilityQueryResultsValues.create(new FeasibilityQueryResults(results)));
}
private FeasibilityQueryResult executeQuery(String cohortId, String cohortQuery, boolean idQuery)
{
// TODO We might want to introduce a more complex result type to represent a count,
// errors and possible meta-data.
ResultSet resultSet = openehrClient.query(cohortQuery, null);
if (idQuery)
{
return FeasibilityQueryResult.idResult(organizationProvider.getLocalIdentifierValue(), cohortId, resultSet);
}
else
{
int count = Integer.parseInt(resultSet.getRow(0).get(0).getValueAsString());
return FeasibilityQueryResult.countResult(organizationProvider.getLocalIdentifierValue(), cohortId, count);
}
}
} | java | 15 | 0.813835 | 115 | 38.708861 | 79 | starcoderdata |
def printFeatureImages(featureImages, naming, printlocation):
i =0
for image in featureImages:
# Normalize to intensity values
imageToPrint = cv2.normalize(image, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)
cv2.imwrite(printlocation + "\\" + naming + str(i) + ".png", imageToPrint)
i+=1 | python | 14 | 0.662824 | 107 | 42.5 | 8 | inline |
public void serialize() {
// try {
//
// if (!file.exists())
// createFiles();
//
// ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(file));
//
// stream.writeInt(id);
// stream.writeInt(round);
// stream.writeObject(ring);
// stream.writeObject(graveyard);
//
// stream.flush();
// console.out("Automatically saving...");
// ApplicationEntry.mainStage.setTitle("Gotcha!");
// } catch (IOException e) {
// e.printStackTrace();
// }
} | java | 3 | 0.505766 | 93 | 29.4 | 20 | inline |
using System;
namespace StoicGoose.WinForms
{
public class EnqueueSamplesEventArgs : EventArgs
{
public short[] Samples { get; set; } = default;
public EnqueueSamplesEventArgs(short[] samples)
{
Samples = samples;
}
}
} | c# | 10 | 0.704641 | 49 | 15.928571 | 14 | starcoderdata |
def setOutputScaleFileName(self, aOutputScaleFileName):
"""
setOutputScaleFileName(ModelScaler self, std::string const & aOutputScaleFileName)
Parameters
----------
aOutputScaleFileName: std::string const &
"""
return _tools.ModelScaler_setOutputScaleFileName(self, aOutputScaleFileName) | python | 6 | 0.672464 | 90 | 33.6 | 10 | inline |
@Nullable
public static PsiClass getKotlinRuntimeMarkerClass(@NotNull GlobalSearchScope scope) {
FqName kotlinPackageFqName = FqName.topLevel(Name.identifier("kotlin"));
String kotlinPackageClassFqName = PackageClassUtils.getPackageClassFqName(kotlinPackageFqName).asString();
ImmutableList<String> candidateClassNames = ImmutableList.of(
kotlinPackageClassFqName,
"kotlin.Unit",
// For older versions
"kotlin.namespace",
"jet.Unit"
);
for (String className : candidateClassNames) {
PsiClass psiClass = JavaPsiFacade.getInstance(scope.getProject()).findClass(className, scope);
if (psiClass != null) {
return psiClass;
}
}
return null;
} | java | 12 | 0.617964 | 114 | 38.809524 | 21 | inline |
package eu.nets.ms.pia.business.sync;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import eu.nets.ms.pia.business.sync.SyncServiceImpl.LockOperation;
import eu.nets.ms.pia.business.sync.SyncServiceImpl.LockOperator;
public class SyncServiceTest {
private static final int STATUS_POLL_TIMEOUT = 8000;
private static final String TEST_TRANS_ID = "1234";
private LockOperation create = new SyncServiceImpl.LockOperation(TEST_TRANS_ID, LockOperator.CREATE);
private LockOperation tryAquire = new SyncServiceImpl.LockOperation(TEST_TRANS_ID, LockOperator.AQUIRE);
private LockOperation release = new SyncServiceImpl.LockOperation(TEST_TRANS_ID, LockOperator.RELEASE);
private boolean threadStarted = false;
private long threadId;
private List callStack = new ArrayList<>();
private SyncService syncService = new SyncServiceImpl();
@Before
public void init(){
if (!threadStarted) {
((SyncServiceImpl)syncService).init();
threadStarted = true;
}
}
@After
public void tearDown(){
callStack.clear();
}
@Test
public void shouldBlockExecutionOfSecondThread() throws InterruptedException {
syncService.createLock(TEST_TRANS_ID);
logg(LockOperator.CREATE);
//This second thread will attempt to aquire the lock
(new Thread(new CallingThreadMock(tryAquire))).start();
Thread.sleep(STATUS_POLL_TIMEOUT + 1000);
//First thread release the lock
syncService.releaseLock(TEST_TRANS_ID);
logg(LockOperator.RELEASE);
Thread.sleep(500);
long lockingThread = callStack.get(0).getThreadId();
assertThat(callStack.get(0).getOperator(), equalTo("CREATE"));
assertThat(callStack.get(1).getOperator(), equalTo("RELEASE"));
assertThat(callStack.size(), equalTo(2));
}
/**
* One thread should wait for release lock.
*
* This simulates this scenario:
* * A lock is created in the thread where the transaction is registered
* * A cli
*
*
* @throws InterruptedException the interrupted exception
*/
@Test
public void oneThreadShouldWaitForReleaseLock() throws InterruptedException {
syncService.createLock(TEST_TRANS_ID);
logg(LockOperator.CREATE);
(new Thread(new CallingThreadMock(tryAquire))).start();
Thread.sleep(STATUS_POLL_TIMEOUT -1000);
//This simulates a callback that will release a lock
(new Thread(new CallingThreadMock(release))).start();
Thread.sleep(STATUS_POLL_TIMEOUT);
/*The thread trying to aquire the lock should not succeed*/
assertThat(callStack.size(), equalTo(3));
assertThat(callStack.get(0).getThreadId(), not(equalTo(callStack.get(1).getThreadId())));
assertThat(callStack.get(2).getOperator(), equalTo("AQUIRE"));
}
/*
* Thread for mocking calls
*/
public class CallingThreadMock implements Runnable {
LockOperation operation;
public CallingThreadMock(LockOperation operation) {
this.operation = operation;
}
public void run() {
try {
// Simulated response time
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (LockOperator.AQUIRE.equals(operation.getOperator())) {
if(syncService.waitForLockAvailable(TEST_TRANS_ID, STATUS_POLL_TIMEOUT)){
logg(LockOperator.AQUIRE);
}
}else if (LockOperator.CREATE.equals(operation.getOperator())) {
syncService.createLock(TEST_TRANS_ID);
logg(LockOperator.CREATE);
}else if (LockOperator.RELEASE.equals(operation.getOperator())) {
syncService.releaseLock(TEST_TRANS_ID);
logg(LockOperator.RELEASE);
}
}
}
private void logg(LockOperator operator){
callStack.add(new LoggedCall(operator));
}
private class LoggedCall{
private final long threadId;
private final String operator;
public LoggedCall(LockOperator operator){
this.threadId = Thread.currentThread().getId();
this.operator = operator.name();
}
public long getThreadId() {
return threadId;
}
public String getOperator() {
return operator;
}
}
} | java | 15 | 0.729871 | 105 | 25.56962 | 158 | starcoderdata |
package de.domschmidt.koku.scheduled;
import de.domschmidt.koku.exceptions.KokuCardDavException;
import de.domschmidt.koku.service.ICardDavService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class CardDavSchedule {
public static final int FIXED_SCHEDULE_RATE = 60 * // minutes
60 * // seconds
1000; // milliseconds
private final ICardDavService cardDavService;
@Autowired
public CardDavSchedule(
final ICardDavService cardDavService
) {
this.cardDavService = cardDavService;
}
@Scheduled(fixedDelay = FIXED_SCHEDULE_RATE)
public void runCardDavExport() {
try {
log.info("Started CardDav Schedule");
this.cardDavService.syncAllContacts();
log.info("Ended CardDav Schedule");
} catch (final KokuCardDavException kokuCardDavException) {
log.error("Unable to run CardDav Sync scheduled, due to: ", kokuCardDavException);
}
}
} | java | 10 | 0.684765 | 94 | 30.5 | 38 | starcoderdata |
void VisualizarFrame( )
{
using namespace std ;
// comprobar y limpiar variable interna de error
assert( glGetError() == GL_NO_ERROR );
// establece la zona visible (toda la ventana)
glViewport( 0, 0, ancho_actual, alto_actual );
// fija la matriz de transformación de coordenadas de los shaders ('u_modelview'),
// (la hace igual a la matriz identidad)
glUniformMatrix4fv( loc_modelview, 1, GL_TRUE, mat_ident );
// fija la matriz de proyeccion 'modelview' de los shaders ('u_proyeccion')
// (la hace igual a la matriz identidad)
glUniformMatrix4fv( loc_proyeccion, 1, GL_TRUE, mat_ident );
// limpiar la ventana
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
// habilitar EPO por Z-buffer (test de profundidad)
glEnable( GL_DEPTH_TEST );
// Dibujar un triángulo en modo diferido
DibujarTrianguloMD_NoInd();
//DibujarTrianguloMD_Ind();
// Cambiar la matriz de transformación de coordenadas (matriz 'u_modelview')
constexpr float incremento_z = -0.1 ;
const GLfloat mat_despl[] = // matriz 4x4 desplazamiento
{ 1.0, 0.0, 0.0, 0.2, // (0,2 en X y en Y, -0.1 en Z (más cerca))
0.0, 1.0, 0.0, 0.2,
0.0, 0.0, 1.0, incremento_z,
0.0, 0.0, 0.0, 1.0,
} ;
glUniformMatrix4fv( loc_modelview, 1, GL_TRUE, mat_despl );
// dibujar triángulo (desplazado) en modo inmediato.
//DibujarTrianguloMI_NoInd(); // no indexado
//DibujarTrianguloMI_Ind(); // indexado
DibujarTrianguloMD_Ind(); // indexado
// comprobar y limpiar variable interna de error
assert( glGetError() == GL_NO_ERROR );
// esperar a que termine 'glDrawArrays' y entonces presentar el framebuffer actualizado
glfwSwapBuffers( ventana_glfw );
} | c++ | 9 | 0.638874 | 91 | 35.24 | 50 | inline |
package util;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
public class OrganizationIterator implements Iterator {
Stack stack;
/**
*
* @param root ceomuzdur, organization implementatıon nesnemizle yaratıyoruz ve
* bu nesneyi yaratırken de onu yolluyoruz. Stackımızın basına da onu yolluyoruz.
*/
public OrganizationIterator(Tree root) {
stack = new Stack
stack.push(root);
}
@Override
public boolean hasNext() {
return !stack.isEmpty();
}
@Override
public IEmployee next() {
if (!stack.isEmpty()) {
Tree curr = stack.pop();
//stackden pop yaparak o andaki calısanı alıp datasını alıyoruz.
IEmployee e = curr.getData();
List children = curr.children();
//çocukları sırayla ziyaret etmek istediğimiz için
// onları yığına ters sırada yerleştiriyorum.
Collections.reverse(children);
for (Tree c : children) {
stack.push(c);
}
return e;
}
return null;
}
} | java | 12 | 0.587519 | 97 | 27.909091 | 44 | starcoderdata |
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using TMPro;
using translator;
///
/// Represents the settings panel for the sorting task.
///
public class SortingSettingsPanel : BaseElementListSettingsPanel
{
protected new void Awake()
{
base.Awake();
InitSkippableDropdown(skippableDropdown);
labelTemplate = "Gegenstand {0}:";
maxNumObjects = 6;
warningMessage.text = "Maximale Anzahl von " + maxNumObjects + " Gegenständen erreicht.";
}
protected override void InitElement(bool isMax, bool isLast, bool isSingle, JObject element = null)
{
BaseListElement newContainer =
Instantiate(ElementPrefab, ElementListContainer.transform).GetComponent
newContainer.btnAdd.onClick.AddListener(AddSelectionElement);
newContainer.btnRemove.onClick.AddListener(() => RemoveSelectionElement(newContainer.gameObject));
newContainer.btnRemove.onClick.AddListener(SaveSettings);
newContainer.btnAdd.gameObject.SetActive(!isMax && isLast);
newContainer.btnRemove.gameObject.SetActive(!isSingle);
newContainer.label.text = string.Format(labelTemplate, newContainer.transform.GetSiblingIndex() + 1);
newContainer.dropdown.options = new List
DataController.Instance.sortableObjects.ForEach(s =>
newContainer.dropdown.options.Add(
new TMP_Dropdown.OptionData(TranslationController.Instance.Translate(s))));
newContainer.dropdown.onValueChanged.AddListener(delegate { SaveSettings(); });
newContainer.dropdown.RefreshShownValue();
if (element == null)
newContainer.SetUpForSettings();
else
newContainer.SetUpForSettings(element);
AdditionalInitElement(newContainer);
}
protected override void AdditionalInitElement(BaseListElement newContainer)
{
SortableObjectListElement sortableObjectListElement = (SortableObjectListElement) newContainer;
sortableObjectListElement.labelingInputField.onEndEdit.AddListener(delegate { SaveSettings(); });
sortableObjectListElement.insideToggle.onValueChanged.AddListener(delegate { SaveSettings(); });
}
} | c# | 19 | 0.716703 | 109 | 42.490566 | 53 | starcoderdata |
private Set<Integer> computeResponsibilities() {
// add hit branches to counter
Collection<Integer> nonZeroIndices = runCoverage.getCounter().getNonZeroIndices();
Set<Integer> hitBranches = new HashSet<>(nonZeroIndices);
int hits = branchesHitCount.getOrDefault(hitBranches, 0);
if (PRINT_COVERAGE_DETAILS) {
System.out.println("[COV] branches hit: " + hitBranches);
System.out.println("[COV] branches known: " + branchesHitCount.keySet());
File equalCovFile = coverageFilePointer.get(hitBranches);
if (equalCovFile != null) {
System.out.println("[COV] equal branches discovered as " + equalCovFile.getName());
}
}
branchesHitCount.put(hitBranches, hits + 1);
return hitBranches;
} | java | 13 | 0.632406 | 99 | 45 | 18 | inline |
import os
import uvicorn
from app import create_app
import sys
import asyncio
if sys.platform.startswith('win'):
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
FASTAPI_CONFIG = os.getenv('FASTAPI_CONFIG') or 'default'
application = create_app(FASTAPI_CONFIG)
@application.get("/tt")
def root():
return {"url": "/tt" }
if __name__ == "__main__":
uvicorn.run("__main__:application", host="0.0.0.0", port=9070, workers=2)
# uvicorn.run("__main__:application", host="0.0.0.0",
# port=9070, reload=True, workers=2) | python | 8 | 0.671958 | 77 | 21.68 | 25 | starcoderdata |
#include "enrico/heat_fluids_driver.h"
#include
#include
#include
namespace enrico {
HeatFluidsDriver::HeatFluidsDriver(MPI_Comm comm, pugi::xml_node node)
: Driver(comm)
{
pressure_bc_ = node.child("pressure_bc").text().as_double();
Expects(pressure_bc_ > 0.0);
}
} | c++ | 14 | 0.702065 | 70 | 18.941176 | 17 | starcoderdata |
<style type="text/css">
.single_border{
border-bottom:2px solid #000;
border-left:1px solid #ddd;
border-right:1px solid #ddd;
}
.blog_title{
border-bottom:1px solid #ddd;
}
.blog_time{
border-bottom:1px solid #ddd;
}.blog_body{
border-bottom:1px solid #ddd;
}
a:hover, a:focus {
color: green;
text-decoration: none;
}
<?php $this->load->view('common/header');
// $all_author_published_blog_find = $this->Home_Model->all_author_published_blog_finding();
?>
<section class="container" style="padding:0px;">
<div class="col-md-8" style="padding:0px;">
<div class="content-grid">
<?php foreach ($categoryWiseData as $key => $value): ?>
<div class="content-grid-info single_border" >
<div class="post-info">
<div class="blog_image">
<img class="center-block" class="img-responsive" style="width:650px; height:240px" alt="No Image Found" src="<?php echo base_url('/assets/images/blogImages/').$value['image'];?>"/>
<div class="post">
<header class="blog_title">
<h3 style="text-align:center">
<a style=" text-decoration: none !important;" href="<?php echo base_url(); ?>home/single_blog/<?php echo $value['BlogID']; ?>"><?php echo $value['BlogTitle']; ?>
<div class="blog_time">
<h5 style="text-align:center ; color:red">
<span >
<?php
$get_blog_date = $value['created'];
$blog_date = new DateTime($get_blog_date);
$new_blog_date = $blog_date->format("j F Y, l, H:i");
$engDATE = array(1,2,3,4,5,6,7,8,9,0,'January','February','March','April','May','June','July','August','September','October','November','December','Saturday','Sunday','Monday','Tuesday','Wednesday','Thursday','Friday');
$bangDATE = array('১','২','৩','৪','৫','৬','৭','৮','৯','০','জানুয়ারী','ফেব্রুয়ারী','মার্চ','এপ্রিল','মে','জুন','জুলাই','আগস্ট','সেপ্টেম্বর','অক্টোবর','নভেম্বর','ডিসেম্বর','শনিবার','রবিবার','সোমবার','মঙ্গলবার','
বুধবার','বৃহস্পতিবার','শুক্রবার'
);
$convertedDATE = str_replace($engDATE, $bangDATE, $new_blog_date);
echo $convertedDATE . "মি.";
?>
<div class="blogbody">
<p style="padding:7px;">
<?php
$string=$value['BlogBody'];
$string = strip_tags($string);
if (strlen($string) > 600) {
$stringCut = substr($string, 0, 600);
// make sure it ends in a word so assassinate doesn't become ass...
$string = substr($stringCut, 0, strrpos($stringCut, ' ')).'... <a style="color:red" href='.base_url().'home/single_blog/'.$value['BlogID'].'>Read More
}
echo $string;
?>
<?php endforeach ?>
<?php $this->load->view('common/right-sitebar');?>
<?php $this->load->view('common/footer');?> | php | 19 | 0.525835 | 228 | 34.079545 | 88 | starcoderdata |
/*
* Copyright (c) 2021, All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boofcv.alg.geo.bundle.cameras;
import georegression.struct.point.Point2D_F64;
import org.jetbrains.annotations.Nullable;
/**
* Bundler and Bundle Adjustment in the Large use a different coordinate system. This
* converts it into what BoofCV understands by applying a negative sign to the Z coordinate.
*
* @author
*/
public class BundlePinholeSnavely extends BundlePinholeSimplified {
@Override
public void project( double camX, double camY, double camZ, Point2D_F64 output ) {
super.project(camX, camY, -camZ, output);
}
@Override
public void jacobian( double X, double Y, double Z,
double[] inputX, double[] inputY,
boolean computeIntrinsic, @Nullable double[] calibX, @Nullable double[] calibY ) {
Z = -Z;
double normX = X/Z;
double normY = Y/Z;
double n2 = normX*normX + normY*normY;
double n2_X = 2*normX/Z;
double n2_Y = 2*normY/Z;
double n2_Z = -2*n2/Z;
double r = 1.0 + (k1 + k2*n2)*n2;
double kk = k1 + 2*k2*n2;
double r_Z = n2_Z*kk;
// partial X
inputX[0] = (f/Z)*(r + 2*normX*normX*kk);
inputY[0] = f*normY*n2_X*kk;
// partial Y
inputX[1] = f*normX*n2_Y*kk;
inputY[1] = (f/Z)*(r + 2*normY*normY*kk);
// partial Z
inputX[2] = f*normX*(r/Z - r_Z); // you have no idea how many hours I lost before I realized the mistake here
inputY[2] = f*normY*(r/Z - r_Z);
if (!computeIntrinsic || calibX == null || calibY == null)
return;
// partial f
calibX[0] = r*normX;
calibY[0] = r*normY;
// partial k1
calibX[1] = f*normX*n2;
calibY[1] = f*normY*n2;
// partial k2
calibX[2] = f*normX*n2*n2;
calibY[2] = f*normY*n2*n2;
}
@Override
public String toString() {
return "BundlePinholeSnavely{" +
"f=" + f +
", k1=" + k1 +
", k2=" + k2 +
'}';
}
} | java | 14 | 0.656759 | 111 | 25.12766 | 94 | starcoderdata |
package com.epam.esm.dto.illness;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class IllnessRequestDto {
@NotBlank(message = "name can't be null or empty")
@Size(min = 4, max = 30, message = "name can be 4 to 30 characters long")
@JsonProperty("name")
private String name;
@NotBlank(message = "description can't be null or empty")
@Size(min = 4, max = 250, message = "description can be 4 to 250 characters long")
@JsonProperty("description")
private String description;
@NotNull(message = "chance to die can't be null")
@Min(value = 0, message = "minimum 0%")
@Max(value = 100, message = "maximum 100%")
@JsonProperty("chance_to_die")
private Integer chanceToDie;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getChanceToDie() {
return chanceToDie;
}
public void setChanceToDie(Integer chanceToDie) {
this.chanceToDie = chanceToDie;
}
} | java | 9 | 0.682041 | 86 | 27.058824 | 51 | starcoderdata |
#/usr/bin/env python
import numpy as np
import tensorflow as tf
def get_maxq_per_state(estimator, states):
# States is (batch_size, 4, 4)
# Want to return (batch_size, 1) maximum Q
qmax = np.amax(get_predictions(estimator, states), axis=1).reshape((-1, 1))
return qmax
def get_predictions(estimator, states):
"""Get predictions for a number of states. States is (batch_size, 4, 4), returns numpy array of (batch_size, 4) with predictions for all actions."""
predict_input_fn = numpy_predict_fn(states)
prediction = estimator.predict(input_fn=predict_input_fn)
list_predictions = [p['logits'] for p in prediction]
np_array_prediction_values = np.array(list_predictions)
return np_array_prediction_values
def numpy_predict_fn(observation):
return tf.estimator.inputs.numpy_input_fn(x={'board': observation.reshape((-1,4,4,1)).astype(np.float32)},
num_epochs=1,
shuffle=False)
def numpy_train_fn(observation, action, reward):
return tf.estimator.inputs.numpy_input_fn(x={'board': observation.reshape((-1,4,4,1)).astype(np.float32)},
y={'action' : action.astype(np.int32), 'reward': reward},
batch_size=1024,
num_epochs=1,
shuffle=False)
def my_input_fn(file_path, perform_shuffle=False, repeat_count=1, augment=False, batch_size=32):
def decode_csv(line):
parsed_line = tf.decode_csv(line, [[0] for i in range(17)] + [[0.0]])
features = parsed_line[0:16]
# Convert from list of tensors to one tensor
features = tf.reshape(tf.cast(tf.stack(features), tf.float32), [4, 4, 1])
action = parsed_line[16]
reward = parsed_line[17]
return {'board': features}, {'action': action, 'reward': reward}
def hflip(feature, label):
image = feature['board']
flipped_image = tf.image.flip_left_right(image)
#tf.Print(flipped_image, [image, flipped_image], "Image and flipped left right")
new_action = tf.gather([0, 3, 2, 1], label['action'])
#tf.Print(newlabel, [label['action'], newlabel], "Label and flipped left right")
return {'board': flipped_image}, {'action': new_action, 'reward': label['reward']}
def rotate_board(feature, label, k):
image = feature['board']
rotated_image = tf.image.rot90(image, 4 - k)
#tf.Print(rotated_image, [image, rotated_image], "Image and rotated by k={}".format(k))
new_action = label['action']
new_action += k
new_action %= 4
#tf.Print(new_action, [label['action'], new_action], "Label and rotated by k={}".format(k))
return {'board': rotated_image}, {'action': new_action, 'reward': label['reward']}
def rotate90(feature, label):
return rotate_board(feature, label, 1)
def rotate180(feature, label):
return rotate_board(feature, label, 2)
def rotate270(feature, label):
return rotate_board(feature, label, 3)
dataset = (tf.data.TextLineDataset(file_path) # Read text file
.skip(1) # Skip header row
.map(decode_csv)) # Transform each elem by applying decode_csv fn
if augment:
parallel_map_calls = 4
augmented = dataset.map(hflip, num_parallel_calls=parallel_map_calls)
dataset = dataset.concatenate(augmented)
r90 = dataset.map(rotate90, num_parallel_calls=parallel_map_calls)
r180 = dataset.map(rotate180, num_parallel_calls=parallel_map_calls)
r270 = dataset.map(rotate270, num_parallel_calls=parallel_map_calls)
dataset = dataset.concatenate(r90)
dataset = dataset.concatenate(r180)
dataset = dataset.concatenate(r270)
if perform_shuffle:
# Randomizes input using a window of 256 elements (read into memory)
dataset = dataset.shuffle(buffer_size=256)
dataset = dataset.repeat(repeat_count) # Repeats dataset this # times
dataset = dataset.batch(batch_size) # Batch size to use
iterator = dataset.make_one_shot_iterator()
batch_features, batch_labels = iterator.get_next()
return batch_features, batch_labels
def estimator(model_params):
model_params['n_classes'] = 4
return tf.estimator.Estimator(
model_fn=my_model,
model_dir='model_dir/{}_{}_{}_{}_{}'.format(model_params['dropout_rate'], model_params['residual_blocks'], model_params['filters'], '-'.join(map(str, model_params['fc_layers'])), '_bn' if model_params['batch_norm'] else ''), # Path to where checkpoints etc are stored
params=model_params)
def residual_block(in_net, filters, mode, bn=False):
# Convolution layer 1
# Input shape: [batch_size, 4, 4, filters]
# Output shape: [batch_size, 4, 4, filters]
net = tf.layers.conv2d(
inputs=in_net,
filters=filters,
kernel_size=[3, 3],
padding="same",
activation=None)
if bn:
# Batch norm
net = tf.layers.batch_normalization(
inputs=net,
training=mode == tf.estimator.ModeKeys.TRAIN
)
# Non linearity
net = tf.nn.relu(net)
# Convolution layer 1
# Input shape: [batch_size, 4, 4, filters]
# Output shape: [batch_size, 4, 4, filters]
net = tf.layers.conv2d(
inputs=net,
filters=filters,
kernel_size=[3, 3],
padding="same",
activation=None)
if bn:
# Batch norm
net = tf.layers.batch_normalization(
inputs=net,
training=mode == tf.estimator.ModeKeys.TRAIN
)
# Skip connection
net = net + in_net
# Non linearity
net = tf.nn.relu(net)
return net
def convolutional_block(in_net, filters, mode, bn=False):
# Convolution layer 1
# Input shape: [batch_size, 4, 4, 1]
# Output shape: [batch_size, 4, 4, filters]
net = tf.layers.conv2d(
inputs=in_net,
filters=filters,
kernel_size=[3, 3],
padding="same",
activation=None)
if bn:
# Batch norm
net = tf.layers.batch_normalization(
inputs=net,
training=mode == tf.estimator.ModeKeys.TRAIN
)
# Non linearity
net = tf.nn.relu(net)
return net
def log2(x):
"""Log to base 2"""
numerator = tf.log(x)
denominator = tf.log(tf.constant(2, dtype=numerator.dtype))
return numerator / denominator
def my_model(features, labels, mode, params):
"""Neural network model with configurable number of residual blocks follwed by fully connected layers"""
l0 = features['board']
# Input shape: [batch_size, 4, 4, 1]
# Output shape: [batch_size, 4, 4, filters]
block_inout = convolutional_block(l0, params['filters'], mode, params['batch_norm'])
# Input shape: [batch_size, 4, 4, filters]
# Output shape: [batch_size, 4, 4, filters]
for res_block in range(params['residual_blocks']):
block_inout = residual_block(block_inout, params['filters'], mode, params['batch_norm'])
# Flatten into a batch of vectors
# Input shape: [batch_size, 4, 4, filters]
# Output shape: [batch_size, 4 * 4 * filters]
net = tf.reshape(block_inout, [-1, 4 * 4 * params['filters']])
for units in params['fc_layers']:
# Fully connected layer
# Input shape: [batch_size, 4 * 4 * 16]
# Output shape: [batch_size, 16]
net = tf.layers.dense(net, units=units, activation=tf.nn.relu)
# Add dropout operation
net = tf.layers.dropout(
inputs=net, rate=params['dropout_rate'], training=mode == tf.estimator.ModeKeys.TRAIN)
# Compute logits (1 per class).
logits = tf.layers.dense(net, params['n_classes'], activation=None)
# Compute predictions.
if mode == tf.estimator.ModeKeys.PREDICT:
predictions = {
#'probabilities': tf.nn.softmax(logits),
'logits': logits,
}
return tf.estimator.EstimatorSpec(mode, predictions=predictions)
# Compute loss on actions compared to records
action_labels = labels['action'] # Shape [batch_size, 1]
# Then calculate loss with softmax cross entropy
action_loss = tf.losses.sparse_softmax_cross_entropy(labels=action_labels, logits=logits)
# Compute loss based no rewards compared to those from environment
reward_labels = labels['reward'] # Shape [batch_size, 1]
# Only have reward from environment from one action so gather predicted
# rewards for those actions and calculate MSE compared to environment
batch_size = tf.shape(labels['action'])[0]
action_idx = tf.reshape(tf.range(batch_size),[-1, 1])
action_labels_reshaped = tf.reshape(labels['action'],[-1, 1])
action_reshaped = tf.reshape(tf.concat([action_idx, action_labels_reshaped],axis=1), [-1, 1, 2])
gathered_logits = tf.gather_nd(logits, action_reshaped)
reward_loss = tf.losses.mean_squared_error(tf.reshape(reward_labels, [-1, 1]), gathered_logits)
# Batch normalize to get distribution closer to zero
# reward_bn = tf.layers.batch_normalization(
# inputs=tf.reshape(labels['reward'], [-1, 1]),
# training=mode == tf.estimator.ModeKeys.TRAIN
# )
# Calculate Q loss on the Q of the input action
#q_loss = tf.losses.mean_squared_error(labels['reward'], tf.reshape(logits, [-1, 1]))
# Select loss (action or reward)
loss = reward_loss
# Compute evaluation metrics.
# accuracy = tf.metrics.accuracy(labels=action_labels,
# predictions=predicted_classes,
# name='acc_op')
# metrics = {'accuracy': accuracy}
# tf.summary.scalar('accuracy', accuracy[1])
if mode == tf.estimator.ModeKeys.EVAL:
return tf.estimator.EstimatorSpec(
mode, loss=loss)
# Create training op.
assert mode == tf.estimator.ModeKeys.TRAIN
optimizer = tf.train.AdamOptimizer(params.get('learning_rate', 0.05))
# Add extra dependencies for batch normalisation
extra_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(extra_update_ops):
train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step())
return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op) | python | 15 | 0.643224 | 275 | 37.112782 | 266 | starcoderdata |
'use strict';
const fs = require('fs');
const path = require('path');
const dot = require('dot');
const c = require('../config');
const DateTime = require("right-track-core/modules/utils/DateTime.js");
// INDEX HTML
let INDEX_HTML = " + c.server.get().name + "
/**
* Build the HTML for the API Server index page
*/
function buildHTML() {
let loc = path.join(__dirname + "/../../static/index.html");
fs.readFile(loc, 'utf8', function (err, data) {
if ( err ) {
console.error("COULD NOT READ INDEX HTML FILE");
return;
}
// Load config variables
let config = c.server.get();
// Add Agency information
let agencyCodes = c.agencies.getAgencies();
let agencies = [];
for ( let i = 0; i < agencyCodes.length; i++ ) {
agencies[agencyCodes[i]] = c.agencies.getAgencyConfig(agencyCodes[i]);
}
// Add Transit Agency Information
let transitCodes = c.transit.getTransitAgencies();
let transit = [];
for ( let i = 0; i < transitCodes.length; i++ ) {
transit[transitCodes[i]] = c.transit.getTransitAgency(transitCodes[i]);
}
// Build Template properties
let it = {
config: config,
agencies: agencies,
transit: transit,
copyrightYear: new Date().getFullYear(),
build: new DateTime.now().toHTTPString()
};
// Replace variables in HTML
let template = dot.template(data);
INDEX_HTML = template(it);
});
}
/**
* Serve the pre-built HTML for the API Server index page
* @param req API Request
* @param res API Response
* @param next API Handler Stack
* @returns Response
*/
function serveHTML(req, res, next) {
// Send HTML in response
res.writeHead(200, {
'Content-Length': Buffer.byteLength(INDEX_HTML),
'Content-Type': 'text/html'
});
res.write(INDEX_HTML);
res.end();
return next();
}
module.exports = {
buildHTML: buildHTML,
serveHTML: serveHTML
}; | javascript | 16 | 0.627198 | 77 | 22.585366 | 82 | starcoderdata |
/*
* Created by michal-swiatek on 19.04.2021.
*
* Github: https://github.com/michal-swiatek
*
* From Cherno game engine series: https://www.youtube.com/playlist?list=PLlrATfBNZ98dC-V-N3m0Go4deliWHPFwT
*/
#ifndef WEHAPPYFEW_EVENTHANDLER_H
#define WEHAPPYFEW_EVENTHANDLER_H
#include "Events/Event.h"
#include "Core/EngineApi.h"
namespace engine {
class ENGINE_API EventHandler
{
public:
explicit EventHandler(Event& event) : event(event) {}
template<class AcceptedEvent, class F>
bool Handle(const F& func)
{
if (event.GetEventType() == AcceptedEvent::GetStaticType())
{
event.handled |= func(static_cast
return true;
}
return false;
}
private:
Event& event;
};
#define BIND_EVENT_CALLBACK(callback) [this](auto&&... args) -> decltype(auto) { return this->callback(std::forward }
}
#endif //WEHAPPYFEW_EVENTHANDLER_H | c | 15 | 0.621022 | 148 | 24.292683 | 41 | starcoderdata |
import fetch from 'isomorphic-fetch';
const beginSearchCity = () => ({ type: 'SEARCH_CITY' });
const setData = json => ({ type: 'RECEIVE_SEARCH_CITY', data: json });
const errorSearchCity = err => ({ type: 'ERROR_SEARCH_CITY', error: err.message });
const searchCity = city => (dispatch) => {
dispatch(beginSearchCity());
fetch(`https://api.teleport.org/api/cities/?search=${city}`)
.then(response => response.json())
.then(json => dispatch(setData(json)))
.catch(err => dispatch(errorSearchCity(err)));
};
export default searchCity; | javascript | 13 | 0.654545 | 83 | 34.588235 | 17 | starcoderdata |
func (cw *CDFWriter) storeChars(val reflect.Value, dimLengths []int64) {
if len(dimLengths) == 0 {
// a single character
str := val.String()
if len(str) == 0 {
return
}
write8(cw.bf, int8(str[0]))
return
}
thisDim := dimLengths[0]
if len(dimLengths) == 1 {
// a string which must be padded
s, ok := val.Interface().(string)
if !ok {
thrower.Throw(ErrInternal)
}
// TODO: this is probably wrong because it could be unlimited
writeBytes(cw.bf, []byte(s))
offset := int64(val.Len())
for offset < thisDim {
write8(cw.bf, 0)
offset++
}
return
}
for i := 0; i < val.Len(); i++ {
value := val.Index(int(i))
cw.storeChars(value, dimLengths[1:])
}
} | go | 11 | 0.611511 | 72 | 21.451613 | 31 | inline |
//ES6 introduced a new way of working with functions and iterators in the form of Generators (or generator functions). A generator is a function that can stop midway and then continue from where it stopped. In short, a generator appears to be a function but it behaves like an iterator
function* timestampGenerator() {
var ts = Date.now();
yield ts;
var additionalTime = yield;
console.log(additionalTime);
if (additionalTime) {
ts = ts + additionalTime
}
console.log(ts)
}
const it = timestampGenerator();
const originalTimestamp = it.next()
it.next()
it.next(1000 * 60) | javascript | 8 | 0.736931 | 285 | 31.944444 | 18 | starcoderdata |
using Android.Graphics;
namespace FFImageLoading.Transformations
{
[Preserve(AllMembers = true)]
public class TintTransformation : ColorSpaceTransformation
{
public TintTransformation() : this(0, 165, 0, 128)
{
}
public TintTransformation(int r, int g, int b, int a)
{
R = r;
G = g;
B = b;
A = a;
}
public TintTransformation(string hexColor)
{
HexColor = hexColor;
}
string _hexColor;
public string HexColor
{
get
{
return _hexColor;
}
set
{
_hexColor = value;
var color = value.ToColor();
R = color.R;
G = color.G;
B = color.B;
A = color.A;
}
}
public bool EnableSolidColor { get; set; }
public int R { get; set; }
public int G { get; set; }
public int B { get; set; }
public int A { get; set; }
public override string Key
{
get
{
return string.Format("TintTransformation,R={0},G={1},B={2},A={3},HexColor={4},EnableSolidColor={5}",
R, G, B, A, HexColor, EnableSolidColor);
}
}
protected override Bitmap Transform(Bitmap sourceBitmap, string path, Work.ImageSource source, bool isPlaceholder, string key)
{
if (EnableSolidColor)
return ToSolidColor(sourceBitmap, R, G, B, A);
RGBAWMatrix = FFColorMatrix.ColorToTintMatrix(R, G, B, A);
return base.Transform(sourceBitmap, path, source, isPlaceholder, key);
}
public static Bitmap ToSolidColor(Bitmap sourceBitmap, int r, int g, int b, int a)
{
var config = sourceBitmap?.GetConfig();
if (config == null)
{
config = Bitmap.Config.Argb8888;
}
int width = sourceBitmap.Width;
int height = sourceBitmap.Height;
Bitmap bitmap = Bitmap.CreateBitmap(width, height, config);
using (Canvas canvas = new Canvas(bitmap))
{
using (Paint paint = new Paint())
{
PorterDuffColorFilter cf = new PorterDuffColorFilter(Color.Argb(a, r, g, b), PorterDuff.Mode.SrcAtop);
paint.SetColorFilter(cf);
canvas.DrawBitmap(sourceBitmap, 0, 0, paint);
return bitmap;
}
}
}
}
} | c# | 21 | 0.648061 | 128 | 20.14 | 100 | starcoderdata |
beKA::beStatus BeProgramBuilderOpencl::Initialize(const string& dll_module/* = ""*/)
{
(void)(dll_module);
beKA::beStatus retVal = beKA::kBeStatusGeneralFailed;
retVal = InitializeOpencl();
std::set<string> unique_published_devices_names;
if (retVal == beKA::kBeStatusSuccess)
{
// Populate the sorted device (card) info table.
BeUtils::GetAllGraphicsCards(opencl_device_table_,unique_published_devices_names);
}
return retVal;
} | c++ | 8 | 0.65996 | 90 | 27.352941 | 17 | inline |
<?php
namespace Faker\Test\Provider;
use Faker\Provider\Uuid as BaseProvider;
use Faker\Test\TestCase;
/**
* @group legacy
*/
final class UuidTest extends TestCase
{
public function testUuidReturnsUuid()
{
$uuid = BaseProvider::uuid();
self::assertTrue($this->isUuid($uuid));
}
public function testUuidExpectedSeed()
{
if (pack('L', 0x6162797A) == pack('N', 0x6162797A)) {
self::markTestSkipped('Big Endian');
}
$this->faker->seed(123);
self::assertEquals('8e2e0c84-50dd-367c-9e66-f3ab455c78d6', BaseProvider::uuid());
self::assertEquals('073eb60a-902c-30ab-93d0-a94db371f6c8', BaseProvider::uuid());
}
protected function isUuid($uuid)
{
return is_string($uuid) && (bool) preg_match('/^[a-f0-9]{8,8}-(?:[a-f0-9]{4,4}-){3,3}[a-f0-9]{12,12}$/i', $uuid);
}
} | php | 13 | 0.617647 | 121 | 26 | 34 | starcoderdata |
using System;
using JetBrains.Annotations;
namespace SkbKontur.Cassandra.DistributedTaskQueue.Cassandra.Entities
{
public class TaskExceptionInfo
{
public TaskExceptionInfo([NotNull] Exception exception)
{
ExceptionMessageInfo = exception.ToString();
}
public string ExceptionMessageInfo { get; private set; }
}
} | c# | 11 | 0.691689 | 69 | 22.375 | 16 | starcoderdata |
@Override
public void mouseReleased(MouseEvent e) {
if (m_createShape) {
if (m_shapePoints.get(0).intValue() == 1) {
m_createShape = false;
Graphics g = m_plot2D.getGraphics();
g.setColor(Color.black);
g.setXORMode(Color.white);
g.drawRect(m_shapePoints.get(1).intValue(), m_shapePoints.get(2)
.intValue(), m_shapePoints.get(3).intValue()
- m_shapePoints.get(1).intValue(), m_shapePoints.get(4)
.intValue() - m_shapePoints.get(2).intValue());
g.dispose();
if (checkPoints(m_shapePoints.get(1).doubleValue(), m_shapePoints
.get(2).doubleValue())
&& checkPoints(m_shapePoints.get(3).doubleValue(),
m_shapePoints.get(4).doubleValue())) {
// then the points all land on the screen
// now do special check for the rectangle
if (m_shapePoints.get(1).doubleValue() < m_shapePoints.get(3)
.doubleValue()
&& m_shapePoints.get(2).doubleValue() < m_shapePoints.get(4)
.doubleValue()) {
// then the rectangle is valid
if (m_shapes == null) {
m_shapes = new ArrayList<ArrayList<Double>>(2);
}
m_shapePoints.set(
1,
new Double(m_plot2D.convertToAttribX(m_shapePoints.get(1)
.doubleValue())));
m_shapePoints.set(
2,
new Double(m_plot2D.convertToAttribY(m_shapePoints.get(2)
.doubleValue())));
m_shapePoints.set(
3,
new Double(m_plot2D.convertToAttribX(m_shapePoints.get(3)
.doubleValue())));
m_shapePoints.set(
4,
new Double(m_plot2D.convertToAttribY(m_shapePoints.get(4)
.doubleValue())));
m_shapes.add(m_shapePoints);
m_submit.setText("Submit");
m_submit.setActionCommand("Submit");
m_submit.setEnabled(true);
PlotPanel.this.repaint();
}
}
m_shapePoints = null;
}
}
} | java | 21 | 0.462418 | 79 | 39.816667 | 60 | inline |
protected void parseStencilSet(JSONObject modelJSON, D current) throws JSONException {
// get stencil type
if (modelJSON.has("stencilset")) {
JSONObject object = modelJSON.getJSONObject("stencilset");
StencilSetReference ssRef;
if (object.has("namespace") && !object.getString("namespace").trim().equals(""))
ssRef = new StencilSetReference(object.getString("namespace"));
else
throw new IllegalArgumentException("No namespace found for stencil set");
if (object.has("url"))
ssRef.setUrl(object.getString("url"));
current.setStencilsetRef(ssRef);
}
} | java | 14 | 0.70132 | 86 | 33.764706 | 17 | inline |
//
// Copyright (c) Microsoft. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.DataFactories.Common.Models;
using Microsoft.Azure.Management.DataFactories.Conversion;
using Microsoft.Azure.Management.DataFactories.Core;
using Microsoft.Azure.Management.DataFactories.Registration.Models;
namespace Microsoft.Azure.Management.DataFactories
{
public class ComputeTypeOperations : IServiceOperations
IComputeTypeOperations
{
public DataFactoryManagementClient Client { get; private set; }
internal ComputeTypeConverter Converter { get; private set; }
internal ComputeTypeOperations(DataFactoryManagementClient client)
{
this.Client = client;
this.Converter = new ComputeTypeConverter();
}
public async Task BeginDeleteAsync(
string resourceGroupName,
string dataFactoryName,
string computeTypeName,
CancellationToken cancellationToken)
{
return await this.Client.InternalClient.ComputeTypes.BeginDeleteAsync(
resourceGroupName,
dataFactoryName,
computeTypeName,
cancellationToken);
}
public async Task CreateOrUpdateAsync(
string resourceGroupName,
string dataFactoryName,
ComputeTypeCreateOrUpdateParameters parameters,
CancellationToken cancellationToken)
{
Ensure.IsNotNull(parameters, "parameters");
Ensure.IsNotNull(parameters.ComputeType, "parameters.ComputeType");
Core.Registration.Models.ComputeType internalComputeType = this.Converter.ToCoreType(parameters.ComputeType);
Core.Registration.Models.ComputeTypeCreateOrUpdateResponse response =
await this.Client.InternalClient.ComputeTypes.CreateOrUpdateAsync(
resourceGroupName,
dataFactoryName,
new Core.Registration.Models.ComputeTypeCreateOrUpdateParameters(internalComputeType));
return new ComputeTypeCreateOrUpdateResponse(response, this.Client);
}
public async Task CreateOrUpdateWithRawJsonContentAsync(
string resourceGroupName,
string dataFactoryName,
string computeTypeName,
ComputeTypeCreateOrUpdateWithRawJsonContentParameters parameters,
CancellationToken cancellationToken)
{
Ensure.IsNotNull(parameters, "parameters");
Core.Registration.Models.ComputeTypeCreateOrUpdateWithRawJsonContentParameters internalParameters =
new Core.Registration.Models.ComputeTypeCreateOrUpdateWithRawJsonContentParameters(parameters.Content);
Core.Registration.Models.ComputeTypeCreateOrUpdateResponse response =
await this.Client.InternalClient.ComputeTypes.CreateOrUpdateWithRawJsonContentAsync(
resourceGroupName,
dataFactoryName,
computeTypeName,
internalParameters,
cancellationToken);
return new ComputeTypeCreateOrUpdateResponse(response, this.Client);
}
public async Task DeleteAsync(
string resourceGroupName,
string dataFactoryName,
string computeTypeName,
CancellationToken cancellationToken)
{
return await this.Client.InternalClient.ComputeTypes.DeleteAsync(
resourceGroupName,
dataFactoryName,
computeTypeName,
cancellationToken);
}
public async Task GetAsync(
string resourceGroupName,
string dataFactoryName,
ComputeTypeGetParameters parameters,
CancellationToken cancellationToken)
{
Ensure.IsNotNull(parameters, "parameters");
Core.Registration.Models.ComputeTypeGetParameters internalParameters =
new Core.Registration.Models.ComputeTypeGetParameters(parameters.RegistrationScope,
parameters.ComputeTypeName);
Core.Registration.Models.ComputeTypeGetResponse response =
await this.Client.InternalClient.ComputeTypes.GetAsync(
resourceGroupName,
dataFactoryName,
internalParameters,
cancellationToken);
return new ComputeTypeGetResponse(response, this.Client);
}
public async Task ListAsync(
string resourceGroupName,
string dataFactoryName,
ComputeTypeListParameters parameters,
CancellationToken cancellationToken)
{
Ensure.IsNotNull(parameters, "parameters");
Core.Registration.Models.ComputeTypeListParameters internalParameters =
new Core.Registration.Models.ComputeTypeListParameters(parameters.RegistrationScope)
{
ComputeTypeName = parameters.ComputeTypeName
};
Core.Registration.Models.ComputeTypeListResponse response =
await this.Client.InternalClient.ComputeTypes.ListAsync(
resourceGroupName,
dataFactoryName,
internalParameters,
cancellationToken);
return new ComputeTypeListResponse(response, this.Client);
}
public async Task ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
Ensure.IsNotNull(nextLink, "nextLink");
Core.Registration.Models.ComputeTypeListResponse response =
await this.Client.InternalClient.ComputeTypes.ListNextAsync(nextLink, cancellationToken);
return new ComputeTypeListResponse(response, this.Client);
}
}
} | c# | 12 | 0.663105 | 121 | 40.716867 | 166 | starcoderdata |
void dcn20_set_mcif_arb_params(
struct dc *dc,
struct dc_state *context,
display_e2e_pipe_params_st *pipes,
int pipe_cnt)
{
enum mmhubbub_wbif_mode wbif_mode;
struct mcif_arb_params *wb_arb_params;
int i, j, k, dwb_pipe;
/* Writeback MCIF_WB arbitration parameters */
dwb_pipe = 0;
for (i = 0; i < dc->res_pool->pipe_count; i++) {
if (!context->res_ctx.pipe_ctx[i].stream)
continue;
for (j = 0; j < MAX_DWB_PIPES; j++) {
if (context->res_ctx.pipe_ctx[i].stream->writeback_info[j].wb_enabled == false)
continue;
//wb_arb_params = &context->res_ctx.pipe_ctx[i].stream->writeback_info[j].mcif_arb_params;
wb_arb_params = &context->bw_ctx.bw.dcn.bw_writeback.mcif_wb_arb[dwb_pipe];
if (context->res_ctx.pipe_ctx[i].stream->writeback_info[j].dwb_params.out_format == dwb_scaler_mode_yuv420) {
if (context->res_ctx.pipe_ctx[i].stream->writeback_info[j].dwb_params.output_depth == DWB_OUTPUT_PIXEL_DEPTH_8BPC)
wbif_mode = PLANAR_420_8BPC;
else
wbif_mode = PLANAR_420_10BPC;
} else
wbif_mode = PACKED_444;
for (k = 0; k < sizeof(wb_arb_params->cli_watermark)/sizeof(wb_arb_params->cli_watermark[0]); k++) {
wb_arb_params->cli_watermark[k] = get_wm_writeback_urgent(&context->bw_ctx.dml, pipes, pipe_cnt) * 1000;
wb_arb_params->pstate_watermark[k] = get_wm_writeback_dram_clock_change(&context->bw_ctx.dml, pipes, pipe_cnt) * 1000;
}
wb_arb_params->time_per_pixel = 16.0 / context->res_ctx.pipe_ctx[i].stream->phy_pix_clk; /* 4 bit fraction, ms */
wb_arb_params->slice_lines = 32;
wb_arb_params->arbitration_slice = 2;
wb_arb_params->max_scaled_time = dcn20_calc_max_scaled_time(wb_arb_params->time_per_pixel,
wbif_mode,
wb_arb_params->cli_watermark[0]); /* assume 4 watermark sets have the same value */
dwb_pipe++;
if (dwb_pipe >= MAX_DWB_PIPES)
return;
}
if (dwb_pipe >= MAX_DWB_PIPES)
return;
}
} | c | 20 | 0.657083 | 122 | 35.807692 | 52 | inline |
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.NoSuchElementException;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int N = sc.nextInt(), M = sc.nextInt(), A[] = new int[M], B[] = new int[M];
for (int i = 0;i < M;++ i) {
A[i] = sc.nextInt() - 1;
B[i] = sc.nextInt() - 1;
}
UnionFindTree unionFind = new UnionFindTree(N);
long ans[] = new long[M + 1];
ans[M] = (long)N * (N - 1) / 2;
for (int i = M - 1;i > 0;-- i) {
ans[i] = ans[i + 1];
if (!unionFind.isUnion(A[i], B[i])) {
ans[i] -= (long)unionFind.getSize(A[i]) * unionFind.getSize(B[i]);
unionFind.unite(A[i], B[i]);
}
}
for (int i = 1;i <= M;++ i) out.println(ans[i]);
out.flush();
}
/**
* 素集合データ構造です。<br>
* 連結成分の個数や大きさを取得することができます。
* @author 31536000
*/
public class UnionFindTree {
private int[] parent; // 負ならばデータ数、正ならば親のindex
/**
* size個の頂点を持つ森を作ります。
* @param size 頂点数
*/
public UnionFindTree(int size) {
this.parent = new int[size];
Arrays.fill(this.parent, -1);
}
/**
* その頂点がどの頂点を根とする連結成分に属しているかを求めます。<br>
* 計算量はO(α(N))です。
* @param n 根を求めたい頂点
* @return 根となっている頂点
*/
public int find(int n) {
while(parent[n] >= 0 && parent[parent[n]] >= 0) n = parent[n] = parent[parent[n]]; // 経路圧縮
return parent[n] >= 0 ? parent[n] : n;
}
/**
* 指定した頂点同士を連結します。<br>
* 計算量はO(α(N))です。
* @param l 連結したい頂点
* @param r 連結したい頂点
* @return この関数によって連結されたならtrue、既に連結だったならfalse
*/
public boolean unite(int l, int r) {
l = find(l);
r = find(r);
if (l == r) return false; // 最初から連結
if (parent[l] >= parent[r]) { // rの方が大きい
parent[r] += parent[l]; // 大きい方へ小さい方をマージする
parent[l] = r;
} else {
parent[l] += parent[r]; // 大きい方へ小さい方をマージする
parent[r] = l;
}
return true;
}
/**
* 指定した2個の頂点が連結か判定します。<br>
* 計算量はO(α(N))です。
* @param l 判定したい頂点
* @param r 判定したい頂点
* @return lとrが連結ならばtrue
*/
public boolean isUnion(int l, int r) {
return find(l) == find(r);
}
/**
* 指定した頂点を含む連結成分の要素数を求めます。<br>
* 計算量はO(α(N))です。
* @param n 要素数を求めたい連結成分の要素
* @return 頂点nを含む連結成分の要素数
*/
public int getSize(int n) {
return -parent[find(n)];
}
/**
* 連結成分の個数を求めます。<br>
* 計算量はO(N)です。
* @return 連結成分の個数
*/
public int getUnion() {
int ret = 0;
for (int i : parent) if (i < 0) ++ ret;
return ret;
}
}
public class FastScanner {
private final InputStream in = System.in;
private final byte[] buffer = new byte[1024];
private int read = 0;
private int length = 0;
private boolean hasNextByte() {
if (read < length) return true;
else {
try {
read = 0;
length = in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
return length > 0;
}
private int readByte() {
return hasNextByte() ? buffer[read++] : -1;
}
private boolean isPrintableChar(int c) {
return 33 <= c && c <= 126;
}
private boolean isNumber(int c) {
return '0' <= c && c <= '9';
}
public boolean hasNext() {
while (hasNextByte() && !isPrintableChar(buffer[read])) read++;
return hasNextByte();
}
public char nextChar() {
if (!hasNextByte()) throw new NoSuchElementException();
return (char)readByte();
}
public String next() {
if (!hasNext()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b;
while (isPrintableChar(b = readByte())) sb.appendCodePoint(b);
return sb.toString();
}
public long nextLong() {
if (!hasNext()) throw new NoSuchElementException();
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (!isNumber(b)) throw new NumberFormatException();
while (true) {
if (isNumber(b)) {
n *= 10;
n += b - '0';
} else if (b == -1 || !isPrintableChar(b)) return minus ? -n : n;
else throw new NumberFormatException();
b = readByte();
}
}
public int nextInt() {
long nl = nextLong();
if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
return (int) nl;
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextInt(int width) {
int[] ret = new int[width];
for (int i = 0;i < width;++ i) ret[i] = nextInt();
return ret;
}
public long[] nextLong(int width) {
long[] ret = new long[width];
for (int i = 0;i < width;++ i) ret[i] = nextLong();
return ret;
}
public int[][] nextInt(int width, int height) {
int[][] ret = new int[height][width];
for (int i = 0, j;i < height;++ i) for (j = 0;j < width;++ j) ret[j][i] = nextInt();
return ret;
}
public long[][] nextLong(int width, int height) {
long[][] ret = new long[height][width];
for (int i = 0, j;i < height;++ i) for (j = 0;j < width;++ j) ret[j][i] = nextLong();
return ret;
}
}
} | java | 16 | 0.579414 | 93 | 22.205479 | 219 | codenet |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace NineCubed.Memo.Plugins.Interfaces
{
public interface IPlugin
{
///
/// プラグインID
///
string PluginId { get; set; }
///
/// 親プラグイン
///
IPlugin ParentPlugin { get; set; }
///
/// プラグインのコンポーネントを返します
///
///
IComponent GetComponent();
///
/// プラグインのタイトル
///
string Title { get; set; }
///
/// プラグインが終了できるかどうか
///
/// false:終了できない
bool CanClosePlugin();
///
/// プラグインの終了処理
///
void ClosePlugin();
///
/// フォーカスを設定します
///
void SetFocus();
///
/// 初期処理を行います
/// 初期化に失敗した場合などは false を返すとプラグインが破棄されます
/// この段階ではまだ他のプラグインに配置されていないため、コンポーネントのサイズなどは取得できません
///
///
bool Initialize(PluginCreateParam param);
///
/// プラグイン配置後の初期化処理を行います
///
/// <param name="param">
///
void InitializePlaced();
}
} | c# | 8 | 0.508287 | 60 | 21.970588 | 68 | starcoderdata |
import os
import time
import re
import yaml
import sqlite3
from sqlite3 import Error
from subprocess import check_output
db_path = ".tmp/source/Public/index.db"
def get_id(con, cursor, table, field, value, force_new=False):
cursor.execute('SELECT rowid FROM {} WHERE {} = "{}";'.format(table, field, value))
row = cursor.fetchall()
if len(row) == 0 or force_new:
cursor.execute('SELECT MAX(rowid) + 1 FROM {}'.format(table))
id_ = cursor.fetchall()[0][0]
if not id_:
id_ = 1
cursor.execute(
'INSERT INTO {} (rowid, {}) VALUES (?,?)'.format(table, field),
(id_, value)
)
con.commit()
return id_
return row[0][0]
def normalize(name):
return name.replace(' ', '').lower()
def register_manifest(con, cursor, data, pathParts, manifest, manifestFilename):
# IDS
id_ = get_id(con, cursor, 'ids', 'id', data['PackageIdentifier'])
# NAMES
if not 'PackageName' in data:
data['PackageName'] = data['PackageIdentifier'].split('.')[-1]
name = get_id(con, cursor, 'names', 'name', data['PackageName'])
# MONIKERS
if not 'Moniker' in data:
data['Moniker'] = data['PackageName'].lower()
moniker = get_id(con, cursor, 'monikers', 'moniker', data['Moniker'])
# VERSION
version = get_id(con, cursor, 'versions', 'version', data['PackageVersion'])
# PATHPARTS
parent_pathpart = 1
for part in pathParts[1:]:
pathpart = get_id(con, cursor, 'pathparts', 'pathpart', part)
cursor.execute('UPDATE pathparts SET parent={} WHERE rowid={};'.format(parent_pathpart, pathpart))
parent_pathpart = pathpart
pathpart = get_id(con, cursor, 'pathparts', 'pathpart', manifestFilename, True)
cursor.execute('UPDATE pathparts SET parent={} WHERE rowid={};'.format(parent_pathpart, pathpart))
con.commit()
# MANIFEST
cursor.execute(
'INSERT INTO manifest (rowid, id, name, moniker, version, channel, pathpart) VALUES (?,?,?,?,?,?,?)',
(manifest, id_, name, moniker, version, 1, pathpart)
)
con.commit()
# NORM_NAMES
norm_name = get_id(con, cursor, 'norm_names', 'norm_name', normalize(data['PackageName']))
cursor.execute(
'INSERT INTO norm_names_map (manifest, norm_name) VALUES (?,?)',
(manifest, norm_name)
)
con.commit()
# NORM_PUBLISHERS
if not 'Publisher' in data:
data['Publisher'] = data['PackageIdentifier'].split('.')[0]
norm_publisher = get_id(con, cursor, 'norm_publishers', 'norm_publisher', normalize(data['Publisher']))
cursor.execute(
'INSERT INTO norm_publishers_map (manifest, norm_publisher) VALUES (?,?)',
(manifest, norm_publisher)
)
con.commit()
# TAGS
if 'Tags' in data:
for _tag in data['Tags']:
tag = get_id(con, cursor, 'tags', 'tag', _tag)
cursor.execute('INSERT INTO tags_map (manifest, tag) VALUES (?,?)', (manifest, tag))
con.commit()
# COMMANDS
if 'Commands' in data:
for _command in data['Commands']:
command = get_id(con, cursor, 'commands', 'command', _command)
cursor.execute(
'INSERT INTO commands_map (manifest, command) VALUES (?,?)',
(manifest, command)
)
con.commit()
# PFNS
if 'Installers' in data:
if 'PackageFamilyName' in data['Installers'][0]:
pfn = get_id(con, cursor, 'pfns', 'pfn', data['Installers'][0]['PackageFamilyName'])
cursor.execute('INSERT INTO pfns_map (manifest, pfn) VALUES (?,?)', (manifest, pfn))
con.commit()
# PRODUCTCODES
if 'ProductCode' in data['Installers'][0]:
productcode = get_id(
con, cursor, 'productcodes', 'productcode',
data['Installers'][0]['ProductCode']
)
cursor.execute(
'INSERT INTO productcodes_map (manifest, productcode) VALUES (?,?)',
(manifest, productcode)
)
con.commit()
def create_catalog(con):
cursor = con.cursor()
# CREATE SQLITE DATABASE
manifest = 1
cursor.execute(
'INSERT INTO pathparts (rowid,pathpart) VALUES (?,?)',
(1, 'manifests')
)
con.commit()
cursor.execute(
'UPDATE metadata SET value=? WHERE name=?;',
(int(time.time()), 'lastwritetime')
)
con.commit()
for (root,_,files) in os.walk('manifests'):
if re.match('.*(?:[0-9]+\.?){2,3}\.[0-9]+$', root):
pathParts = root.split(os.path.sep)
packageName = ".".join(pathParts[2:-1])
manifestFilename = ""
packageData = {}
for file in files:
if file.endswith(".yaml"):
with open(os.path.join(root, file), 'r') as stream:
try:
data = yaml.safe_load(stream)
print('processing', data['PackageIdentifier'], data['PackageVersion'])
except yaml.YAMLError as exc:
print(exc)
if data['ManifestType'] == 'merged':
packageData = data
manifestFilename = file
break
register_manifest(con, cursor, packageData, pathParts, manifest, manifestFilename)
manifest += 1
if __name__ == '__main__':
if os.path.exists(db_path):
os.remove(db_path)
else:
os.makedirs(os.path.dirname(db_path))
con = None
try:
con = sqlite3.connect(db_path)
sql_file = open("index.db.sql")
sql_as_string = sql_file.read()
cur = con.cursor()
cur.executescript(sql_as_string)
con.commit()
create_catalog(con)
except Error as e:
print(e)
finally:
if con:
con.close() | python | 20 | 0.549509 | 109 | 30.139896 | 193 | starcoderdata |
/*****************************************************************
Morozko Java Library org.fugerit.java.core.db
Copyright (c) 2006 Morozko
All rights reserved. This program and the accompanying materials
are made available under the terms of the Apache License v2.0
which accompanies this distribution, and is available at
http://www.apache.org/licenses/
(txt version : http://www.apache.org/licenses/LICENSE-2.0.txt
html version : http://www.apache.org/licenses/LICENSE-2.0.html)
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).
*****************************************************************/
/*
* @(#)DefaultTableBackup.java
*
* @project : org.fugerit.java.core.db
* @package : org.fugerit.java.core.db.backup
* @creation : 05/set/06
* @license : META-INF/LICENSE.TXT
*/
package org.fugerit.java.core.db.backup;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.fugerit.java.core.db.metadata.query.QueryColumnMap;
import org.fugerit.java.core.db.metadata.query.QueryColumnModel;
import org.fugerit.java.core.db.metadata.query.QueryMetadataFacade;
import org.fugerit.java.core.lang.helpers.ClassHelper;
import org.fugerit.java.core.log.BasicLogObject;
/**
*
*
* @author a.k.a. Fugerit
*/
public class DefaultTableBackup extends BasicLogObject implements TableBackup {
public DefaultTableBackup() {
this.getLogger().debug( this.getClass().getName()+" VERSION 0.74" );
this.commitOn = 10;
}
private int commitOn;
private String insertMode;
private String adaptorFrom;
private String adaptorTo;
private String columnCheckMode;
private String statementMode;
/* (non-Javadoc)
* @see org.fugerit.java.core.db.backup.TableBackup#setProperty(java.lang.String, java.lang.String)
*/
public boolean setProperty(String name, String value) {
boolean result = false;
this.getLogger().debug( "setProperty "+name+"="+value );
if ( PROP_COMMIT_ON.equalsIgnoreCase( name ) ) {
this.commitOn = Integer.parseInt( value );
result = true;
} else if ( PROP_STATEMENT_MODE.equalsIgnoreCase( name ) ) {
this.statementMode = value;
} else if ( PROP_INSERT_MODE.equalsIgnoreCase( name ) ) {
this.insertMode = value;
} else if ( PROP_ADAPTOR_FROM.equalsIgnoreCase( name ) ) {
this.adaptorFrom = value;
} else if ( PROP_ADAPTOR_TO.equalsIgnoreCase( name ) ) {
this.adaptorTo = value;
} else if ( PROP_COLUMN_CHECK_MODE.equalsIgnoreCase( name ) ) {
this.columnCheckMode = value;
}
return result;
}
private String[] getColumnNames(Connection from, Connection to, String table, String select ) throws SQLException {
String result[] = null;
try {
List list = new ArrayList
QueryColumnMap mapFrom = null;
try {
mapFrom = QueryMetadataFacade.columnMap( from, select );
} catch (Exception eM ){
this.getLogger().info( "error : "+eM+" try noModify query - "+select );
mapFrom = QueryMetadataFacade.columnMap( from, select, true );
}
QueryColumnMap mapTo = QueryMetadataFacade.columnMap( to, " SELECT * FROM "+table );
this.getLogger().debug( "columns from : "+ mapFrom.size() );
this.getLogger().debug( "columns to : "+ mapTo.size() );
Iterator it = null;
if ( PROP_INSERT_MODE_VALUE_RIGHT.equals( this.insertMode ) ) {
it = mapTo.iterator();
} else {
it = mapFrom.iterator();
}
while ( it.hasNext() ) {
QueryColumnModel columnFrom = (QueryColumnModel)it.next();
QueryColumnModel columnTo = mapTo.get( columnFrom.getName() );
if ( columnTo != null || PROP_COLUMN_CHECK_MODE_VALUE_NOCHECK.equalsIgnoreCase( this.columnCheckMode ) ) {
list.add( columnFrom.getName() );
} else {
this.getLogger().warn( "column : "+columnFrom.getName()+" doesn't exist in destination, skipping column!" );
}
}
result = new String[ list.size() ];
for ( int k=0; k<list.size(); k++ ) {
result[k] = (String)list.get( k );
}
} catch (Exception e) {
e.printStackTrace();
throw ( new SQLException( e.toString() ) );
}
return result;
}
private String[] getTableColumnNames(Connection conn, Connection to, String table, String select) throws SQLException {
return this.getColumnNames(conn, to, table, select );
}
/* (non-Javadoc)
* @see it.engine.backup.TableBackup#backupTable(java.lang.String, java.sql.Connection, java.sql.Connection)
*/
public int backupTable(String table, Connection from, Connection to , TableConfig tableConfig )throws SQLException {
return this.backupTable(table, from, to, "SELECT * FROM "+table, tableConfig );
}
/* (non-Javadoc)
* @see it.engine.backup.TableBackup#backupTable(java.lang.String, java.sql.Connection, java.sql.Connection, java.lang.String)
*/
public int backupTable(String table, Connection from, Connection to, String select, TableConfig tableConfig ) throws SQLException {
this.getLogger().info( "table : "+table );
this.getLogger().info( "select : "+select );
int result = 0;
long starTime = System.currentTimeMillis();
int count = 0;
if ( PROP_STATEMENT_MODE_SINGLE.equalsIgnoreCase( this.statementMode ) ) {
to.setAutoCommit( true );
} else {
to.setAutoCommit( false );
}
this.getLogger().debug("Statement mode : "+this.statementMode);
this.getLogger().debug("Starting backup of table : "+table);
this.getLogger().debug("Select statement : "+select);
// costruisco la insert
String[] toTableColumns = this.getTableColumnNames(from, to, table, select);
StringBuffer queryBuffer = new StringBuffer();
queryBuffer.append( "INSERT INTO "+table+" (" );
for (int k=0; k<toTableColumns.length-1; k++) {
queryBuffer.append( toTableColumns[k]+"," );
}
queryBuffer.append( toTableColumns[toTableColumns.length-1]+")" );
queryBuffer.append( " VALUES (" );
for (int k=0; k<toTableColumns.length-1; k++) {
queryBuffer.append( "?, " );
}
queryBuffer.append( "?)" );
// eseguo la query sulla sorgente dei dati
PreparedStatement fromPS = from.prepareStatement(select);
ResultSet fromRS = fromPS.executeQuery();
// inizio l'inserimento dei dati
String insert = queryBuffer.toString();
this.getLogger().info("Insert statement : "+insert);
PreparedStatement toPS = to.prepareStatement(insert);
// inserimento dati
int rowCount = 0;
int copyCount = 0;
// test
ResultSetMetaData rsmd = fromRS.getMetaData();
// test
BackupAdaptor backupAdaptorFrom = null;;
BackupAdaptor backupAdaptorTo = null;;
if ( tableConfig.getAdaptorFrom() != null ) {
backupAdaptorFrom = tableConfig.getAdaptorFrom();
this.getLogger().info("Override adaptor from : "+backupAdaptorFrom );
} else {
try {
backupAdaptorFrom = (BackupAdaptor)ClassHelper.newInstance( this.adaptorFrom );
} catch (Exception e) {
throw new SQLException( e.toString() );
}
}
if ( tableConfig.getAdaptorTo() != null ) {
backupAdaptorTo = tableConfig.getAdaptorTo();
this.getLogger().info("Override adaptor to : "+backupAdaptorTo );
} else {
try {
backupAdaptorTo = (BackupAdaptor)ClassHelper.newInstance( this.adaptorTo );
} catch (Exception e) {
throw new SQLException( e.toString() );
}
}
while (fromRS.next()) {
rowCount++;
String comment = null;
StringBuffer fullComment = new StringBuffer();
long res = 0;
try {
for (int k=0; k<=toTableColumns.length-1; k++) {
String colName = toTableColumns[k];
int colIndex = (k+1);
comment = "setting column "+colName+" : "+colIndex;
Object obj = backupAdaptorFrom.get( fromRS , rsmd, colIndex );
fullComment.append( " "+comment+" '"+obj+"'" );
backupAdaptorTo.set( toPS , rsmd, obj, colIndex );
}
comment = "executing insert ";
try {
if ( PROP_STATEMENT_MODE_SINGLE.equalsIgnoreCase( this.statementMode ) ) {
res+= toPS.executeUpdate();
} else if ( PROP_STATEMENT_MODE_EXECUTE.equalsIgnoreCase( this.statementMode ) ) {
res+= toPS.executeUpdate();
} else {
toPS.addBatch();
}
} catch (SQLException e) {
this.getLogger().error("Error backing up table "+table+" on row "+rowCount+", "+fullComment, e);
throw e;
}
this.getLogger().debug( "backupTable() res -> "+res );
copyCount++;
count++;
// System.out.println( "----" );
if ( count>= commitOn ) {
this.getLogger().debug( "commit count : "+count+" time : "+(System.currentTimeMillis()-starTime) );
if ( PROP_STATEMENT_MODE_SINGLE.equalsIgnoreCase( this.statementMode ) ) {
// skip commit
} else if ( PROP_STATEMENT_MODE_EXECUTE.equalsIgnoreCase( this.statementMode ) ) {
to.commit();
} else {
toPS.executeBatch();
to.commit();
toPS.clearBatch();
}
count = 0;
}
} catch (Exception e) {
this.getLogger().error("Error backing up table "+table+" on row "+rowCount+", "+comment, e);
result++;
}
}
// execute all remaining
if ( PROP_STATEMENT_MODE_EXECUTE.equalsIgnoreCase( this.statementMode ) ) {
to.commit();
} else {
toPS.executeBatch();
to.commit();
toPS.clearBatch();
}
to.setAutoCommit( true );
fromRS.close();
fromPS.close();
this.getLogger().info("Total source rows : "+rowCount);
this.getLogger().info("Total copied rows : "+copyCount);
this.getLogger().info("Total time (seconds) : "+((System.currentTimeMillis()-starTime)/1000) );
this.getLogger().info("Return code [error count] : '"+result+"'");
return result;
}
} | java | 21 | 0.581088 | 135 | 36.131757 | 296 | starcoderdata |
function(w,h){
if(!this.canvas) return;
if(!w || !h){
// Reset the fullscreen toggle if necessary
if(this.fullscreen && !fullScreenApi.isFullScreen()) this.fullscreen = false;
if(this.fullscreen) this.container.css('background','white');
else this.container.css('background',this.containerbg);
if(this.fullwindow){
this.canvas.css({'width':0,'height':0});
w = $(window).width();
h = $(window).height();
this.canvas.css({'width':w,'height':h});
$(document).css({'width':w,'height':h});
}else{
// We have to zap the width of the canvas to let it take the width of the container
this.canvas.css({'width':0,'height':0});
w = this.container.outerWidth();
h = this.container.outerHeight();
this.canvas.css({'width':w,'height':h});
}
}
if(w == this.wide && h == this.tall) return;
this.setWH(w,h);
// Trigger callback
this.trigger("resize",{w:w,h:h});
} | javascript | 15 | 0.62311 | 87 | 33.333333 | 27 | inline |
using System.Collections.Generic;
using TennisTable.Classes;
using TennisTable.Acces;
namespace TennisTable.Gestion
{
///
/// Couche intermédiaire de gestion (Business Layer)
///
public class GJoueurs : GBase
{
public GJoueurs()
{ }
public GJoueurs(string sChaineConnexion)
: base(sChaineConnexion)
{ }
public int Ajouter(int license, string nom, string prenom, int classement, string mail, int sexe, int? club)
{ return new AJoueurs(ChaineConnexion).Ajouter(license, nom, prenom, classement, mail, sexe, club); }
public int Modifier(int joueurId, int license, string nom, string prenom, int classement, string mail, int sexe, int? club)
{ return new AJoueurs(ChaineConnexion).Modifier(joueurId, license, nom, prenom, classement, mail, sexe, club); }
public List Lire(string index)
{ return new AJoueurs(ChaineConnexion).Lire(index); }
public CJoueurs Lire_ID(int joueurId)
{ return new AJoueurs(ChaineConnexion).Lire_ID(joueurId); }
public int Supprimer(int joueurId)
{ return new AJoueurs(ChaineConnexion).Supprimer(joueurId); }
public int ObtenirLigne(int joueurId, string index)
{ return new AJoueurs(ChaineConnexion).ObtenirLigne(joueurId, index); }
}
} | c# | 13 | 0.68071 | 131 | 42.645161 | 31 | starcoderdata |
public void resubscribeSessions() throws JMSException, QpidException, FailoverException
{
ArrayList sessions = new ArrayList(_conn.getSessions().values());
_logger.info(MessageFormat.format("Resubscribing sessions = {0} sessions.size={1}", sessions, sessions.size())); // FIXME: removeKey?
for (Iterator it = sessions.iterator(); it.hasNext();)
{
AMQSession_0_8 s = (AMQSession_0_8) it.next();
// reset the flow control flag
// on opening channel, broker sends flow blocked if virtual host is blocked
// if virtual host is not blocked, then broker does not send flow command
// that's why we need to reset the flow control flag
s.setFlowControl(true);
reopenChannel(s.getChannelId(), s.getDefaultPrefetchHigh(), s.getDefaultPrefetchLow(), s.isTransacted());
s.setPrefetchLimits(s.getDefaultPrefetchHigh(), 0);
s.resubscribe();
}
} | java | 10 | 0.638298 | 141 | 53.888889 | 18 | inline |
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.smithy.model.validation.linters;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import software.amazon.smithy.model.FromSourceLocation;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.loader.ModelSyntaxException;
import software.amazon.smithy.model.node.NodeMapper;
import software.amazon.smithy.model.selector.AttributeValue;
import software.amazon.smithy.model.selector.Selector;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.ShapeId;
import software.amazon.smithy.model.validation.AbstractValidator;
import software.amazon.smithy.model.validation.ValidationEvent;
import software.amazon.smithy.model.validation.ValidatorService;
import software.amazon.smithy.utils.OptionalUtils;
import software.amazon.smithy.utils.SimpleParser;
/**
* Emits a validation event for each shape that matches a selector.
*/
public final class EmitEachSelectorValidator extends AbstractValidator {
/**
* EmitEachSelector configuration settings.
*/
public static final class Config {
private Selector selector;
private ShapeId bindToTrait;
private MessageTemplate messageTemplate;
/**
* Gets the required selector that matches shapes.
*
* shape that matches the given selector will emit a
* validation event.
*
* @return Selector to match on.
*/
public Selector getSelector() {
return selector;
}
public void setSelector(Selector selector) {
this.selector = selector;
}
/**
* Gets the optional trait that each emitted event is bound to.
*
* event is only emitted for shapes that have this trait.
*
* @return Returns the trait to bind each event to.
*/
public ShapeId getBindToTrait() {
return bindToTrait;
}
public void setBindToTrait(ShapeId bindToTrait) {
this.bindToTrait = bindToTrait;
}
/**
* Gets the optional message template that can reference selector variables.
*
* @return Returns the message template.
*/
public String getMessageTemplate() {
return messageTemplate == null ? null : messageTemplate.toString();
}
/**
* Sets the optional message template for each emitted event.
*
* @param messageTemplate Message template to set.
* @throws ModelSyntaxException if the message template is invalid.
*/
public void setMessageTemplate(String messageTemplate) {
this.messageTemplate = new MessageTemplateParser(messageTemplate).parse();
}
}
public static final class Provider extends ValidatorService.Provider {
public Provider() {
super(EmitEachSelectorValidator.class, configuration -> {
NodeMapper mapper = new NodeMapper();
Config config = mapper.deserialize(configuration, Config.class);
return new EmitEachSelectorValidator(config);
});
}
}
private final Config config;
/**
* @param config Validator configuration.
*/
public EmitEachSelectorValidator(Config config) {
this.config = config;
Objects.requireNonNull(config.selector, "selector is required");
}
@Override
public List validate(Model model) {
// Short-circuit the validation if the binding trait is never used.
if (config.bindToTrait != null && !model.getAppliedTraits().contains(config.getBindToTrait())) {
return Collections.emptyList();
} else if (config.messageTemplate == null) {
return validateWithSimpleMessages(model);
} else {
return validateWithTemplate(model);
}
}
private List validateWithSimpleMessages(Model model) {
return config.getSelector().select(model).stream()
.flatMap(shape -> OptionalUtils.stream(createSimpleEvent(shape)))
.collect(Collectors.toList());
}
private Optional createSimpleEvent(Shape shape) {
FromSourceLocation location = determineEventLocation(shape);
// Only create a validation event if the bound trait (if any) is present on the shape.
if (location == null) {
return Optional.empty();
}
return Optional.of(danger(shape, location, "Selector capture matched selector: " + config.getSelector()));
}
// Determine where to bind the event. Only emit an event when `bindToTrait` is
// set if the shape actually has the trait.
private FromSourceLocation determineEventLocation(Shape shape) {
return config.bindToTrait == null
? shape.getSourceLocation()
: shape.findTrait(config.bindToTrait).orElse(null);
}
// Created events with a message template requires emitting matches
// into a BiConsumer and building up a mutated List of events.
private List validateWithTemplate(Model model) {
List events = new ArrayList<>();
config.getSelector()
.runner()
.model(model)
.selectMatches((shape, vars) -> createTemplatedEvent(shape, vars).ifPresent(events::add));
return events;
}
private Optional createTemplatedEvent(Shape shape, Map<String, Set vars) {
FromSourceLocation location = determineEventLocation(shape);
// Only create a validation event if the bound trait (if any) is present on the shape.
if (location == null) {
return Optional.empty();
}
// Create an AttributeValue from the matched shape and context vars.
// This is then used to expand message template scoped attributes.
AttributeValue value = AttributeValue.shape(shape, vars);
return Optional.of(danger(shape, location, config.messageTemplate.expand(value)));
}
/**
* A message template is made up of "parts", where each part is a function that accepts
* an {@link AttributeValue} and returns a String.
*/
private static final class MessageTemplate {
private final String template;
private final List<Function<AttributeValue, String>> parts;
private MessageTemplate(String template, List<Function<AttributeValue, String>> parts) {
this.template = template;
this.parts = parts;
}
/**
* Expands the MessageTemplate using the provided AttributeValue.
*
* selector result shape along with the variables that were captured
* when the shape was matched are used to create an AttributeValue which
* is then passed to this message to create a validation event message.
*
* @param value The attribute value to pass to each part.
* @return Returns the expanded message template.
*/
private String expand(AttributeValue value) {
StringBuilder builder = new StringBuilder();
for (Function<AttributeValue, String> part : parts) {
builder.append(part.apply(value));
}
return builder.toString();
}
@Override
public String toString() {
return template;
}
}
/**
* Parses message templates by slicing out literals and scoped attribute selectors.
*
* "@" characters in a row (@@) are considered a single "@" because the
* first "@" acts as an escape character for the second.
*/
private static final class MessageTemplateParser extends SimpleParser {
private int mark = 0;
private final List<Function<AttributeValue, String>> parts = new ArrayList<>();
private MessageTemplateParser(String expression) {
super(expression);
}
MessageTemplate parse() {
while (!eof()) {
consumeUntilNoLongerMatches(c -> c != '@');
// '@' followed by '@' is an escaped '@", so keep parsing
// the marked literal if that's the case.
if (peek(1) == '@') {
skip(); // consume the first @.
addLiteralPartIfNecessary();
skip(); // skip the escaped @.
mark++;
} else if (!eof()) {
addLiteralPartIfNecessary();
List path = AttributeValue.parseScopedAttribute(this);
parts.add(attributeValue -> attributeValue.getPath(path).toMessageString());
mark = position();
}
}
addLiteralPartIfNecessary();
return new MessageTemplate(expression(), parts);
}
@Override
public RuntimeException syntax(String message) {
return new RuntimeException("Syntax error at line " + line() + " column " + column()
+ " of EmitEachSelector message template: " + message);
}
private void addLiteralPartIfNecessary() {
String slice = sliceFrom(mark);
if (!slice.isEmpty()) {
parts.add(ignoredAttribute -> slice);
}
mark = position();
}
}
} | java | 19 | 0.635598 | 115 | 37.138686 | 274 | starcoderdata |
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from configparser import ConfigParser
import os
from utility import preprocess_labels
def main():
config_file = "./config.ini"
cp = ConfigParser()
cp.read(config_file)
dataset_csv_dir = cp["TRAIN"].get("dataset_csv_dir")
label_handling = {"empty": cp["LABEL"].get("empty")}
class_names = cp["DEFAULT"].get("class_names").split(",")
for class_name in class_names:
label_handling[class_name] = cp["LABEL"].get(class_name)
trainfile = os.path.join(dataset_csv_dir, "train.csv")
# validationfile = os.path.join(dataset_csv_dir, "valid.csv")
train_df = pd.read_csv(trainfile)
# validation_df = pd.read_csv(validationfile)
processed_train_df = preprocess_labels(train_df, label_handling, class_names)
# print(label_handling["empty"])
filenum = train_df.shape[0]
for class_name in class_names:
print(f"**Stats for {class_name}**")
print(f"labeled: {str(train_df[class_name].count())}")
print(f"NaN: {str(filenum - train_df[class_name].count())}")
print(f"labeled counts: \n{str(train_df[class_name].value_counts())}")
print(f"uncertain label policy: {label_handling[class_name]}")
print(f"counts after preprocessing: \n{str(processed_train_df[class_name].value_counts())}")
if __name__ == "__main__":
main() | python | 16 | 0.656205 | 100 | 36.918919 | 37 | starcoderdata |
Programming/Segmented Least Squares.cpp
/*
Petar 'PetarV' Velickovic
Algorithm: Segmented Least Squares (Microchallenge)
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define MAX_N 501
using namespace std;
typedef long long lld;
/*
Algorithm for calculating the minimal cost of approximating a set of points with segments
The cost of a particular set of segments is calculated as sum(i=1 -> n) E_i + c*L,
where E_i is the error of the i-th point WRT its segment,
c the cost of each segment,
and L the amount of segments used
Input: Set of points (from file) + Cost of each segment (from command line)
Returns: The minimal cost (to command line) + segments used (to file)
Complexity: O(n^2) time, O(n^2) memory
*/
int n = 1, c;
struct Point
{
int x, y;
bool operator <(const Point &p) const
{
return (x < p.x);
}
};
Point pts[MAX_N];
double err[MAX_N][MAX_N]; //err[i][j] - total error by approximating points [i..j] by a segment
double a[MAX_N][MAX_N]; //a[i][j] - the slope of the segment used to approximate points [i..j]
double b[MAX_N][MAX_N]; //b[i][j] - the y-intercept of the segment used to approximate points [i..j]
int xySums[MAX_N], xSums[MAX_N], ySums[MAX_N], xSqrSums[MAX_N], ySqrSums[MAX_N]; //prefix sums for x_i * y_i, x_i, y_i, x_i * x_i and y_i * y_i
double minCost[MAX_N]; //minCost[j] - optimal cost for points [1..j]
int retIndex[MAX_N]; //the last segment in the optimal case for points [1..j] is [retIndex[j], j]
struct Segment
{
double x1, y1, x2, y2;
Segment()
{
this->x1 = 0;
this->y1 = 0;
this->x2 = 0;
this->y2 = 0;
}
Segment(double x1, double y1, double x2, double y2)
{
this->x1 = x1;
this->y1 = y1;
this->x2 = x2;
this->y2 = y2;
}
};
vector ret; //final solution
inline void Precalculate()
{
sort(pts+1, pts+n+1); //can be omitted if points are guaranteed to be given in ascending X order
for (int i=1;i<=n;i++)
{
xSums[i] = xSums[i-1] + pts[i].x;
ySums[i] = ySums[i-1] + pts[i].y;
xSqrSums[i] = xSqrSums[i-1] + pts[i].x * pts[i].x;
xySums[i] = xySums[i-1] + pts[i].x * pts[i].y;
ySqrSums[i] = ySqrSums[i-1] + pts[i].y * pts[i].y;
}
for (int i=1;i<=n;i++)
{
for (int j=i+1;j<=n;j++)
{
int nn = j - i + 1;
int xySum = xySums[j] - xySums[i-1];
int xSum = xSums[j] - xSums[i-1];
int ySum = ySums[j] - ySums[i-1];
int xSqrSum = xSqrSums[j] - xSqrSums[i-1];
int ySqrSum = ySqrSums[j] - ySqrSums[i-1];
a[i][j] = ((nn * xySum - xSum * ySum) * 1.0) / ((nn * xSqrSum - xSum * xSum) * 1.0);
b[i][j] = ((ySum - a[i][j] * xSum) * 1.0) / (nn * 1.0);
err[i][j] = a[i][j] * a[i][j] * xSqrSum + 2.0 * a[i][j] * b[i][j] * xSum - 2.0 * a[i][j] * xySum + nn * b[i][j] * b[i][j] - 2.0 * b[i][j] * ySum + ySqrSum;
}
}
}
inline double SegmentedLeastSquares()
{
for (int j=1;j<=n;j++)
{
minCost[j] = err[1][j] + c;
retIndex[j] = 1;
for (int i=2;i<=j;i++)
{
if (minCost[i-1] + err[i][j] + c < minCost[j])
{
minCost[j] = minCost[i-1] + err[i][j] + c;
retIndex[j] = i;
}
}
}
return minCost[n];
}
inline void getSegments()
{
stack S;
int currInd = n;
while (currInd > 1)
{
int nextInd = retIndex[currInd];
if (nextInd == currInd)
{
S.push(Segment(pts[currInd-1].x, pts[currInd-1].y, pts[currInd].x, pts[currInd].y));
}
else
{
double x1 = pts[nextInd].x;
double y1 = x1 * a[nextInd][currInd] + b[nextInd][currInd];
double x2 = pts[currInd].x;
double y2 = x2 * a[nextInd][currInd] + b[nextInd][currInd];
S.push(Segment(x1, y1, x2, y2));
}
currInd = nextInd - 1;
}
while (!S.empty())
{
ret.push_back(S.top());
S.pop();
}
}
int main(int argc, char **argv)
{
sscanf(argv[1],"%d",&c);
freopen("/Users/PetarV/.makedots","r",stdin);
while (scanf("%d%d",&pts[n].x,&pts[n].y) == 2) n++;
n--;
Precalculate();
printf("%.10lf\n",SegmentedLeastSquares());
freopen("/Users/PetarV/.makedots-segments","w",stdout);
getSegments();
for (int i=0;i<ret.size();i++)
{
printf("%d %d %d %d\n",(int)ret[i].x1, (int)ret[i].y1, (int)ret[i].x2, (int)ret[i].y2);
}
return 0;
} | c++ | 20 | 0.533539 | 167 | 27.092486 | 173 | starcoderdata |
using System;
using Microsoft.Band.Portable.Notifications;
#if __ANDROID__ || __IOS__ || WINDOWS_PHONE_APP
using NativeMessageFlags = Microsoft.Band.Notifications.MessageFlags;
using NativeVibrationType = Microsoft.Band.Notifications.VibrationType;
#endif
#if __ANDROID__
using NativeGuid = Java.Util.UUID;
#elif __IOS__
using NativeGuid = Foundation.NSUuid;
#elif WINDOWS_PHONE_APP
using NativeGuid = System.Guid;
#endif
namespace Microsoft.Band.Portable
{
internal static class NotificationExtensions
{
#if __ANDROID__ || __IOS__ || WINDOWS_PHONE_APP
internal static NativeGuid ToNative(this Guid guid)
{
#if __ANDROID__
return NativeGuid.FromString(guid.ToString("D"));
#elif __IOS__
return new NativeGuid(guid.ToString("D"));
#elif WINDOWS_PHONE_APP
return guid;
#endif
}
internal static Guid FromNative(this NativeGuid guid)
{
#if __ANDROID__
return Guid.Parse(guid.ToString());
#elif __IOS__
return Guid.Parse(guid.AsString());
#elif WINDOWS_PHONE_APP
return guid;
#endif
}
internal static NativeMessageFlags ToNative(this MessageFlags messageFlags)
{
// can't use switch on Android as this is not an enum
if (messageFlags == MessageFlags.ShowDialog)
return NativeMessageFlags.ShowDialog;
return NativeMessageFlags.None;
}
internal static NativeVibrationType ToNative(this VibrationType vibrationType)
{
// can't use switch on Android as this is not an enum
if (vibrationType == VibrationType.RampDown)
return NativeVibrationType.RampDown;
if (vibrationType == VibrationType.RampUp)
return NativeVibrationType.RampUp;
if (vibrationType == VibrationType.NotificationOneTone)
return NativeVibrationType.NotificationOneTone;
if (vibrationType == VibrationType.NotificationTwoTone)
return NativeVibrationType.NotificationTwoTone;
if (vibrationType == VibrationType.NotificationAlarm)
return NativeVibrationType.NotificationAlarm;
if (vibrationType == VibrationType.NotificationTimer)
return NativeVibrationType.NotificationTimer;
if (vibrationType == VibrationType.OneToneHigh)
return NativeVibrationType.OneToneHigh;
if (vibrationType == VibrationType.ThreeToneHigh)
return NativeVibrationType.ThreeToneHigh;
if (vibrationType == VibrationType.TwoToneHigh)
return NativeVibrationType.TwoToneHigh;
throw new ArgumentOutOfRangeException("vibrationType", "Invalid VibrationType specified.");
}
#endif
}
} | c# | 15 | 0.660358 | 103 | 35.113924 | 79 | starcoderdata |
// <copyright file="Program.cs" company="
// Copyright under MIT Licence. See https://opensource.org/licenses/mit-license.php.
//
namespace Jmw.AppInitializer.AspNetCore
{
///
/// Program main class.
///
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public class Program
{
///
/// Entry point.
///
/// <param name="args">Command line arguments.
public static void Main(string[] args)
{
}
}
} | c# | 10 | 0.598592 | 91 | 26.047619 | 21 | starcoderdata |
func validateBlock(block *sdk.Int) error {
// nil value means that the fork has not yet been applied
if block == nil {
return nil
}
if block.IsNegative() {
return sdkerrors.Wrapf(
ErrInvalidChainConfig, "block value cannot be negative: %s", block,
)
}
return nil
} | go | 10 | 0.69395 | 70 | 19.142857 | 14 | inline |
// go.apps.dialogue
// ================
// Models, Views and other stuff for the dialogue screen
(function(exports) {
})(go.apps.dialogue = {}); | javascript | 3 | 0.656863 | 57 | 28.142857 | 7 | starcoderdata |
static
bool checkPrefilterMatch(const ResultSet &ground_truth, const ResultSet &ue2,
bool highlander) {
if (highlander) {
// Highlander + prefilter is tricky. Best we can do is say that if PCRE
// returns matches, UE2 must return a match, though it may not be one
// of the ones returned by PCRE (it may be an earlier match).
if (!ground_truth.matches.empty()) {
return ue2.matches.size() == 1;
}
// We can't verify anything more.
return true;
} else if (!limit_matches || ue2.matches.size() < limit_matches) {
// In prefilter mode, every match found by PCRE must be found by UE2,
// but the UE2 set may be a superset of the PCRE match set.
return std::includes(ue2.matches.begin(), ue2.matches.end(),
ground_truth.matches.begin(), ground_truth.matches.end());
}
// Otherwise, we've hit our match limit. Prefilter mode is quite difficult
// to verify in this case, so we just verify that "something happened".
return true;
} | c++ | 13 | 0.623845 | 79 | 46.086957 | 23 | inline |
# =========================================================================
# Copyright 2015 Yunify, Inc.
# -------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this work except in compliance with the License.
# You may obtain a copy of the License in the LICENSE file, or 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.
# =========================================================================
import os
import sys
import time
import random
import hashlib
from datetime import datetime
try:
from urllib.parse import quote, quote_plus, urlparse
except:
from urllib import quote, quote_plus
from urlparse import urlparse
from qingcloud.conn.auth import QSSignatureAuthHandler
from qingcloud.conn.connection import HttpConnection, HTTPRequest
from .bucket import Bucket
from .exception import get_response_error
from .util import load_data
class Zone(object):
DEFAULT = ""
PEK3A = "pek3a"
class VirtualHostStyleFormat(object):
def build_host(self, server, bucket=""):
if bucket:
return "%s.%s" % (bucket, server)
else:
return server
def build_auth_path(self, bucket="", key=""):
if bucket:
path = "/" + bucket
else:
path = ""
return path + "/%s" % quote(key)
def build_path_base(self, bucket="", key=""):
path = "/"
if key:
path += quote(key)
return path
class QSConnection(HttpConnection):
""" Public connection to qingstor
"""
def __init__(self, qy_access_key_id=None, qy_secret_access_key=None,
host="qingstor.com", port=443, protocol="https",
style_format_class=VirtualHostStyleFormat,
retry_time=3, timeout=900, debug=False):
"""
@param qy_access_key_id - the access key id
@param qy_secret_access_key - the secret access key
@param host - the host to make the connection to
@param port - the port to use when connect to host
@param protocol - the protocol to access to server, "http" or "https"
@param retry_time - the retry_time when message send fail
@param timeout - blocking operations will timeout after that many seconds
@param debug - debug mode
"""
# Set default host
host = host
# Set user agent
self.user_agent = "QingStor SDK Python"
# Set retry times
self.retry_time = retry_time
self.style_format = style_format_class()
super(QSConnection, self).__init__(
qy_access_key_id, qy_secret_access_key, host, port, protocol,
None, None, timeout, debug)
if qy_access_key_id and qy_secret_access_key:
self._auth_handler = QSSignatureAuthHandler(host, qy_access_key_id,
qy_secret_access_key)
else:
self._auth_handler = None
def get_all_buckets(self, zone=""):
if zone:
headers = {"Location": zone}
else:
headers = {}
response = self.make_request("GET", headers=headers)
if response.status == 200:
return load_data(response.read())
else:
err = get_response_error(response)
raise err
def create_bucket(self, bucket, zone=Zone.DEFAULT):
""" Create a new bucket.
Keyword arguments:
bucket - The name of the bucket
zone - The zone at which bucket and its objects will locate.
(Default: follow the service-side rule)
"""
headers = {"Location": zone}
response = self.make_request("PUT", bucket, headers=headers)
if response.status in [200, 201]:
return Bucket(self, bucket)
else:
raise get_response_error(response)
def get_bucket(self, bucket, validate=True):
""" Retrieve a bucket by name.
Keyword arguments:
bucket - The name of the bucket
validate - If ``True``, the function will try to verify the bucket exists
on the service-side. (Default: ``True``)
"""
if not validate:
return Bucket(self, bucket)
response = self.make_request("HEAD", bucket)
if response.status == 200:
return Bucket(self, bucket)
elif response.status == 401:
err = get_response_error(response)
err.code = "invalid_access_key_id"
err.message = "Request not authenticated, Access Key ID is either " \
"missing or invalid."
raise err
elif response.status == 403:
err = get_response_error(response)
err.code = "permission_denied"
err.message = "You don't have enough permission to accomplish " \
"this request."
raise err
elif response.status == 404:
err = get_response_error(response)
err.code = "bucket_not_exists"
err.message = "The bucket you are accessing doesn't exist."
raise err
else:
err = get_response_error(response)
raise err
def _get_content_length(self, body):
thelen = 0
try:
thelen = str(len(body))
except TypeError:
# If this is a file-like object, try to fstat its file descriptor
try:
thelen = str(os.fstat(body.fileno()).st_size)
except (AttributeError, OSError):
# Don't send a length if this failed
pass
return thelen
def _get_body_checksum(self, data):
if hasattr(data, "read"):
# Calculate the MD5 by reading the whole file content
# This is evil, need to refactor later
md5 = hashlib.md5()
blocksize = 1024 * 4
datablock = data.read(blocksize)
while datablock:
if sys.version > "3" and isinstance(datablock, str):
datablock = datablock.encode()
md5.update(datablock)
datablock = data.read(blocksize)
token = md5.hexdigest()
data.seek(0)
else:
if sys.version > "3" and isinstance(data, str):
data = data.encode()
token = hashlib.md5(data).hexdigest()
return token
def _build_params(self, params):
params_str = ""
params = params or {}
for key, value in params.items():
if params_str:
params_str += "&"
params_str += "%s" % quote_plus(key)
if value is not None:
params_str += "=%s" % quote_plus(value)
return params_str
def _urlparse(self, url):
parts = urlparse(url)
return parts.hostname, parts.path or "/", parts.query
def build_http_request(self, method, path, params, auth_path,
headers, host, data):
if isinstance(params, str):
path = "%s?%s" % (path, params)
else:
suffix = self._build_params(params)
path = "%s?%s" % (path, suffix) if suffix else path
req = HTTPRequest(method, self.protocol, headers, host, self.port,
path, params, auth_path, data)
return req
def make_request(self, method, bucket="", key="", headers=None,
data="", params=None, num_retries=3):
""" Make request
"""
host = self.style_format.build_host(self.host, bucket)
path = self.style_format.build_path_base(bucket, key)
auth_path = self.style_format.build_auth_path(bucket, key)
# Build request headers
if not headers:
headers = {}
if "Host" not in headers:
headers["Host"] = host
if "Date" not in headers:
headers["Date"] = datetime.utcnow().strftime("%a, %d %b %Y %X GMT")
if "Content-Length" not in headers:
headers["Content-Length"] = self._get_content_length(data)
if data and "Content-MD5" not in headers:
headers["Content-MD5"] = self._get_body_checksum(data)
if "User-Agent" not in headers:
headers["User-Agent"] = self.user_agent
retry_time = 0
while retry_time < self.retry_time:
next_sleep = random.random() * (2 ** retry_time)
try:
response = self.send(method, path, params, headers, host,
auth_path, data)
if response.status == 307:
location = response.getheader("location")
host, path, params = self._urlparse(location)
headers["Host"] = host
# Seek to the start if this is a file-like object
if hasattr(data, "read") and hasattr(data, "seek"):
data.seek(0)
elif response.status in (500, 502, 503):
time.sleep(next_sleep)
else:
if response.length == 0:
response.close()
return response
except Exception:
if retry_time >= self.retry_time - 1:
raise
retry_time += 1 | python | 19 | 0.546444 | 81 | 34.872263 | 274 | starcoderdata |
package dev.alexengrig.designpatterns.structural.decorator;
public class ConsoleNotifier implements Notifier {
@Override
public void notify(String message) {
System.out.println(message);
}
} | java | 8 | 0.740566 | 59 | 25.5 | 8 | starcoderdata |
//---------------------------------------------------------------------------
#include
#include
//---------------------------------------------------------------------------
namespace asd
{
StandartUIPalette::StandartUIPalette(ui_space * space) : UIPalette(space)
{
handle button(_space, int_rect {0, 0, 120, 80});
handle label(_space, int_rect {0, 0, 120, 80});
Text::setDynamic(label, "", Font::obtain("Arial", "arial.ttf"));
_classes["button"].init("button", button);
_classes["label"].init("label", label);
}
widget * StandartUIPalette::create(const string & classid, widget * parent)
{
auto & cl = _classes[classid];
if(cl == nullptr)
return nullptr;
auto obj = cl->prototype->clone(parent);
obj->properties->set(cl);
return obj;
}
void StandartUIPalette::add(const string & classid, const handle & prototype)
{
auto & cl = _classes[classid];
if(cl != nullptr)
throw Exception("Standart UI palette: Widget prototype for class \"", classid, "\" already exists");
cl.init(classid, prototype);
}
}
//--------------------------------------------------------------------------- | c++ | 11 | 0.531699 | 103 | 26.511628 | 43 | starcoderdata |
def find_similar_learner(self, pipeline, include_siblings=False, num_pipelines=5):
"""Fine similar pipelines by replacing the learner component"""
if self.task_type == TaskType.CLASSIFICATION:
learning_type = TaskType.CLASSIFICATION.value # 'classification'
hierarchy = self.primitives.hierarchies[Category.CLASSIFICATION]
elif self.task_type == TaskType.REGRESSION:
learning_type = TaskType.REGRESSION.value # 'regression'
hierarchy = self.primitives.hierarchies[Category.REGRESSION]
else:
raise Exception('Learning type not recoginized: {}'.format(self.task_type))
learner = pipeline.get_primitive(learning_type)
learner_node = hierarchy.get_node_by_primitive(learner)
if include_siblings:
nodes = [learner_node] + learner_node.get_siblings()
else:
nodes = [learner_node]
similar_primitives = [primitive for node in nodes for primitive in node.get_content()]
pipeline_primitives = [primitive for primitive in pipeline.get_primitives() if not primitive==learner]
similar_weights = [self.get_primitive_weight(primitive, hierarchy)
for primitive in similar_primitives]
pipeline_weights = [self.get_primitive_weight(primitive, hierarchy)
for primitive in pipeline_primitives]
values = self.policy.get_affinities(pipeline_primitives, similar_primitives,
pipeline_weights, similar_weights)
similar_primitives = random_choices_without_replacement(similar_primitives, values, num_pipelines)
similiar_pipelines = []
for component in similar_primitives:
similiar_pipelines.append(pipeline.new_pipeline_replace(learning_type, component))
return similiar_pipelines | python | 12 | 0.663665 | 110 | 61.966667 | 30 | inline |
<?php
class CookieManager {
/**
*
* @param string $name
* @param string $value
* @param int $expire
* @param string $path
*/
public function setCookie($name, $value = null, $expire = null, $path = null) {
if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
// Specify httponly variable if using php >= 5.2.0
setcookie($name, $value, $expire, $path, '', false, true);
} else {
setcookie($name, $value, $expire, $path);
}
}
/**
*
* @param string $name
* @param string $path
*/
public function destroyCookie($name, $path) {
setcookie($name, null, time() - 3600, $path);
}
/**
*
* @param string $name
* @param mixed $defaultValue
* @return string
*/
public function readCookie($name, $defaultValue = null) {
return (isset($_COOKIE[$name])) ? $_COOKIE[$name] : $defaultValue;
}
public function isCookieSet($name) {
return isset($_COOKIE[$name]);
}
} | php | 13 | 0.512582 | 83 | 22.844444 | 45 | starcoderdata |
using System;
using Translation.Client.Web.Models.Base;
namespace Translation.Client.Web.Models.LabelTranslation
{
public class TranslationUploadFromCSVDoneModel : BaseModel
{
public Guid LabelUid { get; set; }
public string LabelKey { get; set; }
public int AddedTranslationCount { get; set; }
public int UpdatedTranslationCount { get; set; }
public int CanNotAddedTranslationCount { get; set; }
public int TotalRowsProcessed { get; set; }
public TranslationUploadFromCSVDoneModel()
{
Title = "translation_upload_done_title";
}
}
} | c# | 10 | 0.671687 | 62 | 27.913043 | 23 | starcoderdata |
$( document ).ready(function() {
// Le canevas sera différent selon la définition d'écran
var width, height, titleFontSize, subtitleFontSize, labelFontSize, pieInnerRadius, pieOuterRadius;
if ($( window ).width() >= 1400) {
width = 782;
height = 620;
titleFontSize = 35;
subtitleFontSize = 15;
labelFontSize = 15;
pieInnerRadius = "73%";
pieOuterRadius = "80%";
} else {
width = 570;
height = 451;
titleFontSize = 30;
subtitleFontSize = 13;
labelFontSize = 12;
pieInnerRadius = "83%";
pieOuterRadius = "77%";
}
// Construction de l'anneau
var pie = new d3pie("screen", {
"header": {
"title": {
"text": "Catégories",
"fontSize": titleFontSize,
"font": "courier"
},
"subtitle": {
"text": "Quelles sont les plus fournies ? *",
"color": "#999999",
"fontSize": subtitleFontSize,
"font": "courier"
},
"location": "pie-center",
"titleSubtitlePadding": 10
},
"footer": {
"text": "* Déterminé à partir du nombre de sous-catégories",
"color": "#999999",
"fontSize": 15,
"font": "courier",
"location": "bottom-center"
},
"size": {
"canvasHeight": height,
"canvasWidth": width,
"pieInnerRadius": pieInnerRadius,
"pieOuterRadius": pieOuterRadius
},
"data": {
"sortOrder": "label-asc",
"content": [
{
"label": "Bureautique",
"value": 9,
"color": "#2383c1"
},
{
"label": "Graphisme",
"value": 7,
"color": "#64a61f"
},
{
"label": "Internet",
"value": 10,
"color": "#7b6788"
},
{
"label": "Loisirs",
"value": 2,
"color": "#a05c56"
},
{
"label": "Multimédia",
"value": 7,
"color": "#961919"
},
{
"label": "Progiciels",
"value": 3,
"color": "#d8d239"
},
{
"label": "Publication",
"value": 5,
"color": "#e98125"
},
{
"label": "Serveurs",
"value": 5,
"color": "#d0743c"
},
{
"label": "SIG",
"value": 1,
"color": "#6ada6a"
},
{
"label": "Traduction",
"value": 1,
"color": "#0b6197"
},
{
"label": "Mathématiques",
"value": 2,
"color": "#7c9058"
},
{
"label": "Utilitaires",
"value": 11,
"color": "#207f32"
}
]
},
"labels": {
"outer": {
"format": "label-percentage1",
"pieDistance": 20
},
"inner": {
"format": "none"
},
"mainLabel": {
"fontSize": labelFontSize
},
"percentage": {
"color": "#999999",
"fontSize": 13,
"decimalPlaces": 0
},
"value": {
"color": "#cccc43",
"fontSize": 13
},
"lines": {
"enabled": true,
"color": "#777777"
},
"truncation": {
"enabled": true
}
},
"tooltips": {
"enabled": true,
"type": "placeholder",
"string": "{label}: {value}, {percentage}%"
},
"effects": {
"pullOutSegmentOnClick": {
"speed": 400,
"size": 10
}
},
"misc": {
"colors": {
"segmentStroke": "#000000"
}
}
});
}); | javascript | 16 | 0.330582 | 102 | 27.463855 | 166 | starcoderdata |
public void SetAdjacentBarChart()
{
if (ChartType != SeriesChartType.BarAdjacent) { Element.Series.Clear(); }
ChartType = SeriesChartType.BarAdjacent;
List<double> PT = new List<double>();
List<int> IV = new List<int>();
List<int> JV = new List<int>();
//Populate Data Set
for (int i = 0; i < DataGrid.Sets.Count; i++)
{
for (int j = 0; j < DataGrid.Sets[i].Points.Count; j++)
{
PT.Add(DataGrid.Sets[i].Points[j].Number);
IV.Add(i);
JV.Add(j);
}
}
int C = Element.Series.Count;
int S = PT.Count;
for (int i = C; i < S; i++)
{
RowSeries CS = new RowSeries();
CS.LabelsPosition = BarLabelPosition.Parallel;
Element.Series.Add(CS);
Element.Series[i].Values = new ChartValues<double>();
Element.Series[i].Values.Add(0.0);
}
C = Element.Series.Count;
if (C > S)
{
for (int i = S; i < C; i++)
{
Element.Series.RemoveAt(Element.Series.Count - 1);
}
}
C = Element.Series.Count;
for (int i = 0; i < S; i++)
{
Element.Series[i].Values[0] = PT[i];
SetAdjacentBarProperties((RowSeries)Element.Series[i], (int)DataGrid.Sets[IV[i]].Points[JV[i]].Label.Alignment);
SetSequenceProperties(IV[i], JV[i], (RowSeries)Element.Series[i]);
}
} | c# | 21 | 0.441915 | 128 | 31.961538 | 52 | inline |
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right
sys.setrecursionlimit(10**7)
def input():
return sys.stdin.readline()[:-1]
mod = 10**9 + 7
def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
if row <= 0:
return [[] for _ in range(col)]
elif col == 1:
return [I() for _ in range(row)]
else:
read_all = [list(map(str, input().split())) for _ in range(row)]
return map(list, zip(*read_all))
#################
N = I()
X,Y,U = LIR(N,3)
X = [int(x) for x in X]
Y = [int(y) for y in Y]
d1 = defaultdict(lambda:defaultdict(list))
d2 = defaultdict(lambda:defaultdict(list))
u = defaultdict(list)
r = defaultdict(list)
d = defaultdict(list)
l = defaultdict(list)
for i in range(N):
if U[i] == 'U':
u[X[i]].append(Y[i])
elif U[i] == 'D':
d[X[i]].append(Y[i])
elif U[i] == 'R':
r[Y[i]].append(X[i])
else:
l[Y[i]].append(X[i])
for k in u.keys():
u[k].sort()
for k in d.keys():
d[k].sort()
for k in r.keys():
r[k].sort()
for k in l.keys():
l[k].sort()
for i in range(N):
d1[U[i]][Y[i]-X[i]].append(X[i])
d2[U[i]][Y[i]+X[i]].append(X[i])
ans = float('inf')
for i in range(N):
if U[i] == 'U':
p = bisect_left(d[X[i]],Y[i])
if p <= len(d[X[i]])-1 and len(d[X[i]]):
ans = min(ans,(d[X[i]][p]-Y[i])*5)
p = bisect_left(d1['L'][Y[i]-X[i]],X[i])
if p <= len(d1['L'][Y[i]-X[i]])-1 and len(d1['L'][Y[i]-X[i]]):
ans = min(ans,(d1['L'][Y[i]-X[i]][p]-X[i])*10)
p = bisect_left(d2['R'][Y[i]+X[i]],X[i])
if 0 <= p-1 <= len(d2['R'][Y[i]+X[i]])-1 and len(d2['R'][Y[i]+X[i]]):
ans = min(ans,(X[i]-d2['R'][Y[i]+X[i]][p-1])*10)
elif U[i] == 'D':
p = bisect_left(u[X[i]],Y[i])
if 0 <= p-1 <= len(u[X[i]])-1 and len(u[X[i]]):
ans = min(ans,(Y[i]-u[X[i]][p-1])*5)
p = bisect_left(d1['R'][Y[i]-X[i]],X[i])
if 0 <= p-1 <= len(d1['R'][Y[i]-X[i]])-1 and len(d1['R'][Y[i]-X[i]]):
ans = min(ans,(X[i]-d1['R'][Y[i]-X[i]][p-1])*10)
p = bisect_left(d2['L'][Y[i]+X[i]],X[i])
if p <= len(d2['L'][Y[i]+X[i]])-1 and len(d2['L'][Y[i]+X[i]]):
ans = min(ans,(d2['L'][Y[i]+X[i]][p]-X[i])*10)
elif U[i] == 'R':
p = bisect_left(l[Y[i]],X[i])
if p <= len(l[Y[i]])-1 and len(l[Y[i]]):
ans = min(ans,(l[Y[i]][p]-X[i])*5)
p = bisect_left(d1['D'][Y[i]-X[i]],X[i])
if p <= len(d1['D'][Y[i]-X[i]])-1 and len(d1['D'][Y[i]-X[i]]):
ans = min(ans,(d1['D'][Y[i]-X[i]][p]-X[i])*10)
p = bisect_left(d2['U'][Y[i]+X[i]],X[i])
if p <= len(d2['U'][Y[i]+X[i]])-1 and len(d2['U'][Y[i]+X[i]]):
ans = min(ans,(d2['U'][Y[i]+X[i]][p]-X[i])*10)
else:
p = bisect_left(r[Y[i]],X[i])
if 0 <= p-1 <= len(r[Y[i]])-1 and len(r[Y[i]]):
ans = min(ans,(X[i]-r[Y[i]][p-1])*5)
p = bisect_left(d1['U'][Y[i]-X[i]],X[i])
if 0 <= p-1 <= len(d1['U'][Y[i]-X[i]])-1 and len(d1['U'][Y[i]-X[i]]):
ans = min(ans,(X[i]-d1['U'][Y[i]-X[i]][p-1])*10)
p = bisect_left(d2['D'][Y[i]+X[i]],X[i])
if 0 <= p-1 <= len(d2['D'][Y[i]+X[i]])-1 and len(d2['D'][Y[i]+X[i]]):
ans = min(ans,(X[i]-d2['D'][Y[i]+X[i]][p-1])*10)
if ans == float('inf'):
print('SAFE')
else:
print(ans) | python | 19 | 0.440264 | 77 | 27.54918 | 122 | codenet |
using System.Collections.Generic;
namespace StructuredFieldValues.Tests;
internal sealed class ReverseEqualityComparer : IEqualityComparer
{
public static IEqualityComparer Instance { get; } = new ReverseEqualityComparer
public bool Equals(T? x, T? y)
=> y is object ? y.Equals(x!) : x is null;
public int GetHashCode(T obj) => obj?.GetHashCode() ?? -1;
} | c# | 11 | 0.704082 | 92 | 29.153846 | 13 | starcoderdata |
import {JetView} from "webix-jet";
import {records} from "../models/records";
export default class EmployeesListView extends JetView {
config() {
return {
view: "list",
width: 310,
// data: records,
template: "#index#. #fullname#",
select: true,
drag: "source",
scroll: "auto",
// css: "unselectable"
};
}
init(_$view, _$) {
super.init(_$view, _$);
_$view.parse(records);
_$view.$view.oncontextmenu = () => false;
}
ready(_$view, _$url) {
super.ready(_$view, _$url);
/***
* Add dynamic indexes
* */
_$view.data.each(function (obj, i) {
obj.index = i + 1;
});
_$view.refresh();
}
} | javascript | 14 | 0.55 | 56 | 15.948718 | 39 | starcoderdata |
// cerner_2^5_2016
// prints A-Z!
var alphabets = '';
var handler = {
get: function(target, name){
alphabets = alphabets + name;
if (name === 'Z') {
console.log(alphabets)
return;
}
eval('Driver.' + String.fromCharCode(name.charCodeAt(0) + 1));
}
}
var Driver = new Proxy({}, handler);
Driver.A | javascript | 16 | 0.534819 | 70 | 22.933333 | 15 | starcoderdata |
<?php
declare(strict_types=1);
namespace spec\drupol\BelgianNationalNumberFaker\Validator;
use drupol\BelgianNationalNumberFaker\Validator\BelgianNationalNumberValidator;
use PhpSpec\ObjectBehavior;
class BelgianNationalNumberValidatorSpec extends ObjectBehavior
{
public function it_can_check_if_a_number_is_valid_or_not(): void
{
$data = [
'81041889503' => true,
'75111515014' => true,
'03103129473' => true,
'1' => false,
'111111111111' => false,
'00000000000' => false,
'01010101010' => false,
'81-04-18-895.03' => true,
'-----------' => false,
'8.5' => false,
'0' => false,
'' => false,
null => false,
'10291188903' => false,
'12345678901' => false,
' 8 1 0 4 1 8 8 9 5 0 3 ' => true,
'81041800003' => false,
'81041899903' => false,
'81041899603' => false,
];
foreach ($data as $id => $expected) {
$this
->isValid($id)
->shouldReturn($expected);
}
}
public function it_is_initializable(): void
{
$this->shouldHaveType(BelgianNationalNumberValidator::class);
}
} | php | 13 | 0.525811 | 79 | 27.25 | 48 | starcoderdata |
void processEvent_6(L1List<NinjaInfo_t>& nList,char* eventcode, void* pGData){
char *ID = getID(eventcode);
L1Item<NinjaInfo_t>* pStop;// luon la diem dung yen
L1Item<NinjaInfo_t>* pMove;// luon la diem di chuyen
gData* p = (gData*) pGData;
L1List<NinjaID_t>* ninjaid = p->headID;
L1Item<NinjaID_t>* pID = ninjaid->getHead();
while(pID){
if(strcmp(pID->data.ID,ID) == 0)break;
pID = pID->pNext;
}
L1Item<NinjaInfo_t>* ptmp = (L1Item<NinjaInfo_t>*) pID->data.pointer;
L1List<NinjaInfo_t> ListID = createListID(nList,pID->data.ID,ptmp);
pMove = ListID.getHead();
L1List<NinjaInfo_t> freezeStt;// List luu cac lan dung lai
bool b = true;
while(b){
if(findNextStop(pMove,pStop)){
freezeStt.push_back(pStop->data);
if(!findNextMove(pStop,pMove)){
b = false;
}
}
else b = false;
}
if(freezeStt.getHead() == NULL) cout <<"6" << ID << ": Non-stop" << endl;
else{
char* time = new char();
cout <<"6" << ID << ": ";
strPrintTime(time,freezeStt.getLast()->data.timestamp);
cout << time <<endl;
}
} | c++ | 13 | 0.627689 | 78 | 27.75 | 36 | inline |
function approve(id)
{
$.post("/Manage/Approve/" + id).success(function () {
$("#" + id).show();
});
}
function approvensfw(id) {
$.post("/Manage/ApproveNSFW/" + id).success(function () {
$("#" + id).show();
});
}
function approvesketchy(id) {
$.post("/Manage/ApproveSketchy/" + id).success(function () {
$("#" + id).show();
});
}
function deny(id) {
$.post("/Manage/Deny/" + id).success(function () {
$("#" + id).show();
});
} | javascript | 15 | 0.492929 | 64 | 19.666667 | 24 | starcoderdata |
h,w=map(int,input().split())
l=[[i for i in input()] for j in range(h)]
INF=float('inf')
dp=[[INF for j in range(w)] for i in range(h)]
dp[0][0]=0
if l[0][0]=="#":
dp[0][0]+=1
if l[-1][-1]=="#":
dp[0][0]+=1
for i in range(1,w):
if l[0][i-1]==l[0][i]:
dp[0][i]=dp[0][i-1]
else:
dp[0][i]=dp[0][i-1]+1
for i in range(1,h):
for j in range(w):
if l[i-1][j]==l[i][j]:
dp[i][j]=dp[i-1][j]
else:
dp[i][j]=dp[i-1][j]+1
if j==0:
continue
if l[i][j-1]==l[i][j]:
dp[i][j]=min(dp[i][j],dp[i][j-1])
else:
dp[i][j]=min(dp[i][j],dp[i][j-1]+1)
print(dp[-1][-1]//2) | python | 15 | 0.407028 | 47 | 24.333333 | 27 | codenet |
import faker from 'faker';
import { User } from '../../src/models';
export default factory =>
factory.define('user', User, {
name: faker.name.findName(),
email: faker.internet.email(),
password: '',
familyIds: [],
}); | javascript | 10 | 0.606695 | 40 | 22.9 | 10 | starcoderdata |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace ycode.Eater
{
public class Eater : MonoBehaviour
{
public bool logging = false;
public int StomachFull = 20;
public int CachingDurationInFrameCounts = 100;
public AbstractITextDisplay StomachDisplay;
public EaterState State { get; private set; }
private bool _active;
public bool IsFull => State.IsFull;
public bool HasEnergy => State.HasEnergy;
private readonly List _targetingFoods = new List
private int _targetingFoodCacheUntil = 0;
private Food _targetingFood;
public Food TargetingFood
{
get
{
if (Time.frameCount > _targetingFoodCacheUntil)
{
_targetingFood = _targetingFoods.OrderBy(x => (x.transform.position - transform.position).magnitude).FirstOrDefault();
_targetingFoodCacheUntil = Time.frameCount + CachingDurationInFrameCounts;
}
return _targetingFood;
}
}
private readonly List _eatingFoods = new List
private int _eatingFoodCacheUntil = 0;
private Food _eatingFood;
public Food eatingFood
{
get
{
if (Time.frameCount > _eatingFoodCacheUntil)
{
_eatingFood = _eatingFoods.OrderBy(x => (x.transform.position - transform.position).magnitude).FirstOrDefault();
_eatingFoodCacheUntil = Time.frameCount + CachingDurationInFrameCounts;
}
return _eatingFood;
}
}
void Start()
{
State = new EaterState(StomachFull);
_active = true;
StartCoroutine(Eat());
}
private void OnDestroy()
{
_active = false;
_targetingFoods.Clear();
_eatingFoods.Clear();
}
void Update()
{
if (StomachDisplay != null)
StomachDisplay.Text = State.Stomach.ToString();
}
public void TargetFood(Food food)
{
if (food == null)
return;
if (!_targetingFoods.Contains(food))
_targetingFoods.Add(food);
if (logging) Debug.Log($"[{gameObject.name}] Next destination is food");
food.OnFoodEmpty += Food_OnFoodEmpty;
}
public void ForgetFood(Food food)
{
if (_targetingFoods.Contains(food))
_targetingFoods.Remove(food);
}
public void Starteating(Food food)
{
if (food == null)
return;
_eatingFoods.Add(food);
}
public void ReleaseFood(Food food)
{
if (_eatingFoods.Contains(food))
_eatingFoods.Remove(food);
}
private void Food_OnFoodEmpty(Food food)
{
food.OnFoodEmpty -= Food_OnFoodEmpty;
ReleaseFood(food);
ForgetFood(food);
}
private IEnumerator Eat()
{
yield return new WaitForFixedUpdate(); // wait for all the game objects to finish `Start()` method call
while (_active)
{
Food food;
if (!IsFull && (food = eatingFood) != null && food.State.TryConsuming(out var calorie))
{
State.Eat(calorie);
if (logging) Debug.Log($"[{gameObject.name}] An Agent ate {calorie} calories of a food.");
}
yield return new WaitForSeconds(1f * Random.value);
}
yield return null;
}
}
} | c# | 24 | 0.529636 | 138 | 27.904412 | 136 | starcoderdata |
private void addEntry() {
Transport transport = null;
AccountItem item;
if (publicBox.isSelected()) {
item = (AccountItem)accounts.getSelectedItem();
transport = item.getTransport();
}
if (transport == null) {
String jid = getJID();
if ( !jid.contains( "@" ) ) {
jid = jid + "@" + SparkManager.getConnection().getServiceName();
}
String nickname = nicknameField.getText();
String group = (String)groupBox.getSelectedItem();
jid = UserManager.escapeJID(jid);
// Add as a new entry
addRosterEntry(jid, nickname, group);
}
else {
String jid = getJID();
try {
jid = Gateway.getJID(transport.getServiceName(), jid);
}
catch (SmackException e) {
Log.error(e);
}
String nickname = nicknameField.getText();
String group = (String)groupBox.getSelectedItem();
addRosterEntry(jid, nickname, group);
}
} | java | 13 | 0.505329 | 80 | 32.147059 | 34 | inline |
import RadioCustom from './src/radio-custom';
/* istanbul ignore next */
RadioCustom.install = function(Vue) {
Vue.component(RadioCustom.name, RadioCustom);
};
export default RadioCustom; | javascript | 6 | 0.763948 | 47 | 24.888889 | 9 | starcoderdata |
# -*- coding: utf-8 -*-
# @Time : 2020/11/21 下午2:23
# @Author : 司云中
# @File : urls.py
# @Software: Pycharm
from django.urls import path, include
from oauth_app.apis.qq_api import QQOauthUrl, QQOauthAccessToken, BindQQAPIView
app_name = 'oauth_app'
qq_urlpatterns = [
path('entrance/', QQOauthUrl.as_view(), name='qq-login-url-api'),
path('token/', QQOauthAccessToken.as_view(), name='qq-login-access-token-api'),
path('qq-login-bind-api/', BindQQAPIView.as_view(), name='qq-login-bind-api')
]
urlpatterns = [
path('qq/', include(qq_urlpatterns)),
] | python | 8 | 0.68 | 83 | 27.571429 | 21 | starcoderdata |
"""
Copyright 2017 ARM Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
This is a sample implementation of a cloud module that can be used with Icetea.
It does nothing but provides an example of a module that could be used to store testcase results,
campaigns, suites etc.
@Author:
"""
# pylint: disable=unused-argument,too-many-arguments
def create(host, port, result_converter=None, testcase_converter=None, args=None):
"""
Function which is called by Icetea to create an instance of the cloud client. This function
must exists.
This function myust not return None. Either return an instance of Client or raise.
"""
return SampleClient(host, port, result_converter, testcase_converter, args)
class SampleClient(object):
"""
Example of a cloud client class.
"""
def __init__(self, host='localhost', port=3000, result_converter=None,
testcase_converter=None, args=None):
# Optional converter for result data from format provided by test framework to
# format supported by server
self.result_converter = result_converter
# Optional converter for testcase metadata from format provided by test framework to
# one supported by server
self.tc_converter = testcase_converter
self.host = host
self.port = port
def set_logger(self, logger):
'''
Set Logger
:param logger: Logger -oject
'''
pass
def get_suite(self, suite, options):
'''
Get suite from server.
returns suite information as a dictionary object.
'''
pass
def get_campaign_id(self, campaign_name):
"""
Get ID of campaign that has name campaign_name
"""
pass
def get_campaigns(self):
"""
Get campaigns from server
"""
pass
def get_campaign_names(self):
"""
Get names of campaigns from server
returns list of campaign/suite names.
"""
pass
def update_testcase(self, metadata):
"""
Update TC data to server or create a new testcase on server.
If testcase_converter has been provided,
use it to convert TC metadata to format accepted by the server.
"""
pass
def send_results(self, result):
"""
Upload a result object to server.
If resultConverter has been provided, use it to convert result object to format accepted
by the server.
If needed, use testcase_converter to convert tc metadata in result to suitable format.
returns new result entry as a dictionary or None.
"""
if self.result_converter:
print(self.result_converter(result))
else:
print(result) | python | 12 | 0.658852 | 97 | 30.386792 | 106 | starcoderdata |
def preprocess_player_df(player_df):
"""preprocess player df. Replace kast and drop rating"""
# replace the kast value in player df with a number
player_df["Kast"] = player_df.Kast.str.replace(r'\%', '')
player_df.replace(to_replace="-", value=0, inplace=True)
player_df["Kast"] = player_df["Kast"].astype(float)
player_df["Kast"] = 0.01 * player_df["Kast"]
# drop rating column of a player
player_df.drop(columns=["Rating"], inplace=True)
return player_df | python | 9 | 0.65587 | 61 | 40.25 | 12 | inline |
'use strict'
const userComment = {};
function userCommentModel(sequelize, Sequelize, comment, user){
var UserComment = sequelize.define('_user_comment', {
user_id: {
type: Sequelize.INTEGER,
allowNull: false,
primaryKey: true
},
comment_id: {
type: Sequelize.INTEGER,
allowNull: false,
primaryKey: true
},
},{
timestamps: false,
freezeTableName: true
});
UserComment.belongsTo(comment, {
foreignKey: 'comment_id',
onDelete: 'cascade',
onUpdate: 'cascade'
});
UserComment.belongsTo(user, {
foreignKey: 'user_id',
onDelete: 'cascade',
onUpdate: 'cascade'
});
return UserComment;
};
userComment.UserCommentModel = userCommentModel;
module.exports = userComment; | javascript | 15 | 0.651365 | 63 | 18.658537 | 41 | starcoderdata |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "common.h"
#include "clrconfig.h"
#include "compatibilityswitch.h"
FCIMPL1(StringObject*, CompatibilitySwitch::GetValue, StringObject* switchNameUNSAFE) {
CONTRACTL {
FCALL_CHECK;
}
CONTRACTL_END;
if (!switchNameUNSAFE)
FCThrowRes(kArgumentNullException, W("Arg_InvalidSwitchName"));
STRINGREF name = (STRINGREF) switchNameUNSAFE;
VALIDATEOBJECTREF(name);
STRINGREF refName = NULL;
HELPER_METHOD_FRAME_BEGIN_RET_1(name);
CLRConfig::ConfigStringInfo info;
info.name = name->GetBuffer();
info.options = CLRConfig::EEConfig_default;
LPWSTR strVal = CLRConfig::GetConfigValue(info);
refName = StringObject::NewString(strVal);
HELPER_METHOD_FRAME_END();
return (StringObject*)OBJECTREFToObject(refName);
}
FCIMPLEND | c++ | 8 | 0.719447 | 87 | 27.515152 | 33 | starcoderdata |
#include
class Foo {
template<class T>
void foo() {
puts("fo3o");
}
};
int main() {
Foo obj;
obj.template foo
return 0;
} | c++ | 10 | 0.554286 | 26 | 9.9375 | 16 | starcoderdata |
import needsthis
def somefunc():
print "Hello from py2app"
if __name__ == '__main__':
somefunc() | python | 6 | 0.612903 | 29 | 14.5 | 8 | starcoderdata |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import {
util,
selectOptions,
ModalLink,
Form,
Fade
} from 'givebox-lib';
import Moment from 'moment';
class PaymentFormClass extends Component {
constructor(props) {
super(props);
this.renderFields = this.renderFields.bind(this);
this.customOnChange = this.customOnChange.bind(this);
this.processForm = this.processForm.bind(this);
this.formSavedCallback = this.formSavedCallback.bind(this);
this.sendEmailCallback = this.sendEmailCallback.bind(this);
this.state = {
loading: false,
sendEmail: {
recipients: '',
message: util.getValue(this.props.sendEmail, 'defaultMsg', '')
}
}
}
componentDidMount() {
}
componentWillUnmount() {
if (this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
}
}
formSavedCallback() {
if (this.props.callback) {
this.props.callback(arguments[0]);
}
}
processCallback(res, err) {
if (!err) {
this.props.formSaved(() => this.formSavedCallback(res.ID));
} else {
if (!this.props.getErrors(err)) this.props.formProp({error: this.props.savingErrorMsg});
}
return;
}
processForm(fields) {
const data = {};
Object.entries(fields).forEach(([key, value]) => {
if (value.autoReturn) data[key] = value.value;
if (key === 'name') {
const name = util.splitName(value.value);
data.firstname = name.first;
data.lastname = name.last;
}
if (key === 'ccnumber') data.number = value.apiValue;
if (key === 'ccexpire') {
const ccexpire = util.getSplitStr(value.value, '/', 2, -1);
data.expMonth = parseInt(ccexpire[0]);
data.expYear = parseInt(`${Moment().format('YYYY').slice(0, 2)}${ccexpire[1]}`);
}
});
console.log('processForm', data);
/*
this.props.sendResource(
this.props.resource,
{
id: [this.props.id],
method: 'patch',
data: data,
callback: this.processCallback.bind(this),
});
*/
}
customOnChange(name, value) {
console.log('customOnChange', name, value);
//this.props.fieldProp(name, { value });
}
sendEmailCallback(recipients, message) {
this.setState({
sendEmail: {
recipients,
message
}
});
}
renderFields() {
const {
breakpoint,
phone,
address,
work,
custom,
sendEmail
} = this.props;
const name = this.props.textField('name', { placeholder: 'Enter Name', label: 'Name', required: true });
const creditCard = this.props.creditCardGroup({ required: true, placeholder: 'xxxx xxxx xxxx xxxx', debug: false});
const email = this.props.textField('email', {required: true, placeholder: 'Enter Email Address', label: 'Email', validate: 'email', inputMode: 'email' });
const phoneField = this.props.textField('phone', {required: phone.required, placeholder: 'Enter Phone Number', validate: 'phone', inputMode: 'tel' });
const addressField = this.props.textField('address', { required: address.required, label: 'Address', placeholder: 'Enter Street Address' });
const city = this.props.textField('city', { required: address.required, label: 'City', placeholder: 'Enter City' });
const zip = this.props.textField('zip', { required: true, label: 'Zip Code', placeholder: 'Enter Zip', maxLength: 5, inputMode: 'numeric' });
const state = this.props.dropdown('state', {label: 'State', fixedLabel: false, selectLabel: 'Enter State', options: selectOptions.states, required: address.required })
const employer = this.props.textField('employer', { required: work.required, label: 'Employer', placeholder: 'Employer' });
const occupation = this.props.textField('occupation', { required: work.required, label: 'Occupation', placeholder: 'Occupation' });
const customField = this.props.textField('note', { required: custom.required, hideLabel: true, placeholder: custom.placeholder });
const cityStateZipGroup =
<div className='column' style={{ width: '40%' }}>{city}
<div className='column' style={{ width: '40%' }}>{state}
<div className='column' style={{ width: '20%' }}>{zip}
;
const sendEmailLink =
<ModalLink id='sendEmail' opts={{ sendEmailCallback: this.sendEmailCallback, sendEmail: this.state.sendEmail, headerText: sendEmail.headerText }}>{sendEmail.linkText}
;
const fields = [
{ name: 'name', field: name, enabled: true, order: 1 },
{ name: 'creditCard', field: creditCard, enabled: true, order: breakpoint === 'mobile' ? 0 : 2 },
{ name: 'email', field: email, enabled: true, order: 3 },
{ name: 'phone', field: phoneField, enabled: phone.enabled, order: 4 },
{ name: 'address', field: addressField, enabled: address.enabled, order: 5 },
{ name: 'zip', field: address.enabled ? cityStateZipGroup : zip, enabled: true, order: 6 },
{ name: 'employer', field: employer, enabled: work.enabled, order: 7 },
{ name: 'occupation', field: occupation, enabled: work.enabled, order: 8 },
{ name: 'custom', field: customField, enabled: custom.enabled, order: 9, width: '100%' },
{ name: 'sendEmail', field: sendEmailLink, enabled: sendEmail.enabled, order: 10, width: '100%' }
];
util.sortByField(fields, 'order', 'ASC');
const items = [];
Object.entries(fields).forEach(([key, value]) => {
if (value.enabled) {
items.push(
<div
key={key}
className='column'
style={{ width: this.props.breakpoint === 'mobile' ? '100%' : util.getValue(value, 'width', '50%') }}
>
{value.field}
);
}
});
return items;
}
render() {
return (
<div className='gbxPaymentForm'>
{this.renderFields()}
{this.props.saveButton(this.processForm, { style: { margin: 0, padding: 0, height: 0, width: 0, visibility: 'hidden' } })}
)
}
}
class PaymentForm extends Component {
constructor(props){
super(props);
this.handleResize = this.handleResize.bind(this);
this.formStateCallback = this.formStateCallback.bind(this);
this.state = {
windowWidthChange: window.innerWidth,
breakpoint: window.innerWidth > props.breakpointSize ? 'desktop' : 'mobile',
formState: {}
}
this._isMounted = false;
}
componentDidMount() {
this._isMounted = true;
if (this._isMounted) window.addEventListener('resize', this.handleResize.bind(this));
}
componentWillUnmount() {
this._isMounted = false;
window.removeEventListener('resize', this.handleResize.bind(this));
if (this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
}
}
handleResize(e) {
if (this._isMounted) {
this.setState({
windowWidthChange: window.innerWidth
});
const breakpoint = window.innerWidth > this.props.breakpointSize ? 'desktop' : 'mobile';
if (breakpoint !== this.state.breakpoint) {
this.setState({ breakpoint });
}
}
}
formStateCallback(formState) {
this.setState({ formState });
}
render() {
const {
windowWidthChange,
breakpoint,
formState
} = this.state;
return (
<div className='givebox-paymentform'>
<Fade
in={util.getValue(formState, 'error', false)}
duration={100}
>
<div className='error'>{util.getValue(formState, 'errorMsg', 'Please fix field errors in red below')}
<Form
id='gbxForm'
name={'gbxForm'}
errorMsg={false}
successMsg={false}
formPropCallback={this.formStateCallback}
options={{
color: this.props.primaryColor
}}
>
<PaymentFormClass
{...this.props}
breakpoint={breakpoint}
/>
)
}
}
PaymentForm.defaultProps = {
breakpointSize: 800,
phone: {
enabled: false,
required: false
},
address: {
enabled: false,
required: false
},
work: {
enabled: false,
required: false
},
custom: {
enabled: false,
required: false,
placeholder: 'Custom placeholder'
},
sendEmail: {
enabled: true,
linkText: 'Tell your friends link',
headerText: 'Tell your friends header!',
defaultMsg: ''
}
}
function mapStateToProps(state, props) {
return {
}
}
export default connect(mapStateToProps, {
})(PaymentForm) | javascript | 25 | 0.608547 | 184 | 28.948805 | 293 | starcoderdata |
from app import crud, schemas
from fastapi import APIRouter
from fastapi import APIRouter, Depends
from mysql.connector import MySQLConnection
from app.api import deps
router = APIRouter()
@router.post("/")
def create_new_user(
db: MySQLConnection = Depends(deps.get_db), *, data: schemas.UserCreate
) -> schemas.UserReturn:
res = crud.user.create(
db, data=schemas.UserCreate(email=data.email, password=data.password)
)
return res
@router.put("/")
def update_user_data(
data: schemas.UserUpdate,
db: MySQLConnection = Depends(deps.get_db),
current_user: schemas.UserReturn = Depends(deps.get_current_user),
) -> schemas.UserUpdate:
crud.user.update(db, id=current_user.id, data=data)
return schemas.Msg(msg="User was successfully updated") | python | 13 | 0.722785 | 77 | 28.259259 | 27 | starcoderdata |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateArtistsTable extends Migration {
public function up()
{
Schema::create('artists', function(Blueprint $table) {
$table->increments('id');
$table->string('name', 100)->index();
$table->string('sort_name', 100)->index();
$table->date('begin_date');
$table->boolean('is_ended');
$table->date('end_date');
$table->integer('artist_type_id')->unsigned();
$table->enum('gender', array('male', 'female', 'other'));
$table->text('bio');
$table->timestamps();
$table->softDeletes();
$table->string('photo_url', 50);
});
}
public function down()
{
Schema::drop('artists');
}
} | php | 18 | 0.638504 | 60 | 23.1 | 30 | starcoderdata |
#include
#include "boost/bind.hpp"
#include "google/protobuf/descriptor.h"
#include "muduo/net/EventLoop.h"
#include "muduo/net/TcpClient.h"
#include "channel.h"
#include "controller.h"
#include "timer.h"
namespace rrpc {
RpcChannel::RpcChannel(std::string proxy_ip,
int32_t proxy_port,
int32_t rpc_src_id,
int32_t rpc_dst_id,
RpcClient* rpc_client) :
sequence_id_(0),
rpc_src_id_(rpc_src_id),
rpc_dst_id_(rpc_dst_id),
loop_pool_(1),
callback_pool_(1),
rpc_proxy_(proxy_ip, proxy_port),
rpc_client_(rpc_client),
rpc_conn_(new RpcConnection()) {
send_buff_ = malloc(SEND_BUFF_MAX_SIZE);
loop_pool_.AddTask(boost::bind(&RpcChannel::StartLoop, this));
}
RpcChannel::~RpcChannel() {
free(send_buff_);
}
void RpcChannel::CallMethod(const ::google::protobuf::MethodDescriptor* method,
::google::protobuf::RpcController* controller,
const ::google::protobuf::Message* request,
::google::protobuf::Message* response,
::google::protobuf::Closure* done) {
RpcMessage message;
RpcMeta meta;
int32_t sequence_id = GetSequenceId();
meta.set_sequence_id(sequence_id);
meta.set_method(method->full_name());
message.meta.CopyFrom(meta);
std::string buff;
request->SerializeToString(&buff);
message.data = buff.c_str();
message.src_id = rpc_src_id_;
message.dst_id = rpc_dst_id_;
uint32_t size;
void* send_buff = message.Packaging(size);
RpcController *rpc_controller = dynamic_cast
rpc_conn_->conn->send(send_buff, size);
// LOG(INFO) << "rpc_channel send message to proxy, size: "
// << size
// << ", sequence_id: " << sequence_id;
requests_[sequence_id] = method;
// sync request
if (NULL == done) {
while (!dynamic_cast {
{
MutexLock lock(&mutex_);
std::map<int32_t, ::google::protobuf::Message*>::iterator it = \
responses_.find(sequence_id);
if (it != responses_.end()) {
response->CopyFrom(*(it->second));
responses_.erase(sequence_id);
return;
}
}
usleep(10000);
}
controller->SetFailed("timeout");
return;
} else {
closures_[sequence_id] = std::make_pair(rpc_controller, done);
responses_[sequence_id] = response;
}
}
void RpcChannel::StartLoop() {
::muduo::net::EventLoop loop;
::muduo::net::TcpClient tcp_client(&loop, rpc_proxy_, "pb_client");
tcp_client.setConnectionCallback(
boost::bind(&RpcChannel::OnConnection, this, _1));
tcp_client.setMessageCallback(
boost::bind(&RpcChannel::OnMessage, this, _1, _2, _3));
tcp_client.connect();
loop.loop();
}
void RpcChannel::OnConnection(const TcpConnectionPtr &conn) {
MutexLock lock(&mutex_);
if (!conn->connected()) {
// LOG(WARNING) << "connection closed by peer";
// TODO retry
return;
}
// send conn meta
conn->setTcpNoDelay(true);
rpc_conn_->conn = conn;
RpcConnectionMeta meta;
meta.conn_id = rpc_src_id_;
meta.crc = 1;
size_t size = sizeof(meta);
char* data = new char[size];
memset(data, 0, size);
memcpy(data, &meta, size);
conn->send(reinterpret_cast size);
// LOG(INFO) << "RpcClient conn meta sended to proxy";
}
void RpcChannel::OnMessage(const ::muduo::net::TcpConnectionPtr &conn,
::muduo::net::Buffer *buf,
::muduo::Timestamp time) {
MutexLock lock(&mutex_);
::muduo::string data = buf->retrieveAllAsString();
rpc_conn_->buff += data;
parse_pool_.AddTask(boost::bind(&RpcChannel::ParseMessage, this));
}
void RpcChannel::ParseMessage() {
// LOG(INFO) << "parse message";
// deal with meta message
if (!rpc_conn_->checked) {
int ret = rpc_conn_->meta_parser->Parse();
// LOG(INFO) << "meta_parser: " << ret;
switch (ret) {
case -1:
break;
case 1:
rpc_conn_->checked = true;
// LOG(INFO) << "conn meta parsed ok";
// reset data
rpc_conn_->buff.clear();
break;
default:
break;
}
return;
}
// deal with rpc message
// LOG(INFO) << "parse with rpc message";
int ret = rpc_conn_->message_parser->Parse();
if (ret == 1) {
RpcMessagePtr message = rpc_conn_->message_parser->GetMessage();
while (message) {
process_pool_.AddTask(
boost::bind(&RpcChannel::ProcessMessage, this, message));
message = rpc_conn_->message_parser->GetMessage();
}
}
}
void RpcChannel::ProcessMessage(RpcMessagePtr message) {
MutexLock lock(&mutex_);
int32_t sequence_id = message->meta.sequence_id();
std::map<int32_t, const ::google::protobuf::MethodDescriptor*>::iterator it = \
requests_.find(sequence_id);
if (it == requests_.end()) {
return;
}
::google::protobuf::Message* response = NULL;
const ::google::protobuf::MethodDescriptor* method = it->second;
const ::google::protobuf::Message* prototype =
::google::protobuf::MessageFactory::generated_factory()->GetPrototype(
method->output_type());
if (prototype) {
response = prototype->New();
}
std::string data(message->data.c_str(), message->data.size());
response->ParseFromString(data);
// remove from requests_
requests_.erase(sequence_id);
if (closures_.find(sequence_id) == closures_.end()) {
responses_[sequence_id] = response;
} else {
responses_[sequence_id]->CopyFrom(*response);
callback_pool_.AddTask(
boost::bind(&RpcChannel::ProcessCallback, this, sequence_id));
}
}
void RpcChannel::ProcessCallback(
int32_t sequence_id) {
// LOG(INFO) << "ProcessCallback, id: " << sequence_id;
::google::protobuf::Closure* done = closures_[sequence_id].second;
RpcController* controller = closures_[sequence_id].first;
if (controller->IsTimeout()) {
controller->SetFailed("timeout");
}
done->Run();
}
} // namespace rrpc | c++ | 19 | 0.56813 | 83 | 31.269608 | 204 | starcoderdata |
using RotorLib.Access.Primitive;
namespace RotorLib.Access.Map {
public interface IMob : IMapObject {
int Crc { get; }
int MobId { get; }
void Move(Position position);
}
} | c# | 8 | 0.613527 | 40 | 19.7 | 10 | starcoderdata |
private void runJob() {
if (this.curRow > this.maxRows) {
logger.info("All rows processed; shuting down this service for the column '"
+ this.column.getName() + "'");
service.shutdownNow();
}
String val = this.column.getRow(curRow);
logger.debug("Sending Row # " + (curRow) + "/" + this.maxRows + ", data < " + val + " >, for "
+ this.column.getName());
this.setValue(val);
// Reschedule the task to run again for next row
++this.curRow;
service.schedule(task, (long) (this.column.getDelay(curRow) / this.getScaleFactor()),
TimeUnit.MILLISECONDS);
logger.info("Next '" + this.getName() + "' value in "
+ (long) (this.column.getDelay(curRow) / this.getScaleFactor()) + " ms.");
} | java | 14 | 0.600262 | 98 | 41.444444 | 18 | inline |
<?php
include 'lib/header.php';
include 'Database.php';
?>
<?php
$db = new Database();
$sql = 'SELECT * FROM tbl_data';
$read = $db->Select($sql);
?>
.table thead{
text-align: center;
}
.table tbody{
text-align: center;
}
.btnn{
text-align: center;
}
.ask{
margin-top: 20px;
}
<div class="container">
<div class="row">
<div class="col-md-1">
<div class="col-md-10">
<?php
if (isset($_GET['msg'])){
echo "<p style='color: red'>".$_GET['msg']."
}
?>
<div class="table">
<table class="table table-hover">
<?php
if ($read){
$i = 0;
while($row = $read->fetch_assoc()) {
$i++;
?>
echo $i; ?>
echo $row['name']; ?>
echo $row['email']; ?>
echo $row['skill']; ?>
<a href="update.php?id=<?php echo urldecode($row['id']); ?>">Edit ||
<?php
}
}else{
echo 'Data not Available';
}
?>
<div class="btnn">
<a href="create.php" class="btn btn-info ask">Create
<div class="col-md-1">
<?php
include 'lib/footer.php';
?> | php | 11 | 0.335168 | 100 | 24.316456 | 79 | starcoderdata |
#!/usr/bin/env python
#coding:utf-8
import sys
import os
import time
import importlib
from twisted.internet import reactor,defer
from txweb import logger, utils
class TaskDaemon(object):
""" 定时任务管理守护进程
"""
def __init__(self, gdata=None, **kwargs):
self.gdata = gdata
def process_task(self,task):
r = task.process()
if isinstance(r, defer.Deferred):
cbk = lambda _time,_cbk,_task: reactor.callLater(_time, _cbk,_task)
r.addCallback(cbk,self.process_task,task).addErrback(logger.exception)
elif isinstance(r,(int,float)):
reactor.callLater(r, self.process_task,task)
def start_task(self,taskcls):
try:
task = taskcls(self)
first_delay = task.first_delay()
if first_delay:
reactor.callLater(first_delay,self.process_task,task)
else:
self.process_task(task)
logger.info('init task %s done'%repr(task))
except Exception as err:
logger.exception(err)
def load_tasks(self,prifix,task_path):
evs = set(os.path.splitext(it)[0] for it in os.listdir(task_path))
for ev in evs:
try:
robj = importlib.import_module("%s.%s"% (prifix,ev))
if hasattr(robj, 'taskcls'):
self.start_task(robj.taskcls)
except Exception as err:
logger.exception(err)
continue | python | 15 | 0.577313 | 82 | 30.510638 | 47 | starcoderdata |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.