file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
models.py
#!/usr/bin/python # # Copyright 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
return data_dict class QuizQuestionListModel(QuizBaseModel): """Maintains a list of question with its quiz id. This is necessary because questions may be shared between different quizes. Attributes: quiz: Reference to quiz object. question: Reference to question object asscociated with quiz....
data_dict['choices'] = random.shuffle(data_dict['choices'])
conditional_block
models.py
#!/usr/bin/python # # Copyright 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
(QuizBaseModel): """Represents a quiz. Attributes: difficulty_level: Difficulty level for the quiz (range 0-10). quiz_property: Reference to property asscociated with quiz. title: Title of the quiz. tags: Associated tags with quiz. trunk: Reference to asscociated trunk with the quiz. introd...
QuizModel
identifier_name
models.py
#!/usr/bin/python # # Copyright 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
data_dict = {'body': self.body, 'id': str(self.key())} return data_dict class QuestionModel(QuizBaseModel): """Represents a question. Attributes: body: Text asscociated with quiz. choices: List of possible choices. shuffle_choices: If set choices are randomly shuffled. h...
def dump_to_dict(self): """Dumps choice to a dictionary for passing around as JSON object."""
random_line_split
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
if '+kspace' in spec: args.append('-DFFT=FFTW3') return args
args.append('{0}=OFF'.format(opt))
conditional_block
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
(self, version): vdate = dt.datetime.strptime(str(version), "%Y%m%d") return "https://github.com/lammps/lammps/archive/patch_{0}.tar.gz".format( vdate.strftime("%d%b%Y").lstrip('0')) supported_packages = ['asphere', 'body', 'class2', 'colloid', 'compress', 'cor...
url_for_version
identifier_name
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
tags = ['ecp', 'ecp-apps'] version('develop', branch='master') version('20180629', '6d5941863ee25ad2227ff3b7577d5e7c') version('20180316', '25bad35679583e0dd8cb8753665bb84b') version('20180222', '4d0513e3183bd57721814d217fdaf957') version('20170922', '4306071f919ec7e759bda195c26cfd9a') ver...
homepage = "http://lammps.sandia.gov/" url = "https://github.com/lammps/lammps/archive/patch_1Sep2017.tar.gz" git = "https://github.com/lammps/lammps.git"
random_line_split
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
"""LAMMPS stands for Large-scale Atomic/Molecular Massively Parallel Simulator. This package uses patch releases, not stable release. See https://github.com/spack/spack/pull/5342 for a detailed discussion. """ homepage = "http://lammps.sandia.gov/" url = "https://github.com/lammps/lammp...
identifier_body
MediaAttachmentEditorUI.tsx
import {GetErrorMessagesUnderElement, Clone, E, CloneWithPrototypes} from "js-vextensions"; import {Column, Pre, RowLR, Spinner, TextInput, Row, DropDown, DropDownTrigger, Button, DropDownContent, Text, CheckBox} from "react-vcomponents"; import {BaseComponent, GetDOM, BaseComponentPlus} from "react-vextensions"; impor...
scrollView: ScrollView; render() { const {creating, editing, style, onChange} = this.props; const {newData} = this.state; const Change = (..._)=>{ if (onChange) { onChange(this.GetNewData()); } this.Update(); }; const image = Validate("UUID", newData.id) == null ? GetMedia(newData.id) : null; con...
{ if (forMount || props.baseData != this.props.baseData) // if base-data changed { this.SetState({newData: CloneWithPrototypes(props.baseData)}); } }
identifier_body
MediaAttachmentEditorUI.tsx
import {GetErrorMessagesUnderElement, Clone, E, CloneWithPrototypes} from "js-vextensions"; import {Column, Pre, RowLR, Spinner, TextInput, Row, DropDown, DropDownTrigger, Button, DropDownContent, Text, CheckBox} from "react-vcomponents"; import {BaseComponent, GetDOM, BaseComponentPlus} from "react-vextensions"; impor...
} scrollView: ScrollView; render() { const {creating, editing, style, onChange} = this.props; const {newData} = this.state; const Change = (..._)=>{ if (onChange) { onChange(this.GetNewData()); } this.Update(); }; const image = Validate("UUID", newData.id) == null ? GetMedia(newData.id) : null; ...
{ this.SetState({newData: CloneWithPrototypes(props.baseData)}); }
conditional_block
MediaAttachmentEditorUI.tsx
import {GetErrorMessagesUnderElement, Clone, E, CloneWithPrototypes} from "js-vextensions"; import {Column, Pre, RowLR, Spinner, TextInput, Row, DropDown, DropDownTrigger, Button, DropDownContent, Text, CheckBox} from "react-vcomponents"; import {BaseComponent, GetDOM, BaseComponentPlus} from "react-vextensions"; impor...
() { const {creating, editing, style, onChange} = this.props; const {newData} = this.state; const Change = (..._)=>{ if (onChange) { onChange(this.GetNewData()); } this.Update(); }; const image = Validate("UUID", newData.id) == null ? GetMedia(newData.id) : null; const enabled = creating || editing; ...
render
identifier_name
MediaAttachmentEditorUI.tsx
import {GetErrorMessagesUnderElement, Clone, E, CloneWithPrototypes} from "js-vextensions"; import {Column, Pre, RowLR, Spinner, TextInput, Row, DropDown, DropDownTrigger, Button, DropDownContent, Text, CheckBox} from "react-vcomponents"; import {BaseComponent, GetDOM, BaseComponentPlus} from "react-vextensions"; impor...
import {SourceChainsEditorUI} from "../../SourceChainsEditorUI"; type Props = {baseData: MediaAttachment, creating: boolean, editing?: boolean, style?, onChange?: (newData: MediaAttachment)=>void}; export class MediaAttachmentEditorUI extends BaseComponent<Props, {newData: MediaAttachment}> { ComponentWillMountOrRece...
import {Media} from "@debate-map/server-link/Source/Link";
random_line_split
settings.py
""" Django settings for news_project project. Generated by 'django-admin startproject' using Django 1.10.5. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ impo...
# https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' # Email Settings # EMAIL_BACKEND = 'djang...
random_line_split
HotkeyDialog.tsx
import React, { useState } from 'react' import TextField from '@mui/material/TextField'
import Help from './Help' import Fade from '@mui/material/Fade' import { useStore } from 'components/hooks/useStore' import { useTheme } from '@mui/material' import CloseButton from 'components/CloseButton' import useReduceMotion from 'libs/useReduceMotion' import { defaultTransitionDuration } from 'libs/transition' e...
import useMediaQuery from '@mui/material/useMediaQuery' import { observer } from 'mobx-react-lite' import Dialog from '@mui/material/Dialog' import DialogTitle from '@mui/material/DialogTitle' import DialogContent from '@mui/material/DialogContent'
random_line_split
models.py
from datetime import datetime from pymongo.connection import Connection from django.db import models from eventtracker.conf import settings def get_mongo_collection(): "Open a connection to MongoDB and return the collection to use." if settings.RIGHT_MONGODB_HOST: connection = Connection.paired( ...
"Dummy model for development." timestamp = models.DateTimeField(auto_now_add=True) event = models.SlugField() params = models.TextField()
identifier_body
models.py
from datetime import datetime from pymongo.connection import Connection from django.db import models from eventtracker.conf import settings def get_mongo_collection(): "Open a connection to MongoDB and return the collection to use." if settings.RIGHT_MONGODB_HOST: connection = Connection.paired( ...
return connection[settings.MONGODB_DB][settings.MONGODB_COLLECTION] def save_event(collection, event, timestamp, params): "Save the event in MongoDB collection" collection.insert({ 'event': event, 'timestamp': datetime.fromtimestamp(timestamp), 'params': params }) class ...
connection = Connection(host=settings.MONGODB_HOST, port=settings.MONGODB_PORT)
conditional_block
models.py
from datetime import datetime from pymongo.connection import Connection from django.db import models from eventtracker.conf import settings def
(): "Open a connection to MongoDB and return the collection to use." if settings.RIGHT_MONGODB_HOST: connection = Connection.paired( left=(settings.MONGODB_HOST, settings.MONGODB_PORT), right=(settings.RIGHT_MONGODB_HOST, settings.RIGHT_MONGODB_PORT) ) els...
get_mongo_collection
identifier_name
models.py
from datetime import datetime from pymongo.connection import Connection from django.db import models from eventtracker.conf import settings def get_mongo_collection(): "Open a connection to MongoDB and return the collection to use." if settings.RIGHT_MONGODB_HOST:
left=(settings.MONGODB_HOST, settings.MONGODB_PORT), right=(settings.RIGHT_MONGODB_HOST, settings.RIGHT_MONGODB_PORT) ) else: connection = Connection(host=settings.MONGODB_HOST, port=settings.MONGODB_PORT) return connection[settings.MONGODB_DB][settings.MONGOD...
connection = Connection.paired(
random_line_split
interface.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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>,...
} #[derive(PartialEq, Eq, Debug)] pub enum Token { DoctypeToken(Doctype), TagToken(Tag), CommentToken(StrTendril), CharacterTokens(StrTendril), NullCharacterToken, EOFToken, ParseError(Cow<'static, str>), } // FIXME: rust-lang/rust#22629 unsafe impl Send for Token { } /// Types which can...
{ if (self.kind != other.kind) || (self.name != other.name) { return false; } let mut self_attrs = self.attrs.clone(); let mut other_attrs = other.attrs.clone(); self_attrs.sort(); other_attrs.sort(); self_attrs == other_attrs }
identifier_body
interface.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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>,...
(&self, other: &Tag) -> bool { if (self.kind != other.kind) || (self.name != other.name) { return false; } let mut self_attrs = self.attrs.clone(); let mut other_attrs = other.attrs.clone(); self_attrs.sort(); other_attrs.sort(); self_attrs == other_...
equiv_modulo_attr_order
identifier_name
interface.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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>,...
None } }
/// The tokenizer will call this after emitting any tag. /// This allows the tree builder to change the tokenizer's state. /// By default no state changes occur. fn query_state_change(&mut self) -> Option<states::State> {
random_line_split
interface.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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>,...
let mut self_attrs = self.attrs.clone(); let mut other_attrs = other.attrs.clone(); self_attrs.sort(); other_attrs.sort(); self_attrs == other_attrs } } #[derive(PartialEq, Eq, Debug)] pub enum Token { DoctypeToken(Doctype), TagToken(Tag), CommentToken(StrTend...
{ return false; }
conditional_block
settings.py
# Django settings for wireframe project. import os PROJECT_DIR = os.path.dirname(__file__) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DAT...
TEMPLATE_LOADERS = ( ('django.template.loaders.cached.Loader', ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )), ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware...
SECRET_KEY = 'p)vc32rphaob@!7nze8@6ih5c_@ygjc%@csf*6^+d^((+%$4p#'
random_line_split
filemanager.rs
use std::path::Path; use crate::channel::*; use crate::threadpool::*; use crossbeam_channel::*; pub enum FileManagerRequests { ReadAll { file: String, sender: Sender<Message>, }, } pub struct ReadAllResult {} pub enum FileManagerRequestsResponses { Ok, ReadAllResult(ReadAllResult), }...
} }); Ok(future) } } impl<'a> Drop for FileManager<'a> { fn drop(&mut self) { if self.epoll > 0 { unsafe { libc::close(self.epoll) }; } } } #[cfg(test)] mod tests { use crate::threadpool::Threadpool; use crossbeam_channel::*; #[t...
} else { panic!("unexpected result")
random_line_split
filemanager.rs
use std::path::Path; use crate::channel::*; use crate::threadpool::*; use crossbeam_channel::*; pub enum FileManagerRequests { ReadAll { file: String, sender: Sender<Message>, }, } pub struct ReadAllResult {} pub enum
{ Ok, ReadAllResult(ReadAllResult), } pub struct FileManager<'a> { epoll: libc::c_int, dispatcher: TypedThreadDispatcher<'a, FileManagerRequests, FileManagerRequestsResponses>, } pub struct TempFile { pub path: std::path::PathBuf, } impl TempFile { pub fn all_equal(path: &str, data: u8) -> s...
FileManagerRequestsResponses
identifier_name
filemanager.rs
use std::path::Path; use crate::channel::*; use crate::threadpool::*; use crossbeam_channel::*; pub enum FileManagerRequests { ReadAll { file: String, sender: Sender<Message>, }, } pub struct ReadAllResult {} pub enum FileManagerRequestsResponses { Ok, ReadAllResult(ReadAllResult), }...
else { panic!("unexpected result") } }); Ok(future) } } impl<'a> Drop for FileManager<'a> { fn drop(&mut self) { if self.epoll > 0 { unsafe { libc::close(self.epoll) }; } } } #[cfg(test)] mod tests { use crate::thread...
{ r }
conditional_block
filemanager.rs
use std::path::Path; use crate::channel::*; use crate::threadpool::*; use crossbeam_channel::*; pub enum FileManagerRequests { ReadAll { file: String, sender: Sender<Message>, }, } pub struct ReadAllResult {} pub enum FileManagerRequestsResponses { Ok, ReadAllResult(ReadAllResult), }...
pub fn random(path: &str, mut size: usize) -> std::io::Result<Self> { use std::io::*; let _ = std::fs::remove_file(&path); let mut file = std::fs::File::create(&path)?; let mut data = vec![0u8; 4 * 1024]; while size > 0 { for v in (4 * 1024).min(0) { ...
{ use std::io::*; let _ = std::fs::remove_file(&path); let mut file = std::fs::File::create(&path)?; let mut data = vec![0u8; 16 * 1024]; for (i, v) in data.iter_mut().enumerate() { *v = f(i); } file.write_all(&data)?; file.sync_all()?; ...
identifier_body
macros.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 ...
=> ( ::syscall::syscall0( ::syscall::nr::$nr) ); ($nr:ident, $a1:expr) => ( ::syscall::syscall1( ::syscall::nr::$nr, $a1 as usize) ); ($nr:ident, $a1:expr, $a2:expr) => ( ::syscall::syscall2( ::syscall::nr::$nr, ...
#[macro_export] macro_rules! syscall { ($nr:ident)
random_line_split
index.ts
import { EffectPreRenderContext, EffectRenderContext, PluginSupport, PostEffectBase, Type, Values, } from '@ragg/delir-core' import * as clamp from 'lodash/clamp' interface Params { threshold: number keyColor: Values.ColorRGBA } export default class ChromakeyPostEffect extends PostEff...
this.tex = gl.createTexture() // get uniform locations this.uni.texture0 = gl.getUniformLocation(this.program, 'texture0') this.uni.keyColor = gl.getUniformLocation(this.program, 'keyColor') this.uni.threshold = gl.getUniformLocation(this.program, 'threshold') // get ...
{ const error = gl.getProgramInfoLog(program) throw new Error(`[@ragg/delir-posteffect-chromakey] Failed to compile shader. (${error})`) }
conditional_block
index.ts
import { EffectPreRenderContext, EffectRenderContext, PluginSupport, PostEffectBase, Type, Values, } from '@ragg/delir-core' import * as clamp from 'lodash/clamp' interface Params { threshold: number keyColor: Values.ColorRGBA } export default class ChromakeyPostEffect extends PostEff...
private static VERTEX_SHADER: string = require('./vertex.vert') private static FRAGMENT_SHADER: string = require('./fragment.frag') private ctxBindToken: PluginSupport.WebGLContextBindToken private gl: WebGL2RenderingContext private texCanvas: HTMLCanvasElement private texCanvasCtx: CanvasRen...
{ return Type.float('threshold', { label: 'Threshold', defaultValue: 1, animatable: true }).colorRgba( 'keyColor', { label: 'Key color', defaultValue: new Values.ColorRGBA(0, 0, 0, 1), animatable: true }, ) }
identifier_body
index.ts
import { EffectPreRenderContext, EffectRenderContext, PluginSupport, PostEffectBase, Type, Values, } from '@ragg/delir-core' import * as clamp from 'lodash/clamp' interface Params { threshold: number keyColor: Values.ColorRGBA } export default class ChromakeyPostEffect extends PostEff...
gl.enableVertexAttribArray(this.attribs.coord) gl.vertexAttribPointer(this.attribs.coord, 2, gl.FLOAT, false, 0, 0) // Update texture gl.activeTexture(gl.TEXTURE0) gl.bindTexture(gl.TEXTURE_2D, this.tex) gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE,...
gl.enableVertexAttribArray(this.attribs.position) gl.vertexAttribPointer(this.attribs.position, 2, gl.FLOAT, false, 0, 0) gl.bindBuffer(gl.ARRAY_BUFFER, this.tex2DBuffer)
random_line_split
index.ts
import { EffectPreRenderContext, EffectRenderContext, PluginSupport, PostEffectBase, Type, Values, } from '@ragg/delir-core' import * as clamp from 'lodash/clamp' interface Params { threshold: number keyColor: Values.ColorRGBA } export default class ChromakeyPostEffect extends PostEff...
(req: EffectRenderContext<Params>) { const { srcCanvas, destCanvas, parameters: { threshold, keyColor }, } = req const destCtx = destCanvas.getContext('2d') const gl = await req.glContextPool.getContextByToken(this.ctxBindToken) const canvas =...
render
identifier_name
st_wc_merge_017.js
/* Copyright 2010-2013 SourceGear, LLC 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, softwar...
() { var my_group = "st_wc_merge_017"; // this variable must match the above group name. this.no_setup = true; // do not create an initial REPO and WD. ////////////////////////////////////////////////////////////////// load("update_helpers.js"); // load the helper functions initialize_u...
st_wc_merge_017
identifier_name
st_wc_merge_017.js
/* Copyright 2010-2013 SourceGear, LLC 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, softwar...
{ var my_group = "st_wc_merge_017"; // this variable must match the above group name. this.no_setup = true; // do not create an initial REPO and WD. ////////////////////////////////////////////////////////////////// load("update_helpers.js"); // load the helper functions initialize_upda...
identifier_body
st_wc_merge_017.js
/* Copyright 2010-2013 SourceGear, LLC 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, softwar...
////////////////////////////////////////////////////////////////// // Do a CLEAN MERGE. ////////////////////////////////////////////////////////////////// vscript_test_wc__print_section_divider("Checkout B, Create B1, and clean merge C into it."); my_make_wd(this); vscript_test_wc__checkout_np( { "repo" : repo...
random_line_split
constants.py
KEY_UP = "up" KEY_DOWN = "down" KEY_RIGHT = "right" KEY_LEFT = "left" KEY_INSERT = "insert" KEY_HOME = "home" KEY_END = "end" KEY_PAGEUP = "pageup" KEY_PAGEDOWN = "pagedown" KEY_BACKSPACE ...
KEY_KEYPAD4 = "keypad4" KEY_KEYPAD5 = "keypad5" KEY_KEYPAD6 = "keypad6" KEY_KEYPAD7 = "keypad7" KEY_KEYPAD8 = "keypad8" KEY_KEYPAD9 = "keypad9" KEY_KEYPAD_PERIOD = "keypad_period" KEY_KEYPAD_DIVIDE = "keypad_divide" KEY_KEYPAD_MULTIPLY ...
KEY_SPACE = "space" KEY_KEYPAD0 = "keypad0" KEY_KEYPAD1 = "keypad1" KEY_KEYPAD2 = "keypad2" KEY_KEYPAD3 = "keypad3"
random_line_split
arg-modules-demo.js
/*let calculator = (function () { let result = 0; function add(x) { result += x; return this; } function subtract(x) { result -= x; return this; } function getResult() { return result; } return{ add, subtract, getResult } })();*/ // our lasted obj starts as empty let calculator = {}; // private if...
(x) { result -= x; return this; } function getResult() { return result; } module.add = add; module.subtract = subtract; module.getResult = getResult; }(calculator)); // calling it with our obj (function (module) { module.add42 = function () { this.add(42);...
subtract
identifier_name
arg-modules-demo.js
/*let calculator = (function () { let result = 0; function add(x) { result += x; return this; } function subtract(x) { result -= x; return this; } function getResult() { return result; } return{ add, subtract, getResult } })();*/ // our lasted obj starts as empty let calculator = {}; // private if...
// calling it with our obj (function (module) { module.add42 = function () { this.add(42); }; }(calculator)); calculator.add42(); console.log(calculator.add(5).getResult());
random_line_split
arg-modules-demo.js
/*let calculator = (function () { let result = 0; function add(x) { result += x; return this; } function subtract(x) { result -= x; return this; } function getResult() { return result; } return{ add, subtract, getResult } })();*/ // our lasted obj starts as empty let calculator = {}; // private if...
function subtract(x) { result -= x; return this; } function getResult() { return result; } module.add = add; module.subtract = subtract; module.getResult = getResult; }(calculator)); // calling it with our obj (function (module) { module.add42 = function () ...
{ result += x; return this; }
identifier_body
utils.py
class TranslationDictionary(object): """ TranslationDictionary """ def __init__(self, dictionaries=None, default=None): self.dictionaries = dictionaries or { 'pt': ('portuguese', _('Portuguese')), 'en': ('english', _('English')), 'es': ('spanish', _('Spanish...
(self, languages=None): if languages: return tuple(self.get_dictionary(l) for l in self.dictionaries) return self.dictionaries.values()
get_dictionaries
identifier_name
utils.py
class TranslationDictionary(object): """ TranslationDictionary """ def __init__(self, dictionaries=None, default=None): self.dictionaries = dictionaries or { 'pt': ('portuguese', _('Portuguese')), 'en': ('english', _('English')), 'es': ('spanish', _('Spanish'...
'da': ('danish', _('Danish')), 'nl': ('dutch', _('Dutch')), 'fi': ('finnish', _('Finnish')), 'fr': ('french', _('French')), 'hu': ('hungarian', _('Hungarian')), 'it': ('italian', _('Italian')), 'nn': ('norwegian', _('Norwegian')), ...
random_line_split
utils.py
class TranslationDictionary(object): """ TranslationDictionary """ def __init__(self, dictionaries=None, default=None): self.dictionaries = dictionaries or { 'pt': ('portuguese', _('Portuguese')), 'en': ('english', _('English')), 'es': ('spanish', _('Spanish...
return self.dictionaries.values()
return tuple(self.get_dictionary(l) for l in self.dictionaries)
conditional_block
utils.py
class TranslationDictionary(object): """ TranslationDictionary """ def __init__(self, dictionaries=None, default=None): self.dictionaries = dictionaries or { 'pt': ('portuguese', _('Portuguese')), 'en': ('english', _('English')), 'es': ('spanish', _('Spanish...
def get_dictionaries(self, languages=None): if languages: return tuple(self.get_dictionary(l) for l in self.dictionaries) return self.dictionaries.values()
return self.get_dictionary_tuple(language)[0]
identifier_body
default_impl.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::collections::HashSet; use std::future::Future; use std::sync::Arc; use futures::future::BoxFuture;...
( this: &(impl DagAlgorithm + ?Sized), set: NameSet, ) -> Result<NameSet> { let mut to_visit: Vec<VertexName> = { let mut list = Vec::with_capacity(set.count().await?); let mut iter = set.iter().await?; while let Some(next) = iter.next().await { let vertex = next?; ...
first_ancestors
identifier_name
default_impl.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::collections::HashSet; use std::future::Future; use std::sync::Arc; use futures::future::BoxFuture;...
} } let hints = Hints::new_inherit_idmap_dag(set.hints()); let set = NameSet::from_iter(visited.into_iter().map(Ok), hints); this.sort(&set).await } pub(crate) async fn heads(this: &(impl DagAlgorithm + ?Sized), set: NameSet) -> Result<NameSet> { Ok(set.clone() - this.parents(set).await?) ...
{ to_visit.push(parent); }
conditional_block
default_impl.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::collections::HashSet; use std::future::Future; use std::sync::Arc; use futures::future::BoxFuture;...
pub(crate) async fn gca_all(this: &(impl DagAlgorithm + ?Sized), set: NameSet) -> Result<NameSet> { this.heads_ancestors(this.common_ancestors(set).await?) .await } pub(crate) async fn common_ancestors( this: &(impl DagAlgorithm + ?Sized), set: NameSet, ) -> Result<NameSet> { let result = mat...
{ this.gca_all(set) .await? .iter() .await? .next() .await .transpose() }
identifier_body
default_impl.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::collections::HashSet; use std::future::Future; use std::sync::Arc; use futures::future::BoxFuture;...
} async fn hint_subdag_for_insertion(&self, _heads: &[VertexName]) -> Result<MemNameDag> { // No need to use such a hint (to avoid infinite recursion). // Pending names should exist in the graph without using remote fetching. Ok(MemNameDag::new()) } } ...
} } Ok(filtered_parents)
random_line_split
qr.js
$(function () { $.widget("as24.qr", { _create: function () { var self = this; $(self.element).find('[data-description="QR-Code Generation"]').find("p").hide(); $(self.element).find('[data-generate="qr-code"]').click(function () { $(self.element).f...
}); })
random_line_split
workspaceTimeoutWarn.js
const util = require('util'); const config = require('../lib/config'); const logger = require('../lib/logger'); const workspaceHelper = require('../lib/workspace'); const sqldb = require('../prairielib/lib/sql-db'); const sqlLoader = require('../prairielib/lib/sql-loader'); const sql = sqlLoader.loadSqlEquiv(__filena...
`WARNING: This workspace will stop in < ${time_to_timeout_min} min. Click "Reboot" to keep working.` ); } }; module.exports.run = util.callbackify(module.exports.runAsync);
for (const workspace of workspaces) { logger.verbose(`workspaceTimeoutWarn: timeout warning for workspace_id = ${workspace.id}`); const time_to_timeout_min = Math.ceil(workspace.time_to_timeout_sec / 60); await workspaceHelper.updateMessage( workspace.id,
random_line_split
p1_no_assignee.py
# 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/. from libmozdata import utils as lmdutils from auto_nag import utils from auto_nag.bzcleaner import BzCleaner from auto_...
def get_extra_for_nag_template(self): return self.get_extra_for_template() def get_extra_for_needinfo_template(self): return self.get_extra_for_template() def ignore_meta(self): return True def has_last_comment_time(self): return True def has_product_component(s...
return {"ndays": self.ndays}
identifier_body
p1_no_assignee.py
# 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/. from libmozdata import utils as lmdutils from auto_nag import utils from auto_nag.bzcleaner import BzCleaner from auto_...
return None def set_people_to_nag(self, bug, buginfo): priority = "high" if not self.filter_bug(priority): return None owners = self.round_robin.get(bug, self.date, only_one=False, has_nick=False) real_owner = bug["triage_owner"] self.add_triage_owner(ow...
mail, nick = self.round_robin.get(bug, self.date) if mail and nick: return {"mail": mail, "nickname": nick}
random_line_split
p1_no_assignee.py
# 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/. from libmozdata import utils as lmdutils from auto_nag import utils from auto_nag.bzcleaner import BzCleaner from auto_...
(BzCleaner, Nag): def __init__(self): super(P1NoAssignee, self).__init__() self.escalation = Escalation( self.people, data=utils.get_config(self.name(), "escalation"), skiplist=utils.get_config("workflow", "supervisor_skiplist", []), ) self.round_r...
P1NoAssignee
identifier_name
p1_no_assignee.py
# 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/. from libmozdata import utils as lmdutils from auto_nag import utils from auto_nag.bzcleaner import BzCleaner from auto_...
return None def set_people_to_nag(self, bug, buginfo): priority = "high" if not self.filter_bug(priority): return None owners = self.round_robin.get(bug, self.date, only_one=False, has_nick=False) real_owner = bug["triage_owner"] self.add_triage_owner(...
return {"mail": mail, "nickname": nick}
conditional_block
SelectFilterPlugin.tsx
/** * 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...
else { // reset data mask based on filter state updateDataMask(filterState.value); } }, [ col, isDisabled, defaultToFirstItem, enableEmptyFilter, inverseSelection, updateDataMask, data, groupby, JSON.stringify(filterState), ]); useEffect(() => { setDataMas...
{ // empty selection if filter is disabled updateDataMask(null); }
conditional_block
SelectFilterPlugin.tsx
/** * 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...
( draft: DataMask & { __cache?: JsonObject }, action: DataMaskAction, ) { switch (action.type) { case 'ownState': draft.ownState = { ...draft.ownState, ...action.ownState, }; return draft; case 'filterState': draft.extraFormData = action.extraFormData; // esli...
reducer
identifier_name
SelectFilterPlugin.tsx
/** * 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...
debounce((val: string) => { dispatchDataMask({ type: 'ownState', ownState: { coltypeMap: initialColtypeMap, search: val, }, }); }, SLOW_DEBOUNCE), [], ); const searchWrapper = (val: string) => { if (searchAllOptions) { debouncedOwnStateF...
const debouncedOwnStateFunc = useCallback(
random_line_split
SelectFilterPlugin.tsx
/** * 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...
{ const { coltypeMap, data, filterState, formData, height, isRefreshing, width, setDataMask, setFocusedFilter, unsetFocusedFilter, appSection, } = props; const { enableEmptyFilter, multiSelect, showSearch, inverseSelection, inputRef, defaultToFir...
identifier_body
OutputStream.py
# Copyright (c) 2012. Los Alamos National Security, LLC. # This material was produced under U.S. Government contract DE-AC52-06NA25396 # for Los Alamos National Laboratory (LANL), which is operated by Los Alamos # National Security, LLC for the U.S. Department of Energy. The U.S. Government # has rights to use, rep...
(self): self.output_str = StringIO() # define output stream writer method # sim_obj should be derived from either PyEntity or PyService def write(self,sim_obj,record_type,*message): for token in message: self.output_str.write(str(token)); self.output_str.w...
__init__
identifier_name
OutputStream.py
# Copyright (c) 2012. Los Alamos National Security, LLC. # This material was produced under U.S. Government contract DE-AC52-06NA25396 # for Los Alamos National Laboratory (LANL), which is operated by Los Alamos # National Security, LLC for the U.S. Department of Energy. The U.S. Government # has rights to use, rep...
core.output(sim_obj,record_type,self.output_str.getvalue()) self.output_str.truncate(0) # create output stream output = OutputStream()
self.output_str.write(str(token)); self.output_str.write(" ");
conditional_block
OutputStream.py
# Copyright (c) 2012. Los Alamos National Security, LLC. # This material was produced under U.S. Government contract DE-AC52-06NA25396 # for Los Alamos National Laboratory (LANL), which is operated by Los Alamos # National Security, LLC for the U.S. Department of Energy. The U.S. Government # has rights to use, rep...
# create output stream output = OutputStream()
for token in message: self.output_str.write(str(token)); self.output_str.write(" "); core.output(sim_obj,record_type,self.output_str.getvalue()) self.output_str.truncate(0)
identifier_body
OutputStream.py
# Copyright (c) 2012. Los Alamos National Security, LLC. # This material was produced under U.S. Government contract DE-AC52-06NA25396 # for Los Alamos National Laboratory (LANL), which is operated by Los Alamos # National Security, LLC for the U.S. Department of Energy. The U.S. Government # has rights to use, rep...
# create output stream output = OutputStream()
random_line_split
NodeList-manipulate.js
/* Copyright (c) 2004-2010, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojo.NodeList-manipulate"]){ dojo._hasResource["dojo.NodeList-manipulate"]=true; dojo.provide("dojo....
var _e=this.length; for(var j=_e-1,_f;_f=this[j];j--){ if(i>0){ _f=this._cloneNode(_f); _c.unshift(_f); } if(j==_e-1){ dojo.place(_f,_d,_a); }else{ _d.parentNode.insertBefore(_f,_d); } _d=_f; } } if(_c.length){ _c.unshift(0); _c.unshift(this.length-1); Array.prototype.splice.apply(this,_c); } return this; },innerHTML:f...
for(var i=0;i<_b.length;i++){ var _d=_b[i];
random_line_split
NodeList-manipulate.js
/* Copyright (c) 2004-2010, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojo.NodeList-manipulate"]){ dojo._hasResource["dojo.NodeList-manipulate"]=true; dojo.provide("dojo....
(_2){ var _3="",ch=_2.childNodes; for(var i=0,n;n=ch[i];i++){ if(n.nodeType!=8){ if(n.nodeType==1){ _3+=_1(n); }else{ _3+=n.nodeValue; } } } return _3; }; function _4(_5){ while(_5.childNodes[0]&&_5.childNodes[0].nodeType==1){ _5=_5.childNodes[0]; } return _5; }; function _6(_7,_8){ if(typeof _7=="string"){ _7=dojo._to...
_1
identifier_name
NodeList-manipulate.js
/* Copyright (c) 2004-2010, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojo.NodeList-manipulate"]){ dojo._hasResource["dojo.NodeList-manipulate"]=true; dojo.provide("dojo....
; dojo.extend(dojo.NodeList,{_placeMultiple:function(_9,_a){ var _b=typeof _9=="string"||_9.nodeType?dojo.query(_9):_9; var _c=[]; for(var i=0;i<_b.length;i++){ var _d=_b[i]; var _e=this.length; for(var j=_e-1,_f;_f=this[j];j--){ if(i>0){ _f=this._cloneNode(_f); _c.unshift(_f); } if(j==_e-1){ dojo.place(_f,_d,_a); }els...
{ if(typeof _7=="string"){ _7=dojo._toDom(_7,(_8&&_8.ownerDocument)); if(_7.nodeType==11){ _7=_7.childNodes[0]; } }else{ if(_7.nodeType==1&&_7.parentNode){ _7=_7.cloneNode(false); } } return _7; }
identifier_body
NodeList-manipulate.js
/* Copyright (c) 2004-2010, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojo.NodeList-manipulate"]){ dojo._hasResource["dojo.NodeList-manipulate"]=true; dojo.provide("dojo....
_14=_17.value||""; if(_17.nodeName.toUpperCase()=="SELECT"&&_17.multiple){ _14=[]; _1b=_17.options; for(i=0;i<_1b.length;i++){ opt=_1b[i]; if(opt.selected){ _14.push(opt.value); } } if(!_14.length){ _14=null; } } return _14; } },append:function(_1c){ return this.addContent(_1c,"last"); },appendTo:function(_1d){ return...
{ return undefined; }
conditional_block
main.browser.ts
/* * Providers provided by Angular */ import {bootstrap} from 'angular2/platform/browser'; /* * App Component * our top level component that holds all of our components */ import {DIRECTIVES, PIPES, PROVIDERS} from './platform/browser'; import {ENV_PROVIDERS} from './platform/environment'; import {provideStore} f...
*/ function bootstrapDomReady() { // bootstrap after document is ready return document.addEventListener('DOMContentLoaded', main); } if ('development' === ENV) { // activate hot module reload if (HMR) { if (document.readyState === 'complete') { main(); } else { bootstrapDomReady(); } ...
/* * Hot Module Reload * experimental version by @gdi2290
random_line_split
main.browser.ts
/* * Providers provided by Angular */ import {bootstrap} from 'angular2/platform/browser'; /* * App Component * our top level component that holds all of our components */ import {DIRECTIVES, PIPES, PROVIDERS} from './platform/browser'; import {ENV_PROVIDERS} from './platform/environment'; import {provideStore} f...
() { return bootstrap(App, [ ...ENV_PROVIDERS, ...PROVIDERS, ...DIRECTIVES, ...PIPES, ...provideStore({counter}), ...[MDL] ]) .catch(err => console.error(err)); } /* * Vendors * For vendors for example jQuery, Lodash, angular2-jwt just import them anywhere in your app * You can a...
main
identifier_name
main.browser.ts
/* * Providers provided by Angular */ import {bootstrap} from 'angular2/platform/browser'; /* * App Component * our top level component that holds all of our components */ import {DIRECTIVES, PIPES, PROVIDERS} from './platform/browser'; import {ENV_PROVIDERS} from './platform/environment'; import {provideStore} f...
else { bootstrapDomReady(); } } else { bootstrapDomReady(); }
{ if (document.readyState === 'complete') { main(); } else { bootstrapDomReady(); } module.hot.accept(); }
conditional_block
main.browser.ts
/* * Providers provided by Angular */ import {bootstrap} from 'angular2/platform/browser'; /* * App Component * our top level component that holds all of our components */ import {DIRECTIVES, PIPES, PROVIDERS} from './platform/browser'; import {ENV_PROVIDERS} from './platform/environment'; import {provideStore} f...
if ('development' === ENV) { // activate hot module reload if (HMR) { if (document.readyState === 'complete') { main(); } else { bootstrapDomReady(); } module.hot.accept(); } else { bootstrapDomReady(); } } else { bootstrapDomReady(); }
{ // bootstrap after document is ready return document.addEventListener('DOMContentLoaded', main); }
identifier_body
parser.py
#!/usr/bin/env python3 # This file is a part of Templ # Copyright (C) 2012 Zachary Dziura # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option...
import htmltag class Parser: """Parses .tmpl file to be outputted as an html file. """ def __init__(self, config_file = 'templ.conf'): self.config_file = config_file self.tree = None self.rules = {} self._load_config() def _load_config(self): """Loads the configurat...
random_line_split
parser.py
#!/usr/bin/env python3 # This file is a part of Templ # Copyright (C) 2012 Zachary Dziura # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option...
(self, name, attributes = {}, children = []): self.name = name self.attributes = attributes self.children = children
__init__
identifier_name
parser.py
#!/usr/bin/env python3 # This file is a part of Templ # Copyright (C) 2012 Zachary Dziura # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option...
else: raise NodeNotFoundError(node_name) def remove_nodes(self, node_name): """Remove all nodes of a given name from the tree. If no nodes exist in the tree, return a NodeNotFoundError. Parameters: Node_Name - The name of the notes ...
del self.nodes[node.name]
conditional_block
parser.py
#!/usr/bin/env python3 # This file is a part of Templ # Copyright (C) 2012 Zachary Dziura # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option...
class NodeNotFoundError(Exception): """Error to be thrown when node is not found in tree.""" def __init__(self, name): self.name = name def __str__(self): return repr(self.name) class Tree: """A parser syntax tree. The syntax tree is nothing more tha...
"""Parses .tmpl file to be outputted as an html file. """ def __init__(self, config_file = 'templ.conf'): self.config_file = config_file self.tree = None self.rules = {} self._load_config() def _load_config(self): """Loads the configuration settings from the config_file....
identifier_body
mouse.rs
//! Back-end agnostic mouse buttons. use num::{ FromPrimitive, ToPrimitive }; /// Represent a mouse button. #[derive(Copy, Clone, RustcDecodable, RustcEncodable, PartialEq, Eq, Ord, PartialOrd, Hash, Debug)] pub enum MouseButton { /// Unknown mouse button. Unknown, /// Left mouse button. Left, ...
} impl ToPrimitive for MouseButton { fn to_u64(&self) -> Option<u64> { match self { &MouseButton::Unknown => Some(0), &MouseButton::Left => Some(1), &MouseButton::Right => Some(2), &MouseButton::Middle => Some(3), &MouseButton::X1 => Some(4), ...
{ FromPrimitive::from_u64(n as u64) }
identifier_body
mouse.rs
//! Back-end agnostic mouse buttons. use num::{ FromPrimitive, ToPrimitive };
#[derive(Copy, Clone, RustcDecodable, RustcEncodable, PartialEq, Eq, Ord, PartialOrd, Hash, Debug)] pub enum MouseButton { /// Unknown mouse button. Unknown, /// Left mouse button. Left, /// Right mouse button. Right, /// Middle mouse button. Middle, /// Extra mouse button number...
/// Represent a mouse button.
random_line_split
mouse.rs
//! Back-end agnostic mouse buttons. use num::{ FromPrimitive, ToPrimitive }; /// Represent a mouse button. #[derive(Copy, Clone, RustcDecodable, RustcEncodable, PartialEq, Eq, Ord, PartialOrd, Hash, Debug)] pub enum MouseButton { /// Unknown mouse button. Unknown, /// Left mouse button. Left, ...
(&self) -> Option<u64> { match self { &MouseButton::Unknown => Some(0), &MouseButton::Left => Some(1), &MouseButton::Right => Some(2), &MouseButton::Middle => Some(3), &MouseButton::X1 => Some(4), &MouseButton::X2 => Some(5), &M...
to_u64
identifier_name
log.rs
/* Copyright (C) 2021 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
(tx: &ModbusTransaction, js: &mut JsonBuilder) -> Result<(), JsonError> { js.open_object("modbus")?; js.set_uint("id", tx.id)?; if let Some(req) = &tx.request { js.open_object("request")?; log_message(&req, js)?; js.close()?; } if let Some(resp) = &tx.response { js....
log
identifier_name
log.rs
/* Copyright (C) 2021 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
} js.close()?; Ok(()) } fn log_message(msg: &Message, js: &mut JsonBuilder) -> Result<(), JsonError> { js.set_uint("transaction_id", msg.transaction_id.into())?; js.set_uint("protocol_id", msg.protocol_id.into())?; js.set_uint("unit_id", msg.unit_id.into())?; js.set_uint("function_raw", ms...
if let Some(resp) = &tx.response { js.open_object("response")?; log_message(&resp, js)?; js.close()?;
random_line_split
log.rs
/* Copyright (C) 2021 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
/// populate a json object with transactional information, for logging fn log(tx: &ModbusTransaction, js: &mut JsonBuilder) -> Result<(), JsonError> { js.open_object("modbus")?; js.set_uint("id", tx.id)?; if let Some(req) = &tx.request { js.open_object("request")?; log_message(&req, js)?;...
{ log(tx, js).is_ok() }
identifier_body
PanelAddColumnButton.ts
import {SearchBox} from 'lineupjs'; import {ISearchOption} from './ISearchOption'; import {IPanelButton, PanelButton, IPanelButtonOptions} from './PanelButton'; import {I18nextManager} from '../../i18n'; export interface IPanelAddColumnButtonOptions extends Pick<IPanelButtonOptions, 'btnClass'> { // nothing to add }...
(parent: HTMLElement, private readonly search: SearchBox<ISearchOption>, options?: IPanelAddColumnButtonOptions) { this.node = parent.ownerDocument.createElement('div'); this.node.classList.add('lu-adder'); this.node.addEventListener('mouseleave', () => { this.node.classList.remove('once'); }); ...
constructor
identifier_name
PanelAddColumnButton.ts
import {SearchBox} from 'lineupjs'; import {ISearchOption} from './ISearchOption'; import {IPanelButton, PanelButton, IPanelButtonOptions} from './PanelButton'; import {I18nextManager} from '../../i18n'; export interface IPanelAddColumnButtonOptions extends Pick<IPanelButtonOptions, 'btnClass'> { // nothing to add }...
}); const button = new PanelButton(this.node, Object.assign(options, { title: I18nextManager.getInstance().i18n.t('tdp:core.lineup.LineupPanelActions.addColumnButton'), faIcon: 'fas fa-plus', onClick: () => { this.node.classList.add('once'); (<HTMLElement>this.search.node.quer...
this.node = parent.ownerDocument.createElement('div'); this.node.classList.add('lu-adder'); this.node.addEventListener('mouseleave', () => { this.node.classList.remove('once');
random_line_split
PanelAddColumnButton.ts
import {SearchBox} from 'lineupjs'; import {ISearchOption} from './ISearchOption'; import {IPanelButton, PanelButton, IPanelButtonOptions} from './PanelButton'; import {I18nextManager} from '../../i18n'; export interface IPanelAddColumnButtonOptions extends Pick<IPanelButtonOptions, 'btnClass'> { // nothing to add }...
}
{ this.node = parent.ownerDocument.createElement('div'); this.node.classList.add('lu-adder'); this.node.addEventListener('mouseleave', () => { this.node.classList.remove('once'); }); const button = new PanelButton(this.node, Object.assign(options, { title: I18nextManager.getInstance().i...
identifier_body
ui_infopanel.py
import wx import functions infoItems=[ ("active time", functions.FormatTime), ("active workers", None), ("active tasks", None), ("tasks done", None), ("pending urls", None), ("unique urls found", None), ("bytes read", functions.FormatByte), ("processing speed", functions.FormatByteSpeed), ("c...
def Update(self, info): for key, f in infoItems: if f: val=f(info[key]) else: val=str(info[key]) if self.text[key].GetLabel()!=val: self.text[key].SetLabel(val) self.Layout()
wx.Panel.__init__(self, parent) self.sizer=wx.GridSizer(rows=len(infoItems), cols=2) self.text={} for key, f in infoItems: self.text[key+"_TITLE"]=wx.StaticText(self, label=key+":") self.text[key]=wx.StaticText(self) self.text[key].SetMaxSize((-1, 20)) self.text[key+"_TITLE"].SetMaxSize((-1, 20...
identifier_body
ui_infopanel.py
import wx import functions infoItems=[ ("active time", functions.FormatTime), ("active workers", None), ("active tasks", None), ("tasks done", None), ("pending urls", None), ("unique urls found", None), ("bytes read", functions.FormatByte), ("processing speed", functions.FormatByteSpeed), ("c...
if self.text[key].GetLabel()!=val: self.text[key].SetLabel(val) self.Layout()
val=str(info[key])
conditional_block
ui_infopanel.py
import wx import functions infoItems=[ ("active time", functions.FormatTime), ("active workers", None), ("active tasks", None), ("tasks done", None), ("pending urls", None), ("unique urls found", None), ("bytes read", functions.FormatByte), ("processing speed", functions.FormatByteSpeed), ("c...
("http 5xx",None)] class InfoPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) self.sizer=wx.GridSizer(rows=len(infoItems), cols=2) self.text={} for key, f in infoItems: self.text[key+"_TITLE"]=wx.StaticText(self, label=key+":") self.text[key]=wx.StaticText(self) ...
random_line_split
ui_infopanel.py
import wx import functions infoItems=[ ("active time", functions.FormatTime), ("active workers", None), ("active tasks", None), ("tasks done", None), ("pending urls", None), ("unique urls found", None), ("bytes read", functions.FormatByte), ("processing speed", functions.FormatByteSpeed), ("c...
(self, info): for key, f in infoItems: if f: val=f(info[key]) else: val=str(info[key]) if self.text[key].GetLabel()!=val: self.text[key].SetLabel(val) self.Layout()
Update
identifier_name
Handler.js
"use strict"; var _ = require("lodash"); var Base = require("./Base"); var User = require("./User"); var UpdateMixin = require("./UpdateMixin"); /** * Ticket handler model for the client * * @namespace models.client * @class Handler * @extends models.client.Base * @uses models.client.UpdateMixin */ var Handle...
return this.rel("handler"); }, }); _.extend(Handler.prototype, UpdateMixin); module.exports = Handler;
* * @method getUser * @return {models.client.User} */ getUser: function(){
random_line_split
quiz_error.rs
extern crate diesel; use self::diesel::result::Error as DatabaseError; use std::error; use std::fmt; use std::convert::From; #[derive(Debug)] pub enum QuizError { DatabaseError(DatabaseError), JokerUnavailable, GameAlreadyFinished, NoGameInProgress, GameStillInProgress, StateError, OutOfR...
(err: DatabaseError) -> Self { QuizError::DatabaseError(err) } }
from
identifier_name
quiz_error.rs
extern crate diesel; use self::diesel::result::Error as DatabaseError; use std::error; use std::fmt; use std::convert::From; #[derive(Debug)] pub enum QuizError { DatabaseError(DatabaseError), JokerUnavailable, GameAlreadyFinished, NoGameInProgress, GameStillInProgress, StateError, OutOfR...
write!(f, "Game already finished error: Tried to interact with a game that has already been finished") } QuizError::NoGameInProgress => { write!(f, "No game in progress error: Tried to play without starting a game firs...
random_line_split
quiz_error.rs
extern crate diesel; use self::diesel::result::Error as DatabaseError; use std::error; use std::fmt; use std::convert::From; #[derive(Debug)] pub enum QuizError { DatabaseError(DatabaseError), JokerUnavailable, GameAlreadyFinished, NoGameInProgress, GameStillInProgress, StateError, OutOfR...
} impl error::Error for QuizError { fn description(&self) -> &str { match *self { QuizError::DatabaseError(ref err) => err.description(), QuizError::JokerUnavailable => "Joker unavailable error", QuizError::GameAlreadyFinished => "Game already finished error", ...
{ match *self { QuizError::DatabaseError(ref err) => write!(f, "Database error: {}", err), QuizError::JokerUnavailable => write!(f, "Joker error: Tried to use unavailable Joker"), QuizError::GameAlreadyFinished => { write!(f, "Game alrea...
identifier_body
getBuildingId.py
import boto3 from decEncoder import * from DynamoTable import * def
(event, context): """Dynamo resource""" buildingTable = DynamoTable('Buildings') return getBuildingId(event, buildingTable) """Lambda handler function for /buildings/{buildingId} API call Returns building with the buildingId specified in the path or 'Building not found' error if buildingId not found ...
handler
identifier_name
getBuildingId.py
import boto3 from decEncoder import * from DynamoTable import * def handler(event, context):
"""Lambda handler function for /buildings/{buildingId} API call Returns building with the buildingId specified in the path or 'Building not found' error if buildingId not found by query search """ def getBuildingId(event, buildingTable): """If buildingId specified, assign it to variable, use get_item...
"""Dynamo resource""" buildingTable = DynamoTable('Buildings') return getBuildingId(event, buildingTable)
identifier_body
getBuildingId.py
import boto3 from decEncoder import * from DynamoTable import * def handler(event, context): """Dynamo resource""" buildingTable = DynamoTable('Buildings') return getBuildingId(event, buildingTable) """Lambda handler function for /buildings/{buildingId} API call Returns building with the buildingId spe...
else: """No path parameters""" return { 'statusCode': 400, 'headers': {'Content-Type': 'application/json'}, 'body': json.dumps({'error': 'Path not found'}) }
"""Error if not found""" return { 'statusCode': 404, 'headers': {'Content-Type': 'application/json'}, 'body': json.dumps({'error': 'Building not found'}) }
conditional_block
getBuildingId.py
import boto3 from decEncoder import * from DynamoTable import * def handler(event, context):
"""Lambda handler function for /buildings/{buildingId} API call Returns building with the buildingId specified in the path or 'Building not found' error if buildingId not found by query search """ def getBuildingId(event, buildingTable): """If buildingId specified, assign it to variable, use get_item ...
"""Dynamo resource""" buildingTable = DynamoTable('Buildings') return getBuildingId(event, buildingTable)
random_line_split
debugger-step-in-ignore-injected-script.js
// 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. (async function() { TestRunner.addResult(`Tests that stepInto doesn't pause in InjectedScriptSource.\n`); await TestRunner.loadLegacyModule('sources')...
() { var cb; var p = new Promise(fullfill => cb = fullfill); SourcesTestRunner.stepInto(); SourcesTestRunner.waitUntilResumed(() => SourcesTestRunner.waitUntilPaused(cb)); return p; } })();
stepIntoPromise
identifier_name
debugger-step-in-ignore-injected-script.js
// 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. (async function() { TestRunner.addResult(`Tests that stepInto doesn't pause in InjectedScriptSource.\n`); await TestRunner.loadLegacyModule('sources')...
})();
}
random_line_split
debugger-step-in-ignore-injected-script.js
// 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. (async function() { TestRunner.addResult(`Tests that stepInto doesn't pause in InjectedScriptSource.\n`); await TestRunner.loadLegacyModule('sources')...
})();
{ var cb; var p = new Promise(fullfill => cb = fullfill); SourcesTestRunner.stepInto(); SourcesTestRunner.waitUntilResumed(() => SourcesTestRunner.waitUntilPaused(cb)); return p; }
identifier_body
capabilities.py
# -*- Mode: Python; coding: iso-8859-1 -*- # vi:si:et:sw=4:sts=4:ts=4 # # Stoqdrivers # Copyright (C) 2005 Async Open Source <http://www.async.com.br> # All rights reserved # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # ...
""" This class is used to represent a driver capability, offering methods to validate a value with base in the capability limits. """ def __init__(self, min_len: Optional[int]=None, max_len: Optional[int]=None, max_size: Optional[Real]=None, min_size: Optional[Real]=None, ...
identifier_body
capabilities.py
# -*- Mode: Python; coding: iso-8859-1 -*- # vi:si:et:sw=4:sts=4:ts=4 # # Stoqdrivers # Copyright (C) 2005 Async Open Source <http://www.async.com.br> # All rights reserved # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # ...
@param min_len: The minimum length of a string @type min_len: int @param max_len: The max length of a string @type max_len: int @param max_size The maximum size for a value @type max_size: number @param min_size: The minimum size for a value...
random_line_split
capabilities.py
# -*- Mode: Python; coding: iso-8859-1 -*- # vi:si:et:sw=4:sts=4:ts=4 # # Stoqdrivers # Copyright (C) 2005 Async Open Source <http://www.async.com.br> # All rights reserved # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # ...
(self, min_len: Optional[int]=None, max_len: Optional[int]=None, max_size: Optional[Real]=None, min_size: Optional[Real]=None, digits: Optional[int]=None, decimals: Optional[Real]=None): """ Creates a new driver capability. A driver capability can be represented basica...
__init__
identifier_name
capabilities.py
# -*- Mode: Python; coding: iso-8859-1 -*- # vi:si:et:sw=4:sts=4:ts=4 # # Stoqdrivers # Copyright (C) 2005 Async Open Source <http://www.async.com.br> # All rights reserved # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # ...
elif value < (self.min_size or float('-inf')): raise CapabilityError("the value can't be less than %r" % self.min_size)
raise CapabilityError("the value can't be greater than %r" % self.max_size)
conditional_block