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 |
|---|---|---|---|---|
ng_control.ts | /**
* @license
* Copyright Google Inc. 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 {AbstractControlDirective} from './abstract_control_directive';
import {ControlContainer} from './control_co... |
abstract viewToModelUpdate(newValue: any): void;
}
| { return <AsyncValidatorFn>unimplemented(); } | identifier_body |
ng_control.ts | /**
* @license
* Copyright Google Inc. 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 {AbstractControlDirective} from './abstract_control_directive';
import {ControlContainer} from './control_co... | (): ValidatorFn { return <ValidatorFn>unimplemented(); }
get asyncValidator(): AsyncValidatorFn { return <AsyncValidatorFn>unimplemented(); }
abstract viewToModelUpdate(newValue: any): void;
}
| validator | identifier_name |
ng_control.ts | /**
* @license
* Copyright Google Inc. 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 {AbstractControlDirective} from './abstract_control_directive';
import {ControlContainer} from './control_co... | } |
get validator(): ValidatorFn { return <ValidatorFn>unimplemented(); }
get asyncValidator(): AsyncValidatorFn { return <AsyncValidatorFn>unimplemented(); }
abstract viewToModelUpdate(newValue: any): void; | random_line_split |
problem6.py | #!/usr/bin/env python
################################################################################
#
# Project Euler - Problem 6
#
# The sum of the squares of the first ten natural numbers is, | #
# 1^2 + 2^2 + ... + 10^2 = 385
# The square of the sum of the first ten natural numbers is,
#
# (1 + 2 + ... + 10)^2 = 552 = 3025
# Hence the difference between the sum of the squares of the first ten natural
# numbers and the square of the sum is 3025 - 385 = 2640
#
# Find the difference between the sum of the squar... | random_line_split | |
problem6.py | #!/usr/bin/env python
################################################################################
#
# Project Euler - Problem 6
#
# The sum of the squares of the first ten natural numbers is,
#
# 1^2 + 2^2 + ... + 10^2 = 385
# The square of the sum of the first ten natural numbers is,
#
# (1 + 2 + ... + 10)^2 = 5... | sum_one_hundred = sum([x for x in range(1, 101)])
sum_one_hundred_squared = sum_one_hundred * sum_one_hundred
sum_squared = sum([x ** 2 for x in range(1, 101)])
solution = sum_one_hundred_squared - sum_squared
print(solution) | conditional_block | |
error.rs | use serde_json::Error as SerdeError;
use std::error::Error as StdError;
use std::fmt;
use std::io::Error as IoError;
#[derive(Debug)]
pub enum LatticeError {
IoError(IoError),
JsonParseError(SerdeError),
InconsistentVertices,
NegativeSize,
}
impl StdError for LatticeError {
fn description(&self) -... |
fn cause(&self) -> Option<&StdError> {
match self {
LatticeError::IoError(err) => Some(err),
LatticeError::JsonParseError(err) => Some(err),
_ => None,
}
}
}
impl fmt::Display for LatticeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
... | {
match self {
LatticeError::IoError(_) => "There was an error reading your file",
LatticeError::JsonParseError(_) => "There was a problem parsing json",
LatticeError::InconsistentVertices => "These vertices are inconsistent",
LatticeError::NegativeSize => "What a... | identifier_body |
error.rs | use serde_json::Error as SerdeError;
use std::error::Error as StdError;
use std::fmt;
use std::io::Error as IoError;
#[derive(Debug)]
pub enum LatticeError {
IoError(IoError), |
impl StdError for LatticeError {
fn description(&self) -> &str {
match self {
LatticeError::IoError(_) => "There was an error reading your file",
LatticeError::JsonParseError(_) => "There was a problem parsing json",
LatticeError::InconsistentVertices => "These vertices ... | JsonParseError(SerdeError),
InconsistentVertices,
NegativeSize,
} | random_line_split |
error.rs | use serde_json::Error as SerdeError;
use std::error::Error as StdError;
use std::fmt;
use std::io::Error as IoError;
#[derive(Debug)]
pub enum LatticeError {
IoError(IoError),
JsonParseError(SerdeError),
InconsistentVertices,
NegativeSize,
}
impl StdError for LatticeError {
fn description(&self) -... | (err: IoError) -> Self {
LatticeError::IoError(err)
}
}
| from | identifier_name |
NodeReader.js | var io = require('cheerio');
var reader = {
readPart: function(body, index) {
var $ = io.load(body);
var part = { };
var title = '';
var items = [];
$('#divMiddleList > div:nth-child(' + index + ')').each(function (index, object) {
title = $(object).find('s... | var image = $(object).find('div.song_item_img > a > img').attr('src') || $(object).find('div.song_item_img > img').attr('src');
var title = $(object).find('div.song_item_title > a').text();
var link = $(object).find('div.song_item_title > a').attr('href');
var artiste = $... |
$('#divMiddleList > div:nth-child(' + (++index) + ') > div.song_item').each(function (index, object) {
| random_line_split |
archive.rs | // Copyright 2013-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-MI... | (&self) -> Vec<String> {
let output = run_ar(self.handler, &self.maybe_ar_prog, "t", None, [&self.dst]);
let output = str::from_utf8(output.output.as_slice()).unwrap();
// use lines_any because windows delimits output with `\r\n` instead of
// just `\n`
output.lines_any().map(|s|... | files | identifier_name |
archive.rs | // Copyright 2013-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-MI... | run_ar(self.handler, &self.maybe_ar_prog, cmd, None, [&self.dst, file]);
}
/// Removes a file from this archive
pub fn remove_file(&mut self, file: &str) {
run_ar(self.handler, &self.maybe_ar_prog, "d", None, [&self.dst, &Path::new(file)]);
}
/// Updates all symbols in the archive ... | pub fn add_file(&mut self, file: &Path, has_symbols: bool) {
let cmd = if has_symbols {"r"} else {"rS"}; | random_line_split |
archive.rs | // Copyright 2013-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-MI... | ,
Err(e) => {
handler.err(format!("could not exec `{}`: {}", ar.as_slice(),
e).as_slice());
handler.abort_if_errors();
fail!("rustc::back::archive::run_ar() should not reach this point");
}
}
}
impl<'a> Archive<'a> {
/// Initializ... | {
let o = prog.wait_with_output().unwrap();
if !o.status.success() {
handler.err(format!("{} failed with: {}",
cmd,
o.status).as_slice());
handler.note(format!("stdout ---\n{}",
... | conditional_block |
archive.rs | // Copyright 2013-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-MI... |
/// Adds all of the contents of the rlib at the specified path to this
/// archive.
///
/// This ignores adding the bytecode from the rlib, and if LTO is enabled
/// then the object file also isn't added.
pub fn add_rlib(&mut self, rlib: &Path, name: &str,
lto: bool) -> io:... | {
let location = self.find_library(name);
self.add_archive(&location, name, [])
} | identifier_body |
StaveTrackGroup.ts | import { Track } from '@src/model/Track';
import { RenderStaff } from '@src/rendering/staves/RenderStaff';
import { StaveGroup } from '@src/rendering/staves/StaveGroup';
export class StaveTrackGroup {
public track: Track;
public staveGroup: StaveGroup;
public staves: RenderStaff[] = [];
public stavesRe... | (staff: RenderStaff): void {
this.staves.push(staff);
if (staff.isRelevantForBoundsLookup) {
this.stavesRelevantForBoundsLookup.push(staff);
}
}
}
| addStaff | identifier_name |
StaveTrackGroup.ts | import { Track } from '@src/model/Track';
import { RenderStaff } from '@src/rendering/staves/RenderStaff';
import { StaveGroup } from '@src/rendering/staves/StaveGroup'; | public staves: RenderStaff[] = [];
public stavesRelevantForBoundsLookup: RenderStaff[] = [];
public firstStaffInAccolade: RenderStaff | null = null;
public lastStaffInAccolade: RenderStaff | null = null;
public constructor(staveGroup: StaveGroup, track: Track) {
this.staveGroup = staveGroup... |
export class StaveTrackGroup {
public track: Track;
public staveGroup: StaveGroup; | random_line_split |
StaveTrackGroup.ts | import { Track } from '@src/model/Track';
import { RenderStaff } from '@src/rendering/staves/RenderStaff';
import { StaveGroup } from '@src/rendering/staves/StaveGroup';
export class StaveTrackGroup {
public track: Track;
public staveGroup: StaveGroup;
public staves: RenderStaff[] = [];
public stavesRe... |
}
}
| {
this.stavesRelevantForBoundsLookup.push(staff);
} | conditional_block |
linear-for-loop.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 x = ~[1, 2, 3];
let mut y = 0;
for x.each |i| { debug!(*i); y += *i; }
debug!(y);
assert!((y == 6));
let s = ~"hello there";
let mut i: int = 0;
for str::each(s) |c| {
if i == 0 { assert!((c == 'h' as u8)); }
if i == 1 { assert!((c == 'e' as u8)); }
if i ... | main | identifier_name |
linear-for-loop.rs | // 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 http://opensource.org/licenses/MIT>, at your
// option. This file... | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT | random_line_split | |
linear-for-loop.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 ... |
debug!(y);
assert!((y == 6));
let s = ~"hello there";
let mut i: int = 0;
for str::each(s) |c| {
if i == 0 { assert!((c == 'h' as u8)); }
if i == 1 { assert!((c == 'e' as u8)); }
if i == 2 { assert!((c == 'l' as u8)); }
if i == 3 { assert!((c == 'l' as u8)); }
... | {
let x = ~[1, 2, 3];
let mut y = 0;
for x.each |i| { debug!(*i); y += *i; } | identifier_body |
linear-for-loop.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 ... |
if i == 4 { assert!((c == 'o' as u8)); }
// ...
i += 1;
debug!(i);
debug!(c);
}
assert!((i == 11));
}
| { assert!((c == 'l' as u8)); } | conditional_block |
static.py | # -* encoding: utf-8 *-
# 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/.
import configargparse
from typing import Any, Type
from gopythongo.utils import highlight, Er... |
@property
def can_read(self) -> bool:
return True
def read(self, args: configargparse.Namespace) -> str:
return args.static_version
def print_help(self) -> None:
print("Static Versioner\n"
"================\n"
"\n"
"The static Version... | if not args.static_version:
raise ErrorMessage("Static versioner requires %s" % highlight("--static-version")) | identifier_body |
static.py | # -* encoding: utf-8 *-
# 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/.
import configargparse
from typing import Any, Type
from gopythongo.utils import highlight, Er... | (self, args: configargparse.Namespace) -> None:
if not args.static_version:
raise ErrorMessage("Static versioner requires %s" % highlight("--static-version"))
@property
def can_read(self) -> bool:
return True
def read(self, args: configargparse.Namespace) -> str:
return... | validate_args | identifier_name |
static.py | # -* encoding: utf-8 *-
# This Source Code Form is subject to the terms of the Mozilla Public | from typing import Any, Type
from gopythongo.utils import highlight, ErrorMessage
from gopythongo.versioners import BaseVersioner
class StaticVersioner(BaseVersioner):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@property
def versioner_name(self) -> s... | # 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/.
import configargparse
| random_line_split |
static.py | # -* encoding: utf-8 *-
# 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/.
import configargparse
from typing import Any, Type
from gopythongo.utils import highlight, Er... |
@property
def can_read(self) -> bool:
return True
def read(self, args: configargparse.Namespace) -> str:
return args.static_version
def print_help(self) -> None:
print("Static Versioner\n"
"================\n"
"\n"
"The static Version... | raise ErrorMessage("Static versioner requires %s" % highlight("--static-version")) | conditional_block |
version.ts | /*
Copyright 2016 kanreisa
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 ... | tags: ["version"],
operationId: "checkVersion",
responses: {
200: {
description: "OK",
schema: {
$ref: "#/definitions/Version"
}
},
default: {
description: "Unexpected Error",
schema: {
... |
api.responseJSON(res, version);
};
get.apiDoc = {
| random_line_split |
review_comments.py | # This file is part of Indico.
# Copyright (C) 2002 - 2019 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from sqlalchemy.ext.declarative import declared_attr
from indico... | db.ForeignKey('users.users.id'),
index=True,
nullable=True
)
@declared_attr
def created_dt(cls):
return db.Column(
UTCDateTime,
nullable=False,
default=now_utc
)
@declared_attr
def modified_dt(cls):
... | return db.Column(
db.Integer, | random_line_split |
review_comments.py | # This file is part of Indico.
# Copyright (C) 2002 - 2019 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from sqlalchemy.ext.declarative import declared_attr
from indico... | (cls):
return db.Column(
db.Integer,
primary_key=True
)
@declared_attr
def user_id(cls):
return db.Column(
db.Integer,
db.ForeignKey('users.users.id'),
index=True,
nullable=False
)
@declared_attr
de... | id | identifier_name |
review_comments.py | # This file is part of Indico.
# Copyright (C) 2002 - 2019 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from sqlalchemy.ext.declarative import declared_attr
from indico... |
@declared_attr
def modified_by_id(cls):
return db.Column(
db.Integer,
db.ForeignKey('users.users.id'),
index=True,
nullable=True
)
@declared_attr
def created_dt(cls):
return db.Column(
UTCDateTime,
nullabl... | return db.Column(
'text',
db.Text,
nullable=False
) | identifier_body |
cargo_run.rs | use std::os;
use ops::{self, ExecEngine};
use util::{CargoResult, human, process, ProcessError, ChainError};
use core::manifest::TargetKind;
use core::source::Source;
use sources::PathSource;
pub fn run(manifest_path: &Path,
target_kind: TargetKind,
name: Option<String>,
options: &mut... | human("`cargo run` requires that a project only have one executable. \
Use the `--bin` option to specify which one to run")),
None => {}
}
let compile = try!(ops::compile(manifest_path, options));
let dst = manifest_path.dir_path().join("target");
let dst = match ... | {
let mut src = try!(PathSource::for_path(&manifest_path.dir_path()));
try!(src.update());
let root = try!(src.get_root_package());
let env = options.env;
let mut bins = root.get_manifest().get_targets().iter().filter(|a| {
let matches_kind = match target_kind {
TargetKind::Bin =... | identifier_body |
cargo_run.rs | use std::os;
use ops::{self, ExecEngine};
use util::{CargoResult, human, process, ProcessError, ChainError};
use core::manifest::TargetKind;
use core::source::Source;
use sources::PathSource;
pub fn run(manifest_path: &Path,
target_kind: TargetKind,
name: Option<String>,
options: &mut... |
}
let compile = try!(ops::compile(manifest_path, options));
let dst = manifest_path.dir_path().join("target");
let dst = match options.target {
Some(target) => dst.join(target),
None => dst,
};
let exe = match (bin.get_profile().get_dest(), bin.is_example()) {
(Some(s),... | {} | conditional_block |
cargo_run.rs | use std::os;
use ops::{self, ExecEngine};
use util::{CargoResult, human, process, ProcessError, ChainError};
use core::manifest::TargetKind;
use core::source::Source;
use sources::PathSource;
pub fn | (manifest_path: &Path,
target_kind: TargetKind,
name: Option<String>,
options: &mut ops::CompileOptions,
args: &[String]) -> CargoResult<Option<ProcessError>> {
let mut src = try!(PathSource::for_path(&manifest_path.dir_path()));
try!(src.update());
let root = try... | run | identifier_name |
cargo_run.rs | use std::os;
use ops::{self, ExecEngine};
use util::{CargoResult, human, process, ProcessError, ChainError};
use core::manifest::TargetKind;
use core::source::Source;
use sources::PathSource;
pub fn run(manifest_path: &Path,
target_kind: TargetKind,
name: Option<String>,
options: &mut... | Some(path) => path,
None => exe,
};
let process = try!(try!(compile.target_process(exe, &root))
.into_process_builder())
.args(args)
.cwd(try!(os::getcwd()));
try!(options.shell.status("Running", proce... | (Some(s), false) => dst.join(s).join(bin.get_name()),
(None, true) => dst.join("examples").join(bin.get_name()),
(None, false) => dst.join(bin.get_name()),
};
let exe = match exe.path_relative_from(&try!(os::getcwd())) { | random_line_split |
lib.rs | //! FFI bindings for `energymon-osp-polling.h`.
extern crate libc;
extern crate energymon_sys;
pub use energymon_sys::energymon;
use libc::{c_int, uint64_t, c_char, size_t};
extern "C" {
pub fn energymon_init_osp_polling(em: *mut energymon) -> c_int;
pub fn energymon_read_total_osp_polling(em: *const energy... | pub fn energymon_is_exclusive_osp_polling() -> c_int;
pub fn energymon_get_osp_polling(em: *mut energymon) -> c_int;
} | random_line_split | |
book.js | /* @flow */
/*
class Name {
firstName: string;
lastName: string;
constructor(firstName:string, lastName:string) {
this.firstName = firstName
this.lastName = lastName
}
}
class EsperantoName {
nominative: Name;
accusative: Name;
constructor(nominative:Name, accusative:Name) {
this.nominativ... | this.address = address
}
var Publisher = function(name:string, location:Address) {
this.name = name
this.location = location
}
var Edition = function(book:Book, editionDate:Date, translator:Person, translationDate:Date) {
this.book = book
this.editionDate = editionDate
this.translator = translator
this.... |
var Address = function(address:string) { | random_line_split |
setup.py | # coding=utf-8
# Bootstrap installation of setuptools
from ez_setup import use_setuptools
use_setuptools()
import os
import sys
from fnmatch import fnmatchcase
from distutils.util import convert_path
from propane_distribution import cmdclassdict
from setuptools import setup, find_packages
from engineer import version... | included in package data are shown on stderr (for debugging
purposes).
Note patterns use wildcards, or can be exact paths (including
leading ``./``), and all searching is case-insensitive.
This function is by Ian Bicking.
"""
out = {}
stack = [(convert_path(where), '', package, only_i... | """
Return a dictionary suitable for use in ``package_data``
in a distutils ``setup.py`` file.
The dictionary looks like::
{'package': [files]}
Where ``files`` is a list of all the files in that package that
don't match anything in ``exclude``.
If ``only_in_packages`` is true, then t... | identifier_body |
setup.py | # coding=utf-8
# Bootstrap installation of setuptools
from ez_setup import use_setuptools
use_setuptools()
import os
import sys
from fnmatch import fnmatchcase
from distutils.util import convert_path
from propane_distribution import cmdclassdict
from setuptools import setup, find_packages
from engineer import version... | for line in temp:
if line is None or line == '' or line.startswith(('#', '-e', '-r')):
continue
else:
requirements.append(line)
return requirements
# noinspection PyShadowingBuiltins
def get_readme():
with open('README.md') as file:
r... | random_line_split | |
setup.py | # coding=utf-8
# Bootstrap installation of setuptools
from ez_setup import use_setuptools
use_setuptools()
import os
import sys
from fnmatch import fnmatchcase
from distutils.util import convert_path
from propane_distribution import cmdclassdict
from setuptools import setup, find_packages
from engineer import version... | (
where='.', package='',
exclude=standard_exclude,
exclude_directories=standard_exclude_directories,
only_in_packages=True,
show_ignored=False):
"""
Return a dictionary suitable for use in ``package_data``
in a distutils ``setup.py`` file.
The dictionary looks li... | find_package_data | identifier_name |
setup.py | # coding=utf-8
# Bootstrap installation of setuptools
from ez_setup import use_setuptools
use_setuptools()
import os
import sys
from fnmatch import fnmatchcase
from distutils.util import convert_path
from propane_distribution import cmdclassdict
from setuptools import setup, find_packages
from engineer import version... |
stack.append((fn, '', new_package, False))
else:
stack.append((fn, prefix + name + '/', package, only_in_packages))
elif package or not only_in_packages:
# is a file
bad_name = False
for pattern in exclu... | new_package = package + '.' + name | conditional_block |
UrlBatch.ts | import AbstractBatch from "@enhavo/app/grid/batch/model/AbstractBatch";
import Confirm from "@enhavo/app/view/Confirm";
import axios from "axios";
import * as _ from "lodash";
import Message from "@enhavo/app/flash-message/Message";
import BatchDataInterface from "@enhavo/app/grid/batch/BatchDataInterface";
import Flas... |
let parameters = this.routeParameters;
if(!parameters) {
parameters = {};
}
if(this.batchData.batchRouteParameters) {
parameters = _.extend(parameters, this.batchData.batchRouteParameters);
}
return this.router.generate(route, parameters);
}... | {
let route = this.route;
if(!route) {
route = this.batchData.batchRoute;
} | random_line_split |
UrlBatch.ts | import AbstractBatch from "@enhavo/app/grid/batch/model/AbstractBatch";
import Confirm from "@enhavo/app/view/Confirm";
import axios from "axios";
import * as _ from "lodash";
import Message from "@enhavo/app/flash-message/Message";
import BatchDataInterface from "@enhavo/app/grid/batch/BatchDataInterface";
import Flas... | extends AbstractBatch
{
public route: string;
public routeParameters: object;
public confirmMessage: string;
protected readonly batchData: BatchDataInterface;
protected readonly translator: Translator;
protected readonly view: View;
protected readonly flashMessenger: FlashMessenger;
pr... | UrlBatch | identifier_name |
UrlBatch.ts | import AbstractBatch from "@enhavo/app/grid/batch/model/AbstractBatch";
import Confirm from "@enhavo/app/view/Confirm";
import axios from "axios";
import * as _ from "lodash";
import Message from "@enhavo/app/flash-message/Message";
import BatchDataInterface from "@enhavo/app/grid/batch/BatchDataInterface";
import Flas... |
}
| {
let route = this.route;
if(!route) {
route = this.batchData.batchRoute;
}
let parameters = this.routeParameters;
if(!parameters) {
parameters = {};
}
if(this.batchData.batchRouteParameters) {
parameters = _.extend(parameters... | identifier_body |
UrlBatch.ts | import AbstractBatch from "@enhavo/app/grid/batch/model/AbstractBatch";
import Confirm from "@enhavo/app/view/Confirm";
import axios from "axios";
import * as _ from "lodash";
import Message from "@enhavo/app/flash-message/Message";
import BatchDataInterface from "@enhavo/app/grid/batch/BatchDataInterface";
import Flas... |
return this.router.generate(route, parameters);
}
}
| {
parameters = _.extend(parameters, this.batchData.batchRouteParameters);
} | conditional_block |
skip_links.js | /*jslint browser: true, white: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, newcap: true, immed: true, indent: 4, onevar: false */
/*global window, $, jQuery, _ */
STUDIP.SkipLinks = {
activeElement : null,
navigationStatus : 0,
/**
* Displays the skip link navigation ... | };
jQuery(window.document).bind('keyup', STUDIP.SkipLinks.showSkipLinkNavigation);
jQuery(window.document).bind('ready', STUDIP.SkipLinks.initialize);
jQuery(window.document).bind('click', function (event) {
if (!jQuery(event.target).is('#skip_link_navigation a')) {
STUDIP.SkipLinks.moveSkipLinkNavigationO... | STUDIP.SkipLinks.setActiveTarget();
}
| random_line_split |
skip_links.js | /*jslint browser: true, white: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, newcap: true, immed: true, indent: 4, onevar: false */
/*global window, $, jQuery, _ */
STUDIP.SkipLinks = {
activeElement : null,
navigationStatus : 0,
/**
* Displays the skip link navigation ... |
STUDIP.SkipLinks.navigationStatus = 2;
},
getFragment: function () {
var fragmentStart = document.location.hash.indexOf('#');
if (fragmentStart < 0) {
return '';
}
return document.location.hash.substring(fragmentStart);
},
/**
* Inserts the lis... | {
jQuery(STUDIP.SkipLinks.box).hide();
jQuery('#skip_link_navigation').animate({opacity: 0}, 500, function () {
jQuery(this).css('left', '-600px');
});
} | conditional_block |
skia.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/.
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)] | #![allow(non_snake_case)]
use libc::*;
pub type SkiaGrContextRef = *mut c_void;
pub type SkiaGrGLInterfaceRef = *const c_void;
#[link(name = "skia")]
extern {
pub fn SkiaGrGLCreateNativeInterface() -> SkiaGrGLInterfaceRef;
pub fn SkiaGrGLInterfaceRetain(anInterface: SkiaGrGLInterfaceRef);
pub fn SkiaGrGLInterfaceRe... | random_line_split | |
zero.rs | use crate::driver::cmd::Args;
use crate::gc::bump::BumpAllocator;
use crate::gc::{Address, Collector, GcReason, Region};
use crate::os::{self, MemoryPermission};
use crate::vm::VM;
pub struct ZeroCollector {
start: Address,
end: Address,
alloc: BumpAllocator,
}
impl ZeroCollector {
pub fn new(args: &A... | (&self, _vm: &VM, size: usize, _array_ref: bool) -> Address {
self.alloc.bump_alloc(size)
}
fn collect(&self, _: &VM, _: GcReason) {
// do nothing
}
fn minor_collect(&self, _: &VM, _: GcReason) {
// do nothing
}
fn dump_summary(&self, runtime: f32) {
let mutato... | alloc | identifier_name |
zero.rs | use crate::driver::cmd::Args;
use crate::gc::bump::BumpAllocator;
use crate::gc::{Address, Collector, GcReason, Region};
use crate::os::{self, MemoryPermission};
use crate::vm::VM;
pub struct ZeroCollector {
start: Address,
end: Address,
alloc: BumpAllocator,
}
impl ZeroCollector {
pub fn new(args: &A... | else {
Some(ptr.region_start(size))
}
}
fn alloc(&self, _vm: &VM, size: usize, _array_ref: bool) -> Address {
self.alloc.bump_alloc(size)
}
fn collect(&self, _: &VM, _: GcReason) {
// do nothing
}
fn minor_collect(&self, _: &VM, _: GcReason) {
// d... | {
None
} | conditional_block |
zero.rs | use crate::driver::cmd::Args;
use crate::gc::bump::BumpAllocator;
use crate::gc::{Address, Collector, GcReason, Region};
use crate::os::{self, MemoryPermission};
use crate::vm::VM;
pub struct ZeroCollector {
start: Address,
end: Address,
alloc: BumpAllocator,
}
impl ZeroCollector {
pub fn new(args: &A... |
}
impl Collector for ZeroCollector {
fn supports_tlab(&self) -> bool {
true
}
fn alloc_tlab_area(&self, _vm: &VM, size: usize) -> Option<Region> {
let ptr = self.alloc.bump_alloc(size);
if ptr.is_null() {
None
} else {
Some(ptr.region_start(size))
... | {
let heap_size: usize = args.max_heap_size();
let reservation = os::reserve_align(heap_size, 0, false);
let start = reservation.start;
let end = start.offset(heap_size);
os::commit_at(start, heap_size, MemoryPermission::ReadWrite);
ZeroCollector {
start,
... | identifier_body |
zero.rs | use crate::driver::cmd::Args;
use crate::gc::bump::BumpAllocator;
use crate::gc::{Address, Collector, GcReason, Region};
use crate::os::{self, MemoryPermission};
use crate::vm::VM;
pub struct ZeroCollector {
start: Address,
end: Address,
alloc: BumpAllocator,
}
impl ZeroCollector {
pub fn new(args: &A... | // do nothing
}
fn dump_summary(&self, runtime: f32) {
let mutator = runtime;
let gc = 0.0f32;
println!("GC stats: total={:.1}", runtime);
println!("GC stats: mutator={:.1}", mutator);
println!("GC stats: collection={:.1}", gc);
println!(
"G... | fn minor_collect(&self, _: &VM, _: GcReason) { | random_line_split |
0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class | (migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='StaticPage',
fields=[
('id', models.AutoField(serialize=False, auto_created=True, primary_key=True, verbose_name='ID')),
('url', models.CharField(verbose_... | Migration | identifier_name |
0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
| 'verbose_name': 'static page',
},
bases=(models.Model,),
),
]
| dependencies = [
]
operations = [
migrations.CreateModel(
name='StaticPage',
fields=[
('id', models.AutoField(serialize=False, auto_created=True, primary_key=True, verbose_name='ID')),
('url', models.CharField(verbose_name='URL', db_index=True, ma... | identifier_body |
0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='StaticPage',
fields=[ | ('id', models.AutoField(serialize=False, auto_created=True, primary_key=True, verbose_name='ID')),
('url', models.CharField(verbose_name='URL', db_index=True, max_length=100)),
('title', models.CharField(verbose_name='title', max_length=200)),
('title_ru',... | random_line_split | |
setup.py | from distutils.core import setup
setup(
name='PyMonad',
version='1.3', | author_email='jason.develops@gmail.com',
packages=['pymonad', 'pymonad.test'],
url='https://bitbucket.org/jason_delaat/pymonad',
license=open('LICENSE.txt').read(),
description='Collection of classes for programming with functors, applicative functors and monads.',
long_description=open('README.... | author='Jason DeLaat', | random_line_split |
guiders-1.1.1.v1314028514.js | "x" button in the top right of the guider
},
_htmlSkeleton: [
"<div class='outty'>",
" <div class='outty_shadow'></div>",
" <div class='outty_container'>",
" <div class='outty_content'>",
" <h4 class='outty_title'></h4>",
" <div class='outty_close'></div>",
" <p class='outty_descript... |
/**
* One way to show a guider to new users is to direct new users to a URL such as
* http://www.mysite.com/myapp#guider=welcome
*
* This can also be used to run guiders on multiple pages, by redirecting from
* one page to another, with the guider id in the hash tag.
*
* Alternat... | random_line_split | |
guiders-1.1.1.v1314028514.js | ButtonContainer.append(xButton);
$('<a href="#" class="close-button-blue"></a>').appendTo(xButton).click(function (e) {
guiders.hideAll();
e.stopPropagation();
e.preventDefault();
});
xButton.click(function() { guiders.hideAll(); });
},
_attach: function(myGuider) {
if (typeof myGuid... | {
id = guiders._lastCreatedGuiderID;
} | conditional_block | |
DnaSeparation.js | // Copyright 2015-2020, University of Colorado Boulder
/**
* Class that defines a separation of the DNA strand. This is used when forcing the DNA strand to separate in certain
* positions, which happens, for instance, when RNA polymerase is attached and transcribing the DNA.
*
* @author John Blanco
* @author Aadi... | * @param {number} targetAmount
*/
constructor( xPos, targetAmount ) {
this.xPos = xPos; // @private - x Position in model space
this.targetAmount = targetAmount; // @private
this.amount = 0;// @private - Actual amount of separation. Starts at 0 and is generally grown over time toward target.
}
... | * @param {number} xPos - X Position in model space where this separation should exist. | random_line_split |
DnaSeparation.js | // Copyright 2015-2020, University of Colorado Boulder
/**
* Class that defines a separation of the DNA strand. This is used when forcing the DNA strand to separate in certain
* positions, which happens, for instance, when RNA polymerase is attached and transcribing the DNA.
*
* @author John Blanco
* @author Aadi... |
}
geneExpressionEssentials.register( 'DnaSeparation', DnaSeparation );
export default DnaSeparation;
| {
this.amount = this.targetAmount * proportion;
} | identifier_body |
DnaSeparation.js | // Copyright 2015-2020, University of Colorado Boulder
/**
* Class that defines a separation of the DNA strand. This is used when forcing the DNA strand to separate in certain
* positions, which happens, for instance, when RNA polymerase is attached and transcribing the DNA.
*
* @author John Blanco
* @author Aadi... | ( xPos ) {
this.xPos = xPos;
}
/**
* @returns {number}
* @public
*/
getAmount() {
return this.amount;
}
/**
* @param {number} proportion
* @public
*/
setProportionOfTargetAmount( proportion ) {
this.amount = this.targetAmount * proportion;
}
}
geneExpressionEssentials.regi... | setXPosition | identifier_name |
ESP32.py | #!/bin/false
# This file is part of Espruino, a JavaScript interpreter for Microcontrollers
#
# Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
#
# 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 h... |
pinutils.findpin(pins, "PD25", True)["functions"]["DAC_OUT1"]=0;
pinutils.findpin(pins, "PD26", True)["functions"]["DAC_OUT2"]=0;
pinutils.findpin(pins, "PD0", True)["functions"]["LED_1"]=0;
pinutils.findpin(pins, "PD10", True)["functions"]["USART0_TX"]=0;
pinutils.findpin(pins, "PD16", True)["functions"]... | pins = pinutils.generate_pins(0,39) # 40 General Purpose I/O Pins.
pinutils.findpin(pins, "PD36", True)["functions"]["ADC1_IN0"]=0;
pinutils.findpin(pins, "PD37", True)["functions"]["ADC1_IN1"]=0;
pinutils.findpin(pins, "PD38", True)["functions"]["ADC1_IN2"]=0;
pinutils.findpin(pins, "PD39", True)["functions"]... | identifier_body |
ESP32.py | #!/bin/false
# This file is part of Espruino, a JavaScript interpreter for Microcontrollers
#
# Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
#
# 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 h... | 'family' : "ESP32",
'package' : "",
'ram' : 512,
'flash' : 0,
'speed' : 160,
'usart' : 3,
'spi' : 2,
'i2c' : 2,
'adc' : 1,
'dac' : 0,
'saved_code' : {
'address' : 0x100000,
'page_size' : 4096,
'pages' : 16,
'flash_available' : 960, # firmware can be up to... |
chip = {
'part' : "ESP32", | random_line_split |
ESP32.py | #!/bin/false
# This file is part of Espruino, a JavaScript interpreter for Microcontrollers
#
# Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
#
# 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 h... | ():
# { "name":"PD20", "sortingname":"D20", "port":"D", "num":"30", "functions":{ "I2C1_SDA":0 }, "csv":{} },
# pins = pinutils.generate_pins(0,5);
##6-11 are used by Flash chip
# pins.extend(pinutils.generate_pins(12,23));
# pins.extend(pinutils.generate_pins(25,27));
##32-33 are routed to rtc for xtal
# pins... | get_pins | identifier_name |
airports.actions.ts | import {Action} from "@ngrx/store";
import {AirportListResource} from "../../api/airports/airport-list.resource";
import {SortOrder} from "../../../../shared/enums/sort-order.enum";
// Initialize Actions
export const INITIALIZE_AIRPORT_SLICE = "INITIALIZE_AIRPORT_SLICE";
// Customer List Actions
export const CHANGE_A... | export class RequestAirportsFailedAction implements Action {
type = REQUEST_AIRPORTS_FAILED;
constructor() {
}
} | random_line_split | |
airports.actions.ts | import {Action} from "@ngrx/store";
import {AirportListResource} from "../../api/airports/airport-list.resource";
import {SortOrder} from "../../../../shared/enums/sort-order.enum";
// Initialize Actions
export const INITIALIZE_AIRPORT_SLICE = "INITIALIZE_AIRPORT_SLICE";
// Customer List Actions
export const CHANGE_A... | implements Action {
type = CHANGE_AIRPORTS_SORTING;
constructor(public payload: { sortBy: string, sortOrder: SortOrder }) {
}
}
export class RequestAirportsAction implements Action {
type = REQUEST_AIRPORTS;
constructor() {
}
}
export class RequestAirportsSuccessfulAction implements Action ... | ChangeAirportsSortingAction | identifier_name |
AsyncRequest.js | //
// Jala Project [http://opensvn.csie.org/traccgi/jala]
//
// Copyright 2004 ORF Online und Teletext GmbH
//
// 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.or... |
thread = (new java.lang.Thread(new java.lang.Runnable({"run": runner})));
thread.start();
return;
};
/**
* Starts this asynchronous request.
* @deprecated Use {@link #run} instead
*/
this.evaluate = function() {
this.run.apply(this, arguments);
return;
};
/**
... | {
// convert arguments object into array
args = Array.prototype.slice.call(arguments, 0, arguments.length);
} | conditional_block |
AsyncRequest.js | //
// Jala Project [http://opensvn.csie.org/traccgi/jala]
//
// Copyright 2004 ORF Online und Teletext GmbH
//
// 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.or... | * Contains the number of milliseconds to wait before starting
* the asynchronous request.
* @type Number
* @private
*/
var delay;
/**
* Run method necessary to implement java.lang.Runnable.
* @private
*/
var runner = function() {
// evaluator that will handle the request
... | random_line_split | |
utils.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may n... |
class IllegalArgumentException(CapturedException):
"""
Passed an illegal or inappropriate argument.
"""
class StreamingQueryException(CapturedException):
"""
Exception that stopped a :class:`StreamingQuery`.
"""
class QueryExecutionException(CapturedException):
"""
... | """
Failed to parse a SQL command.
""" | identifier_body |
utils.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may n... | ():
"""
Hook an exception handler into Py4j, which could capture some SQL exceptions in Java.
When calling Java API, it will call `get_return_value` to parse the returned object.
If any exception happened in JVM, the result will be Java exception object, it raise
py4j.protocol.Py4JJavaError. ... | install_exception_handler | identifier_name |
utils.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may n... |
raise
return deco
def install_exception_handler():
"""
Hook an exception handler into Py4j, which could capture some SQL exceptions in Java.
When calling Java API, it will call `get_return_value` to parse the returned object.
If any exception happened in JVM, the result wil... | raise IllegalArgumentException(s.split(': ', 1)[1], stackTrace) | conditional_block |
utils.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may n... | """
Exception that stopped a :class:`StreamingQuery`.
"""
class QueryExecutionException(CapturedException):
"""
Failed to execute a query.
"""
def capture_sql_exception(f):
def deco(*a, **kw):
try:
return f(*a, **kw)
except py4j.protocol.Py4JJav... | random_line_split | |
fixtures.ts | import { IKoaMiddleware } from "oly-http";
import { array, build, field } from "oly-json";
import { body } from "../src/core/decorators/body";
import { del } from "../src/core/decorators/del";
import { get } from "../src/core/decorators/get";
import { header } from "../src/core/decorators/header";
import { param } from... | }) f: SubData[];
}
@router("/")
export class A1 {
@get("/") get = () => "OK";
@post("/") post = () => "OKpost";
@put("/") put = () => "OKput";
@del("/") del = () => "OKdel";
}
export class A2 {
@get("/query")
query(@query() a: string = "default") {
return {a};
}
@get("/query/list")
queryList(... | random_line_split | |
fixtures.ts | import { IKoaMiddleware } from "oly-http";
import { array, build, field } from "oly-json";
import { body } from "../src/core/decorators/body";
import { del } from "../src/core/decorators/del";
import { get } from "../src/core/decorators/get";
import { header } from "../src/core/decorators/header";
import { param } from... | (@build @body() a: Data) {
return {a};
}
@post("/upload")
upload(@body() a: IUploadedFile) {
return {a};
}
}
@router("/a3")
export class A3 {
@get("/")
@use(dummyMiddleware)
inc() {
return {};
}
}
export class A4 {
@get("/error/raw")
error() {
throw new Error("BOOM");
}
}
| bodyParse | identifier_name |
52d93745fa71_index_muted_until_column_for_use_in_.py | """Index muted_until column for use in filters
Revision ID: 52d93745fa71
Revises: dc0db050f230
Create Date: 2018-12-13 13:53:58.895770
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '52d93745fa71'
down_revision = 'dc0db050f230'
branch_labels = None
depends_on ... | ():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_mute_users_muted_until'), table_name='mute_users')
# ### end Alembic commands ###
| downgrade | identifier_name |
52d93745fa71_index_muted_until_column_for_use_in_.py | """Index muted_until column for use in filters
Revision ID: 52d93745fa71
Revises: dc0db050f230
Create Date: 2018-12-13 13:53:58.895770
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '52d93745fa71'
down_revision = 'dc0db050f230'
branch_labels = None
depends_on ... | # ### end Alembic commands ### | random_line_split | |
52d93745fa71_index_muted_until_column_for_use_in_.py | """Index muted_until column for use in filters
Revision ID: 52d93745fa71
Revises: dc0db050f230
Create Date: 2018-12-13 13:53:58.895770
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '52d93745fa71'
down_revision = 'dc0db050f230'
branch_labels = None
depends_on ... | op.drop_index(op.f('ix_mute_users_muted_until'), table_name='mute_users')
# ### end Alembic commands ### | identifier_body | |
normalisation-rule-store.ts | import WorkspaceAdaptor from './adaptors/workspace';
import {LoadedNormalisationRule, SavedNormalisationRule} from './types/normalisation-rule';
const isEqual = require('lodash.isequal');
const omit = require('lodash.omit');
const clone = (value: any) => JSON.parse(JSON.stringify(value));
export default class Normali... |
get hasActiveRules(): boolean {
return this.activeRules.length > 0;
}
specifyActiveRules(ruleIndices: number[]): void {
this.rules = this.rules!.map((rule, index) =>
Object.assign({}, rule, {active: ruleIndices.includes(index)})
);
}
}
| {
return this.getAllRules().filter(rule => rule.active);
} | identifier_body |
normalisation-rule-store.ts | import WorkspaceAdaptor from './adaptors/workspace';
import {LoadedNormalisationRule, SavedNormalisationRule} from './types/normalisation-rule';
const isEqual = require('lodash.isequal');
const omit = require('lodash.omit');
const clone = (value: any) => JSON.parse(JSON.stringify(value));
export default class Normali... | (): LoadedNormalisationRule[] {
const newBaseRules = this.workspace.get<SavedNormalisationRule[]>('preComparisonTextNormalizationRules');
if (!isEqual(newBaseRules, this.baseRules)) {
this.setupRules(newBaseRules);
}
return this.rules!;
}
get activeRules(): LoadedNor... | getAllRules | identifier_name |
normalisation-rule-store.ts | import WorkspaceAdaptor from './adaptors/workspace';
import {LoadedNormalisationRule, SavedNormalisationRule} from './types/normalisation-rule';
const isEqual = require('lodash.isequal');
const omit = require('lodash.omit');
const clone = (value: any) => JSON.parse(JSON.stringify(value));
export default class Normali... |
return this.rules!;
}
get activeRules(): LoadedNormalisationRule[] {
return this.getAllRules().filter(rule => rule.active);
}
get hasActiveRules(): boolean {
return this.activeRules.length > 0;
}
specifyActiveRules(ruleIndices: number[]): void {
this.rules = t... | {
this.setupRules(newBaseRules);
} | conditional_block |
normalisation-rule-store.ts | import WorkspaceAdaptor from './adaptors/workspace';
import {LoadedNormalisationRule, SavedNormalisationRule} from './types/normalisation-rule';
const isEqual = require('lodash.isequal');
const omit = require('lodash.omit');
const clone = (value: any) => JSON.parse(JSON.stringify(value));
export default class Normali... | } | } | random_line_split |
position.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/. */
//! CSS handling for the computed value of
//! [`position`][position]s
//!
//! [position]: https://drafts.csswg.or... | <W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
try!(self.horizontal.to_css(dest));
try!(dest.write_str(" "));
try!(self.vertical.to_css(dest));
Ok(())
}
}
| to_css | identifier_name |
position.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/. */
//! CSS handling for the computed value of
//! [`position`][position]s
//!
//! [position]: https://drafts.csswg.or... | #[derive(Debug, Clone, PartialEq, Copy)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct Position {
pub horizontal: LengthOrPercentage,
pub vertical: LengthOrPercentage,
}
impl ToCss for Position {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
try!(self.horizo... | random_line_split | |
wfs.py | * name : str - the feature type name. this is what goes in the featureTypes parameter on a GetFeature request.
#: * title : str - the human readable name for this feature type
#: * abstract : str - a short description of this feature type, if necessary
#: * keywords : list(str) - keywords associated wi... |
def get_features(self, request, parms):
if parms.cleaned_data['stored_query_id']:
squid = "SQ_" + parms.cleaned_data['stored_query_id']
try:
return self.__getattribute__(squid)(request, parms)
except AttributeError:
raise OperationNotSup... | namespace = request.build_absolute_uri().split('?')[0] + "/schema" # todo: include https://bitbucket.org/eegg/django-model-schemas/wiki/Home
for model in self.models.values():
if model.objects.count() > 0:
extent = model.objects.extent()
else:
extent = (0... | identifier_body |
wfs.py | JSON")
def AdHocQuery(self, request, parms):
type_names = parms.cleaned_data['type_names'] # only support one type-name at a time (model) for now
#aliases = parms.cleaned_data['aliases'] # ignored for now
flt = parms.cleaned_data['filter'] # filter should be in JSON
flt_lang = par... | connection_string += " user='{user}'".format(user=db_params['USER']) | conditional_block | |
wfs.py | (RequestForm):
feature_id = f.CharField()
@classmethod
def from_request(cls, request):
request['feature_id'] = request.get('id')
class ResolveParameters(RequestForm):
resolve = f.CharField(required=False)
resolve_depth = f.IntegerField()
resolve_timeout = f.FloatField()
@classmeth... | GetFeatureByIdParameters | identifier_name | |
wfs.py | ()
parameters = tuple([adapt(p) for p in parameters])
query = query % parameters
# Connect to PostGIS with OGR.
drv = ogr.GetDriverByName("PostgreSQL")
connection_string = "PG:dbname='{db}'".format(db=db_params['NAME'])
if ... | 'feature_types' : self.adapter.get_feature_descriptions(request)
}) | random_line_split | |
app.py | # -*- coding: utf-8 -*-
"""
frest - flask restful api frame
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This project is the frame of the restful api server created with flask.
:copyright: (C) 2017 h4wldev@gmail.com
:license: MIT, see LICENSE for more details.
"""
import os
from flask_script import Server, Ma... |
manager.run()
| manager.add_command('runserver', Server(host='0.0.0.0', port=port, use_debugger=True)) | conditional_block |
app.py | # -*- coding: utf-8 -*-
"""
frest - flask restful api frame
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This project is the frame of the restful api server created with flask.
:copyright: (C) 2017 h4wldev@gmail.com
:license: MIT, see LICENSE for more details. | import os
from flask_script import Server, Manager
from flask_migrate import Migrate, MigrateCommand
from app import app, db, routes, handler
from app.config import APP_DEFAULT_PORT, APP_SECRET_KEY, ENVIRONMENT
from app.modules.auth import login, token
if __name__ == '__main__':
port = int(os.environ.get('PORT'... | """ | random_line_split |
__init__.py | """Treadmill Kafka API"""
import fnmatch
import logging
import os
import re
import socket
from .. import admin as tadmin
from .. import context
from .. import dnsutils
from .. import discovery
from .. import fs
from .. import zkutils
_LOGGER = logging.getLogger(__name__)
KAFKA_ZK_ROOT = 'kafka'
DEFAULT_KAFKA_DIR =... | (cell, domain):
"""Get the masker Kafka brokers
:param cell: a cell
:type cell: str
:param broker_id: a specific broker id, else, all brokers are returned
:type broker_id: int
:returns: a list of host:ports
"""
label = '_kafka._tcp.{0}.{1}'.format(cell, domain)
return ['{0}:{1}'.f... | get_master_brokers | identifier_name |
__init__.py | """Treadmill Kafka API"""
import fnmatch
import logging
import os
import re
import socket
from .. import admin as tadmin
from .. import context
from .. import dnsutils
from .. import discovery
from .. import fs
from .. import zkutils
_LOGGER = logging.getLogger(__name__)
KAFKA_ZK_ROOT = 'kafka'
DEFAULT_KAFKA_DIR =... |
else:
endpoints = app_discovery.get_endpoints()
return endpoints
def _is_broker_up(hostport):
"""Test whether a broker is up"""
try:
host, port = hostport.split(':')
timeout = 3
socket.create_connection((host, port), timeout)
return True
except socket.erro... | endpoints = app_discovery.get_endpoints_zk(watch_cb=watcher_cb) | conditional_block |
__init__.py | """Treadmill Kafka API"""
import fnmatch
import logging
import os
import re
import socket
from .. import admin as tadmin
from .. import context
from .. import dnsutils
from .. import discovery
from .. import fs
from .. import zkutils
_LOGGER = logging.getLogger(__name__)
KAFKA_ZK_ROOT = 'kafka'
DEFAULT_KAFKA_DIR =... | endpoint=DEFAULT_BROKER_ENDPOINT_NAME,
watcher_cb=None):
"""Get the Kafka broker host and ports for the supplied cell
:param cellname: a cell
:type cellname: str
:param domain: Treadmill DNS domain
:type domain: str
:param zkclient: a ZZookeeper client
:typ... | pass
return False
def get_brokers(cellname, domain, zkclient, app_pattern=None, | random_line_split |
__init__.py | """Treadmill Kafka API"""
import fnmatch
import logging
import os
import re
import socket
from .. import admin as tadmin
from .. import context
from .. import dnsutils
from .. import discovery
from .. import fs
from .. import zkutils
_LOGGER = logging.getLogger(__name__)
KAFKA_ZK_ROOT = 'kafka'
DEFAULT_KAFKA_DIR =... |
def data_dir(kafka_dir=DEFAULT_KAFKA_DIR):
"""Get the Kafka data directory
:param kafka_dir: an optional Kafka directory, default is
kafka.DEFAULT_KAFKA_DIR
:type kafka_dir: string
"""
return os.path.join(kafka_dir, 'data')
def zk_instances_by_zkurl(zkurl, zkroot=KAFKA_ZK_ROOT):
""... | """Get Kafka log file, full path.
:param kafka_dir: an optional Kafka directory, default is
kafka.DEFAULT_KAFKA_DIR
:type kafka_dir: string
"""
return os.path.join(kafka_dir, 'log', 'kafka.log') | identifier_body |
lint-dead-code-5.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 ... | Variant5 { _x: isize }, //~ ERROR: variant is never constructed: `Variant5`
Variant6(isize), //~ ERROR: variant is never constructed: `Variant6`
_Variant7,
}
enum Enum3 { //~ ERROR: enum is never used
Variant8,
Variant9
}
fn main() {
let v = Enum1::Variant1(1);
match v {
Enum1::Var... | #[allow(dead_code)]
Variant4(isize), | random_line_split |
lint-dead-code-5.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 ... | { //~ ERROR: enum is never used
Variant8,
Variant9
}
fn main() {
let v = Enum1::Variant1(1);
match v {
Enum1::Variant1(_) => (),
Enum1::Variant2 => ()
}
let x = Enum2::Variant3(true);
}
| Enum3 | identifier_name |
the_tower_of_zot.ts | import ZoneId from '../../../../../resources/zone_id';
import { OopsyData } from '../../../../../types/data';
import { OopsyTriggerSet } from '../../../../../types/oopsy';
// TODO: Prapti Siddhi is a mistake on its own before stop
// and after stop, only a mistake for the person without stop.
// TODO: does Minduruva d... |
export default triggerSet; | 'Zot Sanduruva Prapti Siddhi': '62A8', // targeted line, sometimes with stop
},
}; | random_line_split |
space.rs | use parking_lot::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use crate::gc::arena;
use crate::gc::{Address, Region};
use crate::mem;
/// Configuration for a space.
/// This makes it possible to use `Space` both for the
/// code space and the permanent space.
pub struct SpaceConfig {
pub executable: boo... | (&self) -> Region {
self.total.clone()
}
pub fn used_region(&self) -> Region {
let start = self.total.start;
let end = self.top.load(Ordering::Relaxed).into();
Region::new(start, end)
}
}
| total | identifier_name |
space.rs | use parking_lot::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use crate::gc::arena;
use crate::gc::{Address, Region};
use crate::mem;
/// Configuration for a space.
/// This makes it possible to use `Space` both for the
/// code space and the permanent space.
pub struct SpaceConfig {
pub executable: boo... |
let size = size - (end - top);
let size = mem::align_usize(size, self.config.chunk);
let new_end = end + size;
if new_end <= self.total.end.to_usize() {
arena::commit(end.into(), size, self.config.executable);
self.end.store(new_end, Ordering::SeqCst);
... | {
return true;
} | conditional_block |
space.rs | use parking_lot::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use crate::gc::arena;
use crate::gc::{Address, Region};
use crate::mem;
/// Configuration for a space.
/// This makes it possible to use `Space` both for the
/// code space and the permanent space.
pub struct SpaceConfig {
pub executable: boo... | Space {
name,
config,
total: Region::new(space_start, space_end),
top: AtomicUsize::new(space_start.to_usize()),
end: AtomicUsize::new(end.to_usize()),
allocate: Mutex::new(()),
}
}
/// allocate memory in this space. This... |
arena::commit(space_start, config.chunk, config.executable);
let end = space_start.offset(config.chunk);
| random_line_split |
bpm-utils.js | } else {
// ?!?
_raw_log = function() {};
}
function _wrap_logger(cname, prefix, level) {
var cfunc;
if(_console && _console[cname]) {
cfunc = _console[cname].bind(_console);
} else {
cfunc = _raw_log;
}
return function() {
var args = Array.prototype.slice.call(argum... | _gm_log(msg);
}; | random_line_split | |
bpm-utils.js | = _console[cname].bind(_console);
} else {
cfunc = _raw_log;
}
return function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(prefix);
if(window.name) {
args.unshift("[" + window.name + "]:");
}
_log_buffer.push(args.join(" "))... | // FIXME: For some reason observe(document.body, [...]) doesn't work
// on Firefox. It just throws an exception. document works.
observer.observe(document, {"childList": true, "subtree": true});
return;
} catch(e) {
// Failed with whatever the error of the week is
log... | {
if(!MutationObserver) {
// Crash and burn. No fallbacks due to not wanting to deal with AMO
// right now.
log_error("MutationObserver not found!");
return;
}
var observer = new MutationObserver(catch_errors(function(mutations, observer) {
for(var m = 0; m < mutatio... | identifier_body |
bpm-utils.js | = _console[cname].bind(_console);
} else {
cfunc = _raw_log;
}
return function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(prefix);
if(window.name) {
args.unshift("[" + window.name + "]:");
}
_log_buffer.push(args.join(" "))... |
while(!node.nextSibling) {
node = node.parentNode;
depth--;
if(!depth) {
end();
return; // Done!
}
}
node = node.nextSibling;
}
if(num) {
// Ran out of nodes, or hit null somehow. I'm not sure how ei... | {
// Only process valid nodes.
if(node.nodeType === node_filter) {
process(node);
}
// Descend (but never into blacklisted tags).
if(node.hasChildNodes()) {
node = node.firstChild;
depth++;
contin... | conditional_block |
bpm-utils.js | = _console[cname].bind(_console);
} else {
cfunc = _raw_log;
}
return function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(prefix);
if(window.name) {
args.unshift("[" + window.name + "]:");
}
_log_buffer.push(args.join(" "))... | (element, start_callback, callback) {
var start_x, start_y;
var on_mouse_move = catch_errors(function(event) {
var dx = event.clientX - start_x;
var dy = event.clientY - start_y;
callback(event, dx, dy);
});
element.addEventListener("mousedown", catch_errors(function(event) {
... | enable_drag | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.