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 |
---|---|---|---|---|---|---|---|
import boto3
def data_chunk(paragraph):
"""
Break up the text into 5000 byte chunks
:param paragraph:
:return: text_list
"""
text_list = []
while paragraph:
text_list.append(str(paragraph[:5000]))
paragraph = paragraph[5000:]
return text_list[:25]
def comprehend():
s3 = boto3.client("s3")
bucket_name = "comments-and-titles"
key = "blob/blob.txt"
file = s3.get_object(Bucket=bucket_name,
Key=key)
paragraph = str(file['Body'].read())
comprehend = boto3.client("comprehend")
sentiment = comprehend.batch_detect_sentiment(TextList=data_chunk(paragraph), LanguageCode="en")
return sentiment
def break_sentiment(sentiment_dictionary):
"""
Breaks up the sentiment result json object to make the results easier to read
:param sentiment_dictionary:
:return: negative, mixed, neutral, positive
"""
ResultList = list(sentiment_dictionary.values())[0]
sentiment_list = []
for dictionary in ResultList:
sentiment_list.append(list(dictionary.values())[1])
negative = 0
mixed = 0
neutral = 0
positive = 0
for sentiment in sentiment_list:
if sentiment == "NEGATIVE":
negative = negative + 1
if sentiment == "MIXED":
mixed = mixed + 1
if sentiment == "NEUTRAL":
neutral = neutral + 1
if sentiment == "POSITIVE":
positive = positive + 1
return negative, mixed, neutral, positive
if __name__ == '__main__':
sd = comprehend()[0]
negative, mixed, neutral, positive = break_sentiment(sd)
|
python
| 13 | 0.612058 | 100 | 24.261538 | 65 |
starcoderdata
|
const Mongoose = require('mongoose')
const commentsSchema = new Mongoose.Schema({
userEmail: {
type: String,
required: true,
},
user: {
type: String,
required: true,
},
event: {
type: Mongoose.Types.ObjectId,
required: true,
},
text: {
type: String,
required: true,
},
responses: {
type: [this],
},
likes: {
type: [Mongoose.Types.ObjectId],
},
date: {
type: Date,
required: true,
},
})
const commentsModel = Mongoose.model('comments', commentsSchema)
module.exports = {
commentsModel,
commentsSchema,
}
|
javascript
| 10 | 0.603679 | 64 | 14.736842 | 38 |
starcoderdata
|
def aggregated_second(self, data):
"""
Main criteria logic contained here
:type data: bzt.modules.aggregator.DataPoint
"""
part = data[self.selector]
if self.label not in part:
self.owner.log.debug("No label %s in %s", self.label, part.keys())
return
val = self.get_value(part[self.label])
self.process_criteria_logic(data[DataPoint.TIMESTAMP], val)
|
python
| 10 | 0.596811 | 78 | 32.846154 | 13 |
inline
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Audio;
public class EnemyAttack : MonoBehaviour {
private Enemy_Master enemyMaster;
private Transform attackTarget;
private Transform myTransform;
public float attackRate = 1;
private float nextAttack;
public float attackRange = 3.5f;
public int attackDamage = 20;
public float range = 0.5f;
public GameObject KillObjectDamage;
public Transform KillObjectDamagepostion;
public AudioSource a;
void SetAttackTarget (Transform targetTransform) {
attackTarget = targetTransform;
}
void DiableTHis()
{
this.enabled = false;
}
void SetIntialRefrance()
{
enemyMaster = GetComponent
// a = GetComponent ();
myTransform = transform;
KillObjectDamagepostion = GameObject.FindGameObjectWithTag("damge").transform;
}
private void OnEnable()
{
SetIntialRefrance();
enemyMaster.EventEnemySetNavTarget += SetAttackTarget;
enemyMaster.EventEnemyDie += DiableTHis;
}
private void OnDisable()
{
enemyMaster.EventEnemyDie -= DiableTHis;
enemyMaster.EventEnemySetNavTarget -= SetAttackTarget;
}
void TryToAttack()
{
if (attackTarget != null)
{
if (Time.time > nextAttack)
{
nextAttack = Time.time + attackRate;
if (Vector3.Distance(myTransform.position, attackTarget.position) <= attackRange)
{
Vector3 lookAtVector3 = new Vector3(attackTarget.position.x, myTransform.position.y, attackTarget.position.z);
myTransform.LookAt(lookAtVector3);
enemyMaster.CallEventEnemyAttack();
enemyMaster.isOnRoute = false;
}
}
}
}
// Update is called once per frame
public void OnEnemyAttack() {
if (attackTarget != null)
{
if (Vector3.Distance(myTransform.position, attackTarget.position) <= attackRange && attackTarget.GetComponent != null)
{
Vector3 toOther = attackTarget.position - myTransform.position;
if (Vector3.Dot(toOther, myTransform.forward) > range)
{
attackTarget.GetComponent
//a.Play ();
Instantiate(KillObjectDamage, KillObjectDamagepostion.position, KillObjectDamagepostion.rotation);
// Destroy (KillObjectDamage, 0.01f);
// هخلى زى دم يظهر قدام الكاميرا
}
}
}
}
private void Update()
{
TryToAttack();
}
}
|
c#
| 20 | 0.604403 | 147 | 28.363636 | 99 |
starcoderdata
|
import os
import threading
from queue import Queue, Empty
import random
import numpy as np
PCT_TEST = 0.2
SAMPLES_PER_FILE = 100
def main():
split_data()
def split_data():
data_path = os.path.realpath('..\\data')
unsorted_path = os.path.join(data_path, 'shuffled', 'session-{}.npy')
read_file_num = 1
data_file = unsorted_path.format(read_file_num)
files = Queue()
while os.path.isfile(data_file):
read_file_num += 1
files.put(data_file)
data_file = unsorted_path.format(read_file_num)
saver = Saver()
splitters = list(Splitter(PCT_TEST, saver=saver, files_to_split=files) for x in range(0, 5))
for sp in splitters:
sp.start()
for sp in splitters:
sp.join()
np.save(os.path.join(data_path, 'test-set.npy'), np.array(saver.test_nums))
np.save(os.path.join(data_path, 'train-set.npy'), np.array(saver.train_nums))
class Saver:
def __init__(self):
self.test_path = os.path.realpath('..\\data\\test\\session-{}.npy')
self.train_path = os.path.realpath('..\\data\\train\\session-{}.npy')
self.test_set = list()
self.train_set = list()
self.train_nums = list()
self.test_nums = list()
self.file_counter = 0
self.lock = threading.Lock()
def add_test(self, data):
self.test_set.append(data)
with self.lock:
if len(self.test_set) >= SAMPLES_PER_FILE:
self.file_counter += 1
files_to_save = np.array(self.test_set[:SAMPLES_PER_FILE])
del self.test_set[:SAMPLES_PER_FILE]
np.save(self.test_path.format(self.file_counter), files_to_save)
self.test_nums.append(self.file_counter)
def add_train(self, data):
self.train_set.append(data)
with self.lock:
if len(self.train_set) >= SAMPLES_PER_FILE:
self.file_counter += 1
files_to_save = np.array(self.train_set[:SAMPLES_PER_FILE])
del self.train_set[:SAMPLES_PER_FILE]
np.save(self.train_path.format(self.file_counter), files_to_save)
self.train_nums.append(self.file_counter)
class Splitter(threading.Thread):
def __init__(self, prob_test: float, files_to_split: Queue, saver: Saver):
super().__init__()
self.prob_test = prob_test
self.files_to_split = files_to_split
self.done = False
self.saver = saver
self.random: random.Random = random.Random()
def run(self):
try:
while not self.done:
file = self.files_to_split.get(True, 0.5)
data = np.load(file)
print('splitting: {}'.format(file))
for data_point in data:
if self.random.random() <= PCT_TEST:
self.saver.add_test(data_point)
else:
self.saver.add_train(data_point)
except Empty:
return
if __name__ == '__main__':
main()
|
python
| 18 | 0.562134 | 96 | 28.557692 | 104 |
starcoderdata
|
func (client *rpcClient) doBatchCall(rpcRequest []*RPCRequest) ([]*RPCResponse, error) {
httpRequest, err := client.newRequest(rpcRequest)
if err != nil {
return nil, fmt.Errorf("rpc batch call on %v: %v", httpRequest.URL.String(), err.Error())
}
httpResponse, err := client.httpClient.Do(httpRequest)
if err != nil {
return nil, fmt.Errorf("rpc batch call on %v: %v", httpRequest.URL.String(), err.Error())
}
defer httpResponse.Body.Close()
var rpcResponse RPCResponses
decoder := json.NewDecoder(httpResponse.Body)
decoder.DisallowUnknownFields()
decoder.UseNumber()
err = decoder.Decode(&rpcResponse)
// parsing error
if err != nil {
// if we have some http error, return it
if httpResponse.StatusCode >= 400 {
return nil, &HTTPError{
Code: httpResponse.StatusCode,
err: fmt.Errorf("rpc batch call on %v status code: %v. could not decode body to rpc response: %v", httpRequest.URL.String(), httpResponse.StatusCode, err.Error()),
}
}
return nil, fmt.Errorf("rpc batch call on %v status code: %v. could not decode body to rpc response: %v", httpRequest.URL.String(), httpResponse.StatusCode, err.Error())
}
// response body empty
if rpcResponse == nil || len(rpcResponse) == 0 {
// if we have some http error, return it
if httpResponse.StatusCode >= 400 {
return nil, &HTTPError{
Code: httpResponse.StatusCode,
err: fmt.Errorf("rpc batch call on %v status code: %v. rpc response missing", httpRequest.URL.String(), httpResponse.StatusCode),
}
}
return nil, fmt.Errorf("rpc batch call on %v status code: %v. rpc response missing", httpRequest.URL.String(), httpResponse.StatusCode)
}
return rpcResponse, nil
}
|
go
| 19 | 0.704694 | 171 | 38.162791 | 43 |
inline
|
/*
* hostapd / VLAN netlink/ioctl api
* Copyright (c) 2012,
*
* This software may be distributed under the terms of the BSD license.
* See README for more details.
*/
#ifndef VLAN_UTIL_H
#define VLAN_UTIL_H
struct hostapd_data;
struct hostapd_vlan;
struct full_dynamic_vlan;
int vlan_add(const char *if_name, int vid, const char *vlan_if_name);
int vlan_rem(const char *if_name);
int vlan_set_name_type(unsigned int name_type);
int ifconfig_helper(const char *if_name, int up);
int ifconfig_up(const char *if_name);
int iface_exists(const char *ifname);
int vlan_if_remove(struct hostapd_data *hapd, struct hostapd_vlan *vlan);
struct full_dynamic_vlan *
full_dynamic_vlan_init(struct hostapd_data *hapd);
void full_dynamic_vlan_deinit(struct full_dynamic_vlan *priv);
void vlan_newlink(const char *ifname, struct hostapd_data *hapd);
void vlan_dellink(const char *ifname, struct hostapd_data *hapd);
#endif /* VLAN_UTIL_H */
|
c
| 8 | 0.736126 | 73 | 29.806452 | 31 |
starcoderdata
|
/*
* SPDX-FileCopyrightText: Copyright 2021,
* SPDX-License-Identifier: BSD-3-Clause
* SPDX-FileType: SOURCE
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the license found in the LICENSE.txt file in the root
* directory of this source tree.
*/
#ifndef _CUDA_DYNAMIC_LOADING_DYNAMIC_LOADING_H_
#define _CUDA_DYNAMIC_LOADING_DYNAMIC_LOADING_H_
// =======
// Headers
// =======
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && \
!defined(__CYGWIN__)
#include // HMODULE, TEXT, LoadLibrary, GetProcAddress
#elif defined(__unix__) || defined(__unix) || \
(defined(__APPLE__) && defined(__MACH__))
#include // dlopen, dlsym
#else
#error "Unknown compiler"
#endif
#include // std::runtime_error
#include // std::ostringstream
// ===============
// dynamic loading
// ===============
/// \namespace dynamic_loading
///
/// \brief Dynamic loading of shared libraries using \c dlopen tool.
///
/// \details The dynamic loading is compiled with \c CUDA_DYNAMIC_LOADING set
/// to \c 1. When enabeld, the CUDA libraries are loaded at the run-
/// time. This method has an advantage and a disadvatage:
///
/// * Advantage: when dynamic loading is enabled, this package can
/// be distributed withoput bundling the large cuda libraris.
/// That is, when the wheel of this package is repaired with
/// \c auditwheel tool in manylinux platform, the cuda libraries
/// will not be bundled to the wheel, so the size of the wheel
/// does not increase. In contrast, if this package is not
/// compiled with dynamic loading, the cuda \c *.so (or \c *.dll)
/// shared library files will be bundled with the wheel and
/// increase the size of the wheel upto 400MB. Such a large wheel
/// file cannot be uploaded to PyPi due to the 100MB size limit.
/// But with dynamic loading, the package requires these libraries
/// only at the run-time, not at the compile time.
/// * Disadvantage: The end-user must install the *same* cuda
/// version that this package is compiled with. For example, if
/// this package is compiled with cuda 11.x, the user must install
/// cuda 11.x (such as 11.0, 11.1, etc), but not cuda 10.x.
///
/// The run time with/withput dynamic loading is the same. That is,
/// using the dynamic loading doesn't affect the performance at all.
///
/// The functions in this namespace load any generic libraries.
/// We use them to load \c libcudart, \c libcublas, and \c
/// libcusparse.
///
/// \note When this package is compiled with dynamic loading enabled, make
/// sure that cuda toolkit is available at run-time. For instance
/// on a linux cluster, run:
///
/// module load cuda
///
/// \s cudartSymbols,
/// cublasSymbols,
/// cusparseSymbols
namespace dynamic_loading
{
// ==================
// get library handle (unix)
// ==================
#if defined(__unix__) || defined(__unix) || \
(defined(__APPLE__) && defined(__MACH__))
/// \brief Loads a library and returns its handle. This function is
/// compiled only on unix-like compiler.
///
/// \details This function is declared as \c static, which means it
/// is only available withing this namespace.
///
/// \param[in] lib_name
/// Name of the library.
/// \return A pointer to the handle of the loaded library.
static void* get_library_handle_unix(const char* lib_name)
{
void* handle = dlopen(lib_name, RTLD_LAZY);
if (!handle)
{
throw std::runtime_error(dlerror());
}
return handle;
}
#endif
// ==================
// get library handle (windows)
// ==================
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && \
!defined(__CYGWIN__)
/// \brief Loads a library and returns its handle. This function is
/// compiled only on a windows compiler.
///
/// \details This function is declared as \c static, which means it
/// is only available withing this namespace.
///
/// \param[in] lib_name
/// Name of the library.
/// \return A pointer to the handle of the loaded library.
static HMODULE get_library_handle_windows(const char* lib_name)
{
HMODULE handle = LoadLibrary(TEXT(lib_name));
if (!handle)
{
std::ostringstream oss;
oss << "Cannot load the shared library '" << lib_name << "'." \
<< std::endl;
std::string message = oss.str();
throw std::runtime_error(message);
}
return handle;
}
#endif
// ===========
// load symbol
// ===========
/// \brief Loads a symbol within a library and returns a pointer to
/// the symbol (function pointer).
///
/// \tparam Signature
/// The template parameter. The returned symbol pointer is cast
/// from \c void* to the template parameter \c Signature, which
/// is essentially a \c typedef for the output function.
/// \param[in] lib_name
/// Name of the library.
/// \param[in] symbol_name
/// Name of the symbol within the library.
/// \return Returns a pointer to the symbol, which is a pointer to a
/// callable function.
template <typename Signature>
Signature load_symbol(
const char* lib_name,
const char* symbol_name)
{
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && \
!defined(__CYGWIN__)
HMODULE handle = get_library_handle_windows(lib_name);
FARPROC symbol = GetProcAddress(handle, symbol_name);
if (symbol == NULL)
{
std::ostringstream oss;
oss << "The symbol '" << symbol << "' is failed to load " \
<< "from the shared library '" << lib_name << "'." \
<< std::endl;
std::string message = oss.str();
throw std::runtime_error(message);
}
#elif defined(__unix__) || defined(__unix) || \
(defined(__APPLE__) && defined(__MACH__))
void* handle = get_library_handle_unix(lib_name);
void* symbol = dlsym(handle, symbol_name);
char *error = dlerror();
if (error != NULL)
{
throw std::runtime_error(dlerror());
}
#else
#error "Unknown compiler"
#endif
return reinterpret_cast
}
} // namespace dynamic_loading
#endif // _CUDA_DYNAMIC_LOADING_DYNAMIC_LOADING_H_
|
c
| 18 | 0.540008 | 79 | 34.73301 | 206 |
starcoderdata
|
#include <iostream>
using namespace std;
#define int long long
signed main(){
int a;
cin>>a;
int g=0;
for(int i=1;i<=a;i++){
if(i%5!=0&&i%3!=0){
g=g+i;
}
}
cout<<g;
return 0;
}
|
c++
| 10 | 0.546392 | 23 | 10.470588 | 17 |
codenet
|
package com.mrh0.qspl.type;
import java.util.ArrayList;
import java.util.Iterator;
import com.mrh0.qspl.io.console.Console;
import com.mrh0.qspl.type.iterator.IIterable;
import com.mrh0.qspl.type.iterator.IKeyIterable;
import com.mrh0.qspl.type.iterator.TRangeIterator;
import com.mrh0.qspl.type.number.TNumber;
import com.mrh0.qspl.type.var.Var;
public class TString implements Val, IIterable, IKeyIterable{
private final String value;
public TString() {
value = "";
}
@Override
public TAtom getTypeAtom() {
return TAtom.get("string");
}
public TString(TString s) {
value = s.get();
}
public TString(String s) {
value = s;
}
public TString(Object o) {
value = o.toString();
}
public TString(StringBuilder sb) {
value = sb.toString();
}
@Override
public int getType() {
return 0;
}
@Override
public Val duplicate() {
return new TString(this);
}
@Override
public boolean booleanValue() {
return value.length() > 0;
}
@Override
public boolean isString() {
return true;
}
@Override
public String getTypeName() {
return "string";
}
@Override
public Val add(Val v) {
return new TString(value + v.toString());
}
@Override
public Val div(Val v) {
if(v.isString())
return new TArray(value.split(TString.from(v).get()));
if(v.isNumber()) {
TArray a = new TArray();
int i = TNumber.from(v).integerValue();
a.add(new TString(value.substring(0, i)));
a.add(new TString(value.substring(i)));
return a;
}
Val.super.div(v);
return TUndefined.getInstance();
}
public Val accessor(ArrayList args) {
if(args.size() == 0)
return TNumber.create(value.length());
else if(args.size() == 1) {
if(args.get(0).isNumber()) {
return new TString(get(TNumber.from(args.get(0)).integerValue()));
}
}
else if(args.size() == 2) {
if(args.get(0).isNumber() && args.get(1).isNumber()) {
StringBuilder sb = new StringBuilder();
int as = TNumber.from(args.get(0)).integerValue();
int ae = TNumber.from(args.get(1)).integerValue();
if(as == ae) {
sb.append(get(as));
}
else if(as < ae && as < 0 && ae >= 0) {
for(int i = size()+as; i > ae-1; i--) {
sb.append(get(i));
}
}
else if(as > ae && as >= 0 && ae < 0){
for(int i = as; i < size()+ae+1; i++) {
sb.append(get(i));
}
}
else if(as < ae) {
for(int i = as; i < ae+1; i++) {
sb.append(get(i));
}
}
else if(as > ae){
for(int i = as; i > ae-1; i--) {
sb.append(get(i));
}
}
return new TString(sb);
}
}
return TUndefined.getInstance();
}
@Override
public String toString() {
return value;
}
public String get() {
return value;
}
public String get(int i) {
return value.charAt(i)+"";
}
public int size() {
return value.length();
}
@Override
public Object getValue() {
return value;
}
public static TString from(Val v) {
if(v instanceof TString)
return (TString)v;
if(v instanceof Var && v.isString())
return from(((Var)v).get());
//Console.g.err("Cannot convert " + v.getTypeName() + " to string.");
return new TString(v.toString());
}
public static String string(Val v) {
return from(v).get();
}
@Override
public Val assign(Val v) {
if(v.isString()) {
return TNumber.create(value.matches(TString.string(v)));
}
return Val.super.assign(v);
}
public class TStringIterator implements Iterator {
private int index;
private String str;
public TStringIterator(TString a) {
str = a.get();
index = 0;
}
@Override
public boolean hasNext() {
return index < str.length();
}
@Override
public Val next() {
return new TString(str.charAt(index++));
}
}
@Override
public Iterator iterator() {
return new TStringIterator(this);
}
@Override
public Iterator keyIterator() {
return new TRangeIterator(0, size()-1);
}
public Val is(Val v) {
return new TNumber(TString.class.isInstance(v));
}
@Override
public int compare(Val v) {
return value.compareTo(v.toString());
}
@Override
public int hashCode() {
return value.hashCode();
}
}
|
java
| 24 | 0.590216 | 71 | 18.351852 | 216 |
starcoderdata
|
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const BASE_CONFIG = {
gateway: require('./gateway-base.js'),
workbench: require('./workbench-base')
};
const CURRENT_CONFIG = {
gateway: {...BASE_CONFIG.gateway},
workbench: {...BASE_CONFIG.workbench}
};
class ConfigManager {
_write(name) {
const config = JSON.stringify(CURRENT_CONFIG[name], null, 4);
fs.writeFileSync(path.join(this._location, `${name}.json`), `${config}\n`, {encoding: 'utf-8', flag: 'w'});
}
constructor(location) {
if (!fs.existsSync(location)) {
fs.mkdirSync(location, {recursive: true});
} else {
const stat = fs.lstatSync(location);
if (!stat.isDirectory()) throw new Error(`Configuration path ${location} is not a directory.`);
}
this._location = location;
for (let name in CURRENT_CONFIG) {
if (fs.existsSync(`${this._location}/${name}.json`)) {
CURRENT_CONFIG[name] = require(`${this._location}/${name}.json`);
}
}
}
getAllConnections() {
return CURRENT_CONFIG.gateway.connections;
}
getDefaultConnection() {
if (CURRENT_CONFIG.gateway.defaultHost.length === 0) return null;
const defaultHost = CURRENT_CONFIG.gateway.defaultHost;
if (typeof CURRENT_CONFIG.gateway.connections[defaultHost] === 'undefined') return null;
return CURRENT_CONFIG.gateway.connections[defaultHost];
}
removeDefaultConnection() {
CURRENT_CONFIG.gateway.defaultHost = '';
}
getConnectionById(id) {
if (typeof CURRENT_CONFIG.gateway.connections[id] === 'undefined') return null;
return CURRENT_CONFIG.gateway.connections[id];
}
writeConnection(connection) {
if (typeof connection.id !== 'string' || connection.id.length <= 15) {
connection.id = crypto.randomBytes(8).toString('hex');
}
if (connection.isRemoved === true) {
const config = CURRENT_CONFIG.gateway.connections[connection.id];
config.isRemoved = true;
if (connection.id === CURRENT_CONFIG.gateway.defaultHost) {
CURRENT_CONFIG.gateway.defaultHost = '';
}
delete CURRENT_CONFIG.gateway.connections[connection.id];
return config;
}
const base =
typeof BASE_CONFIG.gateway.connections[connection.id] === 'object' ? BASE_CONFIG.gateway.connections : {};
const config = {...base, ...connection};
CURRENT_CONFIG.gateway.connections[connection.id] = config;
if (config.isDefault === true) {
CURRENT_CONFIG.gateway.defaultHost = config.id;
}
delete config.isDefault;
return config;
}
getWorkbenchConfig() {
return CURRENT_CONFIG.workbench;
}
writeWorkbenchConfig(config) {
const fieldList = Object.keys(config);
for (let field of fieldList) {
if (config[field] !== null) {
CURRENT_CONFIG.workbench[field] = config[field];
}
}
return CURRENT_CONFIG.workbench;
}
saveState() {
for (let type in CURRENT_CONFIG) {
this._write(type);
}
}
}
module.exports = ConfigManager;
|
javascript
| 14 | 0.590024 | 118 | 27.470588 | 119 |
starcoderdata
|
def display_download_url(self, remote_url_prefix, remote_upload_dir):
download_url_msg = [
["To get your photos, visit:", 84, config.off_black_colour, "c", 0],
[remote_url_prefix, 84, config.blue_colour, "c", 0],
["and enter your photobooth code:", 84, config.off_black_colour, "c", 0],
[remote_upload_dir, 92, config.blue_colour, "c", 0]
]
self.textprinter.print_text(download_url_msg, 40, True)
self.imageprinter.print_images([[config.menu_overlay_image, 'cb', 0, 0]], False)
# Wait for the user to press the Select button to exit to menu
while True:
choice = self.buttonhandler.wait_for_buttons('s', True)
if (choice != 'screensaver'):
break
|
python
| 10 | 0.584184 | 88 | 42.611111 | 18 |
inline
|
/**
* Created by VitorMaGo on 12/01/2017.
*/
import React from 'react';
import {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import { Link } from 'react-router';
import Splash from '../components/Splash';
import SearchInput, {createFilter} from 'react-search-input'
import swal from 'sweetalert';
import '../../node_modules/sweetalert/dist/sweetalert.css';
import '../css/prefs.css';
import Constants from '../constants/constNum';
import {fetchChannels} from '../actions';
import {fetchPrefs} from '../actions';
import {postPref, deletePref, resetWaitPref} from '../actions';
class Prefs extends Component {
constructor(props) {
super(props);
this.state = {posX: 0, posY: 0, searchTerm: ''};
this.setPref = this.setPref.bind(this);
this.searchUpdated = this.searchUpdated.bind(this);
this.setCoords = this.setCoords.bind(this);
this.shoot = this.shoot.bind(this);
}
componentWillMount() {
const {dispatch} = this.props;
dispatch(fetchPrefs());
dispatch(resetWaitPref());
dispatch(fetchChannels());
}
componentWillUnmount(){
}
componentDidUpdate(){
var lefto = this.state.posX;
var topo = this.state.posY;
window.scrollTo(lefto, topo);
var isPrevEditDone= this.props.wasEditDone;
var prevEdit = this.props.wichLastEdit;
var porra = this;
if(!isPrevEditDone){
swal("Ooops...","Houve um problema com o servidor e não foi possível realizar a última alteração que fez. \n\n Por favor tente outra vez dentro de momentos.","warning");
// swal({
// title: "Ooops...",
// text: "Houve um problema com o servidor e não foi possível realizar a última alteração que fez. \n\n Quer tentar outra vez?",
// type: "warning",
// showCancelButton: true,
// confirmButtonColor: "#00847a",
// confirmButtonText: "Tentar outra vez",
// closeOnConfirm: true
//
// },
// function(){
// this.setPref(prevEdit);
// });
swal({
title: "Ooops...",
text: "Houve um problema com o servidor e não foi possível realizar a última alteração que fez. \n\n Quer tentar outra vez?",
type: "warning",
showCancelButton: false,
confirmButtonColor: "#00847a",
confirmButtonText: "Amigos na mesma.",
closeOnConfirm: true
},
function(){
console.log("WAINTG FINISH?", isPrevEditDone);
porra.shoot();
});
}
}
shoot(){
const {dispatch} = this.props;
dispatch(resetWaitPref());
}
setCoords(){
var doc = document.documentElement;
var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
window.localStorage.setItem("posX", left);
window.localStorage.setItem("posY", top);
this.setState({posX: left, posY: top});
}
//chamado no click deum botão, recebe a sigla do canal desse butão
//confirma se ja tem a preferência -> retira o canal das preferenias
//ELSE confirma se ja tem 4 preferÊncias -> alert('max 4!')
//ELSE adiciona canal a prefrências e manda update pa store
setPref(canal) {
this.setCoords();
const {dispatch} = this.props;
var numDePref = Constants.numPref;
var prefremoved = false;
var userprefs = this.props.preferences;
if(userprefs && canal!=="OOOOO"){
userprefs.forEach((itemo, u) => {
if (itemo === canal) {
// --------------------------------------------------------------------------- Remove Pref
console.log("0 DP");
prefremoved = true;
dispatch(deletePref(canal));
}
});
}
if (!prefremoved) {
if (userprefs.length === numDePref) {
swal("Já chega!","A equipa pede desculpa mas de momento não é possível adicionar mais de "+numDePref+" preferências.","warning"); // --- SWEETALERT
} else {
// ----------------------------------------------------------------------------------- Add Pref
console.log("0 PP");
dispatch(postPref(canal));
}
}
}
render() {
var numDePref = Constants.numPref;
const isFetching = this.props.channels.isFetching;
var doneWaiting = this.props.waited;
var x = this.props.preferences;
var moreprefers = x ? x.slice(0,numDePref) : ["TVI","RTPM","HOLHD"];
console.log("5.5.Co.Pf. Prefs:", moreprefers, "edit done?", this.props.wasEditDone, "wich:", this.props.wichLastEdit);
if(!isFetching && doneWaiting) {
var canaisRaw = this.props.channels.tcanais;
var canaisSearch = canaisRaw.filter(createFilter(this.state.searchTerm, 'CallLetter'));
const channels = canaisSearch.map((item, i) => {
var classer = "btn-sm btn-default";
var canalCallLetter = item.CallLetter;
if (moreprefers) {
moreprefers.forEach(function (prefCallLetter) {
if (prefCallLetter === canalCallLetter) {
classer = "btn-sm btn-success";
}
});
}
//console.log("P0.PREFS RNDR", "upprefs", canalCallLetter, "upprefsId", canalCatalogNumber);
return (
<div key={i} className="col-xs-4 col-sm-4 col-md-3 col-lg-2 celulas">
<button id={canalCallLetter} type="button" className={ classer } onClick={() => this.setPref(canalCallLetter)}>
{item.Name}
);
});
return (
<div id="layout-content" className="prefs-wrapper">
<h2 className="canaisFav">Destaque os seus canais favoritos:
<p className="canaisSel">{"'"+
this.props.preferences.map((word)=>{
console.info("word",word);
return (word===",")?" ":(" "+word+" ")
})+"'"
}
<p className="canaisSel">(máx.: {numDePref})
<Link to="/home">
<button type="button" className="btn btn-primary btn-prefs" onClick={() => this.setCoords()}>Finalizar Escolha
<div className="prefs-list">
<SearchInput className="search-input" onChange={this.searchUpdated} />
{ channels }
);
}else{
return(
<div className="prefsLoading">
Prefs
<Splash />
);
}
}
searchUpdated (term) {
this.setState({searchTerm: term})
}
}
Prefs.propTypes = {
channels: PropTypes.object,
preferences: PropTypes.array,
waited: PropTypes.bool,
wasEditDone: PropTypes.bool,
wichLastEdit: PropTypes.any
}
const mapStateToProps = (state, ownProps) => {
return {channels: state.channels, preferences: state.preferences.upreferencias, waited: state.preferences.waitingdone, wasEditDone: state.preferences.edited, wichLastEdit: state.preferences.lastedit}
}
export default connect(mapStateToProps)(Prefs);
|
javascript
| 25 | 0.516013 | 203 | 34.31441 | 229 |
starcoderdata
|
import MySQLdb
def get_conn():
host = '127.0.0.1'
port = 3306
db = "jikexueyuan"
user = "root"
passwd = "
conn = MySQLdb.connect(host=host,
user=user,
# passwd='',
db=db,
port=port,
# charset="utf-8"
)
return conn
class User(object):
def __init__(self, user_id, user_name):
self.user_id = user_id
self.user_name = user_name
def save(self):
conn = get_conn()
cursor = conn.cursor()
sql = "insert into user (user_id, user_name) VALUES (%s, %s)"
cursor.execute(sql,(self.user_id, self.user_name))
conn.commit()
cursor.close()
conn.close()
@staticmethod
def query_all():
conn = get_conn()
cursor = conn.cursor()
sql = "select * from user"
cursor.execute(sql)
rows = cursor.fetchall()
users = []
for r in rows:
user = User(r[0], r[1])
users.append(user)
conn.commit()
cursor.close()
conn.close()
return users
def __str__(self):
return "id:{}--name:{}".format(self.user_id, self.user_name)
|
python
| 13 | 0.477306 | 69 | 24.296296 | 54 |
starcoderdata
|
using Allors.Repository.Attributes;
namespace Allors.Repository
{
[Id("b57c43ed-4e2a-4fc1-8ed7-cdc3a7067da7")]
public partial class Address : Object
{
#region Inherited Properties
public Permission[] DeniedPermissions { get; set; }
public SecurityToken[] SecurityTokens { get; set; }
#endregion
#region Allors
[Id("6165e7b6-b9b1-4ecb-a7ca-87bda8271251")]
[AssociationId("2f81b499-0bc6-4392-960f-e1fb6363b9ab")]
[RoleId("fa4b87ca-9789-48d0-a881-9c0e7e6d168d")]
[Size(256)]
#endregion
[Workspace]
public string Street { get; set; }
#region Allors
[Id("3a7354b2-c766-4b4d-9841-4f7c2d7ab541")]
[AssociationId("7557e59c-da88-4fee-83b9-4835402b1ec5")]
[RoleId("2f0b09ba-5e69-48ea-b90b-3b95a41c1178")]
[Size(256)]
#endregion
[Workspace]
public string City { get; set; }
#region Allors
[Id("5f7e677a-b88d-43df-88e7-e8548d92dd7f")]
[AssociationId("cfe5f711-5ff4-49a1-bf1b-0db4b7949d2f")]
[RoleId("81b6c10a-b0cf-4233-a306-3717667c9c52")]
[Size(256)]
#endregion
[Workspace]
public string Country { get; set; }
#region inherited methods
public void OnBuild() { }
public void OnPostBuild() { }
public void OnInit()
{
}
public void OnPreDerive() { }
public void OnDerive() { }
public void OnPostDerive() { }
#endregion
}
}
|
c#
| 11 | 0.590291 | 63 | 24.327869 | 61 |
starcoderdata
|
std::vector<uint8_t> encode_bmp_image_to_jpegls(const bmp_image& image, const int near_lossless)
{
assert(image.dib_header.depth == 24); // This function only supports 24-bit BMP pixel data.
assert(image.dib_header.compress_type == 0); // Data needs to be stored by pixel as RGB.
charls::jpegls_encoder encoder;
encoder.frame_info({image.dib_header.width, image.dib_header.height, 8, 3})
.near_lossless(near_lossless);
std::vector<uint8_t> buffer(encoder.estimated_destination_size());
encoder.destination(buffer);
encoder.write_standard_spiff_header(charls::spiff_color_space::rgb,
charls::spiff_resolution_units::dots_per_centimeter,
image.dib_header.vertical_resolution / 100,
image.dib_header.horizontal_resolution / 100);
const size_t encoded_size = encoder.encode(image.pixel_data);
buffer.resize(encoded_size);
return buffer;
}
|
c++
| 11 | 0.634122 | 102 | 45.136364 | 22 |
inline
|
/* Copyright © 2010
* Licensed under the terms of the Microsoft Public License (Ms-PL).
*/
using System;
using System.Collections.Generic;
using System.Xml.Linq;
namespace Prolog.Code
{
[Serializable]
public abstract class CodeTerm : IEquatable IImmuttable
{
#region Fields
public const string ElementName = "CodeTerm";
#endregion
#region Constructors
public static CodeTerm Create(XElement xCodeTerm)
{
foreach (XElement xSubtype in xCodeTerm.Elements())
{
if (xSubtype.Name == CodeValue.ElementName) return CodeValue.Create(xSubtype);
if (xSubtype.Name == CodeVariable.ElementName) return CodeVariable.Create(xSubtype);
if (xSubtype.Name == CodeCompoundTerm.ElementName) return CodeCompoundTerm.Create(xSubtype);
if (xSubtype.Name == CodeList.ElementName) return CodeList.Create(xSubtype);
throw new InvalidOperationException(string.Format("Unknown subtype element {0}", xSubtype.Name));
}
throw new InvalidOperationException("No subtype element specified.");
}
#endregion
#region Public Properties
public virtual bool IsCodeCompoundTerm
{
get { return false; }
}
public virtual bool IsCodeVariable
{
get { return false; }
}
public virtual bool IsCodeValue
{
get { return false; }
}
public virtual bool IsCodeList
{
get { return false; }
}
public CodeCompoundTerm AsCodeCompoundTerm
{
get { return (CodeCompoundTerm)this; }
}
public CodeVariable AsCodeVariable
{
get { return (CodeVariable)this; }
}
public CodeValue AsCodeValue
{
get { return (CodeValue)this; }
}
public CodeList AsCodeList
{
get { return (CodeList)this; }
}
#endregion
#region Public Methods
public static bool operator ==(CodeTerm lhs, CodeTerm rhs)
{
if (object.ReferenceEquals(lhs, rhs)) return true;
if (object.ReferenceEquals(lhs, null) || object.ReferenceEquals(rhs, null)) return false;
return lhs.Equals(rhs);
}
public static bool operator !=(CodeTerm lhs, CodeTerm rhs)
{
return !(lhs == rhs);
}
public abstract XElement ToXElement();
#endregion
#region IEquatable Members
public abstract bool Equals(CodeTerm other);
#endregion
#region Hidden Members
protected virtual XElement ToXElementBase(XElement content)
{
return new XElement(ElementName, content);
}
#endregion
}
}
|
c#
| 17 | 0.559294 | 113 | 23.731092 | 119 |
starcoderdata
|
import React, {useState} from "react";
import CatalogueContent from "./CatalogueContent";
import CatalogueSidebar from "./CatalogueSidebar";
import CatalogueSearch from "./CatalogueSearch";
import styles from '../../styles/Catalogue.module.css';
const Catalogue = (props) => {
const [searchQuery, setSearchQuery] = useState('');
const [originFilter, setOriginFilter] = useState({
indonesia: false,
malaysia: false,
thailand: false,
philippines: false,
chinese: false,
japanese: false,
korean: false,
others: false
});
return (
<CatalogueSearch searchQuery={searchQuery} setSearchQuery={setSearchQuery} />
<div className={styles.catalogueBodyWrapper}>
<CatalogueSidebar
originFilter={originFilter}
setOriginFilter={setOriginFilter}
/>
<CatalogueContent searchQuery={searchQuery} originFilter={originFilter} />
);
};
export default Catalogue;
|
javascript
| 13 | 0.610294 | 90 | 31 | 34 |
starcoderdata
|
#https://github.com/qubvel/classification_models
#!pip install opencv-python
#!apt update && apt install -y libsm6 libxext6
#!apt-get install -y libxrender-dev
#!pip install keras
#!pip install scikit-image
import numpy as np
import cv2
import matplotlib.pyplot as plt
from keras.applications.imagenet_utils import decode_predictions
from classification_models import ResNet152
from classification_models import ResNet50
from classification_models import ResNet34
from classification_models.resnet import preprocess_input
import os
from tensorflow.python.client import device_lib
from keras import backend as K
K.tensorflow_backend._get_available_gpus()
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
# The GPU id to use, usually either "0" or "1"
os.environ["CUDA_VISIBLE_DEVICES"]="0"
# print("---wait---\n")
# print(device_lib.list_local_devices())
# 이미지 불러오기
x = cv2.imread('./imgs/tests/4.jpg')
x_image = cv2.resize(x, (224, 224))
x_img_rgb = cv2.cvtColor(x_image, cv2.COLOR_BGR2RGB)
x = preprocess_input(x_image)
x = np.expand_dims(x, 0)
# resnet pre-trained weight 불러오기
# load model - This will take < 10 min since we have to download weights (about 240 Mb)
# model = ResNet152(input_shape=(224,224,3), weights='imagenet', classes=1000)
model = ResNet50(input_shape=(224,224,3), weights='imagenet', classes=1000)
# model = ResNet34(input_shape=(224,224,3), weights='imagenet', classes=1000)
# processing image
y = model.predict(x)
# 결과
predictions_array = decode_predictions(y)[0]
# 시각화
plt.imshow(x_img_rgb)
for pred in predictions_array:
_,class_name, pred_num = pred
text = class_name + ': ' + str(pred_num)
print(text)
plt.imshow(x_img_rgb)
|
python
| 8 | 0.738351 | 87 | 29.436364 | 55 |
starcoderdata
|
package io.leonid.ds.fifopriorityqueue;
import io.leonid.ds.fifopriorityqueue.Message.InstructionType;
import java.util.ArrayList;
import java.util.List;
/**
* Created by on 16.06.2015.
*/
public class Main {
public static void main(String[] args) {
List messages = new ArrayList
messages.add(new Message(InstructionType.B, "M1"));
messages.add(new Message(InstructionType.A, "M2"));
messages.add(new Message(InstructionType.A, "M3"));
messages.add(new Message(InstructionType.C, "M4"));
messages.add(new Message(InstructionType.D, "M5"));
messages.add(new Message(InstructionType.C, "M6"));
FIFOPriorityQueue queue = new FIFOPriorityQueue
for (Message msg : messages) {
queue.enqueue(msg);
}
while (!queue.isEmpty()) {
System.out.println(queue.dequeue());
}
}
}
|
java
| 12 | 0.639621 | 76 | 28.65625 | 32 |
starcoderdata
|
const mysql = require('mysql2')
function Db (config) {
return new Promise((resolve) => {
let conn = mysql.createConnection(config.mysql)
function handleDisconnect (connection) {
connection.on('error', (err) => {
if (!err.fatal) {
return
}
if (err.code !== 'PROTOCOL_CONNECTION_LOST') {
throw err
}
setTimeout(() => {
conn = mysql.createConnection(config.mysql)
handleDisconnect(conn)
}, 1000)
})
}
handleDisconnect(conn)
function Query (query, params = {}) {
return new Promise((resolve, reject) => {
conn.query(query, params, (err, result) => {
if (err) {
reject(err)
} else {
resolve(result)
}
})
})
}
resolve({
query: Query
})
})
}
module.exports = Db
|
javascript
| 25 | 0.515152 | 54 | 20.488372 | 43 |
starcoderdata
|
/**
* @file environmentvariable58.c
* @brief environmentvariable58 probe
* @author "
*
* This probe is able to process a environmentvariable58_object as defined in OVAL 5.8.
*
*/
/*
* Copyright 2009-2011 Red Hat Inc., Durham, North Carolina.
* All Rights Reserved.
*
* 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
*
* Authors:
*
*/
/*
* environmentvariable58 probe:
*
* pid
* name
* value
*/
#ifdef HAVE_CONFIG_H
#include
#endif
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "seap.h"
#include "probe-api.h"
#include "probe/entcmp.h"
#include "alloc.h"
#include "common/debug_priv.h"
#define BUFFER_SIZE 256
extern char **environ;
static int read_environment(SEXP_t *pid_ent, SEXP_t *name_ent, probe_ctx *ctx)
{
int err = 0, pid, empty, fd;
size_t env_name_size;
SEXP_t *env_name, *env_value, *item, *pid_sexp;
DIR *d;
struct dirent *d_entry;
char *buffer, env_file[256], *null_char;
ssize_t buffer_used;
size_t buffer_size;
d = opendir("/proc");
if (d == NULL) {
dE("Can't read /proc: errno=%d, %s.\n", errno, strerror (errno));
return PROBE_EACCESS;
}
if ((buffer = oscap_realloc(NULL, BUFFER_SIZE)) == NULL) {
dE("Can't allocate memory");
closedir(d);
return PROBE_EFAULT;
}
buffer_size = BUFFER_SIZE;
while ((d_entry = readdir(d))) {
if (strspn(d_entry->d_name, "0123456789") != strlen(d_entry->d_name))
continue;
pid = atoi(d_entry->d_name);
pid_sexp = SEXP_number_newi_32(pid);
if (probe_entobj_cmp(pid_ent, pid_sexp) != OVAL_RESULT_TRUE) {
SEXP_free(pid_sexp);
continue;
}
SEXP_free(pid_sexp);
sprintf(env_file, "/proc/%d/environ", pid);
if ((fd = open(env_file, O_RDONLY)) == -1) {
dE("Can't open \"%s\": errno=%d, %s.\n", env_file, errno, strerror (errno));
item = probe_item_create(
OVAL_INDEPENDENT_ENVIRONMENT_VARIABLE58, NULL,
"pid", OVAL_DATATYPE_INTEGER, (int64_t)pid,
NULL
);
probe_item_setstatus(item, SYSCHAR_STATUS_ERROR);
probe_item_add_msg(item, OVAL_MESSAGE_LEVEL_ERROR,
"Can't open \"%s\": errno=%d, %s.", env_file, errno, strerror (errno));
probe_item_collect(ctx, item);
continue;
}
empty = 1;
if ((buffer_used = read(fd, buffer, buffer_size - 1)) > 0) {
empty = 0;
}
while (! empty) {
while (! (null_char = memchr(buffer, 0, buffer_used))) {
ssize_t s;
if ((size_t)buffer_used >= buffer_size) {
buffer_size += BUFFER_SIZE;
buffer = oscap_realloc(buffer, buffer_size);
if (buffer == NULL) {
dE("Can't allocate memory");
exit(ENOMEM);
}
}
s = read(fd, buffer + buffer_used, buffer_size - buffer_used);
if (s <= 0) {
empty = 1;
buffer[buffer_used++] = 0;
}
else {
buffer_used += s;
}
}
do {
char *eq_char = strchr(buffer, '=');
if (eq_char == NULL) {
/* strange but possible:
* $ strings /proc/1218/environ
/dev/input/event0 /dev/input/event1 /dev/input/event4 /dev/input/event3
*/
buffer_used -= null_char + 1 - buffer;
memmove(buffer, null_char + 1, buffer_used);
continue;
}
env_name_size = eq_char - buffer;
env_name = SEXP_string_new(buffer, env_name_size);
env_value = SEXP_string_newf("%s", buffer + env_name_size + 1);
if (probe_entobj_cmp(name_ent, env_name) == OVAL_RESULT_TRUE) {
item = probe_item_create(
OVAL_INDEPENDENT_ENVIRONMENT_VARIABLE58, NULL,
"pid", OVAL_DATATYPE_INTEGER, (int64_t)pid,
"name", OVAL_DATATYPE_SEXP, env_name,
"value", OVAL_DATATYPE_SEXP, env_value,
NULL);
probe_item_collect(ctx, item);
err = 0;
}
SEXP_free(env_name);
SEXP_free(env_value);
buffer_used -= null_char + 1 - buffer;
memmove(buffer, null_char + 1, buffer_used);
} while ((null_char = memchr(buffer, 0, buffer_used)));
}
close(fd);
}
closedir(d);
oscap_free(buffer);
return err;
}
int probe_main(probe_ctx *ctx, void *arg)
{
SEXP_t *probe_in, *name_ent, *pid_ent;
int pid, err;
probe_in = probe_ctx_getobject(ctx);
name_ent = probe_obj_getent(probe_in, "name", 1);
if (name_ent == NULL) {
return PROBE_ENOENT;
}
pid_ent = probe_obj_getent(probe_in, "pid", 1);
if (pid_ent == NULL) {
SEXP_free(name_ent);
return PROBE_ENOENT;
}
PROBE_ENT_I32VAL(pid_ent, pid, pid = -1;, pid = 0;);
if (pid == -1) {
SEXP_free(name_ent);
SEXP_free(pid_ent);
return PROBE_ERANGE;
}
if (pid == 0) {
/* overwrite pid value with actual pid */
SEXP_t *nref, *nval, *new_pid_ent;
nref = SEXP_list_first(probe_in);
nval = SEXP_number_newu_32(getpid());
new_pid_ent = SEXP_list_new(nref, nval, NULL);
SEXP_vfree(pid_ent, nref, nval, NULL);
pid_ent = new_pid_ent;
}
err = read_environment(pid_ent, name_ent, ctx);
SEXP_free(name_ent);
SEXP_free(pid_ent);
return err;
}
|
c
| 17 | 0.632261 | 94 | 24.147826 | 230 |
starcoderdata
|
/*
* Copyright (C) 2014 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.testing.compile;
import static com.google.common.base.Preconditions.checkArgument;
import static javax.tools.Diagnostic.NOPOS;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.LineMap;
import com.sun.source.tree.Tree;
import com.sun.source.util.SourcePositions;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
/**
* A class for managing and retrieving contextual information for Compilation Trees.
*
* class is used to pair a {@code CompilationUnitTree} with its corresponding {@code Trees},
* {@code SourcePositions}, and {@code LineMap} instances. It acts as a client to the contextual
* information these objects can provide for {@code Tree}s within the {@code CompilationUnitTree}.
*
* @author
*/
final class TreeContext {
private final CompilationUnitTree compilationUnit;
private final Trees trees;
private final SourcePositions sourcePositions;
private final LineMap lineMap;
TreeContext(CompilationUnitTree compilationUnit, Trees trees) {
this.compilationUnit = compilationUnit;
this.trees = trees;
this.sourcePositions = trees.getSourcePositions();
this.lineMap = compilationUnit.getLineMap();
}
/** Returns the {@code CompilationUnitTree} instance for this {@code TreeContext}. */
CompilationUnitTree getCompilationUnit() {
return compilationUnit;
}
/** Returns the {@code Trees} instance for this {@code TreeContext}. */
Trees getTrees() {
return trees;
}
/**
* Returns the {@code TreePath} to the given sub-{@code Tree} of this object's
* {@code CompilationUnitTree}
*
* @throws IllegalArgumentException if the node provided is not a sub-{@code Tree} of this
* object's {@code CompilationUnitTree}.
*/
TreePath getNodePath(Tree node) {
TreePath treePath = trees.getPath(compilationUnit, node);
checkArgument(treePath != null, "The node provided was not a subtree of the "
+ "CompilationUnitTree in this TreeContext. CompilationUnit: %s; Node:",
compilationUnit, node);
return treePath;
}
/**
* Returns start line of the given sub-{@code Tree} of this object's {@code CompilationUnitTree},
* climbing the associated {@code TreePath} until a value other than
* {@link javax.tools.Diagnostic.NOPOS} is found.
*
* method will return {@link javax.tools.Diagnostic.NOPOS} if that value is returned
* by a call to {@link SourcePositions#getStartPosition} for every node in the {@link TreePath}
* provided.
*
* @throws IllegalArgumentException if the node provided is not a sub-{@code Tree} of this
* object's {@code CompilationUnitTree}.
*/
long getNodeStartLine(Tree node) {
long startPosition = getNodeStartPosition(node);
return startPosition == NOPOS ? NOPOS : lineMap.getLineNumber(startPosition);
}
/**
* Returns start column of the given sub-{@code Tree} of this object's
* {@code CompilationUnitTree}, climbing the associated {@code TreePath} until a value other than
* {@link javax.tools.Diagnostic.NOPOS} is found.
*
* method will return {@link javax.tools.Diagnostic.NOPOS} if that value is returned
* by a call to {@link SourcePositions#getStartPosition} for every node in the {@link TreePath}
* provided.
*
* @throws IllegalArgumentException if the node provided is not a sub-{@code Tree} of this
* object's {@code CompilationUnitTree}.
*/
long getNodeStartColumn(Tree node) {
long startPosition = getNodeStartPosition(node);
return startPosition == NOPOS ? NOPOS : lineMap.getColumnNumber(startPosition);
}
/**
* Returns end line of the given sub-{@code Tree} of this object's {@code CompilationUnitTree}.
* climbing the associated {@code TreePath} until a value other than
* {@link javax.tools.Diagnostic.NOPOS} is found.
*
* method will return {@link javax.tools.Diagnostic.NOPOS} if that value is returned
* by a call to {@link SourcePositions#getEndPosition} for every node in the {@link TreePath}
* provided.
*
* @throws IllegalArgumentException if the node provided is not a sub-{@code Tree} of this
* object's {@code CompilationUnitTree}.
*/
long getNodeEndLine(Tree node) {
long endPosition = getNodeEndPosition(node);
return endPosition == NOPOS ? NOPOS : lineMap.getLineNumber(endPosition);
}
/**
* Returns end column of the given sub-{@code Tree} of this object's {@code CompilationUnitTree}.
* climbing the associated {@code TreePath} until a value other than
* {@link javax.tools.Diagnostic.NOPOS} is found.
*
* method will return {@link javax.tools.Diagnostic.NOPOS} if that value is returned
* by a call to {@link SourcePositions#getEndPosition} for every node in the {@link TreePath}
* provided.
*
* @throws IllegalArgumentException if the node provided is not a sub-{@code Tree} of this
* object's {@code CompilationUnitTree}.
*/
long getNodeEndColumn(Tree node) {
long endPosition = getNodeEndPosition(node);
return endPosition == NOPOS ? NOPOS : lineMap.getColumnNumber(endPosition);
}
/**
* Returns start position of the given sub-{@code Tree} of this object's
* {@code CompilationUnitTree}, climbing the associated {@code TreePath} until a value other than
* {@link javax.tools.Diagnostic.NOPOS} is found.
*
* method will return {@link javax.tools.Diagnostic.NOPOS} if that value is returned
* by a call to {@link SourcePositions#getStartPosition} for every node in the {@link TreePath}
* provided.
*
* @throws IllegalArgumentException if the node provided is not a sub-{@code Tree} of this
* object's {@code CompilationUnitTree}.
*/
long getNodeStartPosition(Tree node) {
TreePath currentNode = getNodePath(node);
while (currentNode != null) {
long startPosition = sourcePositions.getStartPosition(compilationUnit, currentNode.getLeaf());
if (startPosition != NOPOS) {
return startPosition;
}
currentNode = currentNode.getParentPath();
}
return NOPOS;
}
/**
* Returns end position of the given sub-{@code Tree} of this object's
* {@code CompilationUnitTree}, climbing the associated {@code TreePath} until a value other than
* {@link javax.tools.Diagnostic.NOPOS} is found.
*
* method will return {@link javax.tools.Diagnostic.NOPOS} if that value is returned
* by a call to {@link SourcePositions#getEndPosition} for every node in the {@link TreePath}
* provided.
*
* @throws IllegalArgumentException if the node provided is not a sub-{@code Tree} of this
* object's {@code CompilationUnitTree}.
*/
long getNodeEndPosition(Tree node) {
TreePath currentNode = getNodePath(node);
while (node != null) {
long endPosition = sourcePositions.getEndPosition(compilationUnit, currentNode.getLeaf());
if (endPosition != NOPOS) {
return endPosition;
}
currentNode = currentNode.getParentPath();
}
return NOPOS;
}
}
|
java
| 13 | 0.713559 | 100 | 39.373684 | 190 |
starcoderdata
|
using System;
namespace HotChocolate.AspNetCore
{
internal static class ContentType
{
public const string GraphQL = "application/graphql; charset=utf-8";
public const string Json = "application/json; charset=utf-8";
public const string MultiPart = "multipart/mixed; boundary=\"-\"";
public static ReadOnlySpan JsonSpan() => new char[]
{
'a',
'p',
'p',
'l',
'i',
'c',
'a',
't',
'i',
'o',
'n',
'/',
'j',
's',
'o',
'n'
};
public static ReadOnlySpan MultiPartSpan() => new char[]
{
'm',
'u',
'l',
't',
'i',
'p',
'a',
'r',
't',
'/',
'f',
'o',
'r',
'm',
'-',
'd',
'a',
't',
'a'
};
}
}
|
c#
| 10 | 0.312386 | 75 | 19.333333 | 54 |
starcoderdata
|
package com.facebook.react.touch;
import android.view.MotionEvent;
import android.view.ViewGroup;
public interface OnInterceptTouchEventListener {
boolean onInterceptTouchEvent(ViewGroup viewGroup, MotionEvent motionEvent);
}
|
java
| 6 | 0.825911 | 80 | 26.444444 | 9 |
starcoderdata
|
private void ValidatePipeline(string pipelineName)
{
// Make sure it's a real pipeline
if (!_pipelines.ContainsKey(pipelineName))
{
throw new KeyNotFoundException($"The pipeline {pipelineName} could not be found");
}
// Make sure the pipeline isn't isolated
if (_pipelines[pipelineName].Isolated)
{
throw new InvalidOperationException($"Cannot access documents in isolated pipeline {pipelineName}");
}
// If this is a deployment pipeline and the request pipeline is not, we can access anything
if (_currentPhase.Pipeline.Deployment && !_pipelines[pipelineName].Deployment)
{
return;
}
// Make sure this pipeline isn't deployment (which it is if we're in the output phase) and we're asking for a non-deployment output phase
if ((_currentPhase.Phase == Phase.Input || _currentPhase.Phase == Phase.Output) && _pipelines[pipelineName].Deployment)
{
throw new InvalidOperationException($"Cannot access documents in the {_currentPhase} phase from another deployment pipeline {pipelineName}");
}
// Make sure we're not accessing our own documents or documents from a non-dependency while in the process phase
if (_currentPhase.Phase == Phase.Process)
{
if (pipelineName.Equals(_currentPhase.PipelineName, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException($"Cannot access documents from currently executing pipeline {pipelineName} while in the {nameof(Phase.Process)} phase");
}
if (!GatherProcessPhasePipelineDependencies(_currentPhase).Contains(pipelineName))
{
throw new InvalidOperationException($"Cannot access documents from pipeline {pipelineName} without a dependency while in the {nameof(Phase.Process)} phase");
}
}
}
|
c#
| 18 | 0.615494 | 177 | 52.974359 | 39 |
inline
|
def plot_brightest(hdus):
""" Simply calls the two methods above and plots the data returned. """
idx, brightest = brightness.get_brightest(hdus)
xs, ys = brightness.pixel_data(idx, hdus)
plt.plot(xs, ys)
plt.show()
|
python
| 7 | 0.614786 | 79 | 31.25 | 8 |
inline
|
package org.jmeld.vc.svn;
import org.jmeld.diff.*;
import org.jmeld.util.*;
import org.jmeld.vc.*;
import org.jmeld.vc.util.*;
import java.io.*;
import java.util.regex.*;
public class DiffCmd
extends VcCmd
{
// Instance variables:
private File file;
private boolean recursive;
private BufferedReader reader;
private String unreadLine;
public DiffCmd(File file, boolean recursive)
{
this.file = file;
this.recursive = recursive;
}
public Result execute()
{
super.execute("svn", "diff", "--non-interactive", "--no-diff-deleted",
recursive ? "" : "-N", file.getPath());
return getResult();
}
protected void build(byte[] data)
{
String path;
JMRevision revision;
JMDelta delta;
DiffData diffData;
diffData = new DiffData();
reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(
data)));
try
{
for (;;)
{
path = readIndex();
if (path == null)
{
break;
}
System.out.println("path = " + path);
revision = new JMRevision(null, null);
diffData.addTarget(path, revision);
readLine(); // =====================================
readLine(); // --- (revision ...)
readLine(); // +++ (working copy)
for (;;)
{
delta = readDelta();
if (delta == null)
{
break;
}
revision.add(delta);
}
}
}
catch (IOException ex)
{
ex.printStackTrace();
setResult(Result.FALSE("Parse failed"));
}
setResultData(diffData);
}
private String readIndex()
throws IOException
{
final String indexMarker = "Index: ";
String line;
line = readLine();
if (line == null || !line.startsWith(indexMarker))
{
return null;
}
return line.substring(indexMarker.length());
}
private JMDelta readDelta()
throws IOException
{
final Pattern deltaPattern = Pattern
.compile("@@ -(\\d*),(\\d*) \\+(\\d*),(\\d*) @@");
String line;
Matcher m;
JMDelta delta;
JMChunk originalChunk;
JMChunk revisedChunk;
// @@ @@
line = readLine();
if (line == null)
{
return null;
}
m = deltaPattern.matcher(line);
if (!m.matches())
{
unreadLine(line);
return null;
}
originalChunk = new JMChunk(Integer.valueOf(m.group(1)), Integer.valueOf(m
.group(2)));
revisedChunk = new JMChunk(Integer.valueOf(m.group(3)), Integer.valueOf(m
.group(4)));
delta = new JMDelta(originalChunk, revisedChunk);
while ((line = readLine()) != null)
{
if (line.startsWith(" "))
{
continue;
}
if (line.startsWith("+"))
{
continue;
}
if (line.startsWith("-"))
{
continue;
}
unreadLine(line);
break;
}
System.out.println("delta = " + delta);
return delta;
}
private void unreadLine(String unreadLine)
{
this.unreadLine = unreadLine;
}
private String readLine()
throws IOException
{
String line;
if (unreadLine != null)
{
line = unreadLine;
unreadLine = null;
return line;
}
return reader.readLine();
}
public static void main(String[] args)
{
DiffCmd cmd;
DiffIF result;
File file = parseFile(args);
if (file == null) {
return;
}
result = new SubversionVersionControl()
.executeDiff(file, true);
if (result != null)
{
for (DiffIF.TargetIF target : result.getTargetList())
{
System.out.println(target.getPath() + " " + target.getRevision());
}
}
}
}
|
java
| 16 | 0.527322 | 89 | 18.512563 | 199 |
starcoderdata
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yx.sumk.dubbo.annotation;
import org.apache.dubbo.common.utils.Assert;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @author wjiajun
*/
public class AnnotationAttributes extends LinkedHashMap<String, Object> {
private final String displayName;
private final Annotation annotation;
public AnnotationAttributes(Annotation annotation) {
Assert.notNull(annotation.annotationType(), "'annotationType' must not be null");
this.annotation = annotation;
Class<? extends Annotation> annotationType = annotation.annotationType();
this.displayName = annotationType.getName();
}
public Annotation annotation() {
return this.annotation;
}
public String getString(String attributeName) {
return getRequiredAttribute(attributeName, String.class);
}
public String[] getStringArray(String attributeName) {
return getRequiredAttribute(attributeName, String[].class);
}
public boolean getBoolean(String attributeName) {
return getRequiredAttribute(attributeName, Boolean.class);
}
@SuppressWarnings("unchecked")
public Class<? extends T> getClass(String attributeName) {
return getRequiredAttribute(attributeName, Class.class);
}
@SuppressWarnings("unchecked")
public <A extends Annotation> A[] getAnnotationArray(String attributeName, Class annotationType) {
Object array = Array.newInstance(annotationType, 0);
return (A[]) getRequiredAttribute(attributeName, array.getClass());
}
@SuppressWarnings("unchecked")
private T getRequiredAttribute(String attributeName, Class expectedType) {
Assert.notEmptyString(attributeName, "'attributeName' must not be null or empty");
Object value = get(attributeName);
assertAttributePresence(attributeName, value);
assertNotException(attributeName, value);
if (!expectedType.isInstance(value) && expectedType.isArray() &&
expectedType.getComponentType().isInstance(value)) {
Object array = Array.newInstance(expectedType.getComponentType(), 1);
Array.set(array, 0, value);
value = array;
}
assertAttributeType(attributeName, value, expectedType);
return (T) value;
}
private void assertAttributePresence(String attributeName, Object attributeValue) {
if (attributeValue == null) {
throw new IllegalArgumentException(String.format(
"Attribute '%s' not found in attributes for annotation [%s]", attributeName, this.displayName));
}
}
private void assertNotException(String attributeName, Object attributeValue) {
if (attributeValue instanceof Exception) {
throw new IllegalArgumentException(String.format(
"Attribute '%s' for annotation [%s] was not resolvable due to exception [%s]",
attributeName, this.displayName, attributeValue), (Exception) attributeValue);
}
}
private void assertAttributeType(String attributeName, Object attributeValue, Class expectedType) {
if (!expectedType.isInstance(attributeValue)) {
throw new IllegalArgumentException(String.format(
"Attribute '%s' is of type [%s], but [%s] was expected in attributes for annotation [%s]",
attributeName, attributeValue.getClass().getSimpleName(), expectedType.getSimpleName(),
this.displayName));
}
}
@Override
public Object putIfAbsent(String key, Object value) {
Object obj = get(key);
if (obj == null) {
obj = put(key, value);
}
return obj;
}
@Override
public String toString() {
Iterator<Map.Entry<String, Object>> entries = entrySet().iterator();
StringBuilder sb = new StringBuilder("{");
while (entries.hasNext()) {
Map.Entry<String, Object> entry = entries.next();
sb.append(entry.getKey());
sb.append('=');
sb.append(entry.getValue().toString());
sb.append(entries.hasNext() ? ", " : "");
}
sb.append("}");
return sb.toString();
}
}
|
java
| 15 | 0.743678 | 103 | 33.828358 | 134 |
starcoderdata
|
var webpack = require("webpack");
var pkg = require("./package.json");
var path = require("path");
var StringReplacePlugin = require("string-replace-webpack-plugin");
var config = {
entry: {
"axes": "./src/index.umd.ts"
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name].js",
library: [pkg.namespace.eg, "Axes"],
libraryTarget: "umd",
},
externals: {
"@egjs/component": {
commonjs: "@egjs/component",
commonjs2: "@egjs/component",
amd: "@egjs/component",
root: [pkg.namespace.eg, "Component"]
},
"hammerjs": {
commonjs: "hammerjs",
commonjs2: "hammerjs",
amd: "hammerjs",
root: pkg.namespace.Hammer,
},
},
devtool: "cheap-source-map",
resolve: {
extensions: [".ts", ".js"]
},
module: {
rules: [
{
test: /\.ts$/,
exclude: /node_modules/,
loader: "awesome-typescript-loader"
},
{
test: /(\.js)$/,
loader: StringReplacePlugin.replace({
replacements: [{
pattern: /#__VERSION__#/ig,
replacement: function (match, p1, offset, string) {
return pkg.version;
}
}]
})
}]
},
plugins: [
new webpack.optimize.ModuleConcatenationPlugin(),
new StringReplacePlugin()
]
};
module.exports = function (env) {
env = env || "development";
return require("./config/webpack.config." + env + ".js")(config);
};
|
javascript
| 21 | 0.598083 | 67 | 20.52381 | 63 |
starcoderdata
|
protected void formatThrows(IndentableWriter writer, TestCase test) {
//method threw an exception
ElementInfo exception = (ElementInfo) test.returnValue;
//formatting the assertThrows
writer.indent(indents).append("assertThrows(").append(NL);
writer.indent(indents + 2).append(exception.getClassInfo().getName()).append(".class,").append(NL);
writer.indent(indents + 2).append("() -> {");
formatCall(writer, test).append(";}");
if (messageLevel > NO_MESSAGE) {
writer.append(",").append(NL).indent(indents + 2);
formatAssertMessage(writer, test);
}
writer.append(NL).indent(indents).append(");").append(NL);
}
|
java
| 11 | 0.675188 | 103 | 40.625 | 16 |
inline
|
const knex = require('knex')({
client: 'mysql2',
connection: {
host: 'localhost',
user: 'root'
}
});
knex.raw('CREATE DATABASE IF NOT EXISTS sdc2')
.then(() => knex.raw('USE sdc2'))
.then(() => knex.raw('DROP TABLE IF EXISTS images'))
.then(() => knex.raw('DROP TABLE IF EXISTS listings'))
.then(() => knex.schema.createTable('listings', t => {
t.increments('listingId').unsigned().primary();
}))
.then(() => knex.schema.createTable('images', t => {
t.increments('imgId').unsigned().primary();
t.integer('listingId').unsigned().index().references('listingId').inTable('listings');
t.integer('imgPath');
t.string('description');
}))
.then(() => knex.destroy())
.catch(err => {
console.log(err);
process.exit(1);
});
|
javascript
| 25 | 0.597468 | 90 | 28.259259 | 27 |
starcoderdata
|
def letter_queue(commands):
result = ''
for i in commands:
if 'PUSH' in i: result += i[-1]
else: result = result[1:]
return result
|
python
| 12 | 0.626214 | 47 | 28.571429 | 7 |
starcoderdata
|
package com.toobei.common.utils;
import android.app.Activity;
import android.content.Context;
import com.toobei.common.TopBaseActivity;
import org.xsl781.utils.Logger;
import org.xsl781.utils.NetAsyncTask;
public abstract class MyNetAsyncTask extends NetAsyncTask {
TopBaseActivity activity;
protected String strResponse;
protected MyNetAsyncTask(Context ctx) {
super(ctx);
activity = (TopBaseActivity) ctx;
}
protected MyNetAsyncTask(Context ctx, boolean openDialog) {
super(ctx, openDialog);
activity = (TopBaseActivity) ctx;
}
@Override
protected void onPreExecute() {
if (openDialog && dialog == null) {
dialog = ToastUtil.showCustomDialog((Activity) ctx);
}
}
@Override
protected void onPostExecute(Void aVoid) {
// super.onPostExecute(aVoid);
if (openDialog) {
if (dialog.isShowing() && activity != null && !activity.isFinishing()) {
dialog.dismiss();
}
}
onPost(exception);
if(exception!=null){
Logger.e("onPostExecute",exception.toString());
}
}
}
|
java
| 11 | 0.730989 | 75 | 21.891304 | 46 |
starcoderdata
|
# Copyright 2022 The Matrix.org Foundation C.I.C.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
This module exposes a single function which checks synapse's dependencies are present
and correctly versioned. It makes use of `importlib.metadata` to do so. The details
are a bit murky: there's no easy way to get a map from "extras" to the packages they
require. But this is probably just symptomatic of Python's package management.
"""
import logging
from typing import Iterable, NamedTuple, Optional
from packaging.requirements import Requirement
DISTRIBUTION_NAME = "matrix-synapse"
try:
from importlib import metadata
except ImportError:
import importlib_metadata as metadata # type: ignore[no-redef]
__all__ = ["check_requirements"]
class DependencyException(Exception):
@property
def message(self) -> str:
return "\n".join(
[
"Missing Requirements: %s" % (", ".join(self.dependencies),),
"To install run:",
" pip install --upgrade --force %s" % (" ".join(self.dependencies),),
"",
]
)
@property
def dependencies(self) -> Iterable[str]:
for i in self.args[0]:
yield '"' + i + '"'
DEV_EXTRAS = {"lint", "mypy", "test", "dev"}
RUNTIME_EXTRAS = (
set(metadata.metadata(DISTRIBUTION_NAME).get_all("Provides-Extra")) - DEV_EXTRAS
)
VERSION = metadata.version(DISTRIBUTION_NAME)
def _is_dev_dependency(req: Requirement) -> bool:
return req.marker is not None and any(
req.marker.evaluate({"extra": e}) for e in DEV_EXTRAS
)
class Dependency(NamedTuple):
requirement: Requirement
must_be_installed: bool
def _generic_dependencies() -> Iterable[Dependency]:
"""Yield pairs (requirement, must_be_installed)."""
requirements = metadata.requires(DISTRIBUTION_NAME)
assert requirements is not None
for raw_requirement in requirements:
req = Requirement(raw_requirement)
if _is_dev_dependency(req):
continue
# https://packaging.pypa.io/en/latest/markers.html#usage notes that
# > Evaluating an extra marker with no environment is an error
# so we pass in a dummy empty extra value here.
must_be_installed = req.marker is None or req.marker.evaluate({"extra": ""})
yield Dependency(req, must_be_installed)
def _dependencies_for_extra(extra: str) -> Iterable[Dependency]:
"""Yield additional dependencies needed for a given `extra`."""
requirements = metadata.requires(DISTRIBUTION_NAME)
assert requirements is not None
for raw_requirement in requirements:
req = Requirement(raw_requirement)
if _is_dev_dependency(req):
continue
# Exclude mandatory deps by only selecting deps needed with this extra.
if (
req.marker is not None
and req.marker.evaluate({"extra": extra})
and not req.marker.evaluate({"extra": ""})
):
yield Dependency(req, True)
def _not_installed(requirement: Requirement, extra: Optional[str] = None) -> str:
if extra:
return (
f"Synapse {VERSION} needs {requirement.name} for {extra}, "
f"but it is not installed"
)
else:
return f"Synapse {VERSION} needs {requirement.name}, but it is not installed"
def _incorrect_version(
requirement: Requirement, got: str, extra: Optional[str] = None
) -> str:
if extra:
return (
f"Synapse {VERSION} needs {requirement} for {extra}, "
f"but got {requirement.name}=={got}"
)
else:
return (
f"Synapse {VERSION} needs {requirement}, but got {requirement.name}=={got}"
)
def check_requirements(extra: Optional[str] = None) -> None:
"""Check Synapse's dependencies are present and correctly versioned.
If provided, `extra` must be the name of an pacakging extra (e.g. "saml2" in
`pip install matrix-synapse[saml2]`).
If `extra` is None, this function checks that
- all mandatory dependencies are installed and correctly versioned, and
- each optional dependency that's installed is correctly versioned.
If `extra` is not None, this function checks that
- the dependencies needed for that extra are installed and correctly versioned.
:raises DependencyException: if a dependency is missing or incorrectly versioned.
:raises ValueError: if this extra does not exist.
"""
# First work out which dependencies are required, and which are optional.
if extra is None:
dependencies = _generic_dependencies()
elif extra in RUNTIME_EXTRAS:
dependencies = _dependencies_for_extra(extra)
else:
raise ValueError(f"Synapse {VERSION} does not provide the feature '{extra}'")
deps_unfulfilled = []
errors = []
for (requirement, must_be_installed) in dependencies:
try:
dist: metadata.Distribution = metadata.distribution(requirement.name)
except metadata.PackageNotFoundError:
if must_be_installed:
deps_unfulfilled.append(requirement.name)
errors.append(_not_installed(requirement, extra))
else:
# We specify prereleases=True to allow prereleases such as RCs.
if not requirement.specifier.contains(dist.version, prereleases=True):
deps_unfulfilled.append(requirement.name)
errors.append(_incorrect_version(requirement, dist.version, extra))
if deps_unfulfilled:
for err in errors:
logging.error(err)
raise DependencyException(deps_unfulfilled)
|
python
| 16 | 0.661326 | 88 | 34.465909 | 176 |
starcoderdata
|
from x5_02_jug import minimum_pours
def test_minimum_pours():
assert minimum_pours(3, 5, 3) == (True, 1)
assert minimum_pours(3, 5, 5) == (True, 1)
assert minimum_pours(3, 5, 2) == (True, 2)
assert minimum_pours(3, 5, 1) == (True, 4)
assert minimum_pours(3, 5, 4) == (True, 6)
def test_minimum_pours():
assert minimum_pours(3, 3, 2) == (False, -1)
|
python
| 7 | 0.595745 | 48 | 27.923077 | 13 |
starcoderdata
|
import os
import cv2
import json
import torch
import scipy
import scipy.io as sio
from skimage import io
from torchvision import datasets, transforms
from torchvision.datasets.folder import ImageFolder, default_loader
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.data import create_transform
class Flowers(ImageFolder):
def __init__(self, root, train=True, transform=None, **kwargs):
self.dataset_root = root
self.loader = default_loader
self.target_transform = None
self.transform = transform
label_path = os.path.join(root, 'imagelabels.mat')
split_path = os.path.join(root, 'setid.mat')
print('Dataset Flowers is trained with resolution 224!')
# labels
labels = sio.loadmat(label_path)['labels'][0]
self.img_to_label = dict()
for i in range(len(labels)):
self.img_to_label[i] = labels[i]
splits = sio.loadmat(split_path)
self.trnid, self.valid, self.tstid = sorted(splits['trnid'][0].tolist()), \
sorted(splits['valid'][0].tolist()), \
sorted(splits['tstid'][0].tolist())
if train:
self.imgs = self.trnid + self.valid
else:
self.imgs = self.tstid
self.samples = []
for item in self.imgs:
self.samples.append((os.path.join(root, 'jpg', "image_{:05d}.jpg".format(item)), self.img_to_label[item-1]-1))
class Cars196(ImageFolder, datasets.CIFAR10):
base_folder_devkit = 'devkit'
base_folder_trainims = 'cars_train'
base_folder_testims = 'cars_test'
filename_testanno = 'cars_test_annos.mat'
filename_trainanno = 'cars_train_annos.mat'
base_folder = 'cars_train'
train_list = [
['00001.jpg', '8df595812fee3ca9a215e1ad4b0fb0c4'],
['00002.jpg', '4b9e5efcc3612378ec63a22f618b5028']
]
test_list = []
num_training_classes = 98 # 196/2
def __init__(self, root, train=False, transform=None, target_transform=None, **kwargs):
self.root = root
self.transform = transform
self.target_transform = target_transform
self.loader = default_loader
print('Dataset Cars196 is trained with resolution 224!')
self.samples = []
self.nb_classes = 196
if train:
labels = \
sio.loadmat(os.path.join(self.root, self.base_folder_devkit, self.filename_trainanno))['annotations'][0]
for item in labels:
img_name = item[-1].tolist()[0]
label = int(item[4]) - 1
self.samples.append((os.path.join(self.root, self.base_folder_trainims, img_name), label))
else:
labels = \
sio.loadmat(os.path.join(self.root, 'cars_test_annos_withlabels.mat'))['annotations'][0]
for item in labels:
img_name = item[-1].tolist()[0]
label = int(item[-2]) - 1
self.samples.append((os.path.join(self.root, self.base_folder_testims, img_name), label))
class Pets(ImageFolder):
def __init__(self, root, train=True, transform=None, target_transform=None, **kwargs):
self.dataset_root = root
self.loader = default_loader
self.target_transform = None
self.transform = transform
train_list_path = os.path.join(self.dataset_root, 'annotations', 'trainval.txt')
test_list_path = os.path.join(self.dataset_root, 'annotations', 'test.txt')
self.samples = []
if train:
with open(train_list_path, 'r') as f:
for line in f:
img_name = line.split(' ')[0]
label = int(line.split(' ')[1])
self.samples.append((os.path.join(root, 'images', "{}.jpg".format(img_name)), label-1))
else:
with open(test_list_path, 'r') as f:
for line in f:
img_name = line.split(' ')[0]
label = int(line.split(' ')[1])
self.samples.append((os.path.join(root, 'images', "{}.jpg".format(img_name)), label-1))
class INatDataset(ImageFolder):
def __init__(self, root, train=True, year=2018, transform=None, target_transform=None,
category='name', loader=default_loader):
self.transform = transform
self.loader = loader
self.target_transform = target_transform
self.year = year
# assert category in ['kingdom','phylum','class','order','supercategory','family','genus','name']
path_json = os.path.join(root, f'{"train" if train else "val"}{year}.json')
with open(path_json) as json_file:
data = json.load(json_file)
with open(os.path.join(root, 'categories.json')) as json_file:
data_catg = json.load(json_file)
path_json_for_targeter = os.path.join(root, f"train{year}.json")
with open(path_json_for_targeter) as json_file:
data_for_targeter = json.load(json_file)
targeter = {}
indexer = 0
for elem in data_for_targeter['annotations']:
king = []
king.append(data_catg[int(elem['category_id'])][category])
if king[0] not in targeter.keys():
targeter[king[0]] = indexer
indexer += 1
self.nb_classes = len(targeter)
self.samples = []
for elem in data['images']:
cut = elem['file_name'].split('/')
target_current = int(cut[2])
path_current = os.path.join(root, cut[0], cut[2], cut[3])
categors = data_catg[target_current]
target_current_true = targeter[categors[category]]
self.samples.append((path_current, target_current_true))
# __getitem__ and __len__ inherited from ImageFolder
def build_dataset(is_train, args, folder_name=None):
transform = build_transform(is_train, args)
if args.data_set == 'CIFAR10':
dataset = datasets.CIFAR10(args.data_path, train=is_train, transform=transform, download=True)
nb_classes = 10
elif args.data_set == 'CIFAR100':
dataset = datasets.CIFAR100(args.data_path, train=is_train, transform=transform, download=True)
nb_classes = 100
elif args.data_set == 'CARS':
dataset = Cars196(args.data_path, train=is_train, transform=transform)
nb_classes = 196
elif args.data_set == 'PETS':
dataset = Pets(args.data_path, train=is_train, transform=transform)
nb_classes = 37
elif args.data_set == 'FLOWERS':
dataset = Flowers(args.data_path, train=is_train, transform=transform)
nb_classes = 102
elif args.data_set == 'IMNET':
root = os.path.join(args.data_path, 'train' if is_train else 'val')
dataset = datasets.ImageFolder(root, transform=transform)
nb_classes = 1000
elif args.data_set == 'EVO_IMNET':
root = os.path.join(args.data_path, folder_name)
dataset = datasets.ImageFolder(root, transform=transform)
nb_classes = 1000
elif args.data_set == 'INAT':
dataset = INatDataset(args.data_path, train=is_train, year=2018,
category=args.inat_category, transform=transform)
nb_classes = dataset.nb_classes
elif args.data_set == 'INAT19':
dataset = INatDataset(args.data_path, train=is_train, year=2019,
category=args.inat_category, transform=transform)
nb_classes = dataset.nb_classes
return dataset, nb_classes
def build_transform(is_train, args):
resize_im = args.input_size > 32
if is_train:
# this should always dispatch to transforms_imagenet_train
transform = create_transform(
input_size=args.input_size,
is_training=True,
color_jitter=args.color_jitter,
auto_augment=args.aa,
interpolation=args.train_interpolation,
re_prob=args.reprob,
re_mode=args.remode,
re_count=args.recount,
)
if not resize_im:
# replace RandomResizedCropAndInterpolation with
# RandomCrop
transform.transforms[0] = transforms.RandomCrop(
args.input_size, padding=4)
return transform
t = []
if resize_im:
size = int((256 / 224) * args.input_size)
t.append(
transforms.Resize(size, interpolation=3), # to maintain same ratio w.r.t. 224 images
)
t.append(transforms.CenterCrop(args.input_size))
t.append(transforms.ToTensor())
t.append(transforms.Normalize(IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD))
return transforms.Compose(t)
|
python
| 21 | 0.593835 | 122 | 38.963636 | 220 |
starcoderdata
|
let reverse = function(num) {
return +num
.toString()
.split('')
.reverse()
.join('')
}
/*
function dividing(num) {
let digit;
while(num) {
digit = num % 10;
num = Math.floor(num / 10);
}
}
let n = num;
let digits = n.toString().split("");
let sorted = digits.reverse();
let newNum = sorted.join("");
let resultNum = parseInt(newNum);
return resultNum;
*/
/*
let digit;
let resultDiv;
while(num) {
digit = num % 10;
resultDiv = num = Math.floor(num / 10);
}
console.log(resultDiv)
*/
|
javascript
| 12 | 0.526814 | 45 | 12.229167 | 48 |
starcoderdata
|
#ifndef _PWM_H_
#define _PWM_H_
#define PWM_TIMER NRF_TIMER2
#define PWM_IRQHandler TIMER2_IRQHandler
#define PWM_IRQn TIMER2_IRQn
#define PWM_IRQ_PRIORITY 3
void play_notes( uint32_t* freqs, uint8_t num_notes, uint8_t buzzer_pin );
#endif // _PWM_H_
|
c
| 7 | 0.618729 | 74 | 26.181818 | 11 |
starcoderdata
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "SkillEditorPreviewClient.h"
void SkillEditorPreviewClient::Draw(FViewport* InViewport, FCanvas* Canvas)
{
FEditorViewportClient::Draw(InViewport, Canvas);
}
void SkillEditorPreviewClient::Tick(float DeltaSeconds)
{
FEditorViewportClient::Tick(DeltaSeconds);
if(DeltaSeconds>0.f)
{
PreviewScene->GetWorld()->Tick(LEVELTICK_All,DeltaSeconds);
}
}
UWorld* SkillEditorPreviewClient::GetWorld() const
{
if(PreviewScene!=nullptr)
return PreviewScene->GetWorld();
return GWorld;
}
SkillEditorPreviewClient::SkillEditorPreviewClient(FEditorModeTools* InModeTools,
FPreviewScene* InPreviewScene,
const TWeakPtr InEditorViewportWidget ):
FEditorViewportClient(InModeTools,InPreviewScene,InEditorViewportWidget)
{
SetViewLocation(FVector(100,100,100));
}
SkillEditorPreviewClient::~SkillEditorPreviewClient()
{
}
|
c++
| 12 | 0.741544 | 118 | 27.825 | 40 |
starcoderdata
|
import torch
import torch.nn as nn
from torch.distributions.categorical import Categorical as MultiNomial
from utils import f1_score,get_answer,exact_match_score
def crossEntropyLoss(start_logits,end_logits,answer):
lossFunction=nn.CrossEntropyLoss()
loss=0
for i in range(start_logits.shape[1]):
loss+=lossFunction(start_logits[:,i,:].view(1,-1),torch.tensor(answer['start_offset']).view(1))
loss+=lossFunction(end_logits[:,i,:].view(1,-1),torch.tensor(answer['end_offset']).view(1))
return loss
def reinforcement_gradient_loss(start_logits,end_logits,start_guess,end_guess):
lossFunction=nn.CrossEntropyLoss()
loss=0
for i in range(start_logits.shape[1]):
loss+=lossFunction(start_logits[:,i,:].view(1,-1),start_guess[i].view(1))
loss+=lossFunction(end_logits[:,i,:].view(1,-1),end_guess[i].view(1))
return loss
def reward(document,sampled_starts,sampled_ends,greedy_start,greedy_end,gold_start,gold_end):
rewards=[]
gold_answer,baseline_answer=get_answer(document,gold_start,gold_end,int(greedy_start),int(greedy_end))
baseline=f1_score(baseline_answer,gold_answer)
em=exact_match_score(baseline_answer,gold_answer)
for i in range(4):
gold_answer,sample_answer=get_answer(document,gold_start,gold_end,int(sampled_starts[i]),int(sampled_ends[i]))
f1=f1_score(sample_answer,gold_answer)
normalized_reward=f1-baseline
rewards.append(normalized_reward)
return rewards,baseline,em
def loss_function_for_reinforcement(start_logits,end_logits,answer,document):
final_start_logits=start_logits[:,-1,:].view(-1)
final_end_logits=end_logits[:,-1,:].view(-1)
greedy_start=torch.argmax(final_start_logits)
greedy_end=torch.argmax(final_end_logits)
sample_start=[]
sample_end=[]
for i in range(4):
start_logit=start_logits[:,i,:].view(-1)
end_logit=end_logits[:,i,:].view(-1)
start_sample=MultiNomial(logits=start_logit).sample().detach()
end_sample=MultiNomial(logits=end_logit).sample().detach()
sample_start.append(start_sample)
sample_end.append(end_sample)
rewards,baseline,em=reward(document,sample_start,sample_end,greedy_start,greedy_end,answer['start_offset'],answer['end_offset'])
expected_reward=-sum(rewards)/len(rewards)
reinforcement_loss=reinforcement_gradient_loss(start_logits,end_logits,sample_start,sample_end)
return reinforcement_loss+(expected_reward-reinforcement_loss.item()),baseline,em
def get_loss(start_logits,end_logits,answer,document,sigma_ce,sigma_rl):
ce_loss=crossEntropyLoss(start_logits,end_logits,answer)
rl_loss,baseline,em=loss_function_for_reinforcement(start_logits,end_logits,answer,document)
ce_loss/=(2*sigma_ce**2)
rl_loss/=(2*sigma_rl**2)
ce_loss+=torch.log(sigma_ce**2)
rl_loss+=torch.log(sigma_rl**2)
return ce_loss+rl_loss,baseline,em
|
python
| 15 | 0.613046 | 136 | 42.448718 | 78 |
starcoderdata
|
package resources
type EDRDetection interface {
Detect(data SystemData) (EDRType, bool)
Name() string
Type() EDRType
}
type EDRType string
var (
WinDefenderEDR EDRType = "defender"
KaskperskyEDR EDRType = "kaspersky"
CrowdstrikeEDR EDRType = "crowdstrike"
McafeeEDR EDRType = "mcafee"
SymantecEDR EDRType = "symantec"
CylanceEDR EDRType = "cylance"
CarbonBlackEDR EDRType = "carbon_black"
SentinelOneEDR EDRType = "sentinel_one"
FireEyeEDR EDRType = "fireeye"
ElasticAgentEDR EDRType = "elastic_agent"
)
|
go
| 7 | 0.727434 | 42 | 23.565217 | 23 |
starcoderdata
|
import {
SUBSCRIPTION_LOADING,
SUBSCRIPTION_SUCCESS,
SUBSCRIPTION_ERROR,
SUBSCRIPTION_LOAD,
SUBSCRIPTION_REMOVE_SUCCESS,
SUBSCRIPTION_CLEAN,
} from '../actions/subscription';
import reducer from './subscription';
describe('Subscription reducer', () => {
it('should handle initial state', () => {
expect(reducer(undefined, {})).toEqual({
loading: false,
error: false,
success: false,
subscriptions: [],
});
});
it('should handle SUBSCRIPTION_LOADING action', () => {
expect(reducer({}, { type: SUBSCRIPTION_LOADING, loading: true })).toEqual({
loading: true,
});
});
it('should handle SUBSCRIPTION_LOAD action', () => {
expect(reducer({}, { type: SUBSCRIPTION_LOAD, subscriptions: [{ id: 'abc' }] })).toEqual({
loading: false,
error: false,
success: true,
subscriptions: [{ id: 'abc' }],
});
});
it('should handle SUBSCRIPTION_SUCCESS action', () => {
expect(reducer({ subscriptions: [] }, { type: SUBSCRIPTION_SUCCESS, subscription: { id: 'abc' } })).toEqual({
loading: false,
error: false,
success: true,
subscriptions: [{ id: 'abc' }],
});
});
it('should handle SUBSCRIPTION_ERROR action', () => {
expect(reducer({}, { type: SUBSCRIPTION_ERROR })).toEqual({
loading: false,
error: true,
success: false,
});
});
it('should handle SUBSCRIPTION_REMOVE_SUCCESS action', () => {
expect(
reducer(
{
loading: false,
error: false,
success: true,
subscriptions: [{ category: 'abc' }, { category: 'cde' }],
},
{ type: SUBSCRIPTION_REMOVE_SUCCESS, subscription: { category: 'abc' } }
)
).toEqual({
loading: false,
error: false,
success: true,
subscriptions: [{ category: 'cde' }],
});
});
it('should handle SUBSCRIPTION_CLEAN action', () => {
expect(reducer({}, { type: SUBSCRIPTION_CLEAN })).toEqual({
subscriptions: [],
});
});
});
|
javascript
| 24 | 0.568059 | 113 | 25.089744 | 78 |
starcoderdata
|
#ifndef _ATARI_INTERFACE_H_
#define _ATARI_INTERFACE_H_
#include "SYS_Types.h"
#include "DebuggerDefs.h"
#include
#define C64DEBUGGER_ATARI800_VERSION_STRING "4.2.0"
#define ATARI_AUDIO_BUFFER_FRAMES 512
#define MAX_NUM_POKEYS 2
void mt_SYS_FatalExit(char *text);
unsigned long mt_SYS_GetCurrentTimeInMillis();
void mt_SYS_Sleep(unsigned long milliseconds);
char *ATRD_GetPathForRoms();
extern volatile int atrd_debug_mode;
void atrd_mark_atari_cell_read(uint16 addr);
void atrd_mark_atari_cell_write(uint16 addr, uint8 value);
void atrd_mark_atari_cell_execute(uint16 addr, uint8 opcode);
void atrd_check_pc_breakpoint(uint16 pc);
int atrd_debug_pause_check(int allowRestore);
int atrd_is_performing_snapshot_restore();
int atrd_check_snapshot_restore();
void atrd_check_snapshot_interval();
void atrd_async_load_snapshot(char *filePath);
void atrd_async_save_snapshot(char *filePath);
void atrd_async_set_cpu_pc(int newPC);
void atrd_async_set_reg_a(int newRegValue);
void atrd_async_set_reg_x(int newRegValue);
void atrd_async_set_reg_y(int newRegValue);
void atrd_async_set_reg_p(int newRegValue);
void atrd_async_set_reg_s(int newRegValue);
void atrd_async_check();
void atrd_sound_init();
void atrd_sound_pause();
void atrd_sound_resume();
void atrd_sound_lock();
void atrd_sound_unlock();
void atrd_mutex_lock();
void atrd_mutex_unlock();
int atrd_get_is_receive_channels_data(int pokeyNum);
void atrd_pokey_receive_channels_data(int pokeyNum, int isOn);
void atrd_pokey_channels_data(int pokeyNumber, int v1, int v2, int v3, int v4, short mix);
int atrd_is_debug_on_atari();
unsigned int atrd_get_joystick_state(int port);
unsigned int atrd_get_emulation_frame_number();
void atrd_set_emulation_frame_number(unsigned int frameNum);
// read and write state to CByteBuffer
void *atrd_state_buffer_open(const char *name, const char *mode);
int atrd_state_buffer_close(void *stream);
size_t atrd_state_buffer_read(void *buf, size_t len, void *stream);
size_t atrd_state_buffer_write(const void *buf, size_t len, void *stream);
//
extern volatile int atrd_start_frame_for_snapshots_manager;
extern volatile unsigned int atrd_previous_instruction_maincpu_clk;
extern volatile unsigned int atrd_previous2_instruction_maincpu_clk;
int atrd_get_emulation_frame_num();
extern volatile unsigned int atrdMainCpuDebugCycle;
extern volatile unsigned int atrdMainCpuCycle;
extern volatile unsigned int atrdMainCpuPreviousInstructionCycle;
#endif
|
c
| 8 | 0.77315 | 90 | 29.530864 | 81 |
starcoderdata
|
<?php
namespace Cravler\FayeAppBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Cravler\FayeAppBundle\DependencyInjection\CravlerFayeAppExtension;
use Cravler\FayeAppBundle\EntryPoint\EntryPointInterface;
use Cravler\FayeAppBundle\Service\EntryPointsChain;
use Cravler\FayeAppBundle\Service\ExtensionsChain;
use Cravler\FayeAppBundle\Service\SecurityManager;
use Cravler\FayeAppBundle\Twig\FayeAppExtension;
use Cravler\FayeAppBundle\Ext\AppExtInterface;
/**
* @author
*/
class AppController extends AbstractController
{
/**
* @param Request $request
* @return array
*/
protected function getInitConfig(Request $request)
{
/* @var TokenStorageInterface $ts */
$ts = $this->container->get('security.token_storage');
/* @var SecurityManager $sm */
$sm = $this->container->get('cravler_faye_app.service.security_manager');
$config = $this->container->getParameter(CravlerFayeAppExtension::CONFIG_KEY);
$security = array();
if ($ts->getToken()) {
if ($ts->getToken()->getUser() instanceof UserInterface) {
/* @var UserInterface $user */
$user = $ts->getToken()->getUser();
$security = array(
'username' => $user->getUsername(),
'token' => $sm->createToken($user->getUsername()),
);
}
}
$token = isset($security['token']) ? $security['token'] : 'anonymous';
$security['url'] = $this->generateUrl('faye_app_security', [], 0);
$security['url.hash'] = md5($token . ';' . $security['url'] . ';' . $config['security_url_salt']);
return array(
'url' => FayeAppExtension::generateUri($request, $config),
'options' => $config['app']['options'],
'security' => $security,
'entry_point_prefix' => $config['entry_point_prefix'],
);
}
/**
* @param Request $request
* @return JsonResponse
*/
public function configAction(Request $request)
{
return new JsonResponse($this->getInitConfig($request));
}
/**
* @param Request $request
* @return Response
*/
public function initAction(Request $request)
{
$content = 'FayeApp.connect(' . json_encode(
$this->getInitConfig($request),
JSON_PRETTY_PRINT|JSON_FORCE_OBJECT
) . ');' . PHP_EOL;
/* @var ExtensionsChain $extChain */
$extChain = $this->container->get('cravler_faye_app.service.extensions_chain');
foreach ($extChain->getExtensions() as $extension) {
if ($extension instanceof AppExtInterface) {
$content .= $extension->getAppExt() . PHP_EOL;
}
}
return new Response($content, 200, array('Content-Type' => $request->getMimeType('js')));
}
/**
* @param Request $request
* @return JsonResponse
*/
public function securityAction(Request $request)
{
/* @var EntryPointsChain $entryPointsChain */
$entryPointsChain = $this->container->get('cravler_faye_app.service.entry_points_chain');
/* @var SecurityManager $sm */
$sm = $this->container->get('cravler_faye_app.service.security_manager');
$response = array(
'success' => false,
'cache' => false,
);
$type = null;
$channel = null;
$entryPoint = null;
$data = $request->request->all();
if (isset($data['channel'])) {
if ($data['channel'] === '/meta/subscribe') {
$type = EntryPointInterface::TYPE_SUBSCRIBE;
$channel = $data['subscription'];
} else {
$type = EntryPointInterface::TYPE_PUBLISH;
$channel = $data['channel'];
}
}
if ($channel) {
$key = explode('/', $channel, 3);
if (count($key) == 3) {
$channel = '/' . $key[2];
$entryPoint = $entryPointsChain->getEntryPoint(explode('@', str_replace('~', '.', $key[1]), 2)[1]);
}
}
$message = array(
'ext' => isset($data['ext']) ? $data['ext'] : array(),
'data' => isset($data['data']) ? $data['data'] : array(),
'clientId' => isset($data['clientId']) ? $data['clientId'] : null,
);
if (isset($message['ext']['security']) && $sm->isSystem($message['ext']['security'])) {
$response['success'] = true;
} else if ($entryPoint && $entryPoint->isGranted($type, $channel, $message)) {
$response['success'] = true;
$response['cache'] = $entryPoint->useCache($type, $channel, $message);
}
if ($response['success'] === false && !isset($response['msg'])) {
$response['msg'] = '403::Forbidden';
}
return new JsonResponse($response);
}
/**
* @param Request $request
* @return Response
*/
public function statusAction(Request $request)
{
$config = $this->container->getParameter(CravlerFayeAppExtension::CONFIG_KEY);
$appCfg = $config['app'];
$healthCheckCfg = $config['health_check'];
$scheme = $appCfg['scheme'] ?: $request->getScheme();
$url = $scheme . '://' . $appCfg['host'];
$port = 'https' == $scheme ? 443 : 80;
if ($appCfg['port']) {
$url = $url . ':' . $appCfg['port'];
$port = $appCfg['port'];
}
$url = $url . ($healthCheckCfg['path'] ?: $appCfg['mount']);
$status = 503;
$content = 'Service Unavailable';
try {
$fp = fsockopen($appCfg['host'], $port, $errCode, $errStr, 1);
if ($fp) {
stream_context_set_default(array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
),
));
$headers = get_headers($url);
$code = intval(substr($headers[0], 9, 3));
$responseCode = $healthCheckCfg['response_code'] ?: 400;
if ($responseCode == $code) {
$status = 200;
$content = 'OK';
}
}
fclose($fp);
} catch (\Exception $e) {}
return new Response($content, $status);
}
/**
* @param Request $request
* @param string|null $type
* @return array
*/
public function exampleAction(Request $request, $type = null)
{
$config = $this->container->getParameter(CravlerFayeAppExtension::CONFIG_KEY);
if (!$config['example']) {
throw $this->createNotFoundException();
}
/* @var SecurityManager $sm */
$sm = $this->container->get('cravler_faye_app.service.security_manager');
return $this->render(
'@CravlerFayeApp/App/example.html.twig',
array(
'system' => $type == 'system',
'security' => array(
'system' => $sm->createSystemToken(),
),
)
);
}
}
|
php
| 23 | 0.533897 | 115 | 32.558952 | 229 |
starcoderdata
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
private float mouseX;
private float mouseY;
[Header("Sensitivity of mouse")]
public float sensitivityMouse = 200f;
public Transform Player;
void Update()
{
mouseX = Input.GetAxis("Mouse X") * sensitivityMouse * Time.deltaTime;
mouseY = Input.GetAxis("Mouse Y") * sensitivityMouse * Time.deltaTime;
Player.Rotate(mouseX * new Vector3(0, 1, 0));
transform.Rotate(-mouseY * new Vector3(1, 0, 0));
}
}
|
c#
| 13 | 0.668896 | 78 | 25 | 23 |
starcoderdata
|
public boolean isLocal() {
if (!this.lookupAttempted) {
try {
setLocalPlace((IServiceProviderPlace) Namespace.lookup(this.serviceLocation));
} catch (NamespaceException e) {
// empty catch block
}
logger.debug("NS Lookup for locality on " + this.serviceLocation + (this.localPlace == null ? " failed" : " passed"));
this.lookupAttempted = true;
}
return this.localPlace != null;
}
|
java
| 14 | 0.556886 | 130 | 37.615385 | 13 |
inline
|
#pragma once
#include "lib-main.h"
namespace lib
{
struct Rect
{
int x, y;
int w, h;
Rect() : x(0), y(0), w(1), h(1) {};
Rect(int x, int y, int w, int h) : x(x), y(y), w(w), h(h) {};
RECT toRECT();
};
}
|
c
| 11 | 0.5 | 62 | 9.75 | 20 |
starcoderdata
|
import { MDXProvider } from "@mdx-js/react"
import { MDXRenderer } from "gatsby-plugin-mdx"
import React from "react"
import { TextLink, Anchor } from "./links"
const components = {
a: ({ href, ...props }) => {
const internal = /^\.?\/(?!\/)/.test(href)
return internal ? (
<TextLink to={href} {...props} />
) : (
<Anchor href={href} {...props} />
)
},
}
const shortcodes = {}
const MDX = ({ children, ...props }) => {
return (
<MDXProvider components={components} shortcodes={shortcodes} {...props}>
)
}
export default MDX
|
javascript
| 10 | 0.597037 | 76 | 22.275862 | 29 |
starcoderdata
|
import net.runelite.mapping.Export;
import net.runelite.mapping.Implements;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("gl")
@Implements("Node")
public class Node {
@ObfuscatedName("cb")
@Export("hash")
public long hash;
@ObfuscatedName("cg")
@ObfuscatedSignature(
signature = "Lgl;"
)
@Export("next")
public Node next;
@ObfuscatedName("cl")
@ObfuscatedSignature(
signature = "Lgl;"
)
@Export("previous")
Node previous;
@ObfuscatedName("kc")
@Export("unlink")
public void unlink() {
if(this.previous != null) {
this.previous.next = this.next;
this.next.previous = this.previous;
this.next = null;
this.previous = null;
}
}
@ObfuscatedName("kz")
@Export("linked")
public boolean linked() {
return this.previous != null;
}
}
|
java
| 11 | 0.64308 | 48 | 21.348837 | 43 |
starcoderdata
|
const { join } = require("path");
const { chmodSync, readFileSync, writeFileSync } = require("fs-extra");
const afterPack = async (context) => {
if (context.electronPlatformName !== "linux") {
return;
}
if (context.targets.length !== 1) {
throw new Error("Linux can only target 1 build at a time.");
}
const target = context.targets[0];
if (target.name !== "appImage") {
throw new Error("I don't know if this will work with other linux targets. You'll need to test before removing this check!");
}
const appRunTemplate = readFileSync(join(__dirname, "AppRun"), {encoding: "utf-8"});
const appRunFinal = appRunTemplate.replace(/{APP_NAME}/g, target.options.executableName);
const appRunPath = join(context.appOutDir, "AppRun")
writeFileSync(appRunPath, appRunFinal, {encoding: "utf-8"});
// make sure this file is executable
chmodSync(appRunPath, 0o755);
};
module.exports = afterPack;
|
javascript
| 7 | 0.663934 | 132 | 38.04 | 25 |
starcoderdata
|
#include <bits/stdc++.h>
using namespace std;
using llong = long long;
using ldbl = long double;
using P = pair<llong, llong>;
#define ALL(x) x.begin(), x.end()
const llong inf = 1100100100100100ll;
const llong mod = 1e9+7;
int main() {
llong N, M;
priority_queue<P, vector<P>, greater<P> > A;
llong B, C;
cin >> N >> M;
P in;
for (int i = 0; i < N; i++) {
cin >> in.first;
in.second = 1;
A.push(in);
}
for (int i = 0; i < M; i++) {
cin >> B >> C;
llong era = B;
while(era) {
if (A.top().first >= C)
break;
if (A.top().second <= era) {
era -= A.top().second;
A.pop();
} else {
P next = A.top();
next.second -= era;
era = 0;
A.pop();
A.push(next);
}
}
A.push(P(C, B-era));
}
llong ans = 0;
while(A.size()) {
// cerr << A.top().first << " " << A.top().second << endl;
ans += A.top().first * A.top().second;
A.pop();
}
cout << ans << endl;
return 0;
}
|
c++
| 14 | 0.511727 | 60 | 15.473684 | 57 |
codenet
|
X = int(input())
A = X//500 #500en
nokori = X - A*500
B = nokori //5 #5en
ureshisa = 1000*A + 5*B
print(ureshisa)
|
python
| 7 | 0.570248 | 23 | 11.1 | 10 |
codenet
|
using UnityEngine;
namespace GnosticDev
{
public class UpdatingEntity : MonoBehaviour, ITick
{
private void OnEnable()
{
SimpleUpdateManager.onTick += Tick;
SimpleUpdateManager.onFixedTick += FixedTick;
SimpleUpdateManager.onLateTick += LateTick;
}
private void OnDisable()
{
SimpleUpdateManager.onTick -= Tick;
SimpleUpdateManager.onFixedTick -= FixedTick;
SimpleUpdateManager.onLateTick -= LateTick;
}
public void Tick() => Debug.Log("Ticking");
public void FixedTick() => Debug.Log("Fixed Ticking");
public void LateTick() => Debug.Log("Late Ticking");
}
}
|
c#
| 11 | 0.611625 | 62 | 25.137931 | 29 |
starcoderdata
|
void MaterialChanged(Material material)
{
int offsetInt = Mathf.FloorToInt( material.GetFloat("_QueueOffset") );
material.renderQueue = 3000 + offsetInt; // To show before After 'cutout' shaders use 2450
switch ( (BlendMode)material.GetFloat("_Mode") )
{
case BlendMode.AlphaBlending:
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
break;
case BlendMode.Multiply:
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.DstColor);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
break;
case BlendMode.Randon:
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.DstColor);
break;
}
// Debug.LogFormat("Mat: {0} Queue: {1} Offset: {2} BlendMode: {3}",material.name, material.renderQueue, offsetInt, (BlendMode)material.GetFloat("_Mode"));
SetMaterialKeywords(material);
}
|
c#
| 15 | 0.724678 | 161 | 44.291667 | 24 |
inline
|
public static void applyModification( Entry entry, Modification modification ) throws LdapException
{
Attribute modAttr = modification.getAttribute();
String modificationId = modAttr.getUpId();
switch ( modification.getOperation() )
{
case ADD_ATTRIBUTE:
Attribute modifiedAttr = entry.get( modificationId );
if ( modifiedAttr == null )
{
// The attribute should be added.
entry.put( modAttr );
}
else
{
// The attribute exists : the values can be different,
// so we will just add the new values to the existing ones.
for ( Value value : modAttr )
{
// If the value already exist, nothing is done.
// Note that the attribute *must* have been
// normalized before.
modifiedAttr.add( value );
}
}
break;
case REMOVE_ATTRIBUTE:
if ( modAttr.get() == null )
{
// We have no value in the ModificationItem attribute :
// we have to remove the whole attribute from the initial
// entry
entry.removeAttributes( modificationId );
}
else
{
// We just have to remove the values from the original
// entry, if they exist.
modifiedAttr = entry.get( modificationId );
if ( modifiedAttr == null )
{
break;
}
for ( Value value : modAttr )
{
// If the value does not exist, nothing is done.
// Note that the attribute *must* have been
// normalized before.
modifiedAttr.remove( value );
}
if ( modifiedAttr.size() == 0 )
{
// If this was the last value, remove the attribute
entry.removeAttributes( modifiedAttr.getUpId() );
}
}
break;
case REPLACE_ATTRIBUTE:
if ( modAttr.get() == null )
{
// If the modification does not have any value, we have
// to delete the attribute from the entry.
entry.removeAttributes( modificationId );
}
else
{
// otherwise, just substitute the existing attribute.
entry.put( modAttr );
}
break;
default:
break;
}
}
|
java
| 15 | 0.415923 | 99 | 35.047619 | 84 |
inline
|
#include "ResourceMngr.h"
namespace Engine
{
TextureCache ResourceMngr::textureCache;
Engine::GLTexture ResourceMngr::GetTexture(const char* texturePath)
{
return textureCache.GetTexture(texturePath);
}
}
|
c++
| 8 | 0.78125 | 68 | 17.75 | 12 |
starcoderdata
|
#include
clock_t clock(void)
{
struct timeval tv;
if(gettimeofday(&tv, 0) != 0)
return -1;
return tv.tv_sec * 1000000 + tv.tv_usec;
}
|
c
| 9 | 0.633333 | 41 | 14 | 10 |
starcoderdata
|
<?php
declare(strict_types=1);
namespace GC\Universe\Exception;
class RegisterUniversePublicGalaxiesFullException extends \Exception implements UniverseExceptionInterface
{
/**
* @param \GC\Galaxy\Model\Galaxy
*
* @return \GC\Universe\Exception\RegisterUniversePublicGalaxiesFullException
*/
public static function forFull(): RegisterUniversePublicGalaxiesFullException
{
return new static('Currently there is no public galaxy with enough space for a new player.');
}
}
|
php
| 10 | 0.742481 | 106 | 27 | 19 |
starcoderdata
|
<div class="horizontal-menu">
<nav class="navbar top-navbar col-lg-12 col-12 p-0">
<div class="container">
<div class="text-center navbar-brand-wrapper d-flex align-items-center justify-content-center">
<?php if ($this->data['token']['level'] == 'Admin') { ?>
<a class="navbar-brand brand-logo-mini" href="<?= base_url('dash') ?>">
<a class="navbar-brand brand-logo" href="<?= base_url('dash') ?>">
<?php } else { ?>
<a class="navbar-brand brand-logo-mini" href="<?= base_url('evaluasi') ?>">
<a class="navbar-brand brand-logo" href="<?= base_url('evaluasi') ?>">
<?php } ?>
<div class="navbar-menu-wrapper d-flex align-items-center justify-content-end">
<ul class="navbar-nav navbar-nav-right">
<li class="nav-item nav-profile dropdown">
<a class="nav-link" href="#" data-toggle="dropdown" id="profileDropdown">
<img src="<?= base_url('assets/images/icon.png'); ?>" alt="profile" />
<div class="dropdown-menu dropdown-menu-right navbar-dropdown" aria-labelledby="profileDropdown">
<a class="dropdown-item" href="<?= base_url('logout'); ?>">
<i class="ti-power-off text-primary">
Logout
<button class="navbar-toggler navbar-toggler-right d-lg-none align-self-center" type="button" data-toggle="horizontal-menu-toggle">
<span class="ti-menu">
<?php if ($this->data['token']['level'] == 'Admin') { ?>
<nav class="bottom-navbar">
<div class="container">
<ul class="nav page-navigation">
<li class="nav-item">
<a class="nav-link" href="<?= base_url('dash') ?>">
<i class="fas fa-home menu-icon">
<span class="menu-title">Dashboard
<li class="nav-item">
<a href="#" class="nav-link">
<i class="fas fa-user menu-icon">
<span class="menu-title">User
<i class="fas fa-sort-down menu-arrow">
<div class="submenu">
<ul class="submenu-item">
<li class="nav-item"><a class="nav-link" href="<?= base_url('create-usr') ?>">Tambah User
<li class="nav-item"><a class="nav-link" href="<?= base_url('user') ?>">Data User
<li class="nav-item">
<a href="#" class="nav-link">
<i class="ti-user menu-icon">
<span class="menu-title">Pegawai
<i class="fas fa-sort-down menu-arrow">
<div class="submenu">
<ul class="submenu-item">
<li class="nav-item"><a class="nav-link" href="<?= base_url('create-pgw') ?>">Tambah Pegawai
<li class="nav-item"><a class="nav-link" href="<?= base_url('pegawai') ?>">Data Pegawai
<li class="nav-item">
<a href="#" class="nav-link">
<i class="ti-desktop menu-icon">
<span class="menu-title">Departement
<i class="fas fa-sort-down menu-arrow">
<div class="submenu">
<ul class="submenu-item">
<li class="nav-item"><a class="nav-link" href="<?= base_url('create-dpt') ?>">Tambah Departement
<li class="nav-item"><a class="nav-link" href="<?= base_url('departement') ?>">Data Departement
<li class="nav-item">
<a href="#" class="nav-link">
<i class="ti-support menu-icon">
<span class="menu-title">Kategori Kriteria
<i class="fas fa-sort-down menu-arrow">
<div class="submenu">
<ul class="submenu-item">
<li class="nav-item"><a class="nav-link" href="<?= base_url('create-ktg') ?>">Tambah Kategori
<li class="nav-item"><a class="nav-link" href="<?= base_url('kategori') ?>">Data Kategori
<li class="nav-item">
<a href="#" class="nav-link">
<i class="ti-pencil-alt menu-icon">
<span class="menu-title">Kriteria
<i class="fas fa-sort-down menu-arrow">
<div class="submenu">
<ul class="submenu-item">
<li class="nav-item"><a class="nav-link" href="<?= base_url('create-krt') ?>">Tambah Kriteria
<li class="nav-item"><a class="nav-link" href="<?= base_url('kriteria') ?>">Data Kriteria
<?php } ?>
|
php
| 9 | 0.397688 | 147 | 56.93578 | 109 |
starcoderdata
|
/**
* Copyright (c) Dell Inc., or its subsidiaries. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
package com.dellemc.oe.ingest;
import java.net.URI;
import java.util.concurrent.CompletableFuture;
import com.dellemc.oe.util.Parameters;
import io.pravega.client.ClientConfig;
import io.pravega.client.EventStreamClientFactory;
import io.pravega.client.admin.StreamManager;
import io.pravega.client.stream.EventStreamWriter;
import io.pravega.client.stream.EventWriterConfig;
import io.pravega.client.stream.ScalingPolicy;
import io.pravega.client.stream.StreamConfiguration;
import io.pravega.client.stream.impl.UTF8StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A simple example app that uses a Pravega Writer to write to a given scope and stream.
*/
public class EventWriter {
private static Logger LOG = LoggerFactory.getLogger(EventWriter.class);
public EventWriter() {
}
public void run() {
try{
URI controllerURI = Parameters.getControllerURI();
StreamManager streamManager = StreamManager.create(controllerURI);
String scope = Parameters.getScope();
String streamName = Parameters.getStreamName();
StreamConfiguration streamConfig = StreamConfiguration.builder()
.scalingPolicy(ScalingPolicy.byEventRate(
Parameters.getTargetRateEventsPerSec(), Parameters.getScaleFactor(), Parameters.getMinNumSegments()))
.build();
streamManager.createStream(scope, streamName, streamConfig);
ClientConfig config = ClientConfig.builder().controllerURI(controllerURI)
.credentials(null).trustStore("").build();
EventStreamClientFactory clientFactory = EventStreamClientFactory.withScope(scope, config);
// Create Pravega event writer
EventStreamWriter writer = clientFactory.createEventWriter(
streamName,
new UTF8StringSerializer(),
EventWriterConfig.builder().build());
while(true) {
final CompletableFuture writeFuture = writer.writeEvent( Parameters.getRoutingKey(), Parameters.getMessage());
writeFuture.get();
Thread.sleep(1000);
}
}
catch(Exception e){
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
EventWriter ew = new EventWriter();
ew.run();
}
}
|
java
| 16 | 0.670155 | 129 | 37.486111 | 72 |
starcoderdata
|
package edu.sdccd.cisc191.template;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.stream.Collectors;
import java.util.List;
import static edu.sdccd.cisc191.template.Wordle.initialize;
import static org.junit.jupiter.api.Assertions.*;
class WordleTest {
@Test
void excludeLetters() {
ArrayList wordList = initialize();
String test = "asdf";
String[] array = new String[test.length()];
for (int i = 0; i < test.length(); i++) {
array[i] = Character.toString(test.charAt(i));
}
System.out.println(array[1]);
assert wordList != null;
Wordle.excludeLetters(wordList, test);
for (String s : array)
for (Wordle wordle : wordList) {
if (wordle.getPositionalLetter()
&& wordle.getTestString().contains(s))
fail();
}
}
@Test
void containsLetters() {
ArrayList wordList = initialize();
String positionOne = "e";
String positionTwo = "r";
String positionThree = "";
String positionFour = "";
String positionFive = "";
assert wordList != null;
Wordle.containsLetters(wordList, positionOne, positionTwo, positionThree, positionFour, positionFive);
assertFalse(wordList.get(0).getContainedLetters());
assertTrue(wordList.get(1).getContainedLetters());
assertFalse(wordList.get(2).getContainedLetters());
assertFalse(wordList.get(3).getContainedLetters());
assertFalse(wordList.get(4).getContainedLetters());
assertFalse(wordList.get(5).getContainedLetters());
assertFalse(wordList.get(6).getContainedLetters());
assertFalse(wordList.get(7).getContainedLetters());
assertFalse(wordList.get(8).getContainedLetters());
assertTrue(wordList.get(9).getContainedLetters());
}
@Test
void containsLettersEliminateByPosition() {
ArrayList wordList = initialize();
String positionOne = "";
String positionTwo = "r";
String positionThree = "";
String positionFour = "";
String positionFive = "k";
String a;
assert wordList != null;
Wordle.containsLetters(wordList, positionOne, positionTwo, positionThree, positionFour, positionFive);
for (Wordle wordle : wordList) {
a = Character.toString(wordle.getTestString().charAt(0));
if (a.equals(positionOne) && wordle.getContainedLettersOne())
fail();
a = Character.toString(wordle.getTestString().charAt(1));
if (a.equals(positionTwo) && wordle.getContainedLettersTwo())
fail();
a = Character.toString(wordle.getTestString().charAt(2));
if (a.equals(positionThree) && wordle.getContainedLettersThree())
fail();
a = Character.toString(wordle.getTestString().charAt(3));
if (a.equals(positionFour) && wordle.getContainedLettersFour())
fail();
a = Character.toString(wordle.getTestString().charAt(4));
if (a.equals(positionFive) && wordle.getContainedLettersFive())
fail();
}
}
@Test
void positionalLetters() {
ArrayList wordList = initialize();
assert wordList != null;
Wordle.positionalLetters(wordList, "t", "r", "e", "a", "t");
int counter = 0;
for (Wordle wordle : wordList) {
if (wordle.getPositionalLetter())
counter += 1;
}
assertEquals(1, counter);
}
@Test
void resetValues() {
ArrayList wordList = initialize();
assert wordList != null;
for (Wordle value : wordList) {
value.setExcludedLetters(true);
value.setContainedLetters(true);
value.setContainedLettersOne(true);
value.setContainedLettersTwo(true);
value.setContainedLettersThree(true);
value.setContainedLettersFour(true);
value.setContainedLettersFive(true);
value.setPositionalLettersOne(true);
value.setPositionalLettersTwo(true);
value.setPositionalLettersThree(true);
value.setPositionalLettersFour(true);
value.setPositionalLettersFive(true);
value.setPositionalLetters(true);
}
Wordle.resetValues(wordList);
for (Wordle wordle : wordList) {
if (wordle.getExcludedLetters() ||
wordle.getContainedLettersOne() ||
wordle.getContainedLettersTwo() ||
wordle.getContainedLettersThree() ||
wordle.getContainedLettersFour() ||
wordle.getContainedLettersFive() ||
wordle.getContainedLetters() ||
wordle.getPositionalLettersOne() ||
wordle.getPositionalLettersTwo() ||
wordle.getPositionalLettersThree() ||
wordle.getPositionalLettersFour() ||
wordle.getPositionalLettersFive() ||
wordle.getPositionalLetter()
)
fail();
}
}
@Test
void alphabeticalOrder() {
ArrayList wordList = initialize();
assert wordList != null;
List list = wordList.stream().sorted(Comparator.comparing(Wordle::getTestString)).collect(Collectors.toList());
assertEquals("aalii", list.get(0).getTestString());
assertEquals("aargh", list.get(1).getTestString());
assertEquals("aarti", list.get(2).getTestString());
assertEquals("abaca", list.get(3).getTestString());
assertEquals("abaci", list.get(4).getTestString());
assertEquals("aback", list.get(5).getTestString());
assertEquals("abacs", list.get(6).getTestString());
assertEquals("abaft", list.get(7).getTestString());
assertEquals("abaka", list.get(8).getTestString());
assertEquals("abamp", list.get(9).getTestString());
}
}
|
java
| 23 | 0.59701 | 127 | 37.407407 | 162 |
starcoderdata
|
#pragma once
// Copyright 2010-2020.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include // any_of
#include // to_underlying
#include // integral_constant
namespace dctl::core {
enum struct color
:
unsigned char
{
black,
white,
size
};
constexpr auto operator!(color c) noexcept
{
return static_cast
}
template<color N>
using color_ = std::integral_constant<color, N>;
using black_ = color_
using white_ = color_
template<class T>
using not_ = color_
template<class T>
inline constexpr auto is_color = xstd::any_of<T, color, black_, white_>;
template<color N>
inline constexpr auto color_c = color_
inline constexpr auto black_c = color_c
inline constexpr auto white_c = color_c
template<color N>
constexpr auto operator!(color_ noexcept
{
return color_c
}
} // namespace dctl::core
|
c++
| 11 | 0.655932 | 72 | 21.692308 | 52 |
starcoderdata
|
<?php
if($kdkop==1){
$hasil=$result->query_x1("SELECT norek FROM $tabelTagihan WHERE norek='$norekl' AND kdtran=111 LIMIT 1");
if($result->num($hasil)>0)$result->msg_error('Tagihan Reguler Bulan Ini Belum Realisasi..!!');
$hasil=$result->query_x1("SELECT norek FROM $tabelSusulan WHERE norek='$norekl' AND kdtran=111 LIMIT 1");
if($result->num($hasil)>0)$result->msg_error('Tagihan Reguler Bulan Ini Belum Realisasi..!!');
}else{
$hasil=$result->query_x1("SELECT norek FROM $tabelMicro WHERE norek='$norekl' AND kdtran=111 LIMIT 1");
if($result->num($hasil)>0) $result->msg_error('Tagihan Micro Bulan Ini Belum Realisasi..!!');
}
?>
|
php
| 11 | 0.701997 | 106 | 53.333333 | 12 |
starcoderdata
|
# include "biaseq.h"
/* MAKEBIAS -- Make bias image.
**
**
**
** Revision history:
** ----------------
** 14-Apr-1999 Implementation.
** 08-May-200 Complete rewrite, splitting fitjumps
** and subbias off to separate routines.
**
*/
int makeBias (SingleNicmosGroup *bias, SingleNicmosGroup *sky) {
/* Arguments:
** bias io: bias image
** sky i: sky image
*/
/* Local variables */
int i, j; /* loop indexes */
float skytime; /* sky image exposure time */
float deltatime; /* first difference image exp time */
float ratio; /* exposure time ratio */
/* Get the sky image exposure time */
if (getKeyF (sky->globalhdr, "EXPTIME", &skytime))
return (1);
/* Get the first difference image exposure time */
if (getKeyF (&(bias->sci.hdr), "DELTATIM", &deltatime)) {
n_error ("Error reading DELTATIM keyword.");
return (1);
}
ratio = deltatime / skytime;
/* Subtract the scaled sky from the bias image */
for (j=0; j < sky->sci.data.ny; j++) {
for (i=0; i < sky->sci.data.nx; i++) {
Pix(bias->sci.data,i,j) -= Pix(sky->sci.data,i,j)*ratio;
DQSetPix(bias->dq.data,i,j,
DQPix(bias->dq.data,i,j) | DQPix(sky->dq.data,i,j) );
}
}
return (0);
}
|
c
| 15 | 0.599194 | 64 | 22.396226 | 53 |
starcoderdata
|
//
//
#ifndef PRODUCERCONSUMER_GENERAL_H
#define PRODUCERCONSUMER_GENERAL_H
// user defined
#include "shared_data.hpp"
// standard
#include
#include
#include
#include
#include
#include
namespace antel
{
class thread_manager;
};
namespace antel
{
class thread_manager
{
public:
typedef std::shared_ptr ptr;
private:
/// @brief deploy thread
virtual void deploy() = 0;
public:
/// @brief run thread
/// @note call deploy function, use as PVF idom
void run();
// @brief join current thread
void stop();
public:
/// @brief user interaction handler,
/// i.e callable function from signal
static void signal_handler(int);
private:
/// @brief stop producers thread
/// and waint until producer stops
static void make_sanity_cleaning();
/// @brief consumers thread waiting
static void clean_consumers();
private:
std::thread m_thread;
protected:
static shared_data m_shared_container;
static std::condition_variable m_producers;
static std::condition_variable m_consumers;
protected:
static std::atomic m_producers_should_work;
static std::atomic m_consumers_should_work;
private:
static std::mutex m_cleaning_mutex;
protected:
static std::condition_variable m_clean_consumers;
};
}; // end namespace antel
#endif //PRODUCERCONSUMER_GENERAL_H
|
c++
| 11 | 0.608314 | 57 | 20.786667 | 75 |
starcoderdata
|
package mhfc.net.common.entity.projectile;
import java.util.List;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityThrowable;
import net.minecraft.init.Blocks;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.DamageSource;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class EntityRathalosFireball extends EntityThrowable {
public EntityLivingBase shootingEntity;
public int radius = 1;
public EntityRathalosFireball(World par1World) {
super(par1World);
}
@SideOnly(Side.CLIENT)
public EntityRathalosFireball(
World par1World,
double par2,
double par4,
double par6,
double par8,
double par10,
double par12) {
super(par1World, par2, par4, par6);
}
public EntityRathalosFireball(World par1World, EntityLivingBase par2EntityLivingBase) {
super(par1World, par2EntityLivingBase);
shootingEntity = par2EntityLivingBase;
}
@Override
protected void onImpact(RayTraceResult result) {
if(!this.world.isRemote) {
List list = this.world
.getEntitiesWithinAABBExcludingEntity(this, this.getEntityBoundingBox().expand(4.5D, 3.0D, 4.5D));
list.remove(getThrower());
for (Entity entity : list) {
if (entity instanceof EntityPlayer) {
entity.attackEntityFrom(DamageSource.causeMobDamage(getThrower()), 4 + this.rand.nextInt(14));
} else {
entity.attackEntityFrom(DamageSource.causeMobDamage(getThrower()), 29 + this.rand.nextInt(121));
}
if (world.isRemote || result.entityHit == null) {
continue;
}
boolean flag1 = true;
if(this.shootingEntity != null && this.shootingEntity instanceof EntityLiving) {
flag1 = this.world.getGameRules().getBoolean("mobGriefing");
}
if(flag1) {
BlockPos blockpos = result.getBlockPos().offset(result.sideHit);
if (this.world.isAirBlock(blockpos))
{
this.world.setBlockState(blockpos, Blocks.FIRE.getDefaultState());
}
}
}
}
}
@Override
protected float getGravityVelocity() {
return 0;
}
@Override
public void writeEntityToNBT(NBTTagCompound tagcompound) {
super.writeEntityToNBT(tagcompound);
}
@Override
public void readEntityFromNBT(NBTTagCompound tagcompound) {
super.readEntityFromNBT(tagcompound);
}
}
|
java
| 18 | 0.715185 | 102 | 27.032258 | 93 |
starcoderdata
|
package com.ociweb.protocoltest.data;
import java.io.IOException;
import com.ociweb.pronghorn.util.Appendables;
public class SequenceExampleASample {
int id;
long time;
int measurement;
int action;
public static void setAll(SequenceExampleASample that,int id, long time, int measurement, int action) {
that.id = id;
that.time = time;
that.measurement = measurement;
that.action = action;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof SequenceExampleASample) {
SequenceExampleASample that = (SequenceExampleASample)obj;
return this.id == that.id &&
this.time == that.time &&
this.measurement == that.measurement &&
this.action == that.action;
}
return false;
}
public <A extends Appendable> A appendToString(A target) throws IOException {
Appendables.appendValue(target,"Id:" ,id,"\n");
Appendables.appendValue(target,"Time:" ,time,"\n");
Appendables.appendValue(target,"Measurment:" ,measurement,"\n");
Appendables.appendValue(target,"Action:" ,action,"\n");
return target;
}
public static int estimatedBytes() {
return (4*3)+8;
}
public String toString() {
try {
return appendToString(new StringBuilder()).toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public int getMeasurement() {
return measurement;
}
public void setMeasurement(int measurement) {
this.measurement = measurement;
}
public int getAction() {
return action;
}
public void setAction(int action) {
this.action = action;
}
}
|
java
| 13 | 0.568655 | 107 | 23.55814 | 86 |
starcoderdata
|
# class methods are always decorated with @classmethod
# Static methods can optionally be decorated with @staticmethod
class StaticExample:
@staticmethod
def sum(x,y): #Static method as no ref passed of instance
print(x+y)
@classmethod #If class method annotation is not applied it will be considered as instance method and first parameter will be considered as self ref
def mul(cls,x,y): #class method as ref of cls is passed
print(x*y)
StaticExample.sum(1,2) #called static way prints 3
s = StaticExample()
s.sum(1,2) #It gives error if decorator annotation is not applied as
#it consider sum as instance method instead of static
s1 = StaticExample()
s1.mul(2,3)
|
python
| 10 | 0.703654 | 153 | 34.190476 | 21 |
starcoderdata
|
using NWrath.Synergy.Common.Extensions;
using System;
using System.IO;
using System.Text;
namespace NWrath.Logging
{
public class StreamLogger
: LoggerBase
{
public Stream Writer { get => _writer; set { _writer = value ?? throw Errors.NULL_STREAM; } }
public IStringLogSerializer Serializer { get => _serializer; set { _serializer = value ?? new StringLogSerializer(); } }
public Encoding Encoding { get => _encoding; set { _encoding = value ?? new UTF8Encoding(false); } }
private bool AutoFlush { get; set; } = false;
private Stream _writer;
private Encoding _encoding = new UTF8Encoding(false);
private IStringLogSerializer _serializer = new StringLogSerializer();
private bool _leaveOpen;
public StreamLogger(
Stream writer,
bool autoFlush = false,
bool leaveOpen = false
)
{
Writer = writer;
AutoFlush = autoFlush;
_leaveOpen = leaveOpen;
}
~StreamLogger()
{
Dispose();
}
public override void Dispose()
{
if (AutoFlush && Writer.CanWrite)
{
Writer.Flush();
}
if (!_leaveOpen)
{
Writer.Close();
Writer.Dispose();
}
}
protected override void WriteRecord(LogRecord record)
{
var msg = Serializer.Serialize(record) + Environment.NewLine;
var data = Encoding.GetBytes(msg);
Writer.Write(data, 0, data.Length);
if (AutoFlush && Writer.CanWrite)
{
Writer.Flush();
}
}
}
}
|
c#
| 16 | 0.527715 | 128 | 25.014706 | 68 |
starcoderdata
|
<?php declare(strict_types=1);
namespace App\Event;
use App\TestHelpers\UserHelpers;
use PHPUnit\Framework\TestCase;
class UserUpdatedEventTest extends TestCase
{
/** @test */
public function event_is_initialised_correctly()
{
$preUpdateUser = UserHelpers::createUser();
$postUpdateUser = UserHelpers::createUser();
$currentUser = UserHelpers::createUser();
$trigger = 'A_TRIGGER';
$event = new UserUpdatedEvent($preUpdateUser, $postUpdateUser, $currentUser, $trigger);
self::assertEquals($currentUser->getEmail(), $event->getCurrentUserEmail());
self::assertEquals($postUpdateUser->getEmail(), $event->getPostUpdateEmail());
self::assertEquals($postUpdateUser->getFullName(), $event->getPostUpdateFullName());
self::assertEquals($postUpdateUser->getRoleName(), $event->getPostUpdateRoleName());
self::assertEquals($preUpdateUser->getEmail(), $event->getPreUpdateEmail());
self::assertEquals($preUpdateUser->getRoleName(), $event->getPreUpdateRoleName());
self::assertEquals($trigger, $event->getTrigger());
}
}
|
php
| 11 | 0.690877 | 95 | 39.321429 | 28 |
starcoderdata
|
/* eslint-disable */
const webpack = require('webpack');
const merge = require('webpack-merge');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const HtmlWebpackPlugin = require('html-webpack-plugin');
const cleanWebpackPlugin = require('clean-webpack-plugin');
const webpackBaseConfig = require('./webpack.base.config.js');
const path = require('path');
module.exports = merge(webpackBaseConfig, {
output: {
publicPath: '/public/assets/',
filename: (chunkData) => {
return chunkData.chunk.name === 'builtIn' ? '[name].min.js': '[name].[chunkhash:8].js';
},
chunkFilename: '[name].[chunkhash:8].js'
},
plugins: [
new cleanWebpackPlugin(['dist/*'], {
root: path.resolve(__dirname, '../')
}),
new webpack.HashedModuleIdsPlugin(),
new HtmlWebpackPlugin({
filename: './index.html',
template: './src/templates/index.html',
chunks: ['vendor', 'main']
})
// new BundleAnalyzerPlugin()
]
});
|
javascript
| 14 | 0.617174 | 99 | 35.096774 | 31 |
starcoderdata
|
package view
import (
"fmt"
"fyne.io/fyne"
"fyne.io/fyne/canvas"
"fyne.io/fyne/layout"
"github.com/huobirdcenter/huobi_golang/cmd/marketclientexample"
"image/color"
"time"
)
type UIRoot struct {
canvasObject fyne.CanvasObject
}
func NewUIRoot() *UIRoot {
root := &UIRoot{}
root.makeContent()
return root
}
func (u *UIRoot) GetContent() fyne.CanvasObject {
return u.canvasObject
}
func (u *UIRoot) makeContent() {
makeCell := func() fyne.CanvasObject {
rect := canvas.NewRectangle(color.Black)
rect.SetMinSize(fyne.NewSize(100, 100))
text := canvas.NewText("222", color.White)
textTime := canvas.NewText("333", color.White)
go func() {
for {
text.Text = fmt.Sprintf("%f", marketclientexample.GetCandlestick("umausdt"))
text.Refresh()
textTime.Text = "2222" //time.Now().String() //fmt.Sprintf("%f", marketclientexample.GetCandlestick("forusdt"))
textTime.Refresh()
time.Sleep(time.Millisecond * 3)
}
}()
con := fyne.NewContainerWithLayout(layout.NewVBoxLayout(), canvas.NewText("1111", color.NRGBA{0xff, 0x00, 0x00, 0xff}), text, textTime)
cell := fyne.NewContainerWithLayout(layout.NewCenterLayout(), rect, con)
cell.Resize(fyne.NewSize(50, 50))
return cell
}
u.canvasObject = fyne.NewContainerWithLayout(layout.NewGridLayout(1), makeCell())
}
|
go
| 20 | 0.702128 | 137 | 23.37037 | 54 |
starcoderdata
|
package request
import (
"kuiz/business/quizzes"
)
type CreateQuiz struct {
AuthorID uint
TitleQuiz string `json:"title"`
GivenTime uint `json:"given_time"`
}
func (quiz *CreateQuiz) ToDomain() *quizzes.Domain {
return &quizzes.Domain{
AuthorId: quiz.AuthorID,
TitleQuiz: quiz.TitleQuiz,
GivenTime: quiz.GivenTime,
}
}
|
go
| 11 | 0.725806 | 52 | 17.6 | 20 |
starcoderdata
|
//************************************ bs::framework - Copyright 2018 **************************************//
//*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********//
#pragma once
#include "BsCorePrerequisites.h"
#include "Utility/BsModule.h"
#include "Profiling/BsProfilerCPU.h"
namespace bs
{
/** @addtogroup Profiling-Internal
* @{
*/
/** Contains data about a profiling session. */
struct ProfilerReport
{
CPUProfilerReport cpuReport;
};
/** Type of thread used by the profiler. */
enum class ProfiledThread
{
Sim,
Core
};
/**
* Tracks CPU profiling information with each frame for sim and core threads.
*
* @note Sim thread only unless specified otherwise.
*/
class BS_CORE_EXPORT ProfilingManager : public Module
{
public:
ProfilingManager();
~ProfilingManager();
/** Called every frame. */
void _update();
/**
* Called every frame from the core thread.
*
* @note Core thread only.
*/
void _updateCore();
/**
* Returns a profiler report for the specified frame, for the specified thread.
*
* @param[in] thread Thread for which to retrieve the profiler report.
* @param[in] idx Profiler report index, ranging [0, NUM_SAVED_FRAMES]. 0 always returns the latest report.
* Increasing indexes return reports for older and older frames. Out of range indexes will be
* clamped.
*
* @note
* Profiler reports get updated every frame. Oldest reports that no longer fit in the saved reports buffer are
* discarded.
*/
const ProfilerReport& getReport(ProfiledThread thread, UINT32 idx = 0) const;
private:
static const UINT32 NUM_SAVED_FRAMES;
ProfilerReport* mSavedSimReports;
UINT32 mNextSimReportIdx;
ProfilerReport* mSavedCoreReports;
UINT32 mNextCoreReportIdx;
mutable Mutex mSync;
};
/** Easy way to access ProfilingManager. */
BS_CORE_EXPORT ProfilingManager& gProfiler();
/** @} */
}
|
c
| 12 | 0.662248 | 124 | 24.797468 | 79 |
starcoderdata
|
public boolean crossSeam(ProjectionPoint pt1, ProjectionPoint pt2) {
// either point is infinite
if (ProjectionPointImpl.isInfinite(pt1)
|| ProjectionPointImpl.isInfinite(pt2)) {
return true;
}
return false;
}
|
java
| 8 | 0.605839 | 68 | 29.555556 | 9 |
inline
|
package com.thinksky.kafka.twitter.stream.connect;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GetVersion {
static final Logger log = LoggerFactory.getLogger(TwitterSourceTask.class);
public static String generate(Class clazz) {
String result;
try {
result = GetVersion.class.getPackage().getImplementationVersion();
if (Strings.isNullOrEmpty(result)) {
result = "0.0.0";
}
} catch (Exception ex) {
log.error("Exception thrown while getting error", ex);
result = "0.0.0";
}
return result;
}
}
|
java
| 10 | 0.633784 | 79 | 27.461538 | 26 |
starcoderdata
|
using System.Collections.Generic;
using System.Threading;
using Centigrade.VedaVersum.Model;
using HotChocolate.Types;
using VedaVersum.Backend.DataAccess;
namespace VedaVersum.Backend.Api
{
public class VedaVersumCardObjectType: ObjectType
{
protected override void Configure(IObjectTypeDescriptor descriptor)
{
descriptor
.Field("relatedCards") // Name of the additional field
.Type
.Resolve(async context =>
{
var parent = context.Parent
if(parent.RelatedCardIds == null || parent.RelatedCardIds.Count == 0)
{
return new List
}
var dataAccess = context.Service
return await dataAccess.GetCardsById(parent.RelatedCardIds);
});
}
}
}
|
c#
| 21 | 0.621106 | 91 | 32.2 | 30 |
starcoderdata
|
#include<vector>
std::vector<std::pair<long long, int>> get_prime_factors(long long n) {
std::vector<std::pair<long long, int>> ret;
for (long long i = 2; i * i <= n; i++) {
if (n % i == 0) {
ret.push_back({i, 1});
n /= i;
}
while (n % i == 0) {
ret.back().second++;
n /= i;
}
}
if (n != 1) { ret.push_back({n, 1}); }
return ret;
}
#include<bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
cout << n << ":";
auto v = get_prime_factors(n);
for (int i = 0; i < v.size(); i++) {
auto p = v[i];
for (int j = 0; j < p.second; j++) { cout << " " << p.first; }
}
cout << endl;
}
|
c++
| 13 | 0.422554 | 71 | 22 | 32 |
codenet
|
using PVScan.Mobile.Android.Effects;
using System;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ResolutionGroupName("PVScan")]
[assembly: ExportEffect(typeof(NoEntryVerticalPaddingEffect), nameof(NoEntryVerticalPaddingEffect))]
namespace PVScan.Mobile.Android.Effects
{
public class NoEntryVerticalPaddingEffect : PlatformEffect
{
protected override void OnAttached()
{
Control.SetPadding(Control.PaddingLeft, 0, Control.PaddingRight, 0);
}
protected override void OnDetached()
{
throw new NotImplementedException();
}
}
}
|
c#
| 12 | 0.708202 | 100 | 27.863636 | 22 |
starcoderdata
|
<?php
/**
* field tos
*
* @package VirtueMart
* @subpackage Cart
* @author
* @link http://www.virtuemart.net
* @copyright Copyright (c) 2014 VirtueMart Team. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL2, see LICENSE.php
* @version $Id: cart.php 7682 2014-02-26 17:07:20Z Milbo $
*/
defined('_JEXEC') or die('Restricted access');
$_prefix = $viewData['prefix'];
$field = $viewData['field'];
$tos = $field['value'];
$app = JFactory::getApplication();
if($app->isSite()){
vmJsApi::popup('#full-tos','#terms-of-service');
if (!class_exists('VirtueMartCart')) require(VMPATH_SITE . DS . 'helpers' . DS . 'cart.php');
$cart = VirtuemartCart::getCart();
$cart->prepareVendor();
if(empty($tos) and !VmConfig::get ('agree_to_tos_onorder', true)){
if(is_array($cart->BT) and !empty($cart->BT['tos'])){
$tos = $cart->BT['tos'];
}
}
}
if(!class_exists('VmHtml')) require(VMPATH_ADMIN.DS.'helpers'.DS.'html.php');
echo VmHtml::checkbox ($_prefix.$field['name'], $tos, 1, 0, 'class="terms-of-service required"', 'tos');
if (VmConfig::get ('oncheckout_show_legal_info', 1) and $app->isSite()) {
?>
<div class="terms-of-service">
<label for="tos">
<a href="<?php echo JRoute::_ ('index.php?option=com_virtuemart&view=vendor&layout=tos&virtuemart_vendor_id=1', FALSE) ?>" class="terms-of-service" id="terms-of-service" target="_blank">
<span class="vmicon vm2-termsofservice-icon">
<?php echo vmText::_ ('COM_VIRTUEMART_CART_TOS_READ_AND_ACCEPTED') ?>
<div id="full-tos">
echo vmText::_ ('COM_VIRTUEMART_CART_TOS') ?>
<?php echo $cart->vendor->vendor_terms_of_service ?>
<?php
}
?>
|
php
| 15 | 0.647603 | 188 | 29.928571 | 56 |
starcoderdata
|
func TestPubSub__Publish(t *testing.T) {
ps := NewPubSub()
out1, err := ps.Subscribe("1")
if err != nil {
t.Errorf("could not subscribe")
}
out2, err := ps.Subscribe("2")
if err != nil {
t.Errorf("could not subscribe")
}
df := &MockFrame{}
ps.publish(df)
if one := <-out1; one != df {
t.Errorf("failed to publish")
}
if two := <-out2; two != df {
t.Errorf("failed to publish")
}
// now unsubscribe from one
ps.Unsubscribe("2")
ps.publish(df)
if one := <-out1; one != df {
t.Errorf("failed to publish")
}
if _, ok := <-out2; ok {
t.Errorf("failed to close channel")
}
}
|
go
| 9 | 0.586491 | 40 | 16.371429 | 35 |
inline
|
virtual bool equals(const chunk& other) const {
if (other.tp() != tp()) {
return false;
}
if (tp() == CHUNK_TYPE_WORD_ADDRESS) {
return equals_word_address(other);
} else if (tp() == CHUNK_TYPE_COMMENT) {
return equals_comment(other);
} else if (tp() == CHUNK_TYPE_PERCENT) {
// Any 2 percent chunks are always equal
return true;
} else {
assert(false);
}
}
|
c
| 13 | 0.581509 | 47 | 23.235294 | 17 |
inline
|
void encode_null_block(FILE *outfile, int *a, int nx, int ny)
{
long size_enc;
writeint(outfile, 0);
int Bef = ftell(outfile);
writeint(outfile, 1); /* size of image */
writeint(outfile, 1);
writefloat(outfile, 0.);
writefloat(outfile, *a); /* scale factor for digitization */
// writeint(outfile, ny);
// writeint(outfile, nx);
int Aft = ftell(outfile);
size_enc = Aft - Bef;
long Val = -size_enc-4;
int nf = fseek(outfile, Val, SEEK_CUR);
writeint(outfile, size_enc);
nf = fseek(outfile, size_enc,SEEK_CUR);
}
|
c++
| 7 | 0.617958 | 63 | 27.45 | 20 |
inline
|
using System.Net;
using NUnit.Framework;
namespace RequestsNET.Tests
{
public class ErrorsTests
{
[Test]
public void NoResponse()
{
Assert.ThrowsAsync => Requests.Post("http://localhost:9999/status/404").ToJsonAsync
Assert.ThrowsAsync => Requests.Post("http://localhost:9999/status/404").ToJsonAsync());
var e = Assert.ThrowsAsync => Requests.Post("http://localhost:9999/status/503").ToJsonAsync());
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, e.Response.StatusCode);
Assert.ThrowsAsync
() => Requests.Get("http://localhost:9999/bytes/0")
.ToJsonAsync());
Assert.ThrowsAsync
() => Requests.Get("http://localhost:9999/bytes/0")
.ToJsonAsync
}
}
}
|
c#
| 21 | 0.651386 | 128 | 35.115385 | 26 |
starcoderdata
|
package org.ihtsdo.otf.transformationandtemplate.service.client;
import org.ihtsdo.otf.rest.client.terminologyserver.pojo.DescriptionPojo;
import org.ihtsdo.otf.rest.client.terminologyserver.pojo.SnomedComponent;
public class DescriptionReplacementPojo implements SnomedComponent {
private DescriptionPojo inactivatedDescription;
private DescriptionPojo createdDescription;
private DescriptionPojo updatedDescription;
public String getId() {
return inactivatedDescription != null ? inactivatedDescription.getDescriptionId() : null;
}
public String getConceptId() {
return inactivatedDescription != null ? inactivatedDescription.getConceptId() : null;
}
public DescriptionPojo getInactivatedDescription() {
return inactivatedDescription;
}
public void setInactivatedDescription(DescriptionPojo inactivatedDescription) {
this.inactivatedDescription = inactivatedDescription;
}
public DescriptionPojo getCreatedDescription() {
return createdDescription;
}
public void setCreatedDescription(DescriptionPojo createdDescription) {
this.createdDescription = createdDescription;
}
public DescriptionPojo getUpdatedDescription() {
return updatedDescription;
}
public void setUpdatedDescription(DescriptionPojo updatedDescription) {
this.updatedDescription = updatedDescription;
}
@Override
public String toString() {
return "DescriptionReplacementPojo{" +
"descriptionId='" + (getInactivatedDescription() != null ? getInactivatedDescription().getDescriptionId() : "") + '\'' +
", replacementDescriptionId=" + (getUpdatedDescription() != null ? getUpdatedDescription().getDescriptionId() : "") +
", newReplacementTerm='" + (getCreatedDescription() != null ? getCreatedDescription().getDescriptionId() : "") + '\'' +
'}';
}
}
|
java
| 19 | 0.716334 | 136 | 35.166667 | 54 |
starcoderdata
|
import wandapi.resources.v1.wands
# imported and itemized under __all__ here for endpoint versioning in api.py router setup
__all__ = (
'wands'
)
|
python
| 5 | 0.703947 | 89 | 20.714286 | 7 |
starcoderdata
|
/*
* Copyright 2015-present Open Networking Foundation
*
* 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.onlab.util;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static junit.framework.TestCase.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Unit tests for the sliding window counter.
*/
public class SlidingWindowCounterTest {
private SlidingWindowCounter counter;
@Before
public void setUp() {
counter = new SlidingWindowCounter(2);
}
@After
public void tearDown() {
counter.destroy();
}
@Test
public void testIncrementCount() {
assertEquals(0, counter.get(1));
assertEquals(0, counter.get(2));
counter.incrementCount();
assertEquals(1, counter.get(1));
assertEquals(1, counter.get(2));
counter.incrementCount(2);
assertEquals(3, counter.get(2));
}
@Test
public void testSlide() {
counter.incrementCount();
counter.advanceHead();
assertEquals(0, counter.get(1));
assertEquals(1, counter.get(2));
counter.incrementCount(2);
assertEquals(2, counter.get(1));
assertEquals(3, counter.get(2));
}
@Test
public void testWrap() {
counter.incrementCount();
counter.advanceHead();
counter.incrementCount(2);
counter.advanceHead();
assertEquals(0, counter.get(1));
assertEquals(2, counter.get(2));
counter.advanceHead();
assertEquals(0, counter.get(1));
assertEquals(0, counter.get(2));
}
@Test
public void testSlidingWindowStats() {
SlidingWindowCounter counter = new SlidingWindowCounter(3);
// 1
counter.incrementCount(1);
assertEquals(1, counter.getWindowCount());
assertEquals(1, counter.getWindowCount(1));
// 0, 1
counter.advanceHead();
assertEquals(1, counter.getWindowCount());
assertEquals(0, counter.getWindowCount(1));
assertEquals(1, counter.getWindowCount(2));
// 2, 1
counter.incrementCount(2);
assertEquals(3, counter.getWindowCount());
assertEquals(2, counter.getWindowCount(1));
assertEquals(3, counter.getWindowCount(2));
// 0, 2, 1
counter.advanceHead();
assertEquals(3, counter.getWindowCount());
assertEquals(0, counter.getWindowCount(1));
assertEquals(2, counter.getWindowCount(2));
assertEquals(3, counter.getWindowCount(3));
// 3, 2, 1
counter.incrementCount(3);
assertEquals(6, counter.getWindowCount());
assertEquals(3, counter.getWindowCount(1));
assertEquals(5, counter.getWindowCount(2));
assertEquals(6, counter.getWindowCount(3));
// 0, 3, 2
counter.advanceHead();
assertEquals(5, counter.getWindowCount());
assertEquals(0, counter.getWindowCount(1));
assertEquals(3, counter.getWindowCount(2));
assertEquals(5, counter.getWindowCount(3));
// 4, 3, 2
counter.incrementCount(4);
assertEquals(9, counter.getWindowCount());
assertEquals(4, counter.getWindowCount(1));
assertEquals(7, counter.getWindowCount(2));
assertEquals(9, counter.getWindowCount(3));
// 0, 4, 3
counter.advanceHead();
assertEquals(7, counter.getWindowCount());
assertEquals(0, counter.getWindowCount(1));
assertEquals(4, counter.getWindowCount(2));
assertEquals(7, counter.getWindowCount(3));
// 5, 4, 3
counter.incrementCount(5);
assertEquals(12, counter.getWindowCount());
assertEquals(5, counter.getWindowCount(1));
assertEquals(9, counter.getWindowCount(2));
assertEquals(12, counter.getWindowCount(3));
// 0, 5, 4
counter.advanceHead();
assertEquals(9, counter.getWindowCount());
assertEquals(0, counter.getWindowCount(1));
assertEquals(5, counter.getWindowCount(2));
assertEquals(9, counter.getWindowCount(3));
counter.destroy();
}
@Test
public void testRates() {
assertEquals(0, counter.getWindowRate(), 0.01);
assertEquals(0, counter.getOverallRate(), 0.01);
assertEquals(0, counter.getOverallCount());
counter.incrementCount();
assertEquals(1, counter.getWindowRate(), 0.01);
assertEquals(1, counter.getOverallRate(), 0.01);
assertEquals(1, counter.getOverallCount());
counter.advanceHead();
counter.incrementCount();
counter.incrementCount();
assertEquals(1.5, counter.getWindowRate(), 0.01);
assertEquals(2, counter.getWindowRate(1), 0.01);
assertEquals(1.5, counter.getOverallRate(), 0.01);
assertEquals(3, counter.getOverallCount());
counter.advanceHead();
counter.incrementCount();
counter.incrementCount();
counter.incrementCount();
assertEquals(2.5, counter.getWindowRate(), 0.01);
assertEquals(2, counter.getOverallRate(), 0.01);
assertEquals(6, counter.getOverallCount());
}
@Test
public void testCornerCases() {
try {
counter.get(3);
fail("Exception should have been thrown");
} catch (IllegalArgumentException e) {
assertTrue(true);
}
try {
new SlidingWindowCounter(0);
fail("Exception should have been thrown");
} catch (IllegalArgumentException e) {
assertTrue(true);
}
try {
new SlidingWindowCounter(-1);
fail("Exception should have been thrown");
} catch (IllegalArgumentException e) {
assertTrue(true);
}
}
}
|
java
| 11 | 0.627304 | 75 | 30.850746 | 201 |
starcoderdata
|
package main
import "testing"
func TestURLExists(t *testing.T) {
urlTestTable := []struct {
in string
out bool
}{
{"https://google.com/", true},
{"https://doesnotexist.example.com/", false},
}
for _, tt := range urlTestTable {
exists := urlExists(tt.in)
if exists != tt.out {
t.Errorf("urlExists(%v) => %v, want %v", tt.in, exists, tt.out)
}
}
}
|
go
| 11 | 0.617128 | 66 | 17.904762 | 21 |
starcoderdata
|
import { memo, useState } from 'react'
import cn from 'classnames'
import Link from '@/components/link'
import styles from './text.module.css'
const categories = {
'computer science': '🎓',
language: '🔭',
tools: '🍭'
}
const request = ['🙋🏻', '🙋🏼', '🙋🏽', '🙋🏾', '🙋🏿']
const TextEntry = ({ title, type, comment, href, category, as }) => {
const [diceRoll] = useState(Math.random())
const emoji = category
? categories[category]
: request[Math.round(diceRoll * (request.length - 1))]
return (
<li className={cn(styles.item, !category && styles.request)}>
<Link
href={href}
as={as}
external={!as}
title={`${title}`}
className={styles.link}
>
{emoji && (
<span
role="img"
aria-label={category}
title={category}
className={styles.category}
>
{emoji}
)}
<span className={cn(styles.title, 'clamp', !category && styles.new)}>
{title}
)
}
export default memo(TextEntry)
|
javascript
| 17 | 0.523381 | 77 | 22.659574 | 47 |
starcoderdata
|
package baseutils
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestJoinBytes(t *testing.T) {
a := "Tom"
b := "Jerry"
c := "Puppy"
sep := []byte("")
expected := []byte(a + b + c)
actual := JoinBytes(sep, []byte(a), []byte(b), []byte(c))
assert.Equal(t, expected, actual)
sepStr := ";"
expected = []byte(a + sepStr + b + sepStr + c)
sep = []byte(sepStr)
actual = JoinBytes(sep, []byte(a), []byte(b), []byte(c))
assert.Equal(t, expected, actual)
}
|
go
| 10 | 0.606719 | 58 | 20.083333 | 24 |
starcoderdata
|
package jetbrains.mps.vcs.changesmanager.tree;
/*Generated by MPS */
import jetbrains.mps.annotations.GeneratedClass;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.project.Project;
import jetbrains.mps.vcs.changesmanager.CurrentDifferenceRegistry;
import org.jetbrains.annotations.NotNull;
import java.util.stream.Stream;
import jetbrains.mps.vcs.changesmanager.tree.features.Feature;
import jetbrains.mps.vcs.diff.changes.ModelChange;
import org.jetbrains.mps.openapi.model.SModelReference;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SModelOperations;
import jetbrains.mps.vcs.diff.changes.AddRootChange;
import jetbrains.mps.smodel.SNodePointer;
import jetbrains.mps.vcs.changesmanager.tree.features.NodeFeature;
import jetbrains.mps.vcs.diff.changes.DeleteRootChange;
import jetbrains.mps.vcs.changesmanager.tree.features.ModelFeature;
import jetbrains.mps.vcs.diff.changes.SetPropertyChange;
import jetbrains.mps.vcs.changesmanager.tree.features.PropertyFeature;
import jetbrains.mps.vcs.diff.changes.SetReferenceChange;
import jetbrains.mps.vcs.changesmanager.tree.features.ReferenceFeature;
import jetbrains.mps.vcs.diff.changes.NodeGroupChange;
import org.jetbrains.mps.openapi.model.SNodeId;
import jetbrains.mps.vcs.changesmanager.tree.features.DeletedChildFeature;
import java.util.List;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.vcs.diff.changes.SetConceptChange;
import jetbrains.mps.vcs.diff.changes.ModelAttributeChange;
import jetbrains.mps.vcs.diff.changes.UsedLanguageChange;
import jetbrains.mps.vcs.diff.changes.ImportedModelChange;
import jetbrains.mps.vcs.diff.changes.EngagedLanguageChange;
import jetbrains.mps.vcs.changesmanager.CurrentDifferenceAdapter;
import java.util.HashSet;
import java.util.Set;
import java.util.Collections;
import java.util.stream.Collectors;
@GeneratedClass(node = "r:0fdcfe58-6a3e-4b7d-bea2-685e5d104fd0(jetbrains.mps.vcs.changesmanager.tree)/3751911615136892572", model = "r:0fdcfe58-6a3e-4b7d-bea2-685e5d104fd0(jetbrains.mps.vcs.changesmanager.tree)")
public class FeatureForestMapSupport implements Disposable {
private final Project myProject;
private final FeaturesFromVcs myMap;
private final CurrentDifferenceRegistry myCurrentDifferenceRegistry;
private final FeatureHierarchyListener myListener;
public FeatureForestMapSupport(Project project) {
myProject = project;
myCurrentDifferenceRegistry = CurrentDifferenceRegistry.getInstance(project);
myMap = new FeaturesFromVcs();
myListener = new FeatureHierarchyListener(myMap);
// FIXME why project component listens to global differences?
myCurrentDifferenceRegistry.addGlobalDifferenceListener(myListener);
}
public static FeatureForestMapSupport getInstance(Project ideaProject) {
// XXX FFMS used to be project component, that attached GlobalDifferenceListener on project start
// I wonder if present approach with services doesn't break any assumption. If this service get initialized
// much later than project starts, does it miss any changes CurrentDifferentRegistry has already dispatched to its listeners?
// Indeed, there's little value instantiating FFMS if nobody would query it, therefore being a service sounds right,
// OTOH, expectations (whether FFMS provides 'complete' project state) could be ruined, didn't check that.
return ideaProject.getService(FeatureForestMapSupport.class);
}
@Override
public void dispose() {
myCurrentDifferenceRegistry.removeGlobalDifferenceListener(myListener);
}
@NotNull
public FeaturesFromVcs getMap() {
return myMap;
}
/**
* Features from vcs changes
*/
private static Stream getFeaturesForChange(@NotNull ModelChange change) {
Stream.Builder builder = Stream.builder();
SModelReference modelReference = SModelOperations.getPointer(change.getChangeSet().getNewModel());
if (change instanceof AddRootChange) {
SNodePointer nodePointer = new SNodePointer(modelReference, change.getRootId());
builder.accept(new NodeFeature(nodePointer, change.getRootId()));
} else
if (change instanceof DeleteRootChange) {
builder.accept(new ModelFeature(modelReference));
} else
if (change instanceof SetPropertyChange) {
SetPropertyChange spc = ((SetPropertyChange) change);
SNodePointer nodePointer = new SNodePointer(modelReference, spc.getAffectedNodeId());
builder.accept(new PropertyFeature(nodePointer, spc.getProperty(), spc.getRootId()));
} else
if (change instanceof SetReferenceChange) {
SetReferenceChange src = ((SetReferenceChange) change);
SNodePointer nodePointer = new SNodePointer(modelReference, src.getAffectedNodeId());
builder.accept(new ReferenceFeature(nodePointer, src.getRoleLink(), src.getRootId()));
} else
if (change instanceof NodeGroupChange) {
NodeGroupChange ngc = ((NodeGroupChange) change);
SNodeId parentId = ngc.getNewParentNodeId();
int begin = ngc.getResultBegin();
int end = ngc.getResultEnd();
if (begin == end) {
SNodePointer nodePointer = new SNodePointer(modelReference, parentId);
builder.accept(new DeletedChildFeature(nodePointer, ngc.getRoleLink().getName(), begin, change.getRootId()));
} else {
List changeChildren = ngc.getChangedCollection(true);
for (int i = begin; i < end; i++) {
if (i < changeChildren.size()) {
SNodePointer nodePointer = new SNodePointer(modelReference, changeChildren.get(i).getNodeId());
builder.accept(new NodeFeature(nodePointer, ngc.getRootId()));
}
}
}
} else
if (change instanceof SetConceptChange) {
// todo: create new feature ??
builder.accept(new NodeFeature(new SNodePointer(modelReference, ((SetConceptChange) change).getAffectedNodeId()), change.getRootId()));
} else
if (change instanceof ModelAttributeChange || change instanceof UsedLanguageChange || change instanceof ImportedModelChange || change instanceof EngagedLanguageChange) {
builder.accept(new ModelFeature(modelReference));
}
return builder.build();
}
private static final class FeatureHierarchyListener extends CurrentDifferenceAdapter {
private final FeaturesFromVcs myFFMap;
public FeatureHierarchyListener(FeaturesFromVcs map) {
myFFMap = map;
}
@Override
public void changeAdded(@NotNull final ModelChange change) {
List features = changeAdded0(change);
myFFMap.put(features, change);
myFFMap.fireFeaturesAdded(myFFMap.withAncestors(new HashSet
}
@Override
public void modelStatusChanged(@NotNull SModelReference modelReference) {
Set singleton = Collections. ModelFeature(modelReference));
myFFMap.fireFeaturesRemoved(singleton);
myFFMap.fireFeaturesAdded(singleton);
}
private List changeAdded0(@NotNull ModelChange change) {
return (List FeatureForestMapSupport.getFeaturesForChange(change).collect(Collectors.toList());
}
@Override
public void changesAdded(@NotNull List changes) {
if (changes.isEmpty()) {
return;
}
Set featureSet = new HashSet
for (ModelChange change : changes) {
List features = changeAdded0(change);
featureSet.addAll(features);
myFFMap.put((List features.stream().distinct().collect(Collectors.toList()), change);
}
myFFMap.fireFeaturesAdded(myFFMap.withAncestors(featureSet));
}
@Override
public void changesRemoved(@NotNull List changes) {
if (changes.isEmpty()) {
return;
}
Set featuresToRemove = myFFMap.getFeatures(changes);
featuresToRemove = myFFMap.withAncestors(featuresToRemove);
myFFMap.removeAll(changes);
myFFMap.fireFeaturesRemoved(featuresToRemove);
}
@Override
public void changeRemoved(@NotNull ModelChange change) {
changesRemoved(Collections.singletonList(change));
}
}
}
|
java
| 22 | 0.757827 | 212 | 44.557377 | 183 |
starcoderdata
|
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="box-header">
class="box-title"> SETORAN DINAS COUNTER TERMINAL BANDARA
class="box-title"> TANGGAL <?php echo $this->uri->segment(3). " S/D ".$this->uri->segment(4).", ".$comt_t." / ".$comt_ter." / ".$shift;?>
<!-- /.box-header -->
<div class="box-body table-responsive no-padding">
<table id="example1" class=" table table-bordered" style="font-family: calibri">
<tr style="font-size: 8pt">
Penj.Tiket
<?php foreach($trayek->result_array() as $r) { ?>
echo $r['nama_trayek']." ".number_format($r['tarif']);?>
<?php } ?>
<?php
$no = 1;
foreach($list->result_array() as $rows) {
// echo $shifts."
?>
<td style="text-align:center"> echo $rows['DAY']; ?>
<?php
$counter_1 = $this->laporan_model->get_counter($shifts,$rows['DAY'],$trk,$trmnl);
foreach($counter_1->result_array() as $row) {
if($row['counter']) {$counter=$row['counter'];} else { $counter = "-";}
if($row['trmnl']) {$terminal=$row['trmnl'];} else { $terminal = "-";}
?>
<tr style="font-size: 8pt">
echo $counter; ?>
echo $terminal; ?>
<?php foreach($trayek->result_array() as $r) { ?>
<td style="text-align: right">
echo number_format($this->laporan_model->sum_lap2($rows['DAY'], $r['id_trayek'], $shifts, 'qty', $row['created_by'], $trmnl));?>
echo "Rp".number_format($this->laporan_model->sum_lap2($rows['DAY'], $r['id_trayek'], $shifts, 'total', $row['created_by'], $trmnl));?>
<?php } ?>
<td style="font-size: 8pt; background-color: #f9f8f8; color: #666666; font-weight: bold;text-align: right">
<?php
$subtotal_qty = $this->laporan_model->sum_lap2_samping($rows['DAY'], $trmnl, $row['created_by'], $shifts,'qty');
echo " ".number_format($subtotal_qty)."
$subtotal = $this->laporan_model->sum_lap2_samping($rows['DAY'], $trmnl, $row['created_by'], $shifts,'total');
echo " ".number_format($subtotal)."
?>
<?php $no++; }} ?>
<tr style="font-size: 8pt; background-color: #f9f8f8; color: #666666; font-weight: bold;text-align: right">
<td colspan="3">
TOTAL
<?php foreach($trayek->result_array() as $r) {
$subttl = $this->laporan_model->sum_lap2_bawah($this->uri->segment(3),$this->uri->segment(4),$r['id_trayek'],$trmnl,$shifts,"total");
$subqty = $this->laporan_model->sum_lap2_bawah($this->uri->segment(3),$this->uri->segment(4),$r['id_trayek'],$trmnl,$shifts,"qty");
?>
echo number_format($subqty);?>
echo "Rp ".number_format($subttl);?>
<?php } ?>
<div class="col-xs-10">
<button type="button" class="btn btn-primary" onclick="cetak_lap2_shift()"><i class="fa fa-send"> Cetak
<!-- /.box-body -->
<!-- /.box -->
|
php
| 17 | 0.404369 | 179 | 50.318681 | 91 |
starcoderdata
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.test;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.apache.geronimo.test.local.TestLocal;
import org.apache.geronimo.test.local.TestLocalHome;
import org.apache.geronimo.test.remote.Test;
import org.apache.geronimo.test.remote.TestHome;
import org.apache.geronimo.test.ws.HelloWorld;
import org.apache.geronimo.test.ws.HelloWorldService;
/**
* Servlet implementation class for Servlet: TomcatTestServlet
*
*/
public class TomcatTestServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#HttpServlet()
*/
public TomcatTestServlet() {
super();
}
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println(" application to check references
out.println("
try
{
Context ctx = new InitialContext();
TestHome result = (TestHome)ctx.lookup("java:comp/env/ejb/TestBean");
//TestHome testHome = (TestHome) PortableRemoteObject.narrow(result, TestHome.class);
Test test = result.create();
String echo = test.echo("Test");
out.println("<font align=Center face=\"Garamond\"> Check EJB Reference : Call to bean method returned ->"+echo+"
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/MyDataSource");
Connection con = ds.getConnection();
out.println("<font align=Center face=\"Garamond\"> Check Resource Reference : Got Connection ->"+con+"
QueueConnectionFactory qcf = (QueueConnectionFactory)ctx.lookup("java:comp/env/jms/DefaultActiveMQConnectionFactory");
QueueConnection qCon = qcf.createQueueConnection();
out.println("<font align=Center face=\"Garamond\"> Check JMS Resource Reference : Got Queue Connection ->"+qCon+"
Queue q = (Queue) ctx.lookup("java:comp/env/jms/SendReceiveQueue");
out.println("<font align=Center face=\"Garamond\"> Check JMS Resource Env Reference : Got Queue ->"+q.getQueueName()+"
HelloWorldService hello = (HelloWorldService) ctx.lookup("java:comp/env/service/HelloWorldService");
HelloWorld port = hello.getHelloWorld();
out.println("<font align=Center face=\"Garamond\"> Check Service Reference : Called Web Service ->"+port.getHelloWorld("Test")+"
TestLocalHome resultLocal = (TestLocalHome)ctx.lookup("java:comp/env/ejb/TestLocalBean");
TestLocal testLocal = resultLocal.create();
String echoLocal = testLocal.echoLocal("Test");
out.println("<font align=Center face=\"Garamond\"> Check EJB Local Reference : Call to bean method returned ->"+echoLocal+"
}catch(Exception e)
{
e.printStackTrace();
}
out.println("
}
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
|
java
| 15 | 0.726063 | 152 | 40.315315 | 111 |
starcoderdata
|
import inspect
from enum import EnumMeta, Enum as PyEnum
from pygraphy.utils import patch_indents
class EnumType(EnumMeta):
def __str__(cls):
description = inspect.getdoc(cls)
description_literal = f'"""\n{description}\n"""\n' if description else '' # noqa
return (
description_literal
+ f'enum {cls.__name__} '
+ '{\n'
+ f'{patch_indents(cls.print_enum_values(), indent=1)}'
+ '\n}'
)
def print_enum_values(cls):
literal = ''
for name, _ in cls.__dict__.items():
if name.startswith('_'):
continue
literal += (name + '\n')
return literal[:-1] if literal.endswith('\n') else literal
class Enum(PyEnum, metaclass=EnumType):
pass
|
python
| 15 | 0.548972 | 89 | 26.566667 | 30 |
starcoderdata
|
var prevScrollpos = window.pageYOffset;
window.onscroll = headerbarToggle
function headerbarToggle() {
var btnbar = document.getElementById("btnbar")
var ftrbar = document.getElementById("ftrbar")
var currentScrollPos = window.pageYOffset
if (prevScrollpos < currentScrollPos - 400) {
btnbar.style.opacity = 0.1
}
else if (prevScrollpos < currentScrollPos - 375) {
btnbar.style.opacity = 0.2
}
else if (prevScrollpos < currentScrollPos - 350) {
btnbar.style.opacity = 0.3
}
else if (prevScrollpos < currentScrollPos - 325) {
btnbar.style.opacity = 0.4
}
else if (prevScrollpos < currentScrollPos - 300) {
btnbar.style.opacity = 0.5
}
else if (prevScrollpos < currentScrollPos - 275) {
btnbar.style.opacity = 0.6
}
else if (prevScrollpos < currentScrollPos - 250) {
btnbar.style.opacity = 0.7
}
else if (prevScrollpos < currentScrollPos - 225) {
btnbar.style.opacity = 0.8
}
else if (prevScrollpos < currentScrollPos - 200) {
btnbar.style.opacity = 0.9
}
else {
btnbar.style.opacity = 1
}
if (prevScrollpos < currentScrollPos - 225) {
ftrbar.style.opacity = 0.1
}
else if (prevScrollpos < currentScrollPos - 200) {
ftrbar.style.opacity = 0.2
}
else if (prevScrollpos < currentScrollPos - 175) {
ftrbar.style.opacity = 0.3
}
else if (prevScrollpos < currentScrollPos - 150) {
ftrbar.style.opacity = 0.4
}
else if (prevScrollpos < currentScrollPos - 125) {
ftrbar.style.opacity = 0.5
}
else if (prevScrollpos < currentScrollPos - 100) {
ftrbar.style.opacity = 0.6
}
else if (prevScrollpos < currentScrollPos - 75) {
ftrbar.style.opacity = 0.7
}
else if (prevScrollpos < currentScrollPos - 50) {
ftrbar.style.opacity = 0.8
}
else if (prevScrollpos < currentScrollPos - 25) {
ftrbar.style.opacity = 0.9
}
else {
ftrbar.style.opacity = 1
}
}
|
javascript
| 9 | 0.620265 | 54 | 28.760563 | 71 |
starcoderdata
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class paymentsystem extends Model
{
protected $table = 'paymentsystems';
public function coupon()
{
return $this->belongsTo('paymentsystem');
}
public function paymentlog()
{
return $this->belongsTo('paymentlog');
}
}
|
php
| 10 | 0.641618 | 49 | 13.416667 | 24 |
starcoderdata
|
private void doStopReporting() {
synchronized (this) {
// Note: There is no synchronization to prevent multiple
// reporting loops from running simultaneously. It's possible
// for one to start before another one exits, which is safe
// because flushInternal() is itself synchronized.
if (reportingThread == null) {
return;
}
reportingThread.interrupt();
reportingThread = null;
}
}
|
java
| 8 | 0.56699 | 74 | 38.692308 | 13 |
inline
|
import axios from 'axios';
const user={
state:{
user:localStorage.getItem('my_user') || null,
token:localStorage.getItem('token') || null
},
mutations:{
assignUser(state,{user,token}){
state.user=user;
localStorage.setItem('my_user',JSON.stringify(user));
state.token=token;
localStorage.setItem('token',token);
}
},
actions:{
checkuser(context,redirect=false){
return new Promise((resolve, reject) => {
axios.get('/check-login').then(res=>{
if(!context.state.user){
if(res.data.status==500&&redirect) window.location='/login';
if(res.data.status==200){
let user=res.data.data.user;
let token=res.data.data.access_token;
console.log({user,token});
context.commit('assignUser',{user,token});
}
}
console.log('resolve');
resolve();
});
}, error => {
reject(error);
})
}
}
}
export default user;
|
javascript
| 25 | 0.448547 | 84 | 31.666667 | 39 |
starcoderdata
|
//
// SceneKit+Snapshot.h
// FLEX
//
// Created by on 1/8/20.
//
#import
#import "FHSViewSnapshot.h"
@class FHSSnapshotNodes;
extern CGFloat const kFHSSmallZOffset;
#pragma mark SCNNode
@interface SCNNode (Snapshot)
/// @return the nearest ancestor snapshot node starting at this node
@property (nonatomic, readonly) SCNNode *nearestAncestorSnapshot;
/// @return a node that renders a highlight overlay over a specified snapshot
+ (instancetype)highlight:(FHSViewSnapshot *)view color:(UIColor *)color;
/// @return a node that renders a snapshot image
+ (instancetype)snapshot:(FHSViewSnapshot *)view;
/// @return a node that draws a line between two vertices
+ (instancetype)lineFrom:(SCNVector3)v1 to:(SCNVector3)v2 color:(UIColor *)lineColor;
/// @return a node that can be used to render a colored border around the specified node
- (instancetype)borderWithColor:(UIColor *)color;
/// @return a node that renders a header above a snapshot node
/// using the title text from the view, if specified
+ (instancetype)header:(FHSViewSnapshot *)view;
/// @return a SceneKit node that recursively renders a hierarchy
/// of UI elements starting at the specified snapshot
+ (instancetype)snapshot:(FHSViewSnapshot *)view
parent:(FHSViewSnapshot *)parentView
parentNode:(SCNNode *)parentNode
root:(SCNNode *)rootNode
depth:(NSInteger *)depthOut
nodesMap:(NSMutableDictionary<NSString *, FHSSnapshotNodes *> *)nodesMap
hideHeaders:(BOOL)hideHeaders;
@end
#pragma mark SCNShape
@interface SCNShape (Snapshot)
/// @return a shape with the given path, 0 extrusion depth, and a double-sided
/// material with the given diffuse contents inserted at index 0
+ (instancetype)shapeWithPath:(UIBezierPath *)path materialDiffuse:(id)contents;
/// @return a shape that is used to render the background of the snapshot header
+ (instancetype)nameHeader:(UIColor *)color frame:(CGRect)frame corners:(CGFloat)cornerRadius;
@end
#pragma mark SCNText
@interface SCNText (Snapshot)
/// @return text geometry used to render text inside the snapshot header
+ (instancetype)labelGeometry:(NSString *)text font:(UIFont *)font;
@end
|
c
| 12 | 0.731489 | 94 | 36.301587 | 63 |
starcoderdata
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.