code
stringlengths 0
29.6k
| language
stringclasses 9
values | AST_depth
int64 3
30
| alphanumeric_fraction
float64 0.2
0.86
| max_line_length
int64 13
399
| avg_line_length
float64 5.02
139
| num_lines
int64 7
299
| source
stringclasses 4
values |
---|---|---|---|---|---|---|---|
<?php
namespace App\Business;
use App\Event;
use App\Utils\ValidatorUtil;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
class EventBusiness{
public function getById($id){
try {
$event = Event::with('state')->with('chef')->with('dishes')->find($id);
return $event;
} catch (\Exception $e) {
throw $e;
}
}
public function getByChef($id_chef){
try {
$event = Event::where('id_chef',$id_chef)->with('state')
->with('dishes')->get();
return $event;
} catch (\Exception $e) {
throw $e;
}
}
public function create($event){
$this->validate($event);
return $event->create($event->toArray());
}
public function update($event){
$event->save();
return $event;
}
public function delete($id){
try {
$event = Event::findOrFail($id)->delete();
} catch (\Exception $e) {
throw $e;
}
}
public function getEvent(){
try {
return Event::with('chef')->with('dishes')->get();
} catch (\Exception $e) {
throw $e;
}
}
public function addFoodDish($id,$foodDish){
DB::insert('INSERT INTO food_dish_x_event(id_dish, id_event) VALUES(?,?)',[$foodDish->id,$id]);
}
public function validate($event){
if(ValidatorUtil::isBlank($event->id_state)){
throw new \Exception("No se especifica el estado");
}
if(ValidatorUtil::isBlank($event->id_chef)){
throw new \Exception("chef vacio");
}
if(ValidatorUtil::isBlank($event->image_url)){
throw new \Exception("image_url vacio");
}
if(ValidatorUtil::isBlank($event->name)){
throw new \Exception("name vacio");
}
if(ValidatorUtil::isBlank($event->description)){
throw new \Exception("description");
}
if(ValidatorUtil::isBlank($event->price)){
throw new \Exception("precio vacio");
}
if(ValidatorUtil::isBlank($event->lat_addr)){
throw new \Exception("lat_addr vacio");
}
if(ValidatorUtil::isBlank($event->lon_addr)){
throw new \Exception("lon_addr");
}
if(ValidatorUtil::isBlank($event->address)){
throw new \Exception("address vacio");
}
}
}
|
php
| 16 | 0.502115 | 103 | 25.540816 | 98 |
starcoderdata
|
import React from 'react';
import { Link } from 'gatsby';
import { ReactComponent as NotFoundTitle } from '../assets/svg/404-title.svg';
import { ReactComponent as NotFoundIllustration } from '../assets/svg/404-illustration.svg';
import pagesStyles from './404.module.css';
const NotFound = () => (
<div className={pagesStyles.page}>
<NotFoundTitle className={pagesStyles.title} />
<p className={pagesStyles.description}>
Diving bell has reached the unexplored trenches!
<br />
<Link to="/">Return to the surface?
<NotFoundIllustration className={pagesStyles.illustration} />
);
export default NotFound;
|
javascript
| 11 | 0.698341 | 92 | 33.894737 | 19 |
starcoderdata
|
public static AccessControlProvider newInstance(RepositoryConfig config) throws RepositoryException {
String className = getProviderClass(config);
if (className != null) {
try {
Class<?> acProviderClass = Class.forName(className);
if (AccessControlProvider.class.isAssignableFrom(acProviderClass)) {
AccessControlProvider acProvider = (AccessControlProvider) acProviderClass.newInstance();
acProvider.init(config);
return acProvider;
} else {
throw new RepositoryException("Fail to create AccessControlProvider from configuration.");
}
} catch (Exception e) {
throw new RepositoryException("Fail to create AccessControlProvider from configuration.");
}
}
// ac not supported in this setup.
throw new UnsupportedRepositoryOperationException("Access control is not supported");
}
|
java
| 14 | 0.753278 | 101 | 39 | 21 |
inline
|
@Override
public void setX(int mX) {
// if (controltype.control()) {
//
// int n = getX() - mX;
//
// if (n > 0) {
// if (mX > 70) {
// this.x = mX;
// }
// } else if (n < 0) {
// if (mX < 870) {
//
// this.x = mX;
// }
// }
// } else {
//
// this.x = mX;
// }
//// this.x = mX;
this.x = mX;
}
|
java
| 6 | 0.246939 | 38 | 19.458333 | 24 |
inline
|
/*
Copyright © 2019 https://saltedge.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package com.saltedge.sdk.sample.features;
import android.app.Activity;
import android.text.InputType;
import android.widget.EditText;
import androidx.appcompat.app.AlertDialog;
public class InputValueDialogHelper {
public static void showInputValueDialog(Activity activity, final String inputFieldKey, final InputValueResult callback){
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Enter " + inputFieldKey);
final EditText input = new EditText(activity);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton(android.R.string.ok, (dialog, which) -> {
String enteredText = input.getText().toString();
callback.inputValueResult(inputFieldKey, enteredText);
});
builder.setNegativeButton(android.R.string.cancel, null);
builder.show();
}
}
|
java
| 15 | 0.760359 | 124 | 41.617021 | 47 |
starcoderdata
|
//
// UIScrollView+QMRefreshFooter.h
// CaiFair_Mine
//
// Created by edz on 2019/10/28.
// Copyright © 2019 edz. All rights reserved.
//
#import
NS_ASSUME_NONNULL_BEGIN
@interface UIScrollView (QMRefreshFooter)
@property (nonatomic, assign) NSInteger currentPageCount;
@end
NS_ASSUME_NONNULL_END
|
c
| 9 | 0.761671 | 83 | 19.35 | 20 |
starcoderdata
|
public bool Set(RedisKey key, RedisValue val)
{
if (StringsDictionary.ContainsKey(key))
StringsDictionary.Remove(key);
StringsDictionary.Add(key, val);
return true; // TODO: NX, XX -> bool
}
|
c#
| 9 | 0.553846 | 51 | 28 | 9 |
inline
|
package name.aliaksandrch.px.responses;
import com.google.gson.annotations.SerializedName;
import name.aliaksandrch.px.beans.Photo;
import java.io.Serializable;
import java.util.List;
public class PhotosResponse implements Serializable{
@SerializedName("feature")
private String feature;
@SerializedName("current_page")
private int currentPage;
@SerializedName("total_page")
private int totalPages;
@SerializedName("total_items")
private int totalItems;
@SerializedName("photos")
private List photos;
public String getFeature() {
return feature;
}
public void setFeature(String feature) {
this.feature = feature;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getTotalPages() {
return totalPages;
}
public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
}
public int getTotalItems() {
return totalItems;
}
public void setTotalItems(int totalItems) {
this.totalItems = totalItems;
}
public List getPhotos() {
return photos;
}
public void setPhotos(List photos) {
this.photos = photos;
}
}
|
java
| 6 | 0.670183 | 74 | 19.911765 | 68 |
starcoderdata
|
/**
* SyntaxHighlighter 2.0 brush for Lisp.
* 2009-10-14,
* http://blog.knuthaugen.no/
*
* Based on the 1.5 brush by at http://han9kin.doesntexist.com/
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
* Suite 330, Boston, MA 02111-1307 USA
*/
SyntaxHighlighter.brushes.Lisp = function(){
var funcs = 'lambda list progn mapcar car cdr reverse member append format';
var keywords = 'let while unless cond if eq t nil defvar dotimes setf listp numberp not equal';
var macros = 'loop when dolist dotimes defun';
var operators = '> < + - = * / %';
this.regexList = [
{ regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' },
{ regex: new RegExp('&\\w+;', 'g'), css: 'plain' },
{ regex: new RegExp(';.*', 'g'), css: 'comments' },
{ regex: new RegExp("'(\\w|-)+", 'g'), css: 'variable' },
{ regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' },
{ regex: new RegExp(this.getKeywords(macros), 'gm'), css: 'keyword' },
{ regex: new RegExp(this.getKeywords(funcs), 'gm'), css: 'functions' },
];
}
SyntaxHighlighter.brushes.Lisp.prototype = new SyntaxHighlighter.Highlighter();
SyntaxHighlighter.brushes.Lisp.aliases = ['lisp'];
|
javascript
| 12 | 0.676629 | 111 | 45.386364 | 44 |
starcoderdata
|
namespace GameTop
{
public class JogoFODA
{
private readonly iJogador _jogadorA;
private readonly iJogador _jogadorB;
public JogoFODA(iJogador jogadorA, iJogador jogadorB)
{
_jogadorA = jogadorA;
_jogadorB = jogadorB;
}
public void IniciarJogo()
{
System.Console.Write(_jogadorA.Corre());
System.Console.Write(_jogadorA.Chuta());
System.Console.Write(_jogadorA.Passe());
System.Console.Write("\n PRÓXIMO JOGADOR \n");
System.Console.Write(_jogadorB.Corre());
System.Console.Write(_jogadorB.Chuta());
System.Console.Write(_jogadorB.Passe());
}
}
}
|
c#
| 13 | 0.568306 | 61 | 28.32 | 25 |
starcoderdata
|
package com.wishes.market.service.impl;
import com.wishes.market.config.CommConfig;
import com.wishes.market.config.StringConstant;
import com.wishes.market.mapper.CommentMapper;
import com.wishes.market.mapper.UserDoMapperExt;
import com.wishes.market.model.*;
import com.wishes.market.service.UserService;
import com.wishes.market.utils.PageDto;
import com.wishes.market.utils.security.AESTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* 用户Service实现类
*/
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class UserServiceImpl implements UserService {
@Autowired(required = false)
private UserDoMapperExt userDoMapperExt;
@Resource
private CommentMapper commentMapper;
@Override
public String login(UserDo user) {
String account = user.getAccount();
String password = user.getPassword();
if (StringUtils.isBlank(account)
|| StringUtils.isBlank(password)) {
return null;
} else {
//构造查询条件
UserDoExample example = new UserDoExample();
UserDoExample.Criteria criteria = example.createCriteria();
//查询数据库
criteria.andAccountEqualTo(account);
criteria.andIsDeletedEqualTo(CommConfig.IS_DELETE.NO.getType());
List userInDb = userDoMapperExt.selectByExample(example);
if (!CollectionUtils.isEmpty(userInDb)) {
String passInDb = userInDb.get(0).getPassword();
Long uid = userInDb.get(0).getId();
String userName = userInDb.get(0).getUname();
//AES加密输入密码,并校对
try {
String encryptPwdStr = AESTool.encrypt(password,
CommConfig.MARKET_KEY);
if (passInDb.equals(encryptPwdStr)) {
// TODO: 2019/1/24 可能要做一些持久化鉴权操作
// 先不做了算了!
return uid + "," + StringConstant.LOGIN_SUCCESS + "," + userName;
}
} catch (Exception e) {
e.printStackTrace();
log.error("登陆失败!" + e);
}
}
}
return null;
}
@Override
public String register(UserDo user) {
String account = user.getAccount();
String password = user.getPassword();
String userName = user.getUname();
//获取用户昵称
if (StringUtils.isBlank(userName)) {
user.setUname("新注册用户" + System.currentTimeMillis());
}
if (StringUtils.isBlank(account)
|| StringUtils.isBlank(password)) {
return null;
} else {
//构造查询条件
UserDoExample example = new UserDoExample();
UserDoExample.Criteria criteria = example.createCriteria();
//查询数据库
criteria.andAccountEqualTo(account);
criteria.andIsDeletedEqualTo(CommConfig.IS_DELETE.NO.getType());
List userInDb = userDoMapperExt.selectByExample(example);
if (!CollectionUtils.isEmpty(userInDb)) {
return StringConstant.REGISTER_FAIL_REASON_DUPLICATE_ACCOUNT;
} else {
//将密码进行加密
try {
password = AESTool.encrypt(password, CommConfig.MARKET_KEY);
user.setPassword(password);
//存入数据库
userDoMapperExt.insertSelective(user);
return StringConstant.REGISTER_SUCCESS;
} catch (Exception e) {
e.printStackTrace();
log.error("注册失败!" + e);
}
}
}
return null;
}
/**
* 修改密码、昵称等用户数据
*
* @param user 用户信息
* @return true/false 成功/失败
*/
@Override
public boolean modifyUserInfo(UserDo user) {
return userDoMapperExt.updateByPrimaryKeySelective(user) > 0;
}
@Override
public UserDo getUserInfoByUid(Long uId) {
return userDoMapperExt.selectByPrimaryKey(uId);
}
@Override
public void logout(Integer uid) {
}
@Override
public boolean isExistUser(Long uid) {
return userDoMapperExt.selectByPrimaryKey(uid) != null;
}
@Override
public boolean isExistUser(String account) {
if (StringUtils.isBlank(account)) {
return false;
}
UserDoExample example = new UserDoExample();
UserDoExample.Criteria criteria = example.createCriteria();
//构造查询条件
criteria.andAccountEqualTo(account);
criteria.andIsDeletedEqualTo(CommConfig.IS_DELETE.NO.getType());
List user = userDoMapperExt.selectByExample(example);
return !CollectionUtils.isEmpty(user);
}
@Override
public String insertComment(Comment comment) {
int insert = commentMapper.insert(comment);
if (insert > 0) {
return "succeed";
}
return null;
}
@Override
public String removeComment(Long commentId) {
int delete = commentMapper.deleteByPrimaryKey(commentId);
if (delete > 0) {
return "succeed";
}
return null;
}
@Override
public List searchComment(Long postId) {
return commentMapper.queryComments(postId);
}
@Override
public Long getCommentNumber(Long commodityId) {
return commentMapper.queryCommentNumber(commodityId);
}
@Override
public List getUserInfos(int start, int offset) {
return userDoMapperExt.getUserInfos(start,offset);
}
@Override
public CommConfig.CODES deleteUserInfo(Long id) {
UserDoExample example = new UserDoExample();
UserDoExample.Criteria criteria = example.createCriteria();
//构造查询条件
criteria.andIsDeletedEqualTo(CommConfig.IS_DELETE.NO.getType());
criteria.andIdEqualTo(id);
//获取查询结果
List userList = userDoMapperExt.selectByExample(example);
if (CollectionUtils.isEmpty(userList)) {
//如果结果集为空,则返回目标信息未找到
return CommConfig.CODES.TARGET_NOT_FOUND;
} else {
//因为根据Id定位的数据肯定只有1条或0条,所以这里直接get(0)
UserDo userDo = userList.get(0);
userDoMapperExt.deleteByPrimaryKey(userDo);
return CommConfig.CODES.SUCCESS;
}
}
@Override
public boolean editUser(UserDo userDo) {
userDoMapperExt.updateByPrimaryKey(userDo);
return true;
}
@Override
public PageDto searchCommentBack(int limit, int page) {
//计算起始值和步长
int start = limit * (page - 1);
int offset = limit;
//计算总数
int total = Math.toIntExact(commentMapper.queryCommentNumberBack());
PageDto commentPageDto = new PageDto<>(page, limit, total);
List list = commentMapper.queryCommentsBack(start, offset);
commentPageDto.setLists(list);
return commentPageDto;
}
@Override
public Set getUsersByUidList(Set userIds) {
if (userIds == null || userIds.isEmpty()){
return null;
}
ArrayList userList = new ArrayList<>(userIds);
List usersByUidList = userDoMapperExt.getUsersByUidList(userList);
if (usersByUidList == null || usersByUidList.isEmpty()){
return null;
}
return new HashSet<>(usersByUidList);
}
}
|
java
| 19 | 0.611027 | 89 | 30.328063 | 253 |
starcoderdata
|
package wasm.core.instruction.control;
import wasm.core.exception.Check;
import wasm.core.instruction.Instruction;
import wasm.core.instruction.Operate;
import wasm.core.model.Dump;
import wasm.core.structure.ControlFrame;
import wasm.core.structure.ModuleInstance;
import wasm.core.structure.WasmReader;
import wasm.core.model.index.LabelIndex;
public class Br implements Operate {
@Override
public Dump read(WasmReader reader) {
return reader.readLabelIndex();
}
@Override
public void operate(ModuleInstance mi, Dump args) {
Check.requireNonNull(args);
Check.require(args, LabelIndex.class);
int index = ((LabelIndex) args).intValue();
for (int i = 0; i < index; i++) {
mi.popFrame();
}
ControlFrame frame = mi.topFrame();
if (frame.instruction != Instruction.LOOP) {
mi.exitBlock();
} else {
mi.resetBlock(frame);
frame.pc = 0;
}
}
}
|
java
| 8 | 0.650778 | 55 | 24.7 | 40 |
starcoderdata
|
module.exports = [
{
_id: Math.round(Math.random() * 1000000),
body: "Hey, my name's Pingal. I'm an AI superconnector. I'd love to connect you to some of my friends that you'd click with. I have a lot of friends- 7,365,415 in fact. So, I'm sure I know some people you' ll love :) So, I can get to know you better, can you tell me what you're interested in right now",
timestamp: new Date(Date.UTC(2016, 1, 30, 17, 19, 0)),
user: {
_id: 1,
name: 'Pingal',
hash: 'Pingal',
},
/*
location: {
latitude: 48.864601,
longitude: 2.398704
},
*/
},
{
_id: Math.round(Math.random() * 1000000),
body: "Hey, I'm Bob. I'm interested in a lot of different kinds of stuff ...",
timestamp: new Date(Date.UTC(2017, 1, 30, 17, 20, 0)),
user: {
_id: 2,
name: 'Bob',
hash: 'Bob',
},
},
{
_id: Math.round(Math.random() * 1000000),
body: "Awesome, nice to meet you Bob. In case you need some ideas, here's some things other people are interested in right now.",
channels: [{'topic': 'tea', 'topic_id': 'room:1:15'},{'topic': 'tech', 'topic_id': 'room:1:16'}, {'topic': 'science', 'topic_id': 'room:1:17'}, {'topic': 'frisbee', 'topic_id': 'room:1:18'}, {'topic': 'superbowl', 'topic_id': 'room:1:19'}],
timestamp: new Date(Date.UTC(2017, 1, 30, 17, 21, 0)),
user: {
_id: 1,
name: 'Pingal',
hash: 'Pingal',
},
},
];
|
javascript
| 11 | 0.565038 | 308 | 35.325 | 40 |
starcoderdata
|
'use strict';
const Boom = require('boom');
const Flow = require('../../../models/flow.model');
module.exports = (request, reply) => {
return Flow.deleteByName(request.params.name, (err, flow, metrics) => {
request.addMetrics(metrics);
if (err) {
return reply(Boom.badRequest('ES Request error'));
}
return reply();
});
};
|
javascript
| 15 | 0.578283 | 75 | 22.294118 | 17 |
starcoderdata
|
from clang.cindex import Index, TranslationUnit
from bears.c_languages.ClangBear import clang_available, ClangBear
from coalib.bears.GlobalBear import GlobalBear
class ClangASTPrintBear(GlobalBear):
check_prerequisites = classmethod(clang_available)
LANGUAGES = ClangBear.LANGUAGES
REQUIREMENTS = ClangBear.REQUIREMENTS
def print_node(self, cursor, filename, before='', spec_before=''):
'''
Prints this node and all child nodes recursively in the style of:
::
-node
|-child
`-another child
|- child of child
`- last child of child
:param cursor: The node to print. (Clang cursor.)
:param before: What to print before the node.
:param spec_before: What to print before this node but to replace with
spaces for child nodes.
'''
file = cursor.location.file
if file is not None and file.name == filename:
self.debug(
before + spec_before + '-' + str(cursor.displayname),
str(cursor.kind),
'Lines',
str(cursor.extent.start.line) + '-' +
str(cursor.extent.end.line),
'(' + ' '.join(str(token.spelling)
for token in cursor.get_tokens()) + ')')
children = list(cursor.get_children())
if len(children) > 0:
for child in children[:-1]:
self.print_node(child,
filename,
before + len(spec_before)*' ' + '|')
self.print_node(children[-1],
filename,
before + len(spec_before)*' ',
'`')
def run(self):
"""
This bear is meant for debugging purposes relating to clang. It just
prints out the whole AST for a file to the DEBUG channel.
"""
for filename, file in sorted(self.file_dict.items()):
root = Index.create().parse(
filename,
options=TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD
).cursor
self.print_node(root, filename)
|
python
| 17 | 0.5262 | 78 | 33.938462 | 65 |
starcoderdata
|
def generate_anon_user_password(self, length, segments,
chars, separator='-'):
"""Generates a random password of a nominated length and number
of segments, composed entirely of characters in chars.
The separator is placed in between segments.
"""
new_password = ""
segment_lengths = split_posint_rand(length, segments)
# For every segment...
for i in range (0, len(segment_lengths)):
# Pick some letters for the password
for j in range(0, segment_lengths[i]):
new_password = ''.join(
[new_password, secrets.choice(chars)])
# Finish the segments with a separator
new_password = ''.join([new_password, separator])
# Return the password sans the extra separator
return new_password.rstrip(separator)
|
python
| 14 | 0.589026 | 72 | 43.7 | 20 |
inline
|
def multivariateGrid(col_x, col_y, col_k, df, k_is_color=False, scatter_alpha=.5):
def colored_scatter(x, y, c=None):
def scatter(*args, **kwargs):
args = (x, y)
if c is not None:
kwargs['c'] = c
kwargs['alpha'] = scatter_alpha
plt.scatter(*args, **kwargs)
return scatter
g = sns.JointGrid(
x=col_x,
y=col_y,
data=df
)
color = None
legends = []
for name, df_group in df.groupby(col_k):
legends.append(name)
if k_is_color:
color = name
g.plot_joint(
colored_scatter(df_group[col_x], df_group[col_y], color),
)
sns.distplot(
df_group[col_x].values,
ax=g.ax_marg_x,
color=color,
)
sns.distplot(
df_group[col_y].values,
ax=g.ax_marg_y,
color=color,
vertical=True
)
# Do also global Hist:
sns.distplot(
df[col_x].values,
ax=g.ax_marg_x,
color='grey'
)
sns.distplot(
df[col_y].values.ravel(),
ax=g.ax_marg_y,
color='grey',
vertical=True
)
plt.tight_layout()
plt.xlabel(r'$x_1$', fontsize=14)
plt.ylabel(r'$x_2$', fontsize=14, rotation=0)
plt.legend(legends, fontsize=14, loc='lower left')
plt.grid(alpha=0.3)
# plt.xticks(fontsize=18)
# plt.yticks(fontsize=18)
plt.savefig('data/data.png', dpi=300, bbox_inches="tight")
plt.show()
plt.close()
|
python
| 13 | 0.505148 | 82 | 25.810345 | 58 |
inline
|
// Copyright (c) 2017 Ubisoft Entertainment
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections.Generic;
using Sharpmake.Generators;
using Sharpmake.Generators.VisualStudio;
namespace Sharpmake
{
public static partial class X360
{
[PlatformImplementation(Platform.x360,
typeof(IPlatformDescriptor),
typeof(IPlatformVcxproj))]
public sealed partial class X360Platform : BaseMicrosoftPlatform
{
#region IPlatformDescriptor
public override string SimplePlatformString => "Xbox 360";
public override bool HasDotNetSupport => false;
#endregion
#region IPlatformVcxproj implementation
public override string PackageFileExtension => "xex";
public override bool IsPcPlatform => false;
public override IEnumerable GetImplicitlyDefinedSymbols(IGenerationContext context)
{
yield return "_XBOX";
}
public override IEnumerable GetLibraryPaths(IGenerationContext context)
{
yield return @"$(Xbox360InstallDir)lib\xbox";
}
public override void SetupPlatformToolsetOptions(IGenerationContext context)
{
context.Options["PlatformToolset"] = FileGeneratorUtilities.RemoveLineTag;
}
public override void SelectCompilerOptions(IGenerationContext context)
{
var options = context.Options;
var conf = context.Configuration;
//X360Options.Compiler.CallAttributedProfiling
// disable CallAttributedProfiling="0"
// fastcap CallAttributedProfiling="1" /fastcap
// callcap CallAttributedProfiling="2" /callcap
context.SelectOption
(
Sharpmake.Options.Option(Options.Compiler.CallAttributedProfiling.Disable, () => { options["X360CallAttributedProfiling"] = "Disabled"; }),
Sharpmake.Options.Option(Options.Compiler.CallAttributedProfiling.Fastcap, () => { options["X360CallAttributedProfiling"] = "Fastcap"; }),
Sharpmake.Options.Option(Options.Compiler.CallAttributedProfiling.Callcap, () => { options["X360CallAttributedProfiling"] = "Callcap"; })
);
//X360Options.Compiler.PreschedulingOptimization
// disable Prescheduling="false"
// enable Prescheduling="true" /Ou
context.SelectOption
(
Sharpmake.Options.Option(Options.Compiler.PreschedulingOptimization.Disable, () => { options["X360Prescheduling"] = "false"; }),
Sharpmake.Options.Option(Options.Compiler.PreschedulingOptimization.Enable, () => { options["X360Prescheduling"] = "true"; })
);
context.SelectOption
(
Sharpmake.Options.Option(Options.ImageConversion.PAL50Incompatible.Disable, () => { options["X360Pal50Incompatible"] = "false"; }),
Sharpmake.Options.Option(Options.ImageConversion.PAL50Incompatible.Enable, () => { options["X360Pal50Incompatible"] = "true"; })
);
Options.Linker.ProjectDefaults projectDefault = Sharpmake.Options.GetObject
if (projectDefault == null)
options["X360ProjectDefaults"] = FileGeneratorUtilities.RemoveLineTag;
else
options["X360ProjectDefaults"] = projectDefault.Value;
Options.ImageConversion.AdditionalSections additionalSections = Sharpmake.Options.GetObject
if (additionalSections == null)
options["X360AdditionalSections"] = FileGeneratorUtilities.RemoveLineTag;
else
options["X360AdditionalSections"] = additionalSections.Value;
// X360Options.Linker.SetChecksum
// enable "true"
// disable "false"
context.SelectOption
(
Sharpmake.Options.Option(Options.Linker.SetChecksum.Enable, () => { options["X360SetChecksum"] = "true"; }),
Sharpmake.Options.Option(Options.Linker.SetChecksum.Disable, () => { options["X360SetChecksum"] = "false"; })
);
}
public override void SelectLinkerOptions(IGenerationContext context)
{
base.SelectLinkerOptions(context);
var outputType = context.Configuration.Output;
if (
outputType != Project.Configuration.OutputType.Dll &&
outputType != Project.Configuration.OutputType.DotNetClassLibrary &&
outputType != Project.Configuration.OutputType.Exe &&
outputType != Project.Configuration.OutputType.DotNetConsoleApp &&
outputType != Project.Configuration.OutputType.DotNetWindowsApp)
{
return;
}
context.Options["ImageXexOutput"] = "$(OutDir)$(TargetName).xex";
Options.Linker.RemotePath remotePath = Sharpmake.Options.GetObject
context.Options["X360RemotePath"] = remotePath != null ? remotePath.Value : FileGeneratorUtilities.RemoveLineTag;
Options.Linker.AdditionalDeploymentFolders additionalDeploymentFolders = Sharpmake.Options.GetObject
if (additionalDeploymentFolders != null)
context.Options["AdditionalDeploymentFolders"] = additionalDeploymentFolders.Value;
Options.Linker.LayoutFile layoutFilepath = Sharpmake.Options.GetObject
context.Options["X360LayoutFile"] = layoutFilepath != null ? layoutFilepath.Value : FileGeneratorUtilities.RemoveLineTag;
}
public override void GenerateProjectConfigurationGeneral2(IVcxprojGenerationContext context, IFileGenerator generator)
{
generator.Write(_projectConfigurationsGeneral2);
}
public override void GenerateProjectCompileVcxproj(IVcxprojGenerationContext context, IFileGenerator generator)
{
generator.Write(_projectConfigurationsCompileTemplate);
}
protected override string GetProjectStaticLinkVcxprojTemplate()
{
return _projectConfigurationsStaticLinkTemplate;
}
protected override string GetProjectLinkSharedVcxprojTemplate()
{
return _projectConfigurationsLinkSharedTemplate;
}
protected override IEnumerable GetIncludePathsImpl(IGenerationContext context)
{
var dirs = new List
dirs.Add(@"$(Xbox360InstallDir)include\xbox");
dirs.AddRange(base.GetIncludePathsImpl(context));
return dirs;
}
#endregion
}
}
}
|
c#
| 19 | 0.607334 | 184 | 48.445783 | 166 |
starcoderdata
|
<div class="container views">
<?php if (isset($messageError)) : ?>
<div class="row">
<div class="alert alert-warning"><?= $messageError ?>
<?php endif; ?>
<div class="row">
<form action="index.php?action=modifierPassword" id="formModifPassword" method="post"
onsubmit="return verifFormPassword(this)">
<input type="hidden" name="token" value="<?= $token ?>">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1"><i class="fas fa-lock">
<input id="password" class="form-control form-control-sm classeMdp"
placeholder="entrez votre mot de passe ici" aria-label="password" type="password" name="password"
maxlength="64" minlength="10" onkeyup="verifPassword(this)" required>
<div class="input-group-append">
<span class="input-group-text"><i class="fas fa-info-circle password" data-toggle="tooltip"
data-placement="right"
title="Cliquez ici pour avoir plus d'infos !">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1"><i class="fas fa-lock">
<input id="passwordBis" class="form-control form-control-sm classeMdp"
placeholder="confirmez votre mot de passe" aria-label="password" type="password"
name="passwordBis" maxlength="64" minlength="10" onkeyup="verifPasswordBis('formModifPassword')"
required>
<button class="btn btn-primary my-2 my-sm-0" aria-label="connexion" type="submit" value="connexion">Envoyer
mon email
<div class='ui fluid hidden helpmessage'>
<div class='header'>
<h3 class='popover-header'>Règles conçernant le pseudonyme et le mot de passe :
<div class='popover-body'>
sur les <i class="fas fa-info-circle pseudo"> du formulaire pour avoir plus d'informations.
<p class='password-popup'><?= $messagePassword ?>
|
php
| 7 | 0.530134 | 120 | 52.183673 | 49 |
starcoderdata
|
using System.Linq;
using Csp.Csp.Model;
using Xunit;
namespace CspUnitTest.Core
{
public class DomainTest
{
private readonly Domain _sut;
public DomainTest()
{
_sut = new Domain new []{ new DummyCspValue("Y"), new DummyCspValue("Z") });
}
[Fact]
public void ShouldPruneAValue()
{
// Setup
var val = new DummyCspValue("Y");
// Act
_sut.Prune(val);
// Verify
Assert.True(!_sut.Values.Exists(v => v.C == val.C));
Assert.True(_sut.Pruned.Exists(v => v.C == val.C));
Assert.True(!_sut.RemovedByGuess.Exists(v => v.C == val.C));
// Act
_sut.RestorePruned();
// Verify
Assert.True(_sut.Values.Exists(v => v.C == val.C));
Assert.True(!_sut.Pruned.Exists(v => v.C == val.C));
Assert.True(!_sut.RemovedByGuess.Exists(v => v.C == val.C));
}
[Fact]
public void ShouldRemoveByGuess()
{
// Setup
var val = new DummyCspValue("Y");
// Act
_sut.Suppose(val);
// Verify
Assert.True(_sut.Values.Exists(v => v.C == val.C));
Assert.True(!_sut.Pruned.Exists(v => v.C == val.C));
Assert.True(!_sut.RemovedByGuess.Exists(v => v.C == val.C));
Assert.True(_sut.RemovedByGuess.Any());
// Act
_sut.RestoreGuess();
// Verfy
Assert.True(_sut.Values.Exists(v => v.C == val.C));
Assert.True(!_sut.Pruned.Exists(v => v.C == val.C));
Assert.True(!_sut.RemovedByGuess.Exists(v => v.C == val.C));
}
[Fact]
public void ShouldShrink()
{
// Setup
var val = new DummyCspValue("Y");
// Act
_sut.Shrink(val);
// Verify
Assert.True(_sut.Values.Exists(v => v.C == val.C));
Assert.False(_sut.Pruned.Any());
Assert.Single(_sut.Values);
Assert.False(_sut.RemovedByGuess.Any());
}
}
}
|
c#
| 18 | 0.457746 | 108 | 26.78481 | 79 |
starcoderdata
|
<?= $this->extend('layouts/frame'); ?>
<?= $this->section('content') ?>
<?php if (session()->has('errordata')):?>
$(document).ready(function(){
$("#addTask-<?php echo session()->getFlashdata('idZgodbe')?>").modal('show');
});
<?php endif; ?>
<div class="container project-box">
<div class="row">
<div class="col-lg-12 card card-header">
<div class="d-flex justify-content-between align-items-center">
<?php if ($niSprinta):?>
Trenutno ni sprinta
<?php else :?>
<?php echo date("d.m.Y", strtotime($sprint['zacetniDatum'])).' - '.date("d.m.Y", strtotime($sprint['koncniDatum'])).' ( '.$sprint['trenutniStatus'].' )' ?>
<?php
$date_now = new DateTime("now", new DateTimeZone('Europe/Ljubljana'));
$sprintend = new DateTime($sprint['koncniDatum']);
if (($date_now>$sprintend) && empty($zgodbeAccReady)): ?>
<a class="btn btn-outline-light gradient-custom-2 me-4" role="button" href="/koncajSprint/<?php echo $sprint['idSprinta']?>">Koncaj Sprint
<?php endif?>
<?php endif?>
<?php if (strpos(session()->get('roles')[session()->get('projectId')], 'S') > -1) { ?>
<a class="btn btn-outline-light gradient-custom-2 me-4" role="button" href="/dodajanjeSprintov">Nov sprint
<?php } ?>
<?php if (!$niSprinta):?>
<div class="d-flex justify-content-between align-items-center">
(v točkah): <?php echo $sprint['hitrost'] ?>
<?php endif?>
<div class="row">
<div class="col-lg-6 card card-header">
teku
<div class="col-lg-6 card card-header">
na sprejem
<div class="row">
<div class="col-lg-6 card card-body">
<?php foreach ($zgodbeInProgress as $zgodbaP): ?>
<?php echo view('partials/storyCard',
['zgodba'=>$zgodbaP, 'uporabniki'=>$uporabniki]) ?>
<?php endforeach; ?>
<div class="col-lg-6 card card-body">
<?php foreach ($zgodbeAccReady as $zgodbaA): ?>
<?php echo view('partials/storyCard',
['zgodba'=>$zgodbaA, 'uporabniki'=>$uporabniki]) ?>
<?php endforeach; ?>
<?= $this->endSection() ?>
|
php
| 18 | 0.50328 | 188 | 36.589041 | 73 |
starcoderdata
|
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from httpx_oauth.clients.google import GoogleOAuth2
import fastapi_users.authentication
from fastapi_users import models
from fastapi_users.fastapi_users import FastAPIUsers
app = FastAPI()
jwt_authentication = fastapi_users.authentication.JWTAuthentication(
secret="", lifetime_seconds=3600
)
cookie_authentication = fastapi_users.authentication.CookieAuthentication(secret="")
users = FastAPIUsers(
# dummy get_user_manager
lambda: None,
[cookie_authentication, jwt_authentication],
models.BaseUser,
models.BaseUserCreate,
models.BaseUserUpdate,
models.BaseUserDB,
)
app.include_router(users.get_verify_router())
app.include_router(users.get_register_router())
app.include_router(users.get_users_router())
app.include_router(users.get_reset_password_router())
app.include_router(
users.get_oauth_router(
GoogleOAuth2(client_id="1234", client_secret="4321"), state_secret="secret"
)
)
app.include_router(users.get_auth_router(jwt_authentication), prefix="/jwt")
app.include_router(users.get_auth_router(cookie_authentication), prefix="/cookie")
@pytest.fixture(scope="module")
def get_openapi_dict():
return app.openapi()
def test_openapi_generated_ok():
assert TestClient(app).get("/openapi.json").status_code == 200
class TestLogin:
def test_jwt_login_status_codes(self, get_openapi_dict):
route = get_openapi_dict["paths"]["/jwt/login"]["post"]
assert list(route["responses"].keys()) == ["200", "400", "422"]
def test_jwt_login_200_body(self, get_openapi_dict):
"""Check if example is up to date."""
example = get_openapi_dict["paths"]["/jwt/login"]["post"]["responses"]["200"][
"content"
]["application/json"]["example"]
assert (
example.keys()
== fastapi_users.authentication.jwt.JWTLoginResponse.schema()[
"properties"
].keys()
)
def test_cookie_login_status_codes(self, get_openapi_dict):
route = get_openapi_dict["paths"]["/cookie/login"]["post"]
assert ["200", "400", "422"] == list(route["responses"].keys())
class TestLogout:
def test_cookie_logout_status_codes(self, get_openapi_dict):
route = get_openapi_dict["paths"]["/cookie/logout"]["post"]
assert list(route["responses"].keys()) == ["200", "401"]
class TestReset:
def test_reset_password_status_codes(self, get_openapi_dict):
route = get_openapi_dict["paths"]["/reset-password"]["post"]
assert list(route["responses"].keys()) == ["200", "400", "422"]
def test_forgot_password_status_codes(self, get_openapi_dict):
route = get_openapi_dict["paths"]["/forgot-password"]["post"]
assert list(route["responses"].keys()) == ["202", "422"]
class TestUsers:
def test_patch_id_status_codes(self, get_openapi_dict):
route = get_openapi_dict["paths"]["/{id}"]["patch"]
assert list(route["responses"].keys()) == [
"200",
"401",
"403",
"404",
"400",
"422",
]
def test_delete_id_status_codes(self, get_openapi_dict):
route = get_openapi_dict["paths"]["/{id}"]["delete"]
assert list(route["responses"].keys()) == ["204", "401", "403", "404", "422"]
def test_get_id_status_codes(self, get_openapi_dict):
route = get_openapi_dict["paths"]["/{id}"]["get"]
assert list(route["responses"].keys()) == ["200", "401", "403", "404", "422"]
def test_patch_me_status_codes(self, get_openapi_dict):
route = get_openapi_dict["paths"]["/me"]["patch"]
assert list(route["responses"].keys()) == ["200", "401", "400", "422"]
def test_get_me_status_codes(self, get_openapi_dict):
route = get_openapi_dict["paths"]["/me"]["get"]
assert list(route["responses"].keys()) == ["200", "401"]
class TestRegister:
def test_register_status_codes(self, get_openapi_dict):
route = get_openapi_dict["paths"]["/register"]["post"]
assert list(route["responses"].keys()) == ["201", "400", "422"]
class TestVerify:
def test_verify_status_codes(self, get_openapi_dict):
route = get_openapi_dict["paths"]["/verify"]["post"]
assert list(route["responses"].keys()) == ["200", "400", "422"]
def test_request_verify_status_codes(self, get_openapi_dict):
route = get_openapi_dict["paths"]["/request-verify-token"]["post"]
assert list(route["responses"].keys()) == ["202", "422"]
class TestOAuth2:
def test_google_authorize_status_codes(self, get_openapi_dict):
route = get_openapi_dict["paths"]["/authorize"]["get"]
assert list(route["responses"].keys()) == ["200", "422"]
def test_google_callback_status_codes(self, get_openapi_dict):
route = get_openapi_dict["paths"]["/callback"]["get"]
assert list(route["responses"].keys()) == ["200", "400", "422"]
|
python
| 16 | 0.628708 | 86 | 35.933824 | 136 |
starcoderdata
|
using Albatross.Config;
using Microsoft.Extensions.Configuration;
namespace Albatross.CRM {
public class GetCRMSettings : GetConfig {
public GetCRMSettings(IConfiguration configuration) : base(configuration) { }
protected override string Key => CRMSetting.Key;
}
}
|
c#
| 9 | 0.784512 | 79 | 28.7 | 10 |
starcoderdata
|
private void initAddTagLabels(NBTTreeView nbtTreeView) {
addTagLabels.put(1, iconLabel("img/nbt/byte", ByteTag::new, nbtTreeView));
addTagLabels.put(2, iconLabel("img/nbt/short", ShortTag::new, nbtTreeView));
addTagLabels.put(3, iconLabel("img/nbt/int", IntTag::new, nbtTreeView));
addTagLabels.put(4, iconLabel("img/nbt/long", LongTag::new, nbtTreeView));
addTagLabels.put(5, iconLabel("img/nbt/float", FloatTag::new, nbtTreeView));
addTagLabels.put(6, iconLabel("img/nbt/double", DoubleTag::new, nbtTreeView));
addTagLabels.put(8, iconLabel("img/nbt/string", StringTag::new, nbtTreeView));
addTagLabels.put(9, iconLabel("img/nbt/list", () -> ListTag.createUnchecked(EndTag.class), nbtTreeView));
addTagLabels.put(10, iconLabel("img/nbt/compound", CompoundTag::new, nbtTreeView));
addTagLabels.put(7, iconLabel("img/nbt/byte_array", ByteArrayTag::new, nbtTreeView));
addTagLabels.put(11, iconLabel("img/nbt/int_array", IntArrayTag::new, nbtTreeView));
addTagLabels.put(12, iconLabel("img/nbt/long_array", LongArrayTag::new, nbtTreeView));
// disable all add tag labels
enableAddTagLabels(null);
}
|
java
| 12 | 0.743339 | 107 | 69.4375 | 16 |
inline
|
#ifndef LEXER_CPP
#define LEXER_CPP
#include
#include
#include "lexer.h"
bool Lexer::isValidIdentifier(int c)
{
return c == '_' || isalnum(c);
}
bool Lexer::skipNextChar(const char& c)
{
return isspace(c);
}
Lexer::Lexer(std::istream& input_stream)
: input_stream(input_stream), line(1), column(1)
{
}
char Lexer::read()
{
return input_stream.get();
}
int Lexer::read(char* buf, const int& n)
{
input_stream.read(buf, n);
return input_stream.gcount();
}
unsigned int Lexer::read_u32(const int& n)
{
unsigned int val = 0;
int len = n > 4 ? 4 : n;
switch(len) {
case 4:
val |= read() << 24;
case 3:
val |= read() << 16;
case 2:
val |= read() << 8;
case 1:
val |= read();
}
column += n;
return val;
}
char Lexer::peek()
{
return input_stream.peek();
}
void Lexer::error(const std::string& msg, int line, int column) const
{
throw JSONException(LEXER, msg, line, column);
}
char Lexer::readNextChar()
{
column += 1;
return read();
}
Token Lexer::next_token()
{
Token token;
char nextChar;
std::string lexeme = "";
while(skipNextChar(peek()))
{
nextChar = read();
if(nextChar == '\n')
{
line += 1;
column = 1;
} else {
column += 1;
}
}
int startColumn = column;
int startLine = line;
nextChar = readNextChar();
lexeme += nextChar;
switch(nextChar) {
case EOF:
token = Token(EOS, "", startLine, startColumn);
break;
case '{':
token = Token(LBRACE, "{", startLine, startColumn);
break;
case '}':
token = Token(RBRACE, "}", startLine, startColumn);
break;
case '[':
token = Token(LBRACKET, "[", startLine, startColumn);
break;
case ']':
token = Token(RBRACKET, "]", startLine, startColumn);
break;
case ':':
token = Token(COLON, ":", startLine, startColumn);
break;
case ',':
token = Token(COMMA, ",", startLine, startColumn);
break;
case '"':
// string
lexeme = "";
while(peek() != '"')
{
nextChar = readNextChar();
if(nextChar == '\\') //handle escapes (primarily for quote escape)
{
lexeme += nextChar;
nextChar = readNextChar();
}
if(nextChar == EOF || nextChar == '\n')
{
error("Invalid token '\"" + lexeme + "': string values require an opening and closing quotation mark,", startLine, startColumn);
}
lexeme += nextChar;
}
nextChar = readNextChar();
token = Token(STRING_VAL, lexeme, startLine, startColumn);
break;
default:
if(isdigit(nextChar) || nextChar == '-')
{
if(nextChar == '-')
{
nextChar = readNextChar();
lexeme += nextChar;
if(!isdigit(nextChar)) {
error("Invalid token,", startLine, startColumn);
}
}
bool leadingZero = nextChar == '0';
if(leadingZero && peek() == '0') {
error("Invalid token: leading 0's are not allowed,", startLine, startColumn);
}
while(isdigit(peek()))
{
nextChar = readNextChar();
lexeme += nextChar;
}
if(peek() == '.')
{
// double literal
nextChar = readNextChar();
lexeme += nextChar;
// need to finish reading numbers in
if(!isdigit(peek()))
{
// no numbers after dot error
error("Invalid token: '" + lexeme + "': double values must have at least one trailing digit,", startLine, startColumn);
}
while(isdigit(peek()))
{
nextChar = readNextChar();
lexeme += nextChar;
}
}
if(peek() == 'e' || peek() == 'E')
{
nextChar = readNextChar();
lexeme += nextChar;
nextChar = readNextChar();
if(nextChar == '-' || nextChar == '+')
{
lexeme += nextChar;
nextChar = readNextChar();
}
if(!isdigit(nextChar))
{
error("Invalid token: '" + lexeme + "':", startLine, startColumn);
}
lexeme += nextChar;
while(isdigit(peek()))
{
nextChar = readNextChar();
lexeme += nextChar;
}
}
token = Token(NUMBER_VAL, lexeme, startLine, startColumn);
} else if(nextChar == 't') {
const unsigned int MAGIC_NUMBER = 0x727565;
unsigned int buf = read_u32(3);
if(~(buf ^~ MAGIC_NUMBER)) {
error("Invalid token '\"" + lexeme + "'", startLine, startColumn);
}
token = Token(LITERAL_VAL, "true", startLine, startColumn);
} else if(nextChar == 'f') {
const unsigned int MAGIC_NUMBER = 0x616c7365;
unsigned int buf = read_u32(4);
if(~(buf ^~ MAGIC_NUMBER)) {
error("Invalid token '\"" + lexeme + "'", startLine, startColumn);
}
token = Token(LITERAL_VAL, "false", startLine, startColumn);
} else if(nextChar == 'n') {
const unsigned int MAGIC_NUMBER = 0x756c6c;
unsigned int buf = read_u32(3);
if(~(buf ^~ MAGIC_NUMBER)) {
error("Invalid token '\"" + lexeme + "'", startLine, startColumn);
}
token = Token(LITERAL_VAL, "null", startLine, startColumn);
} else {
error("Invalid token '\"" + lexeme + "'", startLine, startColumn);
}
}
return token;
}
#endif // ifndef LEXER_CPP
|
c++
| 23 | 0.582152 | 133 | 21.665158 | 221 |
starcoderdata
|
import { _ } from 'azk';
import { originalDefer } from 'azk/utils/promises';
import { subscribe } from 'azk/utils/postal';
export function extend(h) {
h.wait_subscription = function(topic, filter = null, block = null) {
var deferred = originalDefer();
var sub = null, msgs = [];
try {
sub = subscribe(topic, (msg) => {
msgs.push(msg);
if (!_.isFunction(filter) || filter(msg, msgs)) {
sub.unsubscribe();
deferred.resolve(msgs);
}
});
if (_.isFunction(block)) {
setImmediate(block);
}
} catch (err) {
deferred.reject(err);
}
return [deferred.promise, sub];
};
h.wait_msgs = function(...args) {
var [wait] = h.wait_subscription(...args);
return wait;
};
h.wait_msg = function(...args) {
return h.wait_msgs(...args).spread((msg) => {
return msg;
});
};
}
|
javascript
| 19 | 0.561905 | 70 | 23.868421 | 38 |
starcoderdata
|
Color World::shadeHit(const Comps comps, const int remaining) {
//preparing
std::shared_ptr<Object> o = comps.object;
Material m = o -> getMaterial();
Tuple normalv = comps.normalv;
Tuple hitOver = comps.over_point;
Tuple eye = comps.eye;
Color out(0, 0, 0);
//iterate over lights
for (size_t i = 0; i < lightsArray.size(); ++i) {
AreaLight currLight = *lightsArray[i];
Color main = lighting(o, currLight, hitOver, normalv, eye);
Color reflected = reflectedColor(comps, remaining);
Color refracted = refractedColor(comps, remaining);
if (m.getReflectivity() > 0 && m.getTransparency() > 0) {
double reflectance = comps.schlick();
out += main + reflected * reflectance + refracted * (1 - reflectance);
} else {
out += main + reflected + refracted;
}
}
out = out * (1.0 / lightsArray.size());
out.clamp();
return out;
}
|
c++
| 13 | 0.592939 | 82 | 34.703704 | 27 |
inline
|
@model IEnumerable
<article class="article">
@foreach (var room in Model.Where(x => !x.IsDeleted))
{
<h5 class="text-center mt-5 ">@room.RoomType
<p class="text-center text-muted">Max people: @room.MaxCapacity
<table class="table table-bordered table-hover">
<thead class="text-center">
<th scope="col">Date
<th scope="col">Single person
<th scope="col">Price per room
@foreach (var roomPrice in room.HotelRoomPrices.Where(x => !x.IsDeleted).OrderBy(x=>x.Date).Where(x=>x.Date>=DateTime.UtcNow))
{
asp-route-modelId="@room.HotelId" asp-route-modelPriceId="@roomPrice.Id" asp-route-startDate="@roomPrice.Date.ToString("yyyy-MM-dd")" asp-route-price="@roomPrice.PricePerPerson.ToString("N2")" asp-action="AddHotelBooking" asp-route-type="1">@roomPrice.PricePerPerson.ToString("N2")
asp-route-modelId="@room.HotelId" asp-route-modelPriceId="@roomPrice.Id" asp-route-startDate="@roomPrice.Date.ToString("yyyy-MM-dd")" asp-route-price="@roomPrice.PricePerNight.ToString()" asp-action="AddHotelBooking" asp-route-type="1">@roomPrice.PricePerNight
}
}
|
c#
| 20 | 0.571341 | 321 | 51.709677 | 31 |
starcoderdata
|
'use strict';
// Load requirements
const assign = require('deep-assign'),
path = require('path'),
fs = require('fs');
// Load modules
const utils = __require('libs/utils');
// Helper utilities
module.exports = {
assignDefaults: function(opts) {
return assign(require('./data/defaults'), opts);
},
// ucfirst
capitalize: function(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
},
// Gets a stream title from the metadata
getStreamTitle: function(stream) {
return stream.title || stream.tags ? stream.tags.title : undefined;
},
// Format stream language
normalizeStreamLanguage: function(stream) {
let lang = stream.language || stream.tags ? stream.tags.language : undefined;
return utils.normalizeLanguage(lang);
},
// Creates a standard naming convention for audio tracks
getFormatedChannels: function(channels) {
if ( channels === 1 ) {
return 'Mono';
} else if ( channels === 2 ) {
return 'Stereo';
} else if ( channels % 2 ) {
return channels + '.0 Channel';
} else {
return (channels - 1) + '.1 Channel';
}
},
clean: function(str) {
if ( typeof str !== 'string') { return str; }
return str.replace(/[^a-z0-9\s\.-]+/gmi, ' ')
.replace(/[\s|\.]+/gmi, ' ')
.replace(/\s/gmi, '.');
},
getCodecs: function(streams) {
let codecs = {video: {}, audio: {}};
streams.forEach((data) => {
if ( data.codec_type === 'video' ) {
codecs.video = {
codec: data.codec_name.replace('h', 'x'),
resolution: data.height + 'p',
depth: data.bits_per_raw_sample + 'bit'
};
} else if ( data.codec_type === 'audio' ) {
codecs.audio = {
codec: data.codec_name,
channels: this.getFormatedChannels(data.channels).replace(/[^0-9\.]+/ig, '')
};
}
});
return codecs;
},
buildDir: function(file, target) {
let basename = './';
if ( target && path.isAbsolute(target) ) {
basename = target;
} else {
basename = path.dirname(file) + ( target ? '/' + target : '' );
}
// Create the directory if needed
if ( ! fs.existsSync(basename) ) {
fs.mkdirSync(basename);
}
return basename;
},
buildName: function(pattern, file, options, metadata, details) {
// Variables
let regex = /(%(\.)?([a-z]{1,2}))/gmi,
codecs = this.getCodecs(metadata.streams),
str = pattern,
m;
// Build data object
let replacements = {
t: ( details.type === 'show' ? details.name : details.name ) || null,
n: ( details.type === 'show' ? details.show.name : details.name ) || null,
y: ( details.type === 'show' ? details.show.year : details.year ) || null,
ex: options.format,
vc: ( options.video.codec === 'copy' ? codecs.video.codec : options.video.codec.replace('lib', '').replace('h', 'x') ),
r: ( details.resolution !== null ? details.resolution : codecs.video.resolution ) || null,
vd: codecs.video.depth || null,
ac: codecs.audio.codec || null,
ad: codecs.audio.channels || null,
ss: utils.pad(details.season || '0', 2),
s: details.season || '0',
ee: utils.pad(details.season || '0', 2),
e: details.episode || '0'
};
// Default to original filename if we don't have any details
if ( replacements.t === null ) {
let filename = path.basename(file).replace(/\.[^/.]+$/, '');
return this.clean(filename + '-' + replacements.vc + '.' + replacements.ex);
}
// Are there any custom replacements in options
if ( typeof options.replacements === 'object' ) {
replacements = assign(replacements, options.replacements);
}
// Find available replacements in pattern
while ( ( m = regex.exec(pattern) ) !== null ) {
// This is necessary to avoid infinite loops with zero-width matches
if ( m.index === regex.lastIndex ) { regex.lastIndex++; }
m.forEach((match, i) => { // jshint ignore:line
let val = replacements[m[3]];
str = str.replace(m[1], ( m[2] !== undefined ? this.clean(val) : val ));
});
}
// Sample suffix
if ( options.preview ) {
str = str.replace('.' + replacements.ex, '-sample.' + replacements.ex);
}
// Clean and send it back
return this.clean(str);
}
};
|
javascript
| 25 | 0.567157 | 125 | 27.668831 | 154 |
starcoderdata
|
private void b(String s1, String s2)
{
Object obj = ((Object) (l.h().c()));
// 0 0:aload_0
// 1 1:getfield #28 <Field IRobotApplication l>
// 2 4:invokevirtual #34 <Method IRobotModel IRobotApplication.h()>
// 3 7:invokevirtual #40 <Method a IRobotModel.c()>
// 4 10:astore_3
if(obj != null && AssetCapabilityUtils.isCloudCapable(((a) (obj)).a()))
//* 5 11:aload_3
//* 6 12:ifnull 46
//* 7 15:aload_3
//* 8 16:invokevirtual #45 <Method AssetInfo a.a()>
//* 9 19:invokestatic #51 <Method boolean AssetCapabilityUtils.isCloudCapable(AssetInfo)>
//* 10 22:ifeq 46
{
obj = ((Object) (((w)obj).c().d()));
// 11 25:aload_3
// 12 26:checkcast #53 <Class w>
// 13 29:invokevirtual #56 <Method Robot w.c()>
// 14 32:invokevirtual #62 <Method NetworkSettings Robot.d()>
// 15 35:astore_3
((NetworkSettings) (obj)).a(s2);
// 16 36:aload_3
// 17 37:aload_2
// 18 38:invokevirtual #67 <Method void NetworkSettings.a(String)>
((NetworkSettings) (obj)).b(s1);
// 19 41:aload_3
// 20 42:aload_1
// 21 43:invokevirtual #69 <Method void NetworkSettings.b(String)>
}
// 22 46:return
}
|
java
| 14 | 0.520879 | 98 | 40.393939 | 33 |
inline
|
import lolex from 'lolex';
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
// 2016-02-03T11:50:53Z
const START_TIME = 1454500253000;
module('Unit | Service | clock-1sec', function(hooks) {
setupTest(hooks);
hooks.beforeEach(function() {
this.fakeClock = lolex.install();
this.fakeClock.tick(START_TIME);
});
hooks.afterEach(function() {
this.fakeClock.uninstall();
});
test('assert that clock will tick two seconds accurately', function(assert) {
const clock = this.owner.lookup('service:clock');
assert.equal(clock.get('time'), START_TIME, 'The clock has not ticked yet');
this.fakeClock.tick(999);
assert.equal(clock.get('time'), START_TIME, 'The clock has not ticked yet');
this.fakeClock.tick(1);
assert.equal(clock.get('time'), START_TIME + 1000, 'The clock has ticked once');
this.fakeClock.tick(1100);
assert.equal(clock.get('time'), START_TIME + 2000, 'The clock has ticked twice at 1 second intervals');
});
test('assert that the interval timing can be changed', function(assert) {
const clock = this.owner.lookup('service:clock');
assert.equal(clock.get('time'), START_TIME, 'The clock has not ticked yet');
clock.set('interval', 100);
assert.equal(clock.get('time'), START_TIME, 'The clock has not ticked yet');
this.fakeClock.tick(99);
assert.equal(clock.get('time'), START_TIME, 'The clock has not ticked yet');
this.fakeClock.tick(1);
assert.equal(clock.get('time'), START_TIME + 100, 'The clock has ticked once');
this.fakeClock.tick(110);
assert.equal(clock.get('time'), START_TIME + 200, 'The clock has ticked twice at 100ms intervals');
});
});
|
javascript
| 17 | 0.67329 | 107 | 31.903846 | 52 |
starcoderdata
|
var alt = require('../alt');
var Api = require('../utils/APIUtils');
function MailThredActions() {
this.markThread = function(payload) {
Api.updateMail(payload.name, parseInt(payload.id, 10), {
isRead: payload.val
});
this.dispatch(payload);
};
this.markAll = function(payload) {
Api.markAll(payload);
this.dispatch(payload);
};
this.delete = function(payload) {
Api.deleteEmail(payload.name, parseInt(payload.id, 10));
this.dispatch(payload);
};
this.clickStar = function(payload) {
Api.updateMail(payload.name, parseInt(payload.id, 10), {
isStarred: payload.val
});
this.dispatch(payload);
};
this.addCheck = function(payload) {
this.dispatch(payload);
};
this.check = function(payload) {
this.dispatch(payload);
};
this.uncheckAll = function(payload) {
this.dispatch(payload);
};
}
module.exports = alt.createActions(MailThredActions);
|
javascript
| 13 | 0.653191 | 60 | 20.860465 | 43 |
starcoderdata
|
public static OAuth2Credentials createOAuth2Credentials(SessionConfiguration sessionConfiguration) throws Exception {
// Store the users OAuth2 credentials in their home directory.
File credentialDirectory =
new File(System.getProperty("user.home") + File.separator + ".uber_credentials");
credentialDirectory.setReadable(true, true);
credentialDirectory.setWritable(true, true);
// If you'd like to store them in memory or in a DB, any DataStoreFactory can be used.
AbstractDataStoreFactory dataStoreFactory = new FileDataStoreFactory(credentialDirectory);
// Build an OAuth2Credentials object with your secrets.
return new OAuth2Credentials.Builder()
.setCredentialDataStoreFactory(dataStoreFactory)
.setRedirectUri(sessionConfiguration.getRedirectUri())
.setClientSecrets(sessionConfiguration.getClientId(), sessionConfiguration.getClientSecret())
.build();
}
|
java
| 12 | 0.70936 | 117 | 49.8 | 20 |
inline
|
N, K = map(int, input().split())
a = list(map(int, input().split()))
mae = 0
naka = sum(a[:K])
usiro = 0
for i in range(K, N):
if a[i]>0:
usiro+=a[i]
ans = max(mae+naka+usiro, mae+usiro)
for i in range(N-K):
naka+=a[i+K]-a[i]
if a[i]>0:
mae+=a[i]
if a[i+K]>0:
usiro-=a[i+K]
ans = max(ans, mae+naka+usiro, mae+usiro)
print(ans)
|
python
| 11 | 0.518919 | 45 | 20.823529 | 17 |
codenet
|
<?php
namespace BrainpopUser\Form;
use Zend\Form\Factory as FormFactory;
use Zend\Form\Form;
class GroupForm extends Form
{
public function __construct($name = null)
{
parent::__construct($name);
$this->init();
}
public function init()
{
$factory = new FormFactory();
$name = $this->getName();
if (null === $name) {
$this->setName('group');
}
$this->add($factory->createElement(array(
'name' => 'account_id',
'type' => 'Zend\Form\Element\Hidden',
)));
$this->add($factory->createElement(array(
'name' => 'name',
'options' => array(
'label' => 'Name:',
),
'attributes' => array(
'placeholder' => 'Group name',
),
)));
$this->add($factory->createElement(array(
'name' => 'invites_bank',
'type' => 'Zend\Form\Element\Number',
'options' => array(
'label' => 'Invites Bank:',
),
'attributes' => array(
'placeholder' => 'Invites bank',
),
)));
$this->add($factory->createElement(array(
'name' => 'add',
'type' => 'Zend\Form\Element\Submit',
'attributes' => array(
'value' => 'Add',
),
)));
$this->add($factory->createElement(array(
'name' => 'id',
'type' => 'Zend\Form\Element\Hidden',
)));
$this->add($factory->createElement(array(
'name' => 'update',
'type' => 'Zend\Form\Element\Submit',
'attributes' => array(
'value' => 'Update',
),
)));
}
}
|
php
| 17 | 0.437229 | 50 | 24.666667 | 72 |
starcoderdata
|
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Models\UserPermission;
use Illuminate\Contracts\Support\Renderable;
use App\Http\Requests\StoreUserRequest;
use App\Http\Requests\UpdateUserRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Hash;
use Password;
use Str;
class UserController extends Controller
{
/**
* Setup controller.
*/
public function __construct()
{
$this->authorizeResource(User::class);
}
/**
* Display a listing of the resource.
* @param Request $request
* @return Renderable
*/
public function index(Request $request)
{
$request->flash();
$query = $request->query('q', '');
$users = User::where('firstName', 'LIKE', "%$query%")
->orWhere('lastName', 'LIKE', "%$query%")
->orwhere('username', 'LIKE', "%$query%")
->orderBy("lastName", "asc")
->paginate(50);
$users->appends(['q' => $query]);
return view('users.users', ['users' => $users]);
}
/**
* Show the form for creating a new resource.
*
* @return Renderable
*/
public function create()
{
return view('users.create');
}
/**
* Store a newly created resource in storage.
*
* @param StoreUserRequest $request
* @return RedirectResponse
*/
public function store(StoreUserRequest $request)
{
$input = $request->validated();
// Auto-generate username if it's not set.
if (!isset($input["username"]) || $input["username"] === "") {
$firstName = strtolower($input["firstName"]);
$lastName = strtolower($input["lastName"]);
$input["username"] = "{$firstName}.{$lastName}";
}
// Set password hash to "!", this hash can NEVER be create in any way.
// So the account is locked until the user changes his password.
// Reference: /etc/shadow in Unix systems
$input['password'] = "!";
// Make the user active on creation.
$input["active"] = true;
$user = User::create($input);
Password::sendResetLink(["email" => $input["email"]]);
$request->session()->flash('success', 'User ' . $user->firstName . ' ' . $user->lastName . ' was successfully created.');
return redirect(route('users.show', ['user' => $user]));
}
/**
* Display the specified resource.
*
* @param User $user
* @return Renderable
*/
public function show(User $user)
{
return view('users.user', ['user' => $user]);
}
/**
* Show the form for editing the specified resource.
*
* @param User $user
* @return Renderable
*/
public function edit(User $user)
{
return view('users.edit', ['user' => $user]);
}
/**
* Update the specified resource in storage.
*
* @param UpdateUserRequest $request
* @param User $user
* @return RedirectResponse
*/
public function update(UpdateUserRequest $request, User $user)
{
$user->update($request->validated());
$request->session()->flash('success', 'Information of user ' . $user->firstName .
' ' . $user->lastName . ' was successfully updated.');
return redirect(route('users.show', ['user' => $user]));
}
/**
* Remove the specified resource from storage.
*
* @param User $user
* @return RedirectResponse
*/
public function destroy(Request $request, User $user)
{
$user->delete();
$request->session()->flash('success', 'User ' . $user->firstName . ' ' . $user->lastName . ' was successfully deleted.');
return redirect()->route('users.index');
}
/**
* Update the password voor the current user
*
* @param Request $request
* @param User $user
* @return RedirectResponse
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function resetPassword(Request $request, User $user)
{
$this->authorize('update', $user);
Password::sendResetLink(["email" => $user->email]);
$request->session()->flash("success", "A password reset email has been sent to {$user->fullName()}.");
return redirect()->route('users.show', ['user' => $user]);
}
/**
* Update the status of a user
* @param Request $request
* @param User $user
* @return RedirectResponse
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function updateStatus(Request $request, User $user)
{
$this->authorize('update', $user);
$user->update([
'active' => $request->input('active')
]);
if($user->active) {
$request->session()->flash('success', "User has now been activated.");
} else {
$request->session()->flash('success', "User has now been deactivated.");
}
return redirect(route('users.show', ['user' => $user]));
}
}
|
php
| 16 | 0.571124 | 129 | 26.121053 | 190 |
starcoderdata
|
void *
drsym_obj_mod_init_pre(byte *map_base, size_t map_size)
{
macho_info_t *mod;
mach_header_t *hdr;
struct load_command *cmd, *cmd_stop;
byte *arch_base;
mod = dr_global_alloc(sizeof(*mod));
memset(mod, 0, sizeof(*mod));
arch_base = find_macho_header(map_base);
if (arch_base == NULL)
return NULL;
mod->map_base = arch_base;
hdr = (mach_header_t *)arch_base;
cmd = (struct load_command *)(hdr + 1);
cmd_stop = (struct load_command *)((char *)cmd + hdr->sizeofcmds);
while (cmd < cmd_stop) {
if (cmd->cmd == LC_SEGMENT || cmd->cmd == LC_SEGMENT_64) {
segment_command_t *seg = (segment_command_t *)cmd;
section_t *sec, *sec_stop;
sec_stop = (section_t *)((char *)seg + seg->cmdsize);
sec = (section_t *)(seg + 1);
while (sec < sec_stop) {
/* sectname is not null-terminated if it's the full 16-char size */
if (strncmp(sec->sectname, "__debug_line", sizeof(sec->sectname)) == 0)
mod->debug_kind |= DRSYM_LINE_NUMS | DRSYM_DWARF_LINE;
sec++;
}
if (strcmp(seg->segname, "__PAGEZERO") == 0 && seg->initprot == 0) {
/* i#1365: any PIE shift is placed after this, and DR skips it
* for the effective base, so we need to adjust our offsets.
*/
mod->offs_adjust = seg->vmsize;
}
} else if (cmd->cmd == LC_SYMTAB) {
/* even if stripped, dynamic symbols are in this table */
struct symtab_command *symtab = (struct symtab_command *)cmd;
mod->debug_kind |= DRSYM_SYMBOLS | DRSYM_MACHO_SYMTAB;
mod->syms = (nlist_t *)(arch_base + symtab->symoff);
mod->num_syms = symtab->nsyms;
mod->strtab = arch_base + symtab->stroff;
mod->strsz = symtab->strsize;
} else if (cmd->cmd == LC_UUID) {
memcpy(mod->uuid, ((struct uuid_command *)cmd)->uuid, sizeof(mod->uuid));
}
cmd = (struct load_command *)((char *)cmd + cmd->cmdsize);
}
return (void *)mod;
}
|
c
| 19 | 0.526025 | 87 | 39.981132 | 53 |
inline
|
/**************************************************************************************************
* Copyright © 2017-2021 *
* Huge thanks to: *
* for plugin idea; *
* for optimisation ideas; *
* Program is distributed under the terms of the MIT License. *
* *
* @date 28.1.2021 *
* @license MIT *
**************************************************************************************************/
import ClassList from "classlist"
import throttle from "lodash.throttle"
export default class Adaptive {
/**
* Viewport describing object
* @typedef viewport
* @type {object} - viewport size
* @property {number} width - viewport width
* @property {number} height - viewport height
*/
/**
* Device configuration object
* @typedef device
* @type {object}
* @property {function({width: number, height: number})} [if] - custom device condition callback
* @property {string|HTMLElement} [element=window] - element selector that will be used for detecting viewport
* @property {number} [rem] - static rem value, overrides k and base calculation
* @property {number} [k=1] - Additional coefficient for rem calculation
* @property {viewport} [base] - base width and height for rem calculation
* @property {viewport} [from] - minimal width and height for setting device
* @property {viewport} [to] - maximal width and height for setting device
* @property {boolean} [setDevice=true] - class, no-class and device set toggle
*/
/**
* Plugin configuration object
* @typedef globalConf
* @type {object}
* @property {number} [rem=10] - default rem value in case no breakpoints matched
* @property {number} [throttle=17] - frequency of viewport data update
* @property {number} [orientationTestCount=50] - orientationchange event end detection tries
* @property {number} [orientationChangeTimeout=1000] - maximum orientationchange event duration before viewport update
*/
/**
* Current adaptive data
* @typedef adaptiveObservable
* @type {object}
* @property {object is - devices status
* @property {number} width - current viewport width
* @property {number} height - current viewport height
* @property {number} rem - current rem size in px
*/
/**
* Vue plugin install function
* @param Vue - Vue framework object
* @param {object<string, device>} config - adaptive configuration file
* @param {globalConf} config.global - Plugin's instance-level config
*/
static install(Vue, config) {
const adaptive = new this(Vue, config)
Vue.adaptive = adaptive
Object.defineProperty(Vue.prototype, "$adaptive", {
/**
* Adaptive current state getter
* @returns {Adaptive} - Adaptive current state observable
*/
get: () => adaptive
})
}
/**
* Splitting configuration and creating eventListeners
* @param Vue - Vue framework object
* @param {{string: device}} config - adaptive configuration file
* @param {globalConf} config.global - Plugin's instance-level config
* @returns {adaptiveObservable} - reactive model, based on Vue
*/
constructor(Vue, config) {
// Defaults
const defaultGlobal = {
rem: 10,
throttle: 17,
orientationTestCount: 25,
orientationChangeTimeout: 1000
}
const defaultConfig = {
if: null,
element: window,
rem: null,
from: null,
to: null,
base: null,
k: 1,
setDevice: true
}
// Global config
this.globals = Object.assign(defaultGlobal, config.global)
this.config = {}
const deviceList = {}
for (let device in config) {
if (config.hasOwnProperty(device) && device !== "global") {
const deviceConfig = (this.config[device] = Object.assign(
{},
defaultConfig,
config[device]
))
device = device.split(":")[0]
if (deviceConfig.setDevice && !deviceList.hasOwnProperty(device))
deviceList[device] = false
}
}
const data = {
is: deviceList,
width: 0,
height: 0,
rem: 0
}
const [major, minor] = Vue.version.split(".").slice(0, 2).map(Number)
/** @type adaptiveObservable */
this.data =
major === 2 && minor >= 6 ? Vue.observable(data) : new Vue({data}).$data
// Listening to change events
window.addEventListener(
"resize",
throttle(this.resize.bind(this), this.globals.throttle)
)
window.addEventListener(
"orientationchange",
this.orientationChange.bind(this)
)
// Initializing Adaptive
this.resize()
return this.data
}
/**
* Handle resize of viewport
*/
resize() {
const viewport = {
width: window.innerWidth,
height: window.innerHeight
}
const cache = {
keys: [window],
values: [viewport]
}
const newDeviceList = {}
let rem = this.globals.rem
// Setting viewport size
if (this.data.width !== viewport.width) this.data.width = viewport.width
if (this.data.height !== viewport.height) this.data.height = viewport.height
for (let name in this.config) {
if (this.config.hasOwnProperty(name)) {
const device = this.config[name]
// Getting device name
name = name.split(":")[0]
// Caching elements viewport
const elementCacheIndex = cache.keys.indexOf(device.element)
let data
if (elementCacheIndex === -1) {
const el =
device.element instanceof HTMLElement
? device.element
: document.querySelector(device.element)
const clientRect = el.getBoundingClientRect()
data = {
width: clientRect.width,
height: clientRect.height
}
cache.keys.push(device.element)
cache.values.push(data)
} else data = cache.values[elementCacheIndex]
// Detecting is breakpoints valid
// Testing if function
const checked = !(
(typeof device.if === "function" && !device.if(data)) ||
// Testing min viewport
(device.from &&
(device.from.width > data.width ||
device.from.height > data.height)) ||
// Testing max viewport
(device.to &&
(device.to.width <= data.width || device.to.height <= data.height))
)
// Testing classes
if (device.setDevice && !newDeviceList[name])
newDeviceList[name] = checked
// Scale changing
if (checked) {
// Setting static rem
if (device.rem) {
rem = device.rem
// Setting dynamic rem
} else if (device.base) {
const remBases = []
if (device.base.width) {
remBases.push(data.width / device.base.width)
}
if (device.base.height) {
remBases.push(data.height / device.base.height)
}
const remBase = Math.min(...remBases)
rem = remBase * device.k * 10
}
}
}
}
this.updateDOM(newDeviceList, rem)
}
/**
* Update documentElement classes and font size
* @param {object. newDeviceList - new devices state
* @param {number} rem - new rem size calculation
*/
updateDOM(newDeviceList, rem) {
const documentElementClassList = new ClassList(document.documentElement)
for (const name in newDeviceList) {
if (newDeviceList.hasOwnProperty(name)) {
const checked = newDeviceList[name]
const oldClass = this.data.is[name] ? name : `no-${name}`
const newClass = checked ? name : `no-${name}`
// Updating classes if changed
if (
oldClass !== newClass ||
!documentElementClassList.contains(newClass)
) {
if (documentElementClassList.contains(oldClass))
documentElementClassList.remove(oldClass)
documentElementClassList.add(newClass)
this.data.is[name] = checked
}
}
}
if (rem !== this.data.rem) {
document.documentElement.style.fontSize = `${rem}px`
this.data.rem = rem
}
}
/**
* Handle orientationChange event
*/
orientationChange() {
let noChangeCount = 0
const end = function () {
clearInterval(interval)
clearTimeout(timeout)
interval = null
timeout = null
}
let interval = setInterval(() => {
const currHeight = window.innerHeight
const currWidth = window.innerWidth
if (currWidth === this.data.width && currHeight === this.data.height) {
noChangeCount++
if (noChangeCount === this.globals.orientationTestCount) end()
} else {
this.data.width = currWidth
this.data.height = currHeight
this.resize()
noChangeCount = 0
}
}, this.globals.throttle)
let timeout = setTimeout(function () {
end()
}, this.globals.orientationChangeTimeout)
}
}
|
javascript
| 27 | 0.566705 | 121 | 32.757042 | 284 |
starcoderdata
|
class Solution {
public void XXX(int[] nums) {
int len=nums.length;
int[] res=new int[len];
int[] tmp=new int[3];
for(int num:nums){
tmp[num]++;
}
int k1=tmp[0];
int k2=tmp[1];
int k3=tmp[2];
for(int i=0;i<k1;i++){
nums[i]=0;
}
for(int i=k1;i<k2+k1;i++){
nums[i]=1;
}
for(int i=k2+k1;i<k3+k1+k2;i++){
nums[i]=2;
}
}
}
|
java
| 8 | 0.407767 | 40 | 20.458333 | 24 |
starcoderdata
|
def save_text(filepath, data, header=None, fmt='%d', delimiter=' '):
if isinstance(data, basestring):
with open(filepath, 'w') as f:
f.write(data)
else:
np.savetxt(filepath, data, fmt=fmt, newline='\n', delimiter=delimiter)
# Write a header.
if header is not None:
with open(filepath, 'r') as f:
contents = f.read()
contents_updated = str(header) + '\n' + contents
with open(filepath, 'w') as f:
f.write(contents_updated)
|
python
| 15 | 0.545287 | 78 | 40.692308 | 13 |
inline
|
def reBar(music21Part, *, inPlace=False):
'''
Re-bar overflow measures using the last known time signature.
>>> irl2 = corpus.parse('irl', number=2)
>>> irl2.metadata.title
'Aililiu na Gamhna, S.35'
>>> music21Part = irl2[1]
The whole part is in 2/4 time, but there are some measures expressed in 4/4 time
without an explicit time signature change, an error in abc parsing due to the
omission of barlines. The method will split those measures such that they conform
to the last time signature, in this case 2/4. The default is to reBar in place.
The measure numbers are updated accordingly.
(NOTE: reBar is called automatically in abcToStreamPart, hence not demonstrated below...)
The key signature and clef are assumed to be the same in the second measure after the
split, so both are omitted. If the time signature is not the same in the second measure,
the new time signature is indicated, and the measure following returns to the last time
signature, except in the case that a new time signature is indicated.
>>> music21Part.measure(15).show('text')
{0.0} <music21.note.Note A>
{1.0} <music21.note.Note A>
>>> music21Part.measure(16).show('text')
{0.0} <music21.note.Note A>
{0.5} <music21.note.Note B->
{1.0} <music21.note.Note A>
{1.5} <music21.note.Note G>
An example where the time signature wouldn't be the same. This score is
mistakenly marked as 4/4, but has some measures that are longer.
>>> irl15 = corpus.parse('irl', number=15)
>>> irl15.metadata.title
'Esternowe, S. 60'
>>> music21Part2 = irl15.parts.first() # 4/4 time signature
>>> music21Part2.measure(1).show('text')
{0.0} <music21.note.Note C>
{1.0} <music21.note.Note A>
{1.5} <music21.note.Note G>
{2.0} <music21.note.Note E>
{2.5} <music21.note.Note G>
>>> music21Part2.measure(1)[-1].duration.quarterLength
1.5
>>> music21Part2.measure(2).show('text')
{0.0} <music21.meter.TimeSignature 1/8>
{0.0} <music21.note.Note E>
Changed in v.5: inPlace is False by default, and a keyword only argument.
'''
if not inPlace:
music21Part = copy.deepcopy(music21Part)
lastTimeSignature = None
measureNumberOffset = 0 # amount to shift current measure numbers
allMeasures = music21Part.getElementsByClass(stream.Measure)
for measureIndex in range(len(allMeasures)):
music21Measure = allMeasures[measureIndex]
if music21Measure.timeSignature is not None:
lastTimeSignature = music21Measure.timeSignature
if lastTimeSignature is None:
raise ABCTranslateException('No time signature found in this Part')
tsEnd = lastTimeSignature.barDuration.quarterLength
mEnd = common.opFrac(music21Measure.highestTime)
music21Measure.number += measureNumberOffset
if mEnd > tsEnd:
m1, m2 = music21Measure.splitAtQuarterLength(tsEnd)
m2.timeSignature = None
if lastTimeSignature.barDuration.quarterLength != m2.highestTime:
try:
m2.timeSignature = m2.bestTimeSignature()
except exceptions21.StreamException as e:
raise ABCTranslateException(
f'Problem with measure {music21Measure.number} ({music21Measure!r}): {e}')
if measureIndex != len(allMeasures) - 1:
if allMeasures[measureIndex + 1].timeSignature is None:
allMeasures[measureIndex + 1].timeSignature = lastTimeSignature
m2.keySignature = None # suppress the key signature
m2.clef = None # suppress the clef
m2.number = m1.number + 1
measureNumberOffset += 1
music21Part.insert(common.opFrac(m1.offset + m1.highestTime), m2)
# elif ((mEnd + music21Measure.paddingLeft) < tsEnd
# and measureIndex != len(allMeasures) - 1):
# The first and last measures are allowed to be incomplete
# music21Measure.timeSignature = music21Measure.bestTimeSignature()
# if allMeasures[measureIndex + 1].timeSignature is None:
# allMeasures[measureIndex + 1].timeSignature = lastTimeSignature
#
if not inPlace:
return music21Part
|
python
| 18 | 0.65587 | 98 | 42.979798 | 99 |
inline
|
using System;
using System.Linq;
using Menshen.Backend.Services;
using Microsoft.AspNetCore.Mvc;
namespace Menshen.Backend.Utils
{
public class MenshenControllerBase : ControllerBase
{
protected readonly ILocker _locker;
protected MenshenControllerBase(ILocker locker)
{
_locker = locker;
}
protected string GetUserIp()
{
return HttpContext.Request.Headers["X-Real-IP"].FirstOrDefault();
}
protected bool GetIsIpBlocked((int, long)? blockDetails)
{
return blockDetails?.Item1 > 3 &&
blockDetails?.Item2 > DateTimeOffset.UtcNow
.AddMinutes(-(int) Math.Pow(2, (double) blockDetails?.Item1)).ToUnixTimeSeconds();
}
}
}
|
c#
| 21 | 0.606396 | 105 | 26.133333 | 30 |
starcoderdata
|
package mediaserver
import (
"mime"
"net/url"
"strings"
"github.com/benpate/convert"
"github.com/benpate/list"
)
// FileSpec represents all the parameters available for requesting a file.
// This can be generated directly from a URL.
type FileSpec struct {
Filename string
Extension string
Width int
Height int
MimeType string
}
// NewFileSpec reads a URL and returns a fully populated FileSpec
func NewFileSpec(file *url.URL, defaultType string) FileSpec {
fullname := list.Last(file.Path, "/")
filename, extension := list.SplitTail(fullname, ".")
if extension == "" {
extension = strings.ToLower(defaultType)
}
mimeType := mime.TypeByExtension(extension)
height := convert.Int(file.Query().Get("height"))
width := convert.Int(file.Query().Get("width"))
return FileSpec{
Filename: filename,
Extension: extension,
Width: width,
Height: height,
MimeType: mimeType,
}
}
// MimeCategory returns the first half of the mime type
func (ms *FileSpec) MimeCategory() string {
return list.Head(ms.MimeType, "/")
}
// CachePath returns the complete path (within the cache directory) to the file requested by this FileSpec
func (ms *FileSpec) CachePath() string {
return ms.CacheDir() + "/" + ms.CacheFilename()
}
// CacheDir returns the name of the directory within the cache where versions of this file will be stored.
func (ms *FileSpec) CacheDir() string {
return ms.Filename
}
// CacheFilename returns the filename to be used when retrieving this from the FileSpec cache.
func (ms *FileSpec) CacheFilename() string {
var buffer strings.Builder
buffer.WriteString("cached")
if ms.MimeCategory() == "image" {
if ms.Width != 0 {
buffer.WriteString("_w" + convert.String(ms.Width))
}
if ms.Height != 0 {
buffer.WriteString("_h" + convert.String(ms.Height))
}
}
buffer.WriteString(ms.Extension)
return buffer.String()
}
// Resize returns TRUE if the FileSpec is requesting that the file be resized.
func (ms *FileSpec) Resize() bool {
return (ms.Width > 0) || (ms.Height > 0)
}
// CacheWidth returns the width of the file to save in the cache
func (ms *FileSpec) CacheWidth() int {
return round100(ms.Width)
}
// CacheHeight returns the height of the file to save in the cache
func (ms *FileSpec) CacheHeight() int {
return round100(ms.Height)
}
|
go
| 14 | 0.712141 | 106 | 23.536842 | 95 |
starcoderdata
|
"""
Module responsible for plugin discovery, configuration and initialization
"""
import importlib
import importlib.util
import pkgutil
import inspect
import sys
from importlib.abc import Traversable
from pygalgen.generator.pluggability.plugin import Plugin
from typing import Any, Union, List
import os
import yaml
import logging
class PluginDiscoveryException(Exception):
pass
def get_plugin_configuration(config_file_path: str) -> dict[str, Any]:
"""
Parameters
----------
config_file_path : str
Returns
-------
Dictionary containing parsed yml file
"""
with open(config_file_path, "r", encoding="utf-8") as file:
return yaml.safe_load(file)
def load_plugin(configuration: dict[str, Any], plugin_dir: str) -> Plugin:
"""
The function initializes plugin based on provided configuration and path
Parameters
----------
configuration : dict[str, Any]
parsed configuration yaml
plugin_dir : str
path to the root directory of plugin
Returns
-------
plugin : Plugin
initialized plugin object
"""
plugin_dct = configuration["plugin"]
installed_modules = set(name for _, name, _ in pkgutil.iter_modules())
# check whether required modules of this plugin are available
for req in plugin_dct["requirements"]:
if req not in installed_modules:
logging.warning(f"Loading of plugin '{plugin_dct['name']}' "
f"failed. Reason: requirement '{req}' of this "
f"plugin "
f"can't be satisfied")
raise PluginDiscoveryException()
path_to_module, module_name = os.path.split(plugin_dct["path"])
module_name = os.path.splitext(module_name)[0]
file_path = os.path.join(plugin_dir, plugin_dct["path"])
# Beware, what follows is a revoltingly dirty hack to solve import problems
plugin_module_dir_path = os.path.join(plugin_dir, path_to_module)
sys.path.append(plugin_module_dir_path)
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
classes = [class_ for _, class_ in inspect.getmembers(module,
lambda member:
inspect.isclass(
member) and
member != Plugin and
issubclass(member,
Plugin))]
if not classes:
logging.warning(f"No plugins were declared in"
f" {plugin_dct['path']}")
raise PluginDiscoveryException()
if len(classes) > 1:
logging.warning(f"More than one plugin definition detected in"
f" {plugin_dct['path']}")
raise PluginDiscoveryException()
assets_path = None
if "assets" in plugin_dct and plugin_dct["assets"] is not None:
assets_path = os.path.join(plugin_dir, plugin_dct["assets"])
return classes[0](plugin_dct.get("order", 0), plugin_dct["name"],
assets_path)
def discover_plugins(path: Union[str, Traversable]) -> List[Plugin]:
"""
Function traverses directory structure with path as a root and loads
all discovered plugins
The plugins have to have valid configuration file to be
Parameters
----------
path : Union[str, Traversable]
path to the root directory of plugins
Returns
-------
result : List[Plugin]
list of initialized plugins
Raises
-------
FileNotFoundError
raises FileNotFoundError in case plugin configuration points
to missing plugin module
"""
try:
result = []
for path, _, files in os.walk(path):
for file in files:
if file.endswith(".yml"):
try:
file_path = os.path.join(path, file)
conf = get_plugin_configuration(file_path)
result.append(load_plugin(conf, path))
except PluginDiscoveryException:
continue
return result
except FileNotFoundError:
raise PluginDiscoveryException("Plugin discovery failed")
|
python
| 18 | 0.576863 | 79 | 30.433566 | 143 |
starcoderdata
|
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
public interface IImageProcess
{
string GetName();
Image RunProcess(Image input);
}
|
c#
| 8 | 0.781818 | 50 | 21.1 | 10 |
starcoderdata
|
package com.lei_cao.android.mtime.app;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.ShareActionProvider;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.lei_cao.android.mtime.app.DAO.MoviesDAO;
import com.lei_cao.android.mtime.app.models.Movie;
import com.lei_cao.android.mtime.app.models.Video;
import com.lei_cao.android.mtime.app.services.MovieResponses;
import com.lei_cao.android.mtime.app.services.MovieService;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import retrofit.Call;
import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;
public class DetailFragment extends Fragment {
static final String DETAIL_MOVIE = "MOVIE";
// The videos adapter
VideosAdapter adapter;
// The movieDb service
MovieService service;
// The apiKey
String apiKey;
MoviesDAO dao;
Movie movie;
Boolean mTwoPane = false;
private ShareActionProvider mShareActionProvider;
private String mVideo;
private static final String MOVIE_SHARE_HASHTAG = " #MTime";
public interface DetailCallback {
public void onShowReviews(Movie movie);
}
public DetailFragment() {
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
Bundle arguments = getArguments();
if (arguments != null) {
movie = arguments.getParcelable(DetailFragment.DETAIL_MOVIE);
} else {
Intent intent = getActivity().getIntent();
if (intent == null || !intent.hasExtra(DetailFragment.DETAIL_MOVIE)) {
return rootView;
}
movie = (Movie) intent.getParcelableExtra(DetailFragment.DETAIL_MOVIE);
}
if (movie == null) {
return rootView;
}
service = new MovieService();
apiKey = getResources().getString(R.string.themoviedb_api_key);
ImageView image = (ImageView) rootView.findViewById(R.id.detail_movie_image);
Picasso.with(getActivity()).load(movie.getDetailUrl()).noFade().into(image);
// set title, overview, rating, release date
TextView title = (TextView) rootView.findViewById(R.id.detail_movie_title);
TextView overview = (TextView) rootView.findViewById(R.id.detail_movie_overview);
TextView vote = (TextView) rootView.findViewById(R.id.detail_movie_vote);
final TextView releaseDate = (TextView) rootView.findViewById(R.id.detail_movie_release_date);
title.setText(movie.title);
overview.setText(movie.overview);
vote.setText(movie.voteAverage);
releaseDate.setText(movie.releaseDate);
ListView videos = (ListView) rootView.findViewById(R.id.detail_movie_videos);
adapter = new VideosAdapter(getActivity(), new ArrayList
videos.setAdapter(adapter);
videos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
Video video = adapter.getItem(position);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(video.GetVideoUrl())));
}
});
Call call = service.service.movieVideos(String.valueOf(movie.id), apiKey);
call.enqueue(new Callback {
@Override
public void onResponse(Response response, Retrofit retrofit) {
if (response.body() != null && response.body().results.size() != 0) {
adapter.clear();
int i = 0;
for (Video v : response.body().results) {
if (i == 0) {
mVideo = v.GetVideoUrl();
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(createShareMovie());
}
}
adapter.add(v);
i++;
}
adapter.notifyDataSetChanged();
}
}
@Override
public void onFailure(Throwable t) {
}
});
Button reviews = (Button) rootView.findViewById(R.id.detail_movie_reviews_button);
reviews.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mTwoPane) {
((MoviesFragment.MovieCallback) getActivity()).onShowReviews(movie);
} else {
((DetailCallback) getActivity()).onShowReviews(movie);
}
}
});
dao = new MoviesDAO(this.getActivity());
dao.open();
final ImageButton favorite = (ImageButton) rootView.findViewById(R.id.detail_movie_favorite_imagebutton);
Movie m = dao.getMovie(movie.id);
if (m != null) {
movie.favorited = true;
favorite.setImageResource(android.R.drawable.btn_star_big_on);
}
favorite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v.setEnabled(false);
if (movie.favorited) {
dao.deleteMovie(movie);
favorite.setImageResource(android.R.drawable.btn_star_big_off);
movie.favorited = false;
} else {
Movie m = dao.createMovie(movie);
if (m != null) {
favorite.setImageResource(android.R.drawable.btn_star_big_on);
movie.favorited = true;
}
}
v.setEnabled(true);
}
});
return rootView;
}
@Override
public void onResume() {
if (dao != null) {
dao.open();
}
super.onResume();
}
@Override
public void onPause() {
if (dao != null) {
dao.close();
}
super.onPause();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.detail_fragment, menu);
// Retrieve the share menu item
MenuItem menuItem = menu.findItem(R.id.action_share);
// Get the provider and hold onto it to set/change the share intent.
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
// If onLoadFinished happens before this, we can go ahead and set the share intent now.
if (mVideo != null) {
mShareActionProvider.setShareIntent(createShareMovie());
}
}
private Intent createShareMovie() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, mVideo + MOVIE_SHARE_HASHTAG);
return shareIntent;
}
}
|
java
| 25 | 0.609342 | 113 | 33.68559 | 229 |
starcoderdata
|
from .base import *
class ProductTestCase(BaseTestCase):
""" This class represents the product test case """
def setUp(self):
super(ProductTestCase, self).setUp()
def test_create_a_product(self):
user_registration(self, test_admin_user)
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
resp = create_product(self, product, token)
self.assertEqual(resp.status_code, 201)
def test_create_an_existing_product(self):
user_registration(self, test_admin_user)
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
resp = create_product(self, product, token)
self.assertEqual(resp.status_code, 400)
response = json.loads(resp.data.decode())
self.assertTrue(
response['message'] == "Sorry, such a product already exists, please confirm its category")
def test_create_product_with_missing_product_name_key(self):
user_registration(self, test_admin_user)
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
resp = create_product(self, product_without_product_name_key, token)
response = json.loads(resp.data.decode())
self.assertTrue(response['message'] == "'product_name' key missing")
def test_create_product_with_missing_product_category_key(self):
user_registration(self, test_admin_user)
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
resp = create_product(self, product_without_category_key, token)
response = json.loads(resp.data.decode())
self.assertTrue(response['message'] == "'category' key missing")
def test_create_product_with_missing_quantity_key(self):
user_registration(self, test_admin_user)
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
resp = create_product(self, product_without_quantity_key, token)
response = json.loads(resp.data.decode())
self.assertTrue(response['message'] == "'quantity' key missing")
def test_create_product_with_missing_price_key(self):
user_registration(self, test_admin_user)
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
resp = create_product(self, product_without_price_key, token)
response = json.loads(resp.data.decode())
self.assertTrue(response['message'] == "'unit_price' key missing")
def test_create_product_with_an_empty_value(self):
user_registration(self, test_admin_user)
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
resp = resp = create_product(self, product_with_an_empty_value, token)
self.assertEqual(resp.status_code, 400)
response = json.loads(resp.data.decode())
self.assertTrue(
response['message'] == "Sorry, there's an empty value, please check your input values")
def test_create_product_with_non_string_product_name(self):
user_registration(self, test_admin_user)
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
resp = create_product(
self, product_with_non_string_product_name, token)
self.assertEqual(resp.status_code, 400)
response = json.loads(resp.data.decode())
self.assertTrue(response['message'] == "A product name's value must be a string")
def test_create_product_with_non_string_category(self):
user_registration(self, test_admin_user)
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
resp = create_product(self, product_with_non_string_category, token)
self.assertEqual(resp.status_code, 400)
response = json.loads(resp.data.decode())
self.assertTrue(response['message'] ==
"A category's value must be a string")
def test_create_product_with_non_integer_quantity(self):
user_registration(self, test_admin_user)
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
resp = create_product(self, product_with_non_integer_quantity, token)
self.assertEqual(resp.status_code, 400)
response = json.loads(resp.data.decode())
self.assertTrue(response['message'] ==
"A quantity's value must be an integer")
def test_create_product_with_non_positive_integer_quantity(self):
user_registration(self, test_admin_user)
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
resp = create_product(self, product_with_non_positive_integer_quantity, token)
self.assertEqual(resp.status_code, 400)
response = json.loads(resp.data.decode())
self.assertTrue(response['message'] ==
"A quantity's value must be a positive integer")
def test_create_product_with_non_float_price(self):
user_registration(self, test_admin_user)
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
resp = create_product(self, product_with_non_float_price, token)
self.assertEqual(resp.status_code, 400)
response = json.loads(resp.data.decode())
self.assertTrue(
response['message'] == "A price's value must be of float data type")
def test_create_product_with_non_positive_float_price(self):
user_registration(self, test_admin_user)
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
resp = create_product(
self, product_with_non_positive_float_price, token)
self.assertEqual(resp.status_code, 400)
response = json.loads(resp.data.decode())
self.assertTrue(response['message'] ==
"A price's value must be a positive float")
def test_get_all_products(self):
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
create_product(self, product, token)
response = get_all_products(self, token)
self.assertEqual(response.status_code, 200)
response = json.loads(response.data.decode())
self.assertTrue(response['message'] == "Success")
def test_xget_non_existing_products(self):
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
response = get_all_products(self, token)
self.assertEqual(response.status_code, 404)
response = json.loads(response.data.decode())
self.assertTrue(response['message'] == "No product record(s) available")
def test_get_specific_product(self):
user_registration(self, test_admin_user)
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
resp = create_product(self, product, token)
response = get_specific_product(self, token)
self.assertEqual(response.status_code, 200)
def test_xget_non_existing_specific_product(self):
user_registration(self, test_admin_user)
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
resp = get_non_existing_product(self, token)
self.assertEqual(resp.status_code, 404)
response = json.loads(resp.data.decode())
self.assertTrue(response['message'] == "Sorry, such a product does not exist")
def test_update_product(self):
user_registration(self, test_admin_user)
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
resp = product_update(self, update_product, token)
response_data = json.loads(resp.data.decode())
self.assertEqual(response_data['message'], "Update successful")
def test_update_non_existent_product(self):
user_registration(self, test_admin_user)
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
resp = product_update(self, update_non_existent_product, token)
response_data = json.loads(resp.data.decode())
self.assertEqual(response_data['message'], "Sorry, such a product does not exist")
def test_update_product_with_missing_product_name_key(self):
user_registration(self, test_admin_user)
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
resp = product_update(
self, update_product_without_product_name_key, token)
response = json.loads(resp.data.decode())
self.assertTrue(response['message'] == "'product_name' key missing")
def test_update_product_with_missing_category_key(self):
user_registration(self, test_admin_user)
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
resp = product_update(self, update_product_without_category_key, token)
response = json.loads(resp.data.decode())
self.assertTrue(response['message'] == "'category' key missing")
def test_update_product_with_missing_quantity_key(self):
user_registration(self, test_admin_user)
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
resp = product_update(self, update_product_without_quantity_key, token)
response = json.loads(resp.data.decode())
self.assertTrue(response['message'] == "'quantity' key missing")
def test_update_product_with_missing_price_key(self):
user_registration(self, test_admin_user)
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
resp = product_update(self, update_product_without_price_key, token)
response = json.loads(resp.data.decode())
self.assertTrue(response['message'] == "'unit_price' key missing")
def test_xdelete_product(self):
user_registration(self, test_admin_user)
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
resp = delete_specific_product(self, token)
self.assertEqual(resp.status_code, 200)
response_data = json.loads(resp.data.decode())
self.assertEqual(response_data['message'], "delete operation successful!")
def test_xxdelete_product_not_existing(self):
user_registration(self, test_admin_user)
admin_login = user_login(self, admin_user_login)
response_content = json.loads(admin_login.data.decode('utf-8'))
token = response_content["access_token"]
resp = delete_specific_product(self, token)
self.assertEqual(resp.status_code, 404)
response_data = json.loads(resp.data.decode())
self.assertEqual(response_data['message'], "Sorry, such a product does not exist!")
def teardown(self):
super(ProductTestCase, self).teardown()
# Make the tests conveniently executable
if __name__ == "__main__":
unittest.main()
|
python
| 12 | 0.658724 | 103 | 49.137405 | 262 |
starcoderdata
|
package tiles;
import gfx.Pantalla;
import nivel.Nivel;
public class TileBasico extends Tile{
protected int tileId;
protected int tileColor;
//Tile color: refiere al color del tile actual
//nivelColor : refiere al index en el nivel (level tile)
public TileBasico(int id, int x, int y, int tileColor, int nivelColor)
{
super(id, false, false, nivelColor);
this.tileId = x + y * 32;
this.tileColor = tileColor;
}
@Override
public void render(Pantalla screen, Nivel level, int x, int y) {
screen.render(x, y, tileId, tileColor,0x00,1);
}
}
|
java
| 7 | 0.715891 | 71 | 20.482759 | 29 |
starcoderdata
|
#-*- coding: utf-8 -*-
import os
import errno
import logging
import paramiko
from django.db import models
from .BaseDestination import BaseDestination
from ..mixins import AccessableMixin
class SFTPDestination(AccessableMixin, BaseDestination):
client = None
def connect(self):
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.client.load_system_host_keys()
pvtkey = paramiko.RSAKey.from_private_key_file(os.path.expanduser(self.key_filename))
self.client.connect(hostname=self.hostname,
port=int(self.port),
username=self.username,
pkey=pvtkey,
timeout=5.0)
return self.client.open_sftp()
def backup(self, contents, subdir, filename, *args, **kwargs):
#print "Hello! This is %s's backup method" % self.__class__.__name__
fd = os.path.join(self.directory, subdir)
sftp = None
try:
sftp = self.connect()
if not self._rexists(sftp,subdir):
sftp.mkdir(subdir)
logging.warning('caminho criado')
sftp.chdir(subdir)
try:
with sftp.open(filename, 'wb+') as f:
for data in contents.chunks():
f.write(data)
except Exception, e:
print e
logging.error(e, errno)
raise
sftp.close()
if self.client:
self.client.close()
return True
except:
if sftp:
sftp.close()
if self.client:
self.client.close()
raise
def restore(self, subdir, filename, *args, **kwargs):
#print "Hello! This is %s's restore method" % self.__class__.__name__
try:
sftp = self.connect()
sftp.chdir(subdir)
with sftp.open(filename, 'rb') as f:
data = [chunks for chunks in iter(lambda: f.read(64 * 1024), '')]
sftp.close()
return (data, True)
except Exception, e:
print e
logging.error(e, errno)
sftp.close()
return (None, False)
def _rexists(self, sftp, path):
"""
Verifica se arquivo existe no servidor remoto
http://docs.python.org/2/library/errno.html#errno.ENOENT
"""
try:
sftp.stat(path)
except IOError, e:
if e.errno == errno.ENOENT:
print e, errno
return False
raise
else:
return True
class Meta:
verbose_name = u'destino SFTP'
verbose_name_plural = u'destinos SFTP'
app_label = 'server'
|
python
| 19 | 0.506132 | 93 | 28.881188 | 101 |
starcoderdata
|
package com.bidbubai.fermat_dap_plugin.layer.digital_asset_transaction.issuer_redemption.bitdubai.version_1.structure.events;
import com.bidbubai.fermat_dap_plugin.layer.digital_asset_transaction.issuer_redemption.bitdubai.version_1.IssuerRedemptionDigitalAssetTransactionPluginRoot;
import com.bidbubai.fermat_dap_plugin.layer.digital_asset_transaction.issuer_redemption.bitdubai.version_1.exceptions.CantCheckAssetIssuerRedemptionProgressException;
import com.bidbubai.fermat_dap_plugin.layer.digital_asset_transaction.issuer_redemption.bitdubai.version_1.structure.database.IssuerRedemptionDao;
import com.bidbubai.fermat_dap_plugin.layer.digital_asset_transaction.issuer_redemption.bitdubai.version_1.structure.database.IssuerRedemptionDatabaseConstants;
import com.bidbubai.fermat_dap_plugin.layer.digital_asset_transaction.issuer_redemption.bitdubai.version_1.structure.database.IssuerRedemptionDatabaseFactory;
import com.bitdubai.fermat_api.DealsWithPluginIdentity;
import com.bitdubai.fermat_api.layer.all_definition.enums.Plugins;
import com.bitdubai.fermat_api.layer.dmp_world.Agent;
import com.bitdubai.fermat_api.layer.dmp_world.wallet.exceptions.CantStartAgentException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.Database;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DealsWithPluginDatabaseSystem;
import com.bitdubai.fermat_api.layer.osa_android.database_system.PluginDatabaseSystem;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantCreateDatabaseException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantExecuteQueryException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantOpenDatabaseException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseNotFoundException;
import com.bitdubai.fermat_api.layer.osa_android.logger_system.DealsWithLogger;
import com.bitdubai.fermat_api.layer.osa_android.logger_system.LogManager;
import com.bitdubai.fermat_bch_api.layer.crypto_network.bitcoin.interfaces.BitcoinNetworkManager;
import com.bitdubai.fermat_bch_api.layer.crypto_vault.asset_vault.interfaces.AssetVaultManager;
import com.bitdubai.fermat_ccp_api.layer.crypto_transaction.outgoing_intra_actor.interfaces.OutgoingIntraActorManager;
import com.bitdubai.fermat_dap_api.layer.all_definition.exceptions.CantSetObjectException;
import com.bitdubai.fermat_dap_api.layer.dap_transaction.asset_issuing.exceptions.CantDeliverDigitalAssetToAssetWalletException;
import com.bitdubai.fermat_dap_api.layer.dap_transaction.common.exceptions.CantExecuteDatabaseOperationException;
import com.bitdubai.fermat_dap_api.layer.dap_transaction.common.exceptions.CantInitializeAssetMonitorAgentException;
import com.bitdubai.fermat_pip_api.layer.platform_service.error_manager.DealsWithErrors;
import com.bitdubai.fermat_pip_api.layer.platform_service.error_manager.ErrorManager;
import com.bitdubai.fermat_pip_api.layer.platform_service.error_manager.UnexpectedPluginExceptionSeverity;
import com.bitdubai.fermat_pip_api.layer.platform_service.event_manager.interfaces.DealsWithEvents;
import com.bitdubai.fermat_pip_api.layer.platform_service.event_manager.interfaces.EventManager;
import java.util.UUID;
import java.util.logging.Logger;
/**
* Created by ( on 09/10/15.
*/
public class IssuerRedemptionMonitorAgent implements Agent,DealsWithLogger,DealsWithEvents,DealsWithErrors, DealsWithPluginDatabaseSystem, DealsWithPluginIdentity {
Database database;
String userPublicKey;
MonitorAgent monitorAgent;
Thread agentThread;
LogManager logManager;
EventManager eventManager;
ErrorManager errorManager;
PluginDatabaseSystem pluginDatabaseSystem;
UUID pluginId;
OutgoingIntraActorManager outgoingIntraActorManager;
AssetVaultManager assetVaultManager;
//DigitalAssetIssuingVault digitalAssetIssuingVault;
BitcoinNetworkManager bitcoinNetworkManager;
//TODO: clean up this class
public IssuerRedemptionMonitorAgent(EventManager eventManager,
PluginDatabaseSystem pluginDatabaseSystem,
ErrorManager errorManager,
UUID pluginId,
String userPublicKey,
AssetVaultManager assetVaultManager,
OutgoingIntraActorManager outgoingIntraActorManager) throws CantSetObjectException {
this.eventManager = eventManager;
this.pluginDatabaseSystem = pluginDatabaseSystem;
this.errorManager = errorManager;
this.pluginId = pluginId;
this.userPublicKey = userPublicKey;
setAssetVaultManager(assetVaultManager);
setOutgoingIntraActorManager(outgoingIntraActorManager);
}
private void setOutgoingIntraActorManager(OutgoingIntraActorManager outgoingIntraActorManager)throws CantSetObjectException{
if(outgoingIntraActorManager==null){
throw new CantSetObjectException("outgoingIntraActorManager is null");
}
this.outgoingIntraActorManager=outgoingIntraActorManager;
}
private void setAssetVaultManager(AssetVaultManager assetVaultManager) throws CantSetObjectException{
if(assetVaultManager==null){
throw new CantSetObjectException("AssetVaultManager is null");
}
this.assetVaultManager=assetVaultManager;
}
/*public void setDigitalAssetIssuingVault(DigitalAssetIssuingVault digitalAssetIssuingVault)throws CantSetObjectException{
if(digitalAssetIssuingVault ==null){
throw new CantSetObjectException("DigitalAssetIssuingVault is null");
}
this.digitalAssetIssuingVault = digitalAssetIssuingVault;
}*/
public void setBitcoinNetworkManager(BitcoinNetworkManager bitcoinNetworkManager) throws CantSetObjectException{
if(bitcoinNetworkManager ==null){
throw new CantSetObjectException("bitcoinNetworkManager is null");
}
this.bitcoinNetworkManager = bitcoinNetworkManager;
}
@Override
public void start() throws CantStartAgentException {
Logger LOG = Logger.getGlobal();
LOG.info("Asset Issuing monitor agent starting");
monitorAgent = new MonitorAgent();
((DealsWithPluginDatabaseSystem) this.monitorAgent).setPluginDatabaseSystem(this.pluginDatabaseSystem);
((DealsWithErrors) this.monitorAgent).setErrorManager(this.errorManager);
try {
((MonitorAgent) this.monitorAgent).Initialize();
} catch (CantInitializeAssetMonitorAgentException exception) {
errorManager.reportUnexpectedPluginException(Plugins.BITDUBAI_ASSET_ISSUING_TRANSACTION, UnexpectedPluginExceptionSeverity.DISABLES_THIS_PLUGIN, exception);
}
this.agentThread = new Thread(monitorAgent);
this.agentThread.start();
}
@Override
public void stop() {
this.agentThread.interrupt();
}
@Override
public void setErrorManager(ErrorManager errorManager) {
this.errorManager=errorManager;
}
@Override
public void setEventManager(EventManager eventManager) {
this.eventManager=eventManager;
}
@Override
public void setLogManager(LogManager logManager) {
this.logManager=logManager;
}
@Override
public void setPluginDatabaseSystem(PluginDatabaseSystem pluginDatabaseSystem) {
this.pluginDatabaseSystem=pluginDatabaseSystem;
}
@Override
public void setPluginId(UUID pluginId) {
this.pluginId=pluginId;
}
/**
* Private class which implements runnable and is started by the Agent
* Based on MonitorAgent created by
*/
private class MonitorAgent implements /*IssuerRedemptionNotificationAgent,*/ DealsWithPluginDatabaseSystem, DealsWithErrors, Runnable{
ErrorManager errorManager;
PluginDatabaseSystem pluginDatabaseSystem;
public final int SLEEP_TIME = /*IssuerRedemptionNotificationAgent.AGENT_SLEEP_TIME*/5000;
int iterationNumber = 0;
IssuerRedemptionDao issuerRedemptionDao;
boolean threadWorking;
@Override
public void setErrorManager(ErrorManager errorManager) {
this.errorManager = errorManager;
}
@Override
public void setPluginDatabaseSystem(PluginDatabaseSystem pluginDatabaseSystem) {
this.pluginDatabaseSystem = pluginDatabaseSystem;
}
@Override
public void run() {
threadWorking=true;
logManager.log(IssuerRedemptionDigitalAssetTransactionPluginRoot.getLogLevelByClass(this.getClass().getName()), "Asset Issuing Transaction Protocol Notification Agent: running...", null, null);
while(threadWorking){
/**
* Increase the iteration counter
*/
iterationNumber++;
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException interruptedException) {
return;
}
/**
* now I will check if there are pending transactions to raise the event
*/
try {
logManager.log(IssuerRedemptionDigitalAssetTransactionPluginRoot.getLogLevelByClass(this.getClass().getName()), "Iteration number " + iterationNumber, null, null);
doTheMainTask();
} catch (CantDeliverDigitalAssetToAssetWalletException | CantCheckAssetIssuerRedemptionProgressException | CantExecuteQueryException e) {
errorManager.reportUnexpectedPluginException(Plugins.BITDUBAI_ISSUER_REDEMPTION_TRANSACTION, UnexpectedPluginExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_PLUGIN, e);
}
}
}
public void Initialize() throws CantInitializeAssetMonitorAgentException {
try {
database = this.pluginDatabaseSystem.openDatabase(pluginId, IssuerRedemptionDatabaseConstants.ASSET_ISSUER_REDEMPTION_DATABASE);
}
catch (DatabaseNotFoundException databaseNotFoundException) {
Logger LOG = Logger.getGlobal();
LOG.info("Database in issuer redemption agent doesn't exists");
IssuerRedemptionDatabaseFactory assetIssuingTransactionDatabaseFactory=new IssuerRedemptionDatabaseFactory(this.pluginDatabaseSystem);
try {
database = assetIssuingTransactionDatabaseFactory.createDatabase(pluginId, userPublicKey);
} catch (CantCreateDatabaseException cantCreateDatabaseException) {
errorManager.reportUnexpectedPluginException(Plugins.BITDUBAI_ISSUER_REDEMPTION_TRANSACTION, UnexpectedPluginExceptionSeverity.DISABLES_THIS_PLUGIN,cantCreateDatabaseException);
throw new CantInitializeAssetMonitorAgentException(cantCreateDatabaseException,"Initialize Monitor Agent - trying to create the plugin database","Please, check the cause");
}
} catch (CantOpenDatabaseException exception) {
errorManager.reportUnexpectedPluginException(Plugins.BITDUBAI_ISSUER_REDEMPTION_TRANSACTION, UnexpectedPluginExceptionSeverity.DISABLES_THIS_PLUGIN, exception);
throw new CantInitializeAssetMonitorAgentException(exception,"Initialize Monitor Agent - trying to open the plugin database","Please, check the cause");
}
}
private void doTheMainTask() throws CantCheckAssetIssuerRedemptionProgressException, CantExecuteQueryException, CantDeliverDigitalAssetToAssetWalletException {
Logger LOG = Logger.getGlobal();
//LOG.info("Asset Issuing monitor agent DoTheMainTask");
try {
issuerRedemptionDao =new IssuerRedemptionDao(pluginDatabaseSystem,pluginId);
} catch (CantExecuteDatabaseOperationException exception) {
throw new CantExecuteQueryException(CantExecuteDatabaseOperationException.DEFAULT_MESSAGE, exception, "Exception in asset Issuing monitor agent","Cannot execute database operation");
} /*catch (OutgoingIntraActorCantGetCryptoStatusException exception) {
throw new CantCheckAssetIssuerRedemptionProgressException(exception,"Exception in asset Issuing monitor agent","Exception in OutgoingIntraActor plugin");
} catch (UnexpectedResultReturnedFromDatabaseException exception) {
throw new CantCheckAssetIssuerRedemptionProgressException(exception,"Exception in asset Issuing monitor agent","Unexpected result in database query");
} catch (CantGetCryptoTransactionException exception){
throw new CantCheckAssetIssuerRedemptionProgressException(exception,"Exception in asset Issuing monitor agent","Cannot get genesis transaction from asset vault");
} catch (CantDeleteDigitalAssetFromLocalStorageException exception) {
this.errorManager.reportUnexpectedPluginException(Plugins.BITDUBAI_ASSET_ISSUING_TRANSACTION, UnexpectedPluginExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_PLUGIN, exception);
} catch (DAPException exception) {
throw new CantCheckAssetIssuerRedemptionProgressException(exception,"Exception in asset Issuing monitor agent","Cannot check the asset issuing progress");
} catch (OutgoingIntraActorCantGetSendCryptoTransactionHashException exception) {
throw new CantCheckAssetIssuerRedemptionProgressException(exception,"Exception in asset Issuing monitor agent","Cannot get the genesis transaction from Outgoing Intra actor");
} catch (CantGetOutgoingIntraActorTransactionManagerException exception) {
throw new CantCheckAssetIssuerRedemptionProgressException(exception,"Exception in asset Issuing monitor agent","Cannot get the outgoing intra actor transaction manager");
} catch(Exception exception){
throw new CantCheckAssetIssuerRedemptionProgressException(exception,"Exception in asset Issuing monitor agent","Unexpected exception");
}*/
}
}
}
|
java
| 19 | 0.739293 | 205 | 54.714286 | 259 |
starcoderdata
|
package com.leammin.leetcode.medium;
import com.leammin.leetcode.struct.ListNode;
/**
* 148. 排序链表
*
* 时间复杂度和常数级空间复杂度下,对链表进行排序。
*
* 1:
*
* 4->2->1->3
* 1->2->3->4
*
*
* 2:
*
* -1->5->3->4->0
* -1->0->3->4->5
*
*
* @author Leammin
* @date 2021-01-10
*/
public interface SortList {
ListNode sortList(ListNode head);
class Solution implements SortList {
@Override
public ListNode sortList(ListNode head) {
if (head == null) {
return null;
}
ListNode s = sort(head);
head = s.next;
s.next = null;
return head;
}
private ListNode sort(ListNode head) {
if (head.next == null) {
head.next = head;
return head;
}
ListNode h = new ListNode(0);
ListNode t = h;
ListNode i = head;
while (i.next != null) {
if (i.next.val < head.val) {
t.next = i.next;
t = t.next;
i.next = i.next.next;
t.next = null;
} else {
i = i.next;
}
}
ListNode result = head;
if (head.next != null) {
result = sort(head.next);
head.next = result.next;
result.next = head;
}
if (h.next != null) {
ListNode leftTail = sort(h.next);
result.next = leftTail.next;
leftTail.next = head;
}
return result;
}
}
class Solution2 implements SortList {
@Override
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode[] bucket = new ListNode[200001];
while (head != null) {
ListNode next = head.next;
int index = head.val + 100000;
head.next = bucket[index];
bucket[index] = head;
head = next;
}
ListNode h = new ListNode(0);
ListNode t = h;
for (ListNode node : bucket) {
t.next = node;
while (t.next != null) {
t = t.next;
}
}
return h.next;
}
}
class Solution3 implements SortList {
@Override
public ListNode sortList(ListNode head) {
int length = getLength(head);
int sublen = 1;
while (sublen < length) {
ListNode rh = null;
ListNode rt = null;
while (head != null) {
ListNode a = head;
ListNode at = nextOrTail(a, sublen - 1);
ListNode b = at.next;
ListNode bt = nextOrTail(b, sublen - 1);
head = null;
at.next = null;
if (bt != null) {
head = bt.next;
bt.next = null;
}
ListNode mergeTail = merge(a, b);
ListNode mergeHead = mergeTail.next;
mergeTail.next = null;
if (rh == null) {
rh = mergeHead;
rt = mergeTail;
} else {
rt.next = mergeHead;
rt = mergeTail;
}
}
head = rh;
sublen *= 2;
}
return head;
}
private ListNode merge(ListNode a, ListNode b) {
ListNode head = new ListNode(0);
ListNode tail = head;
while (a != null && b != null) {
if (a.val <= b.val) {
tail.next = a;
a = a.next;
} else {
tail.next = b;
b = b.next;
}
tail = tail.next;
tail.next = null;
}
tail.next = a;
while (a != null) {
tail = a;
a = a.next;
}
tail.next = b;
while (b != null) {
tail = b;
b = b.next;
}
tail.next = head.next;
head.next = null;
return tail;
}
private int getLength(ListNode head) {
int length = 0;
for (ListNode tmp = head; tmp != null; tmp = tmp.next) {
length++;
}
return length;
}
public ListNode nextOrTail(ListNode node, int times) {
if (node == null) {
return null;
}
for (int i = 0; i < times && node.next != null; i++) {
node = node.next;
}
return node;
}
}
}
|
java
| 16 | 0.389821 | 89 | 27.531915 | 188 |
starcoderdata
|
public double getManualShooterSpeed() {
final double complement = (1 - SHOOTER_MINIMUM_SPEED.get()) / 2;
final double complementsComplement = 1 - complement;
double axis = -stickOperator.getAxis(Joystick.AxisType.kThrottle);
double ret = -(axis * complement + complementsComplement);
//It is now between SHOOTER_MINIMUM_SPEED and 1.0
return axis >= THROTTLE_DEAD_ZONE ? ret : 0.0;
}
|
java
| 10 | 0.655329 | 74 | 53.375 | 8 |
inline
|
package ajtest2;
public class User
{
private String name;
public String getName()
{
return name;
}
public void setName( String name)
{
this.name = name;
}
static public void main(String args[])
{
User u = new User();
System.out.println(u.getName());
u.setName("blah blah");
System.out.println(u.getName());
}
}
|
java
| 10 | 0.637975 | 40 | 14.8 | 25 |
starcoderdata
|
package net.poc.ui;
import io.appium.java_client.MobileBy;
import net.serenitybdd.screenplay.targets.Target;
import org.openqa.selenium.By;
public class CameraViewerPage {
public static final Target SHUTTER = Target.the("Shutter").located(
MobileBy.AccessibilityId("click to capture"));
public static final Target CONFIRM = Target.the("Ok button").located(
MobileBy.AccessibilityId("OK"));
}
|
java
| 10 | 0.726636 | 73 | 29.571429 | 14 |
starcoderdata
|
def setUp(self):
"""This method is run before every test in this class"""
# Create a mock species dictionary
# In reality, the values would be Species objects, but it doesn't matter for testing
species_dict = {
'A': 'A',
'B': 'B',
'C': 'C',
'X': 'X',
}
# Assign to global variable in the input module
inp.species_dict = species_dict
# Initialize the rmg.reaction_systems attribute
global rmg
rmg.reaction_systems = []
|
python
| 8 | 0.541133 | 92 | 31.235294 | 17 |
inline
|
#!/usr/bin/env python
# Copyright 2018
# Copyright (c) 2009-2010 Itaapy, Pierlis, Talend.
#
# 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.
#
#
# Authors (odfdo project):
# The odfdo project is a derivative work of the lpod-python project:
# https://github.com/lpod/lpod-python
# Authors:
from datetime import datetime, timedelta
from decimal import Decimal
from unittest import TestCase, main
from odfdo.datatype import DateTime, Duration, Boolean, Unit
class DateTimeTestCase(TestCase):
def test_encode(self):
date = datetime(2009, 0o6, 26, 11, 9, 36)
expected = "2009-06-26T11:09:36"
self.assertEqual(DateTime.encode(date), expected)
def test_decode(self):
date = "2009-06-29T14:33:21"
expected = datetime(2009, 6, 29, 14, 33, 21)
self.assertEqual(DateTime.decode(date), expected)
class DurationTestCase(TestCase):
def test_encode(self):
duration = timedelta(0, 53, 0, 0, 6)
expected = "PT00H06M53S"
self.assertEqual(Duration.encode(duration), expected)
def test_decode(self):
duration = "PT12H34M56S"
expected = timedelta(0, 56, 0, 0, 34, 12)
self.assertEqual(Duration.decode(duration), expected)
class BooleanTestCase(TestCase):
def test_encode(self):
self.assertEqual(Boolean.encode(True), "true")
self.assertEqual(Boolean.encode(False), "false")
self.assertEqual(Boolean.encode("true"), "true")
self.assertEqual(Boolean.encode("false"), "false")
def test_bad_encode(self):
self.assertRaises(TypeError, Boolean.encode, "on")
self.assertRaises(TypeError, Boolean.encode, 1)
def test_decode(self):
self.assertEqual(Boolean.decode("true"), True)
self.assertEqual(Boolean.decode("false"), False)
def test_bad_decode(self):
self.assertRaises(ValueError, Boolean.decode, "True")
self.assertRaises(ValueError, Boolean.decode, "1")
class UnitTestCase(TestCase):
def test_str(self):
unit = Unit("1.847mm")
self.assertEqual(unit.value, Decimal("1.847"))
self.assertEqual(unit.unit, "mm")
def test_int(self):
unit = Unit(1)
self.assertEqual(unit.value, Decimal("1"))
self.assertEqual(unit.unit, "cm")
def test_float(self):
unit = Unit(3.14)
self.assertEqual(unit.value, Decimal("3.14"))
self.assertEqual(unit.unit, "cm")
def test_encode(self):
value = "1.847mm"
unit = Unit(value)
self.assertEqual(str(unit), value)
# TODO use other units once conversion implemented
def test_eq(self):
unit1 = Unit("2.54cm")
unit2 = Unit("2.54cm")
self.assertTrue(unit1 == unit2)
def test_lt(self):
unit1 = Unit("2.53cm")
unit2 = Unit("2.54cm")
self.assertTrue(unit1 < unit2)
def test_nlt(self):
unit1 = Unit("2.53cm")
unit2 = Unit("2.54cm")
self.assertFalse(unit1 > unit2)
def test_gt(self):
unit1 = Unit("2.54cm")
unit2 = Unit("2.53cm")
self.assertTrue(unit1 > unit2)
def test_ngt(self):
unit1 = Unit("2.54cm")
unit2 = Unit("2.53cm")
self.assertFalse(unit1 < unit2)
def test_le(self):
unit1 = Unit("2.54cm")
unit2 = Unit("2.54cm")
self.assertTrue(unit1 <= unit2)
def test_ge(self):
unit1 = Unit("2.54cm")
unit2 = Unit("2.54cm")
self.assertTrue(unit1 >= unit2)
def test_convert(self):
unit = Unit("10cm")
self.assertEqual(unit.convert("px"), Unit("283px"))
if __name__ == "__main__":
main()
|
python
| 11 | 0.633254 | 74 | 29.289855 | 138 |
starcoderdata
|
package main
import (
"fmt"
"github.com/cryptowilliam/goutil/sys/gcron"
"sync"
"time"
)
var wg sync.WaitGroup
func tryFreq(fm *gcron.RateLimiter, id int) {
defer wg.Add(-1)
for i := 0; i < 5; i++ {
fm.MarkAndWaitBlock()
fmt.Println(fmt.Sprintf("Routine %d got a frequency mutex", id))
}
}
func main() {
fm := gcron.NewRateLimiter(time.Millisecond * 1000)
count := 10
wg.Add(count)
for i := 0; i < count; i++ {
go tryFreq(fm, i)
}
wg.Wait()
}
|
go
| 11 | 0.635193 | 66 | 15.068966 | 29 |
starcoderdata
|
package usecase_test
import (
"context"
"testing"
"github.com/golang/mock/gomock"
"github.com/indrasaputra/hashids"
"github.com/indrasaputra/orvosi-api/entity"
mock_usecase "github.com/indrasaputra/orvosi-api/test/mock/usecase"
"github.com/indrasaputra/orvosi-api/usecase"
"github.com/stretchr/testify/assert"
)
type MedicalRecordCreatorExecutor struct {
usecase *usecase.MedicalRecordCreator
repo *mock_usecase.MockInsertMedicalRecordRepository
}
func TestNewMedicalRecordCreator(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
t.Run("successfully create an instance of MedicalRecordCreator", func(t *testing.T) {
exec := createMedicalRecordCreatorExecutor(ctrl)
assert.NotNil(t, exec.usecase)
})
}
func TestMedicalRecordCreator_Create(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
t.Run("medical record entity is empty/nil", func(t *testing.T) {
exec := createMedicalRecordCreatorExecutor(ctrl)
err := exec.usecase.Create(context.Background(), nil)
assert.NotNil(t, err)
assert.Equal(t, entity.ErrEmptyMedicalRecord, err)
})
t.Run("medical record's symptom is empty", func(t *testing.T) {
exec := createMedicalRecordCreatorExecutor(ctrl)
record := createValidMedicalRecord()
record.Symptom = " "
err := exec.usecase.Create(context.Background(), record)
assert.NotNil(t, err)
assert.Equal(t, entity.ErrInvalidMedicalRecordAttribute, err)
})
t.Run("medical record's diagnosis is empty", func(t *testing.T) {
exec := createMedicalRecordCreatorExecutor(ctrl)
record := createValidMedicalRecord()
record.Diagnosis = " "
err := exec.usecase.Create(context.Background(), record)
assert.NotNil(t, err)
assert.Equal(t, entity.ErrInvalidMedicalRecordAttribute, err)
})
t.Run("medical record's therapy is empty", func(t *testing.T) {
exec := createMedicalRecordCreatorExecutor(ctrl)
record := createValidMedicalRecord()
record.Therapy = ""
err := exec.usecase.Create(context.Background(), record)
assert.NotNil(t, err)
assert.Equal(t, entity.ErrInvalidMedicalRecordAttribute, err)
})
t.Run("medical record's user is nil", func(t *testing.T) {
exec := createMedicalRecordCreatorExecutor(ctrl)
record := createValidMedicalRecord()
record.User = nil
err := exec.usecase.Create(context.Background(), record)
assert.NotNil(t, err)
assert.Equal(t, entity.ErrInvalidMedicalRecordAttribute, err)
})
t.Run("medical record repo fails", func(t *testing.T) {
exec := createMedicalRecordCreatorExecutor(ctrl)
record := createValidMedicalRecord()
exec.repo.EXPECT().Insert(context.Background(), record).Return(entity.ErrInternalServer)
err := exec.usecase.Create(context.Background(), record)
assert.NotNil(t, err)
assert.Equal(t, entity.ErrInternalServer, err)
})
t.Run("successfully create a new medical record", func(t *testing.T) {
exec := createMedicalRecordCreatorExecutor(ctrl)
record := createValidMedicalRecord()
exec.repo.EXPECT().Insert(context.Background(), record).Return(nil)
err := exec.usecase.Create(context.Background(), record)
assert.Nil(t, err)
})
}
func createValidMedicalRecord() *entity.MedicalRecord {
return &entity.MedicalRecord{
ID: hashids.ID(1),
Symptom: "symptom",
Diagnosis: "diagnosis",
Therapy: "therapy",
Result: "result",
User: &entity.User{
ID: hashids.ID(1),
Email: "
Name: "User 1",
GoogleID: "super-long-google-id",
},
}
}
func createMedicalRecordCreatorExecutor(ctrl *gomock.Controller) *MedicalRecordCreatorExecutor {
r := mock_usecase.NewMockInsertMedicalRecordRepository(ctrl)
u := usecase.NewMedicalRecordCreator(r)
return &MedicalRecordCreatorExecutor{
usecase: u,
repo: r,
}
}
|
go
| 17 | 0.733106 | 96 | 27.073529 | 136 |
starcoderdata
|
void FRule::addMultiAssignment(vn_t from, VarName to, bool trusted) {
if (!from || to.name().empty())
return;
// We do not support MultiNames as the receiver of assignments
mul_t froms;
if (from->type == VarType::MULTI) {
froms = static_pointer_cast<MultiName>(from);
} else {
froms->insert(from);
}
for (vn_t subname: froms->names()) {
if (!subname) {
continue;
}
Assignment A(*subname, to, trusted);
assignments.push_back(A);
}
}
|
c++
| 11 | 0.619048 | 69 | 23.2 | 20 |
inline
|
from alice_and_bob.primes import Prime
def test_known_prime():
prime = Prime(3)
assert isinstance(prime, int)
assert prime == 3
def test_raises_value_error_when_not_prime():
try:
not_prime = Prime(4)
assert not_prime == 4
except ValueError:
pass
else:
raise AssertionError('ValueError not raise for non-prime')
def test_large_non_prime():
try:
big_even = Prime.primes[-1] + 1
non_prime = Prime(big_even)
assert non_prime % 2 == 0
except ValueError:
pass
else:
raise AssertionError('Expected ValueError to be raised for large even number')
def test_large_prime():
primes = Prime.primes.copy() # backup primes data
Prime.primes = [2, 3, 5]
prime = Prime(7)
assert prime == Prime.primes[-1] == 7
Prime.primes = primes # restore original data
def test_non_integer():
try:
Prime(3.1)
except TypeError:
pass
else:
raise AssertionError('Expected TypeError to be raised when passing float value')
|
python
| 10 | 0.624319 | 88 | 22.446809 | 47 |
starcoderdata
|
from constants import *
from collections import deque
class Node():
def __init__(self, value=None):
self.value = value
self.children = []
def __eq__(self, other):
"""Overrides the default implementation
For our purposes, at the node level, we consider a node equal to another if they share the same value
and their children share the same value"""
if isinstance(other, Node):
is_equal = self.value == other.value and len(self.children) == len(other.children)
if is_equal:
for child_ind in range(len(self.children)):
if self.children[child_ind].value != other.children[child_ind].value:
return False
return is_equal
return False
def __ne__(self, other):
"""Overrides the default implementation (unnecessary in Python 3)"""
return not self.__eq__(other)
def set_value(self, value):
self.value = value
def set_child_at_index(self, child, index=-1):
if index == -1:
self.children.append(child)
else:
self.children[index] = child
def get_value(self):
return self.value
def get_child_at_index(self, index=-1):
assert abs(index) < len(self.children)
return self.children[index]
def get_children(self):
return self.children
class Tree():
def __init__(self, root):
'''
Initialize tree with root
@param root: root is an object of type Node, representing root of the binary tree
'''
self.root = root
def __eq__(self, other):
"""Overrides the default implementation
For our purposes, at the node level, we consider a node equal to another if they share the same value
and their children share the same value"""
if isinstance(other, Tree):
return self.get_prefix_traversal(self.root) == self.get_prefix_traversal(other.root)
return False
def __ne__(self, other):
"""Overrides the default implementation (unnecessary in Python 3)"""
return not self.__eq__(other)
def get_prefix_traversal(self, start_node=None):
'''
Get prefix traversal of tree
:param start_node: node in the tree, which is root of the subtree we
would like a prefix traversal for
:return: prefix traversal
'''
if start_node == None:
return []
def is_pos_tag(node):
children = node.get_children()
return len(children) == 1 and children[0] and len(children[0].get_children()) == 0
# If we reach a POS tag we follow the same format as
# the Stanford parser prefix
if is_pos_tag(start_node):
prefix_traversal = ["(", start_node.value, start_node.get_children()[0].value, ")"]
return prefix_traversal
prefix_traversal = ["(", start_node.value]
for each_child in start_node.get_children():
prefix_traversal += self.get_prefix_traversal(each_child)
prefix_traversal.append(")")
return prefix_traversal
def get_ancestors(self, query_node, current_node, path=[]):
'''
Get all ancestors along the path from root to a query node
:param query_node: Node object whose ancestors we want
'''
if current_node == None:
return []
# If we reach our query node
if current_node == query_node:
return [current_node]
found_query = False
for each_child in current_node.get_children():
path_to_leaf = self.get_ancestors(query_node, each_child, path)
if len(path_to_leaf) > 0:
found_query = True
path = path_to_leaf
path.append(current_node)
return path
if not found_query:
return []
def get_nodes_with_value(self, query_value, start_node, path=[]):
'''
Get all nodes with a particular value
:param query_node: Node object whose ancestors we want
'''
nodes_with_value = []
def visit_all_nodes(query_value, current_node):
if current_node == None:
return
# If we reach our query node
if current_node.value == query_value:
nodes_with_value.append(current_node)
for each_child in current_node.get_children():
visit_all_nodes(query_value, each_child)
visit_all_nodes(query_value, start_node)
return nodes_with_value
def get_subtree(parts, start_index):
'''
get_subtree returns the end_index in the parse prefix expression corresponding to a given subtree
:param parts: prefix expression of constituency parse of the sentence in the form of a list
:param start_index: start of the subtree
:return: end_index: end of the subtree in the prefix expression
'''
# This is invalid
if parts[start_index] != '(':
return -1
# Create a deque to use it as a stack.
stack = deque()
for element_index in range(start_index, len(parts)):
# Pop a starting bracket
# for every closing bracket
if parts[element_index] == ')':
stack.popleft()
# Push all starting brackets
elif parts[element_index] == '(':
stack.append(parts[element_index])
# If stack becomes empty
if not stack:
end_index = element_index
return end_index
return -1
def get_tree(parts, start_index):
'''
Returns tree structure
:param parts:
:param start_index:
:return:
'''
if start_index >= len(parts):
return Node(None)
# Current Node in prefix expression becomes value of the node
value_index = start_index + 1 # TAG after opening brace
value = parts[value_index]
node = Node(value)
subtree_start = value_index + 1
while parts[subtree_start] == "(":
subtree_end = get_subtree(parts, subtree_start)
if subtree_end - subtree_start == 3:
pos_tag = parts[subtree_start + 1]
word = parts[subtree_end - 1]
child_node = Node(pos_tag)
word_node = Node(word)
child_node.set_child_at_index(word_node, -1)
node.set_child_at_index(child_node, -1)
else:
node.set_child_at_index(get_tree(parts, subtree_start), -1)
subtree_start = subtree_end + 1
return node
def construct_parse(parse):
'''
Converts prefix expression of parse to an expression tree
:param parse: constituency parse of the sentence in prefix
:return: expression tree of constituency parse of the sentence
'''
parse = parse.replace("(", " ( ")
parse = parse.replace(")", " ) ")
parts = parse.split()
start_index = 0
root = get_tree(parts, start_index)
parse_tree = Tree(root)
return parse_tree
def strip_parse(parse):
parse = " ".join(parse)
parse = parse.replace("(", " ")
parse = parse.replace(")", " ")
for each_postag in tagset:
parse = parse.replace(each_postag, "")
parse = " ".join(parse.split())
return parse
|
python
| 16 | 0.588275 | 109 | 29.619247 | 239 |
starcoderdata
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Transaksi;
use DB;
class TransaksiController extends Controller
{
public function index(){
$transaksi = DB::table('transaksis')->where('tgl_dikembalikan','=', null)->get();
// return $jurusan;
$data = array(
'transaksi' => $transaksi
);
return view('transaksi.index',$data);
}
function create()
{
return view('transaksi.create');
}
function store(Request $request)
{
$validatedData =$request->validate([
// 'id' => 'required',
'id_anggota' => 'required',
'kode_buku' => 'required',
'tgl_pinjam' => 'required',
'tgl_kembali' => 'required'
]);
$transaksi = new transaksi();
$transaksi->id_anggota=$request->id_anggota;
$transaksi->kode_buku=$request->kode_buku;
$transaksi->tgl_pinjam=$request->tgl_pinjam;
$transaksi->tgl_kembali=$request->tgl_kembali;
$transaksi->save();
return redirect('transaksi');
}
public function edit(transaksi $transaksi){
$data = array(
'transaksi' => $transaksi
);
return view('transaksi.edit',$data);
}
public function update(transaksi $transaksi)
{
$transaksi->update([
$transaksi->id_anggota=$request->id_anggota,
$transaksi->kode_buku=$request->kode_buku,
$transaksi->tgl_pinjam=$request->tgl_pinjam,
$transaksi->tgl_kembali=$request->tgl_kembali
]);
return redirect('/transaksi');
}
public function destroy(transaksi $transaksi){
$transaksi->delete();
return redirect()->route('transaksi.index');
}
public function kembali( $transaksi)
{
$fromDB = Transaksi::where('id',$transaksi)->first();
$dataTrans = $fromDB->tgl_kembali;
$tgl_dikembalikan = date('Y-m-d');
$denda=1000;
$tglAwal=$dataTrans;
$tglAkhir=$tgl_dikembalikan;
// memecah string tanggal awal untuk mendapatkan
// $pecah1 = explode("-", strtotime($tglAwal));
$date1 = date('d', strtotime($tglAwal));
$month1 = date('m', strtotime($tglAwal));
$year1 = date('Y', strtotime($tglAwal));
// memecah string tanggal awal untuk mendapatkan
// $pecah2 = explode("-", strtotime($tglAkhir));
$date2 = date('d', strtotime($tglAkhir));
$month2 = date('m', strtotime($tglAkhir));
$year2 = date('Y', strtotime($tglAkhir));
// mencari selisih hari dari tanggal awal dan akhir
$jd1 = GregorianToJD($month1, $date1, $year1);
$jd2 = GregorianToJD($month2, $date2, $year2);
$selisih = $jd2 - $jd1;
$denda*=$selisih;
if ($denda<=0)
{
$denda = "0";
}
else
{
$denda;
}
$data = array
(
"id" => $fromDB->id,
"tgl_dikembalikan" => $tgl_dikembalikan,
"Denda" => $denda
);
$user = Transaksi::find($fromDB->id);
$user ->tgl_dikembalikan = $tgl_dikembalikan;
$user ->denda = $denda;
$user ->save();
return redirect('/pengembalian');
}
public function pengembalian(transaksi $transaksi)
{
$transaksi = DB::table('transaksis')->where('tgl_dikembalikan','<>', null)->get();
// return $jurusan;
$data = array(
'transaksi'=> $transaksi
);
return view('transaksi.pengembalian',$data);
}
}
|
php
| 14 | 0.579146 | 89 | 26.766129 | 124 |
starcoderdata
|
//-----------------------------------------------------------------------------
//
// File: espopts.h
// Copyright (C) 1994-1997 Microsoft Corporation
// All rights reserved.
//
//
//
//-----------------------------------------------------------------------------
LTAPIENTRY BOOL RegisterParserOptions(CLocUIOptionSet*);
LTAPIENTRY void UnRegisterParserOptions(const PUID&);
LTAPIENTRY BOOL GetParserOptionValue(const PUID &, LPCTSTR szName, CLocOptionVal *&);
LTAPIENTRY BOOL GetParserOptionBool(const PUID&, LPCTSTR pszName);
LTAPIENTRY const CPascalString GetParserOptionString(const PUID&, LPCTSTR pszName);
LTAPIENTRY DWORD GetParserOptionNumber(const PUID&, LPCTSTR pszName);
|
c
| 9 | 0.59552 | 85 | 32.545455 | 22 |
starcoderdata
|
def fancy_print(self, delete=True):
"""Fancy prints the entire time taken, the differences between the individual timestamps in absolute seconds & in percentages as well as the descriptions.
:param delete: deletes the currently stored list of timestamps after ouput, defaults to True
:type delete: bool, optional
"""
r = self._get_individual_differences()
entire_time = self._get_entire_difference()
self.output_func("------ Time measurements ------")
if self.time_unit == "seconds":
self.output_func(f"Overall: {format(entire_time.total_seconds(), self.decimals_time_f)} seconds")
elif self.time_unit == "milliseconds":
self.output_func(f"Overall: {format(entire_time.total_seconds() * 1000, self.decimals_time_f)} milliseconds")
else:
self.output_func(f"Overall: {entire_time}")
# return early if no steps were recorded
if len(r) == 0:
return
# get length of maximum step-string
step_max_length = len(str(len(r)))
# get length of maximum seconds & millisecond-string
if self.time_unit == "seconds":
time_sec_max_length = max([len(format(x[0].total_seconds(), self.decimals_time_f)) for x in r])
elif self.time_unit == "milliseconds":
time_ms_max_length = max([len(format(x[0].total_seconds() * 1000, self.decimals_time_f)) for x in r])
# output step: step number, time taken and percentage of time taken by step compared to overall time taken
for i, e in enumerate(r):
step = f"{i}".rjust(step_max_length)
perc = f"{e[1]}".format(1.2).rjust(self.decimals_percentage + 4)
# format time values and rjust them in case they have differing lengths
if self.time_unit == "seconds":
time = f"{format(e[0].total_seconds(), self.decimals_time_f)}".rjust(time_sec_max_length) + " seconds"
elif self.time_unit == "milliseconds":
time = f"{format(e[0].total_seconds() * 1000, self.decimals_time_f)}".rjust(time_ms_max_length) + " milliseconds"
else:
time = f"{e[0]}"
self.output_func(f"Step {step}: {time} - {perc} % - Description: {e[2]}")
# delete all stored timestamps if set
if delete:
self.delete_timestamps()
|
python
| 21 | 0.594239 | 162 | 49.645833 | 48 |
inline
|
'use strict';
const path = require('path');
const basePath = path.normalize(__dirname);
const { exec } = require('child_process');
const commandLineArgs = require('command-line-args');
const commandLineUsage = require('command-line-usage');
const cliConf = require(basePath + '/cli-conf.js');
const noteGroup = require(basePath + '/src/noteGroup.js');
const usage = commandLineUsage(cliConf.sections);
/* Parse options */
let options = commandLineArgs(cliConf.optionDefinitions);
if (options.help) {
console.log(usage);
process.exit(0);
}
if (options.input === undefined) {
console.error('You must specify an input directory, use --help for more info');
process.exit(1);
}
if (options.output === undefined) {
console.error('You must specify an output directory, use --help for more info');
process.exit(1);
}
if (options.rename === undefined)
options.rename = true;
if (options.noserver === undefined)
options.noserver = false;
if (options.port === undefined)
options.port = 8080;
options.input = path.resolve(options.input);
options.output = path.resolve(options.output);
let port = options.port;
let n = new noteGroup(options.input, options.rename);
n.outputToFolder(options.output);
if (!options.noserver) {
exec('python -m http.server ' + port, { cwd: options.output });
console.log('');
console.log('Your website can now be accessed at:');
console.log('https://localhost:' + port);
}
|
javascript
| 9 | 0.694004 | 84 | 27.470588 | 51 |
starcoderdata
|
#ifndef _List_H
#define _List_H
#include "../util/common.h"
typedef int ElementType;
struct Node;
typedef struct Node * PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
/**
* 定义 ElementType 相等的规则
*/
int equals(ElementType obj1, ElementType obj2);
/**
* gc List
* @warning: 头结点也会被 gc
*/
void gcList(List L);
/**
* 将 List 置空(只有一个头结点).
*/
List makeEmpty(List L/*in and out*/);
/**
* 判断 List 是否是为空链表
*/
int isEmpty(List L);
/**
* 判断指定位置 p 是否是 List 链表的最后一个元素.
*/
int isLast(Position p, List L);
/**
* 从链表 L 中查找第一个节点的 ElementType 等于 e 的节点位置, 相等规则由 equals 方法指定
*/
Position find(ElementType e, List L);
/**
* 删除指定 ElementType 第一次出现的结点
*/
void deleteItem(ElementType e, List L);
/**
* 查找指定 ElementType 的前驱结点
*/
Position findPrevious(ElementType e, List L);
/**
* 在 p 后面插入一个节点, 节点值为 e
*/
void insert(ElementType e, List L, Position p);
#endif /* _List_H */
|
c
| 6 | 0.667413 | 60 | 14.135593 | 59 |
starcoderdata
|
package com.codefinity.microcontinuum.common.media.canonical;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
// TODO: this is incomplete
public class CanonicalDataFormatter {
public CanonicalDataFormatter() {
super();
}
public byte[] format(Object anObject) {
for (Field field : anObject.getClass().getFields()) {
field.setAccessible(true);
byte[] formattedField = this.formatField(field, anObject);
if (formattedField.length > 0)
; // TODO
}
return null;
}
private byte[] formatField(Field aField, Object anObject) {
byte[] formatted = null;
if ((aField.getModifiers() & Modifier.STATIC) == 0) {
if (aField.getType().isPrimitive()) {
formatted = this.formatPrimitive(aField, anObject);
} else {
formatted = this.formatObject(aField, anObject);
}
}
return formatted;
}
private byte[] formatObject(Field aField, Object anObject) {
// String name = aField.getName();
// Object value;
//
// try {
// value = aField.get(anObject);
// } catch (Throwable t) {
// throw new IllegalArgumentException("The object cannot be formatted.", t);
// }
return null;
}
private byte[] formatPrimitive(Field aField, Object anObject) {
// String name = aField.getName();
// Object value;
//
// try {
// value = aField.get(anObject);
// } catch (Throwable t) {
// throw new IllegalArgumentException("An object primitive cannot be formatted.", t);
// }
return null;
}
}
|
java
| 13 | 0.568627 | 96 | 26.09375 | 64 |
starcoderdata
|
'''
Created on Aug 15, 2019
@author: Jeffrey
'''
import unittest
from datetime import date
from datetime import datetime
from datetime import time
from datetime import timedelta
from datetime import timezone
from converter.time_util import TimeUtils
class Test(unittest.TestCase):
def setUp(self):
self.test_date = date(2019,8,15)
self.test_time = time(20,10,15)
def tearDown(self):
pass
def testCalculateTimestampInputDateAndTime1(self):
time_utils = TimeUtils(self.test_date, self.test_time)
actual = time_utils.calculateTimestamp(None, None, 140.320)
expected = datetime.combine(self.test_date, self.test_time, tzinfo=timezone.utc) + timedelta(0,140.320)
self.assertEqual(expected, actual, 'The calculated timestamp did not match the expected value.')
def testCalculatedTimestampInputDateAndTime2(self):
time_utils = TimeUtils(self.test_date, self.test_time)
test_gps_date = date(1999,12,19)
actual = time_utils.calculateTimestamp(test_gps_date, None, 1432.938)
expected = datetime.combine(self.test_date, self.test_time, tzinfo=timezone.utc) + timedelta(0,1432.938)
self.assertEqual(expected, actual, 'Time calculated timestamp did not match the expected value.')
def testCalculatedTimestampInputDateAndTime3(self):
time_utils = TimeUtils(self.test_date, self.test_time)
test_gps_time = time(22,38,12)
actual = time_utils.calculateTimestamp(None, test_gps_time, 2273.431)
expected = datetime.combine(self.test_date, self.test_time, tzinfo=timezone.utc) + timedelta(0,2273.431)
self.assertEqual(expected, actual, 'Time calculated timestamp did not match the expected value.')
def testCalculatedTimestampInputDateAndTime4(self):
time_utils = TimeUtils(self.test_date, self.test_time)
test_gps_date = date(1999,12,19)
test_gps_time = time(22,38,12)
actual = time_utils.calculateTimestamp(test_gps_date, test_gps_time, 1174.835)
expected = datetime.combine(self.test_date, self.test_time, tzinfo=timezone.utc) + timedelta(0,1174.835)
self.assertEqual(expected, actual, 'Time calculated timestamp did not match the expected value.')
def testCalculateTimestampInputDate1(self):
time_utils = TimeUtils(self.test_date, None)
actual = time_utils.calculateTimestamp(None, None, 140.320)
self.assertIsNone(actual, 'The calculated timestamp was expected to be None.')
def testCalculatedTimestampInputDate2(self):
time_utils = TimeUtils(self.test_date, None)
test_gps_date = date(1999,12,19)
actual = time_utils.calculateTimestamp(test_gps_date, None, 1432.938)
self.assertIsNone(actual, 'The calculated timestamp was expected to be None.')
def testCalculatedTimestampInputDate3(self):
time_utils = TimeUtils(self.test_date, None)
test_gps_time = time(22,38,12)
actual = time_utils.calculateTimestamp(None, test_gps_time, 2273.431)
expected = datetime.combine(self.test_date, test_gps_time, tzinfo=timezone.utc)
self.assertEqual(expected, actual, 'Time calculated timestamp did not match the expected value.')
def testCalculatedTimestampInputDate4(self):
time_utils = TimeUtils(self.test_date, None)
test_gps_date = date(1999,12,19)
test_gps_time = time(22,38,12)
actual = time_utils.calculateTimestamp(test_gps_date, test_gps_time, 1174.835)
expected = datetime.combine(self.test_date, test_gps_time, tzinfo=timezone.utc)
self.assertEqual(expected, actual, 'Time calculated timestamp did not match the expected value.')
def testCalculateTimestampNoInput1(self):
time_utils = TimeUtils(None, None)
actual = time_utils.calculateTimestamp(None, None, 140.320)
self.assertIsNone(actual, 'The calculated timestamp was expected to be None.')
def testCalculatedTimestampNoInput2(self):
time_utils = TimeUtils(None, None)
test_gps_date = date(1999,12,19)
actual = time_utils.calculateTimestamp(test_gps_date, None, 1432.938)
self.assertIsNone(actual, 'The calculated timestamp was expected to be None.')
def testCalculatedTimestampNoInput3(self):
time_utils = TimeUtils(None, None)
test_gps_time = time(22,38,12)
actual = time_utils.calculateTimestamp(None, test_gps_time, 2273.431)
self.assertIsNone(actual, 'The calculated timestamp was expected to be None.')
def testCalculatedTimestampNoInput4(self):
time_utils = TimeUtils(None, None)
test_gps_date = date(2019,8,19)
test_gps_time = time(22,38,12)
actual = time_utils.calculateTimestamp(test_gps_date, test_gps_time, 1174.835)
expected = datetime.combine(test_gps_date, test_gps_time, timezone.utc)
self.assertEqual(expected, actual, 'Time calculated timestamp did not match the expected value.')
def testPosixTimestamp(self):
test_datetime = datetime(1970, 7, 1, 0, 0, 0, tzinfo=timezone.utc)
actual = test_datetime.timestamp()
self.assertEqual(15638400, actual, 'Basic python conversion to Posix timestamp fails.')
def testInfluxDbTimestamp(self):
test_datetime = datetime(2019,8,15,23,21,30,tzinfo=timezone.utc)
actual = TimeUtils.influxDBTimestamp(test_datetime)
self.assertEqual(1565911290000, actual, 'The conversion to InfluxDB timestamp did not return the expected value.')
def testInfluxDbTimestampMillisecond(self):
test_datetime = datetime(2019,8,20,12,12,12,531000,tzinfo=timezone.utc)
actual = TimeUtils.influxDBTimestamp(test_datetime)
self.assertEqual(1566303132531, actual, 'The conversion to InfluxDB timestamp did not return the expected value.')
def testInfluxDbTimestampMicrosecond(self):
test_datetime = datetime(2019,8,20,12,12,12,531999,tzinfo=timezone.utc)
actual = TimeUtils.influxDBTimestamp(test_datetime)
# currently truncates, consider rounding
self.assertEqual(1566303132531, actual, 'The conversion to InfluxDB timestamp did not return the expected value.')
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
|
python
| 12 | 0.683773 | 122 | 48.317829 | 129 |
starcoderdata
|
package de.unidue.ltl.escrito.io.util;
import java.util.HashMap;
import java.util.Map;
public class ExperimentalResultsCollectionUtils {
/**
*
*
* @param experimentalFolderPath a folder containing the output folders for all relevant experiments
* @param evalMeasure the measure to be considered
* @return a Map from ExperimentIds to the value for the specific measure
*/
public static Map<String, Double> getEvalValueForAllExperiments(String experimentalFolderPath, String evalMeasure){
return getEvalValueForAllExperiments(experimentalFolderPath, evalMeasure, ".*");
}
/**
*
*
* @param experimentalFolderPath a folder containing the output folders for all relevant experiments
* @param evalMeasure the measure to be considered
* @param filterPattern pattern to be matched against the experiment name
* @return a Map from ExperimentIds to the value for the specific measure
*/
public static Map<String, Double> getEvalValueForAllExperiments(String experimentalFolderPath, String evalMeasure, String filterPattern){
Map<String, Double> results = new HashMap<String, Double>();
// TODO
return results;
}
/**
*
* @param experimentalFolderPath
* @param filterPattern
* @return a map from prompt id to answerid to classification value
*/
public static Map<String, Map<String, String>> getClassificationResultsForAllExperiments(String experimentalFolderPath, String filterPattern){
Map<String, Map<String, String>> results = new HashMap<String, Map<String, String>>();
// TODO
return results;
}
}
|
java
| 10 | 0.76474 | 143 | 33.959184 | 49 |
starcoderdata
|
<?php
$stmDep = $pdo_conn->prepare("SELECT * FROM `departemen`");
$stmDep->execute();
$rowsDepartemen = $stmDep->fetchAll(PDO::FETCH_ASSOC);
$stmMar = $pdo_conn->prepare("SELECT * FROM `marital_status`");
$stmMar->execute();
$rowsMarital = $stmMar->fetchAll(PDO::FETCH_ASSOC);
$stmJab = $pdo_conn->prepare("SELECT * FROM `jabatan`");
$stmJab->execute();
$rowsJabatan = $stmJab->fetchAll(PDO::FETCH_ASSOC);
if(isset($_GET['id'])){
$status = "update";
$id = str_replace(date('mYd'),'',$_GET['id']);
$sql = $pdo_conn->prepare("SELECT * FROM karyawan WHERE id_karyawan='$id'");
$sql->execute();
$getData = $sql->fetch(PDO::FETCH_ASSOC);
}else{
$status = "add";
}
if(isset($_SESSION['alert'])){
$message = "";
if ($_SESSION['alert'] == "gagalUpload") {
$message = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}elseif ($_SESSION['alert'] == "gagal") {
$a = $_SESSION['error'];
foreach ($a as $data) {
$message = $message.'
}
}
echo "
Toast.fire({
icon: 'error',
title: `".$message."`
})
unset($_SESSION['alert']);
unset($_SESSION['error']);
}
?>
<div style="padding-left:100px; padding-right:100px;" >
<div class="card o-hidden border-0 shadow-lg">
<div class="card-body p-0">
<div class="card-header">
<h1 class="h4 m-0 font-weight-bold text-primary text-capitalize">Form Karyawan
<div class="row" style="margin-top: -30px">
<div class="col-lg-12">
<div class="p-5">
<form class="user" enctype="multipart/form-data" action="../action/actionKaryawan.php?status= method="post">
<input type="text" value="<?=isset($getData['username']) ? $getData['username'] : '' ?>" name="username" class="d-none">
<input type="text" value="<?=isset($getData['password']) ? $getData['password'] : '' ?>" name="password" class="d-none">
<div class="form-group row">
<div class="col-sm-6 mb-3 mb-sm-0">
<input type="text" class="form-control form-control-user form-control-sm" placeholder="Nama" tooltip="tooltip" title="Nama" name="nama" required
value="<?=isset($getData['nama']) ? $getData['nama'] : '' ?>">
<div class="col-sm-6" tooltip="tooltip" title="<?=$status=='update' ? 'NIK Not Udate' : 'NIK' ?>">
<input type="text" class="form-control form-control-user" placeholder="NIK" name="nik" required
value="<?=isset($getData['id_karyawan']) ? $getData['id_karyawan'] : '' ?>" <?=$status=='update' ? 'readonly' : '' ?> >
<div class="form-group row">
<div class="col-sm-6 mb-3 mb-sm-0">
<input type="text" class="form-control form-control-user" placeholder="Tanggal Lahir" datepicker="datepicker" tooltip="tooltip" title="Tanggal Lahir" name="ttl" required value="<?=isset($getData['tanggal_lahir']) ? date('d/m/Y', strtotime($getData['tanggal_lahir'])) : '' ?>">
<div class="col-sm-6">
<input type="text" class="form-control form-control-user" placeholder="Tanggal Masuk" datepicker="datepicker" tooltip="tooltip" title="Tanggal Masuk" name="ttm" required value="<?=isset($getData['tanggal_masuk']) ? date('d/m/Y', strtotime($getData['tanggal_masuk'])) : '' ?>">
<div class="form-group row">
<div class="col-sm-6 mb-3 mb-sm-0">
<input type="text" class="form-control form-control-user" placeholder="Tempat Lahir" tooltip="tooltip" title="Tempat Lahir" name="tl" required value="<?=isset($getData['tempat_lahir']) ? $getData['tempat_lahir'] : '' ?>">
<div class="col-sm-6">
<select class="form-control form-control-user" name='departemen' required>
<option value="">Pilih Departemen
<?php foreach ($rowsDepartemen as $rowDepartemen) { ?>
<option value=" <?=isset($getData['id_dept']) ? $getData['id_dept'] == $rowDepartemen["id_dept"] ? 'selected' : '' : '' ?> >
<?php
}
?>
<div class="form-group row">
<div class="col-sm-6 mb-3 mb-sm-0">
<select name="jk" class="form-control form-control-user" required>
<option value="">Jenis Kelamin
<option value="laki-laki" <?=isset($getData['jenis_kelamin']) ? $getData['jenis_kelamin'] == 'laki-laki' ? 'selected' : '' : '' ?>>Laki-Laki
<option value="Perempuan" <?=isset($getData['jenis_kelamin']) ? $getData['jenis_kelamin'] == 'Perempuan' ? 'selected' : '' : '' ?>>Perempuan
<div class="col-sm-6">
<select class="form-control form-control-user" name='jabatan' required>
<option value="">Pilih Jabatan
<?php foreach ($rowsJabatan as $rowJabatan) { ?>
<option value=" <?=isset($getData['id_jabatan']) ? $getData['id_jabatan'] == $rowJabatan["id_jabatan"] ? 'selected' : '' : '' ?> >
<?php
}
?>
<div class="form-group row">
<div class="col-sm-6 mb-3 mb-sm-0">
<select class="form-control form-control-user" name='marital' required>
<option value="">Pilih Marital Status
<?php foreach ($rowsMarital as $rowsMarital) { ?>
<option value=" <?=isset($getData['marital_status']) ? $getData['marital_status'] == $rowsMarital["id_marital"] ? 'selected' : '' : '' ?> >
<?php
}
?>
<div class="col-sm-6">
<select name="sk" class="form-control form-control-user" required>
<option value="" selected="selected">Status Karyawan
<option value="permanen" <?=isset($getData['status_karyawan']) ? $getData['status_karyawan'] == 'permanen' ? 'selected' : '' : '' ?> >Permanen
<option value="kontrak" <?=isset($getData['status_karyawan']) ? $getData['status_karyawan'] == 'kontrak' ? 'selected' : '' : '' ?> >Kontrak
<div class="form-group row">
<div class="col-sm-6 mb-3 mb-sm-0">
<input type="email" class="form-control form-control-user" placeholder=" tooltip="tooltip" title="Email" name="email"
value="<?=isset($getData['email']) ? $getData['email'] : '' ?>">
<div class="col-sm-6 mb-3 mb-sm-0">
<input type="number" class="form-control form-control-user" placeholder="0812xxxxx" tooltip="tooltip" title="Nomor Telepon" name="nomor"
value="<?=isset($getData['no_telepon']) ? $getData['no_telepon'] : '' ?>">
<div class="form-group row">
<div class="col-sm-6 mb-3 mb-sm-0">
<input type="file" class="form-control form-control-user" tooltip="tooltip" title="Foto" name="foto">
<div class="col-sm-6 mb-3 mb-sm-0" tooltip="tooltip" title="<?=isset($_SESSION['hak_akses']) ? $_SESSION['hak_akses'] !== 'admin' && $status == "update" ? 'Not Akses Edit Here...' : 'NIK' : '' ?>">
<select name="hak" class="form-control form-control-user" <?=isset($_SESSION['hak_akses']) ? $_SESSION['hak_akses'] !== 'admin' && $status == "update" ? 'disabled' : '' : '' ?> >
<option value="" selected="selected">Hak Akses
<option value="karyawan" <?=isset($getData['hak_akses']) ? $getData['hak_akses'] == 'karyawan' ? 'selected' : '' : '' ?> >Karyawan
<option value="admin"<?=isset($getData['hak_akses']) ? $getData['hak_akses'] == 'admin' ? 'selected' : '' : '' ?> >Admin
<option value="pic" <?=isset($getData['hak_akses']) ? $getData['hak_akses'] == 'pic' ? 'selected' : '' : '' ?> >PIC
<option value="manager" <?=isset($getData['hak_akses']) ? $getData['hak_akses'] == 'manager' ? 'selected' : '' : '' ?> >Manager
<?php
if(isset($_SESSION['hak_akses'])){
if($_SESSION['hak_akses'] !== 'admin' && $status == "update"){
if(isset($getData['hak_akses'])){ ?>
<input type="hidden" name="hak" value=" ">
<?php
}
}
}
?>
<div class="form-group row">
<div class="col-sm-12 mb-3 mb-sm-0">
<textarea class="form-control form-control-user" placeholder="Alamat" tooltip="tooltip" title="Alamat" rows="1" name="alamat"><?=isset($getData['alamat']) ? $getData['alamat'] : '' ?>
<div class="form-group row">
<div class="col-sm-6 mb-3 mb-sm-0">
<button type="submit" class="btn btn-primary btn-user btn-block"><?=$status=='update' ? 'Save' : 'Tambah Karyawan' ?>
<div class="col-sm-6">
<a href="?page=karyawan" class="btn btn-google btn-user btn-block">Cancel
|
php
| 13 | 0.396241 | 312 | 70.031915 | 188 |
starcoderdata
|
public static void main(final String[] args) throws Exception {
// Parses the command line
final Options options = options();
final CommandLine command = new DefaultParser().parse(options, args);
// Main options
if (showUsage(command, options)) {
return;
}
setVerbose(command);
// Initializes the games metadata
final Map<String, Game> games = GamesReaderCommandLineAdapter.from(command).read();
logger.info("{} games read", games.size());
// Writes the Emulation Station resources/mamenames.xml file
writeMameNames(command, games);
// Writes the Emulation Station gamelist.xml and custom-collection.cfg files
writeGameListAndCustomCollections(command, games);
}
|
java
| 8 | 0.716667 | 85 | 30.818182 | 22 |
inline
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class TipoGasto extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'cat_tipogasto';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['EMPRESA_ID', 'CAUSAEXENCION_ID', 'DESCRIPCION', 'EXENTO', 'MONTO_A_APLICAR', 'CUENTA_CONTABLE_EXENTO', 'CODIGO_IMPUESTO_EXENTO',
'CUENTA_CONTABLE_AFECTO', 'CODIGO_IMPUESTO_AFECTO', 'CUENTA_CONTABLE_REMANENTE', 'CODIGO_IMPUESTO_REMANENTE', 'ANULADO'];
public $timestamps = false;
public function empresas(){
return $this->belongsToMany(Empresa::class); ///Ojo porque debo modificar
}
}
|
php
| 10 | 0.634449 | 156 | 24.21875 | 32 |
starcoderdata
|
def normalise_kmer_frequency(observed, reference):
"""Normalize kmer counts - divide observed with reference counts."""
normalised = {}
for kmer, count in observed.items():
# In short regions of the reference there could be 0 of certain kmers.
# In such case, just normalize with 1.
try:
normalised[kmer] = count / reference[kmer] * 10 ** 6
except ZeroDivisionError:
normalised[kmer] = count * 10 ** 6
return normalised
|
python
| 12 | 0.637475 | 78 | 43.727273 | 11 |
inline
|
package cn.prinf.demos.junit.api;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
public class WireMockExtensionTest extends TestBase {
@RegisterExtension
WireMockExtension wireMock = new WireMockExtension();
@Autowired
RestTemplate restTemplate;
@Test
void test() throws IOException {
configureFor("localhost", 8080);
wireMock.stubFor(get(urlEqualTo("/users"))
.willReturn(aResponse()
.withHeader("Content-Type", "text/json")
.withBody("{\"name\":\"john\"}")));
String response = restTemplate.getForObject("http://localhost:8080/users", String.class);
Assertions.assertEquals("{\"name\":\"john\"}", response);
}
}
|
java
| 14 | 0.74501 | 97 | 37.825 | 40 |
starcoderdata
|
#ifndef WIDGET_H
#define WIDGET_H
#include "../IDA/types.h"
#include "NamedObject.h"
#include "../common/Matrix4.h"
namespace plasma {
class Node;
class Widget : public plasma::NamedObject {
public:
virtual void Draw(); //I don't know what controls the position where the widget gets drawn
void* deformer_vtable;
float scale;
_BYTE gap44[20];
__int64 d3d11_render_surface_ptr;
Matrix4 matrix;
__int64 field_A0;
_BYTE gapA8[208];
plasma::Node* node;
_BYTE gap180[39];
char end;
};
}
static_assert(sizeof(plasma::Widget) == 0x1A8, "plasma::Widget is not the correct size.");
#endif // WIDGET_H
|
c
| 9 | 0.666667 | 93 | 21.9 | 30 |
starcoderdata
|
bool FindLatestExe(std::string& path) {
if (path.length() < 4)
return false;
static const char VersionsFolder[] = "Versions\\";
static std::size_t BaseFolderNameLen = 10; // "Base00000\"
std::size_t versions_pos = path.find(VersionsFolder);
if (versions_pos == std::string::npos) {
return DoesFileExist(path);
}
// Get the versions path.
std::string versions_path = path;
versions_path.erase(versions_path.begin() + versions_pos + sizeof(VersionsFolder) - 1, versions_path.end());
// Get the exe name.
std::string exe_name = path;
exe_name.erase(exe_name.begin(), exe_name.begin() + versions_pos + sizeof(VersionsFolder) + BaseFolderNameLen - 1);
// Get a list of all subfolders.
std::vector<std::string> subfolders;
scan_directory(versions_path.c_str(), subfolders, true, true);
if (subfolders.size() < 1) {
return DoesFileExist(path);
}
// Sort the subfolders list.
std::sort(subfolders.begin(), subfolders.end());
for (int folder_index = static_cast<int>(subfolders.size()) - 1; folder_index >= 0; --folder_index) {
std::string test_path = subfolders[folder_index] + "\\" + exe_name;
if (DoesFileExist(test_path)) {
path = test_path;
return true;
}
}
return DoesFileExist(path);
}
|
c++
| 11 | 0.622222 | 119 | 33.641026 | 39 |
inline
|
package com.floweytf.bettercreativeitems.tileentity;
import com.floweytf.bettercreativeitems.api.IFluidRenderer;
import com.floweytf.bettercreativeitems.capabilities.CreativeFluidHandler;
import com.floweytf.bettercreativeitems.container.FluidContainer;
import com.floweytf.bettercreativeitems.plugin.FluidRendererRegistry;
import com.floweytf.bettercreativeitems.utils.Utils;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.IInteractionObject;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static com.floweytf.bettercreativeitems.Constants.NBT_TAG_NAME;
import static com.floweytf.bettercreativeitems.Constants.id;
@SuppressWarnings("NullableProblems")
public class FluidTileEntity extends TileEntity implements IInteractionObject {
private static final String TRANSLATION_KEY = Utils.translationKey("container", "fluid", "name");
private static final String GUI_ID = id("fluid").toString();
private final CreativeFluidHandler cap = new CreativeFluidHandler();
@Override
public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) {
if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) {
return true;
}
return super.hasCapability(capability, facing);
}
@Nullable
@Override
public T getCapability(Capability capability, @Nullable EnumFacing facing) {
if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) {
return (T) cap; // ur capping
}
return super.getCapability(capability, facing);
}
@Override
public void readFromNBT(NBTTagCompound compound) {
super.readFromNBT(compound);
cap.fluidRenderer = FluidRendererRegistry.get(compound.getString(NBT_TAG_NAME));
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound compound) {
super.writeToNBT(compound);
compound.setString(NBT_TAG_NAME, FluidRendererRegistry.get(cap.fluidRenderer).toString());
return compound;
}
@Override
public Container createContainer(InventoryPlayer playerInventory, EntityPlayer playerIn) {
return new FluidContainer();
}
@Override
public String getGuiID() {
return GUI_ID;
}
@Override
public String getName() {
return TRANSLATION_KEY;
}
@Override
@Nonnull
public ITextComponent getDisplayName() {
return new TextComponentTranslation(getName());
}
@Override
public boolean hasCustomName() {
return false;
}
@Override
public NBTTagCompound getUpdateTag() {
NBTTagCompound tag = super.getUpdateTag();
tag.setString(NBT_TAG_NAME, FluidRendererRegistry.get(cap.fluidRenderer).toString());
return tag;
}
@Nullable
@Override
public SPacketUpdateTileEntity getUpdatePacket() {
SPacketUpdateTileEntity packet = super.getUpdatePacket();
if (packet == null) {
packet = new SPacketUpdateTileEntity(pos, 1, new NBTTagCompound());
}
packet.nbt.setString(NBT_TAG_NAME, FluidRendererRegistry.get(cap.fluidRenderer).toString());
return packet;
}
@Override
public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) {
super.onDataPacket(net, pkt);
cap.fluidRenderer = FluidRendererRegistry.get(pkt.getNbtCompound().getString(NBT_TAG_NAME));
}
@Override
public void handleUpdateTag(NBTTagCompound tag) {
super.handleUpdateTag(tag);
cap.fluidRenderer = FluidRendererRegistry.get(tag.getString(NBT_TAG_NAME));
}
public IFluidRenderer getFluidRenderer() {
return cap.fluidRenderer;
}
public void setFluidRenderer(IFluidRenderer renderer) {
cap.fluidRenderer = renderer;
IBlockState state = world.getBlockState(pos);
world.notifyBlockUpdate(getPos(), state, state, 2);
}
}
|
java
| 13 | 0.711281 | 101 | 33.390977 | 133 |
starcoderdata
|
$(function () {
var connect = function (attempt) {
var connectionAttempt = attempt;
var tweetSocket = new WebSocket(url);
tweetSocket.onmessage = function (e) {
console.log(e);
var data = JSON.parse(e.data);
$("#tweets").prepend('' +
' +
' <td class="col-sm-1 image">' +
' <a href="https://twitter.com/' + data.user.screen_name + '" target="_blank">' +
' <img src="' + data.user.profile_image_url_https + '"/>' +
' +
' <div class="popup"> +
' +
'<td class="alert alert-success col-sm-11">' + data.text + ' +
'
};
tweetSocket.onopen = function () {
connectionAttempt = 1;
tweetSocket.send("subscribe");
};
tweetSocket.onclose = function () {
if (connectionAttempt < 3) {
$("#tweets").prepend(' Lost Server connection, attempting to' +
'reconnect. Attempt number ' + connectionAttempt + '
setTimeout(function () {
connect(connectionAttempt + 1);
}, 5000);
} else {
alert("The connection with the server was lost")
}
};
};
connect(1);
});
|
javascript
| 28 | 0.449367 | 98 | 29.934783 | 46 |
starcoderdata
|
<?php
namespace App\Modules\Heatmap\Controllers;
use App\Http\Controllers\Controller;
use App\Modules\Heatmap\Data\LinkHitData;
use App\Modules\Heatmap\Data\LinkTypeHitData;
use App\Modules\Heatmap\Requests\HitLinkRequest;
use App\Modules\Heatmap\Requests\HitLinkTypeRequest;
use App\Modules\Heatmap\Resources\HitResource;
use App\Modules\Heatmap\Services\LinkService;
class LinkController extends Controller
{
public function __construct(private LinkService $service)
{
}
public function linkHits(HitLinkRequest $request): HitResource
{
return new HitResource($this->service->getLinkInInterval(LinkHitData::fromRequest($request)));
}
public function linkTypeHits(HitLinkTypeRequest $request): HitResource
{
return new HitResource($this->service->getLinkTypeInInterval(LinkTypeHitData::fromRequest($request)));
}
}
|
php
| 16 | 0.772936 | 110 | 30.142857 | 28 |
starcoderdata
|
def get_comparison_data(teams: str
) -> Tuple[Dict, Dict, List, Dict, Dict, str, str]:
"""Format comparison data to be used in front-end HTML from JSON data files.
:param teams: the teams string requested from front-end
:return: a tuple containing all information needed in front-end
"""
# initialize west conference logo path dictionary and division list
team_img_path = {"west": {}, "east": {}}
all_teams = []
for conf in ["west", "east"]:
for div in DIVISION_DICT[conf].keys():
team_img_path[conf][div] = []
all_teams.append(f"{div} -")
for team in DIVISION_DICT[conf][div]:
team_img_path[conf][div].append({team: f"images/{team}.png"})
all_teams.append(team)
# the stats comparing dictionaries
result = {
"team1": {"W-L R": '', "PPG": '', "FG%": '', "3P%": '', "REB": '',
"AST": ''},
"team2": {"W-L R": '', "PPG": '', "FG%": '', "3P%": '', "REB": '',
"AST": ''}
}
team1, team2 = '', ''
# enum does not allow storing special characters so this dict maps enum
# variables to result display variables
cat_ref = {"WLR": "W-L R", "PPG": "PPG", "FG_PCT": "FG%",
"FG3_PCT": "3P%", "REB": "REB", "AST": "AST"}
# only gather data if request inputs team names
if teams:
team1, team2 = teams[:3], teams[3:]
team_stats = load_team_season_data()
team1_idx = [str(item[0]) for item in team_stats].index(
get_id_from_abb(team1))
team2_idx = [str(item[0]) for item in team_stats].index(
get_id_from_abb(team2))
# populate result dict from file data
for cat, display_cat in cat_ref.items():
team1_data = team_stats[team1_idx][TSIndices.__members__[cat].value]
result["team1"][display_cat] = team1_data
team2_data = team_stats[team2_idx][TSIndices.__members__[cat].value]
result["team2"][display_cat] = team2_data
return (
team_img_path["west"],
team_img_path["east"],
all_teams,
result["team1"],
result["team2"],
team1,
team2
)
|
python
| 16 | 0.531668 | 80 | 36.383333 | 60 |
inline
|
// Listing 3.5:
const isAstReferenceObject = (value) => isObject(value) && ("ref" in value)
// Listing 3.6:
const isAstReference = (value) => isAstReferenceObject(value) && isAstObject(value.ref)
// Export statement to be able to import this function in 'snippets-section3.2.js':
module.exports = isAstReference
|
javascript
| 8 | 0.72327 | 87 | 25.5 | 12 |
starcoderdata
|
/*
* Default text labels.
*/
const textLabels = {
body: {
noMatch: 'Desculpe, nenhum registro correspondente foi encontrado',
toolTip: 'Ordenar',
},
pagination: {
next: 'Próxima página',
previous: 'Página anterior',
rowsPerPage: 'Linhas por página:',
displayRows: 'De',
},
toolbar: {
search: 'Pesquisar',
downloadCsv: 'Download CSV',
print: 'Imprimir',
viewColumns: 'Visualizar colunas',
filterTable: 'Filtrar Tabela',
},
filter: {
all: 'TODOS',
title: 'FILTROS',
reset: 'LIMPAR',
},
viewColumns: {
title: 'Mostrar Colunas',
titleAria: 'Mostrar / ocultar colunas da tabela',
},
selectedRows: {
text: 'linha (s) selecionada',
delete: 'Excluir',
deleteAria: 'Excluir linhas selecionadas',
},
};
export default textLabels;
|
javascript
| 8 | 0.622114 | 71 | 20.657895 | 38 |
starcoderdata
|
func OAuthCallback(response http.ResponseWriter, request *http.Request) {
code := request.URL.Query().Get("code")
stvToken := request.URL.Query().Get("state")
syncTask, err := ObtainBearerToken(code, stvToken)
if err != nil {
//report 40x
response.WriteHeader(http.StatusBadRequest)
}
//if strava is set, set that cookie to
if syncTask.StravaToken != "" {
cookie := &http.Cookie{Name: "strava", Value: fmt.Sprintf("%s", syncTask.StravaToken), Expires: time.Now().Add(356 * 24 * time.Hour), HttpOnly: false}
cookie.Domain = "www.syncmysport.com"
http.SetCookie(response, cookie)
}
//redirect to sign up page with Acknowledgement of success..
cookie := &http.Cookie{Name: "runkeeper", Value: fmt.Sprintf("%s", syncTask.RunkeeperToken), Expires: time.Now().Add(356 * 24 * time.Hour), HttpOnly: false}
cookie.Domain = "www.syncmysport.com"
http.SetCookie(response, cookie)
http.Redirect(response, request, "https://www.syncmysport.com/connect.html", 303)
}
|
go
| 16 | 0.716479 | 157 | 43.454545 | 22 |
inline
|
def build_psc_replication_relationship(pscs):
psc_replication_mapping = {}
for psc in pscs:
(proc, out) = execute([vdcrepadmin_path, '-f', 'showpartners', '-h', psc, '-u', vc_username_wo_domain, '-w', vc_password],env=VMTENV)
results = out.strip().split('\n')
for psc_replication_partner in results:
key = psc
value = psc_replication_partner[7:]
# Ignore duplicate replication agreements
if(psc_replication_mapping.has_key(value) == False or psc_replication_mapping[value] != key):
psc_replication_mapping[psc] = psc_replication_partner[7:]
return psc_replication_mapping
|
python
| 11 | 0.629851 | 138 | 46.928571 | 14 |
inline
|
using ServiceFabric.Watchdog.RuleEngine.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceFabric.Watchdog.RuleEngine.Expressions
{
public abstract class Expression
{
protected char[] _separators;
protected char[] _operators;
public ExpressionValue LeftValue { get; set; }
public ExpressionValue RightValue { get; set; }
public ExpressionOperator Operator { get; set; } = ExpressionOperator.Unknown;
public Expression(char[] separators, char[] operators, string expression = null)
{
_separators = separators;
_operators = operators;
if (!String.IsNullOrEmpty(expression))
Parse(expression);
}
public bool Parse(string expression)
{
LeftValue = null;
Operator = ExpressionOperator.Unknown;
RightValue = null;
int startIndex = 0;
var parsedExpression = ParseSubExpression(expression, 0, startIndex, out int stopIndex);
if (parsedExpression != null)
{
LeftValue = parsedExpression.LeftValue;
Operator = parsedExpression.Operator;
RightValue = parsedExpression.RightValue;
return true;
}
else
return false;
}
public abstract TValue Execute(TriggerItem triggerItem);
protected abstract Expression CreateExpression();
protected abstract ExpressionValue CreateLeftExpressionValue(string value);
protected abstract ExpressionValue CreateRightExpressionValue(string value);
protected Expression ParseSubExpression(string expression, int level, int startIndex, out int stopIndex)
{
var parsedExpression = CreateExpression();
ExpressionParserState state = ExpressionParserState.BeforeLeftValue;
bool hyphened = false;
int index = startIndex;
// loop until we are done
while (index < expression.Length && state != ExpressionParserState.Closed && state != ExpressionParserState.Error)
{
switch (state)
{
case ExpressionParserState.BeforeLeftValue:
case ExpressionParserState.BeforeRightValue:
// okay, what the first character?
if (expression[index] == '(')
{
// increase level and parse sub expression
var subExpression = ParseSubExpression(expression, level + 1, index + 1, out stopIndex);
if (subExpression != null)
{
if (state == ExpressionParserState.BeforeLeftValue)
parsedExpression.LeftValue = new ExpressionValueExpression
else
parsedExpression.RightValue = new ExpressionValueExpression
state = (state == ExpressionParserState.BeforeLeftValue ? ExpressionParserState.Operator : ExpressionParserState.Complete);
index = stopIndex;
if (index < expression.Length && expression[index] == ')')
index++;
while (index < expression.Length && expression[index] == ' ')
index++;
}
else
{
// ignore parenthis and move on
index++;
}
break;
}
else if (expression[index] == '\'' || expression[index] == '\"')
{
// move on pass this and move to state value1
index++;
hyphened = true;
state = (state == ExpressionParserState.BeforeLeftValue ? ExpressionParserState.LeftValue : ExpressionParserState.RightValue);
}
else
{
// move to state value1
state = (state == ExpressionParserState.BeforeLeftValue ? ExpressionParserState.LeftValue : ExpressionParserState.RightValue);
}
break;
case ExpressionParserState.LeftValue:
case ExpressionParserState.RightValue:
int startOperand = index;
// read out the value1 operand
while (index < expression.Length &&
(hyphened ? (expression[index] != '\'' && expression[index] != '\"') :
!_separators.Contains(expression[index])))
index++;
if (state == ExpressionParserState.LeftValue)
{
parsedExpression.LeftValue = CreateLeftExpressionValue(expression.Substring(startOperand, index - startOperand));
if (parsedExpression.LeftValue == null)
state = ExpressionParserState.Error;
}
else
{
parsedExpression.RightValue = CreateRightExpressionValue(expression.Substring(startOperand, index - startOperand));
if (parsedExpression.LeftValue == null)
state = ExpressionParserState.Error;
}
while (index < expression.Length && (expression[index] == '\'' || expression[index] == '\"' || expression[index] == ' '))
index++;
// move to next state
if (state != ExpressionParserState.Error)
state = (state == ExpressionParserState.LeftValue ? ExpressionParserState.Operator : ExpressionParserState.Complete);
hyphened = false;
break;
case ExpressionParserState.Operator:
parsedExpression.Operator = OperatorFromString(expression.Substring(index));
if (parsedExpression.Operator == ExpressionOperator.Unknown)
{
state = ExpressionParserState.Error;
}
else
{
state = ExpressionParserState.BeforeRightValue;
while (index < expression.Length && (_operators.Contains(expression[index]) || expression[index] == ' '))
index++;
}
break;
case ExpressionParserState.Complete:
if (index >= expression.Length || (level > 0 && expression[index] == ')'))
state = ExpressionParserState.Closed;
else if (_operators.Contains(expression[index]))
{
var op = OperatorFromString(expression.Substring(index));
if (op != ExpressionOperator.And && op != ExpressionOperator.Or)
{
state = ExpressionParserState.Error;
break;
}
while (index < expression.Length && (_operators.Contains(expression[index]) || expression[index] == ' '))
index++;
var newExpression = CreateExpression();
newExpression.LeftValue = new ExpressionValueExpression
newExpression.Operator = op;
parsedExpression = newExpression;
if (expression[index] == '(')
index++;
var subExpression = ParseSubExpression(expression, level + 1, index, out stopIndex);
if (subExpression != null)
{
parsedExpression.RightValue = new ExpressionValueExpression
state = ExpressionParserState.Complete;
}
else
state = ExpressionParserState.Error;
index = stopIndex;
while (index < expression.Length && expression[index] == ' ')
index++;
}
else
state = ExpressionParserState.Error;
break;
}
}
stopIndex = index;
return (parsedExpression.LeftValue != null && parsedExpression.Operator != ExpressionOperator.Unknown && parsedExpression.RightValue != null ?
parsedExpression : null);
}
public string ToString(TriggerItem triggerItem)
{
return $"{LeftValue.ToString(triggerItem)} {OperatorAsString(Operator)} {RightValue.ToString(triggerItem)}";
}
private string OperatorAsString(ExpressionOperator op)
{
switch (op)
{
case ExpressionOperator.Add: return "+";
case ExpressionOperator.And: return "&&";
case ExpressionOperator.Divide: return "/";
case ExpressionOperator.Equal: return "==";
case ExpressionOperator.Larger: return ">";
case ExpressionOperator.LargerOrEqual: return ">=";
case ExpressionOperator.Multiply: return "*";
case ExpressionOperator.NotEqual: return "!=";
case ExpressionOperator.Or: return "||";
case ExpressionOperator.Smaller: return "<";
case ExpressionOperator.SmallerOrEqual: return "<=";
case ExpressionOperator.Subtract: return "-";
case ExpressionOperator.Contains: return "contains";
case ExpressionOperator.StartsWith: return "startswith";
case ExpressionOperator.EndsWith: return "endswith";
default: return "--";
}
}
private ExpressionOperator OperatorFromString(string op)
{
if (op.Substring(0, 1) == "+")
return ExpressionOperator.Add;
else if (op.Substring(0, 2) == "&&")
return ExpressionOperator.And;
else if (op.Substring(0, 1) == "/")
return ExpressionOperator.Divide;
else if (op.Substring(0, 2) == "==")
return ExpressionOperator.Equal;
else if (op.Substring(0, 1) == "=")
return ExpressionOperator.Equal;
else if (op.Substring(0, 2) == ">=")
return ExpressionOperator.LargerOrEqual;
else if (op.Substring(0, 1) == ">")
return ExpressionOperator.Larger;
else if (op.Substring(0, 1) == "*")
return ExpressionOperator.Multiply;
else if (op.Substring(0, 2) == "!=")
return ExpressionOperator.NotEqual;
else if (op.Substring(0, 2) == "||")
return ExpressionOperator.Or;
else if (op.Substring(0, 2) == "<=")
return ExpressionOperator.SmallerOrEqual;
else if (op.Substring(0, 1) == "<")
return ExpressionOperator.Smaller;
else if (op.Substring(0, 1) == "-")
return ExpressionOperator.Subtract;
else
return ExpressionOperator.Unknown;
}
}
}
|
c#
| 25 | 0.49208 | 155 | 48.748 | 250 |
starcoderdata
|
import sys
from html_builder import HtmlBuilder
from text_builder import TextBuilder
from director import Director
def main():
args = sys.argv
if len(args) != 2:
usage()
exit(0)
if args[1] == "plain":
text_builder = TextBuilder()
director = Director(text_builder)
director.construct()
result = text_builder.get_result()
print(result)
elif args[1] == "html":
html_builder = HtmlBuilder()
director = Director(html_builder)
director.construct()
filename = html_builder.get_result()
print(filename + "が作成されました。")
else:
usage()
exit(0)
def usage():
print("Usage: python main.py plain プレーンテキストで文書作成")
print("Usage: python main.py html HTMLファイルで文書作成")
if __name__ == "__main__":
main()
|
python
| 11 | 0.595266 | 55 | 21.236842 | 38 |
starcoderdata
|
<?php
namespace tea\tests\xview;
#public
interface IViewDemo extends \IView {
public function set_css_class(string $names);
}
trait IViewDemoTrait {
public $name = '';
public $css_class = '';
public function set_css_class(string $names) {
$this->css_class = $names;
return $this;
}
}
// program end
|
php
| 9 | 0.682692 | 47 | 15.421053 | 19 |
starcoderdata
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Description;
using System.Web.Http.Filters;
using Swashbuckle.Swagger;
namespace HeadlessUmbracoTest.Core.Swagger
{
public class CultureCodeOperationFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline().Where(f => f.Scope == FilterScope.Action);
if (operation.parameters == null)
{
operation.parameters = new List
}
operation.parameters.Add(new Parameter
{
name = "Accept-Language",
@in = "header",
type = "string",
@default = "en-US",
description = "Set language code.",
required = true
});
}
}
}
|
c#
| 17 | 0.606208 | 127 | 28.323529 | 34 |
starcoderdata
|
#ifndef _INC_DUMMY_INSTRUCTION_H
#define _INC_DUMMY_INSTRUCTION_H
class DummyInstruction : public Instruction {
public:
DummyInstruction(ByteString opcode, SizeType instructionLength)
: Instruction(opcode, instructionLength) {
}
virtual void execute(BaseCPU &cpu, const ByteString ¶ms) const {
}
};
#endif//_INC_DUMMY_INSTRUCTION_H
|
c
| 9 | 0.734807 | 72 | 24.928571 | 14 |
starcoderdata
|
public Path CreateBloomFilterStaticPathLightGray()
{
//Rectangles
RectangleGeometry leftRectangleGeometry = new RectangleGeometry
{
Rect = new Rect(100, 50, 150, 150),
RadiusX = 10,
RadiusY = 10
};
RectangleGeometry rightRectangleGeometry = new RectangleGeometry
{
Rect = new Rect(550, 50, 150, 150),
RadiusX = 10,
RadiusY = 10
};
//Arrow
StreamGeometry arrowGeometry = new StreamGeometry
{
FillRule = FillRule.EvenOdd
};
using (StreamGeometryContext sgc = arrowGeometry.Open())
{
sgc.BeginFigure(new Point(455, 125), true, true);
//475,125
sgc.LineTo(new Point(415, 80), true, false);
//425, 75
sgc.LineTo(new Point(415, 105), true, false);
//425,95
sgc.LineTo(new Point(325, 105), true, false);
//325,95
sgc.LineTo(new Point(325, 145), true, false);
//325,155
sgc.LineTo(new Point(415, 145), true, false);
//425,155
sgc.LineTo(new Point(415, 170), true, false);
//425,175
}
arrowGeometry.Freeze();
PathFigure myPathFigure = new PathFigure
{
StartPoint = new Point(645, 200)
};
//Half circle at the bottom ofthe hash function box
myPathFigure.Segments.Add(new ArcSegment(new Point(605, 200), new Size(10, 10), 45, true, SweepDirection.Clockwise, true));
/// Create a PathGeometry to contain the figure.
PathGeometry halfCircle = new PathGeometry();
halfCircle.Figures.Add(myPathFigure);
GeometryGroup geometryGroup = new GeometryGroup();
geometryGroup.Children.Add(leftRectangleGeometry);
geometryGroup.Children.Add(rightRectangleGeometry);
geometryGroup.Children.Add(arrowGeometry);
geometryGroup.Children.Add(halfCircle);
Path path = new Path
{
StrokeThickness = 1,
Stroke = Brushes.Black,
Data = geometryGroup
};
path.Fill = (SolidColorBrush)new BrushConverter().ConvertFrom("#f2f2f2");
return path;
}
|
c#
| 14 | 0.512485 | 135 | 36.671642 | 67 |
inline
|
using System;
using System.Collections.Generic;
using Route4MeSDK.DataTypes.V5;
using static Route4MeSDK.Route4MeManagerV5;
namespace Route4MeSDK.Examples
{
public sealed partial class Route4MeExamples
{
public void AddSkillsToDriver()
{
// Create the manager with the api key
var route4Me = new Route4MeManagerV5(ActualApiKey);
#region Create Member To Update
membersToRemove = new List
CreateTestTeamMember();
if (membersToRemove.Count < 1)
{
Console.WriteLine("Cannot create a team member to remove");
return;
}
var member = membersToRemove[membersToRemove.Count - 1];
#endregion
var queryParams = new MemberQueryParameters()
{
UserId = member.MemberId.ToString()
};
string[] skills = new string[]
{
"Class A CDL", "Forklift", "Skid Steer Loader"
};
var updatedMember = route4Me.AddSkillsToDriver(queryParams,
skills,
out ResultResponse resultResponse);
PrintTeamMembers(updatedMember, resultResponse);
Console.WriteLine("");
Console.WriteLine(
(updatedMember?.CustomData?.ContainsKey("driver_skills") ?? false) == true
? "Driver skills :" + updatedMember.CustomData["driver_skills"]
: "Cannot add skills to the driver"
);
RemoveTestTeamMembers();
}
}
}
|
c#
| 19 | 0.53105 | 95 | 29.767857 | 56 |
starcoderdata
|
import SongBar from './SongBar';
export { Header } from './Header';
export { SearchBar } from './SearchBar';
export { withLoader } from './withLoader';
export { withError } from './withError';
export { Loader } from './Loader';
export { SubHeader } from './SubHeader';
export { SongBar };
|
javascript
| 3 | 0.696165 | 48 | 32.9 | 10 |
starcoderdata
|
static void
make_room_for (int length)
{
int wanted_size;
/* Compute needed size for in-memory buffer. Diversions in-memory
buffers start at 0 bytes, then 512, then keep doubling until it is
decided to flush them to disk. */
output_diversion->used = output_diversion->size - output_unused;
for (wanted_size = output_diversion->size;
wanted_size < output_diversion->used + length;
wanted_size = wanted_size == 0 ? INITIAL_BUFFER_SIZE : wanted_size * 2)
;
/* Check if we are exceeding the maximum amount of buffer memory. */
if (total_buffer_size - output_diversion->size + wanted_size
> MAXIMUM_TOTAL_SIZE)
{
struct diversion *selected_diversion;
int selected_used;
struct diversion *diversion;
int count;
/* Find out the buffer having most data, in view of flushing it to
disk. Fake the current buffer as having already received the
projected data, while making the selection. So, if it is
selected indeed, we will flush it smaller, before it grows. */
selected_diversion = output_diversion;
selected_used = output_diversion->used + length;
for (diversion = diversion_table + 1;
diversion < diversion_table + diversions;
diversion++)
if (diversion->used > selected_used)
{
selected_diversion = diversion;
selected_used = diversion->used;
}
/* Create a temporary file, write the in-memory buffer of the
diversion to this file, then release the buffer. */
selected_diversion->file = tmpfile ();
if (selected_diversion->file == NULL)
M4ERROR ((EXIT_FAILURE, errno,
"ERROR: cannot create temporary file for diversion"));
if (set_cloexec_flag (fileno (selected_diversion->file), true) != 0)
M4ERROR ((warning_status, errno,
"Warning: cannot protect diversion across forks"));
if (selected_diversion->used > 0)
{
count = fwrite (selected_diversion->buffer,
(size_t) selected_diversion->used,
1,
selected_diversion->file);
if (count != 1)
M4ERROR ((EXIT_FAILURE, errno,
"ERROR: cannot flush diversion to temporary file"));
}
/* Reclaim the buffer space for other diversions. */
free (selected_diversion->buffer);
total_buffer_size -= selected_diversion->size;
selected_diversion->buffer = NULL;
selected_diversion->size = 0;
selected_diversion->used = 0;
}
/* Reload output_file, just in case the flushed diversion was current. */
output_file = output_diversion->file;
if (output_file)
{
/* The flushed diversion was current indeed. */
output_cursor = NULL;
output_unused = 0;
}
else
{
/* The buffer may be safely reallocated. */
output_diversion->buffer
= xrealloc (output_diversion->buffer, (size_t) wanted_size);
total_buffer_size += wanted_size - output_diversion->size;
output_diversion->size = wanted_size;
output_cursor = output_diversion->buffer + output_diversion->used;
output_unused = wanted_size - output_diversion->used;
}
}
|
c
| 15 | 0.657494 | 78 | 29.594059 | 101 |
inline
|
// (C) 2007-2018 GoodData Corporation
import cx from 'classnames';
import { colors2Object, numberFormat } from '@gooddata/numberjs';
import styleVariables from '../../styles/variables';
import { ALIGN_LEFT, ALIGN_RIGHT } from '../constants/align';
export function getColumnAlign(header) {
return (header.type === 'measure') ? ALIGN_RIGHT : ALIGN_LEFT;
}
export function getCellClassNames(rowIndex, columnKey, isDrillable) {
return cx(
{
'gd-cell-drillable': isDrillable
},
`s-cell-${rowIndex}-${columnKey}`,
's-table-cell'
);
}
export function getStyledLabel(header, cellContent, applyColor = true) {
if (header.type !== 'measure') {
return { style: {}, label: cellContent.name };
}
const numberInString = cellContent === null ? '' : parseFloat(cellContent);
const formattedNumber = numberFormat(numberInString, header.format);
const { label: origLabel, color } = colors2Object(formattedNumber);
let style;
let label;
if (origLabel === '') {
label = '–';
style = {
color: styleVariables.gdColorStateBlank,
fontWeight: 'bold'
};
} else {
style = (color && applyColor) ? { color } : {};
label = origLabel;
}
return { style, label };
}
|
javascript
| 12 | 0.612805 | 79 | 28.155556 | 45 |
starcoderdata
|
package com.cloud.blog.auth.config.pojo;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* @program: blog
* @description:
* @author: Ailuoli
* @create: 2019-05-27 14:41
**/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class QQUserInfo {
/**
* 昵称
*/
private String nickname;
/**
* 性别
*/
private String gender;
/**
* QQ头像
*/
private String figureurl_qq;
}
|
java
| 7 | 0.622568 | 40 | 13.277778 | 36 |
starcoderdata
|
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* 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 org.maxkey.password.onetimepwd;
import org.maxkey.entity.UserInfo;
import org.maxkey.password.onetimepwd.token.AbstractOtpTokenStore;
import org.maxkey.password.onetimepwd.token.InMemoryOtpTokenStore;
import org.maxkey.util.StringGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* AbstractOTPAuthn.
* @author Administrator
*
*/
public abstract class AbstractOtpAuthn {
private static final Logger logger = LoggerFactory.getLogger(AbstractOtpAuthn.class);
protected AbstractOtpTokenStore optTokenStore = new InMemoryOtpTokenStore();
//验证码有效間隔
protected int interval = 30;
// 验证码长度,范围4~10,默认为6
protected int digits = 6;
protected String crypto = "HmacSHA1";
protected String defaultEncoding ="utf-8";
StringGenerator stringGenerator;
protected String otpType = OtpTypes.TIMEBASED_OTP;
public static final class OtpTypes {
// 手机
public static String MOBILE = "MOBILE";
// 短信
public static String SMS = "SMS";
// 邮箱
public static String EMAIL = "EMAIL";
//TIMEBASED_OPT
public static String TIMEBASED_OTP = "TOPT";
// HmacOTP
public static String HOTP_OTP = "HOTP";
public static String RSA_OTP = "RSA";
public static String CAP_OTP = "CAP";
}
public abstract boolean produce(UserInfo userInfo);
public abstract boolean validate(UserInfo userInfo, String token);
protected String defaultProduce(UserInfo userInfo) {
return genToken(userInfo);
}
/**
* genToken.
* @param userInfo UserInfo
* @return
*/
public String genToken(UserInfo userInfo) {
if (stringGenerator == null) {
stringGenerator = new StringGenerator(StringGenerator.DEFAULT_CODE_NUMBER, digits);
}
String token = stringGenerator.randomGenerate();
logger.debug("Generator token " + token);
return token;
}
/**
* the interval.
* @return the interval
*/
public int getInterval() {
return interval;
}
/**
* interval the interval to set.
* @param interval the interval to set
*/
public void setInterval(int interval) {
this.interval = interval;
}
/**
* digits.
* @return the digits
*/
public int getDigits() {
return digits;
}
/**
* digits the digits to set.
* @param digits the digits to set
*/
public void setDigits(int digits) {
this.digits = digits;
}
/**
* crypto.
* @return the crypto
*/
public String getCrypto() {
return crypto;
}
/**
* crypto the crypto to set.
* @param crypto the crypto to set
*/
public void setCrypto(String crypto) {
this.crypto = crypto;
}
public String getOtpType() {
return otpType;
}
public void setOtpType(String optType) {
this.otpType = optType;
}
public void setOptTokenStore(AbstractOtpTokenStore optTokenStore) {
this.optTokenStore = optTokenStore;
}
public void initPropertys() {
}
public String getDefaultEncoding() {
return defaultEncoding;
}
public void setDefaultEncoding(String defaultEncoding) {
this.defaultEncoding = defaultEncoding;
}
}
|
java
| 12 | 0.649198 | 149 | 24.481707 | 164 |
starcoderdata
|
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
import http from 'http';
import finalHandler from 'finalhandler';
import serveStatic from 'serve-static';
import morgan from 'morgan';
const serverConfig = {
host: 'localhost',
port: 8080,
};
const logger = morgan('combined');
const serve = serveStatic('.');
const server = http.createServer((req, res) => {
logger(req, res, (err) => {
const done = finalHandler(req, res);
if (err) {
done(err);
return;
}
serve(req, res, done);
});
});
server.listen(serverConfig);
console.log(`Open http://${serverConfig.host}:${serverConfig.port} in your browser`);
|
javascript
| 17 | 0.658284 | 85 | 24.037037 | 27 |
starcoderdata
|
#ifndef NONSTD_STRSPN_H_
#define NONSTD_STRSPN_H_
#include
size_t nonstd_strspn(const char* s, const char* accept);
#endif // NONSTD_STRSPN_H_
|
c
| 7 | 0.708861 | 56 | 18.75 | 8 |
starcoderdata
|
public void handleClick( MouseEvent e, Point localPoint )
{
boolean highlightChanged = false;
if ( selectionBox.contains(localPoint) )
{
//Determine the column for the click
if(super.getDrawMode() == TEXTMODE) {
int xPos = calculateIndexFromWriteX ( localPoint.x );
if(xPos >= 0 && xPos < columnSelected.length) {
highlightChanged = true;
if ( !e.isControlDown() && !e.isShiftDown() )
selectNoColumns();
columnSelected[xPos] = !columnSelected[xPos];
}
}
// Determine the row for the click.
if ( topSelect[0] <= localPoint.y && localPoint.y <= bottomSelect[bottomSelect.length-1])
{
highlightChanged = true;
// Clear all selected rows if neither shift nor control are down
if ( !e.isControlDown() && !e.isShiftDown() )
selectNoRows();
for(int x=0; x<topSelect.length; x++) {
if ( topSelect[x] <= localPoint.y && localPoint.y <= bottomSelect[x] )
seqSelected[x] = !seqSelected[x];
}
}
if(!highlightChanged)
{
// Click is inside the box, but not within any of the sequences (i.e. in the header)
if ( ( e.isControlDown() || e.isShiftDown() ) && hasSelection () ) {
selectNoRows ();
selectNoColumns ();
}
else {
// Select all sequences
selectAllRows ();
selectAllColumns ();
}
}
}
else if ( !e.isControlDown() && !e.isShiftDown() ) {
// Click outside of the main box, clear everything unless shift or control is down
selectNoRows ();
selectNoColumns ();
}
repaint();
}
|
java
| 15 | 0.541761 | 100 | 33.764706 | 51 |
inline
|
from itertools import *
from fractions import Fraction
def solve():
best_highest_target = 0
for number in combinations(range(0, 10), 4):
ht = highest_target(number)
if ht > best_highest_target:
best_highest_target = ht
best_number = number
print(best_number)
def highest_target(digits):
frac_digits = tuple([Fraction(d) for d in digits])
operations = ['+', '-', '*', '/']
targets = []
for fds in permutations(frac_digits):
for ops in product(operations, operations, operations):
target = eval_target_a(fds, ops)
if target:
targets.append(target)
target = eval_target_b(fds, ops)
if target:
targets.append(target)
highest = 0
while True:
if highest + 1 in targets:
highest += 1
else:
break
return highest
def eval_target_a(frac_digits, operations):
f1 = eval(frac_digits[0], operations[0], frac_digits[1])
if not f1:
return None
f2 = eval(f1, operations[1], frac_digits[2])
if not f2:
return None
f3 = eval(f2, operations[2], frac_digits[3])
return f3
def eval_target_b(frac_digits, operations):
f1 = eval(frac_digits[0], operations[0], frac_digits[1])
if not f1:
return None
f2 = eval(frac_digits[2], operations[2], frac_digits[3])
if not f2:
return None
f3 = eval(f1, operations[1], f2)
return f3
def eval(f1, op, f2):
if op == '+':
return f1 + f2
elif op == '-':
return f1 - f2
elif op == '*':
return f1 * f2
elif op == '/':
if f2 == 0:
return None
else:
return f1 / f2
solve()
|
python
| 12 | 0.552691 | 63 | 25.626866 | 67 |
starcoderdata
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.