code
stringlengths 0
29.6k
| language
stringclasses 9
values | AST_depth
int64 3
30
| alphanumeric_fraction
float64 0.2
0.86
| max_line_length
int64 13
399
| avg_line_length
float64 5.02
139
| num_lines
int64 7
299
| source
stringclasses 4
values |
---|---|---|---|---|---|---|---|
package sudoku;
import org.junit.Before;
import org.junit.Test;
import sudoku.exceptions.WrongValueException;
import java.util.ResourceBundle;
import static org.junit.Assert.*;
public class SudokuFieldTest {
private SudokuField field;
private SudokuField field2;
@Before
public void setUp() {
field = new SudokuField(0);
}
@Test
public void getFieldValueTest() {
assertEquals(field.getValue(), 0);
}
@Test
public void setFieldValueTest() {
field.setValue(4);
assertEquals(field.getValue(), 4);
assertEquals(field.getStringValue(), "4");
field.setStringValue("5");
assertEquals(field.getValue(), 5);
}
@Test
public void setWrongValueTest() {
assertFalse(field.setStringValue("x"));
}
@Test
public void toStringTest() {
assertNotNull(field.toString());
}
@Test
public void equalsTest() {
field2 = new SudokuField(0);
assertTrue(field.equals(field2)
&& field2.equals(field));
assertTrue(field.equals(field));
}
@Test
public void notEqualsTest() {
assertFalse(field.equals(null));
BacktrackingSudokuSolver bss = new BacktrackingSudokuSolver();
assertFalse(field.equals(bss));
}
@Test
public void hashCodeTest() {
field2 = new SudokuField(0);
assertEquals(field.hashCode(), field2.hashCode());
}
@Test
public void compareToTest(){
field.setValue(0);
field2 = new SudokuField(0);
assertEquals(0, field.compareTo(field2));
field2.setValue(1);
assertEquals(-1, field.compareTo(field2));
field.setValue(3);
assertEquals(1, field.compareTo(field2));
assertThrows(NullPointerException.class, () -> {
field2 = null;
field.compareTo(field2);
});
}
}
|
java
| 11 | 0.596237 | 75 | 23.604938 | 81 |
starcoderdata
|
from waldur_ansible.common.extension import AnsibleCommonExtension
from waldur_core.core import WaldurExtension
class JupyterHubManagementExtension(WaldurExtension):
class Settings:
WALDUR_JUPYTER_HUB_MANAGEMENT = {
'JUPYTER_MANAGEMENT_PLAYBOOKS_DIRECTORY': '%swaldur-apps/jupyter_hub_management/' % AnsibleCommonExtension.Settings.WALDUR_ANSIBLE_COMMON['ANSIBLE_LIBRARY'],
}
@staticmethod
def django_app():
return 'waldur_ansible.jupyter_hub_management'
@staticmethod
def is_assembly():
return True
@staticmethod
def rest_urls():
from .urls import register_in
return register_in
|
python
| 13 | 0.707715 | 169 | 28.304348 | 23 |
starcoderdata
|
def __remove_event(self, events, each):
"""remove event from events
:param events: the list contain some events
:param each: the event will be removed
:return: None
"""
self.logger.warning("remove event with udata: %s", str(each.udata))
for event in events:
if event.ident == each.ident:
events.remove(event)
break
|
python
| 10 | 0.560096 | 75 | 31.076923 | 13 |
inline
|
package com.bbn.speed.listener;
import com.bbn.speed.Speed;
import com.bbn.speed.core.GameAnimator;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.ReadyEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class ReadyListener extends ListenerAdapter {
@Override
public void onReady(ReadyEvent event) {
/*
for (Guild g : event.getJDA().getGuilds()) {
Speed.rethink.insertGuild(g.getId());
}
for (User u : event.getJDA().getUsers()) {
Speed.rethink.insertUser(u.getId());
} */
System.out.println("Bot started!");
new GameAnimator(event.getJDA()).start();
}
}
|
java
| 9 | 0.669271 | 52 | 29.72 | 25 |
starcoderdata
|
#pragma once
#include "core/animation_system.hpp"
#include "core/assert.hpp"
#include "core/camera.hpp"
#include "core/config.hpp"
#include "core/platform_defines.hpp"
#include "core/ecs.hpp"
#include "core/frustum.hpp"
#include "core/input.hpp"
#include "core/input_types.hpp"
#include "core/lua.hpp"
#include "core/math.hpp"
#include "core/scene.hpp"
#include "core/time.hpp"
#include "core/window.hpp"
#include "graphics/graphics_api.hpp"
#include "graphics/lights.hpp"
#include "graphics/render_system.hpp"
#include "graphics/shader_c_shared/lights.h"
#include "graphics/shadow_map.hpp"
#include "graphics/texture_manager.hpp"
#include "graphics/vulkan.hpp"
#include "resource/image.hpp"
#include "resource/material.hpp"
#include "resource/model.hpp"
#include "resource/resource_manager.hpp"
#include "resource/script.hpp"
#include "resource/shader.hpp"
#include "utils/logger.hpp"
#include "utils/random.hpp"
#include "components/animation_component.hpp"
#include "components/entity_metadata.hpp"
#include "components/model_renderer.hpp"
#include "components/skinned_renderer.hpp"
#include "components/script_component.hpp"
#include "components/transform.hpp"
namespace PG = Progression;
namespace Progression
{
extern bool g_engineShutdown;
extern bool g_converterMode;
bool EngineInitialize( std::string config_name = "" );
void EngineQuit();
} // namespace Progression
|
c++
| 8 | 0.767844 | 54 | 24.685185 | 54 |
starcoderdata
|
#include "FW/document.h"
#include "FW/UI/ui_file_explorer.h"
#include "FW/UI/ui_main_window.h"
#include "FW/UI/ui_editor_container.h"
#include "ui_fileexplorer.h"
#include
#include
#include
#include "FW/controller.h"
#include "FW/UI/ui_file_contextmenu.h"
TypeUiFileExplorer::TypeUiFileExplorer( TypeController& controller, QWidget* parent ) :
QWidget( parent ),
TypeVariant( 0 ),
m_Controller( &controller ),
ui( new Ui::TypeUiFileExplorer )
{
m_Path = "";
m_Model = new QStringListModel( this );
ui->setupUi( this );
ui->ListView->setModel( m_Model );
ui->ListView->setEditTriggers( QAbstractItemView::DoubleClicked );
Update();
connect(
ui->ListView,
QListView::doubleClicked,
this,
TypeUiFileExplorer::OnDoubleClicked
);
connect(
ui->RootButton,
QPushButton::clicked,
this,
TypeUiFileExplorer::OnRootButtonClicked
);
connect(
ui->UpButton,
QPushButton::clicked,
this,
TypeUiFileExplorer::OnUpButtonClicked
);
connect(
ui->LineEdit,
QLineEdit::returnPressed,
this,
TypeUiFileExplorer::OnLineEditReturnPressed
);
connect(
ui->ListView,
QListView::customContextMenuRequested,
this,
TypeUiFileExplorer::OnCustomContextMenuRequested
);
}
TypeUiFileExplorer::~TypeUiFileExplorer()
{
delete ui;
}
void TypeUiFileExplorer::FileOpen()
{
QModelIndexList index_list = ui->ListView->selectionModel()->selectedIndexes();
if( index_list.empty() )
return;
QModelIndex index = *index_list.begin();
QString file_name = m_ModelData[index.row()];
if( !Path().isEmpty() )
file_name.prepend( Path() + "/" );
FileOpen( file_name );
}
QString TypeUiFileExplorer::FullPath()
{
if( !Path().isEmpty() )
return Controller().Document().Path() + "/" + Path();
return Controller().Document().Path();
}
void TypeUiFileExplorer::Update()
{
ui->LineEdit->setText( Path() );
m_ModelData = QDir( FullPath() ).entryList();
m_ModelData.pop_front();
m_ModelData.pop_front();
m_Model->setStringList( m_ModelData );
m_Model->layoutChanged();
emit Controller().FileExplorerChanged();
}
void TypeUiFileExplorer::FileNew()
{
QString path = Path();
if( !path.isEmpty() )
path = path + "/";
QString file_name =
QFileDialog::getSaveFileName(
&Controller().MainWindow(),
tr( "New File" ),
path + tr( "untitled" ),
tr( "Text files (*.txt);;Html files (*.html);;Php files (*.php);;Css files (*.css);;Java Script Files (*.js)" )
);
if( file_name.isEmpty() )
return;
Controller().NewFileUiEditor( file_name );
}
void TypeUiFileExplorer::FileMkDir()
{
QString path = Path();
if( !path.isEmpty() )
path = path + "/";
QString file_name =
QFileDialog::getSaveFileName(
&Controller().MainWindow(),
tr( "New File" ),
path + tr( "untitled" ),
tr( "" )
);
if( file_name.isEmpty() )
return;
QDir( path ).mkdir( file_name );
Update();
}
void TypeUiFileExplorer::FileOpen( QString file_name )
{
if( file_name.isEmpty() )
{
m_Path = "";
Update();
return;
}
if( QFileInfo( file_name ).isDir() )
{
m_Path = file_name;
Update();
return;
}
if( !QFileInfo( file_name ).exists() )
{
TypeController::Message( tr( "File doesn't exists" ) );
Update();
return;
}
QStringList string_list = file_name.split( "/" );
string_list.pop_back();
m_Path = string_list.join( "/" );
Update();
Controller().OpenFileUiEditor( file_name );
}
void TypeUiFileExplorer::FileRemove()
{
QModelIndexList index_list = ui->ListView->selectionModel()->selectedIndexes();
if( index_list.empty() )
return;
QModelIndex index = *index_list.begin();
QString file_name = m_ModelData[index.row()];
if( !Path().isEmpty() )
file_name.prepend( Path() + "/" );
FileRemove( file_name );
}
void TypeUiFileExplorer::FileRemove( QString file_name )
{
if( file_name.isEmpty() )
return;
if( !QFileInfo( file_name ).exists() )
{
TypeController::Message( tr( "File doesn't exists" ) );
Update();
return;
}
if( QFileInfo( file_name ).isDir() )
{
if( !QDir( file_name ).removeRecursively() )
qDebug() << "Failed removing dir" << file_name;
Update();
return;
}
if( !QFile( file_name ).remove() )
qDebug() << "Failed removing file" << file_name;
Update();
}
void TypeUiFileExplorer::OnDoubleClicked( const QModelIndex& index )
{
QString file_name = m_ModelData[index.row()];
if( !Path().isEmpty() )
file_name.prepend( Path() + "/" );
FileOpen( file_name );
}
void TypeUiFileExplorer::OnLineEditReturnPressed()
{
FileOpen( ui->LineEdit->text() );
}
void TypeUiFileExplorer::OnCustomContextMenuRequested( const QPoint& point )
{
QPoint global_point = ui->ListView->viewport()->mapToGlobal( point );
QModelIndex index = ui->ListView->indexAt( point );
bool has_selection = false;
if( index.row() >= 0 )
has_selection = true;
TypeUiFileContextMenu context_menu( Controller(), has_selection, global_point, this );
}
void TypeUiFileExplorer::OnRootButtonClicked()
{
m_Path = "";
Update();
}
void TypeUiFileExplorer::OnUpButtonClicked()
{
if( !m_Path.isEmpty() )
{
QStringList path_list = m_Path.split( "/" );
path_list.pop_back();
m_Path = path_list.join( "/" );
Update();
}
}
|
c++
| 13 | 0.589277 | 123 | 21.596154 | 260 |
starcoderdata
|
๏ปฟusing IxMilia.Dwg.Objects;
using System.Collections.Generic;
namespace IxMilia.Dwg
{
internal class DwgObjectCache
{
private IDictionary<DwgHandle, int> _handleToOffset = new Dictionary<DwgHandle, int>();
private IDictionary<DwgHandle, DwgObject> _handleToObject = new Dictionary<DwgHandle, DwgObject>();
private DwgVersionId _version;
public int ObjectCount => _handleToOffset.Count;
public IList Classes { get; }
private DwgObjectCache(DwgVersionId version, IList classes)
{
_version = version;
Classes = classes;
}
public int GetOffsetFromHandle(DwgHandle handle)
{
if (_handleToOffset.TryGetValue(handle, out var offset))
{
return offset;
}
throw new DwgReadException($"Unable to get offset for object handle {handle}");
}
public DwgObject GetObject(BitReader reader, DwgHandle handle, bool allowNull = false)
{
if (_handleToObject.TryGetValue(handle, out var obj))
{
return obj;
}
if (_handleToOffset.TryGetValue(handle, out var offset))
{
obj = DwgObject.Parse(reader.FromOffset(offset), this, _version);
if (obj == null && !allowNull)
{
throw new DwgReadException($"Unsupported object from handle {handle} at offset {offset}.");
}
_handleToObject.Add(handle, obj);
return obj;
}
throw new DwgReadException($"Object with handle {handle} not found in object map.");
}
public T GetObject reader, DwgHandle handle) where T: DwgObject
{
var obj = GetObject(reader, handle);
if (obj is T specific)
{
return specific;
}
throw new DwgReadException($"Expected object of type {typeof(T)} with handle {handle} but instead found {obj.GetType().Name}.");
}
public T GetObjectOrDefault reader, DwgHandle handle) where T: DwgObject
{
if (handle.IsNull)
{
return null;
}
var obj = GetObject(reader, handle, allowNull: true);
if (obj is T specific)
{
return specific;
}
return null;
}
public static DwgObjectCache Parse(BitReader reader, DwgVersionId version, IList classes)
{
var objectCache = new DwgObjectCache(version, classes);
var lastHandle = 0;
var lastLocation = 0;
reader.StartCrcCheck();
var sectionSize = reader.ReadShortBigEndian();
while (sectionSize != 2)
{
var sectionStart = reader.Offset;
var sectionEnd = sectionStart + sectionSize - 2;
while (reader.Offset < sectionEnd)
{
// read data
var handleOffset = reader.Read_MC(allowNegation: false);
var locationOffset = reader.Read_MC();
var handle = lastHandle + handleOffset;
var location = lastLocation + locationOffset;
objectCache._handleToOffset.Add(new DwgHandle((uint)handle), location);
lastHandle = handle;
lastLocation = location;
}
reader.ValidateCrc(initialValue: DwgHeaderVariables.InitialCrcValue, readCrcAsMsb: true);
reader.StartCrcCheck();
sectionSize = reader.ReadShortBigEndian();
}
reader.ValidateCrc(initialValue: DwgHeaderVariables.InitialCrcValue, readCrcAsMsb: true);
return objectCache;
}
}
}
|
c#
| 19 | 0.558007 | 140 | 34.385965 | 114 |
starcoderdata
|
package com.entropyshift.overseer.crypto.key;
import java.security.KeyPair;
/**
* Created by chaitanya.m on 1/13/17.
*/
public final class AsymmetricKeyPairInformation
{
private final String id;
private final KeyPair keyPair;
private final AsymmetricKeyAlgorithms algorithm;
public AsymmetricKeyPairInformation(String id, KeyPair keyPair, AsymmetricKeyAlgorithms algorithm)
{
this.id = id;
this.keyPair = keyPair;
this.algorithm = algorithm;
}
public String getId()
{
return id;
}
public KeyPair getKeyPair()
{
return keyPair;
}
public AsymmetricKeyAlgorithms getAlgorithm()
{
return algorithm;
}
}
|
java
| 8 | 0.665272 | 102 | 18.378378 | 37 |
starcoderdata
|
<?php
class cliente{
private $codigo;
private $nome;
private $cidade;
// function __construct() {
// $this->codigo = isset($_POST['codigo']) ? $_POST['codigo'] : null;
// $this->nome = isset($_POST['nome']) ? $_POST['nome'] : null;
// $this->cidade = isset($_POST['cidade']) ? $_POST['cidade'] : null;
// }
// function start() {
// if (empty($this->nome) || empty($this->cidade)) {
// throw new Exception("Preencha os campos vazios");
// }
// else
// {
// // Do some stuiff
// echo "Cadastro realizado";
// }
// }
// }
// $register = new cliente();
// if(!empty($_POST)){
// $register->start();
}
|
php
| 6 | 0.465955 | 77 | 23.193548 | 31 |
starcoderdata
|
std::vector<Camera::Real> reprojectionErrors(
const Overlap& overlap,
const KeypointMap& keypointMap,
const std::vector<Trace>& traces,
const std::vector<Camera>& cameras) {
const std::reference_wrapper<const Camera> cams[2] = {
cameras[getCameraIndex(overlap.images[0])],
cameras[getCameraIndex(overlap.images[1])] };
const std::reference_wrapper<const std::vector<Keypoint>> keypoints[2] = {
keypointMap.at(overlap.images[0]),
keypointMap.at(overlap.images[1]) };
std::vector<Camera::Real> result;
for (const auto& match : overlap.matches) {
// TODO: if sees is not a good idea, this can be a much simpler loop
bool visible = true;
Camera::Vector2 pixels[2];
for (int i = 0; i < 2; ++i) {
pixels[i] = keypoints[i].get()[match[i]].position;
if (FLAGS_discard_outside_fov) {
if (!cams[1 - i].get().sees(cams[i].get().rigNearInfinity(pixels[i]))) {
visible = false;
break;
}
}
}
if (!visible) {
result.emplace_back(NAN);
} else {
int trace = keypoints[0].get()[match[0]].index;
CHECK_EQ(trace, keypoints[1].get()[match[1]].index);
Camera::Vector3 rig = trace < 0
? triangulate({{ cams[0], pixels[0] }, { cams[1], pixels[1] }})
: traces[trace].position;
Camera::Real squaredNorm = 0;
for (int i = 0; i < 2; ++i) {
squaredNorm += (pixels[i] - cams[i].get().pixel(rig)).squaredNorm();
}
result.emplace_back(sqrt(squaredNorm / 2));
}
}
return result;
}
|
c++
| 22 | 0.597034 | 80 | 34.272727 | 44 |
inline
|
// export default{
// apiKey: "
// authDomain: "talent-10911.firebaseapp.com",
// databaseURL: "https://talent-10911.firebaseio.com",
// projectId: "talent-10911",
// storageBucket: "talent-10911.appspot.com",
// messagingSenderId: "613523415046",
// appID: "talent-10911",
// }
export default{
apiKey: "
authDomain: "talent-management-system-c03c1.firebaseapp.com",
databaseURL: "https://talent-management-system-c03c1.firebaseio.com",
projectId: "talent-management-system-c03c1",
storageBucket: "talent-management-system-c03c1.appspot.com",
messagingSenderId: "828609066070",
appID: "talent-management-system-c03c1",
}
|
javascript
| 15 | 0.72017 | 71 | 34.2 | 20 |
starcoderdata
|
from itertools import product
from dataclasses import dataclass
from typing import Any, List, Tuple
from sympy import Add, Mul, Symbol, simplify, Function
from sympy.functions.special.tensor_functions import KroneckerDelta
class I(KroneckerDelta):
pass
@dataclass
class IndelStep:
act: str
pos: int
lik: Any
def __repr__(self):
pos = str(self.pos)
if self.act == "N":
pos = "_"
return f"{self.act}:{pos}"
IndelPath = Tuple[IndelStep, ...]
e = Symbol("e")
e1 = Symbol("(1-e)")
z1 = Symbol("zโ")
z2 = Symbol("zโ")
z3 = Symbol("zโ")
z4 = Symbol("zโ")
z5 = Symbol("zโ
")
x1 = Symbol("xโ")
x2 = Symbol("xโ")
x3 = Symbol("xโ")
p = Function("p")
CODON = (x1, x2, x3)
ACTG = [0, 1, 2, 3]
def p_eval(x):
if ACTG[0] == x:
return 0.2
if ACTG[1] == x:
return 0.4
if ACTG[2] == x:
return 0.1
assert ACTG[3] == x
return 0.3
def indel_tree_visit(path: IndelPath, seq_len: int, level: int) -> List[IndelPath]:
if level == 4:
return [path]
Step = IndelStep
paths: List[IndelPath] = []
if level in [0, 1]:
step = Step("N", 0, e1)
paths += indel_tree_visit(path + (step,), seq_len, level + 1)
for i in range(seq_len):
step = Step("D", i, e / seq_len)
paths += indel_tree_visit(path + (step,), seq_len - 1, level + 1)
elif level in [2, 3]:
step = Step("N", 0, e1)
paths += indel_tree_visit(path + (step,), seq_len, level + 1)
for i in range(seq_len + 1):
step = Step("I", i, e / (seq_len + 1))
paths += indel_tree_visit(path + (step,), seq_len + 1, level + 1)
return paths
def generate_all_indel_paths():
return indel_tree_visit(tuple(), 3, 0)
def apply_indel_step(step: IndelStep, seq: Tuple[str, ...]):
if step.act == "N":
return seq
elif step.act == "I":
return seq[: step.pos] + ("I",) + seq[step.pos :]
assert step.act == "D"
i = step.pos
j = step.pos + 1
return seq[:i] + seq[j:]
def apply_indel_path(path: IndelPath, seq: Tuple[str, str, str]):
final_seq: Tuple[str, ...] = seq
for step in path:
final_seq = apply_indel_step(step, final_seq)
return final_seq
def indel_path_prob(path: IndelPath):
return Mul(*[step.lik for step in path])
def path_seq_len(path):
return len(apply_indel_path(path, CODON))
def show_probs(paths):
expr = []
vecz = [z1, z2, z3, z4, z5]
vecx = [x1, x2, x3]
for path in paths:
seq = apply_indel_path(path, CODON)
path_prob = indel_path_prob(path)
cond = []
for i in range(len(seq)):
z = vecz[i]
if seq[i] == "I":
cond.append(p(z))
else:
x = seq[i]
cond.append(I(z, x))
cond_prob = Mul(*cond)
expr.append(cond_prob * path_prob)
p1 = f"๐={path}"
p2 = "๐ณ={}".format("".join(str(i) for i in seq))
zstr = "".join(str(z) for z in vecz[: len(seq)])
xstr = "".join(str(x) for x in vecx)
p3 = "p(๐=๐)={}".format(simplify(path_prob))
p4 = f"p(Z={zstr}|X={xstr}, ๐=๐) = {simplify(cond_prob)}"
p5 = f"p(Z={zstr}, ๐=๐|X={xstr}) = " + str(expr[-1])
print(f"{p1} leads to {p2};")
print(f" {p3}; {p4};")
print(f" {p5}.")
print()
fexpr = Add(*expr)
print(f"p(Z={zstr}|X=xโxโxโ) = " + str(simplify(fexpr)))
print(to_latex(f"p(Z={zstr}|X=xโxโxโ) = " + str(simplify(fexpr))))
return Add(*expr)
def to_latex(msg):
trans = {
"xโ": "x_1",
"xโ": "x_2",
"xโ": "x_3",
"zโ": "z_1",
"zโ": "z_2",
"zโ": "z_3",
"zโ": "z_4",
"zโ
": "z_5",
"e": "\\e",
"I": "\\I",
"**": "^",
"*": "",
"|": " \\gv ",
}
for k, v in trans.items():
msg = msg.replace(k, v)
return msg
goal = """Let ๐ denote a path through the base-indel process.
We want to calculate p(Z=๐ณ|X=xโxโxโ) = โ_๐ p(Z=๐ณ,๐=๐|X=xโxโxโ).
Note that p(Z=๐ณ,๐=๐|X=xโxโxโ) = p(Z=๐ณ|X=xโxโxโ,๐=๐)p(๐=๐|X=xโxโxโ)
= p(Z=๐ณ|X=xโxโxโ,๐=๐)p(๐=๐)
"""
print(goal)
paths = generate_all_indel_paths()
expr = dict()
for i in range(1, 6):
print(f"Paths that lead to |๐ณ|={i}")
print("------------------------")
print()
expr[f"|z|={i}"] = show_probs([path for path in paths if path_seq_len(path) == i])
print()
print()
total = 0.0
zsyms = [z1, z2, z3, z4, z5]
for f in range(1, 6):
for z in product(*[ACTG] * f):
subs = [
(e1, 1 - e),
(e, 0.1),
(x1, ACTG[1]),
(x2, ACTG[0]),
(x3, ACTG[3]),
]
for i in range(f):
subs += [(zsyms[i], z[i])]
total += expr[f"|z|={f}"].subs(subs).replace(p, p_eval)
print(total)
|
python
| 15 | 0.497472 | 86 | 22.660287 | 209 |
starcoderdata
|
package com.sago.myJavaTraining.Sandbox.examples.dojo;
import com.sago.myJavaTraining.Sandbox.examples.Exercise;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
public class MostFrequentDojo extends Exercise {
public MostFrequentDojo(HttpServletResponse response) {
super(response);
}
@Override
public void run() {
out.println("----get the number most frequent:");
// mostFrequent(array1) should return 1.
int[] array1 = {1, 3, 1, 3, 2, 1};
out.println("R1: "+mostFrequent(array1));
// mostFrequent(array2) should return 3.
int[] array2 = {3, 3, 1, 3, 2, 1};
out.println("R2: "+mostFrequent(array2));
// mostFrequent(array3) should return null.
int[] array3 = {};
out.println("R3: "+mostFrequent(array3));
// mostFrequent(array4) should return 0.
int[] array4 = {0};
out.println("R4: "+mostFrequent(array4));
// mostFrequent(array5) should return -1.
int[] array5 = {0, -1, 10, 10, -1, 10, -1, -1, -1, 1};
out.println("R5: "+mostFrequent(array5));
}
public int mostFrequent(int[] numbers){
int topNumber= -1 ;
int topCount=-1;
Map count = new HashMap<>();
//loop
for (int i =0; i < numbers.length ; i++)
{
//set items in a map and increas value, key is the numer
//validate if exceeds the current top
}
return topNumber;
}
}
|
java
| 11 | 0.594476 | 68 | 27.963636 | 55 |
starcoderdata
|
@RequestMapping(value = "/studies/{studyId}/notes", method = RequestMethod.POST, params = {"addNote"})
public String addNoteToTable(Model model, @PathVariable Long studyId,
HttpServletRequest request) {
//get the study
Study study = studyRepository.findOne(studyId);
model.addAttribute("study", study);
//disabled the check because we want to add note to the table
// if(study.getHousekeeping().getIsPublished()){
// return "redirect:/studies/" + studyId + "/notes";
// }
//the newly added note can only be assigned one of the availlable subject, not including system note subjects.
Collection<NoteSubject> noteSubjects = noteSubjectService.findAvailableNoteSubjectForStudy(study);
model.addAttribute("availableNoteSubject",noteSubjects);
SecureUser user = currentUserDetailsService.getUserFromRequest(request);
// an form object mapped from the studyNote object, it contains a list of notes
MultiStudyNoteForm msnf = studyNoteOperationsService.generateMultiStudyNoteForm(study.getNotes(), study, user);
//create a default study note with default setting
StudyNote emptyNote = studyNoteOperationsService.createEmptyStudyNote(study,user);
StudyNoteForm emptyNoteForm = studyNoteOperationsService.convertToStudyNoteForm(emptyNote);
//attach the empty form
msnf.getNomalNoteForms().add(0,emptyNoteForm);
//Index of value to add
// final Integer rowId = msnf.getNomalNoteForms().size()-1;
//enable the edit for the new note and disable all edit for other notes
msnf.startEdit(0);
//reload system notes because they are not part of the input
msnf.setSystemNoteForms(studyNoteOperationsService.generateSystemNoteForms(study.getNotes()));
model.addAttribute("multiStudyNoteForm", msnf);
return "study_notes";
}
|
java
| 10 | 0.700051 | 119 | 44.534884 | 43 |
inline
|
๏ปฟnamespace Adnc.Shared.Consts.RegistrationCenter;
public static class RegisteredTypeConsts
{
public const string Direct = "direct";
public const string Consul = "consul";
public const string Nacos = "nacos";
public const string ClusterIP = "clusterip";
}
|
c#
| 9 | 0.735294 | 49 | 29.222222 | 9 |
starcoderdata
|
๏ปฟnamespace Messenger.Bot.Buttons
{
public class LogOutButton : IButton
{
public ButtonTypes ButtonType => ButtonTypes.UrlButton;
}
}
|
c#
| 8 | 0.735849 | 63 | 25.5 | 8 |
starcoderdata
|
package com.github.t3t5u.common.util;
@SuppressWarnings("serial")
public class NoResultException extends RuntimeException {
public NoResultException() {
}
public NoResultException(final String message) {
super(message);
}
public NoResultException(final Throwable cause) {
super(cause);
}
public NoResultException(final String message, final Throwable cause) {
super(message, cause);
}
}
|
java
| 6 | 0.779528 | 102 | 24.4 | 20 |
starcoderdata
|
#pragma once
#include
#include
#include
#include
#include
#include
#include
TE_BEGIN_TERMINUS_NAMESPACE
using EventCallback = std::function
using CallbackID = uint32_t;
class EventManager
{
public:
EventManager();
~EventManager();
CallbackID register_callback(const uint16_t& type, EventCallback callback);
void unregister_callback(const uint16_t& type, const CallbackID& callback_id);
Event* allocate_event(const uint16_t& type);
void queue_event(Event* event);
void process_events();
private:
Event* pop_event();
private:
Mutex m_mutex;
uint32_t m_front;
uint32_t m_back;
uint32_t m_num_events;
Event m_event_pool[TE_MAX_EVENTS];
Event* m_event_queue[TE_MAX_EVENTS];
PackedArray<EventCallback, TE_MAX_CALLBACKS> m_callback_maps[16];
};
TE_END_TERMINUS_NAMESPACE
|
c++
| 11 | 0.689972 | 86 | 25.512195 | 41 |
starcoderdata
|
Vue.component('form-input-com', {
props : ['type','value', 'name', 'params'],
name : 'FormInputCom',
data : function () {
var label = '';
var col = '12';
var placeholder = '';
var params = this.params;
if(params.label) label = params.label;
if(params.col) col = params.col;
if(params.placeholder)
placeholder = params.placeholder;
var colDivClass = 'col-xs-' +col+ ' form-group';
var inpTextClass = 'form-control';
return {
label,
colDivClass,
inpTextClass,
placeholder,
}
},
methods: {
triggerEvent(event) {
this.$emit('trigger_input', { value : event.target.value, name : this.name });
},
},
template: `
<div v-if="type == 'text'">
<div :class="colDivClass">
<label v-if="label" >{{label}}
<input :type="type"
v-model="value"
:class="inpTextClass"
:placeholder="placeholder"
@input="triggerEvent" >
`,
});
|
javascript
| 16 | 0.441341 | 90 | 25.104167 | 48 |
starcoderdata
|
package distudios.at.carcassonne.engine.logic;
public class GoaUldRace extends Player {
public GoaUldRace(int playerID) {
super(playerID);
this.peeps = 10;
this.scoreMultiplierTotal = 1;
this.canSetOnExistingPeeps = true;
this.canOnlySetOnExisitingPeeps = true;
this.peepStrength = 1.2f;
}
}
|
java
| 8 | 0.660969 | 47 | 24.071429 | 14 |
starcoderdata
|
using System.Windows;
using System.Windows.Media;
namespace GitMind.Utils.UI
{
internal class Property
{
private readonly string propertyName;
private readonly ViewModel viewModel;
private object propertyValue;
public Property(string propertyName, ViewModel viewModel)
{
this.propertyName = propertyName;
this.viewModel = viewModel;
}
internal object Value
{
get { return propertyValue; }
set
{
if (propertyValue != value)
{
propertyValue = value;
viewModel.OnPropertyChanged(propertyName);
}
}
}
public static implicit operator string(Property instance) => (string)instance.Value;
public static implicit operator bool(Property instance) => (bool?)instance.Value ?? false;
public static implicit operator int(Property instance) => (int?)instance.Value ?? 0;
public static implicit operator double(Property instance) => (double?)instance.Value ?? 0;
public static implicit operator Rect(Property instance) => (Rect?)instance.Value ?? Rect.Empty;
public static implicit operator Brush(Property instance) => (Brush)instance.Value;
public PropertySetter Set(object value)
{
bool isSet = false;
if (!Equals(propertyValue, value))
{
propertyValue = value;
isSet = true;
viewModel.OnPropertyChanged(propertyName);
}
return new PropertySetter(isSet, viewModel);
}
}
//internal class AsyncProperty
//{
// //private T value;
// private Task valueTask;
// public Property(string propertyName, ViewModel viewModel)
// : base(propertyName, viewModel)
// {
// valueTask = Task.FromResult(default(T));
// }
// public static implicit operator T(Property propertyInstance) => propertyInstance.Get();
// public T Value => Get();
// public T Get()
// {
// return (valueTask.Status == TaskStatus.RanToCompletion)
// ? valueTask.Result : default(T);
// }
// protected override object InternalGet()
// {
// return Get();
// }
// public void Set(T propertyValue)
// {
// // Investigate if we can avoid assigning same value ####
// Set(Task.FromResult(propertyValue));
// }
// public void Set(Task propertyValueTask)
// {
// valueTask = propertyValueTask;
// NotifyChanged();
// if (!valueTask.IsCompleted)
// {
// SetAsync(propertyValueTask).RunInBackground();
// }
// }
// private async Task SetAsync(Task task)
// {
// try
// {
// await task;
// }
// catch (Exception e) when (e.IsNotFatal())
// {
// // Errors will be handled by the task
// }
// NotifyChanged();
// }
// //public T Result => (valueTask.Status == TaskStatus.RanToCompletion)
// // ? valueTask.Result : default(T);
// public bool IsCompleted => valueTask.IsCompleted;
// public bool IsNotCompleted => !valueTask.IsCompleted;
// public bool IsSuccessfullyCompleted => valueTask.Status == TaskStatus.RanToCompletion;
// public bool IsNotSuccessfullyCompleted => !IsSuccessfullyCompleted;
// public bool IsCanceled => valueTask.IsCanceled;
// public bool IsFaulted => valueTask.IsFaulted;
// // public TaskStatus Status => valueTask.Status;
// //public AggregateException Exception => valueTask.Exception;
// //public Exception InnerException => Exception?.InnerException;
// //public string ErrorMessage => InnerException?.Message;
// public void NotifyChanged()
// {
// viewModel.OnPropertyChanged(propertyName);
// // Trigger related properties (if specified using WhenSetAlsoNotify)
// otherProperties?.ForEach(property => viewModel.OnPropertyChanged(propertyName));
// }
// public void WhenSetAlsoNotify(string otherPropertyName)
// {
// if (otherProperties == null)
// {
// otherProperties = new List
// }
// otherProperties.Add(otherPropertyName);
// }
// public override string ToString() => Get()?.ToString() ?? "";
//}
}
|
c#
| 15 | 0.680218 | 97 | 22.554878 | 164 |
starcoderdata
|
var util = require('util'),
base = require('../../core/compute/image'),
_ = require('lodash');
var Image = exports.Image = function Image(client, details) {
base.Image.call(this, client, details);
};
util.inherits(Image, base.Image);
Image.prototype._setProperties = function (details) {
this.id = details.id;
this.name = details.name;
this.created_at = details.created_at;
//
// OpenStack specific
//
this.owner = details.owner;
this.checksum = details.checksum;
this.container_format = details.container_format;
this.disk_format = details.disk_format;
this.min_disk = details.min_disk;
this.min_ram = details.min_ram;
this.size = details.size;
this.visibility = details.visibility;
this.protected = details.protected;
this.tags = details.tags;
this.updated_at = details.updated_at;
this.status = details.status;
};
Image.prototype.toJSON = function () {
return _.pick(this, ['id', 'name', 'status', 'owner', 'created_at', 'updated_at', 'checksum', 'container_format', 'disk_format', 'min_disk',
'min_ram', 'size', 'visibility', 'protected', 'tags']);
};
|
javascript
| 8 | 0.640422 | 142 | 30.5 | 38 |
starcoderdata
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const inversify_1 = require("inversify");
require("reflect-metadata");
const alexa_app_1 = require("alexa-app");
const device_control_intent_1 = require("../intents/device_control_intent");
const types_1 = require("../types");
const alexa_launch_handler_1 = require("../intents/alexa_launch_handler");
const check_build_status_intent_1 = require("../intents/check_build_status_intent");
const queue_build_intent_1 = require("../intents/queue_build_intent");
const active_tasks_intent_1 = require("../intents/active_tasks_intent");
const status_report_intent_1 = require("../intents/status_report_intent");
const feature_disabled_intent_1 = require("../intents/feature_disabled_intent");
const expense_query_intent_1 = require("../intents/expense_query_intent");
const dotcore_intent_1 = require("../intents/dotcore_intent");
;
let AlexaVoiceHandler = class AlexaVoiceHandler {
constructor(logger, deviceRepo, vstsRepo, expressApp, config) {
this.alexaApp = new alexa_app_1.app("alexa");
this.logger = logger;
this.deviceRepo = deviceRepo;
this.config = config;
this.vstsRepo = vstsRepo;
this.alexaApp.express({
expressApp: expressApp,
checkCert: false,
debug: true
});
this.initialize();
}
initialize() {
var self = this;
var logger = this.logger;
this.alexaApp.launch((request, response) => {
try {
var intent = new alexa_launch_handler_1.AlexaLaunchHandler(this.logger, this.deviceRepo);
return intent.handleIntent(request, response);
}
catch (e) {
logger.error(e);
}
});
this.alexaApp.intent("DeviceControlIntent", {
"slots": {},
"utterances": [
"to turn on|off the device"
]
}, (request, response) => {
try {
var intent = new device_control_intent_1.DeviceControlIntentHandler(this.logger, this.deviceRepo);
return intent.handleIntent(request, response);
}
catch (e) {
logger.error(e);
}
});
this.alexaApp.intent("BuildIntent", {
"slots": {},
"utterances": [
"to check on the build",
"to get the status of the build",
"to get the build status"
]
}, (request, response) => {
try {
if (self.config.featureSet.vsts) {
let intent = new check_build_status_intent_1.CheckBuildStatusIntentHandler(this.logger, this.deviceRepo, this.config);
return intent.handleIntent(request, response);
}
else {
let intent = new feature_disabled_intent_1.FeatureDisabledIntentHandler(this.logger);
return intent.handleIntent(request, response);
}
}
catch (e) {
logger.error(e);
response.say(e);
}
});
this.alexaApp.intent("QueueBuildIntent", {
"slots": {},
"utterances": [
"to queue a build",
"to run a build",
"start a build"
]
}, (request, response) => {
try {
if (self.config.featureSet.vsts) {
let intent = new queue_build_intent_1.QueueBuildIntentHandler(this.logger, this.deviceRepo, this.config);
return intent.handleIntent(request, response);
}
else {
let intent = new feature_disabled_intent_1.FeatureDisabledIntentHandler(this.logger);
return intent.handleIntent(request, response);
}
}
catch (e) {
logger.error(e);
}
});
this.alexaApp.intent("AnimationIntent", {
"slots": {},
"utterances": [
"to change the device animation"
]
}, (request, response) => {
try {
let intent = new queue_build_intent_1.QueueBuildIntentHandler(this.logger, this.deviceRepo, this.config);
return intent.handleIntent(request, response);
}
catch (e) {
logger.error(e);
}
});
this.alexaApp.intent("ActiveTasksIntent", {
"slots": {},
"utterances": [
"to list my active tasks"
]
}, (request, response) => __awaiter(this, void 0, void 0, function* () {
try {
if (self.config.featureSet.vsts) {
let intent = new active_tasks_intent_1.ActiveTasksIntentHandler(this.logger, this.vstsRepo, self.config);
return intent.handleIntent(request, response);
}
else {
let intent = new feature_disabled_intent_1.FeatureDisabledIntentHandler(this.logger);
return intent.handleIntent(request, response);
}
}
catch (e) {
logger.error(e);
}
}));
this.alexaApp.intent("StatusReportIntent", {
"slots": {},
"utterances": [
"to read the current status report"
]
}, (request, response) => __awaiter(this, void 0, void 0, function* () {
try {
if (self.config.featureSet.wiki) {
var intent = new status_report_intent_1.StatusReportIntentHandler(this.logger, self.config);
return intent.handleIntent(request, response);
}
else {
let intent = new feature_disabled_intent_1.FeatureDisabledIntentHandler(this.logger);
return intent.handleIntent(request, response);
}
}
catch (e) {
logger.error(e);
}
}));
this.alexaApp.intent("ExpenseQueryIntent", {
"slots": {},
"utterances": [
"how much have I spent on this
]
}, (request, response) => __awaiter(this, void 0, void 0, function* () {
try {
if (self.config.featureSet.exfin) {
var intent = new expense_query_intent_1.ExpenseQueryIntentHandler(this.logger, self.config);
return intent.handleIntent(request, response);
}
else {
let intent = new feature_disabled_intent_1.FeatureDisabledIntentHandler(this.logger);
return intent.handleIntent(request, response);
}
}
catch (e) {
logger.error(e);
}
}));
this.alexaApp.intent("NewSimulationIntent", {
"slots": {},
"utterances": [
"create a new simulation"
]
}, (request, response) => __awaiter(this, void 0, void 0, function* () {
try {
if (self.config.featureSet.exfin) {
var intent = new dotcore_intent_1.DotCoreIntentHandler(this.logger, self.config);
return intent.handleIntent(request, response);
}
else {
let intent = new feature_disabled_intent_1.FeatureDisabledIntentHandler(this.logger);
return intent.handleIntent(request, response);
}
}
catch (e) {
logger.error(e);
}
}));
}
};
AlexaVoiceHandler = __decorate([
__param(0, inversify_1.inject(types_1.TYPES.Logger)),
__param(1, inversify_1.inject(types_1.TYPES.DeviceRepo)),
__param(2, inversify_1.inject(types_1.TYPES.VstsRepo)),
__param(3, inversify_1.inject(types_1.TYPES.ExpressApp)),
__param(4, inversify_1.inject(types_1.TYPES.Config)),
__metadata("design:paramtypes", [Object, Object, Object, Object, Object])
], AlexaVoiceHandler);
exports.AlexaVoiceHandler = AlexaVoiceHandler;
let RuntimeVoiceHandlerFactory = class RuntimeVoiceHandlerFactory {
getVoiceHandler(logger, deviceRepo, vstsRepo, app, config) {
return new AlexaVoiceHandler(logger, deviceRepo, vstsRepo, app, config);
}
};
RuntimeVoiceHandlerFactory = __decorate([
inversify_1.injectable()
], RuntimeVoiceHandlerFactory);
exports.RuntimeVoiceHandlerFactory = RuntimeVoiceHandlerFactory;
//# sourceMappingURL=voice_handler.js.map
|
javascript
| 25 | 0.545613 | 151 | 42.665254 | 236 |
starcoderdata
|
#!/usr/bin/python
# coding=utf-8
"""This table stores a pair example of proceced images."""
import uuid
from datetime import datetime
import pytz
from sqlalchemy.dialects.postgresql import UUID, JSON
from deblurrer import db
class Example(db.Model):
"""
Store the record of a consumed Example.
The images fields are json encoded
containing metada and resource location information
"""
__tablename__ = "examples"
id = db.Column(UUID(as_uuid=True), primary_key=True, unique=True, nullable=False)
input_image = db.Column(db.String, nullable=False)
output_image = db.Column(db.String, nullable=False)
score = db.Column(db.Integer, nullable=True)
created = db.Column(db.DateTime(timezone=True), default=datetime.utcnow().replace(tzinfo=pytz.utc), nullable=False)
def __init__(self, id, input_image, output_image):
self.id = id
self.input_image = input_image
self.output_image = output_image
def __repr__(self):
return "<ID: {} Created: {}>".format(self.id, self.created)
|
python
| 12 | 0.686497 | 119 | 29.257143 | 35 |
starcoderdata
|
def read_job_num(output_path):
"""
Extract job num from the job_path
"""
job_name = output_path.split("/")[-2]
job_num = int(job_name.split('_')[-1][1:])
return job_num
|
python
| 12 | 0.5625 | 46 | 26.571429 | 7 |
inline
|
#ifndef _LSPIPE
#define _LSPIPE
#pragma once
#ifndef UNICODE
#define UNICODE
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include
#include
#include
#include
#include
#include
#include
#include
#pragma comment(lib, "ntdll.lib")
#define LastWin32 (0)
#define Winsock2 L"winsock2\\\\catalogchangelistener-(.+)-0"
#define WmiEvent L"pipe_eventroot\\\\cimv2scm event provider"
#define Chromium L".*mojo\\.(\\d+)\\.\\d+\\.\\d+"
#define MsysPipe L"msys-\\S+-(\\d+)-\\S+"
template<typename T, bool (*Cleanup)(T)>
struct AutoHelper {
using pointer = T;
void operator()(T t) const {
if (!Cleanup(t))
std::wcout << L"[!] err: 0x"
<< std::hex
<< ::GetLastError()
<< std::endl;
#ifdef DEBUG
else
std::wcout << L"[*] successfully released" << std::endl;
#endif
}
};
bool AutoHandle(const HANDLE h) { return ::CloseHandle(h); }
bool AutoLocals(const HLOCAL h) { return nullptr == ::LocalFree(h); }
#endif
|
c++
| 14 | 0.63059 | 69 | 20.09434 | 53 |
starcoderdata
|
var _ = require('lodash');
var svd = require('node-svd').svd;
var Matrix = require('milker').Matrix;
module.exports = SvdCalculator;
function SvdCalculator(){
}
SvdCalculator.prototype.run = function(model, options){
var iterations = 1;
var dim = 0;
if( options.svdDimensions ){
dim = options.svdDimensions;
}
if( options.svdIterations ){
iterations = options.svdIterations;
}
var predictedMatrix = _.cloneDeep( model.output['filledMatrix'] );
var originalMatrix = model.input;
for( var i = 0; i < iterations; i++ ){
predictedMatrix = doSvd(predictedMatrix, originalMatrix, dim);
}
model.addOutput('predictedMatrix', predictedMatrix);
}
function doSvd(predictedMatrix, originalMatrix, dim){
var res = svd(predictedMatrix, dim);
var U = new Matrix( res.U );
var S = Matrix.diagonal( res.S );
var V = new Matrix( res.V );
var svdMatrix = U.product(S).product(V);
var predictedMatrix = svdMatrix.elements();
// fill only null entries in original matrix
for( var row in originalMatrix ){
for( var col in originalMatrix[row] ){
if( originalMatrix[row][col] != null ){
predictedMatrix[row][col] = Number( (originalMatrix[row][col]).toFixed(4) );
} else{
predictedMatrix[row][col] = Number( (predictedMatrix[row][col]).toFixed(4) );
}
}
}
return predictedMatrix;
}
|
javascript
| 19 | 0.672689 | 85 | 22.209677 | 62 |
starcoderdata
|
def setUp(self):
# Create user
user = User.objects.create_user(username='test user', email='test@localhost', password='test')
user.is_staff = True
user.save()
self.user = user
# Set up client
self.client = Client()
self.client.login(username='test user', password='test')
# Set up initial data
testing_service_class, created = ServiceClass.objects.get_or_create(name='Testing')
external_service_type, created = ServiceType.objects.get_or_create(name='External',
service_class=testing_service_class)
external_service_type, created = ServiceType.objects.get_or_create(name='Private Interconnect',
service_class=testing_service_class)
provider_node_type, created = NodeType.objects.get_or_create(type='Provider', slug="provider")
site_node_type, created = NodeType.objects.get_or_create(type='Site', slug="site")
optical_node_node_type, created = NodeType.objects.get_or_create(type='Optical Node', slug="optical-node")
self.provider, created = NodeHandle.objects.get_or_create(
node_name='Default Provider',
node_type=provider_node_type,
node_meta_type='Relation',
creator=self.user,
modifier=self.user,
)
self.site, created = NodeHandle.objects.get_or_create(
node_name='Default Site',
node_type=site_node_type,
node_meta_type='Location',
creator=self.user,
modifier=self.user,
)
self.optical_node, created = NodeHandle.objects.get_or_create(
node_name='Default Optical Node',
node_type=optical_node_node_type,
node_meta_type='Physical',
creator=self.user,
modifier=self.user,
)
|
python
| 9 | 0.57519 | 114 | 49.666667 | 39 |
inline
|
#include
#include
#include "complex_numbers.h"
namespace complex_numbers {
Complex::Complex(double r, double i) : re(r), im(i) {}
Complex Complex::operator+(const Complex& other) const {
Complex sum{re + other.re, im + other.im};
return sum;
}
Complex Complex::operator-(const Complex& other) const {
Complex diff{re - other.re, im - other.im};
return diff;
}
Complex Complex::operator*(const Complex& other) const {
Complex prod{re * other.re - im * other.im, im * other.re + re * other.im};
return prod;
}
Complex Complex::operator/(const Complex& other) const {
Complex quot{(re * other.re + im * other.im) /
(other.re * other.re + other.im * other.im),
(im * other.re - re * other.im) /
(other.re * other.re + other.im * other.im)};
return quot;
}
double Complex::abs() const { return sqrt(re * re + im * im); }
Complex Complex::conj() const {
Complex cx{re, -im};
return cx;
}
double Complex::real() const { return re; }
double Complex::imag() const { return im; }
Complex Complex::exp() const {
Complex ex{std::exp(re) * std::cos(im), std::exp(re) * std::sin(im)};
return ex;
}
bool operator==(const Complex& lhs, const Complex& rhs) {
// Adapted from
// https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon
using std::abs;
using std::ceil;
using std::numeric_limits;
auto almost_equal = [](double x, double y, int ulp) {
// the machine epsilon has to be scaled to the magnitude of the
// values used and multiplied by the desired precision in ULPs
// (units in the last place) unless the result is subnormal
return abs(x - y) <=
numeric_limits * ceil(abs(x + y)) * ulp ||
abs(x - y) < numeric_limits
};
return almost_equal(lhs.real(), rhs.real(), 2) &&
almost_equal(lhs.imag(), rhs.imag(), 2);
}
std::ostream& operator<<(std::ostream& os, Complex const& value) {
os << "(" << value.real() << "," << value.imag() << ")";
return os;
}
} // namespace complex_numbers
|
c++
| 19 | 0.601453 | 80 | 29.178082 | 73 |
starcoderdata
|
#pragma once
#include
#include
//----------------------------------------------------------------------------------------------------
// Default World Map Settings
//----------------------------------------------------------------------------------------------------
static constexpr unsigned int kWorldWidth = 1280;
static constexpr unsigned int kWorldHeight = 720;
//----------------------------------------------------------------------------------------------------
// Default Height Noise and Value Parameters
//----------------------------------------------------------------------------------------------------
static constexpr float kHeightNoiseDivisor = 2.0f;
static constexpr float kHeightNoiseExponent = 0.1f;
static constexpr unsigned int kDefaultHeightOctaves = 6;
static constexpr unsigned int kDefaultHeightInputRange = 2;
static constexpr float kDefaultHeightPersistance = 0.5f;
//----------------------------------------------------------------------------------------------------
// Default Moisture Noise and Value Parameters
//----------------------------------------------------------------------------------------------------
static constexpr unsigned int kDefaultMoistureOctaves = 6;
static constexpr unsigned int kDefaultMoistureInputRange = 15;
static constexpr float kDefaultMoisturePersistance = 0.5f;
//----------------------------------------------------------------------------------------------------
// Default Tempurature Value Parameters
//----------------------------------------------------------------------------------------------------
static constexpr float kDefaultPoleTempuratureNormal = 0.0f;
static constexpr float kDefaultEquatorTempuratureNormal = 1.0f;
static constexpr float kDefaultTempuratureFalloffExponent = 0.7f;
//----------------------------------------------------------------------------------------------------
// Default Cloud Noise Parameters
//----------------------------------------------------------------------------------------------------
// The dimensions of the generated world in tiles.
static constexpr unsigned int kCloudWidth = kWorldWidth;
static constexpr unsigned int kCloudHeight = kWorldHeight;
static constexpr float kCloudNoiseDivisor = 2.0f;
static constexpr float kCloudNoiseExponent = 8.0f;
static constexpr unsigned int kDefaultCloudOctaves = 6;
static constexpr unsigned int kDefaultCloudInputRange = 2;
static constexpr float kDefaultCloudPersistance = 0.5f;
//----------------------------------------------------------------------------------------------------
// Default Cloud Gameplay Parameters
//----------------------------------------------------------------------------------------------------
static constexpr float kCloudScrollSpeedMin = 20.0f;
static constexpr float kCloudScrollSpeedMax = 70.0f;
//----------------------------------------------------------------------------------------------------
// Default Fire Gameplay Parameters
//----------------------------------------------------------------------------------------------------
static constexpr float kFireLifetime = 1.0f;
static constexpr float kFireTickTime = 0.1f;
// The chance a tile has to catch fire at game start.
static constexpr float kGrasslandCombustionChance = 0.00001f;
static constexpr float kForestCombustionChance = 0.0001f;
static constexpr float kSavannaCombustionChance = 0.0005f;
static constexpr float kSwampCombustionChance = 0.000001f;
// The chance a tile has to catch fire when adjacent to a burning tile.
static constexpr float kGrasslandBurnChance = 0.03f;
static constexpr float kForestBurnChance = 0.04f;
static constexpr float kSavannaBurnChance = 0.05f;
static constexpr float kSwampBurnChance = 0.005f;
//----------------------------------------------------------------------------------------------------
// Cellular Automata - Rocks, Trees, and Cliff chances.
//----------------------------------------------------------------------------------------------------
static constexpr int kNumCellularAutomataIterations = 10;
static constexpr float kSaltGrassToRockChance = 0.0025f;
static constexpr float kSaltGrassToTreeChance = 0.005f;
static constexpr float kSaltSavannaToRockChance = 0.005f;
static constexpr float kSaltSavannaToCliffChance = 0.01f;
static constexpr float kSaltSnowtoRockChance = 0.005f;
static constexpr float kSaltSnowtoTreeChance = 0.01f;
static constexpr float kSaltDesertToRockChance = 0.001f;
static constexpr float kSaltGlacierToRockChance = 0.001f;
static constexpr float kSaltSwamptoRockChance = 0.001f;
static constexpr float kForestGrowthChance = 0.25f;
static constexpr float kRockGrowthChance = 0.2f;
static constexpr float kCliffGrowthChance = 0.15f;
//----------------------------------------------------------------------------------------------------
// Biome Configuration
//----------------------------------------------------------------------------------------------------
// Height
static constexpr float kMaxHeight = 8000.0f;
static constexpr float kHeightToTempDivisor = 1000.0f;
static constexpr float kOceanRange = 4200.0f;
static constexpr float kReefRange = 4500.0f;
static constexpr float kWaterRange = 1500.0f;
static constexpr float kMountainRange = 6200.0f;
// Tempurature
static constexpr float kHeightToTempRateOfChange = -6.5f;
static constexpr float kTundraRange = -5.0f;
static constexpr float kTaigaRange = 0.0f;
static constexpr float kTemperateRange = 18.0f;
static constexpr float kTropicalRange = 30.0f;
static constexpr float kMaxTemp = 50.0f;
// Moisture
static constexpr float kLandHeightRange = kMaxHeight - kWaterRange;
static constexpr float kDuneMoisture = 250.0f;
static constexpr float kSavannaMoisture = 375.0f;
static constexpr float kSnowMoisture = 500.0f;
static constexpr float kGrasslandMoisture = 600.0f;
static constexpr float kMaxMoisture = 500.0f;
//----------------------------------------------------------------------------------------------------
// Biome Colors
//----------------------------------------------------------------------------------------------------
static constexpr Exelius::Color kOcean = Exelius::Color(81, 92, 129);
static constexpr Exelius::Color kReef = Exelius::Color(79, 100, 146);
static constexpr Exelius::Color kRock = Exelius::Color(125, 125, 125);
static constexpr Exelius::Color kGlacier = Exelius::Color(189, 198, 206);
static constexpr Exelius::Color kSnow = Exelius::Color(160, 183, 168);
static constexpr Exelius::Color kDesert = Exelius::Color(191, 176, 132);
static constexpr Exelius::Color kDunes = Exelius::Color(163, 171, 123);
static constexpr Exelius::Color kCliff = Exelius::Color(139, 123, 95);
static constexpr Exelius::Color kSavanna = Exelius::Color(161, 154, 110);
static constexpr Exelius::Color kGrassland = Exelius::Color(123, 165, 110);
static constexpr Exelius::Color kForest = Exelius::Color(96, 127, 88);
static constexpr Exelius::Color kSwamp = Exelius::Color(123, 148, 129);
static constexpr Exelius::Color kBlackScorch = Exelius::Color(107, 113, 100);
static constexpr Exelius::Color kError = Exelius::Colors::Red;
|
c
| 5 | 0.568919 | 102 | 44.628205 | 156 |
starcoderdata
|
using CHD.Common.Native;
using CHD.Common.Saver;
namespace CHD.Common.Letter.Factory
{
public interface ILetterFactory
where TNativeMessage : NativeMessage
{
ILetter Create(
TNativeMessage message
);
}
}
|
c#
| 8 | 0.643333 | 51 | 21.230769 | 13 |
starcoderdata
|
import {
Fort, MustacheViewEngine
} from 'fortjs';
import {
routes
} from './routes';
import { EjsViewEngine } from './ejs_view_engine';
export class App extends Fort {
constructor() {
super();
this.routes = routes;
this.viewEngine = EjsViewEngine;
}
}
|
javascript
| 9 | 0.612245 | 50 | 17.4375 | 16 |
starcoderdata
|
import Model from '../../database/model';
import schema from '../../../schemas/surveys/stats';
export default () => ({
async start({ database }) {
const stats = new Model(database, 'stats', schema);
stats.hiddenProperties.push('_rssData');
return stats;
}
});
|
javascript
| 12 | 0.628159 | 55 | 26.7 | 10 |
starcoderdata
|
def invert(self, data=None, mesh=None, zWeight=1.0, startModel=None,
**kwargs):
"""Run the full inversion.
Parameters
----------
data : pg.DataContainer
mesh : pg.Mesh [None]
zWeight : float [1.0]
startModel : float | iterable [None]
If set to None fop.createDefaultStartModel(dataValues) is called.
Keyword Arguments
-----------------
forwarded to Inversion.run
Returns
-------
model : array
Model mapped for match the paraDomain Cell markers.
The calculated model is in self.fw.model.
"""
if data is None:
data = self.data
if data is None:
pg.critical('No data given for inversion')
self.applyData(data)
# no mesh given and there is no mesh known .. we create them
if mesh is None and self.mesh is None:
mesh = self.createMesh(data, **kwargs)
# a mesh was given or created so we forward it to the fop
if mesh is not None:
self.setMesh(mesh)
# remove unused keyword argument .. need better kwargfs
self.fop._refineP2 = kwargs.pop('refineP2', False)
dataVals = self._ensureData(self.fop.data)
errorVals = self._ensureError(self.fop.data, dataVals)
if self.fop.mesh() is None:
pg.critical('Please provide a mesh')
# inversion will call this itsself as default behaviour
# if startModel is None:
# startModel = self.fop.createStartModel(dataVals)
# pg._g('invert-dats', dataVals)
# pg._g('invert-err', errVals)
# pg._g('invert-sm', startModel)
kwargs['startModel'] = startModel
self.fop.setRegionProperties('*', zWeight=zWeight)
# Limits is no mesh related argument here or base??
limits = kwargs.pop('limits', None)
if limits is not None:
self.fop.setRegionProperties('*', limits=limits)
self.preRun(**kwargs)
self.fw.run(dataVals, errorVals, **kwargs)
self.postRun(**kwargs)
return self.paraModel(self.fw.model)
|
python
| 10 | 0.575744 | 77 | 29.788732 | 71 |
inline
|
n,*a=map(int,open(0).read().split())
sa = sum(a)
ha = sa/2
x = 0
for i in range(n):
x+=a[i]
if x>=ha:
break
y = sa-x
print(min(abs(x-y),abs((x-a[i])-(y+a[i]))))
|
python
| 12 | 0.511905 | 43 | 15.9 | 10 |
codenet
|
package com.justapp.photofeed.presentation.base;
import com.arellomobile.mvp.MvpView;
/**
* ะะฐะทะพะฒะพะต ะฟัะตะดััะฐะฒะปะตะฝะธะต ะดะปั MVP ัั
ะตะผั ะฒ ะฟัะธะปะพะถะตะฝะธะธ
*
* @author
*/
public interface BaseView extends MvpView {
}
|
java
| 6 | 0.75 | 51 | 17 | 12 |
starcoderdata
|
from datetime import date
from decimal import Decimal
from typing import Dict
from unittest.mock import AsyncMock, ANY, MagicMock
import pytest
from vacations import bl
@pytest.mark.asyncio
async def test_send_ephemeral(monkeypatch) -> None:
mock = AsyncMock(name='async_slack_request')
monkeypatch.setattr(bl, 'async_slack_request', mock)
await bl.send_ephemeral('test')
mock.assert_awaited_once_with(method='chat_postEphemeral', payload=ANY)
# noinspection PyProtectedMember
@pytest.mark.asyncio
async def test_send_notification(monkeypatch) -> None:
mock = AsyncMock(name='async_slack_request')
monkeypatch.setattr(bl, 'async_slack_request', mock)
await bl._send_notification('test')
mock.assert_awaited_once_with(method='chat_postMessage', payload=ANY)
# noinspection PyProtectedMember
@pytest.mark.asyncio
async def test_notify_admins(monkeypatch, test_command_metadata: Dict) -> None:
mock_builder = MagicMock(name='build_admin_request_notification')
blocks = mock_builder.return_value = [
{
'type': 'section',
'text': {
'type': 'mrkdwn',
'text': 'some text'
}
}
]
monkeypatch.setattr(bl, 'build_admin_request_notification', mock_builder)
mock_notification = AsyncMock(name='build_admin_request_notification')
monkeypatch.setattr(bl, '_send_notification', mock_notification)
await bl._notify_admins(
'vacation',
date.today(),
date.today(),
1,
10,
'reason',
'asdasdasd'
)
mock_builder.assert_called_once()
mock_notification.assert_awaited_once_with(
blocks[0]['text']['text'],
blocks,
bl.ADMIN_CHANNEL
)
@pytest.mark.asyncio
async def test_open_request_view(
test_command_metadata: Dict,
monkeypatch
) -> None:
mock_get_days = AsyncMock(name='get_days_by_user_id')
monkeypatch.setattr(bl, 'get_days_by_user_id', mock_get_days)
mock_builder = MagicMock(name='build_request_view')
view = mock_builder.return_value = {}
monkeypatch.setattr(bl, 'build_request_view', mock_builder)
mock_slack = AsyncMock(name='async_slack_request')
monkeypatch.setattr(bl, 'async_slack_request', mock_slack)
await bl.open_request_view(None)
mock_slack.assert_awaited_once_with(
method='views_open',
payload={
'trigger_id': test_command_metadata['trigger_id'],
'view': view
}
)
def test_parse_request_view(test_action_metadata: Dict) -> None:
leave_type, date_from, date_to, reason = bl.parse_request_view()
assert leave_type == 'test'
assert date_from == date(2020, 10, 31)
assert date_to == date(2020, 10, 31)
assert reason == 'asdasd'
@pytest.mark.asyncio
async def test_approve_request(monkeypatch, test_request: Dict) -> None:
mock_process = AsyncMock(name='_process_request')
mock_process.return_value = test_request
monkeypatch.setattr(bl, '_process_request', mock_process)
mock_increase = AsyncMock(name='increase_days_by_user')
monkeypatch.setattr(bl, 'increase_days_by_user', mock_increase)
request_id = '123'
users = 'users'
history = 'history'
await bl.approve_request(history, users, request_id)
mock_process.assert_awaited_once_with(history, request_id, 'approved')
mock_increase.assert_awaited_once_with(
users,
test_request['leave_type'],
Decimal(-test_request['duration']),
test_request['user_id']
)
@pytest.mark.asyncio
async def test_deny_request(monkeypatch) -> None:
mock_process = AsyncMock(name='_process_request')
monkeypatch.setattr(bl, '_process_request', mock_process)
request_id = '123'
history = 'history'
await bl.deny_request(history, request_id)
mock_process.assert_awaited_once_with(history, request_id, 'denied')
@pytest.mark.asyncio
async def test_create_request_invalid_leave_type_fails(
test_command_metadata: Dict,
monkeypatch
) -> None:
mock = AsyncMock(name='send_ephemeral')
monkeypatch.setattr(bl, 'send_ephemeral', mock)
await bl.create_request(None, None, 'asd', None, None, '')
mock.assert_awaited_once()
@pytest.mark.asyncio
async def test_create_request(
test_command_metadata: Dict,
monkeypatch
) -> None:
mock_get_days = AsyncMock(name='get_days_by_user_id')
monkeypatch.setattr(bl, 'get_days_by_user_id', mock_get_days)
mock_save = AsyncMock(name='save_request')
mock_save.return_value = '123asd'
monkeypatch.setattr(bl, 'save_request', mock_save)
mock_send = AsyncMock(name='_send_notification')
monkeypatch.setattr(bl, '_send_notification', mock_send)
mock_notify = AsyncMock(name='_notify_admins')
monkeypatch.setattr(bl, '_notify_admins', mock_notify)
users = 'users'
history = 'history'
await bl.create_request(
history,
users,
'test',
date.today(),
date.today(),
''
)
mock_get_days.assert_awaited_once()
mock_save.assert_awaited_once()
mock_send.assert_awaited_once()
mock_notify.assert_awaited_once()
# noinspection PyProtectedMember
@pytest.mark.asyncio
async def test_process_request(
test_action_metadata: Dict,
test_request: Dict,
monkeypatch
) -> None:
mock_get_request = AsyncMock(name='get_request_by_id')
mock_get_request.return_value = test_request
monkeypatch.setattr(bl, 'get_request_by_id', mock_get_request)
mock_update = AsyncMock(name='update_request_status')
monkeypatch.setattr(bl, 'update_request_status', mock_update)
mock_send = AsyncMock(name='_send_notification')
monkeypatch.setattr(bl, '_send_notification', mock_send)
await bl._process_request(None, test_request['_id'], 'approved')
mock_update.assert_awaited_once()
assert mock_send.await_count == 2
|
python
| 13 | 0.663308 | 79 | 28.924623 | 199 |
starcoderdata
|
<?php
namespace Proprios\Http\Controllers\API;
use Proprios\Http\Requests\API\CreateLegislacaoTipoAPIRequest;
use Proprios\Http\Requests\API\UpdateLegislacaoTipoAPIRequest;
use Proprios\Models\LegislacaoTipo;
use Proprios\Repositories\LegislacaoTipoRepository;
use Illuminate\Http\Request;
use Proprios\Http\Controllers\AppBaseController;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;
/**
* Class LegislacaoTipoController
* @package Proprios\Http\Controllers\API
*/
class LegislacaoTipoAPIController extends AppBaseController
{
/** @var LegislacaoTipoRepository */
private $legislacaoTipoRepository;
public function __construct(LegislacaoTipoRepository $legislacaoTipoRepo)
{
$this->legislacaoTipoRepository = $legislacaoTipoRepo;
}
/**
* Display a listing of the LegislacaoTipo.
* GET|HEAD /legislacaoTipos
*
* @param Request $request
* @return Response
*/
public function index(Request $request)
{
$this->legislacaoTipoRepository->pushCriteria(new RequestCriteria($request));
$this->legislacaoTipoRepository->pushCriteria(new LimitOffsetCriteria($request));
$legislacaoTipos = $this->legislacaoTipoRepository->all();
return $this->sendResponse($legislacaoTipos->toArray(), 'Legislacao Tipos retrieved successfully');
}
/**
* Store a newly created LegislacaoTipo in storage.
* POST /legislacaoTipos
*
* @param CreateLegislacaoTipoAPIRequest $request
*
* @return Response
*/
public function store(CreateLegislacaoTipoAPIRequest $request)
{
$input = $request->all();
$legislacaoTipos = $this->legislacaoTipoRepository->create($input);
return $this->sendResponse($legislacaoTipos->toArray(), 'Legislacao Tipo saved successfully');
}
/**
* Display the specified LegislacaoTipo.
* GET|HEAD /legislacaoTipos/{id}
*
* @param int $id
*
* @return Response
*/
public function show($id)
{
/** @var LegislacaoTipo $legislacaoTipo */
$legislacaoTipo = $this->legislacaoTipoRepository->findWithoutFail($id);
if (empty($legislacaoTipo)) {
return $this->sendError('Legislacao Tipo not found');
}
return $this->sendResponse($legislacaoTipo->toArray(), 'Legislacao Tipo retrieved successfully');
}
/**
* Update the specified LegislacaoTipo in storage.
* PUT/PATCH /legislacaoTipos/{id}
*
* @param int $id
* @param UpdateLegislacaoTipoAPIRequest $request
*
* @return Response
*/
public function update($id, UpdateLegislacaoTipoAPIRequest $request)
{
$input = $request->all();
/** @var LegislacaoTipo $legislacaoTipo */
$legislacaoTipo = $this->legislacaoTipoRepository->findWithoutFail($id);
if (empty($legislacaoTipo)) {
return $this->sendError('Legislacao Tipo not found');
}
$legislacaoTipo = $this->legislacaoTipoRepository->update($input, $id);
return $this->sendResponse($legislacaoTipo->toArray(), 'LegislacaoTipo updated successfully');
}
/**
* Remove the specified LegislacaoTipo from storage.
* DELETE /legislacaoTipos/{id}
*
* @param int $id
*
* @return Response
*/
public function destroy($id)
{
/** @var LegislacaoTipo $legislacaoTipo */
$legislacaoTipo = $this->legislacaoTipoRepository->findWithoutFail($id);
if (empty($legislacaoTipo)) {
return $this->sendError('Legislacao Tipo not found');
}
$legislacaoTipo->delete();
return $this->sendResponse($id, 'Legislacao Tipo deleted successfully');
}
}
|
php
| 13 | 0.666579 | 107 | 28.550388 | 129 |
starcoderdata
|
var VALIDATORS = [];
var MODELS = [];
var SPECIALTY_FORMS = [];
var SPECIALTY_INTAKE_FORMS = [];
var SPECIALTY;
var AC_SPECIALTY = 'ac';
var AM_SPECIALTY = 'am';
var PASSWORD_RESET="
var BH_SPECIALTY = 'bh';
var DOM_SPECIALTY = 'dom';
var PMD_SPECIALTY = 'pmd';
var POT_SPECIALTY = 'pot';
var GP_SPECIALTY = 'gp';
var PRACTICE;
var AAC_EVAL_TYPE = 'aac';
var ACTIVE = "active";
var CANCEL = "cancel";
var CANCELLED_LETTER_MODE = "cancelled_letter_mode";
var CLIENT_STATUS_AUTHORIZED = 1;
var CLIENT_STATUS_NOT_FOUND = 0;
var CLIENT_STATUS_INVALID_PASSWORD = -1;
var CLIENT_STATUS_INACTIVE = -2;
var CLIENT_STATUS_PASSWORD_ALREADY_CREATED = -3;
var CLIENT_STATUS_RECOVERY_CODE_EXPIRED = -4;
var CLIENT_STATUS_RECOVERY_CODE_ALREADY_USED = -5;
var CLIENT_STATUS_ACTIVATION_CODE_EXPIRED = -6;
var CLIENT_STATUS_ACTIVATION_CODE_ALREADY_USED = -7;
var PENDING_TRANSACTION="pending_transaction";
var NOTIFICATION_TEXT;
var CLINICAL = "clinical";
var CONS = "cons";
var CREATE = "create";
var CLOSED = true;
var DECREASE = "decrease";
var DEFAULT_APP_PATH = "/cfpm/";
var DELETE = "delete";
var DELETED = "deleted";
var DRAFT = true;
var DO_AUTO_LOGOUT = true;
var DO_AUTO_SERVER_LOGOUT = true;
var DO_RELOAD = true;
var DO_SCROLL = true;
var DONT_SCROLL = false;
var EDIT = "edit";
var EVAL = "eval";
var FORM_CLOSE = "close";
var FORM_DELETE = "delete";
var FORM_OPEN = "open";
var INCREASE = "increase";
var INTEGER_TYPE = "integer";
var IS_PATIENT = true;
var LETTER_READ = 'read';
var LETTER_SAVED = 'saved';
var MESSAGE_DELETED = 'deleted';
var MESSAGE_INBOX = 'inbox';
var MESSAGE_DRAFT = 'draft';
var MESSAGE_SAVED = 'saved';
var MESSAGE_SENT = 'sent';
var MESSAGE_COMPOSE = 'message-compose-btn';
var MESSAGE_TYPE_GENERAL = 1;
var MESSAGE_TYPE_MEDICAL_ADVICE = 2;
var MESSAGE_TYPE_RX_RENEWAL = 3;
var MESSAGE_TYPE_APPT_REQUEST = 4;
var MESSAGE_TYPE_INITIAL_APPT_REQUEST = 5;
var NEW = "new";
var NEW_LETTER_MODE = "new_letter_mode";
var NO_PRINT = false;
var NOT_A_RELOAD = false;
var NOT_CLOSED = false;
var NOT_DRAFT = false;
var NOT_PATIENT = false;
var NOT_READING_MESSAGE = false;
var OFFICE = "office";
var ONE_MINUTE = 60000;
var ONE_SECOND = 1000;
var OT_EVAL_TYPE = 'ot';
var PAID = "paid";
var PATIENT_CLIENT_TYPE = "patient";
var PM_MODULE = "pm";
var PRINT = true;
var PORTAL_MODULE = "portal";
var PASSWORD_PLACEHOLDER = '
var PROFILE_PLACEHOLDER_SM="assets/images/headshot_placeholder_sm.jpg";
var READING_MESSAGE = true;
var RESOLVED = "resolved";
var RETURN_CODE_DUP_EMAIL = -1;
var RETURN_CODE_INVALID_PASSWORD = -3;
var RETURN_CODE_INVALID_SSN = -3;
var RETURN_CODE_DUP_USERNAME = -1;
var RETURN_CODE_DUP_USER_EMAIL = -3;
var RETURN_CODE_VALID = 1;
var SAVED = 'saved';
var SENT = "sent";
var SENT_LETTER_MODE = "sent_letter_mode";
var SPEECH_EVAL_TYPE = 'speech';
var SITE_MODULE = "site";
var STORE_MODULE = "store";
var TEXT_TYPE= "text";
var TX = "tx";
var UPDATE = "update";
var USER_ACTIVE = 1;
var USER_CLIENT_TYPE = "user";
var VIEW = "view";
var VIEW_LETTER_MODE = "view_letter_mode";
var app_aacEval;
var app_aacIntake;
var app_intakeFormValidators;
var app_activityLogClinicianSearchTypeAheads;
var app_activityLogPatientSearchTypeAheads;
var app_activityLogs;
var app_adminScreenCache;
var app_adminScreenItemCache;
var app_appointmentsCache;
var app_apptTypes;
var app_billingTicket= null;
var app_billingTicketEntry;
var app_billingTicketEntryId;
var app_calendar = null;
var app_calendarView = 'month';
var app_card = null;
var app_client = null;
var app_clientFullName;
var app_clientProperties;
var app_clientType;
var app_clinicianActivityTypeAheads;
var app_clinicianInfo;
var app_clinicianLocations;
var app_clinicianPatients;
var app_clinicianPatientsSelectOptions;
var app_clinicians;
var app_credentials;
var app_dashboardCache;
var app_date;
var app_evalMode = null;
var app_fbabipId;
var app_finalScreenButton;
var app_finalScreenNumber;
var app_form = null;
var app_formClassName;
var app_formId;
var app_formNewInstanceId;
var app_forms = {};
var app_gender;
var app_goalBankItem;
var app_goalBankItemId;
var app_goalBankItems;
var app_groupByPatientsLog;
var app_guardian = null;
var app_guardianLastNameTypeAheads;
var app_guardians;
var app_headerFooterCache;
var app_hideElementListCache;
var app_idleInterval;
var app_idleTime = 0;
var app_formError;
var app_intakeFormIndices = [];
var app_invoice;
var app_invoiceId;
var app_leadMgmtCache;
var app_letter = null;
var app_letterId;
var app_lettersCache;
var app_locations;
var app_ltg
var app_message;
var app_messageMailbox;
var app_messages;
var app_messageBCCRecipientsInput;
var app_messagesCache;
var app_messageCCRecipientsInput;
var app_messagePrimaryRecipientsInput;
var app_messageValidRecipientsInput;
var app_module;
var app_missingFields = [];
var app_notificationText;
var app_openFormId = null;
var app_otEvals = null;
var app_otIntakes = null;
var app_otProgs = null;
var app_otTxs = null;
var app_parkWarningDisplayed;
var app_patient = null;
var app_patientForm = null;
var app_patientFormId;
var app_patientFullName;
var app_patientId;
var app_patientProfileImage;
var app_patientChartCache;
var app_patientChartItemCache;
var app_patientClinicians;
var app_patientForms;
var app_patientInfo;
var app_patientIntake;
var app_patientIntakeId;
var app_patientInvoices;
var app_patientLetters;
var app_patients;
var app_patientSearchTypeAheads;
var app_potPatientForms;
var app_practiceClientProperties;
var app_practiceForms;
var app_previousScreen;
var app_profileImageTempPath = "";
var app_programs;
var app_reportList;
var app_reportName;
var app_reportsCache;
var app_reportTitle;
var app_roles;
var app_rxRenewalCache;
var app_scheduleCache;
var app_screen;
var app_selectedClinician;
var app_sendMessageCache;
var app_settingsCache;
var app_signinCache;
var app_specialtyClientProperties;
var app_speechEval;
var app_speechIntake;
var app_stgDescriptions = null;
var app_templateFormPrefix;
var app_templateFormName;
var app_templateFormTitle;
var app_templateScreenName;
var app_templateClassName;
var app_txNote;
var app_txNotes;
var app_validMessageRecipients;
var app_userDashboard;
var app_userLocations;
var app_users;
var app_guardian;
var app_usStates;
var app_cptModifiers;
var app_waitListPatients;
var app_yourRecordsCache;
var app_pm_nestedFormOffsetClass;
var app_patientEncounter;
|
javascript
| 3 | 0.759369 | 71 | 25.353909 | 243 |
starcoderdata
|
๏ปฟusing System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
namespace UCalc.Data
{
public class RecentlyOpenedItem
{
public string DisplayText { get; }
public string Path { get; }
public RecentlyOpenedItem(string path)
{
DisplayText = System.IO.Path.GetFileNameWithoutExtension(path);
Path = path;
}
private bool Equals(RecentlyOpenedItem other)
{
return DisplayText == other.DisplayText && Path == other.Path;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == GetType() && Equals((RecentlyOpenedItem) obj);
}
public override int GetHashCode()
{
return HashCode.Combine(DisplayText, Path);
}
public override string ToString()
{
return DisplayText;
}
}
public class RecentlyOpenedList : ICollection INotifyCollectionChanged
{
private const int MaxCount = 10;
private readonly string _path;
private readonly List _list;
public RecentlyOpenedList(string path)
{
_path = path;
_list = new List
Load(path);
}
private void Load(string path)
{
try
{
var lines = File.ReadAllLines(path);
_list.AddRange(lines.Where(itemPath => itemPath != "").Take(MaxCount)
.Select(itemPath => new RecentlyOpenedItem(itemPath)));
}
catch (IOException)
{
// Do nothing
}
}
private void Store(string path)
{
try
{
File.WriteAllLines(path, _list.Select(item => item.Path));
}
catch (IOException)
{
// Do nothing
}
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
public IEnumerator GetEnumerator()
{
return _list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _list.GetEnumerator();
}
public void Add(RecentlyOpenedItem item)
{
var index = _list.IndexOf(item);
if (index != -1)
{
_list.RemoveAt(index);
}
_list.Insert(0, item);
if (_list.Count > MaxCount)
{
_list.RemoveAt(MaxCount);
}
Store(_path);
}
public void Clear()
{
_list.Clear();
Store(_path);
}
public bool Contains(RecentlyOpenedItem item)
{
return _list.Contains(item);
}
public void CopyTo(RecentlyOpenedItem[] array, int arrayIndex)
{
_list.CopyTo(array, arrayIndex);
}
public bool Remove(RecentlyOpenedItem item)
{
var result = _list.Remove(item);
Store(_path);
return result;
}
public int Count => _list.Count;
public bool IsReadOnly => false;
public event NotifyCollectionChangedEventHandler CollectionChanged;
}
}
|
c#
| 23 | 0.53177 | 119 | 24.296552 | 145 |
starcoderdata
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
function measurePaint(test) {
test.tracingCategories = 'blink';
test.traceEventsToMeasure = [
'LocalFrameView::RunPrePaintLifecyclePhase',
'LocalFrameView::RunPaintLifecyclePhase'
];
PerfTestRunner.measureFrameTime(test);
}
|
javascript
| 7 | 0.758621 | 73 | 32.833333 | 12 |
starcoderdata
|
/*
* (C) Copyright 2006-2009 Nuxeo SA (http://nuxeo.com/) and others.
*
* 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.
*
* Contributors:
* Nuxeo - initial API and implementation
*
* $Id$
*/
package org.nuxeo.ecm.platform.preview.converters;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.nuxeo.ecm.core.api.Blob;
import org.nuxeo.ecm.core.api.blobholder.BlobHolder;
import org.nuxeo.ecm.core.convert.api.ConversionException;
import org.nuxeo.ecm.core.convert.api.ConversionService;
import org.nuxeo.ecm.core.convert.api.ConverterCheckResult;
import org.nuxeo.ecm.core.convert.extension.ConverterDescriptor;
import org.nuxeo.ecm.core.convert.extension.ExternalConverter;
import org.nuxeo.runtime.api.Framework;
public class HtmlPreviewConverter implements ExternalConverter {
/**
* @deprecated since 11.1. Use {@link Framework#getService(Class)} with {@link ConversionService} instead.
*/
@Deprecated
protected static ConversionService cs;
protected static Boolean canUsePDF2Html;
protected static Boolean canUseOOo2Html;
/**
* @deprecated since 11.1. Use {@link Framework#getService(Class)} with {@link ConversionService} instead.
*/
@Deprecated
protected static ConversionService getConversionService() {
if (cs == null) {
cs = Framework.getService(ConversionService.class);
}
return cs;
}
protected static boolean getCanUsePDF2Html() {
if (canUsePDF2Html == null) {
try {
canUsePDF2Html = Framework.getService(ConversionService.class)
.isConverterAvailable("pdf2html")
.isAvailable();
} catch (ConversionException e) {
return false;
}
}
return canUsePDF2Html;
}
protected static boolean getCanUseOOo2Html() {
if (canUseOOo2Html == null) {
try {
canUseOOo2Html = Framework.getService(ConversionService.class)
.isConverterAvailable("office2html")
.isAvailable();
} catch (ConversionException e) {
return false;
}
}
return canUseOOo2Html;
}
protected List getConverterChain(String srcMT) {
List subConverters = new ArrayList<>();
if (srcMT == null) {
return null;
}
if (srcMT.equals("text/html") || srcMT.equals("text/xml") || srcMT.equals("text/xhtml")) {
return subConverters;
}
if (getCanUsePDF2Html()) {
if (srcMT.equals("application/pdf")) {
subConverters.add("pdf2html");
} else {
subConverters.add("any2pdf");
subConverters.add("pdf2html");
}
} else {
if (getCanUseOOo2Html()) {
subConverters.add("office2html");
} else {
return null;
}
}
return subConverters;
}
@Override
public BlobHolder convert(BlobHolder blobHolder, Map<String, Serializable> parameters) throws ConversionException {
Blob sourceBlob = blobHolder.getBlob();
List subConverters = getConverterChain(sourceBlob.getMimeType());
if (subConverters == null) {
throw new ConversionException("Can not find suitable underlying converters to handle html preview",
blobHolder);
}
BlobHolder result = blobHolder;
for (String converterName : subConverters) {
result = Framework.getService(ConversionService.class).convert(converterName, result, parameters);
}
Blob blob = result.getBlob();
if (blob != null && blob.getEncoding() == null) {
blob.setEncoding("UTF-8");
}
return result;
}
@Override
public void init(ConverterDescriptor descriptor) {
// TODO Auto-generated method stub
}
@Override
public ConverterCheckResult isConverterAvailable() {
ConverterCheckResult result = new ConverterCheckResult();
result.setAvailable(getCanUseOOo2Html() || getCanUsePDF2Html());
return result;
}
}
|
java
| 16 | 0.62041 | 119 | 31.215686 | 153 |
starcoderdata
|
/********************************************************************
created: 2013/12/08
filename: BladeUI_blang.h
author: Crazii
purpose:
*********************************************************************/
#ifndef __Blade_BladeUI_blang_h__
#define __Blade_BladeUI_blang_h__
#include
#define BLANG_INPUT_SETTING "Input Setting"
#define BLANG_KEYBOARD_API "Keyboard API"
#define BLANG_MOUSE_API "Mouse API"
#define BLANG_TOUCH_API "Touch API"
#endif // __Blade_BladeUI_blang_h__
|
c
| 3 | 0.514981 | 70 | 32.4375 | 16 |
starcoderdata
|
func newIdentsCall(scopeVar string, newIdents []*ast.Ident, isConst bool) ast.Stmt {
if scopeVar == "" {
scopeVar = idents.scope
}
f := "Declare"
if isConst {
f = "Constant"
}
expr := newCallStmt(scopeVar, f)
call := expr.X.(*ast.CallExpr)
call.Args = make([]ast.Expr, 2*len(newIdents))
for i, ident := range newIdents {
// Quoted identifier name.
call.Args[2*i] = newStringLit(strconv.Quote(ident.Name))
if isConst {
// Pass the value if constant. Cast it if it doesn't fit an int32.
call.Args[2*i+1] = castIfOverflow(ident)
} else {
// Pass a pointer if variable.
call.Args[2*i+1] = &ast.UnaryExpr{
Op: token.AND,
X: ident,
}
}
}
return expr
}
|
go
| 15 | 0.640288 | 84 | 23.857143 | 28 |
inline
|
#include
int tak(int x, int y, int z) {
return y < x
? tak(tak(x - 1, y, z), tak(y - 1, z, x), tak(z - 1, x, y))
: z;
}
int main() {
std::cout << tak(30, 22, 12) << std::endl;
}
|
c++
| 10 | 0.446512 | 67 | 18.545455 | 11 |
starcoderdata
|
pub(crate) fn run(self) {
let raw = self.raw;
mem::forget(self);
// Transfer one ref-count to a Task object.
let task = Task::<S> {
raw,
_p: PhantomData,
};
// Use the other ref-count to poll the task.
raw.poll();
// Decrement our extra ref-count
drop(task);
}
|
rust
| 7 | 0.480663 | 52 | 23.2 | 15 |
inline
|
def get_closest_point(points, point):
""" Get the closest point in an array of points to the given point. """
if len(points) == 1:
return 0, points[0]
min_dist = None
min_pt = None
min_i = None
for i, pt in enumerate(points):
v = [point[j] - pt[j] for j in range(0, 3)]
dist = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])
if (min_dist is None) or (dist < min_dist):
min_dist = dist
min_pt = pt
min_i = i
return min_i, min_pt
|
python
| 13 | 0.513566 | 75 | 31.3125 | 16 |
inline
|
/*
-------------------------------------------------------------------------------
This file is part of Eris Engine
-------------------------------------------------------------------------------
Copyright (c) 2017
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-------------------------------------------------------------------------------
*/
#ifndef _BASE__CALLBACK_LIST_H
#define _BASE__CALLBACK_LIST_H
#include
#include
#include
#include
namespace Detail {
template <typename FuncSig>
class CallbackListBase {
public:
using Function = std::function
using FunctionList = std::list
using Registration = typename FunctionList::iterator;
protected:
FunctionList callbackList;
public:
Registration Register(Function func) {
callbackList.push_front(func);
return std::begin(callbackList);
}
using iterator = typename FunctionList::iterator;
using const_iterator = typename FunctionList::const_iterator;
iterator begin() { return std::begin(callbackList); }
const_iterator begin() const { return std::begin(callbackList); }
iterator end() { return std::end(callbackList); }
const_iterator end() const { return std::end(callbackList); }
auto Size() const { return callbackList.size(); }
};
} // namespace Detail
template <typename FuncSig, bool AllowUnregisterDuringCallAll>
class CallbackList;
template <typename FuncSig>
class CallbackList<FuncSig, false> : public Detail::CallbackListBase {
using Base = Detail::CallbackListBase
#ifndef NDEBUG
bool inCallAll = false;
#endif
public:
template <typename... Args>
void CallAll(Args &&... args) {
#ifndef NDEBUG
inCallAll = true;
#endif
for (auto &callback : this->callbackList)
callback(std::forward
#ifndef NDEBUG
inCallAll = false;
#endif
}
void Unregister(typename Base::Registration registration) {
#ifndef NDEBUG
assert(!inCallAll);
#endif
this->callbackList.erase(registration);
}
};
template <typename FuncSig>
class CallbackList<FuncSig, true> : public Detail::CallbackListBase {
using Base = Detail::CallbackListBase
std::vector<typename Base::Registration> toUnregister;
bool inCallAll = false;
void UnregisterPending() {
for (auto reg : toUnregister)
this->callbackList.erase(reg);
toUnregister.clear();
}
public:
template <typename... Args>
void CallAll(Args &&... args) {
inCallAll = true;
for (auto &callback : this->callbackList)
callback(std::forward
inCallAll = false;
UnregisterPending();
}
void Unregister(typename Base::Registration registration) {
if (!inCallAll) {
this->callbackList.erase(registration);
return;
}
// We are currently calling the callbacks, and thus it is dangerous to
// erase an element. Instead we wait until the callbacks are done being
// called and then remove it
toUnregister.push_back(registration);
}
};
#endif // _BASE__CALLBACK_LIST_H
|
c
| 15 | 0.692703 | 79 | 29.251852 | 135 |
starcoderdata
|
// license:BSD-3-Clause
// copyright-holders:
/***************************************************************************
1943 Video Hardware
This board handles tile/tile and tile/sprite priority with a PROM. Its
working is hardcoded in the driver.
The PROM have address inputs wired as follows:
A0 bg (SCR) opaque
A1 bit 2 of sprite (OBJ) attribute (guess)
A2 bit 3 of sprite (OBJ) attribute (guess)
A3 sprite (OBJ) opaque
A4 fg (CHAR) opaque
A5 wired to mass
A6 wired to mass
A7 wired to mass
2 bits of the output selects the active layer, it can be:
(output & 0x03)
0 bg2 (SCR2)
1 bg (SCR)
2 sprite (OBJ)
3 fg (CHAR)
other 2 bits (output & 0x0c) unknown
***************************************************************************/
#include "emu.h"
#include "includes/1943.h"
/***************************************************************************
Convert the color PROMs into a more useable format.
1943 has three 256x4 palette PROMs (one per gun) and a lot ;-) of 256x4
lookup table PROMs.
The palette PROMs are connected to the RGB output this way:
bit 3 -- 220 ohm resistor -- RED/GREEN/BLUE
-- 470 ohm resistor -- RED/GREEN/BLUE
-- 1 kohm resistor -- RED/GREEN/BLUE
bit 0 -- 2.2kohm resistor -- RED/GREEN/BLUE
***************************************************************************/
PALETTE_INIT_MEMBER(_1943_state,1943)
{
const uint8_t *color_prom = memregion("proms")->base();
int i;
for (i = 0; i < 0x100; i++)
{
int bit0, bit1, bit2, bit3;
int r, g, b;
/* red component */
bit0 = (color_prom[i + 0x000] >> 0) & 0x01;
bit1 = (color_prom[i + 0x000] >> 1) & 0x01;
bit2 = (color_prom[i + 0x000] >> 2) & 0x01;
bit3 = (color_prom[i + 0x000] >> 3) & 0x01;
r = 0x0e * bit0 + 0x1f * bit1 + 0x43 * bit2 + 0x8f * bit3;
/* green component */
bit0 = (color_prom[i + 0x100] >> 0) & 0x01;
bit1 = (color_prom[i + 0x100] >> 1) & 0x01;
bit2 = (color_prom[i + 0x100] >> 2) & 0x01;
bit3 = (color_prom[i + 0x100] >> 3) & 0x01;
g = 0x0e * bit0 + 0x1f * bit1 + 0x43 * bit2 + 0x8f * bit3;
/* blue component */
bit0 = (color_prom[i + 0x200] >> 0) & 0x01;
bit1 = (color_prom[i + 0x200] >> 1) & 0x01;
bit2 = (color_prom[i + 0x200] >> 2) & 0x01;
bit3 = (color_prom[i + 0x200] >> 3) & 0x01;
b = 0x0e * bit0 + 0x1f * bit1 + 0x43 * bit2 + 0x8f * bit3;
palette.set_indirect_color(i, rgb_t(r, g, b));
}
/* color_prom now points to the beginning of the lookup table */
color_prom += 0x300;
/* characters use colors 0x40-0x4f */
for (i = 0x00; i < 0x80; i++)
{
uint8_t ctabentry = (color_prom[i] & 0x0f) | 0x40;
palette.set_pen_indirect(i, ctabentry);
}
/* foreground tiles use colors 0x00-0x3f */
for (i = 0x80; i < 0x180; i++)
{
uint8_t ctabentry = ((color_prom[0x200 + (i - 0x080)] & 0x03) << 4) |
((color_prom[0x100 + (i - 0x080)] & 0x0f) << 0);
palette.set_pen_indirect(i, ctabentry);
}
/* background tiles also use colors 0x00-0x3f */
for (i = 0x180; i < 0x280; i++)
{
uint8_t ctabentry = ((color_prom[0x400 + (i - 0x180)] & 0x03) << 4) |
((color_prom[0x300 + (i - 0x180)] & 0x0f) << 0);
palette.set_pen_indirect(i, ctabentry);
}
/* sprites use colors 0x80-0xff
bit 3 of BMPROM.07 selects priority over the background,
but we handle it differently for speed reasons */
for (i = 0x280; i < 0x380; i++)
{
uint8_t ctabentry = ((color_prom[0x600 + (i - 0x280)] & 0x07) << 4) |
((color_prom[0x500 + (i - 0x280)] & 0x0f) << 0) | 0x80;
palette.set_pen_indirect(i, ctabentry);
}
}
WRITE8_MEMBER(_1943_state::c1943_videoram_w)
{
m_videoram[offset] = data;
m_fg_tilemap->mark_tile_dirty(offset);
}
WRITE8_MEMBER(_1943_state::c1943_colorram_w)
{
m_colorram[offset] = data;
m_fg_tilemap->mark_tile_dirty(offset);
}
WRITE8_MEMBER(_1943_state::c1943_c804_w)
{
/* bits 0 and 1 are coin counters */
machine().bookkeeping().coin_counter_w(0, data & 0x01);
machine().bookkeeping().coin_counter_w(1, data & 0x02);
/* bits 2, 3 and 4 select the ROM bank */
membank("bank1")->set_entry((data & 0x1c) >> 2);
/* bit 5 resets the sound CPU - we ignore it */
/* bit 6 flips screen */
flip_screen_set(data & 0x40);
/* bit 7 enables characters */
m_char_on = data & 0x80;
}
WRITE8_MEMBER(_1943_state::c1943_d806_w)
{
/* bit 4 enables bg 1 */
m_bg1_on = data & 0x10;
/* bit 5 enables bg 2 */
m_bg2_on = data & 0x20;
/* bit 6 enables sprites */
m_obj_on = data & 0x40;
}
TILE_GET_INFO_MEMBER(_1943_state::c1943_get_bg2_tile_info)
{
uint8_t *tilerom = memregion("gfx5")->base() + 0x8000;
int offs = tile_index * 2;
int attr = tilerom[offs + 1];
int code = tilerom[offs];
int color = (attr & 0x3c) >> 2;
int flags = TILE_FLIPYX((attr & 0xc0) >> 6);
SET_TILE_INFO_MEMBER(2, code, color, flags);
}
TILE_GET_INFO_MEMBER(_1943_state::c1943_get_bg_tile_info)
{
uint8_t *tilerom = memregion("gfx5")->base();
int offs = tile_index * 2;
int attr = tilerom[offs + 1];
int code = tilerom[offs] + ((attr & 0x01) << 8);
int color = (attr & 0x3c) >> 2;
int flags = TILE_FLIPYX((attr & 0xc0) >> 6);
tileinfo.group = color;
SET_TILE_INFO_MEMBER(1, code, color, flags);
}
TILE_GET_INFO_MEMBER(_1943_state::c1943_get_fg_tile_info)
{
int attr = m_colorram[tile_index];
int code = m_videoram[tile_index] + ((attr & 0xe0) << 3);
int color = attr & 0x1f;
SET_TILE_INFO_MEMBER(0, code, color, 0);
}
void _1943_state::video_start()
{
m_bg2_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(FUNC(_1943_state::c1943_get_bg2_tile_info),this), TILEMAP_SCAN_COLS, 32, 32, 2048, 8);
m_bg_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(FUNC(_1943_state::c1943_get_bg_tile_info),this), TILEMAP_SCAN_COLS, 32, 32, 2048, 8);
m_fg_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(FUNC(_1943_state::c1943_get_fg_tile_info),this), TILEMAP_SCAN_ROWS, 8, 8, 32, 32);
m_bg_tilemap->configure_groups(*m_gfxdecode->gfx(1), 0x0f);
m_fg_tilemap->set_transparent_pen(0);
save_item(NAME(m_char_on));
save_item(NAME(m_obj_on));
save_item(NAME(m_bg1_on));
save_item(NAME(m_bg2_on));
}
void _1943_state::draw_sprites( bitmap_ind16 &bitmap, const rectangle &cliprect, int priority )
{
int offs;
for (offs = m_spriteram.bytes() - 32; offs >= 0; offs -= 32)
{
int attr = m_spriteram[offs + 1];
int code = m_spriteram[offs] + ((attr & 0xe0) << 3);
int color = attr & 0x0f;
int sx = m_spriteram[offs + 3] - ((attr & 0x10) << 4);
int sy = m_spriteram[offs + 2];
if (flip_screen())
{
sx = 240 - sx;
sy = 240 - sy;
}
// the priority is actually selected by bit 3 of BMPROM.07
if (priority)
{
if (color != 0x0a && color != 0x0b)
m_gfxdecode->gfx(3)->transpen(bitmap,cliprect, code, color, flip_screen(), flip_screen(), sx, sy, 0);
}
else
{
if (color == 0x0a || color == 0x0b)
m_gfxdecode->gfx(3)->transpen(bitmap,cliprect, code, color, flip_screen(), flip_screen(), sx, sy, 0);
}
}
}
uint32_t _1943_state::screen_update_1943(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
{
m_bg2_tilemap->set_scrollx(0, m_bgscrollx[0] + 256 * m_bgscrollx[1]);
m_bg_tilemap->set_scrollx(0, m_scrollx[0] + 256 * m_scrollx[1]);
m_bg_tilemap->set_scrolly(0, m_scrolly[0]);
if (m_bg2_on)
m_bg2_tilemap->draw(screen, bitmap, cliprect, 0, 0);
else
bitmap.fill(m_palette->black_pen(), cliprect);
if (m_obj_on)
draw_sprites(bitmap, cliprect, 0);
if (m_bg1_on)
m_bg_tilemap->draw(screen, bitmap, cliprect, 0, 0);
if (m_obj_on)
draw_sprites(bitmap, cliprect, 1);
if (m_char_on)
m_fg_tilemap->draw(screen, bitmap, cliprect, 0, 0);
return 0;
}
|
c++
| 17 | 0.60449 | 171 | 27.374074 | 270 |
starcoderdata
|
mt2App.service( 'ClientGroupApiService' , function ( $http ) {
var self = this;
self.pagerApiUrl = '/api/pager/ClientGroup';
self.mt1ApiUrl = '/api/mt1/clientgroup';
self.baseApiUrl = '/api/clientgroup';
self.getClientGroup = function ( groupId , successCallback , failureCallback ) {
$http( {
"method" : "GET" ,
"url" : self.mt1ApiUrl + '/' + groupId
} ).then( successCallback , failureCallback );
};
self.getClientGroups = function ( page , count , sortField , successCallback , failureCallback ) {
var sort = { 'field' : sortField , 'desc' : false };
if (/^\-/.test( sortField ) ) {
sort.field = sort.field.substring( 1 );
sort.desc = true;
}
return $http( {
"method" : "GET" ,
"url" : self.pagerApiUrl ,
"params" : { "page" : page , "count" : count , "sort" : sort }
} ).then( successCallback , failureCallback );
};
self.getAllClientGroups = function ( successCallback , failureCallback ) {
$http( {
"method" : "GET" ,
"url" : self.baseApiUrl + "/all"
} ).then( successCallback , failureCallback );
};
self.getClients = function ( groupID , successCallback , failureCallback ) {
$http( {
"method" : "GET" ,
"url" : self.mt1ApiUrl + '/clients/' + groupID
} ).then( successCallback , failureCallback );
}
self.createClientGroup = function ( groupData , successCallback , failureCallback ) {
$http( {
"method" : "POST" ,
"url" : self.baseApiUrl ,
"data" : groupData
} ).then( successCallback , failureCallback );
};
self.updateClientGroup = function ( groupData , successCallback ,failureCallback ) {
$http( {
"method" : "PUT" ,
"url" : self.baseApiUrl + '/' + groupData.gid ,
"params" : { "_method" : "PUT" } ,
"data" : groupData
} ).then( successCallback , failureCallback );
};
self.copyClientGroup = function ( groupId , successCallback , failureCallback ) {
$http( {
"method" : "GET" ,
"url" : self.baseApiUrl + '/copy/' + groupId ,
} ).then( successCallback , failureCallback );
};
self.deleteClientGroup = function ( groupId , successCallback , failureCallback ) {
$http( {
"method" : "DELETE" ,
"url" : self.baseApiUrl + '/' + groupId
} ).then( successCallback , failureCallback );
};
} );
|
javascript
| 20 | 0.538934 | 102 | 34.22973 | 74 |
starcoderdata
|
package com.trico.salyut.engine;
import com.trico.salyut.token.SToken;
import java.util.List;
import java.util.Objects;
public class Statements<T extends SToken> {
private List tokenList;
private int moveIndex;
private T curTok;
private boolean eof;
public static <T extends SToken> Statements of(List tokenList){
Objects.requireNonNull(tokenList);
return new Statements<>(tokenList);
}
private Statements(List tokenList){
this.tokenList = tokenList;
}
public T curTok(){
return curTok;
}
public T getNextTok(){
return this.curTok = getTok();
}
private T getTok(){
if (moveIndex == tokenList.size()){
this.eof = true;
return null;
}
return tokenList.get(moveIndex++);
}
public boolean isEOF(){
return eof;
}
public void rollback(){
moveIndex = 0;
eof = false;
}
}
|
java
| 10 | 0.597938 | 73 | 19.638298 | 47 |
starcoderdata
|
public void unloadBuffer(int index, boolean saveFirst) {
CompletableFuture.runAsync(() -> {
ChunkBuffer buf = buffers.getAndSet(index, null); // Get buffer, set it to null
// Once used mark gets to zero, we can unload
while (true) { // Spin loop until used < 1
Thread.onSpinWait();
int used = getUsedCount(index);
if (used < 1) {
break;
}
}
// Finally, unload
buf.unload();
// And then buffer "wrapper" object is left for GC to claim
}, executor);
}
|
java
| 14 | 0.486154 | 91 | 37.294118 | 17 |
inline
|
#pragma once
#include "vec3.h"
struct ray
{
struct vec3 source;
struct vec3 direction;
};
|
c
| 5 | 0.688 | 26 | 11.5 | 10 |
starcoderdata
|
๏ปฟusing Nest;
using Sikiro.Tookits.Base;
namespace Sikiro.Elasticsearch.Extension
{
public static class ResponseExtension
{
public static ApiResult GetApiResult<T, TResult>(this ISearchResponse searchResponse)
where T : class, new() where TResult : class, new()
{
return searchResponse.ApiCall.Success
? ApiResult
: ApiResult
}
public static ApiResult GetApiResult(this CreateResponse createResponse)
{
return createResponse.ApiCall.Success
? ApiResult.IsSuccess()
: ApiResult.IsFailed(createResponse.ApiCall.OriginalException.Message);
}
}
}
|
c#
| 15 | 0.661502 | 105 | 35.478261 | 23 |
starcoderdata
|
#include "familytree.h"
#include
#include
void fill(tree *node, int level){
node->left = NULL;
node->right = NULL;
node->id = g_node_id;
sprintf(node->name, "%s%d", names[g_node_id % 31], g_node_id/31);
node->data = (123*(g_node_id + node->name[1] * g_node_id / 31)) % 9113;
node->IQ = 0;
g_node_id++;
if (level < MAXLEVEL-1) {
node->right = malloc(sizeof(tree));
node->left = malloc(sizeof(tree));
fill(node->right, level+1);
fill(node->left, level+1);
}
}
void initialize(tree *node) {
g_node_id = 0;
fill(node, 0);
}
void tearDown(tree* node) {
if (node != NULL) {
if (node->left != NULL) tearDown(node->left);
if (node->right != NULL) tearDown(node->right);
free(node);
}
}
int is_prime(int n){
int i, flag = 1;
for(i=2; i<=n/2; ++i){
if(n%i==0){
flag=0;
break;
}
}
return flag;
}
int compute_IQ(int data){
// nothing meaningfull, just a function that is kind of computationally expensive
// such that parallelising makes sense :)
int i; int sum = 0;
for(i = 0; i < data; i++){
if(is_prime(i))
sum++;
}
return 70 + (sum % 100)*(sum % 100)*(sum % 100)*(sum % 100)/1000000;
}
|
c
| 14 | 0.58214 | 82 | 17.84127 | 63 |
starcoderdata
|
๏ปฟusing System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace PanRepro
{
public partial class MyPage : ContentPage
{
public MyPage()
{
Pos = "Text";
InitializeComponent();
var gest = new PanGestureRecognizer();
grid.GestureRecognizers.Add(gest);
grid2.GestureRecognizers.Add(gest);
gest.PanUpdated += Gest_PanUpdated;
}
public string Pos { get; set; }
private void Gest_PanUpdated(object sender, PanUpdatedEventArgs e)
{
if (e.StatusType == GestureStatus.Completed)
return;
Pos = e.TotalX + " " + e.TotalY;
foreach (var kid in grid.Children)
{
((Label)kid).Text = Pos;
}
foreach (var kid in grid2.Children)
{
((Label)kid).Text = Pos;
}
}
}
}
|
c#
| 14 | 0.511603 | 74 | 24.621622 | 37 |
starcoderdata
|
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface
# from itemadapter import ItemAdapter
import telegram_send
from datetime import datetime
class Crawlerps5Pipeline:
def process_item(self, item, spider):
if item['price']:
telegram_send.send(messages=[f"Produto {item['name']} encontrado por {item['price']} na url abaixo: \n\n {item['url']}"])
else:
current_date = datetime.now()
current_hour = current_date.hour
current_minute = current_date.minute
# Checks if bot has run for 24h (every 7 am)
if current_hour == 9 and current_minute <= 1:
telegram_send.send(messages=["Bot ativo por 24h, produto ainda nรฃo encontrado"])
if not item['name']:
telegram_send.send(messages=["Ocorreu um erro ao buscar o produto, verificar no site"])
|
python
| 16 | 0.665129 | 133 | 36.37931 | 29 |
starcoderdata
|
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/vr/skia_surface_provider_factory.h"
#include "chrome/browser/vr/cmd_buffer_surface_provider.h"
namespace vr {
std::unique_ptr SkiaSurfaceProviderFactory::Create() {
return std::make_unique
}
} // namespace vr
|
c++
| 11 | 0.763676 | 75 | 29.466667 | 15 |
starcoderdata
|
#!/usr/bin/env python3
# vim: ts=2 sw=2 sts=2 et tw=81:
"""
Recursive k=2 division of data. Centroids picked via
random projection.
- License: (c) 2021 MIT License
"""
import re, math, random
from it import it
from csv import csv
from functools import cmp_to_key
import matplotlib.pyplot as plt
def eg1():
random.seed(1)
t= Tab(fast=False)
for row in csv("../data/auto93.csv"): t.add(row)
rows = t.ordered()
for row in rows[:5 ]: print(row.uses())
print("")
for row in rows[-5:]: print(row.uses())
def eg2():
random.seed(1)
t= Tab(fast=True)
for row in csv("../data/auto93.csv"): t.add(row)
rows = t.ordered()
for n,row in enumerate(rows):
row.gt = n/len(rows)
show(t.cluster(),t)
def eg3():
random.seed(1)
t= Tab(fast=False)
for row in csv("../data/auto93.csv"):
t.add(row)
assert 398== len(t.rows)
t1 = t.clone(t.rows)
#print(len(t1.rows))
assert 398== len(t1.rows)
#print(t.ymid())
assert int is type(t.rows[1].cells[4])
a=t.rows[1]
c=t.rows[-1]
b,_=a.furthest(t.rows,t)
for n,row in enumerate(t.ordered()):
row.gt = n/len(t.rows)
for n,rows in enumerate(leaves(t.cluster())):
avg = sum(row.gt for row in rows)/len(rows)
for row in rows:
print(f"{row.x}\t{row.y}\t{avg}")
def Row(lst):
def uses(i): return [i.cells[col.pos] for col in i._tab.uses()]
def gt(i,j,tab):
s1,s2,n = 0,0,len(tab.cols.y)
for col in tab.cols.y:
pos,w = col.pos, col.w
a,b = i.cells[pos], j.cells[pos]
a,b = col.norm(a), col.norm(b)
s1 -= math.e**(w*(a-b)/n)
s2 -= math.e**(w*(b-a)/n)
return s1/n < s2/n
def dist(i,j,tab):
d,n = 0,0
for c in tab.uses():
a,b = i.cells[c.pos], j.cells[c.pos]
a,b = c.norm(a), c.norm(b)
d += (a-b)**tab.p
n += 1
return (d/n)**(1/tab.p)
def furthest(i,rows,tab):
hi = -1
for j in rows:
tmp = i.dist(j,tab)
if tmp > hi: hi,out = tmp, j
return out,hi
return it(cells=lst,x=None,y=None,gt=0) + locals()
def plus(i,x):
if x != "?":
i.n += 1; i.add(x)
return x
def Skip(pos=0, txt="", w=1):
def add(i,x): return x
return it(pos=pos, txt=txt, w=w, n=0) + locals()
def Sym(pos=0, txt="", w=1):
def mid(i): return i.mode
def add(i,x,n=1):
now = i.seen[x] = i.seen.get(x, 0) + n
if now > i.most: i.most, i.mode = now, x
return x
return it(pos=pos, txt=txt, w=w, n=0, seen={}, most=0, mode=None) + locals()
def Num(pos=0, txt="", w=1):
def add(i, x): i._all += [x]; i.ok=False
def mid(i) : n,a = _all(i); return a[int(n/2)]
def var(i) : n,a = _all(i); return (a[int(.9*n)] - a[int(n/10)]) / 2.56
def norm(i,x): _,a = _all(i); return (x - a[0]) / (a[-1] - a[0])
def _all(i) :
i._all = i._all if i.ok else sorted(i._all)
i.ok = True
return len(i._all), i._all
return it(pos=pos, txt=txt, w=w, n=0, ok=False, _all=[]) + locals()
def Cols():
def add(i,pos,txt):
weight = -1 if "-" in txt else 1
where = ([] if "?" in txt else (i.y if txt[-1] in "+-" else i.x))
what = (Skip if "?" in txt else (Num if txt[0].isupper() else Sym))
now = what(pos,txt,weight)
where += [now]
i.all += [now]
return it(all=[],x=[],y=[]) + locals()
def Tab(using="y",p=2, fast=False):
def adds(i,src) : return [add(i,row) for row in src]; return i
def cluster(i) : return tree(i.rows, i, fast)
def makeCols(i,a) : return [i.cols.add(pos,txt) for pos,txt in enumerate(a)]
def makeRow(i,a) : return Row([plus(col,x) for col,x in zip(i.cols.all,a)])
def mid(i) : return [col.mid() for col in i.cols.all]
def uses(i) : return i.cols[i.using]
def ymid(i) : return [col.mid() for col in i.cols.y]
def ordered(i) : return sorted(i.rows, key=cmp_to_key(ordered1(i)))
def ordered1(i) :
return lambda a,b: (0 if id(a)==id(b) else (1 if a.gt(b,i) else -1))
def clone(i,inits=[]):
j = Tab(using=i.using, p=i.p, fast=i.fast)
j.add( i.header )
[j.add(row) for row in inits]
return j
def add(i,a) :
if i.cols.all:
a = a if type(a) == list else a.cells
assert len(a) == len(i.cols.all), "wrong number of cells"
i.rows += [i.makeRow(a)]
else:
i.makeCols(a)
i.header=a
return it(header=[], rows=[], cols=Cols(),using=using,p=2,fast=fast) + locals()
def tree(rows0, root, fast):
def worker(rows, lo, lvl):
if len(rows) > lo*2:
up0, down0, here = div(rows, lvl,root,fast)
here.down = worker(down0, lo, lvl+1)
here.up = worker(up0, lo, lvl+1)
return here
#rows0 = [random.choice(rows0) for _ in range(256)]
return worker(rows0, len(rows0)**.5, 0)
def div(rows, lvl,root,fast):
def twoFarPoints(rows):
if fast:
anyone = random.choice(rows)
north,_ = anyone.furthest(rows,root)
south, c = north.furthest(rows,root)
else:
c=-1
for m,one in enumerate(rows):
for n,two in enumerate(rows):
if n > m:
tmp = one.dist(two,root)
if tmp > c:
north, south, c = one, two, tmp
return north, south, c
###################################
north,south,c = twoFarPoints(rows)
tmp = []
for row in rows:
a,b = row.dist(north,root), row.dist(south,root)
x = max(0, min(1, (a**2 + c**2 - b**2)/(2*c)))
y = (a**2 - x**2)**.5
if lvl==0: row.x,row.y = x,y
tmp += [(x, row)]
mid = len(tmp) // 2
rows = [z[-1] for z in sorted(tmp,key=lambda z:z[0])]
north,south = rows[:mid], rows[mid:]
xs = sorted(tmp, key=lambda z:z[1].x)
ys = sorted(tmp, key=lambda z:z[1].y)
return north, south, it(
_rows=rows, north=north, south=south, c=c, up=None, down=None,
x0= xs[0][0], xmid= xs[mid][0], x1= xs[-1][0],
y0= xs[0][1], ymid= xs[mid][1], y1= xs[-1][1])
def stats(t,rows):
header= [Num(pos=col.pos, txt=col.txt) for col in t.cols.y]
for row in rows:
[col.add(row.cells[col.pos]) for col in header]
heads= ' '.join([f"{col.txt:>5}"
for col in header])
mids = ' '.join([f"{col.mid():5}" for col in header])
return heads,mids
def show(here,t, lvl=0,all=None, id=0):
if here:
heads, mids= stats(t,here._rows)
if not all:
all = len(here._rows)
print("\n %n %wins "+heads+"\n")
if here:
if not here.up and not here.down:
avg = int(100*sum(row.gt for row in here._rows)/len(here._rows))
n = int(100*len(here._rows)/all)
c = ("abcdefghijklmnopqrstuvwxyz"\
+"ABCDEFGHIJKLMNOPQRSTUVWXYZ")[id]
id += 1
print(f"{c:2} {n:3} {avg:3} "+mids) #+ " " + "|.. "*lvl)
id = show(here.up, t, lvl+1, all, id)
id = show(here.down,t, lvl+1, all, id)
return id
def leaves(tree):
if tree.up:
for x in leaves(tree.up) : yield x
for x in leaves(tree.down): yield x
else:
yield tree._rows
def fastmap(src):
with open(file) as fp:
for a in fp:
yield [atom(x) for x in re.sub(ignore, '', a).split(sep)]
#__name__ == "__main__" and anExample()
#__name__ == "__main__" and anExample()
__name__ == "__main__" and eg3()
|
python
| 19 | 0.545743 | 81 | 29.707627 | 236 |
starcoderdata
|
ERROR_RANGE_PERCENTAGE_DB: float = 0.5
MEASURE_FOR_TEXTS_WITHOUT_CONTEXTS: float = 0.8
MEASURE_TO_COLUMN_KEY_REFERS_TO_NAMES: float = 0.75
MINIMAL_UPPER_CHAR_DENSITY: float = 0.8
MAXIMUM_NUMBER_OF_ELEMENTS_IN_A_REGEX: int = 4000
SAMPLE_DATA_TO_CHOOSE_NAMES:float = 0.25
MAXIMUM_NUMBER_OF_POSSIBLE_NAMES_FOR_A_QUERY: float = 100
|
python
| 4 | 0.674479 | 57 | 34 | 11 |
starcoderdata
|
import util from './util'
const window = util.getGlobal()
const message = {}
const _self = window.name || '_parent'
const _listeners = []
const _key = 'MSG|'
const _queue = []
// for post message and onmessage event
message.addMsgListener = function (cb) {
_listeners.push(cb)
}
const onMessage = function (_event) {
for (var i = 0, l = _listeners.length; i < l; i++) {
try {
_listeners[i].call(null, _event)
} catch (e) {}
}
}
const formatOrigin = (function () {
var _reg = /^([\w]+?:\/\/.*?(?=\/|$))/i
return function (_origin) {
_origin = _origin || ''
if (_reg.test(_origin)) {
return RegExp.$1
}
return '*'
}
})()
// ๆฃๆตwindow.nameๅๅๆ
ๅต
const checkWindowName = () => {
// check name
var _name = unescape(window.name || '').trim()
if (!_name || _name.indexOf(_key) !== 0) {
return
}
window.name = ''
// check result
const _result = util.string2object(_name.replace(_key, ''), '|')
const _origin = (_result.origin || '').toLowerCase()
// check origin
if (!!_origin && _origin !== '*' && location.href.toLowerCase().indexOf(_origin) !== 0) {
return
}
// dispatch onmessage event
onMessage({
data: JSON.parse(_result.data || 'null'),
source: window.frames[_result.self] || _result.self,
origin: formatOrigin(_result.ref || document.referrer)
})
}
const checkNameQueue = (function () {
var _checklist
var _hasItem = function (_list, _item) {
for (var i = 0, l = _list.length; i < l; i++) {
if (_list[i] === _item) {
return !0
}
}
return !1
}
return function () {
if (!_queue.length) return
_checklist = []
for (var i = _queue.length - 1, _map; i >= 0; i--) {
_map = _queue[i]
if (!_hasItem(_checklist, _map.w)) {
_checklist.push(_map.w)
_queue.splice(i, 1)
// set window.name
_map.w.name = _map.d
}
}
_checklist = null
}
})()
const startTimer = message.startTimer = (() => {
let flag = false
return () => {
if (!flag) {
flag = true
if (!window.postMessage) {
setInterval(checkNameQueue, 100)
setInterval(checkWindowName, 20)
}
}
}
})()
message.postMessage = (w, options = {}) => {
util.fillUndef(options, {
origin: '*',
source: _self
})
if (!window.postMessage) {
startTimer()
if (util.isObject(options)) {
var _result = {}
_result.origin = options.origin || ''
_result.ref = location.href
_result.self = options.source
_result.data = JSON.stringify(options.data)
options = _key + util.object2string(_result, '|', !0)
}
_queue.unshift({
w,
d: escape(options)
})
} else {
let data = options.data
if (!window.FormData) {
data = JSON.stringify(data)
}
w.postMessage(data, options.origin)
}
}
module.exports = message
|
javascript
| 14 | 0.553725 | 91 | 22.304 | 125 |
starcoderdata
|
import CarouselView from './CarouselView';
export default class Carousel{
constructor(cart, quickView){
this.cart = cart;
this.quickView = quickView;
}
//pass sku from carouselView to cart:
passSkuToCart(sku){
this.cart.addItemToCart(sku, 1);
}
//pass sku from carouselView to QuickView:
passSkuToQV(sku){
this.quickView.receiveSku(sku);
}
}
|
javascript
| 6 | 0.712846 | 44 | 23.8125 | 16 |
starcoderdata
|
def __init__(self, isLiquid = False):
self.isLiquid = isLiquid
quad_size = 1000
x_left = 0
x_right = quad_size
y_down = 0
y_up = quad_size
N = CONSTANTS.SIDE_ELEMENTS_COUNT
nodes, cells, border_nodes_indexes = get_square_circled_triang(N, quad_size) if isLiquid else get_square_triang(N, quad_size)
# define detail border points
self.border_points = [Node(index=1, x=x_left, y=y_down),
Node(index=2, x=x_left, y=y_up),
Node(index=3, x=x_right, y=y_up),
Node(index=4, x=x_right, y=y_down)]
if not isLiquid:
# define point sources
self.source_points = [Node(index=0, x=(x_left + x_right) / 2, y=(y_down + y_up) / 2, q=CONSTANTS.Q_POINT)]
# define detail borders
self.borders = [(self.border_points[0], self.border_points[1]),
(self.border_points[1], self.border_points[2]),
(self.border_points[2], self.border_points[3]),
(self.border_points[3], self.border_points[0])]
self.nodes = [Node(i, node[0], node[1]) for i, node in enumerate(nodes)]
self.elements = [Element(i, self.nodes[cell[0]],
self.nodes[cell[1]], self.nodes[cell[2]]) for i, cell in enumerate(cells)]
if isLiquid:
for i in border_nodes_indexes:
self.nodes[i].t = 0
self.define_border_conditions()
|
python
| 14 | 0.526966 | 133 | 39.526316 | 38 |
inline
|
def __init__(self, get_response):
super().__init__(get_response)
self.cache_expires = getattr(settings, 'APIGW_JWT_PUBLIC_KEY_CACHE_MINUTES', self.CACHE_MINUTES) * 60
self.cache_version = getattr(settings, 'APIGW_JWT_PUBLIC_KEY_CACHE_VERSION', self.CACHE_VERSION)
cache_name = getattr(settings, 'APIGW_JWT_PUBLIC_KEY_CACHE_NAME', self.CACHE_NAME)
# If the cache expires is 0, it does not need to cache
if self.cache_expires:
self.cache = caches[cache_name]
else:
self.cache = DummyCache(cache_name, params={})
|
python
| 12 | 0.641286 | 109 | 48.333333 | 12 |
inline
|
private void OnPointerPressed(object sender, PointerRoutedEventArgs args)
{
GestureRectangle.CapturePointer(args.Pointer);
PointerPoint pointerPoint = args.GetCurrentPoint(Grid);
// Get coordinates relative to the Rectangle.
GeneralTransform transform = Grid.TransformToVisual(GestureRectangle);
_relativePoint = transform.TransformPoint(new Point(pointerPoint.Position.X, pointerPoint.Position.Y));
_gestureRecognizer.ProcessDownEvent(pointerPoint);
}
|
c#
| 14 | 0.703499 | 115 | 44.333333 | 12 |
inline
|
function action(table,history,cellvalue,action){
$.ajax({
type: "POST",
url: "/item-finder/admin/manageApproval",
data: {
"table": table,
"id": cellvalue,
"history": history,
"action": action},
dataType: "json",
success: function(){
}
});
$('#approvalsjqGrid').trigger( 'reloadGrid' );
}
$(document).ready(function () {
$("#usersjqGrid").jqGrid({
styleUI : 'Bootstrap',
datatype: 'json',
mtype: 'GET',
url : 'admin/users',
editurl: 'admin/editUser',
colModel: [
{ label: 'email Id', name: 'emailId', key: true, editable: true, width: 200,editrules : { required: true},edittype:"text"},
{ label: ' name: 'userName', editable: true,editrules : { required: true},edittype:"text"},
{ label: 'User Type', name: 'userType', formatter: statusFormatter},
{ label: 'status', name: 'status'}
],
viewrecords: true,
height: 300,
rowNum: 20,
loadonce: false,
multiselect: true,
width: null,
shrinkToFit: true,
pager: "#usersjqGridPager"
});
function statusFormatter(cellvalue, options, rowObject){
if (cellvalue == 1)
return 'Admin';
else if (cellvalue == 2)
return 'User';
}
$('#usersjqGrid').navGrid('#usersjqGridPager',
{ edit: true, add: true, del: true, search: true, refresh: false, view: false, position: "left", cloneToTop: true },
{
editCaption: "Edit Record",
recreateForm: true,
checkOnUpdate : true,
checkOnSubmit : true,
closeAfterEdit: true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
{
closeAfterAdd: true,
recreateForm: true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
{
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
});
$("#approvalsjqGrid").jqGrid({
styleUI : 'Bootstrap',
datatype: 'json',
mtype: 'GET',
url : 'admin/approvals',
colModel: [
{ label: 'email Id', name: 'userId', key: true},
{ label: 'Approval', name: 'message'},
{ label: 'Actions', name: 'storageId', formatter: actionFormatter}],
viewrecords: true,
height: 300,
rowNum: 20,
loadonce: false,
width: null,
shrinkToFit: true,
pager: "#approvalsjqGridPager"
});
function actionFormatter(cellvalue, options, rowObject){
var message = rowObject.message;
return "<button class='btn btn-success btn-sm actions' onclick=action('"+rowObject.table+"','"+message.replace(/\s+/g,'')+"','"+cellvalue+"','approve')> Approve <button class='btn btn-danger btn-sm actions' onclick=action('"+rowObject.table+"','"+message.replace(/\s+/g,'')+"','"+cellvalue+"','reject')> Decline
}
});
|
javascript
| 22 | 0.60241 | 334 | 28.705263 | 95 |
starcoderdata
|
import React from 'react'
const AboutText = () => (
// <!--Hero Starts-->
<section className="uk-container about-text">
<div className="uk-padding width-100">
<div className="uk-padding-small width-100">
<div className="uk-grid">
<div className="uk-width-1-6@m">
<div className="uk-width-2-3@m">
<h3 className={'section-title '}>Little About Us
<div className="uk-padding-small width-100">
HapRamp is for all the creators,HapRamp is a decentralized social media platform for the creative communities.
If you are a learner, hobbyist, professional or just want to browse through the creativity, HapRamp is for you. Join the communities you are interested in and start exploring.
On HapRamp creators are the owner of their data.A platform with security and privacy as the core properties.
We imagine HapRamp as a place where all the creative communities share their valuable work, earn money, and grow together.
For years we had a dream to create a dedicated platforms for creators which caters to their needs and provides exactly what they need.Join HapRamp and we together will create the most happening platform on the Internet.HapRamp platform is built on STEEM blockchain.
HapRamp.
<div className="uk-padding-small width-100">
);
export default AboutText
|
javascript
| 10 | 0.681462 | 275 | 46.90625 | 32 |
starcoderdata
|
using Roslyn.Compilers.CSharp;
namespace ConsolR.Core.Services
{
internal sealed class ConsoleRewriter : SyntaxRewriter
{
public ConsoleRewriter(string consoleClassName, SemanticModel semanticModel)
{
model = semanticModel;
name = Syntax.IdentifierName(consoleClassName);
}
private readonly SemanticModel model;
private readonly IdentifierNameSyntax name;
protected override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node)
{
var info = model.GetSemanticInfo(node);
var method = (MethodSymbol)info.Symbol;
if (method != null &&
(method.ContainingType != null && method.ContainingType.Name == "Console") &&
(method.ContainingNamespace != null && method.ContainingNamespace.Name == "System") &&
(method.ContainingAssembly != null && method.ContainingAssembly.Name == "mscorlib"))
{
var old = (MemberAccessExpressionSyntax)node.Expression;
return node.ReplaceNode(old, old.Update(name, old.OperatorToken, old.Name));
}
return node;
}
}
}
|
c#
| 17 | 0.739512 | 90 | 28.314286 | 35 |
starcoderdata
|
def __init__(self, mapaX, bloqEnemigo):
self.mapa = mapaX
self.bloqEnemigo = bloqEnemigo
tamaรฑo = self.mapa.shape
self.filMapa = tamaรฑo[0]
self.colMapa = tamaรฑo[1]
self.posEnemigosX = np.array([])
self.posEnemigosY = np.array([])
self.posAntEnemigosX = np.array([])
self.posAntEnemigosY = np.array([])
self.UP = "U"
self.LEFT = "L"
self.DOWN = "D"
self.RIGHT = "R"
self.SAME = "S" # para enemigos que esten encerrados
self.LIBRE = "O"
self.NOLIBRE = "X"
self.rutaReglas = "Reglas/ReglasEnemigos.txt"
self.cargarReglas()
self.reglaAux = np.array([])
self.crearPosEnemigos()
self.crearPosAnteEnemigos()
|
python
| 8 | 0.483184 | 60 | 25.9375 | 32 |
inline
|
D = [("Lambert",34,10.50),("Osborne",22,6.25),("Giacometti",5,100.70)]
print("{}\t{}\t{}".format('Last_Name','Hourly_Wages','Paid_Wages'))
for d in D:
LN,HW,WH=d
PW=HW*WH
Len=len(LN)
if Len<=7:
print("{}\t\t{}\t\t{:.2f}".format(LN,HW,PW))
else:
print("{}\t{}\t\t{:.2f}".format(LN,HW,PW))
|
python
| 13 | 0.515366 | 70 | 17.272727 | 22 |
starcoderdata
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZeldaOracle.Common.Geometry;
using ZeldaOracle.Common.Graphics;
using ZeldaOracle.Common.Scripting;
using ZeldaOracle.Game;
namespace ZeldaOracle.Game.Tiles {
public class TileColorStatue : Tile, IColoredTile, ZeldaAPI.ColorStatue {
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
public TileColorStatue() {
}
//-----------------------------------------------------------------------------
// Static Methods
//-----------------------------------------------------------------------------
/// the properties and events for the tile type.
public static void InitializeTileData(TileData data) {
data.Flags |= TileFlags.Movable;
data.Properties.SetEnumInt("color", PuzzleColor.Red)
.SetDocumentation("Color", "enum", typeof(PuzzleColor), "Color", "The color of the statue.");
}
//-----------------------------------------------------------------------------
// Properties
//-----------------------------------------------------------------------------
public PuzzleColor Color {
get { return Properties.GetEnum PuzzleColor.Red); }
set { }
}
//-----------------------------------------------------------------------------
// API Implementations
//-----------------------------------------------------------------------------
/*ZeldaAPI.Color ZeldaAPI.ColorStatue.Color {
get { return (ZeldaAPI.Color)Properties.Get("color", (int)PuzzleColor.Red); }
}*/
}
}
|
c#
| 14 | 0.446271 | 97 | 30.537037 | 54 |
starcoderdata
|
void declaration_example()
{
// x is represented by an int and scaled down by 1 bit
auto x = fixed_point<int, -1>{3.5};
// another way to specify a fixed-point type is with make_fixed or make_ufixed
auto y = make_fixed<30, 1>{3.5}; // (s30:1)
static_assert(is_same<decltype(x), decltype(y)>::value, ""); // assumes that int is 32-bit
// under the hood, x stores a whole number
cout << x.data() << endl; // "7"
// but it multiplies that whole number by 2^-1 to produce a real number
cout << x << endl; // "3.5"
// like an int, x has limited precision
x /= 2;
cout << x << endl; // "1.5"
}
|
c++
| 9 | 0.591615 | 95 | 32.947368 | 19 |
inline
|
/*
* Copyright 2008-2010 Analog Devices Inc.
*
* Licensed under the GPL-2 or later.
*/
#ifndef _MACH_BLACKFIN_H_
#define _MACH_BLACKFIN_H_
#include "bf518.h"
#include "anomaly.h"
#include
#ifdef CONFIG_BF512
# include "defBF512.h"
#endif
#ifdef CONFIG_BF514
# include "defBF514.h"
#endif
#ifdef CONFIG_BF516
# include "defBF516.h"
#endif
#ifdef CONFIG_BF518
# include "defBF518.h"
#endif
#ifndef __ASSEMBLY__
# include
# ifdef CONFIG_BF512
# include "cdefBF512.h"
# endif
# ifdef CONFIG_BF514
# include "cdefBF514.h"
# endif
# ifdef CONFIG_BF516
# include "cdefBF516.h"
# endif
# ifdef CONFIG_BF518
# include "cdefBF518.h"
# endif
#endif
#endif
|
c
| 6 | 0.720052 | 62 | 16.454545 | 44 |
starcoderdata
|
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.
// Copyright (c) 2017 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef OPENMVG_MATCHING_SVG_MATCHES_HPP
#define OPENMVG_MATCHING_SVG_MATCHES_HPP
#include <string>
#include <utility>
#include <vector>
#include <openMVG/matching/indMatch.hpp>
#include <openMVG/features/feature_container.hpp>
namespace openMVG {
namespace matching {
/**
* @brief Return a string containing the svg file content to display
* a scene containing two images and their feature matches:
* image are exported side by side, feature depicted by circles and
* corresponding features are connected by a line.
*
* @param[in] left_image_path Left image path. For compactness of the output
* svg file the image is exported as a link.
* @param[in] left_image_size Left image size {width,height}.
* @param[in] left_features Left image features.
* @param[in] right_image_path Right image path. For compactness of the output
* svg file the image is exported as a link.
* @param[in] right_image_size Right image size {width,height}.
* @param[in] right_features Right image features.
* @param[in] matches Corresponding features indexes.
* @param[in] b_vertical_display Display images in a vertical or horizontal
* canvas.
* @param[in] feature_circle_radius Radius of the circle used to represent
* the features.
* @param[in] stroke_size Stroke size used to display the line between the
* corresponding features.
*/
std::string Matches2SVGString
(
const std::string & left_image_path,
const std::pair<size_t,size_t> & left_image_size,
const features::PointFeatures & left_features,
const std::string & right_image_path,
const std::pair<size_t,size_t> & right_image_size,
const features::PointFeatures & right_features,
const matching::IndMatches & matches,
const bool b_vertical_display = true,
const double feature_circle_radius = 4.0,
const double stroke_size = 2.0
);
/**
* @brief Saves a svg file containing two images and their feature matches:
* image are exported side by side, feature depicted by circles and
* corresponding features are connected by a line.
*
* @param[in] left_image_path Left image path. For compactness of the output
* svg file the image is exported as a link.
* @param[in] left_image_size Left image size {width,height}.
* @param[in] left_features Left image features.
* @param[in] right_image_path Right image path. For compactness of the output
* svg file the image is exported as a link.
* @param[in] right_image_size Right image size {width,height}.
* @param[in] right_features Right image features.
* @param[in] matches Corresponding features indexes.
* @param[in] b_vertical_display Display images in a vertical or horizontal
* canvas.
* @param[in] svg_filename Path to the output SVG file.
* @param[in] feature_circle_radius Radius of the circle used to represent
* the features.
* @param[in] stroke_size Stroke size used to display the line between the
* corresponding features.
*/
bool Matches2SVG
(
const std::string & left_image_path,
const std::pair<size_t,size_t> & left_image_size,
const features::PointFeatures & left_features,
const std::string & right_image_path,
const std::pair<size_t,size_t> & right_image_size,
const features::PointFeatures & right_features,
const matching::IndMatches & matches,
const std::string & svg_filename,
const bool b_vertical_display = true,
const double feature_circle_radius = 4.0,
const double stroke_size = 2.0
);
/**
* @brief Saves a svg file containing two images and their inlier features
* matches: image are exported side by side, feature depicted by circles and
* corresponding features (inliers) are connected by a line.
*
* @param[in] left_image_path Left image path. For compactness of the output
* svg file the image is exported as a link.
* @param[in] left_image_size Left image size {width,height}.
* @param[in] left_features Left image features.
* @param[in] right_image_path Right image path. For compactness of the output
* svg file the image is exported as a link.
* @param[in] right_image_size Right image size {width,height}.
* @param[in] right_features Right image features.
* @param[in] matches Corresponding features indexes.
* @param[in] inliers Index of the matches array that corresponds to inliers.
* @param[in] b_vertical_display Display images in a vertical or horizontal
* canvas.
* @param[in] svg_filename Path to the output SVG file.
* @param[in] feature_circle_radius Radius of the circle used to represent
* the features.
* @param[in] stroke_size Stroke size used to display the line between the
* corresponding features.
*/
bool InlierMatches2SVG
(
const std::string & left_image_path,
const std::pair<size_t,size_t> & left_image_size,
const features::PointFeatures & left_features,
const std::string & right_image_path,
const std::pair<size_t,size_t> & right_image_size,
const features::PointFeatures & right_features,
const matching::IndMatches & matches,
const std::vector<uint32_t> & inliers,
const std::string & svg_filename,
const bool b_vertical_display = true,
const double feature_circle_radius = 4.0,
const double stroke_size = 2.0
);
} // namespace matching
} // namespace openMVG
#endif // OPENMVG_MATCHING_SVG_MATCHES_HPP
|
c++
| 14 | 0.73009 | 80 | 39.510949 | 137 |
research_code
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GoogleMapsComponents.Maps.Data
{
///
/// google.maps.Data.MouseEvent interface
/// This object is passed to mouse event handlers on a Data object.
/// This interface extends MouseEvent.
///
public class MouseEvent : Maps.MouseEvent
{
public Feature Feature { get; set; }
}
}
|
c#
| 8 | 0.72549 | 114 | 30.166667 | 18 |
starcoderdata
|
@Test(timeout = 30000)
public void testCheckReplicationRetryTask()
throws InterruptedException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
FileNotFoundException, SnapshotInstallException, IOException, LogException {
// Creates 3 members. Sends a command. Waits until a retry has been sent
// to each of the three members three times.
ConcurrentHashMap<MemberId, CountDownLatch> latches = new ConcurrentHashMap<>();
int waitUntilRetryCount = 3;
int membersCount = 3;
Set<MemberId> memberIds = new HashSet<MemberId>();
// One port is left for the leader.
Iterator<Integer> it = NetworkUtils.getRandomFreePorts(membersCount).iterator();
for (int i = 0; i < membersCount - 1; ++i) {
Integer port = it.next();
MemberId memberId = new MemberId("localhost", port);
latches.put(memberId, new CountDownLatch(waitUntilRetryCount));
memberIds.add(memberId);
it.remove();
}
// For the leader last it.next().
Configuration configuration = Configuration.newBuilder().selfId(new MemberId("localhost", it.next())).addMemberIds(memberIds).logUri(URI.create("file:///test")).build();
Injector injector = Guice.createInjector(new Module(configuration));
MemberConnector memberConnector = injector.getInstance(MemberConnector.class);
Log log = new InMemoryLogImpl();
MessageReceiver messageReceiver = mock(MessageReceiver.class);
Mockito.when(messageReceiver.getMemberId()).thenReturn(new MemberId("localhost", NetworkUtils.getRandomFreePort()));
StateMachine stateMachine = mock(StateMachine.class);
ConsensusEventListener raftListener = new ConsensusEventListenerImpl() {
@Override
public void appendEntriesRetryScheduled(MemberId memberId) {
latches.get(memberId).countDown();
}
};
final ConsensusImpl raft = new ConsensusImpl(configuration, memberConnector, messageReceiver, log, stateMachine, 0, MemberRole.Candidate, raftListener);
Method initializeEventLoop = ConsensusImpl.class.getDeclaredMethod("initializeEventLoop", new Class[] {});
initializeEventLoop.setAccessible(true);
initializeEventLoop.invoke(raft, new Object[] {});
Method becomeLeader = ConsensusImpl.class.getDeclaredMethod("becomeLeader", new Class[] {});
becomeLeader.setAccessible(true);
becomeLeader.invoke(raft, new Object[] {});
raft.start();
raft.applyCommand(new byte[0]);
for (CountDownLatch latch : latches.values()) {
latch.await();
}
}
|
java
| 14 | 0.678021 | 177 | 49.727273 | 55 |
inline
|
import React from 'react'
import About from "./style.About";
export default function Index() {
return (
<div className="container">
<div className="Main">
<div className="contain">
Reegram
is a Instagram profile account analyzer and viewer.
uses the Instagram API but is not endorsed or certified by Instagram. All Instagramโข logos and trademarks displayed on this application are property of Instagram
Us
Free Contact Us:
)
}
|
javascript
| 9 | 0.481808 | 204 | 35.28 | 25 |
starcoderdata
|
package no.mnemonic.act.platform.seb.producer.v1.resolvers;
import no.mnemonic.act.platform.dao.cassandra.ObjectManager;
import no.mnemonic.act.platform.dao.cassandra.entity.ObjectTypeEntity;
import no.mnemonic.act.platform.seb.model.v1.ObjectTypeInfoSEB;
import javax.inject.Inject;
import java.util.UUID;
import java.util.function.Function;
public class ObjectTypeInfoDaoResolver implements Function<UUID, ObjectTypeInfoSEB> {
private final ObjectManager objectManager;
@Inject
public ObjectTypeInfoDaoResolver(ObjectManager objectManager) {
this.objectManager = objectManager;
}
@Override
public ObjectTypeInfoSEB apply(UUID id) {
if (id == null) return null;
ObjectTypeEntity type = objectManager.getObjectType(id);
if (type == null) {
return ObjectTypeInfoSEB.builder()
.setId(id)
.setName("N/A")
.build();
}
return ObjectTypeInfoSEB.builder()
.setId(type.getId())
.setName(type.getName())
.build();
}
}
|
java
| 13 | 0.702599 | 85 | 27.081081 | 37 |
starcoderdata
|
func (handler *ReservationHandler) create(c echo.Context) error {
reservation := models.Reservation{}
if err := c.Bind(&reservation); err != nil {
handler.Input.Logger.LogError(err.Error())
return c.JSON(http.StatusBadRequest, nil)
}
lang := getAcceptLanguage(c)
user := getCurrentUser(c)
invalidReservationRequestKeyErr := handler.Input.Translator.Localize(lang, message_keys.InvalidReservationRequestKey)
if strings.TrimSpace(reservation.RequestKey) == "" {
return c.JSON(http.StatusBadRequest,
commons.ApiResponse{
Message: invalidReservationRequestKeyErr,
})
}
reservationRequest, err := handler.Service.FindReservationRequest(reservation.RequestKey)
if err != nil {
return c.JSON(http.StatusInternalServerError, nil)
}
if reservationRequest == nil {
return c.JSON(http.StatusBadRequest,
commons.ApiResponse{
Message: invalidReservationRequestKeyErr,
})
}
if time.Now().After(reservationRequest.ExpireTime) {
return c.JSON(http.StatusBadRequest,
commons.ApiResponse{
Message: invalidReservationRequestKeyErr,
})
}
if len(reservation.Sharers) == 0 {
return c.JSON(http.StatusBadRequest,
commons.ApiResponse{
Message: handler.Input.Translator.Localize(lang, message_keys.EmptySharerError),
})
}
hasReservationConflict, err := handler.Service.HasReservationConflict(reservation.CheckinDate, reservation.CheckoutDate, reservation.RoomId)
if err != nil {
handler.Input.Logger.LogError(err.Error())
return c.JSON(http.StatusBadRequest, nil)
}
if hasReservationConflict {
return c.JSON(http.StatusBadRequest,
commons.ApiResponse{
Message: handler.Input.Translator.Localize(lang, message_keys.ReservationConflictError),
})
}
handler.setReservationFields(&reservation, reservationRequest)
reservation.SetAudit(user)
// create new reservation.
result, err := handler.Service.Create(&reservation)
if err != nil {
handler.Input.Logger.LogError(err.Error())
return c.JSON(http.StatusConflict, commons.ApiResponse{
Message: err.Error(),
})
}
return c.JSON(http.StatusOK, commons.ApiResponse{
Data: result,
Message: handler.Input.Translator.Localize(getAcceptLanguage(c), message_keys.Created),
})
}
|
go
| 17 | 0.754291 | 141 | 29.342466 | 73 |
inline
|
/**
* This file just contains some definitions of functions
* and variables declared in the header files that assist with
* board setup and initialization.
*/
#include "functions.h"
#include "constants.h"
// these are initially declared in constants.h
int32_t ENGINE_TO_REGULAR[BOARD_SQ_NUM];
int32_t REGULAR_TO_ENGINE[STANDARD_BOARD_SIZE];
uint64_t SET_MASK[STANDARD_BOARD_SIZE];
uint64_t CLEAR_MASK[STANDARD_BOARD_SIZE];
uint64_t PIECE_KEYS[13][BOARD_SQ_NUM];
uint64_t SIDE_KEY;
uint64_t CASTLE_KEYS[16];
int32_t FILES_BOARD[BOARD_SQ_NUM];
int32_t RANKS_BOARD[BOARD_SQ_NUM];
uint64_t FILE_BB_MASK[8];
uint64_t RANK_BB_MASK[8];
uint64_t BLACK_PASSED_MASK[STANDARD_BOARD_SIZE];
uint64_t WHITE_PASSED_MASK[STANDARD_BOARD_SIZE];
uint64_t ISOLATED_MASK[STANDARD_BOARD_SIZE];
/**
* Initializes the bitboard masks for pawn evaluation
*/
static void init_eval_masks(void) {
int32_t sq, tsq, rank, file;
// zero out the passed pawn/isolated pawn masks
for(sq = 0; sq < STANDARD_BOARD_SIZE; ++sq) {
ISOLATED_MASK[sq] = 0;
WHITE_PASSED_MASK[sq] = 0;
BLACK_PASSED_MASK[sq] = 0;
}
// initialize them
// you can use the print_bboard function to see what these end up
// being
for(sq = 0; sq < STANDARD_BOARD_SIZE; ++sq) {
tsq = sq + 8;
while(tsq < STANDARD_BOARD_SIZE) {
WHITE_PASSED_MASK[sq] |= (1 << tsq);
tsq += 8;
}
tsq = sq - 8;
while(tsq >= 0) {
BLACK_PASSED_MASK[sq] |= (1 << tsq);
tsq -= 8;
}
if(FILES_BOARD[SQ120(sq)] > FILE_A) {
ISOLATED_MASK[sq] |= FILE_BB_MASK[FILES_BOARD[SQ120(sq)] - 1];
tsq = sq + 7;
while(tsq < 64) {
WHITE_PASSED_MASK[sq] |= (1 << tsq);
tsq += 8;
}
tsq = sq - 9;
while(tsq >= 0) {
BLACK_PASSED_MASK[sq] |= (1 << tsq);
tsq -= 8;
}
}
if(FILES_BOARD[SQ120(sq)] < FILE_H) {
ISOLATED_MASK[sq] |= FILE_BB_MASK[FILES_BOARD[SQ120(sq)] + 1];
tsq = sq + 9;
while(tsq < 64) {
WHITE_PASSED_MASK[sq] |= (1 << tsq);
tsq += 8;
}
tsq = sq - 7;
while(tsq >= 0) {
BLACK_PASSED_MASK[sq] |= (1 << tsq);
tsq -= 8;
}
}
}
// clear out everything
for(sq = 0; sq < 8; ++sq) {
FILE_BB_MASK[sq] = 0;
RANK_BB_MASK[sq] = 0;
}
// set the bits accordingly for the file and bit masks
// going square by square
for(rank = RANK_8; rank >= RANK_1; --rank) {
for(file = FILE_A; file <= FILE_H; ++file) {
sq = rank * 8 + file;
FILE_BB_MASK[file] |= (1 << sq);
RANK_BB_MASK[rank] |= (1 << sq);
}
}
}
/**
* Function to generate a random 64 bit unsigned integer
*/
static uint64_t RAND_64(void) {
uint64_t ret = rand();
ret |= ((uint64_t)rand() << 15);
ret |= ((uint64_t)rand() << 30);
ret |= ((uint64_t)rand() << 45);
ret |= (((uint64_t)rand() & 0xF) << 60);
return ret;
}
/**
* Function to initialize the files and ranks arrays
*/
static void init_files_ranks_arrays(void) {
int32_t index, file, rank, sq;
index = 0, file = FILE_A, rank = RANK_1, sq = A1;
// first, set everything to offboard
// this is so that we just fill in the relevant squares next
for( ; index < BOARD_SQ_NUM; ++index)
FILES_BOARD[index] = RANKS_BOARD[index] = OFFBOARD;
// rank by rank, fill in the coordinates
for(rank = RANK_1; rank <= RANK_8; ++rank) {
for(file = FILE_A; file <= FILE_H; ++file) {
sq = CONVERT_COORDS(file, rank);
FILES_BOARD[sq] = file;
RANKS_BOARD[sq] = rank;
}
}
}
/**
* Function to intialize the random keys
*/
static void init_hashkeys(void) {
for(int32_t ind = 0; ind < 13; ++ind) {
for(int32_t dex = 0; dex < BOARD_SQ_NUM; ++dex) {
PIECE_KEYS[ind][dex] = RAND_64();
}
}
SIDE_KEY = RAND_64();
for(int32_t ind = 0; ind < 16; ++ind) {
CASTLE_KEYS[ind] = RAND_64();
}
}
/**
* Function to initialize the bit mask arrays
*/
static void init_bit_masks(void) {
// zero everything out, to start
memset(SET_MASK, (uint64_t)0, STANDARD_BOARD_SIZE);
memset(CLEAR_MASK, (uint64_t)0, STANDARD_BOARD_SIZE);
// flip flop the clearmask and setmask so that you can actually
// clear and set stuff
for(int32_t index = 0; index < STANDARD_BOARD_SIZE; ++index) {
SET_MASK[index] |= ((uint64_t)1 << index);
CLEAR_MASK[index] = ~SET_MASK[index];
}
}
/**
* Function to initialize our engine and piece arrays
* Clears out the arrays by setting them first to impossible values, then
* continues on by initializing the actual values
*/
static void init_120_to_64(void) {
int32_t square = A1;
int32_t sq64 = 0;
// initialize our placement arrays to impossible values, just to start out
for(int32_t index = 0; index < BOARD_SQ_NUM; ++index)
ENGINE_TO_REGULAR[index] = STANDARD_BOARD_SIZE + 1;
memset(REGULAR_TO_ENGINE, BOARD_SQ_NUM, STANDARD_BOARD_SIZE);
// for each square in the actual board
// fill in the number coordinates for mapping back and forth
for(int32_t rank = RANK_1; rank <= RANK_8; ++rank) {
for(int32_t file = FILE_A; file <= FILE_H; ++file) {
square = CONVERT_COORDS(file, rank);
REGULAR_TO_ENGINE[sq64] = square;
ENGINE_TO_REGULAR[square] = sq64;
++sq64;
}
}
}
/**
* Initialize everything.
* Externally visible function used in the main engine.
*/
void init_all(void) {
init_120_to_64();
init_bit_masks();
init_hashkeys();
init_files_ranks_arrays();
init_eval_masks();
init_MVV_LVA();
}
|
c
| 14 | 0.601678 | 76 | 24.151376 | 218 |
starcoderdata
|
package main
import (
"errors"
"fmt"
"io"
"net/http"
"os"
// "path/filepath"
"github.com/gorilla/mux"
"github.com/satori/go.uuid"
// "github.com/sjsafranek/goutils"
)
func uploadTemplate(message string) string {
return `<!DOCTYPE html>
<form enctype="multipart/form-data" action="/upload" method="POST">
Upload
<input type="file" placeholder="uploadfile" name="uploadfile">
<input type="submit" value="Upload">
+ message + `
}
func formatApiError(err error) string {
return fmt.Sprintf(`{"status":"error", "error": "%v"}`, err.Error())
}
func newAssetId() string {
return fmt.Sprintf("%s", uuid.Must(uuid.NewV4()))
}
func FileUpload(r *http.Request) (string, int) {
r.ParseMultipartForm(32 << 20)
file, handler, err := r.FormFile("uploadfile")
if nil != err {
logger.Error(err)
return formatApiError(err), http.StatusBadRequest
}
defer file.Close()
asset_id := newAssetId()
// ext := filepath.Ext(handler.Filename)
// save_file_name := fmt.Sprintf("%v%v", asset_id, ext)
save_file_name := fmt.Sprintf("%v", asset_id)
f, err := os.OpenFile(ASSETS_DIRECTORY+save_file_name, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
logger.Error(err)
return formatApiError(err), http.StatusInternalServerError
}
defer f.Close()
io.Copy(f, file)
err = Insert(handler.Filename, asset_id)
if nil != err {
logger.Error(err)
return formatApiError(err), http.StatusInternalServerError
}
result, err := Select(asset_id)
if nil != err {
logger.Error(err)
return formatApiError(err), http.StatusInternalServerError
}
return fmt.Sprintf(`{"status":"ok", "data": %v}`, result), http.StatusOK
}
func FileDelete(r *http.Request) (string, int) {
vars := mux.Vars(r)
asset_id, ok := vars["asset_id"]
if ok {
err := Delete(asset_id)
if nil != err {
logger.Error(err)
return formatApiError(err), http.StatusInternalServerError
}
result, err := Select(asset_id)
if nil != err {
logger.Error(err)
return formatApiError(err), http.StatusInternalServerError
}
return fmt.Sprintf(`{"status":"ok", "data": %v}`, result), http.StatusOK
// logger.Debugf("Deleting %v", asset_id)
// if !utils.FileExists(fmt.Sprintf("./%v%v", ASSETS_DIRECTORY, asset_id)) {
// err := errors.New("File not found")
// logger.Error(err)
// return formatApiError(err), http.StatusInternalServerError
// }
//
// result := `"TODO"`
// DELETE FILE
// return fmt.Sprintf(`{"status":"ok", "data": %v}`, result), http.StatusOK
}
err := errors.New("asset_id not provided in url")
logger.Error(err)
return formatApiError(err), http.StatusInternalServerError
}
func FileUploadHandler(w http.ResponseWriter, r *http.Request) {
if "GET" == r.Method {
fmt.Fprintf(w, uploadTemplate(""))
return
}
results, status_code := FileUpload(r)
w.WriteHeader(status_code)
fmt.Fprintf(w, uploadTemplate(results))
}
func ApiV1FileHandler(w http.ResponseWriter, r *http.Request) {
if "GET" == r.Method {
vars := mux.Vars(r)
asset_id, _ := vars["asset_id"]
http.Redirect(w, r, fmt.Sprintf("/asset/%v", asset_id), 200)
return
}
results, status_code := func() (string, int) {
switch r.Method {
case "POST":
return FileUpload(r)
case "DELETE":
return FileDelete(r)
default:
err := errors.New("Method Not Allowed")
logger.Warn(err)
return formatApiError(err), http.StatusMethodNotAllowed
}
}()
w.WriteHeader(status_code)
fmt.Fprintf(w, results)
}
|
go
| 15 | 0.626592 | 93 | 24.288591 | 149 |
starcoderdata
|
<?php
/*
*MIT License
*
*Copyright (c) 2018
*
*Permission is hereby granted, free of charge, to any person obtaining a copy
*of this software and associated documentation files (the "Software"), to deal
*in the Software without restriction, including without limitation the rights
*to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
*copies of the Software, and to permit persons to whom the Software is
*furnished to do so, subject to the following conditions:
*
*The above copyright notice and this permission notice shall be included in all
*copies or substantial portions of the Software.
*
*THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
*AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
*LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
*OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*SOFTWARE.
*
*/
namespace Aspi\Framework\Protocole\Http;
use Psr\Http\Message\ResponseInterface;
use Zend\Diactoros\ServerRequest;
use Zend\Diactoros\ServerRequestFactory;
use Zend\Diactoros\Stream;
use Aspi\Framework\Application\Kernel;
use Pimple\Container;
class WebServer extends \Swoole\Http\Server
{
const CHUNK_SIZE = 1048576;//1M
private $container = null;
public function __construct(Container $container)
{
$this->container = $container;
$port = $this->container['HttpConfig']->get('port');
$host = $this->container['HttpConfig']->get('host');
parent::__construct($host,((int)$port),SWOOLE_PROCESS, SWOOLE_SOCK_TCP);
$this->set(
[
'open_http2_protocol' => 1,
'enable_static_handler' => true,
]);
$this->on('request', [$this, 'onRequest']);
}
public function onRequest(\swoole_http_request $swooleRequest, \swoole_http_response $swooleResponse)
{
//https://github.com/mcfog/lit-swan/blob/master/src/SwanServer.php
//https://github.com/swoole/swoole-src/issues/559
//$this->initSession($swooleRequest,$swooleResponse);
$psrReq = $this->makePsrRequest($swooleRequest);
$app = new Kernel($this->container);
$psrRequest = $app->run($psrReq);
$this->emitResponse($swooleResponse, $psrRequest);
}
private function initSession(\swoole_http_request $swooleRequest, \swoole_http_response $swooleResponse)
{
if (session_status() != PHP_SESSION_ACTIVE) {
session_start();
}
if (isset($swooleRequest->cookie[session_name()])) {
// Client has session cookie set, but Swoole might have session_id() from some
// other request, so we need to regenerate it
session_id($swooleRequest->cookie[session_name()]);
} else {
$params = session_get_cookie_params();
if (session_id()) {
session_id(\bin2hex(\random_bytes(32)));
}
$_SESSION = array();
$swooleResponse->rawcookie(
session_name(),
session_id(),
$params['lifetime'] ? time() + $params['lifetime'] : null,
$params['path'],
$params['domain'],
$params['secure'],
$params['httponly']
);
}
}
private function emitResponse(\swoole_http_response $res, ResponseInterface $psrRequest)
{
$res->status($psrRequest->getStatusCode());
foreach ($psrRequest->getHeaders() as $name => $values) {
foreach ($values as $value) {
$res->header($name, $value);
}
}
$body = $psrRequest->getBody();
$body->rewind();
if ($body->getSize() > static::CHUNK_SIZE) {
while (!$body->eof()) {
$res->write($body->read(static::CHUNK_SIZE));
}
$res->end();
} else {
$res->end($body->getContents());
}
}
/**
*
* @param \swoole_http_request $req
* @return \Psr\Http\Message\ServerRequestInterface
*/
private function makePsrRequest(\swoole_http_request $req): \Psr\Http\Message\ServerRequestInterface
{
//http://paul-m-jones.com/archives/6416
$server = [];
foreach ($req->server as $key => $value) {
$server[strtoupper($key)] = $value;
}
$server = ServerRequestFactory::normalizeServer($server);
$files = isset($req->files)
? ServerRequestFactory::normalizeFiles($req->files)
: [];
$cookies = isset($req->cookie) ? $req->cookie : [];
$query = isset($req->get) ? $req->get : [];
$body = isset($req->post) ? $req->post : [];
$stream = new Stream('php://memory', 'wb+');
$stream->write($req->rawContent());
$stream->rewind();
foreach ($req->header as $key => $value) {
$headers[strtoupper($key)] = $value;
}
$request = new ServerRequest(
$server,
$files,
ServerRequestFactory::marshalUriFromServer($server, $headers),
ServerRequestFactory::get('REQUEST_METHOD', $server, 'GET'),
$stream,
$headers
);
return $request
->withCookieParams($cookies)
->withQueryParams($query)
->withParsedBody($body);
}
}
|
php
| 20 | 0.588277 | 108 | 36.766667 | 150 |
starcoderdata
|
package org.hkijena.jipipe.extensions.imagejalgorithms.ij1.morphology;
import ij.ImagePlus;
import ij.ImageStack;
import inra.ijpb.morphology.Reconstruction3D;
import org.hkijena.jipipe.api.JIPipeCitation;
import org.hkijena.jipipe.api.JIPipeDocumentation;
import org.hkijena.jipipe.api.JIPipeNode;
import org.hkijena.jipipe.api.JIPipeProgressInfo;
import org.hkijena.jipipe.api.nodes.*;
import org.hkijena.jipipe.api.nodes.categories.ImagesNodeTypeCategory;
import org.hkijena.jipipe.api.parameters.JIPipeParameter;
import org.hkijena.jipipe.extensions.imagejalgorithms.ij1.Neighborhood2D;
import org.hkijena.jipipe.extensions.imagejdatatypes.datatypes.d3.greyscale.ImagePlus3DGreyscaleData;
import org.hkijena.jipipe.extensions.imagejdatatypes.datatypes.d3.greyscale.ImagePlus3DGreyscaleMaskData;
import org.hkijena.jipipe.extensions.imagejdatatypes.util.ImageJUtils;
import org.hkijena.jipipe.extensions.parameters.library.primitives.BooleanParameterSettings;
@JIPipeDocumentation(name = "Morphological reconstruction 3D", description = "Geodesic reconstruction repeats conditional dilations or erosions until idempotence. " +
"Two images are required: the marker image, used to initialize the reconstruction, an the mask image, used to constrain the reconstruction. " +
"More information: https://imagej.net/plugins/morpholibj")
@JIPipeCitation("https://imagej.net/plugins/morpholibj")
@JIPipeNode(nodeTypeCategory = ImagesNodeTypeCategory.class, menuPath = "Morphology")
@JIPipeInputSlot(value = ImagePlus3DGreyscaleData.class, slotName = "Marker", autoCreate = true)
@JIPipeInputSlot(value = ImagePlus3DGreyscaleMaskData.class, slotName = "Mask", autoCreate = true)
@JIPipeOutputSlot(value = ImagePlus3DGreyscaleData.class, slotName = "Output", autoCreate = true)
@JIPipeCitation(" & (2016), \"MorphoLibJ: integrated library and plugins for mathematical morphology with ImageJ\", " +
"Bioinformatics (Oxford Univ Press) 32(22): 3532-3534, PMID 27412086, doi:10.1093/bioinformatics/btw413")
public class MorphologicalReconstruction3DAlgorithm extends JIPipeIteratingAlgorithm {
private boolean applyDilation = true;
private Neighborhood2D connectivity = Neighborhood2D.FourConnected;
public MorphologicalReconstruction3DAlgorithm(JIPipeNodeInfo info) {
super(info);
}
public MorphologicalReconstruction3DAlgorithm(MorphologicalReconstruction3DAlgorithm other) {
super(other);
this.applyDilation = other.applyDilation;
this.connectivity = other.connectivity;
}
@JIPipeDocumentation(name = "Type of reconstruction", description = "Determines which type of reconstruction is applied")
@BooleanParameterSettings(comboBoxStyle = true, trueLabel = "By dilation", falseLabel = "By erosion")
@JIPipeParameter("apply-dilation")
public boolean isApplyDilation() {
return applyDilation;
}
@JIPipeParameter("apply-dilation")
public void setApplyDilation(boolean applyDilation) {
this.applyDilation = applyDilation;
}
@JIPipeDocumentation(name = "Connectivity", description = "Determines the neighborhood around each pixel that is checked for connectivity")
@JIPipeParameter("connectivity")
public Neighborhood2D getConnectivity() {
return connectivity;
}
@JIPipeParameter("connectivity")
public void setConnectivity(Neighborhood2D connectivity) {
this.connectivity = connectivity;
}
@Override
protected void runIteration(JIPipeDataBatch dataBatch, JIPipeProgressInfo progressInfo) {
ImagePlus markerImage = dataBatch.getInputData("Marker", ImagePlus3DGreyscaleData.class, progressInfo).getImage();
ImagePlus maskImage = dataBatch.getInputData("Mask", ImagePlus3DGreyscaleMaskData.class, progressInfo).getImage();
maskImage = ImageJUtils.ensureEqualSize(maskImage, markerImage, true);
ImageStack resultImage;
if (applyDilation)
resultImage = Reconstruction3D.reconstructByDilation(markerImage.getImageStack(), maskImage.getImageStack(), connectivity.getNativeValue());
else
resultImage = Reconstruction3D.reconstructByErosion(markerImage.getImageStack(), maskImage.getImageStack(), connectivity.getNativeValue());
ImagePlus outputImage = new ImagePlus("Reconstructed", resultImage);
outputImage.copyScale(markerImage);
dataBatch.addOutputData(getFirstOutputSlot(), new ImagePlus3DGreyscaleData(outputImage), progressInfo);
}
}
|
java
| 12 | 0.777705 | 166 | 53.464286 | 84 |
starcoderdata
|
const fs = require('fs')
const path = require('path')
const INPUT = './node_modules/three/examples/js/'
const OUTPUT = './src/three/'
const dirs =
[
'controls',
'effects',
]
const files =
[
'controls/VRControls.js',
'controls/OrbitControls.js',
'controls/DeviceOrientationControls.js',
'effects/VREffect.js',
]
const globalReplace = function(str, pattern, replacement) {
return str.replace(new RegExp(pattern, 'g'), replacement);
};
const transform = (m, code) =>
{
// trun the global modifiction into an import and a local variable definition
code = code.replace(`THREE.${m} =`, `import * as THREE from 'three';\nvar ${m} =`);
// change references from the global modification to the local variable
code = globalReplace(code, `THREE.${m}`, m);
// export that local variable as default from this module
code += `\nexport default ${m};`;
// expose private functions so that users can manually use controls
// and we can add orientation controls
if (m === 'OrbitControls') {
code = globalReplace(code, 'function rotateLeft\\(', 'rotateLeft = function(');
code = globalReplace(code, 'function rotateUp\\(', 'rotateUp = function(');
code = globalReplace(code, 'rotateLeft', 'scope.rotateLeft');
code = globalReplace(code, 'rotateUp', 'scope.rotateUp');
// comment out the context menu prevent default line...
code = globalReplace(
code,
"scope.domElement.addEventListener\\( 'contextmenu'",
"\/\/scope.domElement.addEventListener\\( 'contextmenu'"
);
}
return code;
}
fs.rmdirSync(OUTPUT, { recursive: true })
fs.mkdirSync(OUTPUT)
dirs.forEach(d => fs.mkdirSync(OUTPUT + d))
files.forEach(f =>
{
const code = fs.readFileSync(INPUT + f, 'utf8')
fs.writeFileSync(OUTPUT + f, transform(f.split("/").reverse()[0].split(".")[0], code))
})
console.log('Done.')
|
javascript
| 23 | 0.674334 | 88 | 26.724638 | 69 |
starcoderdata
|
private boolean isThrowableIgnored(@NonNull final Throwable throwable) {
// Don't crash the application over a simple network problem
return ExceptionUtils.hasAssignableCause(throwable,
// network api cancellation
IOException.class, SocketException.class,
// blocking code disposed
InterruptedException.class, InterruptedIOException.class);
}
|
java
| 7 | 0.595436 | 82 | 59.375 | 8 |
inline
|
package models
import "errors"
type BoardPayload struct {
Id int64 `json:"id" gorm:"primaryKey"`
Payload string `json:"payload"`
}
func (p *BoardPayload) TableName() string {
return "board_payload"
}
func (p *BoardPayload) Update(selectField interface{}, selectFields ...interface{}) error {
return DB().Model(p).Select(selectField, selectFields...).Updates(p).Error
}
func BoardPayloadGets(ids []int64) ([]*BoardPayload, error) {
if len(ids) == 0 {
return nil, errors.New("empty ids")
}
var arr []*BoardPayload
err := DB().Where("id in ?", ids).Find(&arr).Error
return arr, err
}
func BoardPayloadGet(id int64) (string, error) {
payloads, err := BoardPayloadGets([]int64{id})
if err != nil {
return "", err
}
if len(payloads) == 0 {
return "", nil
}
return payloads[0].Payload, nil
}
func BoardPayloadSave(id int64, payload string) error {
var bp BoardPayload
err := DB().Where("id = ?", id).Find(&bp).Error
if err != nil {
return err
}
if bp.Id > 0 {
// already exists
bp.Payload = payload
return bp.Update("payload")
}
return Insert(&BoardPayload{
Id: id,
Payload: payload,
})
}
|
go
| 14 | 0.661578 | 91 | 18.983051 | 59 |
starcoderdata
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void calc_ans (int *n_ac, int *n_penalty, int n_ques, int n_subm) {
int i, n;
char result[3];
int8_t is_ac[n_ques]; /* if AC then 1, else 0 */
int n_wa[n_ques];
memset(is_ac, 0, n_ques*sizeof(int8_t));
memset(n_wa, 0, n_ques*sizeof(int));
for ( i=0; i<n_subm; i++ ) {
scanf("%d%s", &n, result);
if ( !strncmp("AC", result, 2) )
is_ac[n-1] = 1;
else if ( is_ac[n-1] != 1 )
n_wa[n-1]++;
}
for ( i=0; i<n_ques; i++ ) {
if ( is_ac[i] == 1 ) {
(*n_ac)++;
*n_penalty += n_wa[i];
}
}
}
int main (void) {
int n, m;
int n_ac=0, n_penalty=0;
scanf("%d%d", &n, &m);
calc_ans(&n_ac, &n_penalty, n, m);
printf("%d %d\n", n_ac, n_penalty);
return EXIT_SUCCESS;
}
|
c
| 12 | 0.449831 | 74 | 21.74359 | 39 |
codenet
|
import discord
from discord.ext import commands
class Close:
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
async def close(self, ctx, *reason):
"""
Close a ticket
:param ctx:
:param user_name:
:param reason:
:return:
"""
if "-ticket" in ctx.message.channel.name:
await self.bot.delete_channel(ctx.message.channel)
out = ''
if len(reason) != 0:
for word in reason:
out += word
out += " "
else:
out = "No reason"
close_embed = discord.Embed(title="The ticket as been closed", color=discord.Color.red())
close_embed.add_field(name="Author", value=ctx.message.author, inline=True)
close_embed.add_field(name="Reason", value=out)
close_embed.set_footer(text="Ticket bot", icon_url=self.bot.user.avatar_url)
await self.bot.send_message(ctx.message.author, embed=close_embed)
else:
await self.bot.say("You are not in a ticket channel")
def setup(bot):
bot.add_cog(Close(bot))
|
python
| 16 | 0.548414 | 101 | 27.52381 | 42 |
starcoderdata
|
static String readMultipleLinesRespone(HttpsURLConnection connect) throws IOException {
InputStream inputStream;
if (connect != null) {
inputStream = connect.getInputStream();
} else {
throw new IOException("!");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String response ="";
String line;
while ((line = reader.readLine()) != null) {
response+=line;
}
reader.close();
//String aaa = connect.getContentEncoding();
// String encoding = connect.getContentEncoding() == null ? "UTF-8"
// : connect.getContentEncoding();
return response;
}
|
java
| 10 | 0.592896 | 96 | 37.578947 | 19 |
inline
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateConsultationarvTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('consultationarvs', function (Blueprint $table) {
$table->increments('id');
$table->string('centre_code');
$table->tinyInteger('siTraitementJ0');
$table->tinyInteger('siTraitementJ14');
$table->tinyInteger('siTraitementJ30');
$table->date('dateConsultation');
$table->string('derniereAdresse');
$table->string('tel');
$table->string('personnelsoignant_code');
$table->float('poids');
$table->float('taille');
$table->float('imc');
$table->integer('indiceKarno');
$table->integer('tauxCD4');
$table->string('traitementARVInit');
$table->string('traitementAssocie');
$table->date('dateProchainRDV');
$table->string('manifestationsCliniques');
$table->string('evenement');
$table->tinyInteger('siModificationTraitementARV');
$table->string('protocole_code');
$table->string('ligne_code');
$table->string('motifChangementTraitement');
$table->string('changementEffectue');
$table->string('code_nouvelle_ligne');
$table->string('conclusion');
$table->string('statutPatient');
$table->string('criteresEligibilite');
$table->string('schemaInitial');
$table->string('bilanSuivi');
$table->string('transfereDe');
$table->timestamps();
});
Schema::table('consultationarvs', function($table) {
$table->foreign('code_nouvelle_ligne')->references('code')->on('lignes');
$table->foreign('personnelsoignant_code')->references('code')->on('personnelsoignants');
$table->foreign('protocole_code')->references('code')->on('protocoles');
$table->foreign('ligne_code')->references('code')->on('lignes');
$table->foreign('centre_code')->references('code')->on('centres');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('consultationarv');
}
}
|
php
| 18 | 0.550877 | 100 | 28.147727 | 88 |
starcoderdata
|
/** @file Plane.cpp
@author
Implementation of the class Athena::Math::Plane
@note This is based on the corresponding class from
<a href="http://www.ogre3d.org/">Ogre3D
*/
#include
//#include
#include
using namespace Athena::Math;
/****************************** CONSTRUCTION / DESTRUCTION ******************************/
Plane::Plane()
: normal(Vector3::ZERO), d(0.0)
{
}
//-----------------------------------------------------------------------
Plane::Plane(const Plane& rhs)
: normal(rhs.normal), d(rhs.d)
{
}
//-----------------------------------------------------------------------
Plane::Plane(const Vector3& rkNormal, Real fConstant)
: normal(rkNormal), d(-fConstant)
{
}
//-----------------------------------------------------------------------
Plane::Plane(Real a, Real b, Real c, Real _d)
: normal(a, b, c), d(_d)
{
}
//-----------------------------------------------------------------------
Plane::Plane(const Vector3& rkNormal, const Vector3& rkPoint)
{
redefine(rkNormal, rkPoint);
}
//-----------------------------------------------------------------------
Plane::Plane(const Vector3& rkPoint0, const Vector3& rkPoint1, const Vector3& rkPoint2)
{
redefine(rkPoint0, rkPoint1, rkPoint2);
}
/**************************************** METHODS ***************************************/
Real Plane::getDistance(const Vector3& rkPoint) const
{
return normal.dotProduct(rkPoint) + d;
}
//-----------------------------------------------------------------------
Plane::tSide Plane::getSide(const Vector3& rkPoint) const
{
Real fDistance = getDistance(rkPoint);
if (fDistance < 0.0)
return Plane::NEGATIVE_SIDE;
if (fDistance > 0.0)
return Plane::POSITIVE_SIDE;
return Plane::NO_SIDE;
}
//-----------------------------------------------------------------------
Plane::tSide Plane::getSide(const AxisAlignedBox& box) const
{
if (box.isNull())
return NO_SIDE;
if (box.isInfinite())
return BOTH_SIDE;
return getSide(box.getCenter(), box.getHalfSize());
}
//-----------------------------------------------------------------------
Plane::tSide Plane::getSide(const Vector3& centre, const Vector3& halfSize) const
{
Real dist = getDistance(centre);
Real maxAbsDist = normal.absDotProduct(halfSize);
if (dist < -maxAbsDist)
return Plane::NEGATIVE_SIDE;
if (dist > +maxAbsDist)
return Plane::POSITIVE_SIDE;
return Plane::BOTH_SIDE;
}
//-----------------------------------------------------------------------
void Plane::redefine(const Vector3& rkPoint0, const Vector3& rkPoint1,
const Vector3& rkPoint2)
{
Vector3 kEdge1 = rkPoint1 - rkPoint0;
Vector3 kEdge2 = rkPoint2 - rkPoint0;
normal = kEdge1.crossProduct(kEdge2);
normal.normalise();
d = -normal.dotProduct(rkPoint0);
}
//-----------------------------------------------------------------------
void Plane::redefine(const Vector3& rkNormal, const Vector3& rkPoint)
{
normal = rkNormal;
d = -rkNormal.dotProduct(rkPoint);
}
//-----------------------------------------------------------------------
Vector3 Plane::projectVector(const Vector3& p) const
{
Matrix3 xform;
xform[0][0] = 1.0f - normal.x * normal.x;
xform[0][1] = -normal.x * normal.y;
xform[0][2] = -normal.x * normal.z;
xform[1][0] = -normal.y * normal.x;
xform[1][1] = 1.0f - normal.y * normal.y;
xform[1][2] = -normal.y * normal.z;
xform[2][0] = -normal.z * normal.x;
xform[2][1] = -normal.z * normal.y;
xform[2][2] = 1.0f - normal.z * normal.z;
return xform * p;
}
//-----------------------------------------------------------------------
Real Plane::normalise(void)
{
Real fLength = normal.length();
// Will also work for zero-sized vectors, but will change nothing
if (fLength > 1e-08f)
{
Real fInvLength = 1.0f / fLength;
normal *= fInvLength;
d *= fInvLength;
}
return fLength;
}
|
c++
| 8 | 0.481383 | 90 | 23.915663 | 166 |
starcoderdata
|
#include "testee.hpp"
int add(const int a, const int b)
{
return a + b;
}
|
c++
| 6 | 0.672727 | 33 | 14.714286 | 7 |
starcoderdata
|
# -*- coding: utf-8 -*-
"""
Copyright ยฉ2017. The Regents of the University of California (Regents). All Rights Reserved.
Permission to use, copy, modify, and distribute this software and its documentation for educational,
research, and not-for-profit purposes, without fee and without a signed licensing agreement, is
hereby granted, provided that the above copyright notice, this paragraph and the following two
paragraphs appear in all copies, modifications, and distributions. Contact The Office of Technology
Licensing, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643-
7201, http://ipira.berkeley.edu/industry-info for commercial licensing opportunities.
IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,
INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF
THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
"""
"""
User-friendly functions for computing grasp quality metrics.
Author:
"""
from abc import ABCMeta, abstractmethod
import copy
import itertools as it
import logging
import matplotlib.pyplot as plt
try:
import mayavi.mlab as mlab
except:
logging.warning('Failed to import mayavi')
import numpy as np
import os
import scipy.stats
import sys
import time
from dexnet.grasping import Grasp, GraspableObject, GraspQualityConfig
from dexnet.grasping.robust_grasp_quality import RobustPointGraspMetrics3D
from dexnet.grasping.random_variables import GraspableObjectPoseGaussianRV, ParallelJawGraspPoseGaussianRV, ParamsGaussianRV
from dexnet.grasping import PointGraspMetrics3D
from autolab_core import RigidTransform
import IPython
class GraspQualityResult:
""" Stores the results of grasp quality computation.
Attributes
----------
quality : float
value of quality
uncertainty : float
uncertainty estimate of the quality value
quality_config : :obj:`GraspQualityConfig`
"""
def __init__(self, quality, uncertainty=0.0, quality_config=None):
self.quality = quality
self.uncertainty = uncertainty
self.quality_config = quality_config
# class GraspQualityFunction(object, metaclass=ABCMeta):
class GraspQualityFunction(object):
"""
Abstraction for grasp quality functions to make scripts for labeling with quality functions simple and readable.
Attributes
----------
graspable : :obj:`GraspableObject3D`
object to evaluate grasp quality on
quality_config : :obj:`GraspQualityConfig`
set of parameters to evaluate grasp quality
"""
__metaclass__ = ABCMeta
def __init__(self, graspable, quality_config):
# check valid types
if not isinstance(graspable, GraspableObject):
raise ValueError('Must provide GraspableObject')
if not isinstance(quality_config, GraspQualityConfig):
raise ValueError('Must provide GraspQualityConfig')
# set member variables
self.graspable_ = graspable
self.quality_config_ = quality_config
self._setup()
def __call__(self, grasp):
return self.quality(grasp)
@abstractmethod
def _setup(self):
""" Sets up common variables for grasp quality evaluations """
pass
@abstractmethod
def quality(self, grasp):
""" Compute grasp quality.
Parameters
----------
grasp : :obj:`GraspableObject3D`
grasp to quality quality on
Returns
-------
:obj:`GraspQualityResult`
result of quality computation
"""
pass
class QuasiStaticQualityFunction(GraspQualityFunction):
""" Grasp quality metric using a quasi-static model.
"""
def __init__(self, graspable, quality_config):
GraspQualityFunction.__init__(self, graspable, quality_config)
@property
def graspable(self):
return self.graspable_
@graspable.setter
def graspable(self, obj):
self.graspable_ = obj
def _setup(self):
if self.quality_config_.quality_type != 'quasi_static':
raise ValueError('Quality configuration must be quasi static')
def quality(self, grasp):
""" Compute grasp quality using a quasistatic method.
Parameters
----------
grasp : :obj:`GraspableObject3D`
grasp to quality quality on
Returns
-------
:obj:`GraspQualityResult`
result of quality computation
"""
if not isinstance(grasp, Grasp):
raise ValueError('Must provide Grasp object to compute quality')
quality = PointGraspMetrics3D.grasp_quality(grasp, self.graspable_,
self.quality_config_)
return GraspQualityResult(quality, quality_config=self.quality_config_)
class RobustQuasiStaticQualityFunction(GraspQualityFunction):
""" Grasp quality metric using a robust quasi-static model (average over random perturbations)
"""
def __init__(self, graspable, quality_config, T_obj_world=RigidTransform(from_frame='obj', to_frame='world')):
self.T_obj_world_ = T_obj_world
GraspQualityFunction.__init__(self, graspable, quality_config)
@property
def graspable(self):
return self.graspable_
@graspable.setter
def graspable(self, obj):
self.graspable_ = obj
self._setup()
def _setup(self):
if self.quality_config_.quality_type != 'robust_quasi_static':
raise ValueError('Quality configuration must be robust quasi static')
self.graspable_rv_ = GraspableObjectPoseGaussianRV(self.graspable_,
self.T_obj_world_,
self.quality_config_.obj_uncertainty)
self.params_rv_ = ParamsGaussianRV(self.quality_config_,
self.quality_config_.params_uncertainty)
def quality(self, grasp):
""" Compute grasp quality using a robust quasistatic method.
Parameters
----------
grasp : :obj:`GraspableObject3D`
grasp to quality quality on
Returns
-------
:obj:`GraspQualityResult`
result of quality computation
"""
if not isinstance(grasp, Grasp):
raise ValueError('Must provide Grasp object to compute quality')
grasp_rv = ParallelJawGraspPoseGaussianRV(grasp,
self.quality_config_.grasp_uncertainty)
mean_q, std_q = RobustPointGraspMetrics3D.expected_quality(grasp_rv,
self.graspable_rv_,
self.params_rv_,
self.quality_config_)
return GraspQualityResult(mean_q, std_q, quality_config=self.quality_config_)
class GraspQualityFunctionFactory:
@staticmethod
def create_quality_function(graspable, quality_config):
""" Creates a quality function for a particular object based on a configuration, which can be passed directly from a configuration file.
Parameters
----------
graspable : :obj:`GraspableObject3D`
object to create quality function for
quality_config : :obj:`GraspQualityConfig`
parameters for quality function
"""
# check valid types
if not isinstance(graspable, GraspableObject):
raise ValueError('Must provide GraspableObject')
if not isinstance(quality_config, GraspQualityConfig):
raise ValueError('Must provide GraspQualityConfig')
if quality_config.quality_type == 'quasi_static':
return QuasiStaticQualityFunction(graspable, quality_config)
elif quality_config.quality_type == 'robust_quasi_static':
return RobustQuasiStaticQualityFunction(graspable, quality_config)
else:
raise ValueError('Grasp quality type %s not supported' %(quality_config.quality_type))
|
python
| 15 | 0.652446 | 144 | 37 | 227 |
starcoderdata
|
@Test
void applyToMethod_withKnownNameOverlapping_shouldRedrawANewName_andBeSuccessfullyApplied(){
// The variable was chosen by a seed so there would be a forced overlap in names
// The transformer should re-draw a name after detecting the collision
AddUnusedVariableTransformer transformer = new AddUnusedVariableTransformer(1);
CtElement ast = Launcher.parseClass(
"package lampion.test.examples; class A { " +
"int some(int agedWaleNurse){return agedWaleNurse;}" +
"}");
var result = transformer.applyAtRandom(ast);
assertTrue(ast.toString().contains("="));
assertNotEquals(new EmptyTransformationResult(),result);
}
|
java
| 10 | 0.675272 | 96 | 45.0625 | 16 |
inline
|
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.Comparator.*;
public class Solution {
public int[] twoSum(int[] nums, int target) {
List objs = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
objs.add(new Pair(i, nums[i]));
}
//System.out.println(Arrays.toString(objs.toArray()));
Collections.sort(objs);
//System.out.println(Arrays.toString(objs.toArray()));
int low = 0, high = objs.size() - 1;
while (low < high) {
int diff = target - objs.get(low).value;
if (diff > objs.get(high).value) {
while ((low + 1 < high)
&& (objs.get(low).value == objs.get(low + 1).value)) {
low++;
}
low++;
} else if (diff < objs.get(high).value) {
while ((high - 1 >= low)
&& (objs.get(high).value == objs.get(high - 1).value)) {
high--;
}
high--;
} else {
return new int[] {objs.get(low).index, objs.get(high).index};
}
}
return null;
}
static final class Pair implements Comparable {
// Comparable wih comparator construction methods
private static final Comparator COMPARATOR =
comparingInt((Pair p) -> p.value);
private final int index;
private final int value;
Pair(int index, int value) {
this.index = index;
this.value = value;
}
@Override
public int compareTo(Pair p) {
return COMPARATOR.compare(this, p);
}
@Override
public String toString() {
return "(index=" + index + ", value=" + value + ")";
}
}
public int[] twoSum2(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i]) && i != map.get(nums[i])) {
return new int[] {i, map.get(nums[i])};
}
map.put(target - nums[i], i);
}
return null;
}
public static void main(String[] args) {
Input[] inputs = {
new Input(new int[]{ 2, 7, 11, 15 }, 9),
};
for (int i = 0; i < inputs.length; i++) {
int[] nums = inputs[i].nums;
int target = inputs[i].target;
System.out.printf("\n Given nums: %s, target = %d",
Arrays.toString(nums), target);
Solution solution = new Solution();
int[] pairs = solution.twoSum(nums, target);
System.out.printf("\n Output: %s\n",
(pairs == null) ? "Not found" : Arrays.toString(pairs));
}
}
static final class Input {
private final int[] nums;
private final int target;
Input(int[] nums, int target) {
this.nums = nums;
this.target = target;
}
}
}
|
java
| 17 | 0.492345 | 80 | 29.240741 | 108 |
starcoderdata
|
<?php
class Dosen_model extends CI_model
{
public function getAll()
{
return $this->db->get('dosen')->result_array();
}
public function getAmpuan()
{
return $this->db->get('ampuan')->result_array();
}
// public function getById($id_dosen)
// {
// $this->db->select('*');
// $this->db->from('dosen');
// $this->db->join('ampuan', 'dosen.id_dosen=ampuan.id_dosen');
// $this->db->join('kelas', 'ampuan.id_kelas=kelas.id_kelas');
// $this->db->where('ampuan.id_dosen',$id_dosen);
// $query = $this->db->get();
// return $query;
// }
public function add($nama, $kelas)
{
$this->db->trans_start();
//INSERT TO PACKAGE
$data = [
"nama" => $nama
];
$this->db->insert('dosen', $data);
//GET ID PACKAGE
$package_id = $this->db->insert_id();
$result = array();
foreach($kelas AS $key => $val){
$result[] = array(
'id_dosen' => $package_id,
'id_kelas' => $_POST['kelas'][$key]
);
}
//MULTIPLE INSERT TO DETAIL TABLE
$this->db->insert_batch('ampuan', $result);
$this->db->trans_complete();
}
public function update($nama,$kelas,$id_dosen)
{
$this->db->trans_start();
//UPDATE TO PACKAGE
$data = array(
'nama' => $nama
);
$this->db->where('id_dosen',$id_dosen);
$this->db->update('dosen', $data);
if(!empty($kelas)){
//DELETE DETAIL PACKAGE
$this->db->delete('ampuan', array('id_dosen' => $id_dosen));
$result = array();
foreach($kelas AS $key => $val){
$result[] = array(
'id_dosen' => $id_dosen,
'id_kelas' => $_POST['kelas_edit'][$key]
);
}
//MULTIPLE INSERT TO DETAIL TABLE
$this->db->insert_batch('ampuan', $result);
}
$this->db->trans_complete();
}
public function delete($id)
{
$this->db->trans_start();
$this->db->delete('ampuan', array('id_dosen' => $id));
$this->db->delete('dosen', array('id_dosen' => $id));
$this->db->trans_complete();
}
}
|
php
| 16 | 0.508962 | 65 | 24.25 | 84 |
starcoderdata
|
๏ปฟnamespace Tufan.Ticket.Domain.Model.Entity
{
public class Policy
{
public object MaxSeats { get; set; }
public object MaxSingle { get; set; }
public int MaxSingleMales { get; set; }
public int MaxSingleFemales { get; set; }
public bool MixedGenders { get; set; }
public bool GovId { get; set; }
public bool Lht { get; set; }
}
}
|
c#
| 8 | 0.59194 | 49 | 29.615385 | 13 |
starcoderdata
|
fn write_report(stdout: &mut StandardStream, url: &str, ok: bool) {
// get the styles based on if the request was ok
let (color, status) = if ok {
(Color::Green, "โ")
} else {
(Color::Red, "X")
};
// capture any stdout errors
|| -> io::Result<()> {
stdout.set_color(ColorSpec::new().set_fg(Some(color)))?;
writeln!(stdout, "{} โ {}", status, url)
}()
.expect("unable to write report to stdout")
}
|
rust
| 16 | 0.542299 | 67 | 29.8 | 15 |
inline
|
module.exports = function(grunt) {
"use strict";
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
banner: '/*! <%= pkg.name %>, version <%= pkg.version %>, copyright by <%= pkg.author %> | <%= grunt.template.today("yyyy-mm-dd") %> */\n',
compress: {
drop_console: true
}
},
build: {
files: [{
expand: true,
cwd: 'src/js',
src: '**/*.js',
dest: 'build',
ext: '.min.js'
}]
},
example: {
options: {
compress: {
drop_console: false
}
},
files: [{
expand: true,
cwd: 'src/js',
src: '**/*.js',
dest: 'examples',
ext: '.min.js'
}]
}
},
cssmin: {
project: {
files: [{
expand: true,
cwd: 'src/css',
src: ['*.css'],
dest: 'build',
ext: '.min.css'
}]
}
},
autoprefixer: {
options: {
browsers: ["Firefox ESR", "Opera 12", "ff >= 10", "ios >= 5", "ie > 8"],
silent: true
},
multiple_files: {
src: 'src/css/*.css'
}
},
compass: {
options: {
sassDir: 'src/scss/'
},
dev: {
options: {
cssDir: 'src/css/',
environment: 'development'
}
}
},
watch: {
scripts: {
files: ['src/**/*.js'],
tasks: ['uglify'],
options: {
spawn: false
}
},
scss: {
files: ['src/**/*.scss'],
tasks: ['compass:dev','autoprefixer', 'cssmin'],
options: {
spawn: false
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.loadNpmTasks('grunt-autoprefixer');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['watch']);
};
|
javascript
| 28 | 0.333705 | 155 | 27.305263 | 95 |
starcoderdata
|
// README
// Instruction: https://github.com/soetani/gas-sync-google-calendar
// 1. How many days do you want to sync your calendars?
var DAYS_TO_SYNC = 30;
// 2. Calendar ID mapping: [Calendar ID (Source), Calendar ID (Guest)]
var CALENDAR_IDS = [
[' '
[' '
];
// 3. What is Slack webhook URL? You'll be notified when the sync is failed
var SLACK_WEBHOOK_URL = 'https://hooks.slack.com/services/foobar';
// copy config
var COPIED_PREFIX = 'ใโณใ';
var COPIED_DESC_PREFIX = 'ใcopied event from ';
var COPIED_DESC_SUFFIX = 'ใ'
function main(){
var dateFrom = new Date();
var dateTo = new Date(dateFrom.getTime() + (DAYS_TO_SYNC * 24 * 60 * 60* 1000));
CALENDAR_IDS.forEach(function(ids){
var sourceId = ids[0];
var guestId = ids[1];
Logger.log('Source: ' + sourceId + ' / Guest: ' + guestId);
var events = CalendarApp.getCalendarById(sourceId).getEvents(dateFrom, dateTo);
events.forEach(function(event){
var guest = event.getGuestByEmail(guestId);
guest ? syncStatus(event, guest) : invite(event, guestId, sourceId);
// if copied original event was move, delete copy event.
reflectCopyEventIfOriginChanged(event, guestId, sourceId);
});
});
}
function test() {
var dateFrom = new Date(2021, 2, 23, 10);
var dateTo = new Date(dateFrom.getTime() + (DAYS_TO_SYNC * 24 * 60 * 60* 1000));
var sourceId = CALENDAR_IDS[0][0];
var guestId = CALENDAR_IDS[0][1];
var events = CalendarApp.getCalendarById(' dateTo);
var event = events[0]
Logger.log(event.getTitle());
Logger.log(event.getGuestList().length == 1);
// events.forEach(function(event) {
// Logger.log(event.getTitle());
// });
var isInviter = event.getDescription().startsWith(COPIED_DESC_PREFIX + sourceId + COPIED_DESC_SUFFIX)
Logger.log('isInviterStatus: ' + isInviter)
var events = CalendarApp.getCalendarById(sourceId).getEvents(event.getStartTime(), event.getEndTime());
var isExist = !!events.find(element => {(
element.getTitle() == COPIED_PREFIX + event.getTitle() &&
element.getStartTime().toString() == event.getStartTime().toString() &&
element.getEndTime().toString() == event.getEndTime().toString())}
);
// Logger.log(events)
// Logger.log(events[0].getTitle() == COPIED_PREFIX + events[0].getTitle())
// Logger.log(events[0].getStartTime().toString() == events[0].getStartTime().toString())
// Logger.log(events[0].getEndTime().toString() == events[0].getEndTime().toString())
// Logger.log(events[0].getTitle())
// invite(event, guestId, sourceId);
}
function syncStatus(event, guest){
var sourceStatus = event.getMyStatus();
var guestStatus = guest.getGuestStatus();
if(guestStatus != CalendarApp.GuestStatus.YES && guestStatus != CalendarApp.GuestStatus.NO) return;
if((sourceStatus == CalendarApp.GuestStatus.YES || sourceStatus == CalendarApp.GuestStatus.NO) && sourceStatus != guestStatus){
// Notify when source status is opposite from guest's status
// notify('Failed to sync the status of the event: ' + event.getTitle() + ' (' + event.getStartTime() + ')');
}
else if(sourceStatus != guestStatus && sourceStatus != CalendarApp.GuestStatus.OWNER){
// Update status when my status is invited/maybe AND guest's status is yes/no
event.setMyStatus(guestStatus);
Logger.log('Status updated:' + event.getTitle() + ' (' + event.getStartTime() + ')');
}
}
function invite(event, guestId, sourceId){
var result = event.addGuest(guestId);
Logger.log('Invited: ' + event.getTitle() + ' (' + event.getStartTime() + ')');
if(!result.getGuestByEmail(guestId) && !event.getTitle().startsWith(COPIED_PREFIX)) {
// invite failed, create copy event
createCopyEvent(
event,
sourceId,
guestId
);
}
}
function createCopyEvent(event, sourceId, guestId) {
// check already copied event created
var events = CalendarApp.getCalendarById(sourceId).getEvents(event.getStartTime(), event.getEndTime());
var isExist = !!events.find(element => (
element.getTitle() == COPIED_PREFIX + event.getTitle() &&
element.getStartTime().toString() == event.getStartTime().toString() &&
element.getEndTime().toString() == event.getEndTime().toString()));
if(!isExist) {
// not exist copy event, then create.
CalendarApp.getCalendarById(sourceId).createEvent(
COPIED_PREFIX + event.getTitle(), event.getStartTime(), event.getEndTime(),
{guests: [guestId, sourceId].toString(), description: COPIED_DESC_PREFIX + sourceId + COPIED_DESC_SUFFIX + "\n" + event.getDescription()}
);
}
}
function reflectCopyEventIfOriginChanged(copyEvent, guestId, sourceId) {
if (!copyEvent.getTitle().startsWith(COPIED_PREFIX)) {
// Skip if not event start copied_prefix
return true;
}
var isInviter = copyEvent.getCreators().join() === sourceId;
if (!isInviter) {
// Skip if not copy event inviter
return true;
}
var events = CalendarApp.getCalendarById(sourceId).getEvents(copyEvent.getStartTime(), copyEvent.getEndTime());
var orgEvent = events.find(element => (
element.getTitle() == copyEvent.getTitle().slice(COPIED_PREFIX.length) &&
element.getStartTime().toString() == copyEvent.getStartTime().toString() &&
element.getEndTime().toString() == copyEvent.getEndTime().toString()));
if(!orgEvent && copyEvent.getGuestList().length == 1 &&
!!copyEvent.getGuestByEmail(guestId) && copyEvent.getCreators().join() === sourceId){
// delete copyEvent if orginal event is deleted or moved
copyEvent.deleteEvent();
return true;
}
if(copyEvent.getDescription() !== COPIED_DESC_PREFIX + sourceId + COPIED_DESC_SUFFIX + "\n" + orgEvent.getDescription()) {
// reflect copyEvent description if original event description is changed
copyEvent.setDescription(COPIED_DESC_PREFIX + sourceId + COPIED_DESC_SUFFIX + "\n" + orgEvent.getDescription());
}
}
function notify(message){
var data = {'text': message};
var options = {
'method': 'post',
'contentType': 'application/json',
'payload': JSON.stringify(data)
};
UrlFetchApp.fetch(SLACK_WEBHOOK_URL, options);
}
|
javascript
| 20 | 0.672618 | 143 | 40.372549 | 153 |
starcoderdata
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.