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 network
import (
"github.com/trust-net/go-trust-net/core"
"github.com/trust-net/go-trust-net/consensus"
)
type MockPlatformManager struct {
IsStartCalled bool
StartError error
IsStopCalled bool
StopError error
IsSuspendCalled bool
SuspendError error
StatusCallTxId *core.Byte64
StatusBlock consensus.Block
StatusError error
IsStateCalled bool
StateState *State
IsTrusteeCalled bool
TrusteeApp Trustee
SubmitPayload []byte
SubmitSignature []byte
SubmitSubmitter []byte
SubmitId *core.Byte64
IsPeersCalled bool
PeersPeers []AppConfig
DisconnectApp *AppConfig
DisconnectError error
}
// start the platform block producer
func (mgr *MockPlatformManager) Start() error {
mgr.IsStartCalled = true
return mgr.StartError
}
// stop the platform processing
func (mgr *MockPlatformManager) Stop() error {
mgr.IsStopCalled = true
return mgr.StopError
}
// suspend the platform block producer
func (mgr *MockPlatformManager) Suspend() error {
mgr.IsSuspendCalled = true
return mgr.SuspendError
}
// query status of a submitted transaction, by its transaction ID
// returns the block where it was finalized, or error if not finalized
func (mgr *MockPlatformManager) Status(txId *core.Byte64) (consensus.Block, error) {
mgr.StatusCallTxId = txId
return mgr.StatusBlock, mgr.StatusError
}
// get a snapshot of current world state
func (mgr *MockPlatformManager) State() *State {
mgr.IsStateCalled = true
return mgr.StateState
}
// get mining reward balance
func (mgr *MockPlatformManager) MiningRewardBalance(miner []byte) *RTU {
return BytesToRtu(nil)
}
// get a reference to trustee app
func (mgr *MockPlatformManager) Trustee() Trustee {
mgr.IsTrusteeCalled = true
return mgr.TrusteeApp
}
// submit a transaction payload, and get a transaction ID
func (mgr *MockPlatformManager) Submit(txPayload, signature, submitter []byte) *core.Byte64 {
mgr.SubmitPayload = txPayload
mgr.SubmitSignature = signature
mgr.SubmitSubmitter = submitter
return mgr.SubmitId
}
// get a list of current peers
func (mgr *MockPlatformManager) Peers() []AppConfig {
mgr.IsPeersCalled = true
return mgr.PeersPeers
}
// disconnect a specific peer
func (mgr *MockPlatformManager) Disconnect(app *AppConfig) error {
mgr.DisconnectApp = app
return mgr.DisconnectError
}
type mockBlock struct {
consensus.BlockSpec
uncleMiners [][]byte
hash *core.Byte64
props map[string][]byte
}
func (b *mockBlock) ParentHash() *core.Byte64 {
return &b.PHASH
}
func (b *mockBlock) Miner() []byte {
return b.MINER
}
func (b *mockBlock) Nonce() *core.Byte8 {
return &b.NONCE
}
func (b *mockBlock) Timestamp() *core.Byte8 {
return &b.TS
}
func (b *mockBlock) Delta() *core.Byte8 {
return &b.DELTA
}
func (b *mockBlock) Depth() *core.Byte8 {
return &b.DEPTH
}
func (b *mockBlock) Weight() *core.Byte8 {
return &b.WT
}
func (b *mockBlock) Update(key, value []byte) bool {
b.props[string(key)] = value
return true
}
func (b *mockBlock) Delete(key []byte) bool {
return false
}
func (b *mockBlock) Lookup(key []byte) ([]byte, error) {
return b.props[string(key)], nil
}
func (b *mockBlock) Uncles() []core.Byte64 {
return b.UNCLEs
}
func (b *mockBlock) UncleMiners() [][]byte {
return b.uncleMiners
}
func (b *mockBlock) Transactions() []consensus.Transaction {
return b.TXs
}
func (b *mockBlock) AddTransaction(tx *consensus.Transaction) error {
b.TXs = append(b.TXs, *tx)
return nil
}
func (b *mockBlock) Hash() *core.Byte64 {
return b.hash
}
// create a copy of block sendable on wire
func (b *mockBlock) Spec() consensus.BlockSpec {
spec := consensus.BlockSpec{
PHASH: b.PHASH,
MINER: append([]byte{}, b.MINER...),
TXs: make([]consensus.Transaction,len(b.TXs)),
TS: b.TS,
DELTA: b.DELTA,
DEPTH: b.DEPTH,
WT: b.WT,
UNCLEs: make([]core.Byte64,len(b.UNCLEs)),
NONCE: b.NONCE,
}
spec.STATE = b.STATE
for i, tx := range b.TXs {
spec.TXs[i] = tx
}
for i, uncle := range b.UNCLEs {
spec.UNCLEs[i] = uncle
}
return spec
}
// a deterministic numeric value for the block for ordering of competing blocks
func (b *mockBlock) Numeric() uint64 {
num := uint64(0)
if b.hash == nil {
num -= 1
return num
}
for _, b := range b.hash.Bytes() {
num += uint64(b)
}
return num
}
func newMockBlock(miner string, uncles []string) *mockBlock {
block := &mockBlock{
BlockSpec: consensus.BlockSpec{
MINER: []byte(miner),
},
props: make(map[string][]byte),
}
for _, uncle := range uncles {
block.uncleMiners = append(block.uncleMiners, []byte(uncle))
}
return block
}
|
go
| 16 | 0.718811 | 93 | 20.904306 | 209 |
starcoderdata
|
namespace Core.Framework
{
///
/// Providers simply provide consumers with something, by way of either a read-only property, or a getter method with no input
///
/// <typeparam name="TToProvide">The type to provide
public interface IProvider<out TToProvide>
{
///
/// Returns the type requested
///
/// type requested
TToProvide Get();
}
}
|
c#
| 7 | 0.619342 | 130 | 31.4 | 15 |
starcoderdata
|
import React from "react"
import AnchorLink from "react-anchor-link-smooth-scroll"
const PortfolioImage = ({ url, alt, title, name, onClick }) => (
<AnchorLink
role="button"
href="#slideshow"
offset={27}
onClick={onClick}
className="flex grid-item"
>
<img
src={url}
alt={alt}
className="model-portfolio-image"
title={title}
name={name}
/>
)
export default PortfolioImage
|
javascript
| 7 | 0.640496 | 64 | 19.166667 | 24 |
starcoderdata
|
# coding: utf-8
##-------------------------------------------------------------------------------------------
##
## Separated MRCNN-FCN Pipeline (import model_mrcnn)
## Train FCN head only
##
## Pass predicitions from MRCNN to use as training data for FCN
##-------------------------------------------------------------------------------------------
import os, sys, math, io, time, gc, platform, pprint, argparse
import numpy as np
import tensorflow as tf
import keras
import keras.backend as KB
sys.path.append('./')
import mrcnn.model_mrcnn as mrcnn_modellib
import mrcnn.model_fcn as fcn_modellib
import mrcnn.visualize as visualize
from datetime import datetime
from mrcnn.config import Config
from mrcnn.dataset import Dataset
from mrcnn.utils import log, stack_tensors, stack_tensors_3d, write_stdout
from mrcnn.datagen import data_generator, load_image_gt
from mrcnn.coco import CocoDataset, CocoConfig, CocoInferenceConfig, evaluate_coco, build_coco_results
from mrcnn.prep_notebook import mrcnn_coco_train, prep_coco_dataset
from mrcnn.utils import Paths
pp = pprint.PrettyPrinter(indent=2, width=100)
np.set_printoptions(linewidth=100,precision=4,threshold=1000, suppress = True)
##----------------------------------------------------------------------------------------------
##
##----------------------------------------------------------------------------------------------
def build_heatmap_files(
mrcnn_model,
dataset,
iterations = 5,
start_from = 0,
dest_path = None):
'''
train_dataset: Training Dataset objects.
'''
assert mrcnn_model.mode == "trainfcn", "Create model in training mode."
log("Starting for {} iterations - batch size of each iteration: {}".format(iterations, batch_size))
log(" Output destination: {}".format(dest_path))
tr_generator= data_generator(dataset, mrcnn_model.config,
shuffle=False,
augment=False,
batch_size= mrcnn_model.config.BATCH_SIZE,
image_index = start_from)
## Start main loop
epoch_idx = 0
for epoch_idx in range(iterations) :
tm_start = time.time()
train_batch_x, train_batch_y = next(tr_generator)
print(' ==> mrcnn_model: step {} of {} iterations, image_id: {} '.format(epoch_idx, iterations, train_batch_x[1][:,0]))
# print(' length of train_batch_x:', len(train_batch_x), ' number of things in batch x :', train_batch_x[1].shape)
# for i in train_batch_x:
# print(' ', i.shape)
# print('length of train_batch_y:', len(train_batch_y))
# results = get_layer_output_1(mrcnn_model.keras_model, train_batch_x, [0,1,2,3], 1)
results = mrcnn_model.keras_model.predict(train_batch_x)
# pr_hm_norm, gt_hm_norm, pr_hm_scores, gt_hm_scores = results[:4]
for i in range(batch_size):
# print(' pr_hm_norm shape :', results[0][i].shape)
# print(' pr_hm_scores shape :', results[1][i].shape)
# print(' gt_hm_norm shape :', results[2][i].shape)
# print(' gt_hm_scores shape :', results[3][i].shape)
image_id = train_batch_x[1][i,0]
coco_image_id = dataset.image_info[image_id]['id']
coco_filename = os.path.basename(dataset.image_info[image_id]['path'])
## If we want to save the files with a sequence # 0,1,2,.... which is the index of dataset.image_info[index] use this:
# filename = 'hm_{:012d}.npz'.format(image_id)
## If we want to use the coco_id as the file name, use the following:
filename = 'hm_{:012d}.npz'.format(coco_image_id)
print(' output: {} image_id: {} coco_image_id: {} coco_filename: {} output file: {}'.format(
i, image_id, coco_image_id, coco_filename, filename))
# print(' output file: ',os.path.join(dest_path, filename))
np.savez_compressed(os.path.join(dest_path, filename),
input_image_meta=train_batch_x[1][i],
pr_hm_norm = results[0][i],
pr_hm_scores = results[1][i],
gt_hm_norm = results[2][i],
gt_hm_scores = results[3][i],
coco_info = np.array([coco_image_id, coco_filename]) )
tm_stop= time.time()
print(' ==> Elapsed time {:.4f}s # of items in results: {} '.format(tm_stop - tm_start,len(train_batch_x)))
print('Final : mrcnn_model epoch_idx{} iterations {}'.format(epoch_idx, iterations))
return
##---------------------------------------------------------------------------
## main routine
##---------------------------------------------------------------------------
if __name__ == '__main__':
start_time = datetime.now().strftime("%m-%d-%Y @ %H:%M:%S")
print()
print('--> Build heatmap npz files from MRCNN')
print('--> Execution started at:', start_time)
print(" Tensorflow Version: {} Keras Version : {} ".format(tf.__version__,keras.__version__))
##------------------------------------------------------------------------------------
## Parse command line arguments
##------------------------------------------------------------------------------------
# parser = command_line_parser()
parser = argparse.ArgumentParser(description='Train Mask R-CNN on MS COCO.')
parser.add_argument('--model', required=False,
default='last',
metavar="/path/to/weights.h5",
help="MRCNN model weights file: 'coco' , 'init' , or Path to weights .h5 file ")
parser.add_argument('--datasets', required=False,
choices=['train', 'val35k', 'minival'],
nargs = '+',
type=str.lower,
metavar="/path/to/weights.h5",
help="coco datasets to build: train, val35k, minival")
parser.add_argument('--output_dir', required=True,
default='train_heatmaps',
metavar="/MLDatasets/coco2014_heatmaps/train_heatmaps",
help='output directory (default=MLDatasets/coco2014_heatmaps/train_heatmaps)')
parser.add_argument('--iterations', required=True,
default=1, type = int,
metavar="<iterations to run>",
help='Number of iterations to run (default=1)')
parser.add_argument('--batch_size', required=False,
default=5, type = int,
metavar="<batch size>",
help='Number of data samples in each batch (default=5)')
parser.add_argument('--start_from', required=False,
default=-1, type = int,
metavar="<last epoch ran>",
help='Starting image index -1 or n to start from image n+1')
parser.add_argument('--sysout', required=False,
choices=['SCREEN', 'FILE'],
default='screen', type=str.upper,
metavar="
help="sysout destination: 'screen' or 'file'")
args = parser.parse_args()
##----------------------------------------------------------------------------------------------
## if debug is true set stdout destination to stringIO
##----------------------------------------------------------------------------------------------
print(" MRCNN Model : ", args.model)
print(" Output Directory : ", args.output_dir)
print(" Datasets : ", args.datasets)
print(" Iterations : ", args.iterations)
print(" Start from image # : ", args.start_from)
print(" Batch Size : ", args.batch_size)
print(" Sysout : ", args.sysout)
if args.sysout == 'FILE':
print(' Output is written to file....')
sys.stdout = io.StringIO()
##------------------------------------------------------------------------------------
## setup project directories
## DIR_ROOT : Root directory of the project
## MODEL_DIR : Directory to save logs and trained model
## COCO_MODEL_PATH : Path to COCO trained weights
##---------------------------------------------------------------------------------
paths = Paths()
paths.display()
##------------------------------------------------------------------------------------
## Build configuration object
##------------------------------------------------------------------------------------
mrcnn_config = CocoConfig()
mrcnn_config.NAME = 'mrcnn'
mrcnn_config.TRAINING_PATH = paths.MRCNN_TRAINING_PATH
mrcnn_config.COCO_DATASET_PATH = paths.COCO_DATASET_PATH
mrcnn_config.COCO_MODEL_PATH = paths.COCO_MODEL_PATH
mrcnn_config.RESNET_MODEL_PATH = paths.RESNET_MODEL_PATH
mrcnn_config.VGG16_MODEL_PATH = paths.VGG16_MODEL_PATH
mrcnn_config.COCO_CLASSES = None
mrcnn_config.BATCH_SIZE = int(args.batch_size) # Batch size is 2 (# GPUs * images/GPU).
mrcnn_config.IMAGES_PER_GPU = int(args.batch_size) # Must match BATCH_SIZE
mrcnn_config.STEPS_PER_EPOCH = 1 # int(args.steps_in_epoch)
mrcnn_config.LEARNING_RATE = 0.001 # float(args.lr)
mrcnn_config.EPOCHS_TO_RUN = 1 # int(args.epochs)
mrcnn_config.LAST_EPOCH_RAN = 0 # int(args.last_epoch)
mrcnn_config.NEW_LOG_FOLDER = False
mrcnn_config.SYSOUT = args.sysout
mrcnn_config.display()
##------------------------------------------------------------------------------------
## Build Mask RCNN Model in TRAINFCN mode
##------------------------------------------------------------------------------------
try :
del mrcnn_model
print('delete model is successful')
gc.collect()
except:
pass
KB.clear_session()
mrcnn_model = mrcnn_modellib.MaskRCNN(mode='trainfcn', config=mrcnn_config)
##------------------------------------------------------------------------------------
## Load Mask RCNN Model Weight file
##------------------------------------------------------------------------------------
exclude_list = []
mrcnn_model.load_model_weights(init_with = args.model, exclude = exclude_list)
##------------------------------------------------------------------------------------
## Display model configuration information
##------------------------------------------------------------------------------------
mrcnn_config.display()
print()
mrcnn_model.layer_info()
print()
##------------------------------------------------------------------------------------
## Build & Load Training and Validation datasets
##------------------------------------------------------------------------------------
dest_path = os.path.join(paths.DIR_DATASET, args.output_dir)
print('Output destination folder : ', dest_path)
iterations = args.iterations
batch_size = args.batch_size
start_from = args.start_from
print(' Iterations: ', type(iterations), iterations)
print(' batch Size: ', type(batch_size), batch_size)
print(' StartFrom : ', type(start_from), start_from)
# dataset = prep_coco_dataset(["train", "val35k"], mrcnn_config)
dataset = prep_coco_dataset(args.datasets, mrcnn_config)
##--------------------------------------------------------------------------------
## Call build routine
##--------------------------------------------------------------------------------
build_heatmap_files(mrcnn_model, dataset, iterations= iterations,
start_from = start_from, dest_path = dest_path)
end_time = datetime.now().strftime("%m-%d-%Y @ %H:%M:%S")
print()
print('--> Build heatmap npz files from MRCNN')
print('--> Execution ended at:', end_time)
##----------------------------------------------------------------------------------------------
## If in debug mode write stdout intercepted IO to output file
##----------------------------------------------------------------------------------------------
if mrcnn_config.SYSOUT == 'FILE':
sysout_file = os.path.join('./', "{:%Y%m%dT%H%M}".format(datetime.now()))
write_stdout(sysout_file, '_sysout', sys.stdout )
sys.stdout = sys.__stdout__
print(' Run information written to ', sysout_file+'_sysout.out')
print('--> Build heatmap npz files from MRCNN')
print('--> Execution ended at:', end_time)
exit(0)
|
python
| 14 | 0.45654 | 132 | 48.087591 | 274 |
starcoderdata
|
#include
#include "FileReader.h"
#include "Window.h"
#include "ObjectManager/ObjectManager.h"
#include "Graphics/GLProgram.h"
#include "File/FileReaderHandler.h"
#include "World/Camera.h"
#include "World/PhysicalWorld.h"
int main()
{
FileReader* reader = new FileReader("C:/Users/rmyho/Desktop/PicoEngine/data/");
FileReaderHandler::setFileReader(reader);
const int width = 1000;
const int height = 500;
Window window(width, height);
Camera camera(width, height, 20);
GLProgram program("shaders/vertex/vertex_base.glsl", "shaders/fragment/fragment_base.glsl");
ObjectManager* om = program.addBoxManager();
Object* obj = om->createObject(10);
obj->rotate(btQuaternion(btVector3(1, 0.5, 0.2), 5));
obj->setPosition(btVector3(0, 10, 0));
Object* obj2 = om->createObject(0, 0, 0, glm::vec3(0, -5, 0), glm::vec3(1), glm::vec3(5, 0.1, 5));
glm::vec3 light(1, -2, 1.5);
while (window.isOpen())
{
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
obj->push(btVector3(0, -20, 0));
PhysicalWorld::getInstance()->step(60);
program.render(light, camera.getPV());
window.swapBuffers();
}
FileData* fd = new FileData();
return 0;
}
|
c++
| 10 | 0.691104 | 99 | 22.823529 | 51 |
starcoderdata
|
"use strict";
/* global window FSLit $ CodeMirror */
window.FSLit = window.FSLit || {};
(function () {
function useCodeMirror(editor, text) {
return CodeMirror(editor, { lineNumbers: true,
theme: "tango",
value: text || "",
mode: "text/x-fstar" });
}
var HTML = ['<div class="fstar-remote-editor">',
' <div class="editor">
' <div class="control-panel">',
' <input class="run" type="button" value="" disabled="disabled" />',
'
' <pre class="stdout">
'
var StandaloneClient = FSLit.StandaloneClient = function(host, _fname, fcontents, _cli) {
var $root = this.$root = $(HTML);
$(host).replaceWith($root);
this.$editor = $root.find(".editor");
this.$stdout = $root.find(".stdout").empty();
this.$run = $root.find(".run").click($.proxy(this.verifyCurrentInput, this));
this.toggleButton(false);
this.editor = useCodeMirror(this.$editor[0], fcontents || "");
};
StandaloneClient.prototype.toggleButton = function(disabled, message) {
this.$run.prop("disabled", disabled);
this.$run.val(message || "Run F*!");
};
StandaloneClient.prototype.verify = function(input) {
$.post("http://www.rise4fun.com/rest/ask/fstar", input, function (data) {
this.$stdout.text(data);
this.toggleButton(false);
});
};
StandaloneClient.prototype.verifyCurrentInput = function(_event) {
var fcontents = this.editor.getValue();
this.$stdout.empty();
this.toggleButton(true, "Running…");
this.verify(fcontents);
};
StandaloneClient.prototype.setValue = function(fcontents) {
this.editor.setValue(fcontents, -1);
};
StandaloneClient.prototype.setFilename = function() {};
function openStandaloneEditor(documentURL, $linkNode) {
var root = $('
$linkNode.parent().after(root);
// fstarjs-config.js overwrites FSLit.StandaloneClient,
// making it point to FStar.CLI.Client.
var fname = documentURL.replace(/^.*\//, "");
var client = new FSLit.StandaloneClient(root, fname, null, null);
$.get(documentURL, function(data) { client.setValue(data); }, 'text');
$linkNode.remove();
}
function addStandaloneEditorLinks() {
$(".fstar-standalone-editor-link")
.each(function () {
var href = $(this).attr("href");
var $span = $('<span class="fstar-standalone-editor-link">');
$span.text($(this).text());
$span.click(function() { openStandaloneEditor(href, $span); });
$(this).replaceWith($span);
});
}
function activateSolutionBodies() {
$(".solution-body")
.each(function () {
var body = $(this);
body.click(function () {
body.addClass("fstar-clear-solution");
});
});
}
function resizeCodeMirrorInstances() {
// Also found in fstar.cli.html
if (document && document.fonts && document.fonts.ready) {
document.fonts.ready.then(function () {
var editors = document.getElementsByClassName("CodeMirror");
for (var idx = 0; idx < editors.length; idx++) {
var editor = editors[idx].CodeMirror;
editor && editor.refresh();
}
});
}
}
$(function() {
addStandaloneEditorLinks();
activateSolutionBodies();
resizeCodeMirrorInstances();
});
}());
|
javascript
| 22 | 0.531162 | 93 | 34.445455 | 110 |
starcoderdata
|
package com.zxr.medicalaid.mvp.model.ModelImpl;
import com.zxr.medicalaid.mvp.entity.moudle.CancleInfo;
import com.zxr.medicalaid.mvp.model.CancleModel;
import com.zxr.medicalaid.mvp.model.base.BaseModelImpl;
import rx.Observable;
/**
* Created by ASUS-NB on 2017/7/14.
*/
public class CancleModelImpl extends BaseModelImpl implements CancleModel {
@Override
public Observable cancleLink(String doctorId, String patientId) {
return api.cancleLink(doctorId,patientId);
}
}
|
java
| 8 | 0.780936 | 87 | 30.473684 | 19 |
starcoderdata
|
"""
Rpw Logger
Usage:
>>> from rpw.utils.logger import logger
>>> logger.info('My logger message')
>>> logger.error('My error message')
"""
import sys
class mockLoggerWrapper():
def __init__(*args, **kwargs):
pass
def __getattr__(self, *args, **kwargs):
return mockLoggerWrapper(*args, **kwargs)
def __call__(self, *args, **kwargs):
pass
class LoggerWrapper():
"""
Logger Wrapper to extend loggers functionality.
The logger is called in the same as the regular python logger,
but also as a few extra features.
>>> logger.info('Message')
[INFO] Message
Log Title
>>> logger.title('Message')
=========
Message
=========
Disable logger
>>> logger.disable()
Log Errors: This method appends errmsg to self.errors.
This allows you to check if an error occured, and if it did not,
close console window.
>>> logger.error('Message')
[ERROR] Message
>>> print(logger.errors)
['Message']
"""
def __init__(self):
handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter("[%(levelname)s] %(message)s")
# TODO: Show Module
# formatter = logging.Formatter("[%(levelname)s] %(message)s [%(module)s:%(lineno)s]")
handler.setFormatter(formatter)
logger = logging.getLogger('rpw_logger')
logger.addHandler(handler)
logger.setLevel(logging.INFO)
handler_title = logging.StreamHandler(sys.stdout)
formatter_title = logging.Formatter("%(message)s")
handler_title.setFormatter(formatter_title)
logger_title = logging.getLogger('rpw_logger_title')
logger_title.addHandler(handler_title)
logger_title.setLevel(logging.INFO)
self._logger = logger
self._logger_title = logger_title
self.errors = []
def disable(self):
""" Sets logger level to logging.CRICITAL """
self._logger.setLevel(logging.CRITICAL)
def verbose(self, verbose):
"""
Sets logger to Verbose.
Args:
(bool): True to set `logger.DEBUG`, False to set to `logging.INFO`.
Usage:
>>> logger.verbose(True)
"""
if verbose:
self._logger.setLevel(logging.DEBUG)
else:
self._logger.setLevel(logging.INFO)
def title(self, msg):
""" Log Message on logging.INFO level with lines above and below """
print('=' * 100)
self._logger_title.info(msg)
print('=' * 100)
def info(self, msg):
""" Log Message on logging.INFO level """
self._logger.info(msg)
def debug(self, msg):
""" Log Message on logging.DEBUG level """
self._logger.debug(msg)
def warning(self, msg):
""" Log Message on logging.WARNING level """
self._logger.warning(msg)
def error(self, msg):
""" Log Message on logging.ERROR level """
self._logger.error(msg)
self.errors.append(msg)
def critical(self, msg):
""" Log Message on logging.CRITICAL level """
self._logger.critical(msg)
def setLevel(self, level):
self._logger.setLevel(level)
def deprecate_warning(depracated, replaced_by=None):
msg = '{} has been deprecated and will be removed soon.'.format(depracated)
if replaced_by:
msg += ' Use {} instead'.format(replaced_by)
logger.warning(msg)
try:
import logging
except ImportError:
# In Dynamo, Use Mock Logger
logger = mockLoggerWrapper()
else:
# In PyRevit, Use Logger
logger = LoggerWrapper()
|
python
| 12 | 0.579195 | 94 | 24.393103 | 145 |
starcoderdata
|
import 'elements-sk/styles/buttons'
import { $$ } from 'common-sk/modules/dom'
import './index.js'
$$('#ask').addEventListener('click', e => {
$$('#dialog').open('Do something dangerous?').then(() => {
$$('#results').textContent = 'Confirmed!';
}).catch(() => {
$$('#results').textContent = 'Cancelled!';
});
})
|
javascript
| 19 | 0.571429 | 60 | 24.307692 | 13 |
starcoderdata
|
export function walk(node, f) {
if (node) {
do {
let next = node.nextSibling // in case the node gets replaced
if (node.nodeType === node.ELEMENT_NODE) {
f.call(node)
walk(node.firstChild, f)
}
node = next
} while (node)
}
}
export function walkTextNodes(node, f) {
if (node) {
do {
let next = node.nextSibling // in case the node gets replaced
if (node.nodeType === node.ELEMENT_NODE) {
walkTextNodes(node.firstChild, f)
} else if (node.nodeType === node.TEXT_NODE) {
f.call(node, node.data, node.parentNode)
}
node = next
} while (node)
}
}
export function selfAndAll(el, selector) {
let res = []
if (el.matches(selector)) res.push(el)
res = [...res, ...el.querySelectorAll(selector)]
return res
}
export function replaceNodeByOuterHTMLFragment(node, html) {
let parent = node.parentNode
let fragment = node.getRootNode().createElement('div')
fragment.innerHTML = html
for (let ch of Array.from(fragment.childNodes)) {
parent.insertBefore(ch, node)
}
parent.removeChild(node)
}
export let endsWith = (longStr, part) => longStr.indexOf(part, longStr.length - part.length) !== -1
let _REST = null
export let REST = () => _REST
let _RESTRIM = null
export let RESTRIM = () => _RESTRIM
export let startsWith = (longStr, part) => {
let res = longStr.substr(0, part.length) == part
_REST = res ? longStr.slice(part.length) : null
_RESTRIM = res ? _REST.replace(/^ */, '') : null
return res
}
export let startsWithIgnoreCase = (longStr, part) => {
let res = longStr.substr(0, part.length).toUpperCase() == part.toUpperCase()
_REST = res ? longStr.slice(part.length) : null
_RESTRIM = res ? _REST.replace(/^ */, '') : null
return res
}
export let indexOfIgnoreCase = (arr, part) => {
let pART = part.toUpperCase()
for (let i in arr) {
if (arr[i].toUpperCase() === pART) {
return i
}
}
return -1
}
export let equalsIgnoreCase = (longStr, part) => {
return longStr.toUpperCase() === part.toUpperCase()
}
// To avoid eslint warning and unsafe direct access to hasOwnProperty
export let hasOwnProperty = (o, k) => Object.prototype.hasOwnProperty.call(o, k)
// eslint-disable-next-line no-console
export let consoleLog = (...args) => console.log(...args)
|
javascript
| 16 | 0.642151 | 99 | 27.703704 | 81 |
starcoderdata
|
import argparse
import logging
from arc852.constants import CAMERA_NAME, CAMERA_NAME_DEFAULT
from arc852.constants import DEVICE_ID, LED_NAME, LED_BRIGHTNESS_DEFAULT
from arc852.constants import DRAW_CONTOUR, DRAW_BOX
from arc852.constants import GRPC_PORT_DEFAULT, GRPC_HOST
from arc852.constants import HSV_RANGE, WIDTH, USB_CAMERA, BGR_COLOR, MIDDLE_PERCENT, FLIP_X, FLIP_Y
from arc852.constants import HSV_RANGE_DEFAULT, SERIAL_PORT_DEFAULT, DEFAULT_BAUD
from arc852.constants import HTTP_DELAY_SECS, HTTP_FILE, LOG_LEVEL, LOG_FILE, MINIMUM_PIXELS, GRPC_PORT, DISPLAY, LEDS
from arc852.constants import HTTP_DELAY_SECS_DEFAULT, HTTP_HOST_DEFAULT, HTTP_TEMPLATE_DEFAULT
from arc852.constants import HTTP_PORT_DEFAULT, HTTP_PORT, TEMPLATE_FILE
from arc852.constants import IMAGE_X, IMAGE_Y, IMAGE_X_DEFAULT, IMAGE_Y_DEFAULT
from arc852.constants import LED_BRIGHTNESS, VERTICAL_LINES, HORIZONTAL_LINES
from arc852.constants import MASK_X, MASK_Y, USB_ID, IMAGE_TOPIC, SO_TOPIC, COMPRESSED, FORMAT, FILENAME, FPS, DRAW_LINE
from arc852.constants import MIDDLE_PERCENT_DEFAULT, MAXIMUM_OBJECTS_DEFAULT, MAXIMUM_OBJECTS
from arc852.constants import MINIMUM_PIXELS_DEFAULT, WIDTH_DEFAULT
from arc852.constants import OOR_SIZE_DEFAULT, OOR_TIME, OOR_TIME_DEFAULT, OOR_UPPER, OOR_UPPER_DEFAULT
from arc852.constants import SERIAL_PORT, BAUD_RATE, HTTP_HOST, USB_PORT, OOR_SIZE
def setup_cli_args(*args):
parser = argparse.ArgumentParser()
for arg in args:
if type(arg) is list:
for a in arg:
a(parser)
else:
arg(parser)
return vars(parser.parse_args())
def bgr(p):
return p.add_argument("--bgr", "--bgr_color", dest=BGR_COLOR, required=True,
help="BGR target value, e.g., -b \"174, 56, 5\"")
def image_topic(p):
return p.add_argument("--img_topic", dest=IMAGE_TOPIC, required=True, help="ROS image topic")
def so_topic(p):
return p.add_argument("--so_topic", dest=SO_TOPIC, default="/single_object",
help="Single Object topic")
def compressed(p):
return p.add_argument("--compressed", dest=COMPRESSED, default=False, action="store_true",
help="Use CompressedImage [false]")
def format(p):
return p.add_argument("--format", dest=FORMAT, default="bgr8", help="Image format [bgr8]")
def filename(p):
return p.add_argument("-f", "--filename", dest=FILENAME, required=True, help="Source filename")
def fps(p):
return p.add_argument("--fps", dest=FPS, default=30, type=int, help="Frames per second [30]")
def usb_camera(p):
return p.add_argument("-u", "--usb", dest=USB_CAMERA, default=False, action="store_true",
help="Use USB camera [false]")
# usb was changed to usb_camera
# def usb(p):
# return p.add_argument("-u", "--usb", dest=USB_CAMERA, default=False, action="store_true",
# help="Use USB camera [false]")
def usb_id(p):
return p.add_argument("--usb_id", dest=USB_ID, default=-1, type=int, help="USB camera id")
def usb_port(p):
return p.add_argument("--usb_port", dest=USB_PORT, default=-1, type=int, help="USB camera port")
def flip_x(p):
return p.add_argument("-x", "--flipx", dest=FLIP_X, default=False, action="store_true",
help="Flip image on X axis [false]")
def flip_y(p):
return p.add_argument("-y", "--flipy", dest=FLIP_Y, default=False, action="store_true",
help="Flip image on Y axis [false]")
def mask_x(p):
return p.add_argument("--mask_x", "--maskx", dest=MASK_X, default=0, type=int, help="Image mask on X axis [0]")
def mask_y(p):
return p.add_argument("--mask_y", "--masky", dest=MASK_Y, default=0, type=int, help="Image mask on Y axis [0]")
def width(p):
return p.add_argument("-w", "--width", dest=WIDTH, default=WIDTH_DEFAULT, type=int,
help="Image width [{0}]".format(WIDTH_DEFAULT))
def middle_percent(p):
return p.add_argument("--percent", "--middle_percent", dest=MIDDLE_PERCENT, default=MIDDLE_PERCENT_DEFAULT,
type=int, help="Middle percent [{0}]".format(MIDDLE_PERCENT_DEFAULT))
def minimum_pixels(p):
return p.add_argument("--min_pixels", dest=MINIMUM_PIXELS, default=MINIMUM_PIXELS_DEFAULT, type=int,
help="Minimum pixel area [{0}]".format(MINIMUM_PIXELS_DEFAULT))
def max_objects(p):
return p.add_argument("--max_objects", dest=MAXIMUM_OBJECTS, default=MAXIMUM_OBJECTS_DEFAULT, type=int,
help="Maximum objects [{0}]".format(MAXIMUM_OBJECTS_DEFAULT))
def hsv_range(p):
return p.add_argument("--range", "--hsv", "--hsv_range", dest=HSV_RANGE, default=HSV_RANGE_DEFAULT, type=int,
help="HSV range [{0}]".format(HSV_RANGE_DEFAULT))
def grpc_port(p):
return p.add_argument("-p", "--port", dest=GRPC_PORT, default=GRPC_PORT_DEFAULT, type=int,
help="gRPC port [{0}]".format(GRPC_PORT_DEFAULT))
def grpc_host(p):
return p.add_argument("-g", "--grpc", "--grpc_host", dest=GRPC_HOST, required=True,
help="gRPC location server hostname")
def leds(p):
return p.add_argument("--leds", dest=LEDS, default=False, action="store_true",
help="Enable Blinkt led feedback [false]")
def draw_line(p):
return p.add_argument("--draw_line", "--line", dest=DRAW_LINE, default=False, action="store_true",
help="Draw fitted line [false]")
def draw_contour(p):
return p.add_argument("--draw_contour", "--contour", dest=DRAW_CONTOUR, default=False, action="store_true",
help="Draw contour box [false]")
def draw_box(p):
return p.add_argument("--draw_box", "--box", dest=DRAW_BOX, default=False, action="store_true",
help="Draw bounding box [false]")
def display(p):
return p.add_argument("--display", dest=DISPLAY, default=False, action="store_true", help="Display image [false]")
def serial_port(p):
return p.add_argument("-s", "--serial", dest=SERIAL_PORT, default=SERIAL_PORT_DEFAULT,
help="Serial port [{0}]".format(SERIAL_PORT_DEFAULT))
def baud_rate(p):
return p.add_argument("--baud", "--baud_rate", dest=BAUD_RATE, default=DEFAULT_BAUD,
help="Baud rate [{0}]".format(DEFAULT_BAUD))
def device_id(p):
return p.add_argument("--did", "--device_id", dest=DEVICE_ID, help="USB device ID")
def led_name(p):
return p.add_argument("--led", "--led_name", dest=LED_NAME, required=True, help="LED name")
def led_brightness(p):
return p.add_argument("--brightness", "--led_brightness", dest=LED_BRIGHTNESS, default=LED_BRIGHTNESS_DEFAULT,
help="LED brightness [{0}]".format(LED_BRIGHTNESS_DEFAULT))
def camera_name(p):
return p.add_argument("-c", "--camera", "--camera_name", dest=CAMERA_NAME, required=True, help="Camera name")
def camera_name_optional(p):
return p.add_argument("-c", "--camera", "--camera_name", dest=CAMERA_NAME, required=False,
default=CAMERA_NAME_DEFAULT, help="Camera name")
# def mqtt_host(p):
# return p.add_argument("-m", "--mqtt", "--mqtt_host", dest=MQTT_HOST, required=True, help="MQTT server hostname")
def calib(p):
return p.add_argument("--calib", default=False, action="store_true", help="Calibration mode [false]")
def alternate(p):
return p.add_argument("--alternate", default=False, action="store_true",
help="Alternate servo actions [false]")
def vertical_lines(p):
return p.add_argument("--vertical", "--vertical_lines", dest=VERTICAL_LINES, default=False, action="store_true",
help="Draw vertical lines [false]")
def horizontal_lines(p):
return p.add_argument("--horizontal", "--horizontal_lines", dest=HORIZONTAL_LINES, default=False,
action="store_true", help="Draw horizontal lines [false]")
def http_host(p):
return p.add_argument("--http", dest=HTTP_HOST, default=HTTP_HOST_DEFAULT,
help="HTTP hostname:port [{0}]".format(HTTP_HOST_DEFAULT))
def http_delay_secs(p):
return p.add_argument("--delay", "--http_delay", dest=HTTP_DELAY_SECS, default=HTTP_DELAY_SECS_DEFAULT, type=float,
help="HTTP delay secs [{0}]".format(HTTP_DELAY_SECS_DEFAULT))
def http_verbose(p):
return p.add_argument("--http_verbose", "--verbose_http", dest="http_verbose", default=False, action="store_true",
help="Enable verbose HTTP log [false]")
# verbose was changed to log_level
# def verbose(p):
# return p.add_argument("-v", "--verbose", dest=LOG_LEVEL, default=logging.INFO, action="store_const",
# const=logging.DEBUG, help="Enable debugging info")
def log_level(p):
return p.add_argument("-v", "--verbose", dest=LOG_LEVEL, default=logging.INFO, action="store_const",
const=logging.DEBUG, help="Enable debugging info")
def log_file(p):
return p.add_argument("-l", "--log_file", dest=LOG_FILE, default=None, help="Logging output to file")
# def mqtt_topic(p):
# return p.add_argument("--topic", "--mqtt_topic", dest=MQTT_TOPIC, required=True,
# help="Desired MQTT topic")
def oor_size(p):
return p.add_argument("--oor_size", dest=OOR_SIZE, type=int, default=OOR_SIZE_DEFAULT,
help="Out of range buffer size [{0}]".format(OOR_SIZE_DEFAULT))
def oor_time(p):
return p.add_argument("--oor_time", dest=OOR_TIME, type=int, default=OOR_TIME_DEFAULT,
help="Out of range time [{0}]".format(OOR_TIME_DEFAULT))
def oor_upper(p):
return p.add_argument("--oor_upper", dest=OOR_UPPER, type=int, default=OOR_UPPER_DEFAULT,
help="Out of range upper boundary [{0}]".format(OOR_UPPER_DEFAULT))
def http_port(p):
return p.add_argument("-p", "--port", dest=HTTP_PORT, default=HTTP_PORT_DEFAULT, type=int,
help="HTTP port [{0}]".format(HTTP_PORT_DEFAULT))
def http_file(p):
return p.add_argument("-i", "--file", "--http_file", dest=HTTP_FILE, default=HTTP_TEMPLATE_DEFAULT,
help="HTTP template file")
def template_file(p):
return p.add_argument("-t", "--template", dest=TEMPLATE_FILE,
default=HTTP_TEMPLATE_DEFAULT, help="Template file name [{}]".format(HTTP_TEMPLATE_DEFAULT))
def image_x(p):
return p.add_argument("-x", "--image_x", dest=IMAGE_X, default=IMAGE_X_DEFAULT, type=int,
help="Image x [{0}]".format(IMAGE_X_DEFAULT))
def image_y(p):
return p.add_argument("-y", "--image_y", dest=IMAGE_Y, default=IMAGE_Y_DEFAULT, type=int,
help="Image y [{0}]".format(IMAGE_Y_DEFAULT))
|
python
| 12 | 0.630175 | 120 | 37.678322 | 286 |
starcoderdata
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using STGSample.Barrage;
using STGSample.Bullets;
using STGSample.Factories;
using STGSample.Utils;
namespace STGSample.Enemies
{
public class SampleEnemy : AbstractEnemy
{
public override Vector2 DrawPoint => new Vector2(Position.X - 10, Position.Y - 10);
private Vector2 FirePosition => new Vector2(Position.X, Position.Y + 10);
public SampleEnemy(Vector2 position, float health, float attack, float fireRate, float defense)
{
centerPosition = position;
Health = MaxHealth = health;
Attack = attack;
FireRate = fireRate;
Defense = defense;
barrages.Add(new LineBarrage(this, -1, 300, new Vector2(3, 4), Vector2.Zero, FirePosition, attack));
barrages.Add(new LineBarrage(this, -1, 300, new Vector2(-3, -4), Vector2.Zero, FirePosition, attack));
barrages.Add(new LineBarrage(this, -1, 300, new Vector2(4, -3), Vector2.Zero, FirePosition, attack));
barrages.Add(new LineBarrage(this, -1, 300, new Vector2(-4, 3), Vector2.Zero, FirePosition, attack));
//Physics = new Physics(new Vector2(1, 1), Vector2.Zero);
sprite = SpriteFactory.CreateSprite(GetType());
}
public override void Draw(SpriteBatch spriteBatch)
{
sprite.Draw(spriteBatch, DrawBox, layerDepth: 0.5f);
}
public override Rectangle DrawBox => HitBox.BoundingBox;
public override IGraph HitBox => new GraphRectangle(DrawPoint.X, DrawPoint.Y, 20, 20);
public override void HitPlayer(IPlayer player)
{
//Do nothing.
}
public override void Update(GameTime gameTime)
{
sprite.Update(gameTime);
//centerPosition += Physics.Update(gameTime);
foreach (var barrage in barrages) barrage.Update(gameTime);
}
/*float fireDelay;*/
public override void Fire(List bullets, List enemies)
{
foreach (var barrage in barrages) barrage.Fire(bullets, enemies);
/* float fireGap = (FireRate + 2) / 2;
float damage = Attack;
fireDelay -= fireGap;
if (fireDelay <= 0)
{
fireDelay = 24;
bullets.Add(new EnemyBullet(this, FirePosition, new Vector2(0, 10), Vector2.Zero, damage, Color.White));
}*/
}
}
}
|
c#
| 18 | 0.616861 | 120 | 36.422535 | 71 |
starcoderdata
|
void CAcapSettings::SetFields(int nID, char * strSetting)
{
CString strTempSetting;
if(nID > 0)
{
//Some ID's don't exist in Windows but in Mac. Need to do double checking for those..
switch(nID)
{
case IDS_INI_REAL_NAME:
{
long outLen;
char outStr[255];
long inLen = strlen(strSetting);
UTF8To88591(strSetting, inLen, outStr, &outLen);
outStr[outLen] = NULL;
SetIniString(nID, outStr);
}
break;
case IDS_FIRST_UNREAD:
SetIniShort(IDS_INI_FIRST_UNREAD_NORMAL, (_stricmp(strSetting, "normal") == 0));
SetIniShort(IDS_INI_FIRST_UNREAD_STATUS, (_stricmp(strSetting, "status") == 0));
SetIniShort(IDS_INI_USE_POP_LAST, (_stricmp(strSetting, "poplast")==0));
break;
case IDS_POP_AUTHENTICATE:
SetIniShort(IDS_INI_AUTH_APOP, (_stricmp(strSetting, "apop") == 0));
SetIniShort(IDS_INI_AUTH_RPA, (_stricmp(strSetting, "rpa") == 0));
SetIniShort(IDS_INI_AUTH_PASS, (_stricmp(strSetting, "password")==0));
SetIniShort(IDS_INI_AUTH_KERB, (_stricmp(strSetting, "kerberos")==0));
break;
case IDS_SEND_FORMAT:
SetIniShort(IDS_INI_SEND_MIME, ((_stricmp(strSetting, "applesingle") == 0) ||
(_stricmp(strSetting, "appledouble") == 0)));
SetIniShort(IDS_INI_SEND_BINHEX, (_stricmp(strSetting, "binhex") == 0));
SetIniShort(IDS_INI_SEND_UUENCODE, (_stricmp(strSetting, "uuencode")==0));
break;
case IDS_INI_ACCESS_METHOD:
SetIniShort(IDS_INI_USES_POP, (_stricmp(strSetting, "pop") == 0));
SetIniShort(IDS_INI_USES_IMAP, (_stricmp(strSetting, "imap") == 0));
break;
case IDS_INI_DS_DEFAULT:
SetIniShort(IDS_INI_FINGER_DEFAULT_LOOKUP, (_stricmp(strSetting, "finger") == 0));
SetIniShort(IDS_INI_LDAP_DEFAULT_LOOKUP, (_stricmp(strSetting, "ldap") == 0));
SetIniShort(IDS_INI_PH_DEFAULT_LOOKUP, (_stricmp(strSetting, "ph") == 0));
break;
case IDS_INI_LEAVE_ON_SERVER_DAYS:
if(atoi(strSetting) > 0)
SetIniString(nID, strSetting);
else
SetIniShort(IDS_INI_DELETE_MAIL_FROM_SERVER, 0);
break;
default:
//Set the puppy
SetIniString(nID, strSetting);
break;
}
}
if(GetIniShort(IDS_INI_LEAVE_MAIL_ON_SERVER))
{
if(GetIniShort(IDS_INI_LEAVE_ON_SERVER_DAYS) > 0)
SetIniShort(IDS_INI_DELETE_MAIL_FROM_SERVER, 1);
else
SetIniShort(IDS_INI_DELETE_MAIL_FROM_SERVER, 0);
}
}
|
c++
| 18 | 0.643573 | 88 | 28.9625 | 80 |
inline
|
var saveSelectColor = {
'Name': 'SelcetColor',
'Color': 'theme-white'
}
// 判断用户是否已有自己选择的模板风格
if (storageLoad('SelcetColor')) {
$('body').attr('class', storageLoad('SelcetColor').Color);
} else {
storageSave(saveSelectColor);
$('body').attr('class', 'theme-white');
}
// 本地缓存
function storageSave(objectData) {
localStorage.setItem(objectData.Name, JSON.stringify(objectData));
}
function storageLoad(objectName) {
if (localStorage.getItem(objectName)) {
return JSON.parse(localStorage.getItem(objectName))
} else {
return false
}
}
|
javascript
| 9 | 0.669903 | 70 | 20.344828 | 29 |
starcoderdata
|
package com.github.charlemaznable.core.net;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.tuple.Pair;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.Proxy;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import static com.github.charlemaznable.core.codec.Json.json;
import static com.github.charlemaznable.core.lang.Listt.newArrayList;
import static com.github.charlemaznable.core.lang.Str.isEmpty;
import static com.github.charlemaznable.core.net.Url.encode;
import static java.lang.String.format;
import static java.net.HttpURLConnection.setFollowRedirects;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;
import static org.apache.commons.lang3.tuple.Pair.of;
@Slf4j
public final class HttpReq {
private final String baseUrl;
private String req;
private Charset charset = UTF_8;
private StringBuilder params = new StringBuilder();
private List<Pair<String, String>> props = newArrayList();
private SSLSocketFactory sslSocketFactory;
private HostnameVerifier hostnameVerifier;
private Proxy proxy;
public HttpReq(String baseUrl) {
this.baseUrl = baseUrl;
}
public HttpReq(String baseUrlTemplate, Object... baseUrlArgs) {
this(format(baseUrlTemplate, baseUrlArgs));
}
public static String get(String baseUrl) {
return new HttpReq(baseUrl).get();
}
public static String get(String baseUrlTemplate, Object... baseUrlArgs) {
return get(format(baseUrlTemplate, baseUrlArgs));
}
public HttpReq req(String req) {
this.req = req;
return this;
}
public HttpReq cookie(String value) {
if (isNull(value)) return this;
return prop("Cookie", value);
}
public HttpReq prop(String name, String value) {
props.add(of(name, value));
return this;
}
public HttpReq param(String name, String value) {
if (params.length() > 0) params.append('&');
params.append(name).append('=').append(encode(value));
return this;
}
public HttpReq params(Map<String, String> params) {
for (val paramEntry : params.entrySet()) {
val key = paramEntry.getKey();
val value = paramEntry.getValue();
if (isEmpty(key) || isEmpty(value)) continue;
param(key, value);
}
return this;
}
public HttpReq requestBody(String requestBody) {
if (nonNull(requestBody)) {
if (params.length() > 0) params.append('&');
params.append(requestBody);
}
return this;
}
public HttpReq sslSocketFactory(SSLSocketFactory sslSocketFactory) {
this.sslSocketFactory = sslSocketFactory;
return this;
}
public HttpReq hostnameVerifier(HostnameVerifier hostnameVerifier) {
this.hostnameVerifier = hostnameVerifier;
return this;
}
public HttpReq proxy(Proxy proxy) {
this.proxy = proxy;
return this;
}
public String post() {
HttpURLConnection http = null;
try {
// Post请求的url,与get不同的是不需要带参数
val url = baseUrl + (isNull(req) ? "" : req);
http = commonSettings(url);
postSettings(http);
setHeaders(http);
setSSL(http);
// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
// 要注意的是connection.getOutputStream会隐含的进行connect。
http.connect();
writePostRequestBody(http);
return parseResponse(http, url);
} catch (Exception e) {
log.error("post error {}", e.getMessage());
return null;
} finally {
if (nonNull(http)) http.disconnect();
}
}
public String get() {
HttpURLConnection http = null;
try {
val url = baseUrl + (isNull(req) ? "" : req)
+ (params.length() > 0 ? ("?" + params) : "");
http = commonSettings(url);
setHeaders(http);
setSSL(http);
http.connect();
return parseResponse(http, url);
} catch (Exception e) {
log.error("get error {}", e.getMessage());
return null;
} finally {
if (nonNull(http)) http.disconnect();
}
}
private HttpURLConnection commonSettings(String urlString) throws IOException {
setFollowRedirects(true);
val url = new URL(urlString);
val http = (HttpURLConnection) (isNull(this.proxy) ?
url.openConnection() : url.openConnection(this.proxy));
http.setRequestProperty("Accept-Charset", this.charset.name());
http.setConnectTimeout(60 * 1000);
http.setReadTimeout(60 * 1000);
return http;
}
private void postSettings(HttpURLConnection http) throws ProtocolException {
// 设置是否向connection输出,因为这个是post请求,参数要放在
// http正文内,因此需要设为true
http.setDoOutput(true);
http.setDoInput(true); // Read from the connection. Default is true.
http.setRequestMethod("POST");// 默认是 GET方式
http.setUseCaches(false); // Post 请求不能使用缓存
http.setInstanceFollowRedirects(true);
// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
// 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode进行编码
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
}
private void setHeaders(HttpURLConnection http) {
for (val prop : props) http.setRequestProperty(prop.getKey(), prop.getValue());
}
private void setSSL(HttpURLConnection http) {
if (!(http instanceof HttpsURLConnection)) return;
if (nonNull(sslSocketFactory))
((HttpsURLConnection) http).setSSLSocketFactory(sslSocketFactory);
if (nonNull(hostnameVerifier))
((HttpsURLConnection) http).setHostnameVerifier(hostnameVerifier);
}
private void writePostRequestBody(HttpURLConnection http) throws IOException {
if (params.length() == 0) return;
val out = new DataOutputStream(http.getOutputStream());
// The URL-encoded contend 正文,正文内容其实跟get的URL中 '? '后的参数字符串一致
// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面
// 错误用法: out.writeBytes(postData)
val postData = params.toString();
out.write(postData.getBytes(this.charset));
out.flush();
out.close();
}
private String parseResponse(HttpURLConnection http, String url) throws IOException {
val status = http.getResponseCode();
val rspCharset = parseCharset(http.getHeaderField("Content-Type"));
if (status == 200) return readResponseBody(http, rspCharset);
log.warn("non 200 response :" + readErrorResponseBody(url, http, status, rspCharset));
return null;
}
private Charset parseCharset(String contentType) {
if (isNull(contentType)) return this.charset;
String charsetName = null;
for (val param : contentType.replace(" ", "").split(";")) {
if (param.startsWith("charset=")) {
charsetName = param.split("=", 2)[1];
break;
}
}
return isNull(charsetName) ? this.charset : Charset.forName(charsetName);
}
private String readResponseBody(HttpURLConnection http, Charset charset) throws IOException {
return readInputStreamToString(http.getInputStream(), charset);
}
private String readErrorResponseBody(String url, HttpURLConnection http, int status, Charset charset) throws IOException {
val errorStream = http.getErrorStream();
if (nonNull(errorStream)) {
val error = readInputStreamToString(errorStream, charset);
return (url + ", STATUS CODE =" + status + ", headers=" + json(http.getHeaderFields()) + "\n\n" + error);
} else {
return (url + ", STATUS CODE =" + status + ", headers=" + json(http.getHeaderFields()));
}
}
private String readInputStreamToString(InputStream inputStream, Charset charset) throws IOException {
val baos = new ByteArrayOutputStream();
val buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
return new String(baos.toByteArray(), charset);
}
}
|
java
| 16 | 0.642155 | 126 | 32.281955 | 266 |
starcoderdata
|
package cn.home.modules.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
@Aspect
public class AroundExample {
@Around("com.xyz.myapp.SystemArchitecture.businessService()")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
// start stopwatch
Object retVal = pjp.proceed();
// stop stopwatch
return retVal;
}
}
|
java
| 9 | 0.785219 | 75 | 27.866667 | 15 |
starcoderdata
|
/**
* Copyright (C) 2002 (
*
* 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 de.mhus.lib.core.util;
import de.mhus.lib.core.pojo.DefaultFilter;
import de.mhus.lib.core.pojo.PojoAttribute;
import de.mhus.lib.core.pojo.PojoModel;
import de.mhus.lib.core.pojo.PojoParser;
/**
* Convert a object into string using pojo mechanism. The conversion is done if the method toString
* is used for the first time.
*
* @author mikehummel
*/
public class Stringifier {
private Object from;
private String str;
private int level;
public Stringifier(Object in) {
this(in, 1);
}
public Stringifier(Object in, int level) {
this.from = in;
this.level = level;
}
@Override
public synchronized String toString() {
if (str == null) {
str = doStringify(from, 0);
}
return str;
}
private String doStringify(Object in, int level) {
if (in == null) return "null";
if (level >= this.level) return in.toString();
StringBuilder out = new StringBuilder();
out.append('{');
try {
out.append(in.getClass()).append(':');
PojoModel model =
new PojoParser()
.parse(in, "_", null)
.filter(new DefaultFilter(true, false, true, true, true))
.getModel();
boolean first = true;
for (PojoAttribute attr : model) {
if (first) first = false;
else out.append(',');
try {
out.append(attr.getName())
.append('=')
.append(doStringify(attr.get(in), level + 1));
} catch (Throwable t) {
out.append(t.toString());
}
}
} catch (Throwable t) {
out.append(t.toString());
}
out.append('}');
return out.toString();
}
public static void stringifyArray(Object[] in) {
if (in == null) return;
for (int i = 0; i < in.length; i++) in[i] = stringifyWrap(in[i]);
}
public static Object stringifyWrap(Object o) {
if (o == null) return null;
Class<? extends Object> c = o.getClass();
if (c.isPrimitive() || o instanceof String) return o;
String cn = c.getName();
if (cn.startsWith("java") || cn.startsWith("javax")) return o;
return new Stringifier(o);
}
}
|
java
| 18 | 0.559035 | 99 | 29.66 | 100 |
starcoderdata
|
def user_status(self, handle: str, from_sub: int = None, count: int = None):
'''
Codeforces API name: user.status.
Returns submissions of specified user as list of
Submission objects.
handle (Required) : str. Codeforces user handle.
from_sub (API: from): int. 1-based index of the first
submission to return.
count : int. Number of returned submissions.
Example: cf.user_status(handle='Fefer_Ivan',
from_sub=1,
count=10)
'''
# NOTE: from is a keyword in Python
kwargs = {
'handle': handle,
'from': from_sub,
'count': count
}
self.request_api('user.status', **kwargs)
return list(map(Submission, self.last_api['result']))
|
python
| 10 | 0.508494 | 76 | 41.095238 | 21 |
inline
|
using System.Collections.Generic;
namespace PizzaBox.Domain.Models
{
public class Location
{
public Address Address { get; set; }
public Dictionary<string, int> Inventory { get; set; }
public List Orders { get; set; }
public override string ToString()
{
return Address.City + " has " +Orders.Count+ " orders.";
}
public string PrintLocationOrders()
{
string location = Address.City + " orders are: ";
foreach (var Order in Orders)
{
location += Order.PrintOrder();
}
return location;
}
}
}
|
c#
| 13 | 0.634375 | 62 | 23.615385 | 26 |
starcoderdata
|
public static List<String> forModule( String javaLauncherPath, String modulePath, String mainModule, String mainClass ) {
List<String> commands = new ArrayList<>();
//if( modulePath == null ) throw new NullPointerException( "Module path cannot be null" );
if( mainModule == null ) throw new NullPointerException( "Main module cannot be null" );
if( mainClass == null ) throw new NullPointerException( "Module main class cannot be null" );
// Add the java executable path
commands.add( javaLauncherPath == null ? OperatingSystem.getJavaLauncherPath() : javaLauncherPath );
// Add the VM parameters to the commands
RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
for( String command : runtimeBean.getInputArguments() ) {
// Skip some commands
if( command.equals( "exit" ) ) continue;
if( command.equals( "abort" ) ) continue;
if( command.startsWith( "--module-path" ) ) continue;
if( command.startsWith( "-Djdk.module.main" ) ) continue;
if( command.startsWith( "-Djdk.module.main.class" ) ) continue;
if( !commands.contains( command ) ) commands.add( command );
}
// Add the module information
if( modulePath != null ) {
commands.add( "-p" );
commands.add( modulePath );
}
commands.add( "-m" );
commands.add( mainModule + "/" + mainClass );
return commands;
}
|
java
| 10 | 0.695685 | 121 | 38.558824 | 34 |
inline
|
boolean TelnetStreamClass::disconnected() {
#if __has_include(<WiFiNINA.h>) || __has_include(<WiFi101.h>)
if (server.status() == 0) // 0 is CLOSED
return true;
#else
if (!server)
return true;
#endif
if (!client || !client.available()) {
client = server.available(); // try to get next client with data
}
|
c++
| 9 | 0.614925 | 68 | 26.083333 | 12 |
inline
|
from collections import deque, Counter
from dataclasses import dataclass
from pathlib import Path
from typing import List
import argparse
FILE_DIR = Path(__file__).parent
@dataclass()
class Coords:
y: int
x: int
def check_neighbors(matrix: List[str]) -> tuple:
"""
Tuple is a List[ints] and a list of coordinates of low_points
"""
coords = []
lows = []
diagonals = [(-1, -1), (-1, 1), (1, -1), (1, 1)]
for y in range(len(matrix)):
for x in range(len(matrix[0])):
cell = matrix[y][x]
neighbors = []
for yy in [-1, 0, 1]:
for xx in [-1, 0, 1]:
if (yy == 0 and xx == 0) or (yy, xx) in diagonals:
continue
y_cell = y+yy
x_cell = x+xx
if (y_cell >= 0 and x_cell >= 0) and (y_cell < len(matrix) and x_cell < len(matrix[y])):
neighbors.append(matrix[y + yy][x + xx])
if all([int(cell) < int(ii) for ii in neighbors]):
coords.append((y, x))
lows.append(int(cell))
return [l+1 for l in lows], coords
def bfs(matrix: List[str], coords: tuple[int]):
q = deque()
visited = set()
visited.add(coords)
q.appendleft(coords)
while q:
cur_node = q.pop()
cur_node = Coords(cur_node[0], cur_node[1])
diagonals = [(-1, -1), (-1, 1), (1, -1), (1, 1)]
for yy in [-1, 0, 1]:
for xx in [-1, 0, 1]:
if (yy == 0 and xx == 0) or (yy, xx) in diagonals:
continue
y_cell = cur_node.y+yy
x_cell = cur_node.x+xx
if (y_cell >= 0 and x_cell >= 0) and (y_cell < len(matrix) and x_cell < len(matrix[0])):
if matrix[cur_node.y + yy][cur_node.x + xx] != "9":
if (cur_node.y+yy, cur_node.x+xx) not in visited:
visited.add((cur_node.y+yy, cur_node.x+xx))
q.appendleft((cur_node.y+yy, cur_node.x+xx))
return visited
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
breakpoint()
print(args.accumulate(args.integers))
test_data = [
"2199943210",
"3987894921",
"9856789892",
"8767896789",
"9899965678",
]
test_outputs = [x for x in test_data]
test_lows, test_coords = check_neighbors(test_outputs)
print(sum(test_lows))
test_basins = []
for c in test_coords:
test_basins.append(bfs(test_data, c))
test_basins.sort(key=len, reverse=True)
print(test_basins)
DATA = (FILE_DIR / "input.txt").read_text().strip()
data = [x for x in DATA.split("\n")]
# sol 1
lows, coords = check_neighbors(data)
print(coords[0])
print("Number of coords:", len(coords))
print(sum(lows))
# sol 2
basins = []
for c in coords:
basins.append(bfs(data, c))
basins.sort(key=len, reverse=True)
print(len(basins[0]) * len(basins[1]) * len(basins[2]))
|
python
| 21 | 0.511588 | 108 | 30.772727 | 110 |
starcoderdata
|
using System.Data.Common;
using DataWings.Common;
using DataWings.SQLite;
namespace DataWings.IntegrationTests
{
class SqlProvider : SQLiteProvider, ISqlProviderFactory
{
private static SqlProvider current;
public static SqlProvider GetInstance(string connString)
{
if (current == null)
current = new SqlProvider(connString);
return current;
}
public SqlProvider(string connectionString) : base(connectionString)
{
}
protected override void SqlExecuted(string sql)
{
Database.ReceiveExecutedSql(sql);
}
public ISqlProvider CreateProvider(string connectionString)
{
return this;
}
}
}
|
c#
| 13 | 0.617834 | 76 | 22.787879 | 33 |
starcoderdata
|
void Yield() {
CPU* cpu = GetCPULocal();
if (cpu->currentThread) {
cpu->currentThread->timeSlice = 0;
}
asm("int $0xFD"); // Send schedule IPI to self
}
|
c++
| 9 | 0.570621 | 50 | 21.25 | 8 |
inline
|
@Test
public void shouldFlushEachRecord() throws IOException {
for (int i = 0; i < 10; ++i) {
// write metrics
try (final Metrics metrics = metricsCreator.create()) {
metrics.put("id", i);
}
// make sure newly introduced metric is in the stream without closing metrics creator
try (final MetricsReader reader = newMetricsReader()) {
for (int j = 0; j <= i; ++j) {
final Map<String, ?> metrics = reader.readNext();
assertNotNull(metrics);
assertEquals(j, metrics.get("id"));
}
}
}
}
|
java
| 15 | 0.57363 | 91 | 31.5 | 18 |
inline
|
package com.CTF011064.MobilePhone;
public class SamsungGalaxyNote8 extends Android {
// Constructor
public SamsungGalaxyNote8() {
}
// Feature
public void UsePen() {
}
}
|
java
| 8 | 0.768627 | 74 | 16.066667 | 15 |
starcoderdata
|
# coding=utf-8
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# pylint: disable=too-many-lines
# pylint: disable=line-too-long
from knack.help_files import helps # pylint: disable=unused-import
helps['healthcareapis'] = """
type: group
short-summary: Commands to manage service.
"""
helps['healthcareapis create'] = """
type: command
short-summary: create service.
examples:
- name: Create or Update a service with all parameters
text: |-
az healthcareapis create --resource-group "rg1" --name "service1" --kind "fhir-R4" \\
--location "westus2" --cosmos-db-offer-throughput "1000" --authentication-authority \\
"https://login.microsoftonline.com/common" --authentication-audience \\
"https://azurehealthcareapis.com" --authentication-smart-proxy-enabled true \\
--cors-max-age "1440" --cors-allow-credentials false \\
--access-policies-object-id c487e7d1-3210-41a3-8ccc-e9372b78da47,5b307da8-43d4-492b-8b66-b0294ade872f \\
--cors-origins "*" --cors-headers "*" --cors-methods "DELETE,GET,OPTIONS,PATCH,POST,PUT"
- name: Create or Update a service with minimum parameters
text: |-
az healthcareapis create --resource-group "rg1" --name "service2" --kind "fhir-R4" \\
--location "westus2" --access-policies-object-id c487e7d1-3210-41a3-8ccc-e9372b78da47
"""
helps['healthcareapis update'] = """
type: command
short-summary: update service.
examples:
- name: Patch Service
text: |-
az healthcareapis update --resource-group "rg1" --name "service2" --kind "fhir-R4" \\
--location "westus2" --access-policies-object-id c487e7d1-3210-41a3-8ccc-e9372b78da47
"""
helps['healthcareapis delete'] = """
type: command
short-summary: delete service.
examples:
- name: Delete Service
text: |-
az healthcareapis delete --resource-group "rg1" --name "service1"
"""
helps['healthcareapis list'] = """
type: command
short-summary: list service.
"""
helps['healthcareapis show'] = """
type: command
short-summary: show service.
"""
|
python
| 5 | 0.594358 | 119 | 38.952381 | 63 |
starcoderdata
|
fn main() {
// This enables logging via env_logger & log crate macros. If you don't need logging or want
// to implement your own, omit this line.
opcua_console_logging::init();
// Create an OPC UA server with sample configuration and default node set
let mut server = Server::new(ServerConfig::load(&PathBuf::from("server.conf")).unwrap());
let ns = {
let address_space = server.address_space();
let mut address_space = address_space.write().unwrap();
address_space.register_namespace("urn:opcua-sensors-server").unwrap()
};
// Add some variables
add_sensor_variables(&mut server, ns);
// Run the server. This does not ordinarily exit so you must Ctrl+C to terminate
println!("Starting....");
server.run();
}
|
rust
| 14 | 0.659873 | 96 | 36.428571 | 21 |
inline
|
<?php
/**
* @package Wsal
* @subpackage Sensors
* Login/Logout sensor.
*
* 1000 User logged in
* 1001 User logged out
* 1002 Login failed
* 1003 Login failed / non existing user
* 1004 Login blocked
* 4003 User has changed his or her password
*/
class WSAL_Sensors_LogInOut extends WSAL_AbstractSensor
{
/**
* Transient name.
* WordPress will prefix the name with "_transient_" or "_transient_timeout_" in the options table.
*/
const TRANSIENT_FAILEDLOGINS = 'wsal-failedlogins-known';
const TRANSIENT_FAILEDLOGINS_UNKNOWN = 'wsal-failedlogins-unknown';
/**
* @var WP_User current user object
*/
protected $_current_user = null;
/**
* Listening to events using WP hooks.
*/
public function HookEvents()
{
add_action('wp_login', array($this, 'EventLogin'), 10, 2);
add_action('wp_logout', array($this, 'EventLogout'));
add_action('password_reset', array($this, 'EventPasswordReset'), 10, 2);
add_action('wp_login_failed', array($this, 'EventLoginFailure'));
add_action('clear_auth_cookie', array($this, 'GetCurrentUser'), 10);
add_filter('wp_login_blocked', array($this, 'EventLoginBlocked'), 10, 1);
}
/**
* Sets current user.
*/
public function GetCurrentUser()
{
$this->_current_user = wp_get_current_user();
}
/**
* Event Login.
*/
public function EventLogin($user_login, $user = null)
{
if (empty($user)) {
$user = get_user_by('login', $user_login);
}
$userRoles = $this->plugin->settings->GetCurrentUserRoles($user->roles);
if ($this->plugin->settings->IsLoginSuperAdmin($user_login)) {
$userRoles[] = 'superadmin';
}
$this->plugin->alerts->Trigger(1000, array(
'Username' => $user_login,
'CurrentUserRoles' => $userRoles,
), true);
}
/**
* Event Logout.
*/
public function EventLogout()
{
if ($this->_current_user->ID != 0) {
$this->plugin->alerts->Trigger(1001, array(
'CurrentUserID' => $this->_current_user->ID,
'CurrentUserRoles' => $this->plugin->settings->GetCurrentUserRoles($this->_current_user->roles),
), true);
}
}
/**
* Login failure limit count.
* @return integer limit
*/
protected function GetLoginFailureLogLimit()
{
return 10;
}
/**
* Expiration of the transient saved in the WP database.
* @return integer Time until expiration in seconds from now
*/
protected function GetLoginFailureExpiration()
{
return 12 * 60 * 60;
}
/**
* Check failure limit.
* @param string $ip IP address
* @param integer $site_id blog ID
* @param WP_User $user user object
* @return boolean passed limit true|false
*/
protected function IsPastLoginFailureLimit($ip, $site_id, $user)
{
$get_fn = $this->IsMultisite() ? 'get_site_transient' : 'get_transient';
if ($user) {
$dataKnown = $get_fn(self::TRANSIENT_FAILEDLOGINS);
return ($dataKnown !== false) && isset($dataKnown[$site_id.":".$user->ID.":".$ip]) && ($dataKnown[$site_id.":".$user->ID.":".$ip] > $this->GetLoginFailureLogLimit());
} else {
$dataUnknown = $get_fn(self::TRANSIENT_FAILEDLOGINS_UNKNOWN);
return ($dataUnknown !== false) && isset($dataUnknown[$site_id.":".$ip]) && ($dataUnknown[$site_id.":".$ip] > $this->GetLoginFailureLogLimit());
}
}
/**
* Increment failure limit.
* @param string $ip IP address
* @param integer $site_id blog ID
* @param WP_User $user user object
*/
protected function IncrementLoginFailure($ip, $site_id, $user)
{
$get_fn = $this->IsMultisite() ? 'get_site_transient' : 'get_transient';
$set_fn = $this->IsMultisite() ? 'set_site_transient' : 'set_transient';
if ($user) {
$dataKnown = $get_fn(self::TRANSIENT_FAILEDLOGINS);
if (!$dataKnown) {
$dataKnown = array();
}
if (!isset($dataKnown[$site_id.":".$user->ID.":".$ip])) {
$dataKnown[$site_id.":".$user->ID.":".$ip] = 1;
}
$dataKnown[$site_id.":".$user->ID.":".$ip]++;
$set_fn(self::TRANSIENT_FAILEDLOGINS, $dataKnown, $this->GetLoginFailureExpiration());
} else {
$dataUnknown = $get_fn(self::TRANSIENT_FAILEDLOGINS_UNKNOWN);
if (!$dataUnknown) {
$dataUnknown = array();
}
if (!isset($dataUnknown[$site_id.":".$ip])) {
$dataUnknown[$site_id.":".$ip] = 1;
}
$dataUnknown[$site_id.":".$ip]++;
$set_fn(self::TRANSIENT_FAILEDLOGINS_UNKNOWN, $dataUnknown, $this->GetLoginFailureExpiration());
}
}
/**
* Event Login failure.
* @param string $username username
*/
public function EventLoginFailure($username)
{
list($y, $m, $d) = explode('-', date('Y-m-d'));
$ip = $this->plugin->settings->GetMainClientIP();
$username = array_key_exists('log', $_POST) ? $_POST["log"] : $username;
$newAlertCode = 1003;
$user = get_user_by('login', $username);
$site_id = (function_exists('get_current_blog_id') ? get_current_blog_id() : 0);
if ($user) {
$newAlertCode = 1002;
$userRoles = $this->plugin->settings->GetCurrentUserRoles($user->roles);
if ($this->plugin->settings->IsLoginSuperAdmin($username)) {
$userRoles[] = 'superadmin';
}
}
// Check if the alert is disabled from the "Enable/Disable Alerts" section
if (!$this->plugin->alerts->IsEnabled($newAlertCode)) {
return;
}
if ($this->IsPastLoginFailureLimit($ip, $site_id, $user)) {
return;
}
$objOcc = new WSAL_Models_Occurrence();
if ($newAlertCode == 1002) {
if (!$this->plugin->alerts->CheckEnableUserRoles($username, $userRoles)) {
return;
}
$occ = $objOcc->CheckKnownUsers(
array(
$ip,
$username,
1002,
$site_id,
mktime(0, 0, 0, $m, $d, $y),
mktime(0, 0, 0, $m, $d + 1, $y) - 1
)
);
$occ = count($occ) ? $occ[0] : null;
if (!empty($occ)) {
// update existing record exists user
$this->IncrementLoginFailure($ip, $site_id, $user);
$new = $occ->GetMetaValue('Attempts', 0) + 1;
if ($new > $this->GetLoginFailureLogLimit()) {
$new = $this->GetLoginFailureLogLimit() . '+';
}
$occ->UpdateMetaValue('Attempts', $new);
$occ->UpdateMetaValue('Username', $username);
//$occ->SetMetaValue('CurrentUserRoles', $userRoles);
$occ->created_on = null;
$occ->Save();
} else {
// create a new record exists user
$this->plugin->alerts->Trigger($newAlertCode, array(
'Attempts' => 1,
'Username' => $username,
'CurrentUserRoles' => $userRoles
));
}
} else {
$occUnknown = $objOcc->CheckUnKnownUsers(
array(
$ip,
1003,
$site_id,
mktime(0, 0, 0, $m, $d, $y),
mktime(0, 0, 0, $m, $d + 1, $y) - 1
)
);
$occUnknown = count($occUnknown) ? $occUnknown[0] : null;
if (!empty($occUnknown)) {
// update existing record not exists user
$this->IncrementLoginFailure($ip, $site_id, false);
$new = $occUnknown->GetMetaValue('Attempts', 0) + 1;
if ($new > $this->GetLoginFailureLogLimit()) {
$new = $this->GetLoginFailureLogLimit() . '+';
}
$occUnknown->UpdateMetaValue('Attempts', $new);
$occUnknown->created_on = null;
$occUnknown->Save();
} else {
// create a new record not exists user
$this->plugin->alerts->Trigger($newAlertCode, array('Attempts' => 1));
}
}
}
/**
* Event changed password.
* @param WP_User $user user object
*/
public function EventPasswordReset($user, $new_pass)
{
if (!empty($user)) {
$userRoles = $this->plugin->settings->GetCurrentUserRoles($user->roles);
$this->plugin->alerts->Trigger(4003, array(
'Username' => $user->user_login,
'CurrentUserRoles' => $userRoles
), true);
}
}
/**
* Event login blocked.
* @param string $username username
*/
public function EventLoginBlocked($username)
{
$user = get_user_by('login', $username);
$userRoles = $this->plugin->settings->GetCurrentUserRoles($user->roles);
if ($this->plugin->settings->IsLoginSuperAdmin($username)) {
$userRoles[] = 'superadmin';
}
$this->plugin->alerts->Trigger(1004, array(
'Username' => $username,
'CurrentUserRoles' => $userRoles
), true);
}
}
|
php
| 21 | 0.506804 | 178 | 33.656028 | 282 |
starcoderdata
|
#!/usr/bin/env python
# encoding: utf-8
"""
vcf_parser
Command Line Interface for vcf_parser
Created by on 2014-12-12.
Copyright (c) 2014 __MoonsoInc__. All rights reserved.
"""
from __future__ import print_function
import sys
import os
import click
from pprint import pprint as pp
from datetime import datetime
from codecs import open
from vcf_adjunct_parser import __version__, VCFAdjunctParser
def print_version(ctx, param, value):
"""Callback function for printing version and exiting
Args:
ctx (object) : Current context
param (object) : Click parameter(s)
value (boolean) : Click parameter was supplied or not
Returns:
None:
"""
if not value or ctx.resilient_parsing:
return
click.echo('vcf_adjunct_parser version: ' + __version__)
ctx.exit()
### This is the main script ###
@click.command()
@click.argument('variant_file',
nargs=1,
type=click.Path(),
metavar=' or -'
)
@click.option('-v', '--vep',
is_flag=True,
help='If variants are annotated with the Variant Effect Predictor.'
)
@click.option('-s', '--split',
is_flag=True,
help='Split the variants with multiallelic calls.'
)
@click.option('-o', '--outfile',
type=click.Path(exists=False),
help='Path to a outfile.'
)
@click.option('-a',"--allele_symbol",
default='0',
help="The symbol that should be used when representing "\
"unobserved alleles. Default is '0'"
)
@click.option('-v', '--verbose',
is_flag=True,
help='Increase output verbosity.'
)
@click.option('-i', '--check_info',
is_flag=True,
help='Skip to check if info fields are correct for all variants.'
)
@click.option('--silent',
is_flag=True,
help='Do not print vcf data.'
)
@click.option('--version',
is_flag=True,
callback=print_version,
expose_value=False,
is_eager=True
)
@click.option('-l', '--logfile',
type=click.Path(exists=False),
help="Path to log file. If none logging is "\
"printed to stderr."
)
@click.option('--loglevel',
type=click.Choice(['DEBUG', 'INFO', 'WARNING', 'ERROR',
'CRITICAL']),
help="Set the level of log output."
)
def cli(variant_file, vep, split, outfile, verbose, silent, check_info,
allele_symbol, logfile, loglevel):
"""
Tool for parsing vcf files.
Prints the vcf file to output.
If --split/-s is used all multiallelic calls will be splitted and printed
as single variant calls.
For more information, please see github.com/moonso/vcf_parser.
"""
from vcf_adjunct_parser import logger, init_log
if not loglevel:
if verbose:
loglevel = 'INFO'
init_log(logger, logfile, loglevel)
nr_of_variants = 0
start = datetime.now()
# with open(variant_file, 'r', encoding="utf-8") as f:
# for line in f:
# if not line.startswith('#'):
# nr_of_variants += 1
if variant_file == '-':
logger.info("Start parsing variants from stdin")
my_parser = VCFParser(
fsock=sys.stdin,
split_variants=split,
check_info=check_info,
allele_symbol=allele_symbol
)
else:
logger.info("Start parsing variants from file {0}".format(variant_file))
my_parser = VCFParser(
infile = variant_file,
split_variants=split,
check_info=check_info,
allele_symbol=allele_symbol
)
if outfile:
f = open(outfile, 'w', encoding='utf-8')
logger.info("Printing vcf to file {0}".format(outfile))
if not silent:
logger.info("Printing vcf to stdout")
else:
logger.info("Skip printing since silent is active")
for line in my_parser.metadata.print_header():
if outfile:
f.write(line+'\n')
else:
if not silent:
print(line)
try:
for variant in my_parser:
variant_line = '\t'.join([variant[head] for head in my_parser.header])
if outfile:
f.write(variant_line + '\n')
else:
if not silent:
print(variant_line)
nr_of_variants += 1
except SyntaxError as e:
print(e)
logger.info('Number of variants: {0}'.format(nr_of_variants))
logger.info('Time to parse file: {0}'.format(str(datetime.now() - start)))
# print('Number of variants: {0}'.format(nr_of_variants))
# print('Time to parse file: {0}'.format(str(datetime.now() - start)))
if __name__ == '__main__':
cli()
|
python
| 16 | 0.552366 | 87 | 29.329412 | 170 |
starcoderdata
|
public void LoadFromModel(List<EditableVoxelList> allParts, VoxelModelPart part)
{
//No support for undo.
_voxelData.Clear();
foreach (var d in part.VoxelList)
{
_voxelData.AddAndGetRef(d.X, d.Y, d.Z) = d.Color;
}
UpdateAll();
_basePoint = part.BasePoint;
_translation = part.Translation;
_bondName = part.BoneName;
_parent = part.ParentId == -1 ? null : allParts[part.ParentId];
}
|
c#
| 13 | 0.523452 | 80 | 37.142857 | 14 |
inline
|
function getURLTeleversements(){
let location = window.location.href;
location = location.replace("http://","");
//http://424w.cgodin.qc.ca/papersensation/michael/module-admin?controller=EditArborescence&action=EditArborescence
let tabSplit = location.split("/");
tabSplit.pop();
tabSplit[tabSplit.length-1] = tabSplit[tabSplit.length-1].replace("//","/");
tabSplit.push("televersements");
location = tabSplit.join("/")+"/";
console.log(location);
return "http://"+location;
}
$scope.docTitreLien = {
href: (getURLTeleversements()+"{{doc.hyperLien}}"),
};
configPost(Object);
configCouleurs();
$scope.state = 0;
function ConfirmerSuppressionBD() {
$_postObj.tabObjToPost = [];
$scope.model.forEach((x) => {
if (x.toDelete !== true) {
x.modelState = 3;
}
$_postObj.tabObjToPost.push(x);
});
postChanges('DocumentBD', "module-admin.php?controller=EditArborescence&action=ConfirmerSuppressionBD", null, false, afficherVerdictState, false);
}
function afficherVerdictState() {
$scope.state = 1;
let trParent = document.getElementById("tr_parent");
let thEtat = document.getElementById("thEtat");
//Remove Checkbox column
trParent.querySelector(".colSupprCB").remove();
console.log(trParent);
//Change col heading
thEtat.innerHTML = "Verdict";
//Add verdict column
trParent.innerHTML += "
//remove other btns
document.getElementById("btnEnregistrer").remove();
document.getElementById("btnSupprimer").remove();
//Show btnNettoyage
document.getElementById("btnNettoyage").removeAttribute("style");
}
function getNearestElementByQuery(element, tagName) {
//da wae
let workingElement;
let compteur = 0;
do {
compteur++;
workingElement = element.parentElement;
if (compteur > 256) {
break;
return -1;
}
} while (workingElement.tagName.toLowerCase() !== tagName.toLowerCase());
return workingElement;
}
function ConfirmerSuppressionFichiers() {
let lien = "?controller=EditArborescence&action=ConfirmerSuppressionFichiers";
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState === XMLHttpRequest.DONE)
finalState(xhttp);
};
xhttp.open("GET", lien, true);
xhttp.send();
}
function finalState(xhttp) {
$scope.model = JSON.parse(xhttp.responseText);
let trTH = document.getElementById("trTH");
let trParent = document.getElementById("tr_parent");
let fluxTRTH = "";
fluxTRTH += "<th scope=\"col\">#
fluxTRTH += "<th scope=\"col\">Nom du fichier
fluxTRTH += "<th scope=\"col\">Verdict
trTH.innerHTML = fluxTRTH;
let fluxTR_PARENT = "";
fluxTR_PARENT += "<td index-offset='1'>{{_index}}
fluxTR_PARENT += "
fluxTR_PARENT += "
trParent.innerHTML = fluxTR_PARENT;
$_anguleuxInterne.updateAgFor(document.getElementById("tr_parent"));
document.getElementById("btnNettoyage").remove();
}
|
javascript
| 13 | 0.647317 | 150 | 26.247863 | 117 |
starcoderdata
|
// Copyright (c) All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace TestProject;
public class ReplacePartitionTests
{
[Fact(Skip = "For manual testing.")]
public void ReplaceImageStub()
{
ReplacePartitionTask task = new();
TestInteraction interaction = new(
new ResponseConsoleService
{
NextReadLine = "yes"
},
"rp", @"\\?\PhysicalDrive11", @"T:\ide\untitled(1.9 GB Apple_HFS)", "i:4");
task.Execute(interaction);
}
[Fact]
public void NoTargetReturnsError()
{
ReplacePartitionTask task = new();
TestInteraction interaction = new("replacepartition");
ExitCode exitCode = task.Execute(interaction);
exitCode.Should().Be(ExitCode.InvalidArgument);
interaction.Logger.ToString().Should().StartWith("Error: This command requires a target.");
}
[Fact]
public void NoSourceReturnsError()
{
ReplacePartitionTask task = new();
TestInteraction interaction = new("replacepartition", "foo");
ExitCode exitCode = task.Execute(interaction);
exitCode.Should().Be(ExitCode.InvalidArgument);
interaction.Logger.ToString().Should().StartWith("Error: Need a target image and a source partition file.");
}
}
|
c#
| 17 | 0.641685 | 116 | 32.357143 | 42 |
starcoderdata
|
// "Replace with lambda" "true"
class Test {
interface Eff<A, B> {
B f(A a);
}
interface InOut {
A run() throws IOException;
default InOut bind(final Eff<A, InOut f) {
return new In {
@Override
public B run() throws IOException {
return f.f(InOut.this.run()).run();
}
};
}
}
}
|
java
| 18 | 0.519894 | 57 | 18.894737 | 19 |
starcoderdata
|
int main() {
#ifdef _WIN32
WSADATA WSAData;
WSAStartup(0x101, &WSAData);
#else
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
return (1);
#endif
// initialize Pubnub state
Pubnub_overload1("demo", "demo", "", "", false);
printf("UUID:::%s", uuid());
return 0;
}
|
c
| 10 | 0.543974 | 52 | 16.176471 | 17 |
inline
|
const Jimp = require('jimp')
let globalFont
let globalFontSize = {
width: 9, // note: this number determined by trial and error
height: 16
}
Jimp.loadFont(Jimp.FONT_SANS_16_BLACK).then(function (font) {
console.log('font loaded')
globalFont = font
});
class Canvas {
constructor() {
this.transform = { x: 0, y: 0 }
this.fillStyle = 0xFF0000FF
}
init () {
if (this.image) return
if (!this.width || !this.height) return
this.image = new Jimp(this.width, this.height) // TODO: callback here?
}
getX (x) { return this.transform.x + x }
getY (y) { return this.transform.y + y }
getBufferAsPng (callback) {
if (!this.image) this.image = new Jimp(0, 0)
return this.image.getBuffer(Jimp.MIME_PNG, callback)
}
getContext (contextType) {
if (contextType !== '2d') return null
return this // pretend we are our own CanvasRenderingContext2D
}
save () { } // TODO: not needed for my use case
restore () { } // TODO: not needed for my use case
clearRect () { } // TODO: not needed for my use case
fillRect (x, y, width, height) {
this.init()
let rgba = (this.fillStyle === '#000000') ? {
r: 0, g: 0, b: 0, a: 255
} : {
r: 255, g: 255, b: 255, a: 255
}
this.image.scan(this.getX(x), this.getY(y), width, height, function (x, y, idx) {
// x, y is the position of this pixel on the image
// idx is the position start position of this rgba tuple in the bitmap Buffer
// this is the image
this.bitmap.data[ idx + 0 ] = rgba.r
this.bitmap.data[ idx + 1 ] = rgba.g
this.bitmap.data[ idx + 2 ] = rgba.b
this.bitmap.data[ idx + 3 ] = rgba.a
// rgba values run from 0 - 255
// e.g. this.bitmap.data[idx] = 0; // removes red from this pixel
})
}
fillText (text, x, y) {
if (!globalFont) return
this.init()
// this.font 20px
let offset = this.measureText(text).width // this.textAlign == 'right'
if (this.textAlign == 'center') offset = offset/2
if (this.textAlign == 'left') offset = 0
this.image.print(globalFont, this.getX(x - offset), this.getY(y - globalFontSize.height), text)
}
measureText (text) {
return {
width: text.length * globalFontSize.width
}
}
translate (x, y) {
this.transform.x += x
this.transform.y += y
}
}
module.exports = Canvas
|
javascript
| 14 | 0.611111 | 99 | 29.461538 | 78 |
starcoderdata
|
import data.make_stterror_data.utils as utils
import os
import sys
import subprocess
# TTS imports
from gtts import gTTS
import pyttsx3
# sys.path.append("~/PycharmProjects/pyfestival") # https://github.com/techiaith/pyfestival/pull/4
# import festival
__author__ = '
"""
Text-To-Speech Module
"""
class TTS:
def __init__(self, data_dir="", result_dir="", audio_type=".wav"):
print("Initializing TTS Module")
self.audio_type = audio_type
self.project_dir = utils.project_dir_name()
self.data_dir = data_dir
self.result_dir = result_dir
utils.ensure_dir(self.project_dir + self.result_dir)
def set_data_dir(self, data_dir):
self.data_dir = data_dir
def set_result_dir(self, result_dir):
self.result_dir = result_dir
def read_text(self, text, sentence_id, tts_type="gtts"):
if "macsay" in tts_type: # Mac
self.audio_from_mac_say(text, sentence_id)
else: # google gtts
self.audio_from_google(text, sentence_id)
def audio_from_google(self, text, sentence_id):
gtts = gTTS(text=text, lang='en') # , slow=False)
partial_saved_audio_filename = self.project_dir + self.result_dir + "gtts_" + sentence_id
tmp_saved_audio_filename = partial_saved_audio_filename + "_tmp" + self.audio_type
final_saved_audio_filename = partial_saved_audio_filename + self.audio_type
gtts.save(tmp_saved_audio_filename)
# fix_missing_riff_header = "ffmpeg - i "+tmp_saved_audio_filename+" -y "+final_saved_audio_filename
# Making ffmpeg quieter (less verbose): ffmpeg -nostats -loglevel 0 -i 2.mp3 ~/PycharmProjects/STTError/assets/2.mp3
subprocess.call(
["ffmpeg", "-nostats", "-loglevel", "0", "-i", tmp_saved_audio_filename, "-y", final_saved_audio_filename])
# os.system("ffmpeg -nostats -loglevel 0 -i {} -y {}".format(tmp_saved_audio_filename, final_saved_audio_filename))
# Remove tmp_saved_audio_filename
subprocess.call(["rm", tmp_saved_audio_filename])
return final_saved_audio_filename
def audio_from_mac_say(self, text, sentence_id):
""" Mac's say command: Mac Systems
"""
for voice in ['Fred']: # ['Alex', 'Fred', 'Victoria']
partial_saved_audio_filename = self.project_dir + self.result_dir + "macsay_" + sentence_id
tmp_saved_audio_filename = partial_saved_audio_filename + "_tmp.aiff"
final_saved_audio_filename = partial_saved_audio_filename + self.audio_type
subprocess.call(["say", "-o", tmp_saved_audio_filename, "-v", voice, text])
subprocess.call(["ffmpeg", "-nostats", "-loglevel", "0", "-i", tmp_saved_audio_filename, "-y",
final_saved_audio_filename])
# os.system("say -o {} -v {} {}".format(tmp_saved_audio_filename, voice, text))
# os.system("ffmpeg -nostats -loglevel 0 -i {} -y {}".format(tmp_saved_audio_filename, final_saved_audio_filename))
# Remove tmp_saved_audio_filename
subprocess.call(["rm", tmp_saved_audio_filename])
return final_saved_audio_filename
|
python
| 13 | 0.626016 | 127 | 42.216216 | 74 |
starcoderdata
|
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 28 02:28:25 2021
@author: suhar
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
dataset = pd.read_csv('dataset_syn.csv')
test_dataset = pd.read_csv('test_dataset_syn.csv')
print(dataset.corr())
print(test_dataset.corr())
dlen = len(dataset)
serit1 = dataset.iloc[:, 0]
serit2 = dataset.iloc[:, 1]
serit3 = dataset.iloc[:, 2]
seritno = dataset.iloc[:, 3]
test_dlen = len(dataset)
test_serit1 = test_dataset.iloc[:, 0]
test_serit2 = test_dataset.iloc[:, 1]
test_serit3 = test_dataset.iloc[:, 2]
test_seritno = test_dataset.iloc[:, 3]
plt.plot(dataset)
plt.show()
plt.plot(test_dataset)
plt.show()
trainx_data = pd.DataFrame(pd.concat([serit1,serit2,serit3], axis=1))
trainy_data = pd.DataFrame(seritno)
testx_data = pd.DataFrame(pd.concat([test_serit1,test_serit2,test_serit3], axis=1))
testy_data = pd.DataFrame(test_seritno)
trainx_data.to_csv('xtr.csv', index = False)
trainy_data.to_csv('ytr.csv', index = False)
testx_data.to_csv('xte.csv', index = False)
testy_data.to_csv('yte.csv', index = False)
|
python
| 8 | 0.713328 | 106 | 25.533333 | 45 |
starcoderdata
|
#pragma once
#include
#include
#include
#include
#include
namespace lava {
/**
* Windowing system event.
*/
struct WsEvent {
public:
struct WindowSizeData {
uint16_t width;
uint16_t height;
};
struct MouseButtonData {
int16_t x;
int16_t y;
MouseButton which;
};
struct MouseMoveData {
int16_t x;
int16_t y;
int16_t dx;
int16_t dy;
};
struct MouseWheelData {
int16_t x;
int16_t y;
MouseWheel which;
// Standard delta is 1.f, but hight precision mice (ou touchpads)
// might be non-integers.
float delta;
};
struct KeyData {
Key which;
};
struct TextData {
uint32_t codepoint; // Unicode codepoint
};
// -----
WsEventType type;
union {
WindowSizeData windowSize;
MouseButtonData mouseButton;
MouseMoveData mouseMove;
MouseWheelData mouseWheel;
KeyData key;
TextData text;
};
};
}
|
c++
| 9 | 0.493263 | 77 | 19.875 | 64 |
starcoderdata
|
"""
suppressing-dephasing-real-time.py: suppressing dephasing using real-time Hamiltonian estimation
Author: - Quantum Machines
Created: 02/02/2021
Created on QUA version: 0.8.439
"""
from qm.QuantumMachinesManager import QuantumMachinesManager
from qm.qua import *
from qm import SimulationConfig
import numpy as np
import matplotlib.pyplot as plt
import time
from configuration import *
qmManager = QuantumMachinesManager()
QM = qmManager.open_qm(
config
) # Generate a Quantum Machine based on the configuration described above
N = 3 # 120
t_samp = 12 // 4
th = 0
fB_min = 50
fB_max = 70
Nf = 2 # 256
N_avg = 2
fB_vec = np.linspace(fB_min, fB_max, Nf)
dfB = np.diff(fB_vec)[0]
alpha = 0.25
beta = 0.67
elements = ["DET", "D1", "D2", "RF-QPC", "DET_RF"]
def prep_stage():
play("prep", "D1")
play("prep", "D2")
play("ramp_down_evolve", "D1")
play("ramp_up_evolve", "D2")
def readout_stage():
play("ramp_up_read", "D1")
play("ramp_down_read", "D2")
wait(t_samp * k + prep_len // 4 + 2 * ramp_len // 4, "RF-QPC")
play("readout", "D1")
play("readout", "D2")
measure("measure", "RF-QPC", None, demod.full("integW1", I))
with program() as dephasingProg:
N_avg = declare(int)
k = declare(int)
I = declare(fixed)
fB = declare(fixed)
state = declare(bool, size=N)
state_str = declare_stream()
rabi_state = declare(bool)
rabi_state_str = declare_stream()
ind1 = declare(int, value=0)
Pf = declare(fixed, value=[1 / len(fB_vec)] * int(len(fB_vec)))
rk = declare(fixed)
C = declare(fixed)
norm = declare(fixed)
#########################
# Feedback and Estimate #
#########################
update_frequency("DET", 0)
with for_(k, 2, k <= N, k + 1):
play("prep", "D1")
play("prep", "D2")
play("evolve", "D1", duration=t_samp * k)
play("evolve", "D2", duration=t_samp * k)
play("readout", "D1")
play("readout", "D2")
wait(t_samp * k + prep_len // 4, "RF-QPC")
measure("measure", "RF-QPC", None, demod.full("integW1", I))
assign(state[k - 1], I > 0)
save(state[k - 1], state_str)
assign(rk, Cast.to_fixed(state[k - 1]) - 0.5)
assign(ind1, 0)
with for_(fB, fB_min, fB < fB_max, fB + dfB):
assign(C, Math.cos2pi(Cast.mul_fixed_by_int(fB, t_samp * k)))
assign(Pf[ind1], (0.5 + rk * (alpha + beta * C)) * Pf[ind1])
assign(ind1, ind1 + 1)
assign(norm, 1 / Math.sum(Pf))
with for_(ind1, 0, ind1 < Pf.length(), ind1 + 1):
assign(Pf[ind1], Pf[ind1] * norm)
update_frequency("D1_RF", 1e6 * (fB_min + dfB * Math.argmax(Pf)))
update_frequency("D2_RF", 1e6 * (fB_min + dfB * Math.argmax(Pf)))
#########
# Operate#
#########
with for_(k, 2, k <= N, k + 1):
prep_stage()
wait(prep_len // 4 + ramp_len // 4, "D1_RF")
wait(prep_len // 4 + ramp_len // 4, "D2_RF")
play("const" * amp(0.05), "D1_RF", duration=t_samp * k)
play("const" * amp(0.05), "D2_RF", duration=t_samp * k)
play("evolve", "D1", duration=t_samp * k)
play("evolve", "D2", duration=t_samp * k)
readout_stage()
assign(rabi_state, I > 0)
save(rabi_state, rabi_state_str)
with stream_processing():
state_str.save_all("state_str")
rabi_state_str.save_all("rabi_state_str")
job = qmManager.simulate(config, dephasingProg, SimulationConfig(int(5000)))
# res = job.result_handles
# states = res.state_str.fetch_all()['value']
samples = job.get_simulated_samples()
samples.con1.plot()
plt.figure()
# G1=samples.con1.analog['1'][270:550]
# G2=samples.con1.analog['2'][270:550]
G1 = samples.con1.analog["1"][1050:1300]
G2 = samples.con1.analog["2"][1050:1300]
ax1 = plt.subplot(311)
plt.plot(G1)
plt.setp(ax1.get_xticklabels(), visible=False)
plt.ylabel("G1[V]")
plt.yticks(np.linspace(-0.1, 0.2, 5))
plt.grid()
ax2 = plt.subplot(312, sharex=ax1)
plt.plot(G2)
plt.xlabel("time [ns]")
plt.ylabel("G2[V]")
plt.setp(ax2.get_xticklabels(), visible=False)
plt.yticks(np.linspace(-0.2, 0.1, 5))
plt.grid()
ax3 = plt.subplot(313, sharex=ax1)
plt.plot(G1 - G2)
plt.xlabel("time [ns]")
plt.ylabel("$\epsilon [V]$")
plt.ylim([-0.3, 0.6])
plt.yticks(np.linspace(-0.1, 0.5, 5))
plt.text(40, 0.2, "Preparation stage")
plt.text(170, 0.2, "Readout stage")
plt.grid()
plt.show()
|
python
| 17 | 0.591751 | 104 | 28.251613 | 155 |
starcoderdata
|
package aie.sss.models;
public class ExamSubject extends Subject {
private String date,startTime,endTime,day;
public ExamSubject(String name, String doctorName ,String date, String startTime, String endTime, String day) {
super(name, "",doctorName,0);
this.date = date;
this.startTime = startTime;
this.endTime = endTime;
this.day = day;
}
public String getDate() {
return date;
}
public String getStartTime() {
return startTime;
}
public String getEndTime() {
return endTime;
}
public String getDay() {
return day;
}
}
|
java
| 8 | 0.625369 | 116 | 21.6 | 30 |
starcoderdata
|
//Chapter4 - Project 4.1
import java.util.Scanner;
public class TriangleTester
{
public static void main (String[] args)
{
Triangle calc = new Triangle();
Scanner in = new Scanner (System.in);
System.out.println ("\n" +"===================================================================" + "\n");
System.out.println ("Please enter your first corner point coordinates for triangle");
double x1 = in.nextDouble();
double y1 = in.nextDouble();
System.out.println ("Please enter your second corner point coordinates for triangle");
double x2 = in.nextDouble();
double y2 = in.nextDouble();
System.out.println ("Please enter your third corner point coordinates for triangle");
double x3 = in.nextDouble();
double y3 = in.nextDouble();
calc.getFirstCorner(x1,y1);
calc.getSecondCorner(x2,y2);
calc.getThirdCorner(x3,y3);
System.out.println ("\n" +"===================================================================" + "\n");
System.out.println ("The first triangle side length is : " + calc.getFirstLength());
System.out.println ("The second triangle side length is : " + calc.getSecondLength());
System.out.println ("The third triangle side length is : " + calc.getThirdLength());
calc.getLargestLength();
System.out.println ("\n" +"===================================================================" + "\n");
System.out.println ("The first largest triangle angle is : " + calc.getFirstLargestAngle());
System.out.println ("The second largest triangle angle is : " + calc.getSecondLargestAngle());
System.out.println ("The third largest triangle angle is : " + calc.getThirdLargestAngle());
System.out.println ("\n" +"===================================================================" + "\n");
System.out.println ("The triangle perimeter is : " + calc.getPerimeter());
System.out.println ("\n" +"===================================================================" + "\n");
System.out.println ("The triangle area is : " + calc.getArea());
}
}
|
java
| 11 | 0.574724 | 105 | 42.369565 | 46 |
starcoderdata
|
<!DOCTYPE html>
<html lang="de">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<?php
//list of all pages except index.php
$pages = [
['name' => 'search', 'linktext' => 'Suche', 'place' => 'header'],
['name' => 'guidance', 'linktext' => 'Anleitung', 'place' => 'header'],
['name' => 'background','linktext' => 'Hintergrund', 'place' => 'header'],
['name' => 'blog', 'linktext' => 'Blog', 'place' => 'header'],
['name' => 'login', 'linktext' => 'Konto', 'place' => 'header'],
['name' => 'contact', 'linktext' => 'Kontaktformular', 'place' => 'footer'],
['name' => 'impressum', 'linktext' => 'Impressum', 'place' => 'footer'],
['name' => 'data', 'linktext' => 'Daten', 'place' => 'nowhere'],
];
$title = "Startseite - DBS-VIS";
foreach ($pages as $index => $page) {
$listitem = "<li";
if ($_SERVER["SCRIPT_NAME"] == "/dbs-vis/" . $page["name"] . ".php") {
$listitem .= " aria-current='page'><a id='current-page'>";
$title = $page["linktext"] . " - DBS-VIS";
} else {
$listitem .= "><a href='" . $page["name"] . ".php'>";
};
$listitem .= $page["linktext"] . "
$pages[$index]["listitem"] = $listitem;
};
echo $title;
?>
<link rel="stylesheet" href="./stylesheet.css">
<link rel="icon" type="image/svg+xml" href="./graphics/logo.svg" sizes="any">
<div id="headline">
<a href="./index.php" class="head">
<img id="logo" alt="" src="./graphics/logo.svg">
<?php
foreach ($pages as $page) {
if ($page["place"] == "header") {
echo $page["listitem"];
};
};
?>
|
php
| 12 | 0.505741 | 80 | 30.551724 | 58 |
starcoderdata
|
<?php
namespace app\index\model;
class Goods extends Base{
// protected function base($query){
// $query->where('company_id', session('power_user.company_id'));
// }
public function company(){
return $this->hasOne('Company', 'id', 'company_id');
}
// public function supply(){
// return $this->hasOne('Supply', 'id', 'supply_id');
// }
public function cate(){
return $this->hasOne('Cate', 'id', 'cate_id')->bind(['cate_name' => 'name']);
}
public function unit(){
return $this->hasOne('Unit', 'id', 'unit_id')->bind(['unit_name' => 'name',]);
}
}
|
php
| 12 | 0.563636 | 86 | 23.481481 | 27 |
starcoderdata
|
package com.library.bean.EntityQq;
public class UrlUtil
{
public static String urlZh = "http://zhuanlan.zhihu.com/dingxiangyisheng";
public String urlZhAdd = "http://zhuanlan.zhihu.com/api/columns/dingxiangyisheng/posts?limit=10&offset=40";
}
|
java
| 6 | 0.789298 | 108 | 36.375 | 8 |
starcoderdata
|
@Test
public void testUnlinkFile() throws CatalogException, IOException {
URI uri = Paths.get(getStudyURI()).resolve("data").toUri();
link(uri, "myDirectory", Long.toString(studyId), new ObjectMap("parents", true), sessionIdUser);
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_ID.key(), studyId)
.append(FileDBAdaptor.QueryParams.PATH.key(), "~myDirectory/*")
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), File.FileStatus.READY);
QueryResult<File> fileQueryResultLinked = catalogManager.getFileManager().get(studyId, query, null, sessionIdUser);
System.out.println("Number of files/folders linked = " + fileQueryResultLinked.getNumResults());
// Now we try to unlink the file
catalogManager.getFileManager().unlink("myDirectory/data/test/folder/test_0.5K.txt", Long.toString(studyId), sessionIdUser);
fileQueryResultLinked = catalogManager.getFileManager().get(35L, QueryOptions.empty(), sessionIdUser);
assertEquals(1, fileQueryResultLinked.getNumResults());
assertTrue(fileQueryResultLinked.first().getPath().contains(".REMOVED"));
assertEquals(fileQueryResultLinked.first().getPath().indexOf(".REMOVED"),
fileQueryResultLinked.first().getPath().lastIndexOf(".REMOVED"));
// We send the unlink command again
catalogManager.getFileManager().unlink("35", Long.toString(studyId), sessionIdUser);
fileQueryResultLinked = catalogManager.getFileManager().get(35L, QueryOptions.empty(), sessionIdUser);
// We check REMOVED is only contained once in the path
assertEquals(fileQueryResultLinked.first().getPath().indexOf(".REMOVED"),
fileQueryResultLinked.first().getPath().lastIndexOf(".REMOVED"));
}
|
java
| 12 | 0.694188 | 132 | 64.785714 | 28 |
inline
|
#!/usr/bin/env python3
"""HackerNews API client library."""
import argparse
import asyncio
import logging
import aiohttp
import async_timeout
FETCH_TIMEOUT = 1000
ITEM_URL = 'https://hacker-news.firebaseio.com/v0/item/{}.json'
LOGGER = logging.getLogger()
USER_URL = 'https://hacker-news.firebaseio.com/v0/user/{}.json'
async def async_fetch_url(url, session):
"""Download JSON from the url."""
with async_timeout.timeout(FETCH_TIMEOUT):
async with session.get(url) as response:
return await response.json()
async def async_fetch_urls(urls, session, recursive=0):
"""Download (asynchronously) JSON from the urls.
Params:
urls : list[string] : list of urls to be fetched
recursive : int : if positive, dig down to 'recursive' level of 'kids'
Returns:
list[dict] : list of dicts with HN posts in question
"""
LOGGER.debug('fetching %s urls with recursive=%s', len(urls), recursive)
tasks = [asyncio.ensure_future(async_fetch_url(url, session))
for url in urls]
items = await asyncio.gather(*tasks)
if recursive > 0:
new_items = []
for i, item in enumerate(items):
if item:
kids = item.get('kids') or item.get('submitted') or []
urls = [ITEM_URL.format(kid) for kid in kids]
if urls:
LOGGER.debug('[%d/%d/%d] adding %s urls to the queue',
i+1,
len(items),
len(items)+len(new_items),
len(urls))
new_items += await async_fetch_urls(
urls, session, recursive=recursive-1)
items += new_items
return items
def fetch_urls(urls, recursive=0):
"""Download (asynchronously) JSON from the urls.
Params:
urls : list[string] : list of urls to be fetched
recursive : int : if positive, dig down to 'recursive' level of 'kids'
Returns:
list[dict] : list of dicts with HN posts in question
"""
LOGGER.debug('fetching %s urls with recursive=%s', len(urls), recursive)
loop = asyncio.get_event_loop()
items = []
with aiohttp.ClientSession(loop=loop) as session:
items = loop.run_until_complete(
async_fetch_urls(urls, session, recursive=recursive)
)
loop.close()
return items
def get_user_items(username, recursive=0):
"""Return all user's items.
Params:
username : string : e.g. 'whoishiring'
Return:
list[dict] : list of user's posts
"""
LOGGER.debug('fetching posts of %s', username)
url = USER_URL.format(username)
return fetch_urls([url], recursive=recursive)
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='[%H:%M:%S]')
parser = argparse.ArgumentParser(description='Fetch HN posts.')
parser.add_argument('--author',
type=str,
help='Name of posts author')
parser.add_argument('--recursive',
type=int,
default=0,
help='Recursion level (default 0)')
parser.add_argument('--verbose',
action='store_true',
help='Detailed output')
args = parser.parse_args()
if args.verbose:
LOGGER.setLevel(logging.DEBUG)
if args.author:
data = get_user_items(args.author, args.recursive)
print('fetched {} posts'.format(len(data)))
|
python
| 18 | 0.574646 | 79 | 32.616822 | 107 |
starcoderdata
|
package com.yr.net.app.customer.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yr.net.app.common.exception.AppException;
import com.yr.net.app.customer.dto.*;
import com.yr.net.app.customer.entity.UserMultimedia;
import com.baomidou.mybatisplus.extension.service.IService;
import com.yr.net.app.moments.bo.CommentMultiQueryBo;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.List;
/**
* @author dengbp
*/
public interface IUserMultimediaService extends IService {
String FILE_TYPE = "3gp,avi,mp4,flv,kux,mpeg";
/**
* Description 用户多媒体
* @param file
* @param relationId 关联源文件id,视频封面使用
* @throws AppException
* @return MultipartFileRespDto
* @Author dengbp
* @Date 00:42 2020-11-25
**/
MultipartFileRespDto saveFile(MultipartFile file,String relationId)throws AppException;
/**
* Description 用户多媒体信息
* @param ids 多媒体id,多个逗号分开
* @param using 用处:0个人资料里的相册(或视频),1个人动态
* @param mulType 多媒体类型 0:图片;1:视频
* @param isFree 是否收费 0:免费:1收费
* @param price
* @param coordinate
* @param showWord 我的秀言
* @throws AppException
* @return void
* @Author dengbp
* @Date 00:42 2020-11-25
**/
void updateMulInfo(String ids,Integer using, int mulType, int isFree, String price, CoordinateRequestDto coordinate,String showWord)throws AppException;
/**
* Description 视频列表
* @param requestDto requestDto
* @throws AppException
* @return com.baomidou.mybatisplus.core.metadata.IPage
* @Author dengbp
* @Date 18:28 2020-12-04
**/
List videoList(VideoRequestDto requestDto)throws AppException;
/**
* Description 个人相册
* @param requestDto requestDto
* @throws AppException
* @return com.baomidou.mybatisplus.core.metadata.IPage
* @Author dengbp
* @Date 18:28 2020-12-04
**/
List getAlbum(AlbumRequestDto requestDto)throws AppException;
/**
* Description 根据多媒体删除用户媒体
* @param ids 多媒体id
* @return void
* @throws AppException
* @Author dengbp
* @Date 10:15 PM 1/22/21
**/
void albumDel(List ids)throws AppException;
/**
* Description 获取用户相片数量
* @param userId
* @throws AppException
* @return java.lang.Integer
* @Author dengbp
* @Date 12:55 AM 1/17/21
**/
Integer getAlbumCount(String userId)throws AppException;
/**
* Description 动态主题或评论查找多媒体信息
* @param commentMultiQueryBo
* @param type 多媒体使用场景类型 0:主题;1:评论内容
* @throws AppException
* @return java.util.List
* @Author dengbp
* @Date 13:28 2020-12-18
**/
List findByComment(CommentMultiQueryBo commentMultiQueryBo,Integer type)throws AppException;
}
|
java
| 8 | 0.689987 | 156 | 27.186916 | 107 |
starcoderdata
|
<?php
namespace App\Http\Controllers;
use App\MessageResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Auth;
use App\Message;
class MessageResponsesController extends Controller
{
// TODO
// protected $fillable = ['message_id', 'responder_id', 'body'];
public function create($message_id)
{
if(auth()->check()) {
return view('messages/respond', compact('message_id'));
}
}
public function store($id)
{
$this->validate(request(), [
'body' => 'required'
]);
$response = New MessageResponse;
$response->message_id = $id;
$response->responder_id = auth()->id();
$response->body = request('body');
if($response->save()) {
return back()->with('message', 'Tak for dit svar');
// return URL::to('/beskeder/').$id;
}
}
}
|
php
| 15 | 0.565217 | 67 | 20.904762 | 42 |
starcoderdata
|
func ExampleByteBuffer() {
// This request handler sets 'Your-IP' response header
// to 'Your IP is <ip>'. It uses ByteBuffer for constructing response
// header value with zero memory allocations.
yourIPRequestHandler := func(ctx *fasthttp.RequestCtx) {
b := fasthttp.AcquireByteBuffer()
b.B = append(b.B, "Your IP is <"...)
b.B = fasthttp.AppendIPv4(b.B, ctx.RemoteIP())
b.B = append(b.B, ">"...)
ctx.Response.Header.SetBytesV("Your-IP", b.B)
fmt.Fprintf(ctx, "Check response headers - they must contain 'Your-IP: %s'", b.B)
// It is safe to release byte buffer now, since it is
// no longer used.
fasthttp.ReleaseByteBuffer(b)
}
// Start fasthttp server returning your ip in response headers.
fasthttp.ListenAndServe(":8080", yourIPRequestHandler)
}
|
go
| 13 | 0.68375 | 83 | 36.190476 | 21 |
inline
|
<?php
Class Mahasiswa extends Ci_controller
{
function __construct()
{
parent::__construct();
$this->load->model('model_mahasiswa');
}
function index(){
$data['data']=$this->model_mahasiswa->tampilData();
$this->load->view('mahasiswa',$data);
}
function tambah(){
$rows = array('nim'=>$this->input->post('nim'),
'nama'=>$this->input->post('nama'),
'jurusan'=>$this->input->post('jurusan'),
'alamat'=>$this->input->post('alamat')
);
$this->db->insert('mahasiswa',$rows);
redirect (site_url('crud'));
}
}
?>
|
php
| 13 | 0.573427 | 54 | 18.758621 | 29 |
starcoderdata
|
def GaussianNoisePerturbation_Sphere( mu_0, sigma ):
nDimManifold = mu_0.nDim
# Generate a random Gaussians with polar Box-Muller Method
rand_pt = np.zeros( nDimManifold ).tolist()
for i in range( nDimManifold ):
r2 = 0
x = 0
y = 0
while( r2 > 1.0 or r2 == 0 ):
x = ( 2.0 * np.random.rand() - 1.0 )
y = ( 2.0 * np.random.rand() - 1.0 )
r2 = x * x + y * y
gen_rand_no = sigma * y * np.sqrt( -2.0 * np.log( r2 ) / r2 )
rand_pt[ i ] = gen_rand_no
# print( rand_pt )
# Set Random Vector to Tangent Vector - ListToTangent
rand_tVec = manifolds.sphere_tVec( nDimManifold )
rand_tVec.SetTangentVector( rand_pt )
# Projected Tangent to Mean Point
rand_tVec_projected = mu_0.ProjectTangent( mu_0, rand_tVec )
# Perturbed point at time_pt
pt_perturbed = mu_0.ExponentialMap( rand_tVec_projected )
return pt_perturbed
|
python
| 15 | 0.647474 | 63 | 25.625 | 32 |
inline
|
using System;
using System.Net;
namespace Thinktecture.Net
{
/// credentials for password-based authentication schemes such as basic, digest, NTLM, and Kerberos authentication.
public interface INetworkCredential : IAbstraction ICredentials
#if NETSTANDARD1_1 || NETSTANDARD1_3 || NET45 || NET46
, ICredentialsByHost
#endif
{
/// or sets the domain or computer name that verifies the credentials.
/// name of the domain associated with the credentials.
///
/// <IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
///
string Domain { get; set; }
/// or sets the password for the user name associated with the credentials.
/// password associated with the credentials. If this <see cref="T:System.Net.NetworkCredential" /> instance was initialized with the <see name="Password" /> parameter set to null, then the <see cref="P:System.Net.NetworkCredential.Password" /> property will return an empty string.
///
/// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
///
string Password { get; set; }
/// or sets the user name associated with the credentials.
/// user name associated with the credentials.
///
/// <IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
///
string UserName { get; set; }
/// an instance of the <see cref="T:System.Net.NetworkCredential" /> class for the specified Uniform Resource Identifier (URI) and authentication type.
/// <see cref="T:System.Net.NetworkCredential" /> object.
/// <param name="uri">The URI that the client provides authentication for.
/// <param name="authType">The type of authentication requested, as defined in the <see cref="P:System.Net.IAuthenticationModule.AuthenticationType" /> property.
new INetworkCredential GetCredential(Uri uri, string authType);
#if NETSTANDARD1_1 || NETSTANDARD1_3 || NET45 || NET46
/// an instance of the NetworkCredential class for the specified host, port, and authentication type.
/// <param name="host">The host computer that authenticates the client.
/// <param name="port">The port on the host that the client communicates with.
/// <param name="authenticationType">The type of authentication requested, as defined in the IAuthenticationModule.AuthenticationType property.
/// NetworkCredential for the specified host, port, and authentication protocol, or null if there are no credentials available for the specified host, port, and authentication protocol.
new INetworkCredential GetCredential(string host, int port, string authenticationType);
#endif
}
}
|
c#
| 9 | 0.753658 | 307 | 66 | 50 |
starcoderdata
|
import React from "react";
const AppContext = React.createContext({});
AppContext.displayName = "AppData";
export default AppContext;
|
javascript
| 3 | 0.769697 | 43 | 19.625 | 8 |
starcoderdata
|
import React from 'react';
class GrossingApp extends React.Component {
render() {
const model = this.props.model;
return (
<a href={model.link} target="_blank" rel="noreferrer" className="item">
<img className="item-icon" src={model.icon} alt="App Icon" />
<div className="item-detail">
<div className="item-name">
{model.name}
<div className="item-category">
{model.category}
);
}
}
export default GrossingApp;
|
javascript
| 13 | 0.457652 | 83 | 28.26087 | 23 |
starcoderdata
|
Buffer.length = {};
Buffer.name = {};
Buffer.prototype = {};
Buffer.poolSize = {};
Buffer.from = {};
Buffer.alloc = {};
Buffer.allocUnsafe = {};
Buffer.allocUnsafeSlow = {};
Buffer.isBuffer = {};
Buffer.compare = {};
Buffer.isEncoding = {};
Buffer.concat = {};
Buffer.byteLength = {};
|
javascript
| 4 | 0.635088 | 28 | 20.923077 | 13 |
starcoderdata
|
package com.ksyun.media.shortvideo.demo;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.RequestFuture;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.ksyun.media.shortvideo.utils.KS3ClientWrap;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
/**
* get ks3 token on 17/4/13.
*/
public class KS3TokenTask {
private static String TAG = "KS3TokenTask";
public static final String TOKEN_SERVER_URL = "http://ksvs-demo.ks-live.com:8720/api/upload/ks3/sig";
//Get ks3 Token
private static final String TYPE = "type";
private static final String MD5 = "md5";
private static final String VERB = "verb";
private static final String RES = "res";
private static final String HEADERS = "headers";
private static final String DATE = "date";
private RequestQueue mRequestQueue;
private Context mContext;
public KS3TokenTask(Context context) {
mContext = context;
}
/**
* 向APPServer请求token
*
* @param httpMethod
* @param contentType
* @param date
* @param contentMD5
* @param resource
* @param headers
* @return
*/
public KS3ClientWrap.KS3AuthInfo requsetTokenToAppServer(String httpMethod, String contentType, String
date, String
contentMD5, String resource, String headers) {
Log.d(TAG, "requsetTokenToAppServer");
String response = doGetToken(httpMethod, contentType, contentMD5, date, resource, headers);
String token = null;
String serverDate = null;
try {
JSONObject json = new JSONObject(response);
token = json.getString("Authorization");
Log.d(TAG, "token:" + token);
serverDate = json.getString("Date");
} catch (JSONException e) {
e.printStackTrace();
}
return new KS3ClientWrap.KS3AuthInfo(token, serverDate);
}
//Get Image Token
private String doGetToken(String httpMethod, String contentType, String contentMD5, String
date, String resource, String headers) {
Map<String, String> param = new HashMap<>();
param.put(TYPE, contentType);
param.put(MD5, contentMD5);
param.put(VERB, httpMethod);
param.put(RES, resource);
param.put(HEADERS, headers);
param.put(DATE, date);
return doSyncHttpRequest(TOKEN_SERVER_URL, param);
}
private String doSyncHttpRequest(String url, Map<String, String> params) {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(mContext);
}
String response = new String();
RequestFuture future = RequestFuture.newFuture();
StringRequest request = new StringRequest(Request.Method.GET, getFinalUrlWithParams(url,
params, false), future, future);
mRequestQueue.add(request);
try {
response = (String) future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return response;
}
private String getFinalUrlWithParams(String url, Map<String, String> param, boolean paramsOnly) {
String ret = "";
if (param != null && param.size() > 0) {
Uri uri = Uri.parse(url);
Uri.Builder builder = uri.buildUpon();
for (Map.Entry<String, String> entry : param.entrySet()) {
builder.appendQueryParameter(entry.getKey(), entry.getValue());
}
if (paramsOnly)
ret = builder.build().getQuery();
else
ret = builder.build().toString();
}
return ret;
}
}
|
java
| 14 | 0.633168 | 106 | 30.317829 | 129 |
starcoderdata
|
public void mergeQuery(Map<String, ?> context) throws SQLException // CB TODO - synchronizations? concurrent execution vs. merging? Escaping?
{
if (originalQuery == null)
{
synchronized (this)
{
if (originalQuery == null)
{
originalQuery = getQuery();
}
}
}
StringBuilder mergedQuery = new StringBuilder();
Matcher matcher = mergeLexer.matcher(originalQuery);
int pos = 0;
while (matcher.find())
{
if (matcher.start() > pos) mergedQuery.append(originalQuery.substring(pos, matcher.start()));
String reference = matcher.group().substring(1);
String value = Optional.ofNullable(context.get(reference)).map(val -> String.valueOf(val)).orElse(matcher.group());
if (value == null) throw new SQLException("Undefined reference: @" + reference);
mergedQuery.append(value);
pos = matcher.end();
}
mergedQuery.append(originalQuery.substring(pos));
setQuery(mergedQuery.toString());
}
|
java
| 13 | 0.569432 | 141 | 41.444444 | 27 |
inline
|
package android.os;
import android.annotation.Nullable;
public class ServiceManager {
/**
* Returns a reference to a service with the given name.
*
* @param name the name of the service to get
* @return a reference to the service, or if the service doesn't exist
*/
@Nullable
public static IBinder getService(String name) {
throw new RuntimeException("STUB");
}
/**
* Place a new @a service called @a name into the service
* manager.
*
* @param name the name of the new service
* @param service the service object
*/
public static void addService(String name, IBinder service) {
throw new RuntimeException("STUB");
}
}
|
java
| 9 | 0.640541 | 92 | 25.428571 | 28 |
starcoderdata
|
import React, { PureComponent } from 'react';
import { RefreshControl, ScrollView, InteractionManager, ActivityIndicator, StyleSheet, View } from 'react-native';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import ScrollableTabView from 'react-native-scrollable-tab-view';
import DefaultTabBar from 'react-native-scrollable-tab-view/DefaultTabBar';
import { colors, fontStyles, baseStyles } from '../../../styles/common';
import AccountOverview from '../../UI/AccountOverview';
import Tokens from '../../UI/Tokens';
import { getWalletNavbarOptions } from '../../UI/Navbar';
import { strings } from '../../../../locales/i18n';
import { renderFromWei, weiToFiat, hexToBN } from '../../../util/number';
import Engine from '../../../core/Engine';
import CollectibleContracts from '../../UI/CollectibleContracts';
import Analytics from '../../../core/Analytics';
import { ANALYTICS_EVENT_OPTS } from '../../../util/analytics';
import { getTicker } from '../../../util/transactions';
import OnboardingWizard from '../../UI/OnboardingWizard';
import { showTransactionNotification, hideCurrentNotification } from '../../../actions/notification';
import ErrorBoundary from '../ErrorBoundary';
const styles = StyleSheet.create({
wrapper: {
flex: 1,
backgroundColor: colors.white
},
tabUnderlineStyle: {
height: 2,
backgroundColor: colors.blue
},
tabStyle: {
paddingBottom: 0
},
textStyle: {
fontSize: 12,
letterSpacing: 0.5,
...fontStyles.bold
},
loader: {
backgroundColor: colors.white,
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
});
/**
* Main view for the wallet
*/
class Wallet extends PureComponent {
static navigationOptions = ({ navigation }) => getWalletNavbarOptions('wallet.title', navigation);
static propTypes = {
/**
* Map of accounts to information objects including balances
*/
accounts: PropTypes.object,
/**
* ETH to current currency conversion rate
*/
conversionRate: PropTypes.number,
/**
* Currency code of the currently-active currency
*/
currentCurrency: PropTypes.string,
/**
/* navigation object required to push new views
*/
navigation: PropTypes.object,
/**
* An object containing each identity in the format address => account
*/
identities: PropTypes.object,
/**
* A string that represents the selected address
*/
selectedAddress: PropTypes.string,
/**
* An array that represents the user tokens
*/
tokens: PropTypes.array,
/**
* An array that represents the user collectibles
*/
collectibles: PropTypes.array,
/**
* Current provider ticker
*/
ticker: PropTypes.string,
/**
* Current onboarding wizard step
*/
wizardStep: PropTypes.number
};
state = {
refreshing: false
};
accountOverviewRef = React.createRef();
mounted = false;
componentDidMount = () => {
requestAnimationFrame(async () => {
const { AssetsDetectionController, AccountTrackerController } = Engine.context;
AssetsDetectionController.detectAssets();
AccountTrackerController.refresh();
this.mounted = true;
});
};
onRefresh = async () => {
requestAnimationFrame(async () => {
this.setState({ refreshing: true });
const {
AssetsDetectionController,
AccountTrackerController,
CurrencyRateController,
TokenRatesController
} = Engine.context;
const actions = [
AssetsDetectionController.detectAssets(),
AccountTrackerController.refresh(),
CurrencyRateController.start(),
TokenRatesController.poll()
];
await Promise.all(actions);
this.setState({ refreshing: false });
});
};
componentWillUnmount() {
this.mounted = false;
}
renderTabBar() {
return (
<DefaultTabBar
underlineStyle={styles.tabUnderlineStyle}
activeTextColor={colors.blue}
inactiveTextColor={colors.fontTertiary}
backgroundColor={colors.white}
tabStyle={styles.tabStyle}
textStyle={styles.textStyle}
/>
);
}
onChangeTab = obj => {
InteractionManager.runAfterInteractions(() => {
if (obj.ref.props.tabLabel === strings('wallet.tokens')) {
Analytics.trackEvent(ANALYTICS_EVENT_OPTS.WALLET_TOKENS);
} else {
Analytics.trackEvent(ANALYTICS_EVENT_OPTS.WALLET_COLLECTIBLES);
}
});
};
onRef = ref => {
this.accountOverviewRef = ref;
};
renderContent() {
const {
accounts,
conversionRate,
currentCurrency,
identities,
selectedAddress,
tokens,
collectibles,
navigation,
ticker
} = this.props;
let balance = 0;
let assets = tokens;
if (accounts[selectedAddress]) {
balance = renderFromWei(accounts[selectedAddress].balance);
assets = [
{
name: 'Ether', // FIXME: use 'Ether' for mainnet only, what should it be for custom networks?
symbol: getTicker(ticker),
isETH: true,
balance,
balanceFiat: weiToFiat(hexToBN(accounts[selectedAddress].balance), conversionRate, currentCurrency),
logo: '../images/eth-logo.png'
},
...tokens
];
} else {
assets = tokens;
}
const account = { address: selectedAddress, ...identities[selectedAddress], ...accounts[selectedAddress] };
return (
<View style={styles.wrapper}>
<AccountOverview account={account} navigation={navigation} onRef={this.onRef} />
<ScrollableTabView
renderTabBar={this.renderTabBar}
// eslint-disable-next-line react/jsx-no-bind
onChangeTab={obj => this.onChangeTab(obj)}
>
<Tokens navigation={navigation} tabLabel={strings('wallet.tokens')} tokens={assets} />
<CollectibleContracts
navigation={navigation}
tabLabel={strings('wallet.collectibles')}
collectibles={collectibles}
/>
);
}
renderLoader() {
return (
<View style={styles.loader}>
<ActivityIndicator size="small" />
);
}
/**
* Return current step of onboarding wizard if not step 5 nor 0
*/
renderOnboardingWizard = () => {
const { wizardStep } = this.props;
return (
[1, 2, 3, 4].includes(wizardStep) && (
<OnboardingWizard navigation={this.props.navigation} coachmarkRef={this.accountOverviewRef} />
)
);
};
render = () => (
<ErrorBoundary view="Wallet">
<View style={baseStyles.flexGrow} testID={'wallet-screen'}>
<ScrollView
style={styles.wrapper}
refreshControl={<RefreshControl refreshing={this.state.refreshing} onRefresh={this.onRefresh} />}
>
{this.props.selectedAddress ? this.renderContent() : this.renderLoader()}
{this.renderOnboardingWizard()}
);
}
const mapStateToProps = state => ({
accounts: state.engine.backgroundState.AccountTrackerController.accounts,
conversionRate: state.engine.backgroundState.CurrencyRateController.conversionRate,
currentCurrency: state.engine.backgroundState.CurrencyRateController.currentCurrency,
identities: state.engine.backgroundState.PreferencesController.identities,
selectedAddress: state.engine.backgroundState.PreferencesController.selectedAddress,
tokens: state.engine.backgroundState.AssetsController.tokens,
collectibles: state.engine.backgroundState.AssetsController.collectibles,
ticker: state.engine.backgroundState.NetworkController.provider.ticker,
wizardStep: state.wizard.step
});
const mapDispatchToProps = dispatch => ({
showTransactionNotification: args => dispatch(showTransactionNotification(args)),
hideCurrentNotification: () => dispatch(hideCurrentNotification())
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(Wallet);
|
javascript
| 18 | 0.700463 | 115 | 26.878229 | 271 |
starcoderdata
|
export class PoliciesAPIError extends Error {
constructor(message, code, details) {
super(code + ': ' + message);
this.code = code;
this.details = details;
}
}
export class PoliciesAPI {
/**
API for managing policies
**/
// Create new API handler to PoliciesAPI.
// preflightHandler (if defined) can return promise
constructor(base_url = 'https://1172.16.58.3:3434/u/', preflightHandler = null) {
this.__url = base_url;
this.__id = 1;
this.__preflightHandler = preflightHandler;
}
/**
List all policies
**/
async list(token){
return (await this.__call('List', {
"jsonrpc" : "2.0",
"method" : "PoliciesAPI.List",
"id" : this.__next_id(),
"params" : [token]
}));
}
/**
Create new policy
**/
async create(token, policy, definition){
return (await this.__call('Create', {
"jsonrpc" : "2.0",
"method" : "PoliciesAPI.Create",
"id" : this.__next_id(),
"params" : [token, policy, definition]
}));
}
/**
Remove policy
**/
async remove(token, policy){
return (await this.__call('Remove', {
"jsonrpc" : "2.0",
"method" : "PoliciesAPI.Remove",
"id" : this.__next_id(),
"params" : [token, policy]
}));
}
/**
Update policy definition
**/
async update(token, policy, definition){
return (await this.__call('Update', {
"jsonrpc" : "2.0",
"method" : "PoliciesAPI.Update",
"id" : this.__next_id(),
"params" : [token, policy, definition]
}));
}
/**
Apply policy for the resource
**/
async apply(token, lambda, policy){
return (await this.__call('Apply', {
"jsonrpc" : "2.0",
"method" : "PoliciesAPI.Apply",
"id" : this.__next_id(),
"params" : [token, lambda, policy]
}));
}
/**
Clear applied policy for the lambda
**/
async clear(token, lambda){
return (await this.__call('Clear', {
"jsonrpc" : "2.0",
"method" : "PoliciesAPI.Clear",
"id" : this.__next_id(),
"params" : [token, lambda]
}));
}
__next_id() {
this.__id += 1;
return this.__id
}
async __call(method, req) {
const fetchParams = {
method: "POST",
headers: {
'Content-Type' : 'application/json',
},
body: JSON.stringify(req)
};
if (this.__preflightHandler) {
await Promise.resolve(this.__preflightHandler(method, fetchParams));
}
const res = await fetch(this.__url, fetchParams);
if (!res.ok) {
throw new Error(res.status + ' ' + res.statusText);
}
const data = await res.json();
if ('error' in data) {
throw new PoliciesAPIError(data.error.message, data.error.code, data.error.data);
}
return data.result;
}
}
|
javascript
| 15 | 0.48315 | 93 | 24.206349 | 126 |
starcoderdata
|
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Horaire extends CI_Controller {
public function get_by_arret($id_ligne, $id_arret, $sens, $jour = NULL)
{
if(!is_numeric((int)$id_arret) || !is_numeric((int)$sens))
{
retour('Merci de vous rapporter à la notice de l\'api', FALSE);
}
$horaires['horaires'] = $this->horaires_model->get_liste($id_ligne, $id_arret, $sens, $jour);
retour('Horaire à l\'arret', TRUE, $horaires);
}
public function get_by_arret_current($id_ligne, $id_arret, $sens, $nb, $jour = NULL)
{
if(!is_numeric((int)$id_arret) || !is_numeric((int)$sens))
{
retour('Merci de vous rapporter à la notice de l\'api', FALSE);
}
$horaires['horaires'] = $this->horaires_model->get_liste_current($id_ligne, $id_arret, $sens, $nb, $jour);
retour('Horaire à l\'arret', TRUE, $horaires);
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
|
php
| 14 | 0.654076 | 108 | 28.617647 | 34 |
starcoderdata
|
const { TITLES } = require('../constants');
const isMM = require('./is-mm');
const labelByKey = require('./label-by-key');
module.exports = (key) => labelByKey(key) || (isMM(key) ? TITLES.MM : (key === 'ai' ? TITLES.AI : TITLES.IPT));
|
javascript
| 9 | 0.637681 | 111 | 38.428571 | 7 |
starcoderdata
|
/*
* Copyright (C) 2021 - 2021, SanteSuite Inc. and the SanteSuite Contributors (See NOTICE.md for full copyright notices)
* Copyright (C) 2019 - 2021, Fyfe Software Inc. and the SanteSuite Contributors
* Portions Copyright (C) 2015-2018 Mohawk College of Applied Arts and Technology
*
* 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.
*
* User: fyfej
* Date: 2021-8-5
*/
using SanteDB.Core;
using SanteDB.Core.Configuration;
using SanteDB.Core.Event;
using SanteDB.Core.Model;
using SanteDB.Core.Model.Collection;
using SanteDB.Core.Model.Entities;
using SanteDB.Core.Security;
using SanteDB.Core.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace SanteDB.Persistence.MDM.Services
{
///
/// Represents a resource listener that handles bundles
///
public class BundleResourceListener : MdmResourceListener
{
// Listeners for chaining
private IEnumerable m_listeners;
///
/// Bundle resource listener
///
public BundleResourceListener(IEnumerable listeners) : base(new ResourceMergeConfiguration(typeof(Bundle), false))
{
this.m_listeners = listeners;
}
///
/// As a bundle, we call the base on the contents of the data
///
protected override void OnPrePersistenceValidate(object sender, DataPersistingEventArgs e)
{
e.Data = this.ChainInvoke(sender, e, e.Data, nameof(OnPrePersistenceValidate), typeof(DataPersistingEventArgs<>));
}
///
/// Chain invoke a bundle on inserted
///
protected override void OnInserting(object sender, DataPersistingEventArgs e)
{
e.Data = this.ChainInvoke(sender, e, e.Data, nameof(OnInserting), typeof(DataPersistingEventArgs<>));
}
///
/// Chain invoke a bundle
///
protected override void OnSaving(object sender, DataPersistingEventArgs e)
{
e.Data = this.ChainInvoke(sender, e, e.Data, nameof(OnSaving), typeof(DataPersistingEventArgs<>));
}
///
/// On obsoleting
///
protected override void OnObsoleting(object sender, DataPersistingEventArgs e)
{
e.Data = this.ChainInvoke(sender, e, e.Data, nameof(OnObsoleting), typeof(DataPersistingEventArgs<>));
}
///
/// Merging a bundle? Impossible
///
public override Bundle Merge(Guid master, IEnumerable linkedDuplicates)
{
throw new NotSupportedException("Cannot merge bundles");
}
///
/// Un-merge a bundle? Even more impossible than merging
///
public override Bundle Unmerge(Guid master, Guid unmergeDuplicate)
{
throw new NotSupportedException("Cannot unmerge bundles");
}
///
/// Cannot query bundles
///
protected override void OnQuerying(object sender, QueryRequestEventArgs e)
{
throw new NotSupportedException("Cannot query bundles");
}
///
/// Cannot query bundles
///
protected override void OnQueried(object sender, QueryResultEventArgs e)
{
throw new NotSupportedException("Cannot query bundles");
}
///
/// Cannot query bundles
///
protected override void OnRetrieved(object sender, DataRetrievedEventArgs e)
{
throw new NotSupportedException("Cannot retrieve bundles");
}
///
/// Cannot query bundles
///
protected override void OnRetrieving(object sender, DataRetrievingEventArgs e)
{
throw new NotSupportedException("Cannot retrieve bundles");
}
///
/// Performs a chain invokation on the bundle's contents
///
private Bundle ChainInvoke(object sender, object eventArgs, Bundle bundle, string methodName, Type argType)
{
for (int i = 0; i < bundle.Item.Count; i++)
{
var data = bundle.Item[i];
var mdmHandler = typeof(MdmResourceListener<>).MakeGenericType(data.GetType());
var evtArgType = argType.MakeGenericType(data.GetType());
var evtArgs = Activator.CreateInstance(evtArgType, data, (eventArgs as SecureAccessEventArgs).Principal);
foreach (var hdlr in this.m_listeners.Where(o => o.GetType() == mdmHandler))
{
var exeMethod = mdmHandler.GetRuntimeMethods().Single(m => m.Name == methodName && m.GetParameters().Select(p => p.ParameterType).SequenceEqual(new Type[] { typeof(Object), evtArgType }));
exeMethod.Invoke(hdlr, new Object[] { bundle, evtArgs });
// Cancel?
var subData = evtArgType.GetRuntimeProperty("Data").GetValue(evtArgs) as IdentifiedData;
if (bundle.Item[i].Key == subData.Key)
bundle.Item[i] = subData;
if(eventArgs is DataPersistingEventArgs
(eventArgs as DataPersistingEventArgs |= (bool)evtArgType.GetRuntimeProperty("Cancel").GetValue(evtArgs);
}
}
// Now that bundle is processed , process it
if ((eventArgs as DataPersistingEventArgs == true && (methodName == "OnInserting" || methodName == "OnSaving"))
{
var businessRulesSerice = ApplicationServiceContext.Current.GetService
bundle = businessRulesSerice?.BeforeInsert(bundle) ?? bundle;
// Business rules shouldn't be used for relationships, we need to delay load the sources
bundle.Item.OfType =>
{
if (i.SourceEntity == null)
{
var candidate = bundle.Item.Find(o => o.Key == i.SourceEntityKey) as Entity;
if (candidate != null)
i.SourceEntity = candidate;
}
});
bundle = ApplicationServiceContext.Current.GetService TransactionMode.Commit, AuthenticationContext.Current.Principal);
bundle = businessRulesSerice?.AfterInsert(bundle) ?? bundle;
}
return bundle;
}
}
}
|
c#
| 28 | 0.616378 | 208 | 40.038251 | 183 |
starcoderdata
|
/*
* Copyright (c) [2019] [潘志勇]
* [pzy-opensource] is licensed under the Mulan PSL v1.
* You can use this software according to the terms and conditions of the Mulan PSL v1.
* You may obtain a copy of Mulan PSL v1 at:
* http://license.coscl.org.cn/MulanPSL
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
* PURPOSE.
* See the Mulan PSL v1 for more details.
*/
package org.pzy.opensource.springboot.domain.bo;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 潘志勇
* @date 2019-01-14
*/
@Setter
@Getter
@ToString
public class CrossInfoBO {
/**
* 接口URI(以`/`开头). 默认值: /**
*/
private String uri;
/**
* 允许的访问的域名(多个使用分号分割).默认值:*
* e.g *;http://www.baidu.com;http://localhost:8081;https://*.aliyun.com
*/
private String allowedOrigins;
/**
* 允许的请求头(多个使用分号分割).默认值:*
* e.g *;
*/
private String allowedHeaders;
/**
* 允许的请求方法.(多个使用分好分割).默认值:*
* e.g *;POST;GET
*/
private String allowedMethods;
/**
* 跨域请求是否允许携带cookie. 默认: true
*/
private Boolean allowCredentials;
public CrossInfoBO() {
this.allowedOrigins = "*";
this.allowedMethods = "*";
this.allowedHeaders = "*";
this.uri = "/**";
this.allowCredentials = true;
}
}
|
java
| 16 | 0.634756 | 151 | 25.885246 | 61 |
starcoderdata
|
package handlers
import (
"context"
"errors"
"log"
"math/rand"
"net/http"
"time"
"github.com/QuinnMain/infograph/golang/custom_errors"
mdb "github.com/QuinnMain/infograph/golang/db_alt"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"golang.org/x/crypto/bcrypt"
)
var src = rand.NewSource(time.Now().UnixNano())
const (
letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)
// generateRandomString can be used to create verification codes or something this
// this implementation comes from stackoverflow
// https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-go
func generateRandomString(n int) string {
b := make([]byte, n)
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return string(b)
}
func hashPassword(password, salt string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password+salt), 14)
return string(bytes), err
}
func checkPasswordHash(password, salt, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password+salt))
return err == nil
}
// func UpdatePassword(env env.Env, user mdb.MUser, w http.ResponseWriter, r *http.Request) http.HandlerFunc {
// if *user.Status != mdb.UserStatusActive {
// return write.Error(errors.RouteUnauthorized)
// }
// decoder := json.NewDecoder(r.Body)
// var u mdb.MUser
// err := decoder.Decode(&u)
// if err != nil || &u == nil {
// return write.Error(errors.NoJSONBody)
// }
// // шифруем пароль
// salt := generateRandomString(32)
// hashedPassword, err := hashPassword(*u.Password, salt)
// if err != nil {
// return write.Error(err)
// }
// // обновляем
// update := bson.D{
// {"$set", bson.D{
// {"password",
// {"salt", salt}},
// },
// }
// _, err = env.Collection(string(mdb.RESETS)).UpdateByID(r.Context(), *u.Id, update)
// if err != nil {
// return write.Error(err)
// }
// if err != nil {
// return write.Error(err)
// }
// return write.Success()
// }
// TODO: стоит это кэшировать
func UserCheck(db *mongo.Database, c *gin.Context) (mdb.MUser, error, int) {
u := mdb.MUser{}
session := sessions.Default(c)
userIdHex := session.Get("userId") // есть подозрение что эта строчка так-же сжирает сессию!
if userIdHex == nil {
return u, errors.New("empty session"), http.StatusNotFound
}
userId, _ := primitive.ObjectIDFromHex(userIdHex.(string))
filter := bson.D{{"_id", userId}}
err := mdb.GetOne(context.TODO(), db, mdb.USERS, filter, &u)
if err != nil {
if isNotFound(err) {
return u, custom_errors.UserNotFound, http.StatusNotFound
}
return u, err, http.StatusInternalServerError
}
// проверяем на статус
// if u.Status != mdb.UserStatusActive {
// return mdb.MUser{}, custom_errors.InvalidToken, http.StatusUnauthorized
// }
return u, nil, http.StatusOK
}
func Whoami(db *mongo.Database) gin.HandlerFunc {
fn := func(c *gin.Context) {
u, err, statusCode := UserCheck(db, c)
if err != nil {
// c.JSON(statusCode, gin.H{
// "status": u.Status,
// "permissions": u.Permissions,
// })
c.AbortWithError(statusCode, err)
return
}
//else
c.JSON(http.StatusOK, gin.H{
"status": u.Status,
"permissions": u.Permissions,
})
}
return fn
}
type AuthRequest struct {
Email string `form:"email" json:"email" binding:"required"` //! сюрприз! это трудно объяснить
Password string `form:"password" json:"password" binding:"required"`
}
// POST
// https://stackoverflow.com/a/69289345/13697067
func Login(db *mongo.Database) gin.HandlerFunc {
fn := func(c *gin.Context) {
// предотвращаем дупликацию сессии
session := sessions.Default(c)
userIdHex := session.Get("userId")
log.Printf("нашли: %v", userIdHex)
if userIdHex != nil {
c.JSON(http.StatusOK, gin.H{
"message": "User is already signed in",
})
return
}
// читаем запрос
email := c.PostForm("email")
postPassword := c.PostForm("password")
// ищем пользователя в бд (по запросу)
u := mdb.MUser{}
filter := bson.D{{"email", email}}
log.Printf("авторизация по почте:%s", email)
err := mdb.GetOne(context.TODO(), db, mdb.USERS, filter, &u)
// если такого нет:
if err != nil {
if isNotFound(err) {
c.AbortWithError(http.StatusUnauthorized, custom_errors.UserNotFound)
return
}
c.AbortWithError(http.StatusInternalServerError, err)
return
}
// если такой есть:
// проверяем предоставленный пароль
if !checkPasswordHash(postPassword, u.Salt, u.Password) {
c.AbortWithError(http.StatusUnauthorized, custom_errors.FailedLogin)
return
}
log.Printf("%v", u.Id.Hex()) //tmp
// создаём сессию для этого пользователя
session.Set("userId", u.Id.Hex())
err = session.Save()
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.JSON(http.StatusOK, gin.H{
"message": "User signed in successfully",
})
}
return fn
}
func Logout(db *mongo.Database) gin.HandlerFunc {
fn := func(c *gin.Context) {
log.Printf("logging out someone")
session := sessions.Default(c)
session.Clear()
session.Save()
c.JSON(http.StatusOK, gin.H{
"message": "User Sign out successfully",
})
}
return fn
}
// регистрация
// POST
func Signup(db *mongo.Database) gin.HandlerFunc {
fn := func(c *gin.Context) {
email := c.PostForm("email")
postPassword := c.PostForm("password")
// проверяем почту на реальность
// if _, err := mail.ParseAddress(email); err != nil {
// c.AbortWithError(http.StatusNotAcceptable, err)
// return
// }
log.Printf("registering email %s", email)
// ищем пользователя в бд
u := mdb.MUser{}
filter := bson.D{{"email", email}}
err := mdb.GetOne(context.TODO(), db, mdb.USERS, filter, &u)
log.Println("Попытались найти человека с такой почтой, нашли:")
log.Printf("%#v", u)
if err != nil {
if isNotFound(err) { //* это хорошо, логин/почта не занята
log.Println("То есть ничего")
// солим и хэшируем пароль
salt := generateRandomString(32)
password, passwordHashErr := hashPassword(postPassword, salt)
if passwordHashErr != nil {
log.Println("Password hashing error")
c.AbortWithError(500, passwordHashErr)
return
}
// добавляем пользователя
newUser := mdb.MUser{
Id: primitive.NewObjectID(),
Login: "",
Email: email,
Permissions: []string{},
Password: password,
Salt: salt,
Status: mdb.UserStatusUnverified,
Commentary: "
// VerificationCode: generateRandomString(32), // мб убрать это поле
}
log.Printf("Добавляем нового пользователя:\n%#v", newUser)
_, insertionErr := mdb.InsertOne(context.TODO(), db, mdb.USERS, newUser)
if insertionErr != nil {
log.Println("DB insertion error")
c.AbortWithError(500, insertionErr)
return
}
c.JSON(200, gin.H{
"OK": "registration success",
})
return
}
log.Println("User retrieval error")
c.AbortWithError(500, err)
return
}
log.Println("'Already taken' error")
c.AbortWithStatusJSON(http.StatusConflict, gin.H{
"error": "login or email already taken", //TODO: опасно, dev environment only
})
}
return fn
}
// filter := bson.D{{"$or", bson.A{
// // bson.D{{"login", email}},
// bson.D{{"email", email}},
// }}}
|
go
| 19 | 0.657215 | 110 | 26.940141 | 284 |
starcoderdata
|
"use strict";
var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
var React = _interopRequire(require("react"));
var Demo = React.createClass({
displayName: "Demo",
render: function render() {
return React.createElement(
"div",
null,
"Hello from Shanghai JavaScript Meetup!"
);
}
});
React.render(React.createElement(Demo, null), document.body);
|
javascript
| 13 | 0.64554 | 94 | 20.35 | 20 |
starcoderdata
|
/**
* Copyright (c) 2014, Institute of Telematics, Karlsruhe Institute of Technology.
*
* This file is part of the PktAnon project. PktAnon is distributed under 2-clause BSD licence.
* See LICENSE file found in the top-level directory of this distribution.
*/
#include "AnonBytewise.h"
#include
#include
namespace pktanon
{
AnonBytewise::AnonBytewise()
{
}
AnonBytewise::AnonBytewise ( const AnonBytewise& other ) : AnonPrimitive ( other )
{
memcpy ( anonbytes, other.anonbytes, 256*sizeof ( unsigned char ) );
}
AnonBytewise::~AnonBytewise()
{
}
AnonPrimitive::ANON_RESULT AnonBytewise::anonymize ( void* buf, unsigned int len )
{
unsigned char* pnt;
for ( unsigned int i = 0; i < len; i++ )
{
pnt = ( unsigned char* ) buf + i;
memset ( pnt, anonbytes[*pnt], 1 );
} // for (unsigned int i=0; i<len; i++)
return ANON_RESULT ( len );
}
}
|
c++
| 13 | 0.680493 | 95 | 20.238095 | 42 |
starcoderdata
|
import {EventListenerConfig} from './EventListenerConfig'
export class EventListenerConfigBuilder {
/**
*
* @param {String} event
*/
constructor(event = '') {
/**
*
* @params {string}
* @protected
*/
this._event = event
/**
*
* @params {Function}
* @callback
* @protected
*/
this._callback = () => true
/**
*
* @params {boolean}
* @protected
*/
this._capture = false
/**
*
* @params {boolean}
* @protected
*/
this._once = false
/**
*
* @params {boolean}
* @protected
*/
this._passive = false
}
/**
*
* @param {String} event
* @return {EventListenerConfigBuilder}
* @constructor
*/
static listen(event) {
return new this(event)
}
/**
*
* @param {Function} clb
* @return {EventListenerConfigBuilder}
*/
callback(clb) {
this._callback = clb
return this
}
/**
*
* @param {boolean} [capture = true]
* @return {EventListenerConfigBuilder}
*/
capture(capture = true) {
this._capture = capture
return this
}
/**
*
* @param {boolean} [once = true]
* @return {EventListenerConfigBuilder}
*/
once(once = true) {
this._once = once
return this
}
/**
*
* @param {boolean} [passive = true]
* @return {EventListenerConfigBuilder}
*/
passive(passive = true) {
this._passive = passive
return this
}
/**
*
* @return {EventListenerConfig}
*/
build() {
if (this._hasOptions()) {
const options = {}
if (this._capture) {
options.capture = true
}
if (this._once) {
options.once = true
}
if (this._passive) {
options.passive = true
}
return EventListenerConfig.createWithOptions(this._event, this._callback, options)
} else {
return EventListenerConfig.create(this._event, this._callback)
}
}
/**
*
* @return {boolean}
* @protected
*/
_hasOptions() {
return this._capture || this._once || this._passive
}
}
|
javascript
| 10 | 0.545619 | 107 | 17 | 123 |
starcoderdata
|
import torch
from torch import nn
# colect loss function
def get_loss(name, m1=1.35, m2=0.5, m3=0.40, s=64.0, l_a=10, u_a=110, l_m=0.2, u_m=0.45, lambda_g=20):
if name == "cosface":
return CosFace(s = s, m = m3)
elif name == "arcface":
return ArcFace(s = s, m = m2)
elif name == 'sphereface':
return SphereFace(s = s, m = m1)
elif name == 'mixface':
return MixFace(s = s, m1 = m1, m2 = m2, m3 = m3)
elif name =='magface':
return MagFace(l_a, u_a, l_m, u_m, lambda_g, s=s)
elif name =='mag_cosface':
return Mag_CosFace(l_a, u_a, l_m, u_m, s=s)
else:
raise ValueError()
# thesis loss function -> improved combined margin
class Mag_CosFace(nn.Module):
def __init__(self, l_a, u_a, l_m, u_m, s):
super(Mag_CosFace, self).__init__()
self.s = s
self.l_a = l_a
self.u_a = u_a
self.l_m = l_m
self.u_m = u_m
self.m = 0.1
self.lambda_g = 20
def margin(self, a_i):
m = (self.u_m-self.l_m) / (self.u_a - self.l_a) * (a_i-self.l_a) + self.l_m
return m
def calc_loss_G(self, x_norm):
g = 1/(self.u_a**2) * x_norm + 1/(x_norm)
return torch.mean(g)
def forward(self, cosine: torch.Tensor, label, x):
# a_i
a_i = torch.norm(x, dim=1, keepdim=True).clamp(self.l_a, self.u_a)
# m(a_i)
m = self.margin(a_i).mean().item()
index = torch.where(label != -1)[0]
# make varaible margin
m_hot = torch.zeros(index.size()[0], cosine.size()[1], device=cosine.device)
m_hot.scatter_(1, label[index, None], m)
# make fixed margin
m_hot2 = torch.zeros(index.size()[0], cosine.size()[1], device=cosine.device)
m_hot2.scatter_(1, label[index, None], self.m)
# add to variable margin in angular space
cosine.acos_()
cosine[index] += m_hot
cosine.cos_()
# add to fixed margin in cosine space
cosine[index] -= m_hot2
cosine = cosine * self.s
g = self.calc_loss_G(a_i) * self.lambda_g
return cosine, g
class MagFace(nn.Module):
def __init__(self, l_a, u_a, l_m, u_m, lambda_g, s):
super(MagFace, self).__init__()
self.s = s
self.l_a = l_a
self.u_a = u_a
self.l_m = l_m
self.u_m = u_m
self.lambda_g = lambda_g
def margin(self, a_i):
m = (self.u_m-self.l_m) / (self.u_a - self.l_a) * (self.u_a - a_i) + self.l_m
return m
def calc_loss_G(self, x_norm):
g = 1/(self.u_a**2) * x_norm + 1/(x_norm)
return torch.mean(g)
def forward(self, cosine: torch.Tensor, label, x):
a_i = torch.norm(x, dim=1, keepdim=True).clamp(self.l_a, self.u_a)
m = self.margin(a_i).mean().item()
index = torch.where(label != -1)[0]
m_hot = torch.zeros(index.size()[0], cosine.size()[1], device=cosine.device)
m_hot.scatter_(1, label[index, None], m)
cosine.acos_()
cosine[index] += m_hot
cosine.cos_().mul_(self.s)
g = self.calc_loss_G(a_i) * self.lambda_g
return cosine, g.item()
class SphereFace(nn.Module):
def __init__(self, s=64.0, m=1.35):
super(SphereFace, self).__init__()
self.s = s
self.m = m
# 고쳐야함
def forward(self, cosine: torch.Tensor, label, x):
#print(cosine)
index = torch.where(label != -1)[0] # label에서 GT 위치
m_hot = torch.ones(index.size()[0], cosine.size()[1], device=cosine.device)
m_hot.scatter_(1, label[index, None], self.m)
#print(index.size()[0], cosine.size(), cosine.size()[1], label.size(), m_hot.size())
cosine.acos_()
cosine[index] *= m_hot
cosine.cos_().mul_(self.s)
#print(cosine)
return cosine, 0
class MixFace(nn.Module):
def __init__(self, s=64.0, m1=1.35, m2=0.5, m3=0.40):
super(MixFace, self).__init__()
self.s = s
self.m1 = m1
self.m2 = m2
self.m3 = m3
# 고쳐야함
def forward(self, cosine: torch.Tensor, label, x):
index = torch.where(label != -1)[0] # label에서 GT 위치
# SphereFace
m1_hot = torch.ones(index.size()[0], cosine.size()[1], device=cosine.device)
m1_hot.scatter_(1, label[index, None], self.m1)
# ArcFace
m2_hot = torch.zeros(index.size()[0], cosine.size()[1], device=cosine.device)
m2_hot.scatter_(1, label[index, None], self.m2)
# CosFace
m3_hot = torch.zeros(index.size()[0], cosine.size()[1], device=cosine.device)
m3_hot.scatter_(1, label[index, None], self.m3)
cosine.acos_()
cosine[index] *= m1_hot
cosine[index] += m2_hot
cosine.cos_()
cosine[index] -= m3_hot
ret = cosine * self.s
return ret, 0
class CosFace(nn.Module):
def __init__(self, s=64.0, m=0.40):
super(CosFace, self).__init__()
self.s = s
self.m = m
def forward(self, cosine, label, x):
index = torch.where(label != -1)[0]
m_hot = torch.zeros(index.size()[0], cosine.size()[1], device=cosine.device)
m_hot.scatter_(1, label[index, None], self.m)
cosine[index] -= m_hot
ret = cosine * self.s
return ret, 0
class ArcFace(nn.Module):
def __init__(self, s=64.0, m=0.5):
super(ArcFace, self).__init__()
self.s = s
self.m = m
def forward(self, cosine: torch.Tensor, label, x):
index = torch.where(label != -1)[0]
m_hot = torch.zeros(index.size()[0], cosine.size()[1], device=cosine.device)
m_hot.scatter_(1, label[index, None], self.m)
cosine.acos_()
cosine[index] += m_hot
cosine.cos_().mul_(self.s)
return cosine, 0
|
python
| 13 | 0.532596 | 102 | 29.921053 | 190 |
starcoderdata
|
using FluentAssertions;
using Validation.Attributes;
using Xunit;
namespace Validation.Test.Attributes;
public class OfLegalAgeAttributeTest
{
private readonly OfLegalAgeAttribute _uut;
public OfLegalAgeAttributeTest()
{
_uut = new OfLegalAgeAttribute();
}
[Theory]
[InlineData(18)]
[InlineData(19)]
[InlineData(20)]
[InlineData(100)]
public void Should_BeValid(int input)
{
var result = _uut.IsValid(input);
result.Should().Be(true);
}
[Theory]
[InlineData(17)]
[InlineData(16)]
[InlineData(0)]
[InlineData(-1)]
public void Should_BeInvalid(int input)
{
var result = _uut.IsValid(input);
result.Should().Be(false);
}
}
|
c#
| 13 | 0.616745 | 61 | 19.225 | 40 |
starcoderdata
|
from flask import Flask, request, jsonify
import boto3
import time
server = Flask(__name__)
sfn = boto3.client('stepfunctions', region_name='us-east-1')
ddb = boto3.client('dynamodb')
#microserviços
@server.route("/")
def root_path():
return("ok")
@server.route("/teste/prepara-agenda", methods=["POST"])
def teste():
event = request.json
print(event['TaskToken'])
token = event['TaskToken']
ispb = event['ispb']
message = '{ "output": "Prepara agenda concluido com sucesso", "sucesso": "true" }'
if (True):
sucesso = True
time.sleep(10)
response = sfn.send_task_success(taskToken=token, output=message)
return (response)
else:
sucesso = False
error = { "error": "Falso" }
cause = { "cause": "Prepara Agendas não foi concluído com sucesso" }
response = sfn.send_task_failure(taskToken=token, error=error, cause=cause)
return (response)
@server.route("/teste/efetiva-operacao", methods=["POST"])
def efetiva_operacao():
return("chamada EFETIVA OPERACAO do microserviço")
@server.route("/teste/valida-anuencia/")
def valida_anuencia():
event = request.json
ispb = event['ispb']
message = "chamada VALIDA ANUENCIA do microserviço"
return ({ "ispb": ispb, "message": message})
@server.route("/teste/envia-anuencia", methods=["POST"])
def envia_anuencia():
event = request.json
ispb = event['ispb']
message = "chamada ENVIA ANUENCIA do microserviço"
response = ddb.update_item(
TableName='r2c3',
Key={
'ispb': {
'S': ispb
}
},
UpdateExpression='SET Anuencia = :status',
ExpressionAttributeValues={
':status': {
'S': 'enviada'
}
}
)
return ({ "ispb": ispb, "message": message})
@server.route('/
def worker_task(task):
return("tarefa {} executada").format(task)
if __name__ == "__main__":
server.run(host='0.0.0.0')
|
python
| 14 | 0.597037 | 87 | 23.695122 | 82 |
starcoderdata
|
import Component from '@glimmer/component';
import { action } from '@ember/object';
export default class IconComponent extends Component {
@action clicked(...args) {
if (this.args.onClick) this.args.onClick(...args);
}
get placement() {
return this.args.placement || 'right';
}
}
|
javascript
| 11 | 0.677852 | 54 | 23.833333 | 12 |
starcoderdata
|
int ObStoreRowSingleScanEstimator::estimate_macro_row_count(const ObMacroBlockCtx& macro_block_ctx,
const bool is_start_block, const bool is_last_block, ObPartitionEst& part_est)
{
int ret = OB_SUCCESS;
if (!macro_block_ctx.is_valid()) {
ret = OB_INVALID_ARGUMENT;
STORAGE_LOG(WARN, "invalid args", K(ret), K(macro_block_ctx));
} else {
ObFullMacroBlockMeta meta;
ObArray<ObMicroBlockInfo> micro_infos;
if (OB_FAIL(context_.sstable_->get_meta(macro_block_ctx.get_macro_block_id(), meta))) {
STORAGE_LOG(WARN, "Fail to get macro meta, ", K(ret), K(macro_block_ctx));
} else if (!meta.is_valid()) {
ret = OB_ERR_UNEXPECTED;
STORAGE_LOG(WARN, "The macro block meta is NULL, ", K(ret), K(macro_block_ctx));
} else if ((!is_start_block) && (!is_last_block)) {
// in the middle of scan ranges;
part_est.logical_row_count_ += meta.meta_->row_count_;
} else if (OB_FAIL(context_.cache_context_.block_index_cache_->get_micro_infos(context_.sstable_->get_table_id(),
macro_block_ctx,
context_.range_->get_range(),
is_start_block,
is_last_block,
micro_infos))) {
if (OB_BEYOND_THE_RANGE == ret) {
ret = OB_SUCCESS;
} else {
STORAGE_LOG(WARN, "failed to get micro infos", K(ret), K_(context), K(macro_block_ctx));
}
} else {
// FIXME:
// 1. io_micro_block_ costs need multiply block cache hit percent.
// 2. row costs are not precise, need check in micro block.
int64_t average_row_count = 0;
int64_t average_row_size = 0;
int64_t micro_block_count = micro_infos.count();
if (0 != meta.meta_->micro_block_count_) {
average_row_count = meta.meta_->row_count_ / meta.meta_->micro_block_count_;
}
if (0 != meta.meta_->row_count_) {
average_row_size =
(meta.meta_->micro_block_index_offset_ - meta.meta_->micro_block_data_offset_) / meta.meta_->row_count_;
}
if (OB_SUCCESS == ret && is_start_block && micro_block_count > 0) {
if (OB_FAIL(estimate_border_cost(micro_infos,
macro_block_ctx,
true /*check_start*/,
average_row_count,
average_row_size,
micro_block_count,
part_est))) {
STORAGE_LOG(WARN, "failed to estimate border cost", K(ret));
}
}
if (OB_SUCCESS == ret && is_last_block && micro_block_count > 0) {
if (OB_FAIL(estimate_border_cost(micro_infos,
macro_block_ctx,
false /*check_start*/,
average_row_count,
average_row_size,
micro_block_count,
part_est))) {
STORAGE_LOG(WARN, "failed to estimate border cost", K(ret));
}
}
if (OB_SUCCESS == ret && micro_block_count > 0) {
int64_t other_row_count = average_row_count * micro_block_count;
part_est.logical_row_count_ += other_row_count;
}
}
}
return ret;
}
|
c++
| 24 | 0.559961 | 117 | 39.298701 | 77 |
inline
|
<?php
namespace App\Http\Controllers\US6;
use Illuminate\Http\Request;
use App\Models\User;
use App\AccountSettings;
use Auth;
use Input;
use App\Http\Controllers\Controller;
class WeightController extends Controller
{
//
@return void
public function __construct()
{
$this->middleware('auth');
}
public function save(Request $request){
auth()->user()->weight = $request->input('inputweight');
auth()->user()->height = $request->input('inputheight');
auth()->user()->ideal_weight = $request->input('inputDreamWeight');
auth()->user()->save();
return view('home');
}
}
|
php
| 9 | 0.615385 | 75 | 17.416667 | 36 |
starcoderdata
|
package aplicacion.post;
import aplicacion.user.User;
/**
*
* @author hugo
*/
public class Post {
private Integer id;
private User userid;
private String title;
private String body;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public User getUserid() {
return userid;
}
public void setUserid(User userid) {
this.userid = userid;
}
}
|
java
| 8 | 0.570164 | 44 | 14.211538 | 52 |
starcoderdata
|
//go:build integration
// +build integration
package integration
import (
"context"
"fmt"
"testing"
"time"
v1 "k8s.io/api/core/v1"
"github.com/stretchr/testify/require"
)
func TestLiveUpdateAfterCrashRebuild(t *testing.T) {
f := newK8sFixture(t, "live_update_after_crash_rebuild")
defer f.TearDown()
f.SetRestrictedCredentials()
pw := f.newPodWaiter("app=live-update-after-crash-rebuild").
withExpectedPhase(v1.PodRunning)
initialPods := pw.wait()
f.TiltUp()
fmt.Println("> Waiting for pods from initial build")
pw = pw.withExpectedPodCount(1)
initialBuildPods := pw.withDisallowedPodIDs(initialPods).wait()
ctx, cancel := context.WithTimeout(f.ctx, time.Minute)
defer cancel()
f.CurlUntil(ctx, "http://localhost:31234", "🍄 One-Up! 🍄")
// Live update
fmt.Println("> Perform a live update")
f.ReplaceContents("compile.sh", "One-Up", "Two-Up")
ctx, cancel = context.WithTimeout(f.ctx, time.Minute)
defer cancel()
f.CurlUntil(ctx, "http://localhost:31234", "🍄 Two-Up! 🍄")
// Check that the pods were changed in place, and that we didn't create new ones
afterLiveUpdatePods := pw.withDisallowedPodIDs(initialPods).wait()
require.Equal(t, initialBuildPods, afterLiveUpdatePods, "after first live update")
// Delete the pod and make sure it got replaced with something that prints the
// same thing (crash rebuild).
fmt.Println("> Kill pod, wait for crash rebuild")
f.runCommandSilently("kubectl", "delete", "pod", afterLiveUpdatePods[0], namespaceFlag)
ctx, cancel = context.WithTimeout(f.ctx, time.Minute)
defer cancel()
f.CurlUntil(ctx, "http://localhost:31234", "🍄 Two-Up! 🍄")
afterCrashRebuildPods := pw.withDisallowedPodIDs(afterLiveUpdatePods).wait()
// Another live update! Make sure that, after the crash rebuild, we're able to run more
// live updates (i.e. that we have one and only one pod associated w/ the manifest)
fmt.Println("> Perform another live update")
f.ReplaceContents("compile.sh", "Two-Up", "Three-Up")
ctx, cancel = context.WithTimeout(f.ctx, time.Minute)
defer cancel()
f.CurlUntil(ctx, "http://localhost:31234", "🍄 Three-Up! 🍄")
afterSecondLiveUpdatePods := pw.withDisallowedPodIDs(afterLiveUpdatePods).wait()
// Check that the pods were changed in place, and that we didn't create new ones
require.Equal(t, afterCrashRebuildPods, afterSecondLiveUpdatePods)
}
|
go
| 10 | 0.734051 | 88 | 30.763158 | 76 |
starcoderdata
|
class OpenGLMemManager
{
public:
OpenGLMemManager();
~OpenGLMemManager();
/// Pick a buffer ID off the list or ask OpenGL for one
GLuint getBufferID(unsigned int size=0,GLenum drawType=GL_STATIC_DRAW);
/// Toss the given buffer ID back on the list for reuse
void removeBufferID(GLuint bufID);
/// Pick a texture ID off the list or ask OpenGL for one
GLuint getTexID();
/// Toss the given texture ID back on the list for reuse
void removeTexID(GLuint texID);
/// Clear out any and all buffer IDs that we may have sitting around
void clearBufferIDs();
/// Clear out any and all texture IDs that we have sitting around
void clearTextureIDs();
/// Print out stats about what's in the cache
void dumpStats();
/// Clean up resources, don't cache anything else
void teardown();
/// Globally enable/disable buffer reuse, 0 to disable
static void setBufferReuse(int maxBuffers);
/// Globally enable/disable texture reuse, 0 to disable
static void setTextureReuse(int maxTextures);
protected:
std::mutex idLock;
std::unordered_set<GLuint> buffIDs;
std::unordered_set<GLuint> texIDs;
bool shutdown = false;
static int maxCachedBuffers;
static int maxCachedTextures;
}
|
c
| 9 | 0.684049 | 75 | 28 | 45 |
inline
|
func (s *DataMsgServiceServer) DataChanges(stream msg.DataMsgService_DataChangesServer) error {
for {
chng, err := stream.Recv()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
for _, sub := range s.adapter.base.Subscriptions() {
for _, keyPrefix := range sub.KeyPrefixes {
if strings.HasPrefix(chng.Key, keyPrefix) {
sub.ChangeChan <- msg.NewChangeWatchResp(chng, func(err2 error) {
err = stream.Send(&msg.DataChangeReply{Key: chng.Key, OperationType: chng.OperationType,
Result: 0 /*TODO VPP Result*/})
if err != nil {
logrus.DefaultLogger().Error(err) //Not able to propagate it somewhere else
}
})
}
}
}
}
}
|
go
| 26 | 0.636364 | 95 | 26.115385 | 26 |
inline
|
internal byte[] appendEscapeCodes(byte[] buffer)
{
var encodedBuffer = new byte[0].AsEnumerable();
var startIndex = 0;
for(var endIndex=0;endIndex<buffer.Length;endIndex++)
{
if (buffer[endIndex] == Escapecode)
{
encodedBuffer = encodedBuffer.Concat(buffer.Skip(startIndex).Take(endIndex - startIndex));
startIndex = endIndex; //Add the escapecode again, so it occurs twice
}
else if (buffer.Skip(endIndex).Take(Delimiter.Length).SequenceEqual(Delimiter))
{
encodedBuffer = encodedBuffer.Concat(buffer.Skip(startIndex).Take(endIndex - startIndex));
encodedBuffer = encodedBuffer.Concat(new[] { Escapecode });
startIndex = endIndex; //Add delimiter after escapecode
}
else
{
//continue matching
}
}
encodedBuffer = encodedBuffer.Concat(buffer.Skip(startIndex));
return encodedBuffer.ToArray();
}
|
c#
| 19 | 0.691874 | 95 | 33.115385 | 26 |
inline
|
// based on https://docs.saltstack.com/en/develop/ref/states/all/salt.states.pkg.html
/*
{
name: 'ppa:wolfnet/logstash',
dist: 'sid',
file: '/etc/apt/sources.list.d/logstash.list',
keyId: '28B04E4A',
keyServer: 'keyserver.ubuntu.com'
}
*/
const exec = require('./exec')
module.exports = pkgSource
function pkgSource (options) {
const {
name,
keyServer,
keyId
} = options
var command = `add-apt-repository -y "${name}"`
if (keyServer) {
command += ` --keyserver ${keyServer}`
}
// const commands = [command, 'apt update']
return exec({
command,
sudo: true
})
}
|
javascript
| 9 | 0.626623 | 85 | 17.117647 | 34 |
starcoderdata
|
const fs = require('fs');
const path = require('path');
const readdir = require('fs/promises');
const project_dist = path.join(`${__dirname}/project-dist`);
const folder_styles = path.join(`${__dirname}/styles`);
readdir.readdir(folder_styles, {withFileTypes: true}).then(files => {
for (let file of files) {
let ext_name = path.extname(file.name);
if (ext_name === '.css') {
let read_file = new fs.createReadStream(`${__dirname}/styles/${file.name}`, {encoding: 'utf-8'});
read_file.on('data', (data) => fs.appendFile(
`${project_dist}/bundle.css`,
`\n${data}`,
'utf8',
(err) => {
if (err) throw err;
console.log('Done');
}
));
}
}
});
|
javascript
| 22 | 0.557221 | 103 | 28.36 | 25 |
starcoderdata
|
/*
* Copyright 2020-present MongoDB, Inc.
*
* 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.
*/
#include
#include "mongocrypt.h"
#include
void
_errexit_mongocrypt (mongocrypt_t *crypt, int line);
#define ERREXIT_MONGOCRYPT(crypt) _errexit_mongocrypt (crypt, __LINE__);
void
_errexit_ctx (mongocrypt_ctx_t *ctx, int line);
#define ERREXIT_CTX(ctx) _errexit_ctx (ctx, __LINE__);
void
_errexit_bson (bson_error_t *error, int line);
#define ERREXIT_BSON(err) _errexit_bson (err, __LINE__);
#define ERREXIT(...) \
do { \
MONGOC_ERROR (__VA_ARGS__); \
abort (); \
} while (0)
void
_log_to_stdout (mongocrypt_log_level_t level,
const char *message,
uint32_t message_len,
void *ctx);
char *
util_getenv (const char *key);
mongocrypt_binary_t *
util_bson_to_bin (bson_t *bson);
typedef struct {
mongocrypt_ctx_t *ctx;
mongoc_collection_t *keyvault_coll;
mongoc_client_t *mongocryptd_client;
mongoc_client_t *collinfo_client;
const char *db_name;
bool trace;
} _state_machine_t;
bool
_state_machine_run (_state_machine_t *state_machine,
bson_t *result,
bson_error_t *error);
bson_t *
util_bin_to_bson (mongocrypt_binary_t *bin);
bson_t *
util_read_json_file (const char *path);
void
args_parse (bson_t *args, int argc, char **argv);
const char *
bson_get_utf8 (bson_t *bson, const char *key, const char *default_value);
const char *
bson_req_utf8 (bson_t *bson, const char *key);
const uint8_t *
bson_get_bin (bson_t *bson, const char *dotkey, uint32_t *len);
const uint8_t *
bson_req_bin (bson_t *bson, const char *dotkey, uint32_t *len);
bson_t *
bson_get_json (bson_t *bson, const char *key);
bson_t *
bson_req_json (bson_t *bson, const char *key);
bool
bson_get_bool (bson_t *bson, const char *key, bool default_value);
|
c
| 7 | 0.65408 | 75 | 24.936842 | 95 |
starcoderdata
|
package syncelevators
import (
"fmt"
"strconv"
"time"
. "../config"
"../networkCommunication/peers"
)
type SyncChannels struct {
UpdateQueue chan [NumElevators]Elev
UpdateSync chan Elev
OrderUpdate chan Keypress
OnlineElevators chan [NumElevators]bool
IncomingMsg chan Message
OutgoingMsg chan Message
PeerUpdate chan peers.PeerUpdate
PeerTxEnable chan bool
}
// Synchronise called as goroutine; forwards data to network, synchronises data from network.
func Synchronise(ch SyncChannels, id int) {
var (
registeredOrders [NumFloors][NumButtons - 1]AckList
elevList [NumElevators]Elev
sendMsg Message
recentlyDied [NumElevators]bool
someUpdate bool
offline bool
)
timeout := make(chan bool)
go func() { time.Sleep(1 * time.Second); timeout <- true }()
select {
case initMsg := <-ch.IncomingMsg:
elevList = initMsg.Elevator
registeredOrders = initMsg.RegisteredOrders
someUpdate = true
case <-timeout:
offline = true
}
lostID := -1
reassignTimer := time.NewTimer(5 * time.Second)
broadcastTicker := time.NewTicker(100 * time.Millisecond)
singleModeTicker := time.NewTicker(100 * time.Millisecond)
reassignTimer.Stop()
singleModeTicker.Stop()
for {
if offline {
if elevList[id].Online {
offline = false
reInitTimer := time.NewTimer(1 * time.Second)
REINIT:
for {
select {
case reInitMsg := <-ch.IncomingMsg:
if reInitMsg.Elevator != elevList && reInitMsg.ID != id {
tmpElevator := elevList[id]
elevList = reInitMsg.Elevator
elevList[id] = tmpElevator
someUpdate = true
reInitTimer.Stop()
break REINIT
}
case <-reInitTimer.C:
break REINIT
}
}
}
}
if lostID != -1 {
fmt.Println("ELEVATOR", lostID, "DIED")
recentlyDied[lostID] = true
lostID = -1
}
select {
case newElev := <-ch.UpdateSync:
oldQueue := elevList[id].Queue
if newElev.State == Undefined {
ch.PeerTxEnable <- false
} else if newElev.State != Undefined && elevList[id].State == Undefined {
ch.PeerTxEnable <- true
}
elevList[id] = newElev
elevList[id].Queue = oldQueue
someUpdate = true
case newOrder := <-ch.OrderUpdate:
if newOrder.Finished {
elevList[id].Queue[newOrder.Floor] = [NumButtons]bool{}
someUpdate = true
if newOrder.Btn != BtnInside {
registeredOrders[newOrder.Floor][BtnUp].ImplicitAcks[id] = Finished
registeredOrders[newOrder.Floor][BtnDown].ImplicitAcks[id] = Finished
fmt.Println("We Finished order", newOrder.Btn, "at floor", newOrder.Floor+1)
}
} else {
if newOrder.Btn == BtnInside {
elevList[id].Queue[newOrder.Floor][newOrder.Btn] = true
someUpdate = true
} else {
registeredOrders[newOrder.Floor][newOrder.Btn].DesignatedElevator = newOrder.DesignatedElevator
registeredOrders[newOrder.Floor][newOrder.Btn].ImplicitAcks[id] = Acked
fmt.Println("We acknowledged a new order", newOrder.Btn, "at floor", newOrder.Floor+1)
fmt.Println("\tdesignated to", registeredOrders[newOrder.Floor][newOrder.Btn].DesignatedElevator)
}
}
case msg := <-ch.IncomingMsg:
if msg.ID == id || !elevList[msg.ID].Online || !elevList[id].Online {
continue
} else {
if msg.Elevator != elevList {
tmpElevator := elevList[id]
elevList = msg.Elevator
elevList[id] = tmpElevator
someUpdate = true
}
for elevator := 0; elevator < NumElevators; elevator++ {
if elevator == id || !elevList[msg.ID].Online || !elevList[id].Online {
continue
}
for floor := 0; floor < NumFloors; floor++ {
for btn := BtnUp; btn < BtnInside; btn++ {
switch msg.RegisteredOrders[floor][btn].ImplicitAcks[elevator] {
case NotAcked:
if registeredOrders[floor][btn].ImplicitAcks[id] == Finished {
registeredOrders = copyAckList(msg, registeredOrders, elevator, floor, id, btn)
} else if registeredOrders[floor][btn].ImplicitAcks[elevator] != NotAcked {
registeredOrders[floor][btn].ImplicitAcks[elevator] = NotAcked
}
case Acked:
if registeredOrders[floor][btn].ImplicitAcks[id] == NotAcked {
fmt.Println("Order ", btn, "from ", msg.ID, "in floor", floor+1, "has been acked!")
registeredOrders = copyAckList(msg, registeredOrders, elevator, floor, id, btn)
} else if registeredOrders[floor][btn].ImplicitAcks[elevator] != Acked {
registeredOrders[floor][btn].ImplicitAcks[elevator] = Acked
}
if checkAllAckStatus(elevList, registeredOrders[floor][btn].ImplicitAcks, Acked) &&
!elevList[id].Queue[floor][btn] &&
registeredOrders[floor][btn].DesignatedElevator == id {
fmt.Println("We've been assigned a new order!")
elevList[id].Queue[floor][btn] = true
someUpdate = true
}
case Finished:
if registeredOrders[floor][btn].ImplicitAcks[id] == Acked {
registeredOrders = copyAckList(msg, registeredOrders, elevator, floor, id, btn)
} else if registeredOrders[floor][btn].ImplicitAcks[elevator] != Finished {
registeredOrders[floor][btn].ImplicitAcks[elevator] = Finished
}
if checkAllAckStatus(elevList, registeredOrders[floor][btn].ImplicitAcks, Finished) {
registeredOrders[floor][btn].ImplicitAcks[id] = NotAcked
if registeredOrders[floor][btn].DesignatedElevator == id {
elevList[id].Queue[floor][btn] = false
someUpdate = true
}
}
}
}
}
}
if someUpdate {
ch.UpdateQueue <- elevList
someUpdate = false
}
}
case <-singleModeTicker.C:
for floor := 0; floor < NumFloors; floor++ {
for btn := BtnUp; btn < BtnInside; btn++ {
if registeredOrders[floor][btn].ImplicitAcks[id] == Acked &&
!elevList[id].Queue[floor][btn] {
fmt.Println("We've been assigned a new order!")
elevList[id].Queue[floor][btn] = true
someUpdate = true
}
if registeredOrders[floor][btn].ImplicitAcks[id] == Finished {
registeredOrders[floor][btn].ImplicitAcks[id] = NotAcked
}
}
}
if someUpdate {
ch.UpdateQueue <- elevList
someUpdate = false
}
case <-broadcastTicker.C:
if !offline {
sendMsg.RegisteredOrders = registeredOrders
sendMsg.Elevator = elevList
sendMsg.ID = id
ch.OutgoingMsg <- sendMsg
}
case p := <-ch.PeerUpdate:
fmt.Printf("Peer update:\n")
fmt.Printf(" Peers: %q\n", p.Peers)
fmt.Printf(" New: %q\n", p.New)
fmt.Printf(" Lost: %q\n", p.Lost)
if len(p.Peers) == 0 {
offline = true
singleModeTicker.Stop()
} else if len(p.Peers) == 1 {
singleModeTicker = time.NewTicker(100 * time.Millisecond)
} else {
singleModeTicker.Stop()
}
if len(p.New) > 0 {
newID, _ := strconv.Atoi(p.New)
elevList[newID].Online = true
} else if len(p.Lost) > 0 {
lostID, _ = strconv.Atoi(p.Lost[0])
elevList[lostID].Online = false
if elevList[lostID].Queue != [NumFloors][NumButtons]bool{} && !recentlyDied[lostID] {
reassignTimer.Reset(1 * time.Second)
}
}
var onlineElevators [NumElevators]bool
for elevator := 0; elevator < NumElevators; elevator++ {
onlineElevators[elevator] = elevList[elevator].Online
}
fmt.Println("Online elevators changed: ", onlineElevators)
tmpList := onlineElevators
go func() { ch.OnlineElevators <- tmpList }()
case <-reassignTimer.C:
for elevator := 0; elevator < NumElevators; elevator++ {
if !recentlyDied[elevator] {
continue
}
recentlyDied[elevator] = false
for floor := 0; floor < NumFloors; floor++ {
for btn := BtnUp; btn < BtnInside; btn++ {
if elevList[elevator].Queue[floor][btn] {
elevList[id].Queue[floor][btn] = true
elevList[elevator].Queue[floor][btn] = false
}
}
}
}
ch.UpdateQueue <- elevList
someUpdate = false
}
}
}
|
go
| 27 | 0.642581 | 102 | 29.819231 | 260 |
starcoderdata
|
using UnityEngine;
using System.Collections;
public class Wall : MonoBehaviour {
void OnCollisionEnter(Collision col){
int layer = LayerMask.NameToLayer("Bullet");
if(col.gameObject.layer == layer){
Destroy(col.gameObject);
}
}
}
|
c#
| 13 | 0.672956 | 52 | 23.461538 | 13 |
starcoderdata
|
void OculusVR::OVRBuffer::OnRender()
{
// Switch to eye render target
glBindFramebuffer(GL_FRAMEBUFFER, m_eyeFbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_eyeTexId, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depthBuffer, 0);
glViewport(0, 0, m_eyeTextureSize.w, m_eyeTextureSize.h);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
|
c++
| 7 | 0.736842 | 97 | 42.8 | 10 |
inline
|
/**
* Returns a user facing message re: how long it has been since a current date.
* @usage dateDiff(article_published_at); output examples like ... a year ago || 9 months ago || 1 year ago
*
* @param {function} date a function
* @returns {string} User facing messge holding date diff value and msg.
*/
export const dateDiff = date => {
date = date.split('-');
let today = new Date();
let year = today.getFullYear();
let month = today.getMonth() + 1;
let day = today.getDate();
let yy = parseInt(date[0]);
let mm = parseInt(date[1]);
let dd = parseInt(date[2]);
let years, months, days;
let tag = 'ago';
// months
months = month - mm;
if (day < dd) {
months = months - 1;
}
// years
years = year - yy;
if (month * 100 + day < mm * 100 + dd) {
years = years - 1;
months = months + 12;
}
// days
days = Math.floor(
(today.getTime() - new Date(yy + years, mm + months - 1, dd).getTime()) /
(24 * 60 * 60 * 1000)
);
let response = 'problem using dateDiff';
if (years === 0 && months === 0) {
response = days < 2 ? days + ' day ' + tag : days + ' days ' + tag;
}
if (years === 0 && months >= 0) {
response = months + ' months ' + tag;
}
if (years > 0) {
response = years + ' year ' + tag;
}
if (years === 1) {
response = 'a year ' + tag;
}
return response;
};
|
javascript
| 19 | 0.560351 | 107 | 23.854545 | 55 |
starcoderdata
|
import numpy as np
import os
from segmentation_net import UnetPadded
from utils import unet_pred, CleanPrediction
#LOG = os.path.abspath('./UnetPadded__0.001__4/')
LOG = os.path.join(os.path.dirname(__file__), 'UnetPadded__0.001__4/')
MODEL = UnetPadded(image_size=(212, 212), log=LOG, n_features=4)
MEAN = np.load(os.path.join(os.path.dirname(__file__), 'mean_file.npy'))
def pred_cnn(image, model=MODEL, mean=MEAN):
unet_imag = unet_pred(image, mean, model)['predictions'].astype('uint8')
result = CleanPrediction(unet_imag)
return result
|
python
| 10 | 0.701252 | 76 | 30.055556 | 18 |
starcoderdata
|
package resources
import (
"context"
"fmt"
"github.com/sirupsen/logrus"
"github.com/operator-framework/operator-lifecycle-manager/pkg/api/apis/operators/v1alpha1"
k8sclient "sigs.k8s.io/controller-runtime/pkg/client"
)
func upgradeApproval(ctx context.Context, client k8sclient.Client, ip *v1alpha1.InstallPlan) error {
if ip.Spec.Approved == false && len(ip.Spec.ClusterServiceVersionNames) > 0 {
logrus.Infof("Approving %s resource version: %s", ip.Name, ip.Spec.ClusterServiceVersionNames[0])
ip.Spec.Approved = true
err := client.Update(ctx, ip)
if err != nil {
return fmt.Errorf("error approving installplan: %w", err)
}
}
return nil
}
|
go
| 12 | 0.73503 | 100 | 25.72 | 25 |
starcoderdata
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Push;
use App\Store;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
class PushsController extends Controller
{
public function index()
{
$store = Store::all()->where('email' , Auth::guard('store')->user()->email)->pluck('id');
$pushs=Push::all()->where('Store_id', $store['0']);
foreach ($pushs as &$info)
{
if($info['statue']==1){
$info['statue']='已推播';
}
else{
$info['statue']='未推播';
}
}
return view('managment.push',compact('pushs'));
}
public function create()
{
return view('managment.pushcreate');
}
public function view($id)
{
$push=Push::all()->where('id',$id);
$data=['pushs'=>$push];
return view('managment.pushview',$data);
}
public function store(Request $request)
{
$messsages = array(
'title.required'=>'你必須輸入促銷訊息名稱',
'content.required'=>'你必須輸入促銷訊息內容',
'picture.required'=>'你必須上傳圖片',
'date_start.required'=>'你必須輸入起始日期',
'date_end.required'=>'你必須輸入結束日期',
'time_start.required'=>'你必須輸入起始時間',
'time_end.required'=>'你必須輸入時間',
);
$rules = array(
'title' => 'required',
'content' => 'required',
'picture' => 'required',
'date_start' => 'required',
'date_end' => 'required',
'time_start' => 'required',
'time_end' => 'required',
);
$validator = Validator::make($request->all(), $rules,$messsages);
if ($validator->fails())
{
return redirect()->back()->withErrors($validator->errors());
}
$store = Store::all()->where('email' , Auth::guard('store')->user()->email)->pluck('id');
if ($request->hasFile('picture')) {
$file_name = $request->file('picture')->getClientOriginalName();
$destinationPath = '/public/push';
$request->file('picture')->storeAs($destinationPath,$file_name);
// save new image $file_name to database
// $push->update(['picture' => $file_name]);
Push::create([
'Store_id' => $store['0'],
'title' => $request['title'],
'content' => $request['content'],
'picture' => $file_name,
'date_start' => $request['date_start'],
'date_end' => $request['date_end'],
'time_start' => $request['time_start'],
'time_end' => $request['time_end'],
]);
}
return redirect()->route('pushlist');
}
public function edit($id)
{
$push=Push::all()->where('id',$id);
$data=['pushs'=>$push];
return view('managment.pushedit',$data);
}
public function update(Request $request,$id)
{
$push=Push::find($id);
$push->update($request->all());
if ($request->hasFile('picture')) {
$file_name = $request->file('picture')->getClientOriginalName();
$destinationPath = '/public/push';
$request->file('picture')->storeAs($destinationPath,$file_name);
// save new image $file_name to database
$push->update(['picture' => $file_name]);
}
return redirect()->route('pushlist');
}
public function destroy($id)
{
Push::destroy($id);
return redirect()->route('pushlist');
}
public function changestatue($id){
$push=Push::all()->where('id',$id)->first();
if($push['statue']==0){
$push->update([
'statue'=>1
]);
}
else{
$push->update([
'statue'=>0
]);
}
return redirect()->route('pushlist');
}
public function push(){
}
}
|
php
| 17 | 0.492954 | 98 | 29.413534 | 133 |
starcoderdata
|
public void saveMatchResultFile(int source1Id, int source2Id,
String resultName, String fileName) {
if (source1Id == Source.UNDEF || source2Id == Source.UNDEF
|| resultName == null || fileName == null)
return;
MatchResult result = manager.loadMatchResult(source1Id, source2Id, resultName);
String resultStr = toRDFAlignment(result);
// append result to file if existing other create new file
ExportUtil.writeToFile(fileName, resultStr, true);
}
|
java
| 10 | 0.730526 | 81 | 45.7 | 10 |
inline
|
package com.devonfw.module.httpclient.common.impl.rest;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import com.devonfw.module.httpclient.common.impl.ServiceClientHttpAdapter;
import com.devonfw.module.service.common.api.client.async.ServiceClientInvocation;
import com.devonfw.module.service.common.api.client.async.ServiceClientStub;
import com.devonfw.module.service.common.api.client.context.ServiceContext;
import com.devonfw.module.service.common.base.client.async.ServiceClientInvocationImpl;
/**
* Implementation of {@link ServiceClientStub} and {@link InvocationHandler} that acts as dynamic proxy for service API
* to capture {@link ServiceClientInvocation}s.
*
* @param type of the {@link ServiceContext#getApi() service API}.
* @since 2021.04.003
*/
public class SyncServiceClientStub implements InvocationHandler {
private final ServiceContext context;
private final ServiceClientHttpAdapter adapter;
private final String baseUrl;
private S proxy;
/**
* The constructor.
*
* @param context the {@link ServiceContext}.
* @param adapter the {@link ServiceClientHttpAdapter}.
* @param baseUrl the discovered and resolved base URL of the service to invoke.
*/
protected SyncServiceClientStub(ServiceContext context, ServiceClientHttpAdapter adapter, String baseUrl) {
super();
this.context = context;
this.adapter = adapter;
this.baseUrl = baseUrl;
}
@Override
public Object invoke(Object instance, Method method, Object[] args) throws Throwable {
Class declaringClass = method.getDeclaringClass();
if (declaringClass == Object.class) {
switch (method.getName()) {
case "toString":
return "ServiceClient for " + this.context.getApi().getName();
case "getClass":
return this.context.getApi();
case "hashCode":
return Integer.valueOf(hashCode());
case "equals":
if ((args != null) && (args.length == 1) && (args[0] == instance)) {
return Boolean.TRUE;
}
return Boolean.FALSE;
}
return null;
}
long startTime = System.nanoTime();
ServiceClientInvocation invocation = new ServiceClientInvocationImpl<>(method, args, this.context);
HttpRequest request = this.adapter.createRequest(invocation, this.baseUrl);
HttpResponse response = this.adapter.getHttpClient().send(request, BodyHandlers.ofString());
Object result = this.adapter.handleResponse(response, startTime, invocation);
return result;
}
/**
* @return the dynamic proxy.
*/
public S get() {
return this.proxy;
}
/**
* @param type of the {@link ServiceContext#getApi() service API}.
* @param context the {@link ServiceContext}.
* @param adapter the {@link ServiceClientHttpAdapter}.
* @param baseUrl the discovered and resolved base URL of the service to invoke.
* @return the {@link SyncServiceClientStub}.
*/
@SuppressWarnings("unchecked")
public static SyncServiceClientStub of(ServiceContext context, ServiceClientHttpAdapter adapter,
String baseUrl) {
SyncServiceClientStub stub = new SyncServiceClientStub<>(context, adapter, baseUrl);
Class interfaces = new Class { context.getApi() };
stub.proxy = (S) Proxy.newProxyInstance(adapter.getClassLoader(), interfaces, stub);
return stub;
}
}
|
java
| 17 | 0.712813 | 119 | 34.196078 | 102 |
starcoderdata
|
using Newtonsoft.Json;
namespace ASoft.BattleNet.Starcraft2.Models.Profile
{
public sealed class ProfileSnapshot
{
[JsonConstructor]
public ProfileSnapshot(ProfileSeasonSnapshot seasonSnapshot, int totalRankedSeasonGamesPlayed)
{
SeasonSnapshot = seasonSnapshot;
TotalRankedSeasonGamesPlayed = totalRankedSeasonGamesPlayed;
}
public ProfileSeasonSnapshot SeasonSnapshot { get; }
public int TotalRankedSeasonGamesPlayed { get; }
}
}
|
c#
| 10 | 0.717082 | 102 | 27.1 | 20 |
starcoderdata
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TaskManager.Utils.BaseService.Monitor.Model;
using TaskManager.Utils.BaseService.Monitor.SystemRuntime;
using TaskManager.Utils.BaseService.Monitor.SystemRuntime.BatchQueues;
namespace TaskManager.Utils.BaseService.Monitor
{
public class TimeWatchHelper
{
static TimeWatchLogBatchQueue timewatchlogbatchqueue;
static TimeWatchLogApiBatchQueue timewatchlogapibatchqueue;
static TimeWatchHelper()
{
timewatchlogbatchqueue = new TimeWatchLogBatchQueue();
timewatchlogapibatchqueue = new TimeWatchLogApiBatchQueue();
}
public static void AddTimeWatchLog(TimeWatchLogInfo log)
{
if (TaskManager.Utils.Common.ConfigHelper.IsWriteTimeWatchLog && TaskManager.Utils.Common.ConfigHelper.IsWriteTimeWatchLogToMonitorPlatform)
{
try
{
timewatchlogbatchqueue.Add(log);
}
catch (Exception exp)
{
TaskManager.Utils.Log.ErrorLog.Write("耗时日志出错",exp);
}
}
}
public static void AddTimeWatchApiLog(TimeWatchLogApiInfo log)
{
if (TaskManager.Utils.Common.ConfigHelper.IsWriteTimeWatchLog && TaskManager.Utils.Common.ConfigHelper.IsWriteTimeWatchLogToMonitorPlatform)
{
try
{
timewatchlogapibatchqueue.Add(log);
//timewatchlogbatchqueue.Add(new TimeWatchLogInfo()
//{
// fromip = log.fromip,
// logcreatetime = log.logcreatetime,
// logtag = log.url.GetHashCode(),
// url=log.url,
// time = log.time,
// sqlip = "",
// remark = log.tag,
// projectname = log.projectname,
// msg = log.msg,
// logtype = (int)EnumTimeWatchLogType.ApiUrl
//});
}
catch (Exception exp)
{
TaskManager.Utils.Log.ErrorLog.Write("耗时日志api出错", exp);
}
}
}
}
}
|
c#
| 18 | 0.551356 | 152 | 35.878788 | 66 |
starcoderdata
|
def get_loglikelihood(self, p, actions):
'''
Inputs:
- p, batch of probability tensors
- actions, the actions taken
'''
try:
if len(actions)>1:
actions = actions[:,0]
dist = torch.distributions.categorical.Categorical(p)
return dist.log_prob(actions)
except Exception as e:
raise ValueError("Numerical error")
|
python
| 11 | 0.540793 | 65 | 32.076923 | 13 |
inline
|
package com.flowci.core.config.domain;
import com.flowci.domain.SimpleAuthPair;
import com.flowci.util.StringHelper;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.springframework.data.mongodb.core.mapping.Document;
@Getter
@Setter
@Accessors(chain = true)
@Document(collection = "configuration")
public class SmtpConfig extends Config {
public enum SecureType {
NONE,
SSL,
TLS,
}
private String server;
private Integer port;
private SecureType secure = SecureType.NONE;
private SimpleAuthPair auth;
public SmtpConfig() {
setCategory(Category.SMTP);
}
}
|
java
| 9 | 0.717037 | 62 | 17.75 | 36 |
starcoderdata
|
package auth
import (
"context"
"github.com/deepsourcelabs/cli/deepsource/auth"
"github.com/deepsourcelabs/graphql"
)
type RequestPATParams struct {
DeviceCode string `json:"deviceCode"`
Description string `json:"description"`
}
type RequestPATRequest struct {
Params RequestPATParams
}
// GraphQL mutation to request JWT
const requestPATMutation = `
mutation request($input:RequestPATWithDeviceCodeInput!) {
requestPatWithDeviceCode(input:$input) {
token
expiry
user {
email
}
}
}`
type RequestPATResponse struct {
auth.PAT `json:"requestPatWithDeviceCode"`
}
func (r RequestPATRequest) Do(ctx context.Context, client IGQLClient) (*auth.PAT, error) {
req := graphql.NewRequest(requestPATMutation)
req.Header.Set("Cache-Control", "no-cache")
req.Var("input", r.Params)
var res RequestPATResponse
if err := client.GQL().Run(ctx, req, &res); err != nil {
return nil, err
}
return &res.PAT, nil
}
|
go
| 10 | 0.735263 | 90 | 19.282609 | 46 |
starcoderdata
|
package com.mskmz.catmvvm.catrvdemo;
import android.view.View;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.mskmz.catmvvm.core.v.CatActivity;
import com.mskmz.catmvvm.databinding.ActivityRvBinding;
public class RvActivity extends CatActivity {
ObservableList list;
RvItemModel a = new RvItemModel("7");
@Override
protected void init() {
super.init();
list = new ObservableArrayList<>();
getDb().rvShow.setAdapter(new RvAdapter(list));
getDb().rvShow.setLayoutManager(new LinearLayoutManager(this));
list.add(new RvItemModel("1"));
list.add(new RvItemModel("2"));
list.add(new RvItemModel("3"));
list.add(new RvItemModel("4"));
list.add(new RvItemModel("5"));
list.add(new RvItemModel("6"));
list.add(a);
list.add(new RvItemModel("8"));
getDb().btnLog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
list.remove(5);
a.str = "9";
a.notifyChange();
}
});
}
}
|
java
| 15 | 0.636148 | 71 | 29.902439 | 41 |
starcoderdata
|
package cn.jackbin.SimpleRecord.mapper;
import cn.jackbin.SimpleRecord.entity.RoleDO;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Repository;
import java.util.Date;
import java.util.List;
/**
*
* Mapper 接口
*
*
* @author jackbin
* @since 2020-07-21
*/
@Repository
public interface RoleMapper extends BaseMapper {
List queryByUserId(Long userId);
int queryTotal(String name, Boolean deleted, Date date);
List queryByPage(String name, Boolean deleted, Date date, int begin, int end);
void notDelete(Long id);
}
|
java
| 7 | 0.73913 | 90 | 22 | 27 |
starcoderdata
|
private void HandleOwnerLoaded(object sender, RoutedEventArgs e)
{
if (null == _page) // Don't want to attach to BackKeyPress twice
{
InitializeRootVisual();
if (null != _rootVisual)
{
_page = _rootVisual.Content as PhoneApplicationPage;
if (_page != null)
{
_page.BackKeyPress += new EventHandler<CancelEventArgs>(HandlePageBackKeyPress);
SetBinding(ApplicationBarMirrorProperty, new Binding { Source = _page, Path = new PropertyPath("ApplicationBar") });
}
}
}
}
|
c#
| 21 | 0.482711 | 140 | 43.3125 | 16 |
inline
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.