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 |
|---|---|---|---|---|
vextracti32x4.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn vextracti32x4_1() {
run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTI32x4, operand1: Some(Direct(XMM5)), operand2: ... |
fn vextracti32x4_3() {
run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTI32x4, operand1: Some(Direct(XMM30)), operand2: Some(Direct(ZMM5)), operand3: Some(Literal8(61)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K1), broadcast: None }, ... | {
run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTI32x4, operand1: Some(IndirectScaledDisplaced(EDX, Eight, 1098025544, Some(OperandSize::Xmmword), None)), operand2: Some(Direct(ZMM1)), operand3: Some(Literal8(15)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broa... | identifier_body |
vextracti32x4.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn vextracti32x4_1() { | fn vextracti32x4_2() {
run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTI32x4, operand1: Some(IndirectScaledDisplaced(EDX, Eight, 1098025544, Some(OperandSize::Xmmword), None)), operand2: Some(Direct(ZMM1)), operand3: Some(Literal8(15)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: fa... | run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTI32x4, operand1: Some(Direct(XMM5)), operand2: Some(Direct(ZMM0)), operand3: Some(Literal8(65)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 243, 125, 202, 57, 1... | random_line_split |
take-break-modal.component.spec.ts | // Copyright 2020 The Oppia Authors. 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 ap... |
}
describe('TakeBreakModalComponent', function() {
let component: TakeBreakModalComponent;
let fixture: ComponentFixture<TakeBreakModalComponent>;
let ngbActiveModal: NgbActiveModal;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MockTranslatePipe, TakeBreakModalComponent]... | {
return;
} | identifier_body |
take-break-modal.component.spec.ts | // Copyright 2020 The Oppia Authors. 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 ap... | let fixture: ComponentFixture<TakeBreakModalComponent>;
let ngbActiveModal: NgbActiveModal;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MockTranslatePipe, TakeBreakModalComponent],
providers: [
{
provide: NgbActiveModal,
useClass: MockActiv... | describe('TakeBreakModalComponent', function() {
let component: TakeBreakModalComponent; | random_line_split |
take-break-modal.component.spec.ts | // Copyright 2020 The Oppia Authors. 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 ap... | {
dismiss(): void {
return;
}
close(): void {
return;
}
}
describe('TakeBreakModalComponent', function() {
let component: TakeBreakModalComponent;
let fixture: ComponentFixture<TakeBreakModalComponent>;
let ngbActiveModal: NgbActiveModal;
beforeEach(async(() => {
TestBed.configureTesting... | MockActiveModal | identifier_name |
common.js | const isColorString = (str: string): boolean => {
let color;
try {
color = chroma(str);
} catch (e) {
color = false;
}
return !!color;
}
// NOTE: replace decimals and negative signs otherwise it'll get caught by the
// NON_NUMBER_REGEX
// TODO: why is the NON_NUMBER_REGEX check in here?
export const... | createUnitFashion(segments[3]),
createColorFashion(segments[4])
]
};
}
export const parseStyle = (raw: string|number, name: ?string): Fashion => {
return typeof raw === 'number' ?
createNumberFashion(raw)
: isNumberString(raw) ?
createNumberFashion(raw)
: typeof raw === 'string' &... | createUnitFashion(segments[1]),
createUnitFashion(segments[2]), | random_line_split |
common.js | const isColorString = (str: string): boolean => {
let color;
try {
color = chroma(str);
} catch (e) {
color = false;
}
return !!color;
}
// NOTE: replace decimals and negative signs otherwise it'll get caught by the
// NON_NUMBER_REGEX
// TODO: why is the NON_NUMBER_REGEX check in here?
export const... | else if (c === ')') {
if (openParenCount === 1) {
splits.push(
chars
.slice(startingCharIndexes.pop(), i + 1)
.join('')
);
openParenCount -= 1;
} else if (openParenCount > 1) {
openParenCount -= 1;
}
}
}
return splits;
}
/**
... | {
openParenCount += 1;
} | conditional_block |
test_setup_wizard.py | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from django.core.cache import cache
from sentry.testutils import PermissionTestCase
from sentry.api.endpoints.setup_wizard import SETUP_WIZARD_CACHE_KEY
class SetupWizard(PermissionTestCase):
def test_redirect(self):
use... | (self):
self.create_organization(owner=self.user)
self.login_as(self.user)
url = reverse('sentry-project-wizard-fetch', kwargs={
'wizard_hash': 'xyz'
})
resp = self.client.get(url)
assert resp.status_code == 302
| test_redirect_to_org | identifier_name |
test_setup_wizard.py | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from django.core.cache import cache
from sentry.testutils import PermissionTestCase
from sentry.api.endpoints.setup_wizard import SETUP_WIZARD_CACHE_KEY
class SetupWizard(PermissionTestCase):
def test_redirect(self):
|
def test_simple(self):
self.create_organization(owner=self.user)
self.login_as(self.user)
key = '%s%s' % (SETUP_WIZARD_CACHE_KEY, 'abc')
cache.set(key, 'test')
url = reverse('sentry-project-wizard-fetch', kwargs={
'wizard_hash': 'abc'
})
resp ... | user = self.create_user('foo@example.com', is_active=False)
url = reverse('sentry-project-wizard-fetch', kwargs={
'wizard_hash': 'abc'
})
resp = self.client.get(url)
self.login_as(user)
assert resp.status_code == 302 | identifier_body |
test_setup_wizard.py | from __future__ import absolute_import |
from sentry.testutils import PermissionTestCase
from sentry.api.endpoints.setup_wizard import SETUP_WIZARD_CACHE_KEY
class SetupWizard(PermissionTestCase):
def test_redirect(self):
user = self.create_user('foo@example.com', is_active=False)
url = reverse('sentry-project-wizard-fetch', kwargs={
... |
from django.core.urlresolvers import reverse
from django.core.cache import cache | random_line_split |
two_gram_model.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditions apply:
#
# This pro... |
def getFieldInfo(self):
"""Returns the metadata specifying the format of the model's output.
The result may be different than the list of
nupic.data.fieldmeta.FieldMetaInfo objects supplied at initialization due
to the transcoding of some input fields into meta- fields, such as
datetime -> dayO... | """
This method is used for the data source to communicate to the
model any statistics that it knows about the fields
Since the two-gram has no use for this information, this is a no-op
"""
pass | identifier_body |
two_gram_model.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditions apply:
#
# This pro... |
Once called, the model will not be able to learn from subsequent input
records. Learning may not be resumed on a given instance of the model once
this is called as the implementation may optimize itself by pruning data
structures that are necessary for learning.
"""
self._learningEnabled = Fals... | def finishLearning(self):
"""Places the model in a permanent "finished learning" mode. | random_line_split |
two_gram_model.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditions apply:
#
# This pro... |
results.inferences = dict()
results.inferences[opfutils.InferenceElement.prediction] = predictions
results.inferences[opfutils.InferenceElement.encodings] = encodedPredictions
self._prevValues = inputBuckets
self._reset = False
return results
def finishLearning(self):
"""Places the mode... | predictions.append(default)
encodedPredictions.append(self._encoder.encodeField(fieldName,
default)) | conditional_block |
two_gram_model.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditions apply:
#
# This pro... | (self):
"""Returns the metadata specifying the format of the model's output.
The result may be different than the list of
nupic.data.fieldmeta.FieldMetaInfo objects supplied at initialization due
to the transcoding of some input fields into meta- fields, such as
datetime -> dayOfWeek, timeOfDay, et... | getFieldInfo | identifier_name |
digit.spec.tsx | import { render, RenderResult } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Digit } from './digit';
describe('<Digit />', () => {
const props = {
digit: 3,
onInput: jest.fn(),
};
const setup = (): RenderResult => render(<Digit {...props} />);
it('shoul... | const { getByRole } = setup();
const button = getByRole('button');
expect(button).toBeInTheDocument();
expect(button).toHaveTextContent('3');
});
it('should handle input', () => {
expect.assertions(2);
const { getByText } = setup();
const button = getByText('3') as HTMLButtonElement;
... | expect.assertions(2); | random_line_split |
init.py | ''' TODO: Init package docs
'''
import logging
import uuid
from grader.models import Grader
from grader.utils.config import is_grader_dir
logger = logging.getLogger(__name__)
help = 'Initialize grader by creating grader.yml'
def | (parser):
parser.add_argument('--course-id', default=str(uuid.uuid4()),
help='Unique course ID (for docker\'s sake)')
parser.add_argument('--force', action='store_true',
help='Overwrite an existing grader.yml')
parser.add_argument('--canvas-host', default=None... | setup_parser | identifier_name |
init.py | ''' TODO: Init package docs
'''
import logging
import uuid
from grader.models import Grader
from grader.utils.config import is_grader_dir
logger = logging.getLogger(__name__)
help = 'Initialize grader by creating grader.yml'
def setup_parser(parser):
parser.add_argument('--course-id', default=str(uuid.uuid4()... | logger.debug("Setting up grader in {}".format(args.path))
# Check for existing config
if is_grader_dir(args.path) and not args.force:
logger.critical(
"grader already configured in {}. Abort!".format(args.path)
)
raise SystemExit(1)
if args.canvas_host:
canvas_t... | identifier_body | |
init.py | ''' TODO: Init package docs
'''
import logging
import uuid
from grader.models import Grader
from grader.utils.config import is_grader_dir
logger = logging.getLogger(__name__)
help = 'Initialize grader by creating grader.yml'
def setup_parser(parser):
parser.add_argument('--course-id', default=str(uuid.uuid4()... |
if args.canvas_host:
canvas_token = input("Canvas access token (from {}/profile/settings): ".format(args.canvas_host))
else:
canvas_token = None
# Create the new grader
g = Grader.new(args.path, args.name, args.course_id, args.canvas_host, canvas_token)
logger.info("Wrote {}".form... | logger.critical(
"grader already configured in {}. Abort!".format(args.path)
)
raise SystemExit(1) | conditional_block |
init.py | ''' TODO: Init package docs
'''
import logging
import uuid
from grader.models import Grader | logger = logging.getLogger(__name__)
help = 'Initialize grader by creating grader.yml'
def setup_parser(parser):
parser.add_argument('--course-id', default=str(uuid.uuid4()),
help='Unique course ID (for docker\'s sake)')
parser.add_argument('--force', action='store_true',
... | from grader.utils.config import is_grader_dir
| random_line_split |
primitives.rs | use crate::ast::expressions;
use crate::ast::lexer::tokens;
use crate::ast::parser;
use crate::ast::stack;
use std::string::String as StdString;
#[derive(Debug, Clone)]
pub struct Nil;
impl expressions::Expression for Nil {}
impl Nil {
make_keyword_rule![rule, (tokens::Keyword::NIL, Nil)];
}
#[derive(Debug, Clo... | impl expressions::Expression for Number {}
impl Number {
pub fn rule(parser: &mut parser::Parser, stack: &mut stack::Stack) -> bool {
if let Some(tokens::Token {
token: tokens::TokenType::Number(number),
..
}) = parser.peek().cloned()
{
parser.shift();
... |
#[derive(Debug, Clone)]
pub struct Number(pub f64); | random_line_split |
primitives.rs | use crate::ast::expressions;
use crate::ast::lexer::tokens;
use crate::ast::parser;
use crate::ast::stack;
use std::string::String as StdString;
#[derive(Debug, Clone)]
pub struct Nil;
impl expressions::Expression for Nil {}
impl Nil {
make_keyword_rule![rule, (tokens::Keyword::NIL, Nil)];
}
#[derive(Debug, Clo... | (pub StdString);
impl expressions::Expression for String {}
impl String {
pub fn rule(parser: &mut parser::Parser, stack: &mut stack::Stack) -> bool {
if let Some(tokens::Token {
token: tokens::TokenType::String(string),
..
}) = parser.peek().cloned()
{
p... | String | identifier_name |
primitives.rs | use crate::ast::expressions;
use crate::ast::lexer::tokens;
use crate::ast::parser;
use crate::ast::stack;
use std::string::String as StdString;
#[derive(Debug, Clone)]
pub struct Nil;
impl expressions::Expression for Nil {}
impl Nil {
make_keyword_rule![rule, (tokens::Keyword::NIL, Nil)];
}
#[derive(Debug, Clo... | else {
false
}
}
}
| {
parser.shift();
stack.push_single(Box::new(String(string)));
true
} | conditional_block |
glyph.rs | u32 = 0x00000020;
//static CHAR_IDENTITY_FLAGS_MASK: u32 = 0x00000038;
fn is_simple_glyph_id(id: GlyphId) -> bool {
((id as u32) & GLYPH_ID_MASK) == id
}
fn | (advance: Au) -> bool {
let unsigned_au = advance.to_u32().unwrap();
(unsigned_au & (GLYPH_ADVANCE_MASK >> GLYPH_ADVANCE_SHIFT as uint)) == unsigned_au
}
type DetailedGlyphCount = u16;
// Getters and setters for GlyphEntry. Setter methods are functional,
// because GlyphEntry is immutable and only a u32 in si... | is_simple_advance | identifier_name |
glyph.rs | u32 = 0x00000020;
//static CHAR_IDENTITY_FLAGS_MASK: u32 = 0x00000038;
fn is_simple_glyph_id(id: GlyphId) -> bool {
((id as u32) & GLYPH_ID_MASK) == id
}
fn is_simple_advance(advance: Au) -> bool {
let unsigned_au = advance.to_u32().unwrap();
(unsigned_au & (GLYPH_ADVANCE_MASK >> GLYPH_ADVANCE_SH... |
#[inline(always)]
fn adapt_character_flags_of_entry(&self, other: GlyphEntry) -> GlyphEntry {
GlyphEntry { value: self.value | other.value }
}
}
// Stores data for a detailed glyph, in the case that several glyphs
// correspond to one character, or the glyph's data couldn't be packed.
#[derive(Cl... | {
(self.value & flag) != 0
} | identifier_body |
glyph.rs | ::from((self.value & GLYPH_ADVANCE_MASK) >> GLYPH_ADVANCE_SHIFT as uint).unwrap()
}
fn id(&self) -> GlyphId {
self.value & GLYPH_ID_MASK
}
fn is_ligature_start(&self) -> bool {
self.has_flag(!FLAG_NOT_LIGATURE_GROUP_START)
}
fn is_cluster_start(&self) -> bool {
self.ha... | }
}
// This enum is a proxy that's provided to GlyphStore clients when iterating
// through glyphs (either for a particular TextRun offset, or all glyphs). | random_line_split | |
Alphas.py | # ==========================================
# Author: Richard Wang
# Contact: rwthree@princeton.edu
#
# Performs simple parsing of an "Alpha" file
# Contents are simply (Server #, Alpha)
# Ex:
# 1, 3
# 2, 0
# 3, 1
# ==========================================
import random
import Globals
def updateAlphas(newAlphas, ... |
else:
alphalist.append({'replica': int(l[0]), 'alphaTarget': 0, 'alphaAssign': 0})
file.close()
return alphalist
def distributeAlphas(newAlphas, oldAlphas, totalAssigns):
sumTarget = sumAllAlphaTarget(newAlphas)
sumOldAssigns = sumAllAlphaAssign(oldAlphas)
for i in range(0, len(ne... | alphalist.append({'replica': int(l[0]), 'alphaTarget': int(l[1]), 'alphaAssign': 0}) | conditional_block |
Alphas.py | # ==========================================
# Author: Richard Wang
# Contact: rwthree@princeton.edu
#
# Performs simple parsing of an "Alpha" file
# Contents are simply (Server #, Alpha)
# Ex:
# 1, 3
# 2, 0
# 3, 1
# ==========================================
import random
import Globals
def updateAlphas(newAlphas, ... | (alphalist):
sum = 0
for i in range(0, len(alphalist)):
sum = sum + alphalist[i]['alphaAssign']
return sum
| sumAllAlphaAssign | identifier_name |
Alphas.py | # ==========================================
# Author: Richard Wang
# Contact: rwthree@princeton.edu
#
# Performs simple parsing of an "Alpha" file
# Contents are simply (Server #, Alpha)
# Ex:
# 1, 3
# 2, 0
# 3, 1
# ==========================================
import random
import Globals
def updateAlphas(newAlphas, ... |
def distributeEven(newAlphas, totalAssigns):
remainingAssigns = totalAssigns - sumAllAlphaAssign(newAlphas)
sumTarget = sumAllAlphaTarget(newAlphas)
for i in range(0, len(newAlphas)):
if sumTarget != 0:
newAlphas[i]['alphaAssign'] += int(newAlphas[i]['alphaTarget'] * remainingAssigns / sumTarget)
... | sumTarget = sumAllAlphaTarget(newAlphas)
sumOldAssigns = sumAllAlphaAssign(oldAlphas)
for i in range(0, len(newAlphas)):
for j in range(0, len(oldAlphas)):
if newAlphas[i]['replica'] == oldAlphas[j]['replica'] and newAlphas[i]['alphaTarget'] != 0:
numAssigns = sumOldAssigns + totalAssigns
newAssigns ... | identifier_body |
Alphas.py | # ==========================================
# Author: Richard Wang
# Contact: rwthree@princeton.edu
#
# Performs simple parsing of an "Alpha" file
# Contents are simply (Server #, Alpha)
# Ex:
# 1, 3
# 2, 0
# 3, 1
# ==========================================
import random
import Globals
def updateAlphas(newAlphas, ... | rand = random.randint(0, Globals.NUMREPLICAS - 1)
while remainingAssigns > 0 and sumAllAlphaTarget(newAlphas) != 0:
if newAlphas[rand]['alphaTarget'] != 0:
newAlphas[rand]['alphaAssign'] += 1
remainingAssigns -= 1
rand += 1
if rand > Globals.NUMREPLICAS - 1:
rand = 0
return ... | random_line_split | |
htmlfontelement.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 dom::attr::{Attr, AttrHelpers};
use dom::bindings::codegen::Bindings::HTMLFontElementBinding;
use dom::binding... | {
htmlelement: HTMLElement,
color: Cell<Option<RGBA>>,
}
impl HTMLFontElementDerived for EventTarget {
fn is_htmlfontelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFontElement)))... | HTMLFontElement | identifier_name |
htmlfontelement.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 dom::attr::{Attr, AttrHelpers};
use dom::bindings::codegen::Bindings::HTMLFontElementBinding;
use dom::binding... | self.color.set(str::parse_legacy_color(&attr.value()).ok())
}
_ => {}
}
}
fn before_remove_attr(&self, attr: JSRef<Attr>) {
if let Some(ref s) = self.super_type() {
s.before_remove_attr(attr);
}
match attr.local_name() {
... | match attr.local_name() {
&atom!("color") => { | random_line_split |
htmlfontelement.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 dom::attr::{Attr, AttrHelpers};
use dom::bindings::codegen::Bindings::HTMLFontElementBinding;
use dom::binding... |
}
impl HTMLFontElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLFontElement {
HTMLFontElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLFontElement, localName, prefix, document),
color: Cell::new(No... | {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFontElement)))
} | identifier_body |
gatsby-link_vx.x.x.js | // flow-typed signature: e9b84c500ccc61d64c1ca78e43399035
// flow-typed version: <<STUB>>/gatsby-link_v^1.6.35/flow_v0.68.0
/**
* This is an autogenerated libdef stub for:
*
* 'gatsby-link'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with t... | /**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
// Filename aliases
declare module 'gatsby-link/index' {
declare module.exports: $Exports<'gatsby-link'>;
}
declare module 'gatsby-link/index.js... | random_line_split | |
lexical-scope-in-for-loop.rs | // Copyright 2013 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 ... | () {()}
| sentinel | identifier_name |
lexical-scope-in-for-loop.rs | // Copyright 2013 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 ... |
// AFTER LOOP
// debugger:finish
// debugger:print x
// check:$7 = 1000000
// debugger:continue
fn main() {
let range = [1, 2, 3];
let x = 1000000; // wan meeeljen doollaars!
for &x in range.iter() {
zzz();
sentinel();
let x = -1 * x;
zzz();
sentinel();
}
... | // debugger:finish
// debugger:print x
// check:$6 = -3
// debugger:continue | random_line_split |
lexical-scope-in-for-loop.rs | // Copyright 2013 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 ... |
fn sentinel() {()}
| {()} | identifier_body |
index.tsx | import * as React from "react";
import { merge } from "../utils";
import responsive from "../Responsive";
import ActionIcon from "../ActionIcon";
import { FullSize } from "../Layouts";
const minimize = require("./icons/minimize.svg");
const maximize = require("./icons/maximize.svg");
interface Props {
menuTitle: s... | <div
style={props.isSelected ? merge(tabStyle, activeTabStyle) : tabStyle}
onClick={props.onClick}
>
{props.children}
</div>
);
const Mobile = (props: Props & MenuVisibility): React.ReactElement<any> => (
<FullSize style={{ overflowY: "hidden", flexDirection: "column" }}>
<div
... | children: string,
isSelected: boolean,
onClick: () => void
}): React.ReactElement<any> => ( | random_line_split |
views.py | from django.conf import settings
from django.contrib import messages
from django.forms import Form
from django.http import Http404, HttpResponse, HttpResponseBadRequest
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone... | (request):
return render(request, '404.html') | handler404 | identifier_name |
views.py | from django.conf import settings
from django.contrib import messages
from django.forms import Form
from django.http import Http404, HttpResponse, HttpResponseBadRequest
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone... | # This is an error; time to log, then fail
return HttpResponseBadRequest()
try:
constraint = Constraint.objects.get(slug=fields['constraint'])
except (KeyError, Constraint.DoesNotExist):
# This is an error; time to log, then fail
logge... | logger = get_logger(__name__, request)
if 'POST' == request.method and request.is_ajax():
fields = json.loads(request.body)
try:
user = User.objects.get(email__iexact=fields['email'])
except KeyError:
# This is an error; time to log, then fail
... | identifier_body |
views.py | from django.conf import settings
from django.contrib import messages
from django.forms import Form
from django.http import Http404, HttpResponse, HttpResponseBadRequest
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone... |
else:
form = ReminderForm()
return render(request, 'reminder.html', {'form': form})
# Custom error views
def handler404(request):
return render(request, '404.html') | email = form.cleaned_data['email']
try:
user = User.objects.get(email=email)
date = timezone.now().date()
appointments = user.appointments.filter(date__gte=date)
send_reminder(user, appointments)
except User.DoesNot... | conditional_block |
views.py | from django.conf import settings
from django.contrib import messages
from django.forms import Form
from django.http import Http404, HttpResponse, HttpResponseBadRequest
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone... |
# Custom error views
def handler404(request):
return render(request, '404.html') | random_line_split | |
bench.rs | extern crate env_logger;
extern crate time;
extern crate url;
/// A simple, but immature, benchmark client for destroying other WebSocket frameworks and proving
/// WS-RS's performance excellence. ;)
/// Make sure you allow for enough connections in your OS (e.g. ulimit -Sn 10000).
extern crate ws;
// Try this against... |
Ok(())
}
}
let mut ws = Builder::new()
.with_settings(Settings {
max_connections: CONNECTIONS,
..Settings::default()
})
.build(|out| Connection {
out,
count: 0,
time: 0,
total: 0,
})
... | {
self.out.send(MESSAGE)?;
let time = time::precise_time_ns();
// println!("time {}", time -self.time);
self.total += time - self.time;
self.count += 1;
self.time = time;
} | conditional_block |
bench.rs | extern crate env_logger;
extern crate time;
extern crate url;
/// A simple, but immature, benchmark client for destroying other WebSocket frameworks and proving
/// WS-RS's performance excellence. ;)
/// Make sure you allow for enough connections in your OS (e.g. ulimit -Sn 10000).
extern crate ws;
// Try this against... |
fn on_message(&mut self, msg: Message) -> Result<()> {
assert_eq!(msg.as_text().unwrap(), MESSAGE);
if self.count > MESSAGES {
self.out.close(CloseCode::Normal)?;
} else {
self.out.send(MESSAGE)?;
let time = time::precise_time... | {
self.out.send(MESSAGE)?;
self.count += 1;
self.time = time::precise_time_ns();
Ok(())
} | identifier_body |
bench.rs | extern crate env_logger;
extern crate time;
extern crate url;
/// A simple, but immature, benchmark client for destroying other WebSocket frameworks and proving
/// WS-RS's performance excellence. ;)
/// Make sure you allow for enough connections in your OS (e.g. ulimit -Sn 10000).
extern crate ws;
// Try this against... |
impl Handler for Connection {
fn on_open(&mut self, _: Handshake) -> Result<()> {
self.out.send(MESSAGE)?;
self.count += 1;
self.time = time::precise_time_ns();
Ok(())
}
fn on_message(&mut self, msg: Message) -> Result<()> {
asser... | random_line_split | |
bench.rs | extern crate env_logger;
extern crate time;
extern crate url;
/// A simple, but immature, benchmark client for destroying other WebSocket frameworks and proving
/// WS-RS's performance excellence. ;)
/// Make sure you allow for enough connections in your OS (e.g. ulimit -Sn 10000).
extern crate ws;
// Try this against... | () {
env_logger::init();
let url = url::Url::parse("ws://127.0.0.1:3012").unwrap();
struct Connection {
out: Sender,
count: u32,
time: u64,
total: u64,
}
impl Handler for Connection {
fn on_open(&mut self, _: Handshake) -> Result<()> {
self.out.... | main | identifier_name |
issue-18400.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 ... |
}
fn main() {
let bits: &[_] = &[0, 1];
0.contains(bits);
//~^ ERROR the trait `Set<_>` is not implemented for the type `_`
}
| {
for &bit in bits.iter() {
self.set(bit)
}
} | identifier_body |
issue-18400.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 ... | () {
let bits: &[_] = &[0, 1];
0.contains(bits);
//~^ ERROR the trait `Set<_>` is not implemented for the type `_`
}
| main | identifier_name |
issue-18400.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 ... | }
fn main() {
let bits: &[_] = &[0, 1];
0.contains(bits);
//~^ ERROR the trait `Set<_>` is not implemented for the type `_`
} | } | random_line_split |
index.tsx | import variables from '../../style/themes/default';
import { StyleSheet, ViewStyle } from 'react-native';
export default StyleSheet.create({
input: {
borderRadius: variables.radius_md,
backgroundColor: '#fff',
borderColor: variables.border_color_base,
borderWidth: variables.border_width_sm,
align... | cancelTextContainer: {
height: variables.search_bar_input_height,
justifyContent: 'center',
alignItems: 'center',
} as ViewStyle,
cancelText: {
fontSize: variables.link_button_font_size,
color: variables.color_link,
paddingLeft: variables.h_spacing_lg,
} as ViewStyle,
search: {
tin... | flexDirection: 'row',
} as ViewStyle, | random_line_split |
reducer.js | import { RECORD_DATA_TABLE_STATE_UPDATE, RESET_RECORD_DATA_TABLE_STATE } from './actions'
import { recordDataTableDefaultState, updateRecordDataTableState, updateRecordLockState } from './state'
import { ACTIVE_SURVEY_FETCHED } from 'actions/activeSurvey'
import { RECORD_LOCKED, RECORD_UNLOCKED } from '../actions'
exp... | return { ...recordDataTableDefaultState }
case RECORD_LOCKED:
return updateRecordLockState(state, action.recordId, action.lockedBy)
case RECORD_UNLOCKED:
return updateRecordLockState(state, action.recordId, null)
default:
return state
}
} | switch (type) {
case RECORD_DATA_TABLE_STATE_UPDATE:
return updateRecordDataTableState(state, { ...otherProps })
case ACTIVE_SURVEY_FETCHED:
case RESET_RECORD_DATA_TABLE_STATE: | random_line_split |
reducer.js | import { RECORD_DATA_TABLE_STATE_UPDATE, RESET_RECORD_DATA_TABLE_STATE } from './actions'
import { recordDataTableDefaultState, updateRecordDataTableState, updateRecordLockState } from './state'
import { ACTIVE_SURVEY_FETCHED } from 'actions/activeSurvey'
import { RECORD_LOCKED, RECORD_UNLOCKED } from '../actions'
exp... | (state = recordDataTableDefaultState, action) {
const { type, ...otherProps } = action
switch (type) {
case RECORD_DATA_TABLE_STATE_UPDATE:
return updateRecordDataTableState(state, { ...otherProps })
case ACTIVE_SURVEY_FETCHED:
case RESET_RECORD_DATA_TABLE_STATE:
return { ...recordDataTableD... | recordDataTable | identifier_name |
reducer.js | import { RECORD_DATA_TABLE_STATE_UPDATE, RESET_RECORD_DATA_TABLE_STATE } from './actions'
import { recordDataTableDefaultState, updateRecordDataTableState, updateRecordLockState } from './state'
import { ACTIVE_SURVEY_FETCHED } from 'actions/activeSurvey'
import { RECORD_LOCKED, RECORD_UNLOCKED } from '../actions'
exp... | {
const { type, ...otherProps } = action
switch (type) {
case RECORD_DATA_TABLE_STATE_UPDATE:
return updateRecordDataTableState(state, { ...otherProps })
case ACTIVE_SURVEY_FETCHED:
case RESET_RECORD_DATA_TABLE_STATE:
return { ...recordDataTableDefaultState }
case RECORD_LOCKED:
re... | identifier_body | |
error.rs | use alloc::boxed::Box;
use collections::string::String;
use core::fmt::{self, Debug, Display};
use core::marker::{Send, Sync, Reflect};
/// Base functionality for all errors in Rust.
//#[stable(feature = "rust1", since = "1.0.0")]
pub trait Error: Debug + Display + Reflect {
/// A short description of the error.
... | (err: E) -> Box<Error + Send + Sync + 'a> {
Box::new(err)
}
}
//#[stable(feature = "rust1", since = "1.0.0")]
impl From<String> for Box<Error + Send + Sync> {
fn from(err: String) -> Box<Error + Send + Sync> {
#[derive(Debug)]
struct StringError(String);
impl Error for StringEr... | from | identifier_name |
error.rs | use alloc::boxed::Box;
use collections::string::String;
use core::fmt::{self, Debug, Display};
use core::marker::{Send, Sync, Reflect};
/// Base functionality for all errors in Rust.
//#[stable(feature = "rust1", since = "1.0.0")]
pub trait Error: Debug + Display + Reflect {
/// A short description of the error.
... |
}
//#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<Error + Send + Sync + 'a> {
fn from(err: E) -> Box<Error + Send + Sync + 'a> {
Box::new(err)
}
}
//#[stable(feature = "rust1", since = "1.0.0")]
impl From<String> for Box<Error + Send + Sync> {
... | {
Box::new(err)
} | identifier_body |
error.rs | use alloc::boxed::Box;
use collections::string::String;
use core::fmt::{self, Debug, Display};
use core::marker::{Send, Sync, Reflect};
/// Base functionality for all errors in Rust.
//#[stable(feature = "rust1", since = "1.0.0")]
pub trait Error: Debug + Display + Reflect {
/// A short description of the error.
... |
//#[stable(feature = "rust1", since = "1.0.0")]
impl From<String> for Box<Error + Send + Sync> {
fn from(err: String) -> Box<Error + Send + Sync> {
#[derive(Debug)]
struct StringError(String);
impl Error for StringError {
fn description(&self) -> &str { &self.0 }
}
... | fn from(err: E) -> Box<Error + Send + Sync + 'a> {
Box::new(err)
}
} | random_line_split |
response.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 Nebula, Inc.
# Copyright 2013 Alessio Ababilov
# Copyright 2013 Grid Dynamics
# Copyright 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in complia... | (self):
"""Returns the user id associated with the authentication request.
:returns: str
"""
try:
return self['access']['user']['id']
except KeyError:
return None
@property
def tenant_name(self):
"""Returns the tenant name associated with... | user_id | identifier_name |
response.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 Nebula, Inc.
# Copyright 2013 Alessio Ababilov
# Copyright 2013 Grid Dynamics
# Copyright 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in complia... |
@property
def scoped(self):
"""Checks if the authorization token is scoped to a tenant.
Additionally verifies that there is a populated service catalog.
:returns: bool
"""
try:
if (self['access']['serviceCatalog'] and
self['access']['to... | """Synonym for tenant_id."""
return self.tenant_id | identifier_body |
response.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 Nebula, Inc.
# Copyright 2013 Alessio Ababilov
# Copyright 2013 Grid Dynamics
# Copyright 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in complia... | matching_endpoints = self.filter_endpoints(
endpoint_type, service_type, service_name, filter_attrs)
if not matching_endpoints:
raise exceptions.EndpointNotFound(
"Cannot find requested %s endpoint" % service_type)
elif len(matching_endpoints) > 1:
... | service_type, service_name=None, filter_attrs=None):
"""Returns a unique endpoint which match provided criteria.
"""
filter_attrs = filter_attrs or {} | random_line_split |
response.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 Nebula, Inc.
# Copyright 2013 Alessio Ababilov
# Copyright 2013 Grid Dynamics
# Copyright 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in complia... |
elif 'access' in self and 'serviceCatalog' in self['access']:
# Full catalog ...
for service in self['access']['serviceCatalog']:
if service_type and service.get("type") != service_type:
continue
if service_name and service.get('name')... | for endpoint in self['endpoints']:
add_if_appropriate(endpoint) | conditional_block |
hotspots.js | var hotspots = (function () {
var exports = {};
exports.show = function (hotspot_list) {
$('.hotspot').hide();
for (var i = 0; i < hotspot_list.length; i += 1) |
};
exports.initialize = function () {
exports.show(page_params.hotspots);
};
function mark_hotspot_as_read(hotspot) {
channel.post({
url: '/json/users/me/hotspots',
data: {hotspot: JSON.stringify(hotspot)},
});
}
$(function () {
$("#hotspot_welcome").on('click', function (e) {
... | {
$("#hotspot_".concat(hotspot_list[i])).show();
} | conditional_block |
hotspots.js | var hotspots = (function () {
var exports = {};
exports.show = function (hotspot_list) {
$('.hotspot').hide();
for (var i = 0; i < hotspot_list.length; i += 1) {
$("#hotspot_".concat(hotspot_list[i])).show();
}
};
| exports.initialize = function () {
exports.show(page_params.hotspots);
};
function mark_hotspot_as_read(hotspot) {
channel.post({
url: '/json/users/me/hotspots',
data: {hotspot: JSON.stringify(hotspot)},
});
}
$(function () {
$("#hotspot_welcome").on('click', function (e) {
mar... | random_line_split | |
hotspots.js | var hotspots = (function () {
var exports = {};
exports.show = function (hotspot_list) {
$('.hotspot').hide();
for (var i = 0; i < hotspot_list.length; i += 1) {
$("#hotspot_".concat(hotspot_list[i])).show();
}
};
exports.initialize = function () {
exports.show(page_params.hotspots);
};
func... | (hotspot) {
channel.post({
url: '/json/users/me/hotspots',
data: {hotspot: JSON.stringify(hotspot)},
});
}
$(function () {
$("#hotspot_welcome").on('click', function (e) {
mark_hotspot_as_read("welcome");
e.preventDefault();
e.stopPropagation();
});
$("#hotsp... | mark_hotspot_as_read | identifier_name |
hotspots.js | var hotspots = (function () {
var exports = {};
exports.show = function (hotspot_list) {
$('.hotspot').hide();
for (var i = 0; i < hotspot_list.length; i += 1) {
$("#hotspot_".concat(hotspot_list[i])).show();
}
};
exports.initialize = function () {
exports.show(page_params.hotspots);
};
func... |
$(function () {
$("#hotspot_welcome").on('click', function (e) {
mark_hotspot_as_read("welcome");
e.preventDefault();
e.stopPropagation();
});
$("#hotspot_streams").on('click', function (e) {
mark_hotspot_as_read("streams");
e.preventDefault();
e.stopPropaga... | {
channel.post({
url: '/json/users/me/hotspots',
data: {hotspot: JSON.stringify(hotspot)},
});
} | identifier_body |
ianna_score.py | import pygame
import time
import scripts
"""
Score class
Handles all the score area
package: ianna
"""
class IannaScore():
def __init__ (self, buffer, screen, game_entities):
self.score_image = pygame.image.load('artwork/marcador.png').convert()
self.font = pygame.image.load('artwork/font.png').convert()
... |
for item in player.inventory[self.first_object_in_inventory:]:
if x == 3:
break
self.buffer.blit(player.map.tile_table[self.tiles_per_pickable_object[item]], (currentx,168))
currentx = currentx + 24
x = x + 1
# Use a marker for the current selected object
self.buffer.blit(self.chars[63],(24+... | self.first_object_in_inventory = self.first_object_in_inventory - 1 | conditional_block |
ianna_score.py | import pygame
import time
import scripts
"""
Score class
Handles all the score area
package: ianna
"""
class IannaScore():
def __init__ (self, buffer, screen, game_entities):
self.score_image = pygame.image.load('artwork/marcador.png').convert()
self.font = pygame.image.load('artwork/font.png').convert()
... |
def print_meter(self,x,value, color):
'''
Display an entity health, on X
'''
y=191
value = value*23/100
rect = [x+2,y-value,5,value]
pygame.draw.rect(self.buffer,color,rect)
def print_inventory(self,player):
'''
Display the inventory
'''
currentx = 24
x = 0
if player.current_object >... | '''
Silly function, just wait for a keypress to happen
In the Spectrum version, it should be way better
'''
keypressed = False
keyreleased = False
key = None
while (not keypressed) and (not keyreleased):
events = pygame.event.get()
for event in events:
if event.type == pygame.KEYDOWN: # keypress... | identifier_body |
ianna_score.py | import pygame
import time
import scripts
"""
Score class
Handles all the score area
package: ianna
"""
class IannaScore():
def __init__ (self, buffer, screen, game_entities):
self.score_image = pygame.image.load('artwork/marcador.png').convert()
self.font = pygame.image.load('artwork/font.png').convert()
... | self.buffer.blit(self.chars[char],(8+x*8,168+y*8))
x = x + 1
j = j + 1
pygame.transform.scale(self.buffer,(256*3,192*3),self.screen)
pygame.display.flip()
fpsClock.tick(25) # run at 10 fps
self.buffer.blit(self.chars[32],(240,184))
pygame.transform.scale(self.buffer,(256*3,192*3),self.scree... | char = ord(word[j]) - 32 | random_line_split |
ianna_score.py | import pygame
import time
import scripts
"""
Score class
Handles all the score area
package: ianna
"""
class IannaScore():
def __init__ (self, buffer, screen, game_entities):
self.score_image = pygame.image.load('artwork/marcador.png').convert()
self.font = pygame.image.load('artwork/font.png').convert()
... | (self):
'''
Silly function, just wait for a keypress to happen
In the Spectrum version, it should be way better
'''
keypressed = False
keyreleased = False
key = None
while (not keypressed) and (not keyreleased):
events = pygame.event.get()
for event in events:
if event.type == pygame.KEYDOWN: ... | wait_for_keypress | identifier_name |
backports.spec.ts | import { inspect } from 'util'
import { testing } from 'bs-logger'
import set from 'lodash.set'
import { backportJestConfig } from './backports'
const logger = testing.createLoggerMock()
const logTarget = logger.target
beforeEach(() => {
logTarget.clear()
})
describe('backportJestConfig', () => {
const makeTes... | }) | random_line_split | |
lib.rs |
(bodies of function expressions are checked as part of the
containing function). Inference is used to supply types wherever
they are unknown. The actual checking of a function itself has
several phases (check, regionck, writeback), as discussed in the
documentation for the `check` module.
The type che... |
let se_ty = tcx.mk_fn(Some(local_def(start_id)), tcx.mk_bare_fn(ty::BareFnTy {
unsafety: ast::Unsafety::Normal,
abi: abi::Rust, | random_line_split | |
lib.rs | check phase, we check each function body one at a time
(bodies of function expressions are checked as part of the
containing function). Inference is used to supply types wherever
they are unknown. The actual checking of a function itself has
several phases (check, regionck, writeback), as discussed in the... |
fn require_c_abi_if_variadic(tcx: &ty::ctxt,
decl: &ast::FnDecl,
abi: abi::Abi,
span: Span) {
if decl.variadic && abi != abi::C {
span_err!(tcx.sess, span, E0045,
"variadic function must have C calling... | {
match tcx.def_map.borrow().get(&id) {
Some(x) => x.full_def(),
None => {
span_fatal!(tcx.sess, sp, E0242, "internal error looking up a definition")
}
}
} | identifier_body |
lib.rs | check phase, we check each function body one at a time
(bodies of function expressions are checked as part of the
containing function). Inference is used to supply types wherever
they are unknown. The actual checking of a function itself has
several phases (check, regionck, writeback), as discussed in the... | (ccx: &CrateCtxt,
start_id: ast::NodeId,
start_span: Span) {
let tcx = ccx.tcx;
let start_t = tcx.node_id_to_type(start_id);
match start_t.sty {
ty::TyBareFn(..) => {
match tcx.map.find(start_id) {
Some(ast_map::NodeItem(it)) => {... | check_start_fn_ty | identifier_name |
adjglobals.py | import coeffstore
import expressions
import caching
import libadjoint
from dolfin_adjoint import backend
if backend.__name__ == "dolfin":
import lusolver
# Create the adjointer, the central object that records the forward solve
# as it happens.
adjointer = libadjoint.Adjointer()
mem_checkpoints = set()
disk_check... | lusolver.lu_solvers = [None] * len(lusolver.lu_solvers)
lusolver.adj_lu_solvers = [None] * len(lusolver.adj_lu_solvers)
def adj_html(*args, **kwargs):
'''This routine dumps the current state of the adjglobals.adjointer to a HTML visualisation.
Use it like:
- adj_html("forward.html", "for... |
caching.pis_fwd_to_tlm.clear()
caching.pis_fwd_to_adj.clear()
if backend.__name__ == "dolfin": | random_line_split |
adjglobals.py | import coeffstore
import expressions
import caching
import libadjoint
from dolfin_adjoint import backend
if backend.__name__ == "dolfin":
import lusolver
# Create the adjointer, the central object that records the forward solve
# as it happens.
adjointer = libadjoint.Adjointer()
mem_checkpoints = set()
disk_check... |
# Map from FunctionSpace to LUSolver that has factorised the fsp mass matrix
fsp_lu = {}
| '''Forget all annotation, and reset the entire dolfin-adjoint state.'''
adjointer.reset()
expressions.expression_attrs.clear()
adj_variables.__init__()
function_names.__init__()
adj_reset_cache()
backend.parameters["adjoint"]["stop_annotating"] = False | identifier_body |
adjglobals.py | import coeffstore
import expressions
import caching
import libadjoint
from dolfin_adjoint import backend
if backend.__name__ == "dolfin":
import lusolver
# Create the adjointer, the central object that records the forward solve
# as it happens.
adjointer = libadjoint.Adjointer()
mem_checkpoints = set()
disk_check... |
# A dictionary that saves the functionspaces of all checkpoint variables that have been saved to disk
checkpoint_fs = {}
function_names = set()
def adj_check_checkpoints():
adjointer.check_checkpoints()
def adj_reset_cache():
if backend.parameters["adjoint"]["debug_cache"]:
backend.info_blue("Reset... | adj_variables.increment_timestep()
if time is not None:
adjointer.time.next(time)
if finished:
adjointer.time.finish() | conditional_block |
adjglobals.py | import coeffstore
import expressions
import caching
import libadjoint
from dolfin_adjoint import backend
if backend.__name__ == "dolfin":
import lusolver
# Create the adjointer, the central object that records the forward solve
# as it happens.
adjointer = libadjoint.Adjointer()
mem_checkpoints = set()
disk_check... | (time=None, finished=False):
'''Dolfin does not supply us with information about timesteps, and so more information
is required from the user for certain features. This function should be called at
the end of the time loop with two arguments:
- :py:data:`time` -- the time at the end of the timestep j... | adj_inc_timestep | identifier_name |
link-input.js | 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 the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*... |
});
});
}
}
if ((!validationExist && obj.inputEl.value != '') || (validationExist && validationResult)) {
for (var i = 0; i < obj.constraints.length; i++) {
var constraint = obj.constraints[i];
if (constraint.name == 'pattern') {
var regex = constraint.v... | {
if (id.includes(prop.value) && prop.value != '') {
el.required = false;
el.clearError('required');
el.renderValidation(false, false);
var constraints = el.constraints.forEach(function (constr) {
if (constr.name == 'require... | conditional_block |
link-input.js | 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 the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*... |
YAHOO.util.Dom.addClass(titleEl, 'cstudio-form-field-title');
titleEl.textContent = config.title;
var controlWidgetContainerEl = document.createElement('div');
YAHOO.util.Dom.addClass(controlWidgetContainerEl, 'cstudio-form-control-link-input-container');
var validEl = document.createElement('spa... | // we need to make the general layout of a control inherit from common
// you should be able to override it -- but most of the time it wil be the same
containerEl.id = this.id;
var titleEl = document.createElement('span'); | random_line_split |
engine.rs | use std::str::FromStr;
use crate::parsers::lang::{Lang, LangType};
use crate::parsers::planner;
use crate::parsers::sql::Sql;
use crate::parsers::value::PqlValue;
pub fn evaluate(sql: &str, input: &str, from: &str, to: &str) -> anyhow::Result<String> {
let from_lang_type = LangType::from_str(&from)?;
let to_l... |
pub fn query_evaluate(data: PqlValue, sql: &str) -> anyhow::Result<PqlValue> {
let sql = Sql::from_str(&sql)?;
let data = PqlValue::from(data);
let value = planner::evaluate(sql, data);
Ok(value)
}
| {
let to_lang_type = LangType::from_str(&to)?;
let mut lang = Lang::default();
lang.data = data;
lang.to = to_lang_type;
let output = lang.to_string(true)?;
Ok(output)
} | identifier_body |
engine.rs | use std::str::FromStr;
use crate::parsers::lang::{Lang, LangType};
use crate::parsers::planner;
use crate::parsers::sql::Sql;
use crate::parsers::value::PqlValue;
pub fn evaluate(sql: &str, input: &str, from: &str, to: &str) -> anyhow::Result<String> {
let from_lang_type = LangType::from_str(&from)?;
let to_l... | lang.data = result;
let output = lang.to_string(true)?;
Ok(output)
}
pub fn loads(input: &str, from: &str) -> anyhow::Result<PqlValue> {
let from_lang_type = LangType::from_str(&from)?;
let lang = Lang::from_as(&input, from_lang_type)?;
let value = lang.data;
Ok(value)
}
pub fn dumps(data... | let sql = Sql::from_str(&sql)?;
let result = planner::evaluate(sql, lang.data);
lang.to = to_lang_type; | random_line_split |
engine.rs | use std::str::FromStr;
use crate::parsers::lang::{Lang, LangType};
use crate::parsers::planner;
use crate::parsers::sql::Sql;
use crate::parsers::value::PqlValue;
pub fn evaluate(sql: &str, input: &str, from: &str, to: &str) -> anyhow::Result<String> {
let from_lang_type = LangType::from_str(&from)?;
let to_l... | (data: PqlValue, to: &str) -> anyhow::Result<String> {
let to_lang_type = LangType::from_str(&to)?;
let mut lang = Lang::default();
lang.data = data;
lang.to = to_lang_type;
let output = lang.to_string(true)?;
Ok(output)
}
pub fn query_evaluate(data: PqlValue, sql: &str) -> anyhow::Result<PqlVa... | dumps | identifier_name |
box.js | /*
(The MIT License)
Copyright (C) 2005-2013 Kai Davenport
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... | _.each(options.wires, function(wireoptions, name){
wireoptions.name = options.name + ':' + name;
wireoptions.manual = wireoptions.manual ? true : false;
box.wires[name] = Wire(wireoptions);
})
return box;
}
| {
options || (options = {
name:'device' + utils.littleid()
})
var box = {
name:options.name,
devices:{},
wires:{}
}
_.extend(box, EventEmitter.prototype);
_.each(options.devices, function(deviceoptions, name){
deviceoptions.name = options.name + ':' + name;
deviceoptions.manual =... | identifier_body |
box.js | /*
(The MIT License)
Copyright (C) 2005-2013 Kai Davenport
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... | type: (device factory type)
direction: ( bind | connect | parent )
address: ( 'ipc:/filepath' | 'tcp://x.x.x.x:yyyy' )
->
id:id
sockets: {}
it will turn the children array into a socket map
*/
function factory(options){
options || (options = {
name:'device' + utils... | name -> id: ( socket identity ) | random_line_split |
box.js | /*
(The MIT License)
Copyright (C) 2005-2013 Kai Davenport
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... | (options){
options || (options = {
name:'device' + utils.littleid()
})
var box = {
name:options.name,
devices:{},
wires:{}
}
_.extend(box, EventEmitter.prototype);
_.each(options.devices, function(deviceoptions, name){
deviceoptions.name = options.name + ':' + name;
deviceoptions... | factory | identifier_name |
delete-version.rs | // Purge all references to a crate's version from the database.
//
// Please be super sure you want to do this before running this.
//
// Usage:
// cargo run --bin delete-version crate-name version-number
#![deny(warnings)]
extern crate cargo_registry;
extern crate postgres;
extern crate time;
extern crate semve... |
fn main() {
let conn = postgres::Connection::connect(&env("DATABASE_URL")[..],
&postgres::SslMode::None).unwrap();
{
let tx = conn.transaction().unwrap();
delete(&tx);
tx.set_commit();
tx.finish().unwrap();
}
}
fn env(s: &str) ->... |
use cargo_registry::{Crate, Version}; | random_line_split |
delete-version.rs | // Purge all references to a crate's version from the database.
//
// Please be super sure you want to do this before running this.
//
// Usage:
// cargo run --bin delete-version crate-name version-number
#![deny(warnings)]
extern crate cargo_registry;
extern crate postgres;
extern crate time;
extern crate semve... |
fn delete(tx: &postgres::Transaction) {
let name = match env::args().nth(1) {
None => { println!("needs a crate-name argument"); return }
Some(s) => s,
};
let version = match env::args().nth(2) {
None => { println!("needs a version argument"); return }
Some(s) => s,
};
... | {
match env::var(s).ok() {
Some(s) => s,
None => panic!("must have `{}` defined", s),
}
} | identifier_body |
delete-version.rs | // Purge all references to a crate's version from the database.
//
// Please be super sure you want to do this before running this.
//
// Usage:
// cargo run --bin delete-version crate-name version-number
#![deny(warnings)]
extern crate cargo_registry;
extern crate postgres;
extern crate time;
extern crate semve... | (tx: &postgres::Transaction) {
let name = match env::args().nth(1) {
None => { println!("needs a crate-name argument"); return }
Some(s) => s,
};
let version = match env::args().nth(2) {
None => { println!("needs a version argument"); return }
Some(s) => s,
};
let ver... | delete | identifier_name |
card-harness.d.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
* | * Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { HarnessPredicate, ContentContainerComponentHarness } from '@angular/cdk/testing';
import { CardHarnessFilters } from './card-harness-filters';
/** Selectors for different se... | random_line_split | |
card-harness.d.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { HarnessPredicate, ContentContainerComponentHarness } from '@angular/cdk/testing';
import { CardHarnessFilters... | extends ContentContainerComponentHarness<MatCardSection> {
/** The selector for the host element of a `MatCard` instance. */
static hostSelector: string;
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatCardHarness` that meets
* certain criteria.
* @param options Options ... | MatCardHarness | identifier_name |
borrowck-lend-flow.rs | // Copyright 2012 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 ... | let _w = &v;
borrow_mut(&mut *v); //~ ERROR cannot borrow
}
fn post_freeze() {
// In this instance, the const alias starts after the borrow.
let mut v = box 3;
borrow_mut(&mut *v);
let _w = &v;
}
fn main() {} |
let mut v = box 3; | random_line_split |
borrowck-lend-flow.rs | // Copyright 2012 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 ... | <F>(_f: F) where F: FnOnce() -> bool { panic!() }
fn produce<T>() -> T { panic!(); }
fn inc(v: &mut Box<int>) {
*v = box() (**v + 1);
}
fn pre_freeze() {
// In this instance, the freeze starts before the mut borrow.
let mut v = box 3;
let _w = &v;
borrow_mut(&mut *v); //~ ERROR cannot borrow
}
f... | for_func | identifier_name |
borrowck-lend-flow.rs | // Copyright 2012 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 ... |
fn for_func<F>(_f: F) where F: FnOnce() -> bool { panic!() }
fn produce<T>() -> T { panic!(); }
fn inc(v: &mut Box<int>) {
*v = box() (**v + 1);
}
fn pre_freeze() {
// In this instance, the freeze starts before the mut borrow.
let mut v = box 3;
let _w = &v;
borrow_mut(&mut *v); //~ ERROR cannot... | { panic!() } | identifier_body |
find_minimum.py | #! /usr/bin/python
'''
Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
'''
class Solution:
# @param num, a list of integer
# @return an integer
# You may assume no duplicate exists in the array.
def fi... |
# @param num, a list of integer
# @return an integer
# You may assume duplicate exists in the array.
def findMinDuplicate(self, num):
INT_MIN_VALUE = -(2**32)
size = len(num)
if size == 0:
return INT_MIN_VALUE
elif size == 1:
return num[0]
... | INT_MIN_VALUE = -(2**32)
size = len(num)
if size == 0:
return INT_MIN_VALUE
elif size == 1:
return num[0]
low_index = 0
high_index = size - 1
while (low_index < high_index - 1):
mid_index = low_index + (high_index - low_index) / 2
... | identifier_body |
find_minimum.py | #! /usr/bin/python
'''
Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
'''
class Solution:
# @param num, a list of integer
# @return an integer
# You may assume no duplicate exists in the array.
def | (self, num):
INT_MIN_VALUE = -(2**32)
size = len(num)
if size == 0:
return INT_MIN_VALUE
elif size == 1:
return num[0]
low_index = 0
high_index = size - 1
while (low_index < high_index - 1):
mid_index = low_index + (high_index -... | findMinNoDuplicate | identifier_name |
find_minimum.py | #! /usr/bin/python
'''
Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
'''
class Solution:
# @param num, a list of integer
# @return an integer
# You may assume no duplicate exists in the array.
def fi... |
elif size == 1:
return num[0]
low_index = 0
high_index = size - 1
while (low_index < high_index - 1):
mid_index = low_index + (high_index - low_index) / 2
if (num[mid_index] > num[high_index]):
low_index = mid_index
else:
... | return INT_MIN_VALUE | conditional_block |
find_minimum.py | #! /usr/bin/python
'''
Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
'''
class Solution:
# @param num, a list of integer
# @return an integer
# You may assume no duplicate exists in the array.
def fi... | if size == 0:
return INT_MIN_VALUE
elif size == 1:
return num[0]
low_index = 0
high_index = size - 1
while (low_index < high_index - 1):
mid_index = low_index + (high_index - low_index) / 2
if (num[mid_index] > num[high_index]):
... | INT_MIN_VALUE = -(2**32)
size = len(num) | random_line_split |
aeat_sii_map.py | # Copyright 2017 Ignacio Ibeas <ignacio@acysos.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, exceptions, fields, models
class | (models.Model):
_name = "aeat.sii.map"
_description = "Aeat SII Map"
@api.constrains("date_from", "date_to")
def _unique_date_range(self):
for record in self:
record._unique_date_range_one()
def _unique_date_range_one(self):
# Based in l10n_es_aeat module
domain... | AeatSiiMap | identifier_name |
aeat_sii_map.py | # Copyright 2017 Ignacio Ibeas <ignacio@acysos.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, exceptions, fields, models
| _description = "Aeat SII Map"
@api.constrains("date_from", "date_to")
def _unique_date_range(self):
for record in self:
record._unique_date_range_one()
def _unique_date_range_one(self):
# Based in l10n_es_aeat module
domain = [("id", "!=", self.id)]
if self.... |
class AeatSiiMap(models.Model):
_name = "aeat.sii.map" | random_line_split |
aeat_sii_map.py | # Copyright 2017 Ignacio Ibeas <ignacio@acysos.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, exceptions, fields, models
class AeatSiiMap(models.Model):
_name = "aeat.sii.map"
_description = "Aeat SII Map"
@api.constrains("date_from", "date_to")
def _un... |
def _unique_date_range_one(self):
# Based in l10n_es_aeat module
domain = [("id", "!=", self.id)]
if self.date_from and self.date_to:
domain += [
"|",
"&",
("date_from", "<=", self.date_to),
("date_from", ">=", sel... | for record in self:
record._unique_date_range_one() | identifier_body |
aeat_sii_map.py | # Copyright 2017 Ignacio Ibeas <ignacio@acysos.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, exceptions, fields, models
class AeatSiiMap(models.Model):
_name = "aeat.sii.map"
_description = "Aeat SII Map"
@api.constrains("date_from", "date_to")
def _un... |
date_lst = self.search(domain)
if date_lst:
raise exceptions.UserError(
_("Error! The dates of the record overlap with an existing " "record.")
)
name = fields.Char(string="Model", required=True)
date_from = fields.Date()
date_to = fields.Date()
... | domain += [("date_from", "<=", self.date_to)] | conditional_block |
ob_equality.py | # Copyright (C) 2013-2021 Roland Lutz
#
# 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 2 of the License, or
# (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 the GNU General Public License
# alon... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.