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
HtmlEditor.tsx
/// <reference path="react-rte.d.ts" /> import * as React from 'react' import RichTextEditor, { EditorValue } from 'react-rte'; import { IBinding } from '@framework/Reflection'; export interface HtmlEditorProps { binding: IBinding<string | null | undefined>; readonly?: boolean; } export default cla...
}
return ( <RichTextEditor value={this.state.editorValue} readOnly={this.props.readonly} onChange={ev => this.setState({ editorValue: ev })} onBlur={() => this.saveHtml()} /> ); }
identifier_body
HtmlEditor.tsx
/// <reference path="react-rte.d.ts" /> import * as React from 'react' import RichTextEditor, { EditorValue } from 'react-rte'; import { IBinding } from '@framework/Reflection'; export interface HtmlEditorProps { binding: IBinding<string | null | undefined>; readonly?: boolean; } export default cla...
{ this.saveHtml(); } saveHtml() { if (!this.props.readonly) this.props.binding.setValue(this.state.editorValue.toString("html") || ""); } render() { return ( <RichTextEditor value={this.state.editorValue} rea...
mponentWillUnmount()
identifier_name
HtmlEditor.tsx
/// <reference path="react-rte.d.ts" /> import * as React from 'react' import RichTextEditor, { EditorValue } from 'react-rte'; import { IBinding } from '@framework/Reflection'; export interface HtmlEditorProps { binding: IBinding<string | null | undefined>; readonly?: boolean; } export default cla...
<RichTextEditor value={this.state.editorValue} readOnly={this.props.readonly} onChange={ev => this.setState({ editorValue: ev })} onBlur={() => this.saveHtml()} /> ); } }
random_line_split
lib.rs
#![allow(dead_code)] struct ExampleGroup { name: &'static str, examples: Vec<Example>, } struct Example { name: &'static str, body: Box<Fn() -> bool>,
pub fn it<B: Fn() -> bool + 'static>(&mut self, name: &'static str, body: B) { self.examples.push(Example { name: name, body: Box::new(body), }); } pub fn run(&self) { for example in self.examples.iter() { let result = example.run(); ...
} impl ExampleGroup {
random_line_split
lib.rs
#![allow(dead_code)] struct ExampleGroup { name: &'static str, examples: Vec<Example>, } struct Example { name: &'static str, body: Box<Fn() -> bool>, } impl ExampleGroup { pub fn it<B: Fn() -> bool + 'static>(&mut self, name: &'static str, body: B) { self.examples.push(Example { ...
(&self) -> bool { (self.body)() } } pub fn describe<B: Fn(&mut ExampleGroup)>(name: &'static str, body: B) { let example_group = &mut ExampleGroup { name: name, examples: vec![], }; body(example_group); example_group.run(); }
run
identifier_name
lib.rs
#![allow(dead_code)] struct ExampleGroup { name: &'static str, examples: Vec<Example>, } struct Example { name: &'static str, body: Box<Fn() -> bool>, } impl ExampleGroup { pub fn it<B: Fn() -> bool + 'static>(&mut self, name: &'static str, body: B) { self.examples.push(Example { ...
} } impl Example { pub fn run(&self) -> bool { (self.body)() } } pub fn describe<B: Fn(&mut ExampleGroup)>(name: &'static str, body: B) { let example_group = &mut ExampleGroup { name: name, examples: vec![], }; body(example_group); example_group.run(); }
{ "FAILED" }
conditional_block
stop.spec.js
import {VelocityAnimator} from '../src/animator'; import {initialize} from 'aurelia-pal-browser'; jasmine.getFixtures().fixturesPath = 'base/test/fixtures/'; describe('stop function', () => { let animator; let container; beforeAll(() => initialize()); beforeEach(() => { let elem = $('#test-simple').eq(0...
expect(elems[0].style.opacity).toBe(''); animator.animate(elems, 'fadeIn', {duration: 100}); //stop the animation halfway through setTimeout(()=> { //get current opacity value let opacity0 = elems[0].style.opacity; let opacity1 = elems[1].style.opacity; //stop animations ...
it('stops multiple elements', (done) => { let elems = container.querySelectorAll('.group1'); animator.stop(elems, true);
random_line_split
field_isempty.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
}
{ e.get_header() .read(&self.header_field_path[..]) .map(|v| { match v { Some(&Value::Array(ref a)) => a.is_empty(), Some(&Value::String(ref s)) => s.is_empty(), Some(&Value::Table(ref t)) => t.is_empty(), ...
identifier_body
field_isempty.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
(&self, e: &Entry) -> bool { e.get_header() .read(&self.header_field_path[..]) .map(|v| { match v { Some(&Value::Array(ref a)) => a.is_empty(), Some(&Value::String(ref s)) => s.is_empty(), Some(&Value::Table(r...
filter
identifier_name
field_isempty.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
// This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Pub...
// 2.1 of the License. //
random_line_split
frequency.rs
use envelope; use pitch; /// Types for generating the frequency given some playhead position. pub trait Frequency { /// Return the frequency given some playhead percentage through the duration of the Synth. /// - 0.0 < perc < 1.0l fn hz_at_playhead(&self, perc: f64) -> f64; /// Return the frequency as...
(&self) -> Dynamic { use std::iter::once; if let Dynamic::Hz(hz) = *self { let perc = pitch::Hz(hz as f32).perc(); return Dynamic::Envelope({ once(envelope::Point::new(0.0, perc, 0.0)) .chain(once(envelope::Point::new(1.0, perc, 0.0))) ...
to_env
identifier_name
frequency.rs
use envelope; use pitch; /// Types for generating the frequency given some playhead position. pub trait Frequency { /// Return the frequency given some playhead percentage through the duration of the Synth. /// - 0.0 < perc < 1.0l fn hz_at_playhead(&self, perc: f64) -> f64; /// Return the frequency as...
self.clone() } /// Convert the dynamic to its Hz variant. pub fn to_hz(&self) -> Dynamic { if let Dynamic::Envelope(ref env) = *self { use pitch::{LetterOctave, Letter}; // Just convert the first point to the constant Hz. return match env.points.iter().n...
{ let perc = pitch::Hz(hz as f32).perc(); return Dynamic::Envelope({ once(envelope::Point::new(0.0, perc, 0.0)) .chain(once(envelope::Point::new(1.0, perc, 0.0))) .collect() }) }
conditional_block
frequency.rs
use envelope; use pitch; /// Types for generating the frequency given some playhead position. pub trait Frequency { /// Return the frequency given some playhead percentage through the duration of the Synth. /// - 0.0 < perc < 1.0l fn hz_at_playhead(&self, perc: f64) -> f64; /// Return the frequency as...
#[inline] fn freq_perc_at_playhead(&self, perc: f64) -> f64 { pitch::Hz(self.hz_at_playhead(perc) as f32).perc() } } /// Alias for the Envelope used. pub type Envelope = envelope::Envelope; /// A type that allows dynamically switching between constant and enveloped frequency. #[derive(Debug, Clone...
random_line_split
constants.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ **constants.py** **Platform:** Windows, Linux, Mac Os X. **Description:** Defines **Foundations** package default constants through the :class:`Constants` class. **Others:** """ from __future__ import unicode_literals import os import platform import fou...
""" :param change_version: Package change version. :type change_version: unicode """ version = ".".join((major_version, minor_version, change_version)) """ :param version: Package version. :type version: unicode """ logger = "Foundations_Logger" """ :param logger: Packag...
""" Defines **Foundations** package default constants. """ application_name = "Foundations" """ :param application_name: Package Application name. :type application_name: unicode """ major_version = "2" """ :param major_version: Package major version. :type major_version: un...
identifier_body
constants.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ **constants.py** **Platform:** Windows, Linux, Mac Os X. **Description:** Defines **Foundations** package default constants through the :class:`Constants` class. **Others:** """ from __future__ import unicode_literals import os import platform import fou...
(): """ Defines **Foundations** package default constants. """ application_name = "Foundations" """ :param application_name: Package Application name. :type application_name: unicode """ major_version = "2" """ :param major_version: Package major version. :type major_ver...
Constants
identifier_name
constants.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ **constants.py** **Platform:** Windows, Linux, Mac Os X. **Description:** Defines **Foundations** package default constants through the :class:`Constants` class. **Others:** """ from __future__ import unicode_literals import os import platform import fou...
null_object = "None" """ :param null_object: Default null object string. :type null_object: unicode """
provider_directory = ".HDRLabs" """ :param provider_directory: Package provider directory. :type provider_directory: unicode """
conditional_block
constants.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ **constants.py** **Platform:** Windows, Linux, Mac Os X. **Description:** Defines **Foundations** package default constants through the :class:`Constants` class. **Others:** """ from __future__ import unicode_literals import os import platform import fou...
provider_directory = "HDRLabs" """ :param provider_directory: Package provider directory. :type provider_directory: unicode """ elif platform.system() == "Linux": provider_directory = ".HDRLabs" """ :param provider_directory: Package provider directory...
""" if platform.system() == "Windows" or platform.system() == "Microsoft" or platform.system() == "Darwin":
random_line_split
matrixEvalContext.ts
/* * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * 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 restrict...
}
{ // NOTE: Matrix context-sensitive evaluation is not yet implemented. return createStaticEvalContext(colorAllocatorProvider); }
identifier_body
matrixEvalContext.ts
/*
* All rights reserved. * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the ""Software""), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, mer...
* Power BI Visualizations * * Copyright (c) Microsoft Corporation
random_line_split
matrixEvalContext.ts
/* * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * 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 restrict...
(colorAllocatorProvider: IColorAllocatorCache, dataViewMatrix: DataViewMatrix): IEvalContext { // NOTE: Matrix context-sensitive evaluation is not yet implemented. return createStaticEvalContext(colorAllocatorProvider); } }
createMatrixEvalContext
identifier_name
urls.py
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2012 OpenPlans # # 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 versio...
# (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of ...
random_line_split
test_localfile.py
# -*- coding: utf-8 -*- import nose.tools as ns import os from os.path import join from tempfile import gettempdir from relshell.record import Record from relshell.recorddef import RecordDef from relshell.batch import Batch from shellstreaming.core.batch_queue import BatchQueue from shellstreaming.ostream.localfile imp...
"333" ''' ) def _create_batches(): rdef = RecordDef([{'name': 'col0', 'type': 'INT'}]) return ( Batch(rdef, (Record(111), Record(222), )), Batch(rdef, (Record(333), )), )
ns.eq_(f.read(), '''"111" "222"
random_line_split
test_localfile.py
# -*- coding: utf-8 -*- import nose.tools as ns import os from os.path import join from tempfile import gettempdir from relshell.record import Record from relshell.recorddef import RecordDef from relshell.batch import Batch from shellstreaming.core.batch_queue import BatchQueue from shellstreaming.ostream.localfile imp...
q.push(None) # run ostream ostream = LocalFile(TEST_FILE, output_format='csv', input_queue=q) ostream.join() # check contents with open(TEST_FILE) as f: ns.eq_(f.read(), '''"111" "222" "333" ''' ) def _create_batches(): rdef = RecordDef([{'name': 'col0', 'type': 'INT'}])...
q.push(batch) # [fix] - Batch's output format has to be customized by user
conditional_block
test_localfile.py
# -*- coding: utf-8 -*- import nose.tools as ns import os from os.path import join from tempfile import gettempdir from relshell.record import Record from relshell.recorddef import RecordDef from relshell.batch import Batch from shellstreaming.core.batch_queue import BatchQueue from shellstreaming.ostream.localfile imp...
(): rdef = RecordDef([{'name': 'col0', 'type': 'INT'}]) return ( Batch(rdef, (Record(111), Record(222), )), Batch(rdef, (Record(333), )), )
_create_batches
identifier_name
test_localfile.py
# -*- coding: utf-8 -*- import nose.tools as ns import os from os.path import join from tempfile import gettempdir from relshell.record import Record from relshell.recorddef import RecordDef from relshell.batch import Batch from shellstreaming.core.batch_queue import BatchQueue from shellstreaming.ostream.localfile imp...
def _create_batches(): rdef = RecordDef([{'name': 'col0', 'type': 'INT'}]) return ( Batch(rdef, (Record(111), Record(222), )), Batch(rdef, (Record(333), )), )
q = BatchQueue() for batch in _create_batches(): q.push(batch) # [fix] - Batch's output format has to be customized by user q.push(None) # run ostream ostream = LocalFile(TEST_FILE, output_format='csv', input_queue=q) ostream.join() # check contents with open(TEST_FILE) as f: ...
identifier_body
range.ts
import * as vscode from 'vscode'; import { IMovement } from './../../actions/motion'; import { Position, PositionDiff } from './position'; export class Range { private _start: Position; private _stop: Position; public get start(): Position { return this._start; } public get stop(): Position { retu...
( list: Range[] ): Iterable<{ start: Position; stop: Position; range: Range; i: number }> { for (let i = 0; i < list.length; i++) { yield { i, range: list[i], start: list[i]._start, stop: list[i]._stop, }; } } /** * Create a range from an IMovement. *...
IterateRanges
identifier_name
range.ts
import * as vscode from 'vscode'; import { IMovement } from './../../actions/motion'; import { Position, PositionDiff } from './position'; export class Range { private _start: Position; private _stop: Position; public get start(): Position { return this._start; } public get stop(): Position { retu...
} constructor(start: Position, stop: Position) { this._start = start; this._stop = stop; } /** * Create a range from a VSCode selection. */ public static FromVSCodeSelection(e: vscode.Selection): Range { return new Range(Position.FromVSCodePosition(e.start), Position.FromVSCodePosition(e.e...
random_line_split
range.ts
import * as vscode from 'vscode'; import { IMovement } from './../../actions/motion'; import { Position, PositionDiff } from './position'; export class Range { private _start: Position; private _stop: Position; public get start(): Position { return this._start; } public get stop(): Position { retu...
} /** * Create a range from an IMovement. */ public static FromIMovement(i: IMovement): Range { // TODO: This shows a very clear need for refactoring after multi-cursor is merged! return new Range(i.start, i.stop); } public getRight(count = 1): Range { return new Range(this._start.getRig...
{ yield { i, range: list[i], start: list[i]._start, stop: list[i]._stop, }; }
conditional_block
mod.rs
//! General purpose I/O pub mod crh; pub mod crl; use volatile::{RO, RW, WO}; #[repr(C)] pub struct Gpio { /// Configuration register low /* 0x00 */ pub crl: RW<crl::Register>, /// Configuration register high /* 0x04 */ pub crh: RW<crh::Register>, /* 0x08 */ idr: RO<u32>, /* 0x0C */ odr: RW<u...
{ _10MHz, _2MHz, _50MHz, }
Speed
identifier_name
mod.rs
//! General purpose I/O pub mod crh; pub mod crl; use volatile::{RO, RW, WO}; #[repr(C)] pub struct Gpio { /// Configuration register low /* 0x00 */ pub crl: RW<crl::Register>, /// Configuration register high /* 0x04 */ pub crh: RW<crh::Register>, /* 0x08 */ idr: RO<u32>, /* 0x0C */ odr: RW<u...
/// Port bit set/reset register /* 0x10 */ pub bsrr: WO<bsrr::Register>, /* 0x14 */ brr: WO<u32>, /* 0x18 */ lckr: RW<u32>, } reg!(bsrr: u32 { BS0: 0, BS1: 1, BS2: 2, BS3: 3, BS4: 4, BS5: 5, BS6: 6, BS7: 7, BS8: 8, BS9: 9, BS10: 10, BS11: 11, BS12: 12...
random_line_split
initMultiple.js
$(function () { $('.imageUploadMultiple').each(function (index, item) { var $item = $(item); var $group = $item.closest('.form-group'); var $innerGroup = $item.find('.form-group'); var $errors = $item.find('.errors'); var $input = $item.find('.imageValue'); var flow =...
updateValue(); } }); }); });
$innerGroup.sortable({ onUpdate: function () {
random_line_split
test_jira_hook.py
# -*- coding: utf-8 -*- # # 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 #...
(self, jira_mock): jira_hook = JiraHook() self.assertTrue(jira_mock.called) self.assertIsInstance(jira_hook.client, Mock) self.assertEqual(jira_hook.client.name, jira_mock.return_value.name) if __name__ == '__main__': unittest.main()
test_jira_client_connection
identifier_name
test_jira_hook.py
# -*- coding: utf-8 -*- # # 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 #...
unittest.main()
conditional_block
test_jira_hook.py
# -*- coding: utf-8 -*- # # 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 #...
if __name__ == '__main__': unittest.main()
def setUp(self): configuration.load_test_config() db.merge_conn( models.Connection( conn_id='jira_default', conn_type='jira', host='https://localhost/jira/', port=443, extra='{"verify": "False", "project": "AIRFLOW"}...
identifier_body
test_jira_hook.py
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one
# distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/l...
# or more contributor license agreements. See the NOTICE file
random_line_split
config.js
define([ 'app/App', 'dojo/has', 'dojo/request/xhr', 'dojo/_base/Color', 'esri/config', 'esri/symbols/SimpleMarkerSymbol', 'dojo/domReady!' ], function ( App, has, xhr, Color, esriConfig, SimpleMarkerSymbol ) { esriConfig.defaults.io.corsEnabledServers.push('g...
window.AGRCMap = App; });
{ if (has('agrc-build') === 'prod') { window.AGRCGLOBAL.quadWord = 'result-table-secure-antenna'; } else if (has('agrc-build') === 'stage') { // *.dev.utah.gov & *.deq.utah.gov (their dev servers) window.AGRCGLOBAL.quadWord = 'orca-brown-door-concert'; } else ...
conditional_block
config.js
define([ 'app/App', 'dojo/has', 'dojo/request/xhr', 'dojo/_base/Color', 'esri/config', 'esri/symbols/SimpleMarkerSymbol', 'dojo/domReady!' ], function ( App, has, xhr, Color, esriConfig, SimpleMarkerSymbol ) { esriConfig.defaults.io.corsEnabledServers.push('g...
// apiKey: String // Key for api.mapserv.utah.gov services // Passed in as a parameter to the app apiKey: null, // urls: Object urls: { mapservice: 'https://mapserv.utah.gov/arcgis/rest/services/DEQSpills/MapService/MapServer', landOwne...
// version: String // The version number. version: '2.7.3',
random_line_split
lib.rs
#[cfg(feature = "_docs")] { pub mod $m; } else { mod $m; } } }; } mod clangll; doc_mod!(clang); doc_mod!(ir); doc_mod!(parse); mod regex_set; mod codegen { include!(concat!(env!("OUT_DIR"), "/codegen.rs")); } use std::borrow::Borrow; use std::i...
<T: Borrow<str>>(mut self, arg: T) -> Builder { self.options.whitelisted_functions.insert(&arg); self } /// Whitelist the given variable so that it (and all types that it /// transitively refers to) appears in the generated bindings. pub fn whitelisted_var<T: Borrow<str>>(mut self, arg:...
whitelisted_function
identifier_name
lib.rs
self.options.opaque_types.insert(arg.into()); self } /// Whitelist the given type so that it (and all types that it transitively /// refers to) appears in the generated bindings. pub fn whitelisted_type<T: Borrow<str>>(mut self, arg: T) -> Builder { self.options.whitelisted_type...
{ let (file, _, _, _) = cursor.location().location(); match file.name() { None => ctx.options().builtins, Some(..) => true, } }
identifier_body
lib.rs
} /// Whitelist the given variable so that it (and all types that it /// transitively refers to) appears in the generated bindings. pub fn whitelisted_var<T: Borrow<str>>(mut self, arg: T) -> Builder { self.options.whitelisted_vars.insert(&arg); self } /// Add a string to prepend ...
{ cursor.visit(|child, _| parse_one(ctx, *child, parent, children)); }
conditional_block
lib.rs
#[cfg(feature = "_docs")] { pub mod $m; } else { mod $m; } } }; } mod clangll; doc_mod!(clang); doc_mod!(ir); doc_mod!(parse); mod regex_set; mod codegen { include!(concat!(env!("OUT_DIR"), "/codegen.rs")); } use std::borrow::Borrow; use std::i...
/// Whitelist the given variable so that it (and all types that it /// transitively refers to) appears in the generated bindings. pub fn whitelisted_var<T: Borrow<str>>(mut self, arg: T) -> Builder { self.options.whitelisted_vars.insert(&arg); self } /// Add a string to prepend to ...
self }
random_line_split
liballoc_boxed_test.rs
// Copyright 2012-2015 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-MI...
#[test] fn i64_slice() { let slice: &[i64] = &[i64::MIN, -2, -1, 0, 1, 2, i64::MAX]; let boxed: Box<[i64]> = Box::from(slice); assert_eq!(&*boxed, slice) } #[test] fn str_slice() { let s = "Hello, world!"; let boxed: Box<str> = Box::from(s); assert_eq!(&*boxed, s) }
{ let slice: &[f64] = &[-1.0, 0.0, 1.0, f64::INFINITY]; let boxed: Box<[f64]> = Box::from(slice); assert_eq!(&*boxed, slice) }
identifier_body
liballoc_boxed_test.rs
// Copyright 2012-2015 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-MI...
() { let a = Box::new(5); let b: Box<i32> = a.clone(); assert!(a == b); } #[derive(PartialEq, Eq)] struct Test; #[test] fn any_move() { let a = Box::new(8) as Box<Any>; let b = Box::new(Test) as Box<Any>; match a.downcast::<i32>() { Ok(a) => { assert!(a == Box::new(8)); ...
test_owned_clone
identifier_name
liballoc_boxed_test.rs
// Copyright 2012-2015 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-MI...
} #[test] fn f64_slice() { let slice: &[f64] = &[-1.0, 0.0, 1.0, f64::INFINITY]; let boxed: Box<[f64]> = Box::from(slice); assert_eq!(&*boxed, slice) } #[test] fn i64_slice() { let slice: &[i64] = &[i64::MIN, -2, -1, 0, 1, 2, i64::MAX]; let boxed: Box<[i64]> = Box::from(slice); assert_eq!(&*bo...
assert_eq!(19, y.get()); }
random_line_split
containerwidget.ts
import { WidgetRender } from "../common/widgetrender"; import { Widget } from "./widget"; import { Dockerode } from "../common/docker/dockerode"; import { Log } from "../common/log"; import { Usage, EMPTY_NET_DATA } from "../common/docker/container"; import { injectable } from "inversify"; import { Color } from "../com...
if (this.stream) { this.stream.end(); } this.cpu.setData(Usage.EMPTY); this.mem.setData(Usage.EMPTY); this.net.setData(EMPTY_NET_DATA); this.log.setContent(""); } private async showStatsCharts(container: any) { this.stream = await container.s...
rData() {
identifier_name
containerwidget.ts
import { WidgetRender } from "../common/widgetrender"; import { Widget } from "./widget"; import { Dockerode } from "../common/docker/dockerode"; import { Log } from "../common/log"; import { Usage, EMPTY_NET_DATA } from "../common/docker/container"; import { injectable } from "inversify"; import { Color } from "../com...
} return false; } }
return row[5].indexOf("running") >= 0; }
conditional_block
containerwidget.ts
import { WidgetRender } from "../common/widgetrender"; import { Widget } from "./widget"; import { Dockerode } from "../common/docker/dockerode"; import { Log } from "../common/log"; import { Usage, EMPTY_NET_DATA } from "../common/docker/container"; import { injectable } from "inversify"; import { Color } from "../com...
public getAllElements(): Array<any> { return [this.table, this.text, this.mem, this.cpu, this.net, this.log]; } protected async renderWidget(box: any) { try { const location = { top: 0, left: 0, width: "100%-2", height: "40%-2" }; this.table = WidgetRender.table(bo...
{ return { keys: ["c"], callback: () => { if (!this.table) { this.render(); this.table.focus(); } this.active(); } }; }
identifier_body
containerwidget.ts
import { WidgetRender } from "../common/widgetrender"; import { Widget } from "./widget"; import { Dockerode } from "../common/docker/dockerode"; import { Log } from "../common/log"; import { Usage, EMPTY_NET_DATA } from "../common/docker/container"; import { injectable } from "inversify"; import { Color } from "../com...
Log.error(error); } this.text = WidgetRender.text(box, { top: "40%-2", left: 0, width: "100%-2", height: 2 }, "{bold}✔ Container Stats{bold}"); this.cpu = WidgetRender.line({ top: "40%", left: 0, width: "50%-1", height: "30%" }, Color.red, "CPU Usage (%)"); box.append(this....
random_line_split
vnc_event.py
import string from universe import error from universe.vncdriver import constants class VNCEvent(object): pass def keycode(key): if key in constants.KEYMAP: return constants.KEYMAP.get(key) elif len(key) == 1: return ord(key) else: raise error.Error('Not sure how to translate t...
if down is None or not down: for code in reversed(codes): events.append(cls(code, down=False)) return events @classmethod def by_name(cls, key, down=None): return cls(keycode(key), down=down) def __init__(self, key, down=True): # TODO: validate...
for code in codes: events.append(cls(code, down=True))
conditional_block
vnc_event.py
import string from universe import error from universe.vncdriver import constants class VNCEvent(object): pass def keycode(key): if key in constants.KEYMAP: return constants.KEYMAP.get(key) elif len(key) == 1: return ord(key) else: raise error.Error('Not sure how to translate t...
def __hash__(self): return (self.key, self.down).__hash__() def __eq__(self, other): return type(other) == type(self) and \ other.key == self.key and \ other.down == self.down @property def key_name(self): """Human readable name""" return self....
return repr(self)
identifier_body
vnc_event.py
import string from universe import error from universe.vncdriver import constants class VNCEvent(object): pass def keycode(key): if key in constants.KEYMAP: return constants.KEYMAP.get(key) elif len(key) == 1: return ord(key) else: raise error.Error('Not sure how to translate t...
def compile(self): return 'PointerEvent', self.x, self.y, self.buttonmask def __repr__(self): return 'PointerEvent<x={} y={} buttonmask={}>'.format(self.x, self.y, self.buttonmask) def __str__(self): return repr(self)
def __init__(self, x, y, buttonmask=0): self.x = x self.y = y self.buttonmask = buttonmask
random_line_split
vnc_event.py
import string from universe import error from universe.vncdriver import constants class VNCEvent(object): pass def keycode(key): if key in constants.KEYMAP: return constants.KEYMAP.get(key) elif len(key) == 1: return ord(key) else: raise error.Error('Not sure how to translate t...
(self, other): return type(other) == type(self) and \ other.key == self.key and \ other.down == self.down @property def key_name(self): """Human readable name""" return self._keysym_to_name.get(self.key) class PointerEvent(VNCEvent): def __init__(self, x, y,...
__eq__
identifier_name
level0.py
import sys,os #sys.path.append(os.path.join(os.path.dirname(__file__), '../../..')) #from ethosgame.ethos.level import Level from ..level import Level #from ethosgame.ethos.gameobject import GameObject from ..gameobject import GameObject #from ethosgame.ethos.drawnobject import DrawnObject from ..drawnobject import Dra...
def processMouseMotion(self,pos): #print "Your mouse is at " + str(pos[0]) + " " + str(pos[1]) self.mousex = pos[0] self.mousey = pos[1] if self.drawing and len(self.pts) < 100: self.pts.append( pos ) def processMouseButtonDown(self, pos): print "Ya clicked...
print "You hit the key " + str(key) + "!" if key == pygame.K_RIGHT: self.npc.vx = 0.1
identifier_body
level0.py
import sys,os #sys.path.append(os.path.join(os.path.dirname(__file__), '../../..')) #from ethosgame.ethos.level import Level from ..level import Level #from ethosgame.ethos.gameobject import GameObject from ..gameobject import GameObject #from ethosgame.ethos.drawnobject import DrawnObject from ..drawnobject import Dra...
def processKeyDown(self,key): print "You hit the key " + str(key) + "!" if key == pygame.K_RIGHT: self.npc.vx = 0.1 def processMouseMotion(self,pos): #print "Your mouse is at " + str(pos[0]) + " " + str(pos[1]) self.mousex = pos[0] self.mousey = pos[1] ...
self.npc.processPointCollision(collidingPoints)
conditional_block
level0.py
import sys,os #sys.path.append(os.path.join(os.path.dirname(__file__), '../../..')) #from ethosgame.ethos.level import Level from ..level import Level #from ethosgame.ethos.gameobject import GameObject from ..gameobject import GameObject #from ethosgame.ethos.drawnobject import DrawnObject from ..drawnobject import Dra...
(self, dT): #print "Running level0" #Character info for gobject in self.activeSprites: if gobject is not self.npc: if not gobject.rect.colliderect(self.npc.rect): #if self.npc.vy < 0.3 and (gobject.rect.y >= self.npc.rect.y + self.npc.rect.height):...
update
identifier_name
level0.py
import sys,os #sys.path.append(os.path.join(os.path.dirname(__file__), '../../..')) #from ethosgame.ethos.level import Level from ..level import Level #from ethosgame.ethos.gameobject import GameObject from ..gameobject import GameObject #from ethosgame.ethos.drawnobject import DrawnObject from ..drawnobject import Dra...
collidingPoints = [] for drawnstuff in self.drawnSprites: for point in drawnstuff.pts: x = self.npc.rect.collidepoint(point) if x: collidingPoints.append(point) if(len(collidingPoints) > 0): self.npc.processPointCollision(collidingPoints) d...
self.npc.vy += 0.1 else: self.npc.vy = 0 gobject.update(dT)
random_line_split
vector.rs
/* * Copyright 2018 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applica...
impl super::SafeSliceAccess for f32 {} impl super::SafeSliceAccess for f64 {} } #[cfg(target_endian = "little")] pub use self::le_safe_slice_impls::*; pub fn follow_cast_ref<'a, T: Sized + 'a>(buf: &'a [u8], loc: usize) -> &'a T { let sz = size_of::<T>(); let buf = &buf[loc..loc + sz]; let ptr = ...
impl super::SafeSliceAccess for i32 {} impl super::SafeSliceAccess for i64 {}
random_line_split
vector.rs
/* * Copyright 2018 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applica...
(buf: &'a [u8], loc: usize) -> Self::Inner { let len = read_scalar::<UOffsetT>(&buf[loc..loc + SIZE_UOFFSET]) as usize; let slice = &buf[loc + SIZE_UOFFSET..loc + SIZE_UOFFSET + len]; let s = unsafe { from_utf8_unchecked(slice) }; s } } #[cfg(target_endian = "little")] fn follow_sli...
follow
identifier_name
vector.rs
/* * Copyright 2018 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applica...
impl<'a> Follow<'a> for &'a str { type Inner = &'a str; fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { let len = read_scalar::<UOffsetT>(&buf[loc..loc + SIZE_UOFFSET]) as usize; let slice = &buf[loc + SIZE_UOFFSET..loc + SIZE_UOFFSET + len]; let s = unsafe { from_utf8_unchecked(...
{ let sz = size_of::<T>(); let buf = &buf[loc..loc + sz]; let ptr = buf.as_ptr() as *const T; unsafe { &*ptr } }
identifier_body
v8.rs
/* 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/. */ use interfaces::{cef_v8accessor_t, cef_v8context_t, cef_v8handler_t, cef_v8stack_trace_t}; use interfaces::{cef_v8...
fn cef_v8value_create_array(_length: libc::c_int) -> *mut cef_v8value_t fn cef_v8value_create_function(_name: *const cef_string_t, _handler: *mut cef_v8handler_t) -> *mut cef_v8value_t fn cef_v8stack_trace_get_current(_frame_limit: libc::c_int) -> *mut cef_v8stack_trace_t ...
fn cef_v8value_create_uint(_value: u32) -> *mut cef_v8value_t fn cef_v8value_create_double(_value: c_double) -> *mut cef_v8value_t fn cef_v8value_create_date(_date: *const cef_time_t) -> *mut cef_v8value_t fn cef_v8value_create_string(_value: *const cef_string_t) -> *mut cef_v8value_t fn cef_v8value...
random_line_split
admin.py
from django.contrib import admin from account.models import UserProfile from django.contrib.auth.models import Permission, Group class UserProfileAdmin(admin.ModelAdmin): #,'qq','first_name','last_name','truename','email','groups' fieldsets = [ (None,{'fields':['username']}), ('Profile',{'fields':['last_name','fir...
(admin.ModelAdmin): list_display = ('name','content_type','codename') admin.site.register(Permission,PermissionAdmin)
PermissionAdmin
identifier_name
admin.py
from django.contrib import admin from account.models import UserProfile from django.contrib.auth.models import Permission, Group class UserProfileAdmin(admin.ModelAdmin): #,'qq','first_name','last_name','truename','email','groups' fieldsets = [ (None,{'fields':['username']}), ('Profile',{'fields':['last_name','fir...
admin.site.register(Permission,PermissionAdmin)
list_display = ('name','content_type','codename')
identifier_body
admin.py
from django.contrib import admin from account.models import UserProfile from django.contrib.auth.models import Permission, Group class UserProfileAdmin(admin.ModelAdmin): #,'qq','first_name','last_name','truename','email','groups' fieldsets = [ (None,{'fields':['username']}), ('Profile',{'fields':['last_name','fir...
'is_staff', 'date_joined', 'last_login', #'groups', ) admin.site.register(UserProfile,UserProfileAdmin) class PermissionAdmin(admin.ModelAdmin): list_display = ('name','content_type','codename') admin.site.register(Permission,PermissionAdmin)
list_display = ( 'username', 'truename', 'email', 'is_superuser',
random_line_split
views.py
from django.http import HttpResponse, Http404 from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import render, get_object_or_404 from django.core.urlresolvers import reverse from django.utils.xmlutils import SimplerXMLGenerator from models import Place, Region from models import Locality from ...
objects = do_paging(request, items) return render(request, 'location/geolocation.html', {'geolocation': geolocation, 'objects': objects, 'num_children': len(children), 'children': split_list(children, parts=columns)})
children = geolocation.children.all()
conditional_block
views.py
from django.http import HttpResponse, Http404 from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import render, get_object_or_404 from django.core.urlresolvers import reverse from django.utils.xmlutils import SimplerXMLGenerator from models import Place, Region from models import Locality from ...
handler.startElement(u"Placemark", {}) handler.addQuickElement(u"name", "%s (%s)" % (place.name, place.museumobject__count)) handler.addQuickElement(u"description", '<a href="%s">%s</a>' % (place_url, place.__unicode__())) handler.startElement(u"Point", {}...
random_line_split
views.py
from django.http import HttpResponse, Http404 from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import render, get_object_or_404 from django.core.urlresolvers import reverse from django.utils.xmlutils import SimplerXMLGenerator from models import Place, Region from models import Locality from ...
(request): global_regions = GlobalRegion.objects.all() return render(request, "location/tree_view.html", {'global_regions': global_regions}) def find_location(model_type, id): element_type = ContentType.objects.get(app_label='location', model=model_type) return element_type.get_object_for_this...
tree_view
identifier_name
views.py
from django.http import HttpResponse, Http404 from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import render, get_object_or_404 from django.core.urlresolvers import reverse from django.utils.xmlutils import SimplerXMLGenerator from models import Place, Region from models import Locality from ...
def view_places(request): grs = GlobalRegion.objects.exclude(icon_path="").prefetch_related('children') d = dict((g.name, g) for g in grs) grs = [d['Australia'], d['Pacific'], d['Asia'], d['Europe'], d['Americas'], d['Africa'], d['Middle East']] kml_url = request.build_absolute_uri(reverse('...
element_type = ContentType.objects.get(app_label='location', model=model_type) return element_type.get_object_for_this_type(id=id)
identifier_body
main.rs
use std::env; use std::path::PathBuf; use std::process::Command; fn main() -> std::io::Result<()> { let dist = env::var("CODEQL_DIST").expect("CODEQL_DIST not set"); let db = env::var("CODEQL_EXTRACTOR_QL_WIP_DATABASE") .expect("CODEQL_EXTRACTOR_QL_WIP_DATABASE not set"); let codeql = if env::const...
else { "codeql" }; let codeql: PathBuf = [&dist, codeql].iter().collect(); let mut cmd = Command::new(codeql); cmd.arg("database") .arg("index-files") .arg("--size-limit=5m") .arg("--language=ql") .arg("--working-dir=.") .arg(db); let mut has_include...
{ "codeql.exe" }
conditional_block
main.rs
use std::env; use std::path::PathBuf; use std::process::Command; fn
() -> std::io::Result<()> { let dist = env::var("CODEQL_DIST").expect("CODEQL_DIST not set"); let db = env::var("CODEQL_EXTRACTOR_QL_WIP_DATABASE") .expect("CODEQL_EXTRACTOR_QL_WIP_DATABASE not set"); let codeql = if env::consts::OS == "windows" { "codeql.exe" } else { "codeql" ...
main
identifier_name
main.rs
use std::env; use std::path::PathBuf; use std::process::Command; fn main() -> std::io::Result<()> { let dist = env::var("CODEQL_DIST").expect("CODEQL_DIST not set"); let db = env::var("CODEQL_EXTRACTOR_QL_WIP_DATABASE") .expect("CODEQL_EXTRACTOR_QL_WIP_DATABASE not set"); let codeql = if env::const...
.arg("--include=**/qlpack.yml"); } let exit = &cmd.spawn()?.wait()?; std::process::exit(exit.code().unwrap_or(1)) }
if !has_include_dir { cmd.arg("--include-extension=.ql") .arg("--include-extension=.qll") .arg("--include-extension=.dbscheme")
random_line_split
main.rs
use std::env; use std::path::PathBuf; use std::process::Command; fn main() -> std::io::Result<()>
.unwrap_or_default() .split('\n') { if let Some(stripped) = line.strip_prefix("include:") { cmd.arg("--include").arg(stripped); has_include_dir = true; } else if let Some(stripped) = line.strip_prefix("exclude:") { cmd.arg("--exclude").arg(stripped...
{ let dist = env::var("CODEQL_DIST").expect("CODEQL_DIST not set"); let db = env::var("CODEQL_EXTRACTOR_QL_WIP_DATABASE") .expect("CODEQL_EXTRACTOR_QL_WIP_DATABASE not set"); let codeql = if env::consts::OS == "windows" { "codeql.exe" } else { "codeql" }; let codeql: Path...
identifier_body
mod.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use extract_graphql::extract; use extract_graphql::JavaScriptSourceFeature; use fixture_tests::Fixture; pub fn
(fixture: &Fixture<'_>) -> Result<String, String> { Ok(extract(fixture.content) .into_iter() .map(|source| match source { JavaScriptSourceFeature::GraphQLSource(s) => { format!( "graphql - line: {}, column: {}, text: <{}>", s.line_i...
transform_fixture
identifier_name
mod.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use extract_graphql::extract; use extract_graphql::JavaScriptSourceFeature; use fixture_tests::Fixture; pub fn transform_fixture...
{ Ok(extract(fixture.content) .into_iter() .map(|source| match source { JavaScriptSourceFeature::GraphQLSource(s) => { format!( "graphql - line: {}, column: {}, text: <{}>", s.line_index, s.column_index, s.text ) ...
identifier_body
mod.rs
*/ use extract_graphql::extract; use extract_graphql::JavaScriptSourceFeature; use fixture_tests::Fixture; pub fn transform_fixture(fixture: &Fixture<'_>) -> Result<String, String> { Ok(extract(fixture.content) .into_iter() .map(|source| match source { JavaScriptSourceFeature::GraphQL...
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree.
random_line_split
copy.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); /** * Created by kib357 on 22/01/16. */ class copy { static arrayStructure(target, source, exclude) { if (!Array.isArray(target) || !Array.isArray(source)) { throw new TypeError('copy.arrayStructure cannot be ca...
target[index] = null; } return target; } static objectStructure(target, source, exclude) { if (target == null || source == null) { throw new TypeError('copy.objectStructure cannot be called with null or undefined'); } for (let key of Object.keys...
{ target[index] = []; copy.arrayStructure(target[index], source[index], exclude); continue; }
conditional_block
copy.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); /** * Created by kib357 on 22/01/16. */ class
{ static arrayStructure(target, source, exclude) { if (!Array.isArray(target) || !Array.isArray(source)) { throw new TypeError('copy.arrayStructure cannot be called with not arrays'); } for (let index = 0; index < source.length; index++) { if (typeof source[index] =...
copy
identifier_name
copy.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); /** * Created by kib357 on 22/01/16. */ class copy { static arrayStructure(target, source, exclude) { if (!Array.isArray(target) || !Array.isArray(source)) { throw new TypeError('copy.arrayStructure cannot be ca...
if (typeof source[key] === 'object' && !Array.isArray(source[key])) { target[key] = {}; copy.objectStructure(target[key], source[key], exclude); continue; } if (Array.isArray(source[key])) { target[key] = []; ...
for (let key of Object.keys(source)) { if (exclude instanceof RegExp && exclude.test(key)) { continue; }
random_line_split
APIRequest.js
const querystring = require('querystring'); const snekfetch = require('snekfetch'); const { Error } = require('../../errors'); class APIRequest { constructor(rest, method, path, options) { this.rest = rest; this.client = rest.client; this.method = method; this.path = path.toString();
} getAuth() { if (this.client.token && this.client.user && this.client.user.bot) { return `Bot ${this.client.token}`; } else if (this.client.token) { return this.client.token; } throw new Error('TOKEN_MISSING'); } gen() { const API = `${this.client.options.http.api}/v${this.cli...
this.route = options.route; this.options = options;
random_line_split
APIRequest.js
const querystring = require('querystring'); const snekfetch = require('snekfetch'); const { Error } = require('../../errors'); class APIRequest { constructor(rest, method, path, options) { this.rest = rest; this.client = rest.client; this.method = method; this.path = path.toString(); this.route =...
const request = snekfetch[this.method](`${API}${this.path}`); if (this.options.auth !== false) request.set('Authorization', this.getAuth()); if (this.options.reason) request.set('X-Audit-Log-Reason', encodeURIComponent(this.options.reason)); if (!this.rest.client.browser) request.set('User-Agent', th...
{ const queryString = (querystring.stringify(this.options.query).match(/[^=&?]+=[^=&?]+/g) || []).join('&'); this.path += `?${queryString}`; }
conditional_block
APIRequest.js
const querystring = require('querystring'); const snekfetch = require('snekfetch'); const { Error } = require('../../errors'); class
{ constructor(rest, method, path, options) { this.rest = rest; this.client = rest.client; this.method = method; this.path = path.toString(); this.route = options.route; this.options = options; } getAuth() { if (this.client.token && this.client.user && this.client.user.bot) { re...
APIRequest
identifier_name
configuration.ts
import { workspace } from 'vscode'; import * as process from 'process'; type Env = 'dev' | 'prod' const defaultPomodoroSize = 25; const defaultBreakSize = 5; // const defaultShouldDisplayTimerOnApplicationStart = false; const devPomodoroSize = 0.1; const devBreakSize = 0.2; // const devShouldDisplayTimerOnApplicatio...
(env == 'dev') ? devPomodoroSize : getConfigWorkTime(); export const getBreakSizeInMinutes = () => (env == 'dev') ? devBreakSize : getConfigBreakTime(); // export const shouldDisplayTimerOnApplicationStart = () => // (env == 'dev') ? devShouldDisplayTimerOnApplicationStart : getConfigShouldDisplayTimerOnA...
export const getPomodoroSizeInMinutes = () =>
random_line_split
ascent.rs
<'grammar, W: Write>( grammar: &'grammar Grammar, user_start_symbol: NonterminalString, start_symbol: NonterminalString, states: &[LR1State<'grammar>], action_module: &str, out: &mut RustWrite<W>, ) -> io::Result<()> { let graph = StateGraph::new(&states); let mut ascent = CodeGenerator:...
compile
identifier_name
ascent.rs
/// returns the (optional, fixed) -- number of optional /// items in stack prefix and numer of fixed fn optional_fixed_lens(&self) -> (usize, usize) { (self.len_optional, self.len() - self.len_optional) } fn is_not_empty(&self) -> bool { self.len() > 0 } fn optional(&self...
{ self.all.len() }
identifier_body
ascent.rs
terminal (in which case the lookahead must be // computed interally). fn fn_args( &mut self, optional_prefix: &[Symbol], fixed_prefix: &[Symbol], ) -> (Vec<String>, bool) { assert!( // start state: (optional_prefix.is_empty() && fixed_prefix.is_empty(...
// identify the "start" location for this production; this
random_line_split
gen_test2123.py
import numpy as np import pandas as pd import scipy as sp import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import os, sys try: import cPickle as pickle except: import pickle #connect echoRD Tools pathdir='../echoRD' #path to echoRD lib_path = os.path.abspath(pathdir) #sys.path.append(lib_pa...
plotparticles_specht(particles,mc,pdyn,vG,runname,t,i,saving=True,relative=False,wdir=wdir) [particles,npart,thS,leftover,drained,t]=rE.CAOSpy_rundx1(i*output,(i+1)*output,mc,pdyn,cinf,precTS,particles,leftover,drained,6.,splitfac=4,prec_2D=False,maccoat=macscale,saveDT=saveDT,clogswitch=clogswitch,infilt_method=in...
conditional_block
gen_test2123.py
import numpy as np import pandas as pd import scipy as sp import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import os, sys try: import cPickle as pickle except: import pickle #connect echoRD Tools pathdir='../echoRD' #path to echoRD lib_path = os.path.abspath(pathdir) #sys.path.append(lib_pa...
print('starting new run...') #loop through plot cycles for i in np.arange(dummy.astype(int))[ix:]: plotparticles_specht(particles,mc,pdyn,vG,runname,t,i,saving=True,relative=False,wdir=wdir) [particles,npart,thS,leftover,drained,t]=rE.CAOSpy_rundx1(i*output,(i+1)*output,mc,pdyn,cinf,precTS,particles,leftov...
except:
random_line_split
coyoneda.js
// Video: https://www.youtube.com/watch?v=WH5BrkzGgQY const daggy = require('daggy') const compose = (f, g) => x => f(g(x)) const id = x => x //===============Define Coyoneda========= // create constructor with props 'x' and 'f' // 'x' is our value, 'f' is a function const Coyoneda = daggy.tagged('x', 'f') // map ...
// equivalent to buildUpFn = coyoResult.f, ourSet = coyoResult.x const {f: builtUpFn, x: ourSet} = coyoResult console.log("builtUpFn is: ", builtUpFn, "; ourSet is: ", ourSet) ourSet .forEach(n => console.log(builtUpFn(n))) // 2! // 3! // 4! // 5! //===============Lift a functor in (Array) and achieve Loop fusion...
random_line_split
set_part_quantity_mutation.rs
use async_graphql::{ ID, Context, FieldResult, }; use async_graphql::validators::{IntGreaterThan}; // use eyre::{ // eyre, // // Result, // // Context as _, // }; use printspool_json_store::{ Record, }; use crate::{ part::Part, }; #[derive(Default)] pub struct
; #[derive(async_graphql::InputObject, Debug)] struct SetPartQuantityInput { #[graphql(name="partID")] part_id: ID, #[graphql(validator( IntGreaterThan(value = "0") ))] quantity: i32, } #[async_graphql::Object] impl SetPartQuantityMutation { /// Move a job in the print queue async ...
SetPartQuantityMutation
identifier_name
set_part_quantity_mutation.rs
use async_graphql::{ ID, Context, FieldResult, }; use async_graphql::validators::{IntGreaterThan};
use printspool_json_store::{ Record, }; use crate::{ part::Part, }; #[derive(Default)] pub struct SetPartQuantityMutation; #[derive(async_graphql::InputObject, Debug)] struct SetPartQuantityInput { #[graphql(name="partID")] part_id: ID, #[graphql(validator( IntGreaterThan(value = "0") ...
// use eyre::{ // eyre, // // Result, // // Context as _, // };
random_line_split
notification.py
# Copyright (C) 2018 DataArt # # 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, ...
(self): return self._id @property def notification(self): return self._notification @property def parameters(self): return self._parameters @property def timestamp(self): return self._timestamp
id
identifier_name
notification.py
# Copyright (C) 2018 DataArt # # 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, ...
return self._timestamp
identifier_body
notification.py
# Copyright (C) 2018 DataArt # # 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, ...
def device_id(self): return self._device_id @property def id(self): return self._id @property def notification(self): return self._notification @property def parameters(self): return self._parameters @property def timestamp(self): return se...
self._timestamp = notification[self.TIMESTAMP_KEY] @property
random_line_split
ja.js
utanota.ctrl.lang.ja.writing_direction = "ltr"; tutao.tutanota.ctrl.lang.ja.id = "ja"; tutao.tutanota.ctrl.lang.ja.keys = { "account_label": "ユーザー", "activate_action": "有効にする", "address_label": "アドレス", "add_action": "追加する", "adminEmailSettings_action": "メール", "adminMessages_action": "表示されたメッセージ", "adminUs...
"back_action": "前", "bcc_label": "Bcc", "birthday_alt": "生年月日", "cancel_action": "キャンセルする", "captchaDisplay_label": "キャプチャ", "changeNotificationMailLanguage_msg": "通知メールの言語:", "comment_label": "コメント", "community_label": "コミュニティ", "company_label": "会社", "company_placeholder": "会社", "confidentialMai...
"backTologin_action": "ログインに戻る",
random_line_split
operations.py
""" A naming convention and discovery mechanism for HTTP endpoints. Operations provide a naming convention for references between endpoints, allowing easy construction of links or audit trails for external consumption. """ from collections import namedtuple from enum import Enum, unique # metadata for an operation ...
@property def endpoint_pattern(self): """ Convert the operation's pattern into a regex matcher. """ parts = self.value.pattern.split(".") return "[.]".join( "(?P<{}>[^.]*)".format(part[1:-1]) for part in parts )
for operation in cls: if operation.value.name.lower() == name.lower(): return operation else: raise ValueError(name)
identifier_body
operations.py
""" A naming convention and discovery mechanism for HTTP endpoints. Operations provide a naming convention for references between endpoints, allowing easy construction of links or audit trails for external consumption. """ from collections import namedtuple from enum import Enum, unique # metadata for an operation ...
@property def endpoint_pattern(self): """ Convert the operation's pattern into a regex matcher. """ parts = self.value.pattern.split(".") return "[.]".join( "(?P<{}>[^.]*)".format(part[1:-1]) for part in parts )
return operation else: raise ValueError(name)
random_line_split
operations.py
""" A naming convention and discovery mechanism for HTTP endpoints. Operations provide a naming convention for references between endpoints, allowing easy construction of links or audit trails for external consumption. """ from collections import namedtuple from enum import Enum, unique # metadata for an operation ...
(cls, name): for operation in cls: if operation.value.name.lower() == name.lower(): return operation else: raise ValueError(name) @property def endpoint_pattern(self): """ Convert the operation's pattern into a regex matcher. """ ...
from_name
identifier_name
operations.py
""" A naming convention and discovery mechanism for HTTP endpoints. Operations provide a naming convention for references between endpoints, allowing easy construction of links or audit trails for external consumption. """ from collections import namedtuple from enum import Enum, unique # metadata for an operation ...
@property def endpoint_pattern(self): """ Convert the operation's pattern into a regex matcher. """ parts = self.value.pattern.split(".") return "[.]".join( "(?P<{}>[^.]*)".format(part[1:-1]) for part in parts )
raise ValueError(name)
conditional_block
encoders.py
# coding: utf-8 import math
try: long_int = long except NameError: long_int = int def rshift(val, n): if val >= 0: val2 = val >> n else: val2 = val + 0x100000000 >> n return val2 def str_to_longs(e): t = [] pad = len(e) % 4 if pad != 0: e = e + (4 - pad) * '\x00' array_len = mat...
random_line_split
encoders.py
# coding: utf-8 import math try: long_int = long except NameError: long_int = int def rshift(val, n): if val >= 0: val2 = val >> n else: val2 = val + 0x100000000 >> n return val2 def str_to_longs(e): t = [] pad = len(e) % 4 if pad != 0: e = e + (4 - pad) * '...
else: g = o[l-1] r = (rshift(g, 5) ^ ((s << 2) & 0xffffffff)) + \ (rshift(s, 3) ^ ((g << 4) & 0xffffffff)) ^ \ (u ^ s) + \ (n[3 & p ^ a] ^ g) s = o[p] = (o[p] - r) & 0xffffffff p -=...
g = o[p-1]
conditional_block
encoders.py
# coding: utf-8 import math try: long_int = long except NameError: long_int = int def rshift(val, n): if val >= 0: val2 = val >> n else: val2 = val + 0x100000000 >> n return val2 def str_to_longs(e): t = [] pad = len(e) % 4 if pad != 0: e = e + (4 - pad) * '...
(e, t): r = str_to_longs(e) a = str_to_longs(t) if len(r) <= 1: r = [r[0], 0] l = len(r) g = r[l - 1] s = r[0] i = 2654435769 c = math.floor(6 + 52 / l) u = 0 while c > 0: u += i n = rshift(u, 2) & 3 p = 0 while l > p: ...
encrypt
identifier_name