file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
Vector3D.ts
class Vector3D { public static readonly size: number = 24 /** * Converts array input into a buffer representing a 3 point vector. * * @param {number[]} vector Should contain 3 values * @returns {Buffer} */ public static toBuffer(vector: Array<number>): Buffer { const buffer = Buffer.allocUnsaf...
} export default Vector3D
{ return [ buffer.readDoubleLE(position), buffer.readDoubleLE(position + 8), buffer.readDoubleLE(position + 16) ] }
identifier_body
Vector3D.ts
class Vector3D { public static readonly size: number = 24 /** * Converts array input into a buffer representing a 3 point vector. * * @param {number[]} vector Should contain 3 values * @returns {Buffer} */ public static toBuffer(vector: Array<number>): Buffer { const buffer = Buffer.allocUnsaf...
} export default Vector3D
random_line_split
Vector3D.ts
class Vector3D { public static readonly size: number = 24 /** * Converts array input into a buffer representing a 3 point vector. * * @param {number[]} vector Should contain 3 values * @returns {Buffer} */ public static
(vector: Array<number>): Buffer { const buffer = Buffer.allocUnsafe(this.size) buffer.writeDoubleLE(vector[0], 0) buffer.writeDoubleLE(vector[1], 8) buffer.writeDoubleLE(vector[2], 16) return buffer } /** * Converts buffer input into an array of double values representing a 3 point * ve...
toBuffer
identifier_name
tools.py
## $Id: tools.py 23525 2011-05-12 04:11:40Z davea $ import configxml try: # use new hashlib if available from hashlib import md5 except: import md5 import os, shutil, binascii, filecmp # from http://www.plope.com/software/uuidgen/view _urandomfd = None def urandom(n): """urandom(n) -> str Return ...
(path): """Return the size of a file""" f = open(path) f.seek(0,2) return f.tell() def query_yesno(str): '''Query user; default Yes''' print str, "[Y/n] ", return not raw_input().strip().lower().startswith('n') def query_noyes(str): '''Query user; default No''' print str, "[y/N] ",...
file_size
identifier_name
tools.py
## $Id: tools.py 23525 2011-05-12 04:11:40Z davea $ import configxml try: # use new hashlib if available from hashlib import md5 except: import md5 import os, shutil, binascii, filecmp # from http://www.plope.com/software/uuidgen/view _urandomfd = None def urandom(n): """urandom(n) -> str Return ...
def query_yesno(str): '''Query user; default Yes''' print str, "[Y/n] ", return not raw_input().strip().lower().startswith('n') def query_noyes(str): '''Query user; default No''' print str, "[y/N] ", return raw_input().strip().lower().startswith('y') def get_output_file_path(filename): """...
f = open(path) f.seek(0,2) return f.tell()
random_line_split
tools.py
## $Id: tools.py 23525 2011-05-12 04:11:40Z davea $ import configxml try: # use new hashlib if available from hashlib import md5 except: import md5 import os, shutil, binascii, filecmp # from http://www.plope.com/software/uuidgen/view _urandomfd = None def urandom(n): """urandom(n) -> str Return ...
bytes = "" while len(bytes) < n: bytes += os.read(_urandomfd, n - len(bytes)) return bytes def make_uuid(): return binascii.hexlify(urandom(16)) def md5_file(path): """ Return a 16-digit MD5 hex digest of a file's contents Read the file in chunks """ chunk = 8096 tr...
raise NotImplementedError("/dev/urandom (or equivalent) not found")
conditional_block
tools.py
## $Id: tools.py 23525 2011-05-12 04:11:40Z davea $ import configxml try: # use new hashlib if available from hashlib import md5 except: import md5 import os, shutil, binascii, filecmp # from http://www.plope.com/software/uuidgen/view _urandomfd = None def urandom(n): """urandom(n) -> str Return ...
""" Return the filename's path in the upload directory Use this if you're developing a validator/assimilator in Python """ config = configxml.default_config() fanout = long(config.config.uldl_dir_fanout) s = md5.new(filename).hexdigest()[1:8] x = long(s, 16) return "%s/%x/%s" % (config.c...
identifier_body
is_near_arterial.py
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from variable_functions import my_attribute_label from urbansim.length_constants import UrbanSimLength, UrbanSimLengthConstants from numpy imp...
opus_unittest.main()
conditional_block
is_near_arterial.py
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from variable_functions import my_attribute_label from urbansim.length_constants import UrbanSimLength, UrbanSimLengthConstants from numpy imp...
if __name__=='__main__': opus_unittest.main()
def test_my_inputs( self ): # Assumes distance is measured from the gridcell border to the arterial. tester = VariableTester( __file__, package_order=['urbansim'], test_data={ 'gridcell':{ 'grid_id': array([1,2,3,4,5,6]), ...
identifier_body
is_near_arterial.py
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from variable_functions import my_attribute_label from urbansim.length_constants import UrbanSimLength, UrbanSimLengthConstants from numpy imp...
(opus_unittest.OpusTestCase): def test_my_inputs( self ): # Assumes distance is measured from the gridcell border to the arterial. tester = VariableTester( __file__, package_order=['urbansim'], test_data={ 'gridcell':{ '...
Tests
identifier_name
is_near_arterial.py
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from variable_functions import my_attribute_label from urbansim.length_constants import UrbanSimLength, UrbanSimLengthConstants from numpy impor...
distance_to_arterial = "distance_to_arterial" def dependencies(self): return [my_attribute_label(self.distance_to_arterial)] def compute(self, dataset_pool): return get_is_near_arterial(self.get_dataset().get_attribute(self.distance_to_arterial), ...
class is_near_arterial(Variable): """Boolean indicating if this gridcell is near an arterial, as specified by the arterial threshold (a constant). Distance is assumed to be measured from the "border" of the gridcell."""
random_line_split
app-module.ts
import {BrowserModule} from "@angular/platform-browser"; import {Compiler, NgModule, ErrorHandler} from "@angular/core"; import {FormsModule, ReactiveFormsModule} from "@angular/forms"; import {HttpModule, JsonpModule} from "@angular/http"; import {Ng2Bs3ModalModule} from "ng2-bs3-modal/ng2-bs3-modal"; import {AppCompo...
else { return productionReducer(state, action); // return developmentReducer(state, action); } } @NgModule({ declarations: [decelerations], imports: [ BrowserModule, FormsModule, BrowserAnimationsModule, ReactiveFormsModule, Ng2Bs3ModalModule, ...
{ return productionReducer(state, action); }
conditional_block
app-module.ts
import {BrowserModule} from "@angular/platform-browser"; import {Compiler, NgModule, ErrorHandler} from "@angular/core"; import {FormsModule, ReactiveFormsModule} from "@angular/forms"; import {HttpModule, JsonpModule} from "@angular/http"; import {Ng2Bs3ModalModule} from "ng2-bs3-modal/ng2-bs3-modal"; import {AppCompo...
interface JQueryStatic { base64: any; knob: any; gradientPicker: any; timepicker: any; contextmenu: any; index: any; } } export class CustomToastOption extends ToastOptions { animate: 'flyRight'; positionClass: 'toast-bottom-right'; toastLife: 10000; ...
declare global {
random_line_split
app-module.ts
import {BrowserModule} from "@angular/platform-browser"; import {Compiler, NgModule, ErrorHandler} from "@angular/core"; import {FormsModule, ReactiveFormsModule} from "@angular/forms"; import {HttpModule, JsonpModule} from "@angular/http"; import {Ng2Bs3ModalModule} from "ng2-bs3-modal/ng2-bs3-modal"; import {AppCompo...
(private commBroker: CommBroker, private compiler: Compiler, private ngmslibService: NgmslibService, private yp: YellowPepperService, private fontLoaderService: FontLoaderService) { Lib.Con(`running in dev mode: ${Lib.DevMode()}`); Lib.Con(`App in ${(compiler instanceof Compiler) ? 'AOT' : 'JIT'} mode`)...
constructor
identifier_name
app-module.ts
import {BrowserModule} from "@angular/platform-browser"; import {Compiler, NgModule, ErrorHandler} from "@angular/core"; import {FormsModule, ReactiveFormsModule} from "@angular/forms"; import {HttpModule, JsonpModule} from "@angular/http"; import {Ng2Bs3ModalModule} from "ng2-bs3-modal/ng2-bs3-modal"; import {AppCompo...
}
{ Lib.Con(`running in dev mode: ${Lib.DevMode()}`); Lib.Con(`App in ${(compiler instanceof Compiler) ? 'AOT' : 'JIT'} mode`); window['business_id'] = -1; window['jQueryAny'] = jQuery; window['jXML'] = jQuery; this.ngmslibService.globalizeStringJS(); Lib.Con(String...
identifier_body
server.model.js
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * <%= model.pascalCaseSingular %> Schema */ var <%= model.pascalCaseSingular %>Schema = new Schema({<% model.elements.forEach(function(element) { %> <% if ( ['Schema.Types.ObjectId', 'File'].indexOf(elem...
mongoose.model('<%= model.pascalCaseSingular %>', <%= model.pascalCaseSingular %>Schema);
random_line_split
midasvr.py
import pwsimple # Midas volume rendering ParaviewWeb plugin # Initialize the volume rendering state def
(cameraFocalPoint, cameraPosition, colorArrayName, colorMap, sofPoints, viewSize): if type(colorArrayName) is unicode: colorArrayName = colorArrayName.encode('ascii', 'ignore') activeView = pwsimple.CreateIfNeededRenderView() activeView.CameraFocalPoint = cameraFocalPoint activeView.CameraPosition = ...
InitViewState
identifier_name
midasvr.py
import pwsimple # Midas volume rendering ParaviewWeb plugin # Initialize the volume rendering state def InitViewState (cameraFocalPoint, cameraPosition, colorArrayName, colorMap, sofPoints, viewSize): if type(colorArrayName) is unicode: colorArrayName = colorArrayName.encode('ascii', 'ignore') activeView =...
sof.Points = sofPoints dataRep = pwsimple.Show() dataRep.ScalarOpacityFunction = sof dataRep.Representation = 'Volume' dataRep.ColorArrayName = colorArrayName dataRep.LookupTable = lookupTable retVal = {} retVal['sof'] = sof retVal['lookupTable'] = lookupTable retVal['activeView'] = activeView...
lookupTable.ColorSpace = 0 # 0 corresponds to RGB # Initial scalar opacity function sof = pwsimple.CreatePiecewiseFunction()
random_line_split
midasvr.py
import pwsimple # Midas volume rendering ParaviewWeb plugin # Initialize the volume rendering state def InitViewState (cameraFocalPoint, cameraPosition, colorArrayName, colorMap, sofPoints, viewSize):
sof = pwsimple.CreatePiecewiseFunction() sof.Points = sofPoints dataRep = pwsimple.Show() dataRep.ScalarOpacityFunction = sof dataRep.Representation = 'Volume' dataRep.ColorArrayName = colorArrayName dataRep.LookupTable = lookupTable retVal = {} retVal['sof'] = sof retVal['lookupTable'] = look...
if type(colorArrayName) is unicode: colorArrayName = colorArrayName.encode('ascii', 'ignore') activeView = pwsimple.CreateIfNeededRenderView() activeView.CameraFocalPoint = cameraFocalPoint activeView.CameraPosition = cameraPosition activeView.CameraViewUp = [0.0, 0.0, 1.0] activeView.CameraParallel...
identifier_body
midasvr.py
import pwsimple # Midas volume rendering ParaviewWeb plugin # Initialize the volume rendering state def InitViewState (cameraFocalPoint, cameraPosition, colorArrayName, colorMap, sofPoints, viewSize): if type(colorArrayName) is unicode: colorArrayName = colorArrayName.encode('ascii', 'ignore') activeView =...
dataRep = pwsimple.Show() dataRep.ScalarOpacityFunction = sof dataRep.Representation = 'Volume' dataRep.SelectionPointFieldDataArrayName = colorArrayName dataRep.ColorArrayName = colorArrayName dataRep.LookupTable = lookupTable pwsimple.SetActiveSource(source) pwsimple.Hide(source) if toHide: ...
colorArrayName = colorArrayName.encode('ascii', 'ignore')
conditional_block
languageclient-services.ts
/* * Copyright (C) 2017 TypeFox 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 */ import * as base from 'vscode-base-languageclient...
export interface LanguageClientOptions extends base.BaseLanguageClientOptions { commands: Commands | undefined }
export interface IConnectionProvider extends connection.IConnectionProvider { } export const ILanguageClient = Symbol('ILanguageClient'); export interface ILanguageClient extends base.BaseLanguageClient { }
random_line_split
passport.js
const passport = require('passport'); const request = require('request'); const LocalStrategy = require('passport-local').Strategy; const User = require('../models').User; const INVALID_CREDENTIALS_MESSAGE = 'Invalid email and/or password.'; const UNAUTHORIZED_MESSAGE = 'You are not authorized.'; passport.serializeU...
return done(null, false, { msg: INVALID_CREDENTIALS_MESSAGE }); }); }) .catch(err => done(err)); })); /** * Login Required middleware. */ exports.isAuthenticated = (req, res, next) => { if (req.isAuthenticated()) { return next(); } res.status(401).json({ msg: UNAUTHORIZED_MESSAGE })...
{ return done(null, user); }
conditional_block
passport.js
const passport = require('passport'); const request = require('request'); const LocalStrategy = require('passport-local').Strategy; const User = require('../models').User; const INVALID_CREDENTIALS_MESSAGE = 'Invalid email and/or password.'; const UNAUTHORIZED_MESSAGE = 'You are not authorized.'; passport.serializeU...
/** * Sign in using email and password. */ passport.use(new LocalStrategy({ usernameField: 'email' }, (email, password, done) => { User.findOne({ where: { email: email.toLowerCase() } }) .then(user => { if (!user) { return done(null, false, { msg: INVALID_CREDENTIALS_MESSAGE }); } us...
.then(user => done(null, user)) .catch(err => done(err)); });
random_line_split
Marker.tsx
import * as React from 'react'; import clsx from 'clsx'; import { equals } from 'ramda'; import { Theme } from '@mui/material'; import makeStyles from '@mui/styles/makeStyles'; import { CreateCSSProperties } from '@mui/styles'; export enum LegendMarkerVariant { 'dot', 'bar', } interface StylesProps { color?: ...
disabled, color, variant = LegendMarkerVariant.bar, }: Props): JSX.Element => { const classes = useStyles({ color, variant }); return ( <div className={clsx(classes.icon, { [classes.disabled]: disabled })} /> ); }; export default LegendMarker;
random_line_split
fdt.rs
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use arch::android::create_android_fdt; use arch::fdt::{Error, FdtWriter}; use data_model::DataInit; use std::fs::File; use std::mem; use vm_memory::{Gu...
( fdt_max_size: usize, guest_mem: &GuestMemory, fdt_load_offset: u64, android_fstab: File, ) -> Result<usize, Error> { // Reserve space for the setup_data let fdt_data_size = fdt_max_size - mem::size_of::<setup_data>(); let mut fdt = FdtWriter::new(&[]); // The whole thing is put into ...
create_fdt
identifier_name
fdt.rs
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use arch::android::create_android_fdt; use arch::fdt::{Error, FdtWriter}; use data_model::DataInit; use std::fs::File; use std::mem; use vm_memory::{Gu...
// Reserve space for the setup_data let fdt_data_size = fdt_max_size - mem::size_of::<setup_data>(); let mut fdt = FdtWriter::new(&[]); // The whole thing is put into one giant node with some top level properties let root_node = fdt.begin_node("")?; create_android_fdt(&mut fdt, android_fstab)?...
fdt_load_offset: u64, android_fstab: File, ) -> Result<usize, Error> {
random_line_split
fdt.rs
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use arch::android::create_android_fdt; use arch::fdt::{Error, FdtWriter}; use data_model::DataInit; use std::fs::File; use std::mem; use vm_memory::{Gu...
Ok(fdt_data_size) }
{ return Err(Error::FdtGuestMemoryWriteError); }
conditional_block
fdt.rs
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use arch::android::create_android_fdt; use arch::fdt::{Error, FdtWriter}; use data_model::DataInit; use std::fs::File; use std::mem; use vm_memory::{Gu...
len: fdt_data_size as u32, }; assert!(fdt_data_size as u64 <= X86_64_FDT_MAX_SIZE); let fdt_address = GuestAddress(fdt_load_offset); guest_mem .checked_offset(fdt_address, fdt_data_size as u64) .ok_or(Error::FdtGuestMemoryWriteError)?; guest_mem .write_obj_at_addr(h...
{ // Reserve space for the setup_data let fdt_data_size = fdt_max_size - mem::size_of::<setup_data>(); let mut fdt = FdtWriter::new(&[]); // The whole thing is put into one giant node with some top level properties let root_node = fdt.begin_node("")?; create_android_fdt(&mut fdt, android_fstab...
identifier_body
models.py
from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from django.db.models.fields import FieldDoesNotExist from django.core.exceptions import ImproperlyConfigured from django.utils.timezone import now from model_utils.managers import QueryManager...
(model_class, field_name): return field_name in [f.attname for f in model_class._meta.local_fields]
_field_exists
identifier_name
models.py
from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from django.db.models.fields import FieldDoesNotExist from django.core.exceptions import ImproperlyConfigured from django.utils.timezone import now from model_utils.managers import QueryManager...
""" if not issubclass(sender, StatusModel): return for value, display in getattr(sender, 'STATUS', ()): if _field_exists(sender, value): raise ImproperlyConfigured( "StatusModel: Model '%s' has a field named '%s' which " "conflicts with a status of...
random_line_split
models.py
from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from django.db.models.fields import FieldDoesNotExist from django.core.exceptions import ImproperlyConfigured from django.utils.timezone import now from model_utils.managers import QueryManager...
models.signals.class_prepared.connect(add_status_query_managers) models.signals.class_prepared.connect(add_timeframed_query_manager) def _field_exists(model_class, field_name): return field_name in [f.attname for f in model_class._meta.local_fields]
""" Add a QueryManager for a specific timeframe. """ if not issubclass(sender, TimeFramedModel): return if _field_exists(sender, 'timeframed'): raise ImproperlyConfigured( "Model '%s' has a field named 'timeframed' " "which conflicts with the TimeFramedModel mana...
identifier_body
models.py
from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from django.db.models.fields import FieldDoesNotExist from django.core.exceptions import ImproperlyConfigured from django.utils.timezone import now from model_utils.managers import QueryManager...
if _field_exists(sender, 'timeframed'): raise ImproperlyConfigured( "Model '%s' has a field named 'timeframed' " "which conflicts with the TimeFramedModel manager." % sender.__name__ ) sender.add_to_class('timeframed', QueryManager( (models.Q(start__l...
return
conditional_block
index.js
var mysql = require('mysql'); var Q = require('q'); // database connection object var connection = mysql.createConnection({ host : 'localhost', user : 'root', password : 'root', database : 'euromillions' }); // module execution (function moduleExe(){ var promises = []; //connect to db connectTo...
() { connection.connect(function(err) { if (err) { console.error('error connecting: ' + err.stack); return; } console.log('connected as id ' + connection.threadId); }); } /** * End connection to database */ function disconnectToDb() { connection.end(function(err) { if (err) { ...
connectToDb
identifier_name
index.js
var mysql = require('mysql'); var Q = require('q'); // database connection object var connection = mysql.createConnection({ host : 'localhost', user : 'root', password : 'root', database : 'euromillions' }); // module execution (function moduleExe(){ var promises = []; //connect to db connectTo...
drawData = { draw_id: drawId, number:drawNumbers[i], is_lucky_star: is_lucky_star }; // create a deferred object to resolve with data has been inserted deferred = Q.defer(); // Push promise into array of promises promises.push(deferred.promise); // wrap connection in fun...
for (var i = 0, drawData, deferred; i < drawNumbers.length; i++) {
random_line_split
index.js
var mysql = require('mysql'); var Q = require('q'); // database connection object var connection = mysql.createConnection({ host : 'localhost', user : 'root', password : 'root', database : 'euromillions' }); // module execution (function moduleExe(){ var promises = []; //connect to db connectTo...
'SELECT d.date, count(dn.id) as cnt ' + 'FROM euromillions.draw_number AS dn ' + 'JOIN euromillions.draw AS d ON dn.draw_id = d.id '+ ' WHERE dn.is_lucky_star = 0 ' + ' AND dn.number IN (?) ' + ' GROUP BY d.date '+ ' HAVING cnt = 5;' , [input] , function(err, result) { ...
{ var deferred = Q.defer(); //get user input var input = process.argv.slice(2); input = parseIntArray(input); console.log('> input: ', input); try{ checkMainNumbers(input); } catch (Exception) { console.log('Wrong input or no input given\n'+Exception.message); deferred.resolve(); return ...
identifier_body
index.js
mysql = require('mysql'); var Q = require('q'); // database connection object var connection = mysql.createConnection({ host : 'localhost', user : 'root', password : 'root', database : 'euromillions' }); // module execution (function moduleExe(){ var promises = []; //connect to db connectToDb(...
} /** * check if all promises in the array are fulfilled * * @param promises * @returns {boolean} */ function checkAllPromises(promises) { for (var i = 0, promise; i < promises.length; i++){ promise = promises[i]; if(!promise.isFulfilled()){ return false; } } return true; } /** * Thr...
{ promise = promises[i]; promise.then(function() { areAllPromisesFulfilled = checkAllPromises(promises); // if all the promises are fulfilled then close db connection if(areAllPromisesFulfilled) { disconnectToDb(); } }); }
conditional_block
numtable.py
# -*- coding: utf-8 -*- import decimal def isNum(value): # Einai to value arithmos, i den einai ? """ use: Returns False if value is not a number , True otherwise input parameters : 1.value : the value to check against. output: True or False """ try: float(value) ...
distribution[key] = dist_d(self.posa[key], self.xiliosta[key]) def print_dist(self): self.distribute() print(', '.join(self.column_headers.values())) for col in self.column_list(): pass if __name__ == '__main__': a = ntable() a.print_dist() print(a.get_...
def distribute(self): self.distribution = {} for key in self.posa.keys(): self.
identifier_body
numtable.py
# -*- coding: utf-8 -*- import decimal def isNum(value): # Einai to value arithmos, i den einai ? """ use: Returns False if value is not a number , True otherwise input parameters : 1.value : the value to check against. output: True or False """ try: float(value) ...
nval = sum(tmpArr) dif = val - nval # Get the possible difference to fix round problem if dif == 0: pass else: # Max value Element gets the difference tmpArr[tmpArr.index(max(tmpArr))] += dif return tmpArr def dist_d(val, dist_dic, decimals=2): dist = {} ...
tmpArr.append(dec(val * dec(el, decimals) / tar, decimals))
conditional_block
numtable.py
# -*- coding: utf-8 -*- import decimal def isNum(value): # Einai to value arithmos, i den einai ? """ use: Returns False if value is not a number , True otherwise input parameters : 1.value : the value to check against. output: True or False """ try: float(value) ...
except: return tmpArr for el in distArray: tmpArr.append(dec(val * dec(el, decimals) / tar, decimals)) nval = sum(tmpArr) dif = val - nval # Get the possible difference to fix round problem if dif == 0: pass else: # Max value Element gets the difference ...
""" tmpArr = [] val = dec(val, decimals) try: tar = dec(sum(distArray), decimals)
random_line_split
numtable.py
# -*- coding: utf-8 -*- import decimal def isNum(value): # Einai to value arithmos, i den einai ? """ use: Returns False if value is not a number , True otherwise input parameters : 1.value : the value to check against. output: True or False """ try: float(value) ...
key in self.column_list(): lst.append(self.column_headers[key]) return lst def distribute(self): self.distribution = {} for key in self.posa.keys(): self.distribution[key] = dist_d(self.posa[key], self.xiliosta[key]) def print_dist(self): self...
for
identifier_name
email_settings_widget.tsx
/* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agr...
<div class={styles.formFields}> <Form compactForm={true}> <TextField label="Email" type={"email"} property={currentUser.email} helpText={"The email to which the notification is send."} docLink={docsUrl("configuration/dev_...
<h2>Email Settings</h2> </div>
random_line_split
email_settings_widget.tsx
/* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agr...
(vnode: m.Vnode<Attrs, this>): m.Children | void | null { const currentUser = vnode.attrs.currentUserVM().entity(); const disabledActionButtons = !vnode.attrs.currentUserVM().isModified(); return <div data-test-id="email-settings-widget" class={styles.formContainer}> <FormBody> <div...
view
identifier_name
email_settings_widget.tsx
/* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agr...
return currentUser.checkinAliases().join(','); } }
{ const updatedValues = newValue.trim().split(','); currentUser.checkinAliases(updatedValues); }
identifier_body
switch.py
"""Support for SCSGate switches.""" import logging import voluptuous as vol from homeassistant.components import scsgate from homeassistant.components.switch import SwitchDevice, PLATFORM_SCHEMA from homeassistant.const import ATTR_ENTITY_ID, ATTR_STATE, CONF_NAME, CONF_DEVICES import homeassistant.helpers.config_val...
(self, message): """Handle a SCSGate message related with this switch.""" if self._toggled == message.toggled: self._logger.info( "Switch %s, ignoring message %s because state already active", self._scs_id, message, ) # ...
process_event
identifier_name
switch.py
"""Support for SCSGate switches.""" import logging import voluptuous as vol from homeassistant.components import scsgate from homeassistant.components.switch import SwitchDevice, PLATFORM_SCHEMA from homeassistant.const import ATTR_ENTITY_ID, ATTR_STATE, CONF_NAME, CONF_DEVICES import homeassistant.helpers.config_val...
self.hass.bus.fire( "button_pressed", {ATTR_ENTITY_ID: self._scs_id, ATTR_STATE: command} ) class SCSGateScenarioSwitch: """Provides a SCSGate scenario switch. This switch is always in an 'off" state, when toggled it's used to trigger events. """ def __init__(self, ...
command = "on"
conditional_block
switch.py
"""Support for SCSGate switches.""" import logging import voluptuous as vol from homeassistant.components import scsgate from homeassistant.components.switch import SwitchDevice, PLATFORM_SCHEMA from homeassistant.const import ATTR_ENTITY_ID, ATTR_STATE, CONF_NAME, CONF_DEVICES import homeassistant.helpers.config_val...
def turn_on(self, **kwargs): """Turn the device on.""" from scsgate.tasks import ToggleStatusTask scsgate.SCSGATE.append_task(ToggleStatusTask(target=self._scs_id, toggled=True)) self._toggled = True self.schedule_update_ha_state() def turn_off(self, **kwargs): ...
"""Return true if switch is on.""" return self._toggled
identifier_body
switch.py
"""Support for SCSGate switches.""" import logging import voluptuous as vol from homeassistant.components import scsgate from homeassistant.components.switch import SwitchDevice, PLATFORM_SCHEMA from homeassistant.const import ATTR_ENTITY_ID, ATTR_STATE, CONF_NAME, CONF_DEVICES import homeassistant.helpers.config_val...
self._toggled = False self._logger = logger @property def scs_id(self): """Return the SCS ID.""" return self._scs_id @property def should_poll(self): """No polling needed.""" return False @property def name(self): """Return the name of t...
self._name = name self._scs_id = scs_id
random_line_split
TZlibTransport.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
return (r_percent, w_percent) def getCompSavings(self): ''' Get the current count of saved bytes due to data compression. Returns a tuple of: (inbound_saved_bytes, outbound_saved_bytes) Note: if compression is actually expanding your data (only likely with very tiny thrift ...
w_percent = self.bytes_out_comp / self.bytes_out
conditional_block
TZlibTransport.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
def _reinit_buffers(self): ''' Internal method to initialize/reset the internal StringIO objects for read and write buffers. ''' self.__rbuf = StringIO() self.__wbuf = StringIO() def _init_stats(self): ''' Internal method to reset the internal statistics counters for compressio...
self._init_zlib() self._init_stats()
random_line_split
TZlibTransport.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
def close(self): '''Close the underlying transport,''' self._reinit_buffers() self._init_zlib() return self.__trans.close() def read(self, sz): ''' Read up to sz bytes from the decompressed bytes buffer, and read from the underlying transport if the decompression buffer is empty. ...
'''Accept connections on the underlying transport''' return self.__trans.accept()
identifier_body
TZlibTransport.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
(self): '''Implement the CReadableTransport interface''' return self.__rbuf def cstringio_refill(self, partialread, reqlen): '''Implement the CReadableTransport interface for refill''' retstring = partialread if reqlen < self.DEFAULT_BUFFSIZE: retstring += self.read(self.DEFAULT_BUFFSIZE) ...
cstringio_buf
identifier_name
ws-okcoin.js
var okcoinExchange = { name: 'OKCoin', products: { quarterlies: 'Quarterlies', biWeeklies: 'Bi-Weeklies', weeklies: 'Weeklies' } }, channelToProduct = { this_week: okcoinExchange.products.weeklies, next_week: okcoinExchange.products.biW...
{ var product forEach(channelToProduct, function (key, value) { if (channel.match(new RegExp(key))) { product = value } }) if (product !== undefined) { return product } else { console.log('Unknown channel: ' + channel) } }
identifier_body
ws-okcoin.js
var okcoinExchange = { name: 'OKCoin', products: { quarterlies: 'Quarterlies', biWeeklies: 'Bi-Weeklies', weeklies: 'Weeklies' } }, channelToProduct = { this_week: okcoinExchange.products.weeklies, next_week: okcoinExchange.products.biW...
}
{ console.log('Unknown channel: ' + channel) }
conditional_block
ws-okcoin.js
var okcoinExchange = { name: 'OKCoin', products: { quarterlies: 'Quarterlies', biWeeklies: 'Bi-Weeklies', weeklies: 'Weeklies' } }, channelToProduct = { this_week: okcoinExchange.products.weeklies, next_week: okcoinExchange.products.biW...
function getProduct(channel) { var product forEach(channelToProduct, function (key, value) { if (channel.match(new RegExp(key))) { product = value } }) if (product !== undefined) { return product } else { console.log('Unknown channel: ' + channel) ...
function handleTicker(message) { var volume = parseFloat(message.data.vol) / 10 // in k$ view.updateVolume(okcoinExchange.name, getProduct(message.channel), volume) }
random_line_split
ws-okcoin.js
var okcoinExchange = { name: 'OKCoin', products: { quarterlies: 'Quarterlies', biWeeklies: 'Bi-Weeklies', weeklies: 'Weeklies' } }, channelToProduct = { this_week: okcoinExchange.products.weeklies, next_week: okcoinExchange.products.biW...
(message) { view.updateIndex(okcoinExchange.name, message.data.futureIndex) } // Last trade data function handleTrade(message) { message.data.forEach(function (trade) { view.update(okcoinExchange.name, getProduct(message.channel), 'price', parseFloat(trade[1])) }) } // Volume data function handleT...
handleIndex
identifier_name
train.py
''' Training file with functions for 1) Taking in the inputs 2) Defining the model 3) Reading the input and generating batches 4) Defining the loss, learning rate and optimization functions 5) Running multiple epochs on training and testing ''' import argparse from read_input import * from model import * import tensor...
elif args.filename[-3:] == 'txt': data = load_csv_file(args.filename) else: raise NotImplementedError("File extension not supported") train, val ,test = train_test_split(data, args.split_ratio) batch_train = BatchGenerator(train,args.batch_size,args.batch_len) batch_train.create_batches() max_batc...
parser = argparse.ArgumentParser() parser.add_argument('--filename', type=str, default='./data/tinyshakespeare/input.txt', help='data location for all data') parser.add_argument('--split_ratio', type =list, default=[0.9,0.05,0.05], help='split ratio for train, validation and test') parser.add_argument('--batch_si...
identifier_body
train.py
''' Training file with functions for 1) Taking in the inputs 2) Defining the model 3) Reading the input and generating batches 4) Defining the loss, learning rate and optimization functions 5) Running multiple epochs on training and testing ''' import argparse from read_input import * from model import * import tensor...
:param args: arguments provided by user in main :return: perplexity ''' # to run a session you need the list of tensors/graph nodes and the feed dict # for us its the cost, final_state, and optimizer # you feed in the (x,y) pairs, and you also propagate the state across the batches state = np.zeros((args...
:param max_batches: maximum number of batches that can be called
random_line_split
train.py
''' Training file with functions for 1) Taking in the inputs 2) Defining the model 3) Reading the input and generating batches 4) Defining the loss, learning rate and optimization functions 5) Running multiple epochs on training and testing ''' import argparse from read_input import * from model import * import tensor...
(): # parse arguments parser = argparse.ArgumentParser() parser.add_argument('--filename', type=str, default='./data/tinyshakespeare/input.txt', help='data location for all data') parser.add_argument('--split_ratio', type =list, default=[0.9,0.05,0.05], help='split ratio for train, validation and test') parse...
main
identifier_name
train.py
''' Training file with functions for 1) Taking in the inputs 2) Defining the model 3) Reading the input and generating batches 4) Defining the loss, learning rate and optimization functions 5) Running multiple epochs on training and testing ''' import argparse from read_input import * from model import * import tensor...
else: raise NotImplementedError("File extension not supported") train, val ,test = train_test_split(data, args.split_ratio) batch_train = BatchGenerator(train,args.batch_size,args.batch_len) batch_train.create_batches() max_batches_train = batch_train.epoch_size # New chars seen in test time will hav...
data = load_csv_file(args.filename)
conditional_block
protocol.py
_index) if cached_output is not None: return cached_output transaction = yield from self._transaction_provider(transaction_hash) if transaction is None: raise ValueError('Transaction {0} could not be retrieved'.format(bitcoin.core.b2lx(transaction_hash))) colo...
@property def asset_id(self): """ Gets the asset ID of the output. :return: The asset ID of the output, or None of the output is uncolored. :rtype: bytes | None """ return self._asset_id @property def asset_quantity(self): """ Gets the ...
""" Gets the script of the output. :return: The output script. :rtype: CScript """ return self._script
identifier_body
protocol.py
, OutputType.uncolored) for output in transaction.vout] @classmethod def _compute_asset_ids(cls, inputs, marker_output_index, outputs, asset_quantities): """ Computes the asset IDs of every output in a transaction. :param list[TransactionOutput] inputs: The outputs referenc...
asset_quantity = cls.leb128_decode(stream) # If the LEB128-encoded asset quantity of any output exceeds 9 bytes, # the marker output is deemed invalid if asset_quantity > cls.MAX_ASSET_QUANTITY: return None asset_q...
conditional_block
protocol.py
_index) if cached_output is not None: return cached_output transaction = yield from self._transaction_provider(transaction_hash) if transaction is None: raise ValueError('Transaction {0} could not be retrieved'.format(bitcoin.core.b2lx(transaction_hash))) colo...
(enum.Enum): uncolored = 0 marker_output = 1 issuance = 2 transfer = 3 class TransactionOutput(object): """Represents a transaction output and its asset ID and asset quantity.""" def __init__( self, value=-1, script=bitcoin.core.script.CScript(), ...
OutputType
identifier_name
protocol.py
return cached_output transaction = yield from self._transaction_provider(transaction_hash) if transaction is None: raise ValueError('Transaction {0} could not be retrieved'.format(bitcoin.core.b2lx(transaction_hash))) colored_outputs = yield from self.color_transaction...
:rtype: Future[TransactionOutput] """ cached_output = yield from self._cache.get(transaction_hash, output_index) if cached_output is not None:
random_line_split
lib.rs
//! Watchexec: the library //! //! This is the library version of the CLI tool [watchexec]. The tool is //! implemented with this library, but the purpose of the watchexec project is //! to deliver the CLI tool, instead of focusing on the library interface first //! and foremost. **For this reason, semver guarantees do...
pub use cli::{Args, ArgsBuilder}; pub use run::{run, watch, Handler};
mod watcher;
random_line_split
xc_path8.py
import zstackwoodpecker.test_state as ts_header import os TestAction = ts_header.TestAction def path(): return dict(initial_formation="template5", checking_point=8, path_list=[ [TestAction.create_vm, 'vm1', 'flag=ceph'], [TestAction.create_volume, 'volume1', 'flag=ceph,scsi'], [TestAction.attach_volume, 'vm1...
[TestAction.create_vm_snapshot, 'vm2', 'vm2-snapshot9'], [TestAction.clone_vm, 'vm1', 'vm3', 'full'], [TestAction.delete_volume_snapshot, 'vm1-snapshot5'], [TestAction.stop_vm, 'vm2'], [TestAction.change_vm_image, 'vm2'], [TestAction.delete_vm_snapshot, 'vm2-snapshot9'], ]) ''' The final status: Running:...
random_line_split
xc_path8.py
import zstackwoodpecker.test_state as ts_header import os TestAction = ts_header.TestAction def path():
[TestAction.change_vm_image, 'vm2'], [TestAction.delete_vm_snapshot, 'vm2-snapshot9'], ]) ''' The final status: Running:['vm1', 'vm3'] Stopped:['vm2'] Enadbled:['volume1-snapshot5', 'volume2-snapshot5', 'volume3-snapshot5', 'volume2-backup1'] attached:['volume1', 'volume2', 'volume3', 'clone@volume1', 'clone@vo...
return dict(initial_formation="template5", checking_point=8, path_list=[ [TestAction.create_vm, 'vm1', 'flag=ceph'], [TestAction.create_volume, 'volume1', 'flag=ceph,scsi'], [TestAction.attach_volume, 'vm1', 'volume1'], [TestAction.create_volume, 'volume2', 'flag=ceph,scsi'], [TestAction.attach_volume, 'vm1',...
identifier_body
xc_path8.py
import zstackwoodpecker.test_state as ts_header import os TestAction = ts_header.TestAction def
(): return dict(initial_formation="template5", checking_point=8, path_list=[ [TestAction.create_vm, 'vm1', 'flag=ceph'], [TestAction.create_volume, 'volume1', 'flag=ceph,scsi'], [TestAction.attach_volume, 'vm1', 'volume1'], [TestAction.create_volume, 'volume2', 'flag=ceph,scsi'], [TestAction.attach_volum...
path
identifier_name
pen-0.0.1.min.js
_mode_on || force) console.log('%cPEN DEBUGGER: %c' + message, 'font-family:arial,sans-serif;color:#1abf89;line-height:2em;', 'font-family:cursor,monospace;color:#333;'); }; // shift a function utils.shift = function(key, fn, time) { time = time || 50; var queue = this['_shift_fn' + key], timeout = 'shif...
return nodes; }; // remove style attr Pen.prototype.nostyle = function() { var els = this.config.editor.querySelectorAll('[style]'); [].slice.call(els).forEach(function(item) { item.removeAttribute('style'); }); return this; }; Pen.prototype.toolbar = function() { var that = ...
{ if(el.nodeName.match(/(?:[pubia]|h[1-6]|blockquote|[uo]l|li)/i)) { nodes.push(returnAsNodeName ? el.nodeName.toLowerCase() : el); } el = el.parentNode; }
conditional_block
pen-0.0.1.min.js
_mode_on || force) console.log('%cPEN DEBUGGER: %c' + message, 'font-family:arial,sans-serif;color:#1abf89;line-height:2em;', 'font-family:cursor,monospace;color:#333;'); }; // shift a function utils.shift = function(key, fn, time) { time = time || 50; var queue = this['_shift_fn' + key], timeout = 'shif...
return input.onkeypress; } apply(); }); return this; }; // highlight menu Pen.prototype.highlight = function() { var node = this._sel.focusNode , effects = this._effectNode(node) , menu = this._menu , linkInput = menu.querySelector('input') , highlight; ...
input.onkeypress = function(e) { if(e.which === 13) return createlink(e.target); };
random_line_split
relative_timeframe_to_string.ts
/* MIT License Copyright (c) 2022 Looker Data Sciences, Inc. 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, modi...
*/ import { useTranslation } from 'react-i18next' import type { RelativeTimeframeModel } from '../types/relative_timeframe_types' import { formatDate } from './format_date' export const useRelativeTimeframeToString = ( timeframe: RelativeTimeframeModel ): string => { const { t } = useTranslation('get_relative_ti...
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.
random_line_split
test_annos.py
from __future__ import division from __future__ import print_function import numpy as np import numpy.testing as npt import pandas as pd from deepcpg.data import annotations as annos def test_join_overlapping(): f = annos.join_overlapping
assert len(e) == 0 s = [1, 3, 6] e = [2, 4, 10] expect = (s, e) result = f(s, e) assert result == expect x = np.array([[1, 2], [3, 4], [4, 5], [6, 8], [8, 8], [8, 9], [10, 15], [10, 11], [11, 14], [14, 16]] ) expect...
s, e = f([], []) assert len(s) == 0
random_line_split
test_annos.py
from __future__ import division from __future__ import print_function import numpy as np import numpy.testing as npt import pandas as pd from deepcpg.data import annotations as annos def test_join_overlapping(): f = annos.join_overlapping s, e = f([], []) assert len(s) == 0 assert len(e) == 0 ...
(): start = [3, 10, 17] end = [6, 15, 18] pos = [1, 2, 5, 8, 10, 15, 16, 19] expect = [2, 1, 0, 2, 0, 0, 1, 1] start = np.asarray(start) end = np.asarray(end) pos = np.asarray(pos) actual = annos.distance(pos, start, end) npt.assert_array_equal(actual, expect) pos = [1, 6, 7, 9]...
test_distance
identifier_name
test_annos.py
from __future__ import division from __future__ import print_function import numpy as np import numpy.testing as npt import pandas as pd from deepcpg.data import annotations as annos def test_join_overlapping():
def test_in_which(): f = annos.in_which ys = [2, 4, 12, 17] ye = [2, 8, 15, 18] x = [] expect = [] result = f(x, ys, ye) npt.assert_array_equal(result, expect) x = [-1, 3, 9, 19] expect = [-1, -1, -1, -1] result = f(x, ys, ye) npt.assert_array_equal(result, expect) ...
f = annos.join_overlapping s, e = f([], []) assert len(s) == 0 assert len(e) == 0 s = [1, 3, 6] e = [2, 4, 10] expect = (s, e) result = f(s, e) assert result == expect x = np.array([[1, 2], [3, 4], [4, 5], [6, 8], [8, 8], [8, 9], ...
identifier_body
lightbox.js
a[data-lightbox], area[data-lightbox]', function(event) { self.start($(event.currentTarget)); return false; }); }; // Build html for the lightbox and the overlay. // Attach event handlers to the new DOM elements. click click click Lightbox.prototype.build = function() { var self = this; ...
function addToAlbum($link) { self.album.push({ link: $link.attr('href'), title: $link.attr('data-title') || $link.attr('title') }); } // Support both data-lightbox attribute and rel attribute implementations var dataLightboxValue = $link.attr('data-lightbox'); var $links...
this.album = []; var imageNumber = 0;
random_line_split
lightbox.js
this.$lightbox.find('.lb-container'); this.$image = this.$lightbox.find('.lb-image'); this.$nav = this.$lightbox.find('.lb-nav'); // Store css values for future lookup this.containerPadding = { top: parseInt(this.$container.css('padding-top'), 10), right: parseInt(this....
{ self.$lightbox.find('.lb-dataContainer').width(newWidth); self.$lightbox.find('.lb-prevLink').height(newHeight); self.$lightbox.find('.lb-nextLink').height(newHeight); self.showImage(); }
identifier_body
lightbox.js
a[data-lightbox], area[data-lightbox]', function(event) { self.start($(event.currentTarget)); return false; }); }; // Build html for the lightbox and the overlay. // Attach event handlers to the new DOM elements. click click click Lightbox.prototype.build = function() { var self = this; ...
// Is there a fitting issue? if ((preloader.width > maxImageWidth) || (preloader.height > maxImageHeight)) { if ((preloader.width / maxImageWidth) > (preloader.height / maxImageHeight)) { imageWidth = maxImageWidth; imageHeight = parseInt(preloader.height / (preloade...
{ maxImageHeight = self.options.maxHeight; }
conditional_block
lightbox.js
appendTo($('body')); // Cache jQuery objects this.$lightbox = $('#lightbox'); this.$overlay = $('#lightboxOverlay'); this.$outerContainer = this.$lightbox.find('.lb-outerContainer'); this.$container = this.$lightbox.find('.lb-container'); this.$image = this.$lightbox....
postResize
identifier_name
notify.rs
use notify_rust::{Notification, NotificationHint, NotificationUrgency}; use rusthub::notifications; use std::process::Command; use std::thread; use std::path::Path; const APP_NAME: &'static str = "gh-notify"; pub fn
(notification: &notifications::Notification) { let subject = format!("{} - {}", notification.subject.subject_type, notification.repository.name); let body = notification.subject.title.clone(); let url = notification.subject.url.clone(); let url = url.replace("api.", "").replace("repos/", "").replace("/p...
show_notification
identifier_name
notify.rs
use notify_rust::{Notification, NotificationHint, NotificationUrgency}; use rusthub::notifications; use std::process::Command; use std::thread; use std::path::Path; const APP_NAME: &'static str = "gh-notify"; pub fn show_notification(notification: &notifications::Notification) { let subject = format!("{} - {}", n...
} ).unwrap_or_else(|err| error!("While showing notification: {}", err)); }); } pub fn open_link(url: &str) { debug!("Opening browser link: {}", url); let _ = Command::new("sh") .arg("-c") .arg(format!("xdg-open '{}'", url)) .output() .expect("Failed to op...
random_line_split
notify.rs
use notify_rust::{Notification, NotificationHint, NotificationUrgency}; use rusthub::notifications; use std::process::Command; use std::thread; use std::path::Path; const APP_NAME: &'static str = "gh-notify"; pub fn show_notification(notification: &notifications::Notification) { let subject = format!("{} - {}", n...
pub fn notify_action<F>(summary: &str, body: &str, button_text: &str, timeout: i32, action: F) -> Result<(), String> where F: FnOnce(&str) { let icon = match Path::new("./icon.png").canonicalize() { Ok(path) => path.to_string_lossy().into_owned(), Err(_) => "clock".to_string() }; let hand...
{ debug!("Opening browser link: {}", url); let _ = Command::new("sh") .arg("-c") .arg(format!("xdg-open '{}'", url)) .output() .expect("Failed to open web browser instance."); }
identifier_body
pages.py
# -*- coding: utf-8 -*- """ The project pages map for project """ import io import os from optimus.builder.pages import PageViewBase from optimus.conf import settings from project import __version__ as sveetoy_version from project.sitemap import PageSitemap, tree_from_directory_structure from py_css_styleguide.model...
(PageViewBase): """ Basic page view """ title = "Index" template_name = "index.html" destination = "index.html" foundation_version = 6 def get_context(self): context = super(BasicPage, self).get_context() manifest = Manifest() manifest_filepath = os.path.join(se...
BasicPage
identifier_name
pages.py
# -*- coding: utf-8 -*- """ The project pages map for project """ import io import os from optimus.builder.pages import PageViewBase from optimus.conf import settings from project import __version__ as sveetoy_version from project.sitemap import PageSitemap, tree_from_directory_structure from py_css_styleguide.model...
class BasicPage(PageViewBase): """ Basic page view """ title = "Index" template_name = "index.html" destination = "index.html" foundation_version = 6 def get_context(self): context = super(BasicPage, self).get_context() manifest = Manifest() manifest_filepath = ...
""" Page objects """
random_line_split
pages.py
# -*- coding: utf-8 -*- """ The project pages map for project """ import io import os from optimus.builder.pages import PageViewBase from optimus.conf import settings from project import __version__ as sveetoy_version from project.sitemap import PageSitemap, tree_from_directory_structure from py_css_styleguide.model...
}) return context class PageWithSitemap(BasicPage): """ Page view aware of sitemap """ sitemap = {} def get_context(self): context = super(PageWithSitemap, self).get_context() context.update({ 'site_sitemap': self.sitemap, }) return co...
""" Basic page view """ title = "Index" template_name = "index.html" destination = "index.html" foundation_version = 6 def get_context(self): context = super(BasicPage, self).get_context() manifest = Manifest() manifest_filepath = os.path.join(settings.SOURCES_DIR, ...
identifier_body
lint-group-plugin.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { } }
pleaselintme
identifier_name
lint-group-plugin.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except accordin...
// file at the top-level directory of this distribution and at
random_line_split
lint-group-plugin.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
//~ WARNING item is named 'pleaselintme' #[allow(lint_me)] pub fn main() { fn lintme() { } fn pleaselintme() { } }
{ }
identifier_body
plugin.js
/** * Copyright (c) Tiny Technologies, Inc. All rights reserved. * Licensed under the LGPL or a commercial license. * For LGPL see License.txt in the project root for license information. * For commercial licenses see https://www.tiny.cloud/ * * Version: 5.3.1 (2020-05-27) */ (function () { 'use strict'; ...
Plugin(); }());
{ global.add('noneditable', function (editor) { setup(editor); }); }
identifier_body
plugin.js
/** * Copyright (c) Tiny Technologies, Inc. All rights reserved. * Licensed under the LGPL or a commercial license. * For LGPL see License.txt in the project root for license information. * For commercial licenses see https://www.tiny.cloud/ * * Version: 5.3.1 (2020-05-27) */ (function () { 'use strict'; ...
} else if (hasNonEditClass(node)) { node.attr(contentEditableAttrName, 'false'); } } }); editor.serializer.addAttributeFilter(contentEditableAttrName, function (nodes) { var i = nodes.length, node; while (i--) { node = nodes...
var i = nodes.length, node; while (i--) { node = nodes[i]; if (hasEditClass(node)) { node.attr(contentEditableAttrName, 'true');
random_line_split
plugin.js
/** * Copyright (c) Tiny Technologies, Inc. All rights reserved. * Licensed under the LGPL or a commercial license. * For LGPL see License.txt in the project root for license information. * For commercial licenses see https://www.tiny.cloud/ * * Version: 5.3.1 (2020-05-27) */ (function () { 'use strict'; ...
else if (hasNonEditClass(node)) { node.attr(contentEditableAttrName, 'false'); } } }); editor.serializer.addAttributeFilter(contentEditableAttrName, function (nodes) { var i = nodes.length, node; while (i--) { node = nodes[i]; ...
{ node.attr(contentEditableAttrName, 'true'); }
conditional_block
plugin.js
/** * Copyright (c) Tiny Technologies, Inc. All rights reserved. * Licensed under the LGPL or a commercial license. * For LGPL see License.txt in the project root for license information. * For commercial licenses see https://www.tiny.cloud/ * * Version: 5.3.1 (2020-05-27) */ (function () { 'use strict'; ...
() { global.add('noneditable', function (editor) { setup(editor); }); } Plugin(); }());
Plugin
identifier_name
rate_limit.js
import axios from 'axios'; export default function rateLimit(instance, retries = 5, wait = 1000)
if (axios.defaults.httpsAgent === config.httpsAgent) { delete config.httpsAgent; } return new Promise((resolve) => { setTimeout(() => { resolve(instance(config)); }, wait); }); } throw error; }); }
{ return instance.interceptors.response.use(null, (error) => { const config = error.config; if (!config) { return Promise.reject(error); } config.rateRetryRequest = config.rateRetryRequest || 0; const canTry = (!config.rateRetryRequest || config.rateRetryRequest < retries); if (error....
identifier_body
rate_limit.js
import axios from 'axios'; export default function rateLimit(instance, retries = 5, wait = 1000) { return instance.interceptors.response.use(null, (error) => { const config = error.config; if (!config) { return Promise.reject(error); } config.rateRetryRequest = config.rateRetryRequest || 0; ...
if (axios.defaults.httpsAgent === config.httpsAgent) { delete config.httpsAgent; } return new Promise((resolve) => { setTimeout(() => { resolve(instance(config)); }, wait); }); } throw error; }); }
{ delete config.httpAgent; }
conditional_block
rate_limit.js
import axios from 'axios'; export default function rateLimit(instance, retries = 5, wait = 1000) { return instance.interceptors.response.use(null, (error) => { const config = error.config; if (!config) { return Promise.reject(error); } config.rateRetryRequest = config.rateRetryRequest || 0; ...
delete config.agent; } if (axios.defaults.httpAgent === config.httpAgent) { delete config.httpAgent; } if (axios.defaults.httpsAgent === config.httpsAgent) { delete config.httpsAgent; } return new Promise((resolve) => { setTimeout(() => { resolve(inst...
if (error.code !== 'ECONNABORTED' && error.response.status === 403 && canTry) { config.rateRetryRequest += 1; if (axios.defaults.agent === config.agent) {
random_line_split
rate_limit.js
import axios from 'axios'; export default function
(instance, retries = 5, wait = 1000) { return instance.interceptors.response.use(null, (error) => { const config = error.config; if (!config) { return Promise.reject(error); } config.rateRetryRequest = config.rateRetryRequest || 0; const canTry = (!config.rateRetryRequest || config.rateRet...
rateLimit
identifier_name
index.js
'use strict'; /** * Rounds a number to decimal places * * @param {number} number to be rounded * @param {integer} the number of place to round to * @param {String} the rounding method to be used * @returns {number} the number rounded to places */ function roundto(value, places, roundMethod)
rtn = rtn / factorial; return rtn; } exports = module.exports = roundto;
{ var rtn = 0; var factorial = Math.pow(10, places); roundMethod = typeof roundMethod !== 'undefined' ? roundMethod : 'round'; switch( roundMethod ) { case 'floor': case 'int': rtn = Math.floor( value * factorial ); break; case 'ceiling': rtn = Math.ceil( value * factorial ); break; default: ...
identifier_body
index.js
'use strict'; /** * Rounds a number to decimal places * * @param {number} number to be rounded * @param {integer} the number of place to round to * @param {String} the rounding method to be used * @returns {number} the number rounded to places */ function
(value, places, roundMethod) { var rtn = 0; var factorial = Math.pow(10, places); roundMethod = typeof roundMethod !== 'undefined' ? roundMethod : 'round'; switch( roundMethod ) { case 'floor': case 'int': rtn = Math.floor( value * factorial ); break; case 'ceiling': rtn = Math.ceil( value * factor...
roundto
identifier_name
index.js
'use strict'; /** * Rounds a number to decimal places * * @param {number} number to be rounded * @param {integer} the number of place to round to * @param {String} the rounding method to be used * @returns {number} the number rounded to places */ function roundto(value, places, roundMethod) { var rtn = 0; va...
rtn = Math.floor( value * factorial ); break; case 'ceiling': rtn = Math.ceil( value * factorial ); break; default: rtn = Math.round( value * factorial ); break; } // Divide number by factorial to get decimal places rtn = rtn / factorial; return rtn; } exports = module.exports = roundto;
random_line_split
models.py
"""Social content items: messages aka status updates, private messages, etc.""" from __future__ import annotations import re from sqlalchemy.orm import relationship from sqlalchemy.orm.query import Query from sqlalchemy.schema import Column, ForeignKey from sqlalchemy.types import Integer, UnicodeText from abilian.c...
group_id = Column(Integer, ForeignKey(Group.id)) #: The group this message has been posted to. group = relationship("Group", primaryjoin=(group_id == Group.id), lazy="joined") query = db.session.query_property(MessageQuery) @property def tags(self) -> list[str]: return re.findall(r"(?...
content = Column(UnicodeText(), info=SEARCHABLE | {"index_to": ("text",)}) #: Nullable: if null, then message is public.
random_line_split
models.py
"""Social content items: messages aka status updates, private messages, etc.""" from __future__ import annotations import re from sqlalchemy.orm import relationship from sqlalchemy.orm.query import Query from sqlalchemy.schema import Column, ForeignKey from sqlalchemy.types import Integer, UnicodeText from abilian.c...
class Like(Entity): __tablename__ = "like" __indexable__ = False __editable__ = ["content", "message_id"] __exportable__ = __editable__ + [ "id", "created_at", "updated_at", "creator_id", "owner_id", ] content = Column(UnicodeText, info=SEARCHABLE | {...
"""Private messages are like messages, except they are private.""" __tablename__ = "private_message" __indexable__ = False __editable__ = ["content", "recipient_id"] __exportable__ = __editable__ + [ "id", "created_at", "updated_at", "creator_id", "owner_id", ...
identifier_body
models.py
"""Social content items: messages aka status updates, private messages, etc.""" from __future__ import annotations import re from sqlalchemy.orm import relationship from sqlalchemy.orm.query import Query from sqlalchemy.schema import Column, ForeignKey from sqlalchemy.types import Integer, UnicodeText from abilian.c...
(Entity): """Private messages are like messages, except they are private.""" __tablename__ = "private_message" __indexable__ = False __editable__ = ["content", "recipient_id"] __exportable__ = __editable__ + [ "id", "created_at", "updated_at", "creator_id", "...
PrivateMessage
identifier_name