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 |
|---|---|---|---|---|
test_clusters_acceptance.py | from __future__ import division
from math import sqrt, pi
import unittest
from sapphire import clusters
class SimpleClusterTest(unittest.TestCase):
def setUp(self):
self.cluster = clusters.SimpleCluster(size=100)
def test_station_positions_and_angles(self):
a = sqrt(100 ** 2 - 50 ** 2)
... | (self):
for station in self.cluster.stations:
for detector in station.detectors:
detector.get_xy_coordinates()
def assert_tuple_almost_equal(self, actual, expected):
self.assertIsInstance(actual, tuple)
self.assertIsInstance(expected, tuple)
msg = "Tuple... | test_get_detector_coordinates | identifier_name |
test_clusters_acceptance.py | from __future__ import division
from math import sqrt, pi
import unittest
from sapphire import clusters
class SimpleClusterTest(unittest.TestCase):
def setUp(self):
self.cluster = clusters.SimpleCluster(size=100)
def test_station_positions_and_angles(self):
a = sqrt(100 ** 2 - 50 ** 2) | for actual_value, expected_value in zip(actual, expected):
self.assert_tuple_almost_equal(actual_value, expected_value)
def test_get_detector_coordinates(self):
for station in self.cluster.stations:
for detector in station.detectors:
detector.get_xy_coordinat... | expected = [(0, 2 * a / 3, 0, 0), (0, 0, 0, 0),
(-50, -a / 3, 0, 2 * pi / 3), (50, -a / 3, 0, -2 * pi / 3)]
actual = [(station.x[0], station.y[0], station.z[0], station.angle[0])
for station in self.cluster.stations]
| random_line_split |
test_clusters_acceptance.py | from __future__ import division
from math import sqrt, pi
import unittest
from sapphire import clusters
class SimpleClusterTest(unittest.TestCase):
def setUp(self):
self.cluster = clusters.SimpleCluster(size=100)
def test_station_positions_and_angles(self):
a = sqrt(100 ** 2 - 50 ** 2)
... |
if __name__ == '__main__':
unittest.main()
| self.assertAlmostEqual(actual_value, expected_value, msg=msg) | conditional_block |
server.py | # -*- coding: utf-8 -*-
"""
"""
from datetime import datetime, timedelta
import os
from flask import request
from flask import Flask
import pytz
import db
from utils import get_remote_addr, get_location_data
app = Flask(__name__)
@app.route('/yo-water/', methods=['POST', 'GET'])
def yowater():
payload = re... | user_data.update({'timezone': data.get('time_zone')})
db.reminders.insert(user_data)
return 'OK'
else:
reply_text = reply_object.get('text')
if reply_text == u'Can\'t right now 😖':
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(... |
if data.get('time_zone'): | random_line_split |
server.py | # -*- coding: utf-8 -*-
"""
"""
from datetime import datetime, timedelta
import os
from flask import request
from flask import Flask
import pytz
import db
from utils import get_remote_addr, get_location_data
app = Flask(__name__)
@app.route('/yo-water/', methods=['POST', 'GET'])
def yowater():
| user_data.update({'timezone': data.get('time_zone')})
db.reminders.insert(user_data)
return 'OK'
else:
reply_text = reply_object.get('text')
if reply_text == u'Can\'t right now 😖':
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(... | payload = request.args if request.args else request.get_json(force=True)
username = payload.get('username')
reminder = db.reminders.find_one({'username': username})
reply_object = payload.get('reply')
if reply_object is None:
if db.reminders.find_one({'username': username}) is None:
... | identifier_body |
server.py | # -*- coding: utf-8 -*-
"""
"""
from datetime import datetime, timedelta
import os
from flask import request
from flask import Flask
import pytz
import db
from utils import get_remote_addr, get_location_data
app = Flask(__name__)
@app.route('/yo-water/', methods=['POST', 'GET'])
def yowater():
payload = re... |
if __name__ == "__main__":
app.debug = True
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "5000")))
| reply_text = reply_object.get('text')
if reply_text == u'Can\'t right now 😖':
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=15)
else:
reminder['step'] += 1
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=60)
re... | conditional_block |
server.py | # -*- coding: utf-8 -*-
"""
"""
from datetime import datetime, timedelta
import os
from flask import request
from flask import Flask
import pytz
import db
from utils import get_remote_addr, get_location_data
app = Flask(__name__)
@app.route('/yo-water/', methods=['POST', 'GET'])
def | ():
payload = request.args if request.args else request.get_json(force=True)
username = payload.get('username')
reminder = db.reminders.find_one({'username': username})
reply_object = payload.get('reply')
if reply_object is None:
if db.reminders.find_one({'username': username}) is None:... | yowater | identifier_name |
Linux.py | @" + guestaddr + ":" + destination],
printfn=self.log.debug)
def _customize_files(self, guestaddr):
"""
Method to upload the custom files specified in the TDL to the guest.
"""
self.log.info("Uploading custom files")
for name,... | """
Method to customize the operating system after installation.
"""
return self._internal_customize(libvirt_xml, "mod_only") | identifier_body | |
Linux.py | This check
makes sure that we allow an additional 30 seconds (1 second per ssh
attempt) for sshd to finish initializing.
"""
count = 30
success = False
while count > 0:
try:
self.log.debug("Testing ssh connection, try %d", count)
... | (self, guestaddr):
"""
Method to customize by installing additional packages and files.
"""
if not self.tdl.packages and not self.tdl.files and not self.tdl.commands:
# no work to do, just return
return
self._customize_repos(guestaddr)
for cmd in... | do_customize | identifier_name |
Linux.py | This check
makes sure that we allow an additional 30 seconds (1 second per ssh
attempt) for sshd to finish initializing.
"""
count = 30
success = False
while count > 0:
try:
self.log.debug("Testing ssh connection, try %d", count)
... |
self._customize_files(guestaddr)
self.log.debug("Running custom commands")
for cmd in self.tdl.commands:
self.guest_execute_command(guestaddr, cmd.read())
self.log.debug("Removing non-persisted repos")
self._remove_repos(guestaddr)
self.log.debug("Syncing... | self._install_packages(guestaddr, packstr) | conditional_block |
Linux.py | This check
makes sure that we allow an additional 30 seconds (1 second per ssh
attempt) for sshd to finish initializing.
"""
count = 30
success = False
while count > 0:
try:
self.log.debug("Testing ssh connection, try %d", count)
... | packstr += '"' + package.name + '" '
if packstr != '':
self._install_packages(guestaddr, packstr)
self._customize_files(guestaddr)
self.log.debug("Running custom commands")
for cmd in self.tdl.commands:
self.guest_execute_command(guestaddr, cmd.read... | random_line_split | |
outputServices.ts | /panelService';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { OutputLinkProvider } from 'vs/workbench/parts/output/common/outputLinkProvider';
import { ITextModelService, ITextModelContentProvider } fro... | export class OutputService implements IOutputService {
public _serviceBrand: any;
private receivedOutput: Map<string, BufferedContent> = new Map<string, BufferedContent>();
private channels: Map<string, IOutputChannel> = new Map<string, IOutputChannel>();
private activeChannelId: string;
private _onOutput: Emi... | random_line_split | |
outputServices.ts | panelService';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { OutputLinkProvider } from 'vs/workbench/parts/output/common/outputLinkProvider';
import { ITextModelService, ITextModelContentProvider } from... |
while (this.length > MAX_OUTPUT_LENGTH) {
this.dataIds.shift();
const removed = this.data.shift();
this.length -= removed.length;
}
}
public getDelta(previousDelta?: IOutputDelta): IOutputDelta {
let idx = -1;
if (previousDelta) {
idx = binarySearch(this.dataIds, previousDelta.id, (a, b) => a -... | {
return;
} | conditional_block |
outputServices.ts | panelService';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { OutputLinkProvider } from 'vs/workbench/parts/output/common/outputLinkProvider';
import { ITextModelService, ITextModelContentProvider } from... |
private getOutput(channelId: string, previousDelta: IOutputDelta): IOutputDelta {
if (this.receivedOutput.has(channelId)) {
return this.receivedOutput.get(channelId).getDelta(previousDelta);
}
return undefined;
}
private clearOutput(channelId: string): void {
if (this.receivedOutput.has(channelId)) {
... | {
return this.getChannel(this.activeChannelId);
} | identifier_body |
outputServices.ts | /panelService';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { OutputLinkProvider } from 'vs/workbench/parts/output/common/outputLinkProvider';
import { ITextModelService, ITextModelContentProvider } fro... | (): IOutputChannelIdentifier[] {
return Registry.as<IOutputChannelRegistry>(Extensions.OutputChannels).getChannels();
}
private append(channelId: string, output: string): void {
// Initialize
if (!this.receivedOutput.has(channelId)) {
this.receivedOutput.set(channelId, new BufferedContent());
this._onO... | getChannels | identifier_name |
mod.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | // You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
pub mod editor;
pub mod plain;
pub mod stdout; | // This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// | random_line_split |
mutex.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 ... | }
#[inline]
pub unsafe fn try_lock(&self) -> bool {
ffi::TryEnterCriticalSection(self.inner.get()) != 0
}
pub unsafe fn unlock(&self) {
ffi::LeaveCriticalSection(self.inner.get());
}
pub unsafe fn destroy(&self) {
ffi::DeleteCriticalSection(self.inner.get());
}... |
pub unsafe fn lock(&self) {
ffi::EnterCriticalSection(self.inner.get()); | random_line_split |
mutex.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 ... | (&self) {
ffi::AcquireSRWLockExclusive(self.inner.get())
}
#[inline]
pub unsafe fn try_lock(&self) -> bool {
ffi::TryAcquireSRWLockExclusive(self.inner.get()) != 0
}
#[inline]
pub unsafe fn unlock(&self) {
ffi::ReleaseSRWLockExclusive(self.inner.get())
}
#[inline]... | lock | identifier_name |
mutex.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 ... |
#[inline]
pub unsafe fn unlock(&self) {
ffi::ReleaseSRWLockExclusive(self.inner.get())
}
#[inline]
pub unsafe fn destroy(&self) {
// ...
}
}
pub struct ReentrantMutex { inner: Box<UnsafeCell<ffi::CRITICAL_SECTION>> }
unsafe impl Send for ReentrantMutex {}
unsafe impl Sync for ... | {
ffi::TryAcquireSRWLockExclusive(self.inner.get()) != 0
} | identifier_body |
action_noise.py | # Copyright 2018 The dm_control Authors.
#
# 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 i... | (self, action):
noisy_action = action + self._env.task.random.normal(scale=self._noise_std)
# Clip the noisy actions in place so that they fall within the bounds
# specified by the `action_spec`. Note that MuJoCo implicitly clips out-of-
# bounds control inputs, but we also clip here in case the actions... | step | identifier_name |
action_noise.py | # Copyright 2018 The dm_control Authors.
#
# 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 i... |
def action_spec(self):
return self._env.action_spec()
def __getattr__(self, name):
return getattr(self._env, name)
| return self._env.observation_spec() | identifier_body |
action_noise.py | # Copyright 2018 The dm_control Authors.
#
# 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 i... | def action_spec(self):
return self._env.action_spec()
def __getattr__(self, name):
return getattr(self._env, name) | return self._env.observation_spec()
| random_line_split |
action_noise.py | # Copyright 2018 The dm_control Authors.
#
# 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 i... |
self._minimum = action_spec.minimum
self._maximum = action_spec.maximum
self._noise_std = scale * (action_spec.maximum - action_spec.minimum)
self._env = env
def step(self, action):
noisy_action = action + self._env.task.random.normal(scale=self._noise_std)
# Clip the noisy actions in place ... | raise ValueError(_BOUNDS_MUST_BE_FINITE.format(action_spec=action_spec)) | conditional_block |
single_glyph.rs | extern crate freetype as ft;
extern crate unicode_normalization;
use unicode_normalization::UnicodeNormalization;
const WIDTH: usize = 32;
const HEIGHT: usize = 24;
fn | (bitmap: ft::Bitmap, x: usize, y: usize) -> [[u8; WIDTH]; HEIGHT] {
let mut figure = [[0; WIDTH]; HEIGHT];
let mut p = 0;
let mut q = 0;
let w = bitmap.width() as usize;
let x_max = x + w;
let y_max = y + bitmap.rows() as usize;
for i in x .. x_max {
for j in y .. y_max {
... | draw_bitmap | identifier_name |
single_glyph.rs | extern crate freetype as ft;
extern crate unicode_normalization;
use unicode_normalization::UnicodeNormalization;
const WIDTH: usize = 32;
const HEIGHT: usize = 24;
fn draw_bitmap(bitmap: ft::Bitmap, x: usize, y: usize) -> [[u8; WIDTH]; HEIGHT] |
fn main() {
let ref mut args = std::env::args();
if args.len() != 3 {
let exe = args.next().unwrap();
println!("Usage: {} font character", exe);
return
}
let ref font = args.nth(1).unwrap();
let character = args.next().and_then(|s| s.nfc().next()).unwrap() as usize;
l... | {
let mut figure = [[0; WIDTH]; HEIGHT];
let mut p = 0;
let mut q = 0;
let w = bitmap.width() as usize;
let x_max = x + w;
let y_max = y + bitmap.rows() as usize;
for i in x .. x_max {
for j in y .. y_max {
if i < WIDTH && j < HEIGHT {
figure[j][i] |= bit... | identifier_body |
single_glyph.rs | extern crate freetype as ft;
extern crate unicode_normalization;
use unicode_normalization::UnicodeNormalization;
const WIDTH: usize = 32;
const HEIGHT: usize = 24;
fn draw_bitmap(bitmap: ft::Bitmap, x: usize, y: usize) -> [[u8; WIDTH]; HEIGHT] {
let mut figure = [[0; WIDTH]; HEIGHT];
let mut p = 0;
let ... | for i in 0 .. HEIGHT {
for j in 0 .. WIDTH {
print!("{}",
match figure[i][j] {
p if p == 0 => " ",
p if p < 128 => "*",
_ => "+"
}
);
}
println!("");
}
} | let glyph = face.glyph();
let x = glyph.bitmap_left() as usize;
let y = HEIGHT - glyph.bitmap_top() as usize;
let figure = draw_bitmap(glyph.bitmap(), x, y);
| random_line_split |
single_glyph.rs | extern crate freetype as ft;
extern crate unicode_normalization;
use unicode_normalization::UnicodeNormalization;
const WIDTH: usize = 32;
const HEIGHT: usize = 24;
fn draw_bitmap(bitmap: ft::Bitmap, x: usize, y: usize) -> [[u8; WIDTH]; HEIGHT] {
let mut figure = [[0; WIDTH]; HEIGHT];
let mut p = 0;
let ... |
}
q = 0;
p += 1;
}
figure
}
fn main() {
let ref mut args = std::env::args();
if args.len() != 3 {
let exe = args.next().unwrap();
println!("Usage: {} font character", exe);
return
}
let ref font = args.nth(1).unwrap();
let character = args.... | {
figure[j][i] |= bitmap.buffer()[q * w + p];
q += 1;
} | conditional_block |
process_builder.rs | use std::collections::HashMap;
use std::ffi::CString;
use std::fmt::{self, Formatter};
use std::io::process::{Command, ProcessOutput, InheritFd};
use std::os;
use std::path::BytesContainer;
use util::{CargoResult, ProcessError, process_error};
#[derive(Clone, PartialEq, Show)]
pub struct ProcessBuilder {
program:... | <T: BytesContainer>(mut self, arguments: &[T]) -> ProcessBuilder {
self.args.extend(arguments.iter().map(|t| {
CString::from_slice(t.container_as_bytes())
}));
self
}
pub fn get_args(&self) -> &[CString] {
self.args.as_slice()
}
pub fn cwd(mut self, path: Pa... | args | identifier_name |
process_builder.rs | use std::collections::HashMap;
use std::ffi::CString;
use std::fmt::{self, Formatter};
use std::io::process::{Command, ProcessOutput, InheritFd};
use std::os;
use std::path::BytesContainer;
use util::{CargoResult, ProcessError, process_error};
#[derive(Clone, PartialEq, Show)]
pub struct ProcessBuilder {
program:... |
pub fn args<T: BytesContainer>(mut self, arguments: &[T]) -> ProcessBuilder {
self.args.extend(arguments.iter().map(|t| {
CString::from_slice(t.container_as_bytes())
}));
self
}
pub fn get_args(&self) -> &[CString] {
self.args.as_slice()
}
pub fn cwd(m... | {
self.args.push(CString::from_slice(arg.container_as_bytes()));
self
} | identifier_body |
process_builder.rs | use std::collections::HashMap;
use std::ffi::CString;
use std::fmt::{self, Formatter};
use std::io::process::{Command, ProcessOutput, InheritFd};
use std::os;
use std::path::BytesContainer;
use util::{CargoResult, ProcessError, process_error};
#[derive(Clone, PartialEq, Show)]
pub struct ProcessBuilder {
program:... | }
program
}
}
pub fn process<T: BytesContainer>(cmd: T) -> CargoResult<ProcessBuilder> {
Ok(ProcessBuilder {
program: CString::from_slice(cmd.container_as_bytes()),
args: Vec::new(),
cwd: try!(os::getcwd()),
env: HashMap::new(),
})
} | program.push(' ');
program.push_str(&format!("{}", String::from_utf8_lossy(arg.as_bytes()))[]); | random_line_split |
inline.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 ... | (ccx: @mut CrateContext, fn_id: ast::def_id)
-> ast::def_id {
let _icx = push_ctxt("maybe_instantiate_inline");
match ccx.external.find(&fn_id) {
Some(&Some(node_id)) => {
// Already inline
debug!("maybe_instantiate_inline(%s): already inline as node id %d",
... | maybe_instantiate_inline | identifier_name |
inline.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 ... | trans_item(ccx, item);
local_def(my_id)
}
csearch::found_parent(_, _) => {
ccx.sess.bug("maybe_get_item_ast returned a found_parent \
with a non-item parent");
}
csearch::found(ast::ii_method(impl_did, is_provided, mth)) => {
ccx.sta... | non-enum parent")
} | random_line_split |
inline.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 ... | |a,b,c,d| {
astencode::decode_inlined_item(a, b, ccx.maps,
/*bad*/ copy c, d)
});
return match csearch_result {
csearch::not_found => {
ccx.external.insert(fn_id, None);
fn_id
}
cse... | {
let _icx = push_ctxt("maybe_instantiate_inline");
match ccx.external.find(&fn_id) {
Some(&Some(node_id)) => {
// Already inline
debug!("maybe_instantiate_inline(%s): already inline as node id %d",
ty::item_path_str(ccx.tcx, fn_id), node_id);
retur... | identifier_body |
func-names.js | /**
* @fileoverview Rule to warn when a function expression does not have a name.
* @author Kyle T. Nunery
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.ex... |
}
};
}
};
| {
context.report(node, "Missing function expression name.");
} | conditional_block |
func-names.js | /**
* @fileoverview Rule to warn when a function expression does not have a name.
* @author Kyle T. Nunery
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.ex... | }
}; | context.report(node, "Missing function expression name.");
}
}
}; | random_line_split |
func-names.js | /**
* @fileoverview Rule to warn when a function expression does not have a name.
* @author Kyle T. Nunery
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.ex... | () {
var parent = context.getAncestors().pop();
return (parent.type === "MethodDefinition" || (
parent.type === "Property" && (
parent.method ||
parent.kind === "get" ||
parent.kind === "set"
)
... | isObjectOrClassMethod | identifier_name |
func-names.js | /**
* @fileoverview Rule to warn when a function expression does not have a name.
* @author Kyle T. Nunery
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.ex... |
return {
FunctionExpression: function(node) {
var name = node.id && node.id.name;
if (!name && !isObjectOrClassMethod()) {
context.report(node, "Missing function expression name.");
}
}
};
}
};
| {
var parent = context.getAncestors().pop();
return (parent.type === "MethodDefinition" || (
parent.type === "Property" && (
parent.method ||
parent.kind === "get" ||
parent.kind === "set"
)
... | identifier_body |
VertexPositionTerrain.ts | import { IVertex } from "../IVertex"
import { VertexDeclaration } from "../VertexDeclaration"
import { VertexElement } from "../VertexElement"
import { VertexElementFormat } from "../VertexElementFormat"
import { Vector2 } from "../../math/Vector2"
import { Vector3 } from "../../math/Vector3"
/**
* @internal
* <code... | itionTerrain._vertexDeclaration;
}
constructor(position: Vector3, normal: Vector3, textureCoord0: Vector2, textureCoord1: Vector2) {
this._position = position;
this._normal = normal;
this._textureCoord0 = textureCoord0;
this._textureCoord1 = textureCoord1;
}
}
| return VertexPos | identifier_name |
VertexPositionTerrain.ts | import { IVertex } from "../IVertex"
import { VertexDeclaration } from "../VertexDeclaration"
import { VertexElement } from "../VertexElement"
import { VertexElementFormat } from "../VertexElementFormat"
import { Vector2 } from "../../math/Vector2"
import { Vector3 } from "../../math/Vector3"
/**
* @internal
* <code... | normal;
}
get textureCoord0(): Vector2 {
return this._textureCoord0;
}
get textureCoord1(): Vector2 {
return this._textureCoord1;
}
get vertexDeclaration(): VertexDeclaration {
return VertexPositionTerrain._vertexDeclaration;
}
constructor(position: Vector3, normal: Vector3, textureCoord0: Vector2, te... | (): Vector3 {
return this._ | identifier_body |
VertexPositionTerrain.ts | import { IVertex } from "../IVertex"
import { VertexDeclaration } from "../VertexDeclaration"
import { VertexElement } from "../VertexElement"
import { VertexElementFormat } from "../VertexElementFormat"
import { Vector2 } from "../../math/Vector2"
import { Vector3 } from "../../math/Vector3"
/**
* @internal
* <code... | static TERRAIN_NORMAL0: number = 1;
static TERRAIN_TEXTURECOORDINATE0: number = 2;
static TERRAIN_TEXTURECOORDINATE1: number = 3;
private static _vertexDeclaration: VertexDeclaration;
/**
* @internal
*/
static __init__(): void {
VertexPositionTerrain._vertexDeclaration = new VertexDeclaration(40, [new Ver... | static TERRAIN_POSITION0: number = 0; | random_line_split |
schleifen.rs | fn main() | // for-Schleife
for c in 1..6 {
println!("for: {}", c);
}
// mit enumerate() können die Durchläufe gezählt werden (bei 0 geht es los!)
for (d,e) in (10..16).enumerate() {
println!("for mit enumerate: {}, Durchlauf: {}", e, d);
}
}
| {
// Schleifen - loop, for, while
// loop (ohne Abbruch -> Endlosschleife)
// break - Abbruch der Schleife, continue - aktuellen Durchlauf abbrechen
let mut a = 0;
loop {
a = a + 1;
println!("loop: {}", a);
if a == 5 { break }
}
// while (Sobald Bedingung erfül... | identifier_body |
schleifen.rs | fn | () {
// Schleifen - loop, for, while
// loop (ohne Abbruch -> Endlosschleife)
// break - Abbruch der Schleife, continue - aktuellen Durchlauf abbrechen
let mut a = 0;
loop {
a = a + 1;
println!("loop: {}", a);
if a == 5 { break }
}
// while (Sobald Bedingung er... | main | identifier_name |
schleifen.rs | fn main() {
// Schleifen - loop, for, while
// loop (ohne Abbruch -> Endlosschleife)
// break - Abbruch der Schleife, continue - aktuellen Durchlauf abbrechen
let mut a = 0;
loop {
a = a + 1;
println!("loop: {}", a);
if a == 5 { break }
}
// while (Sobald Bedin... |
} | } | random_line_split |
schleifen.rs | fn main() {
// Schleifen - loop, for, while
// loop (ohne Abbruch -> Endlosschleife)
// break - Abbruch der Schleife, continue - aktuellen Durchlauf abbrechen
let mut a = 0;
loop {
a = a + 1;
println!("loop: {}", a);
if a == 5 |
}
// while (Sobald Bedingung erfüllt ...)
let mut b = 0;
while b != 5 {
b += 1;
println!("while: {}", b);
}
// for-Schleife
for c in 1..6 {
println!("for: {}", c);
}
// mit enumerate() können die Durchläufe gezählt werden (bei 0 geht es los!)
for ... | { break } | conditional_block |
resolver.rs | use std::sync::{Arc,Mutex};
use std::collections::HashMap;
use std::io::BufReader;
use rustls::{ResolvesServerCert, ClientHello};
use rustls::sign::{CertifiedKey, RSASigningKey};
use rustls::internal::pemfile;
use sozu_command::proxy::{CertificateAndKey, CertFingerprint, AddCertificate, RemoveCertificate};
use sozu_co... | (&mut self, remove_certificate: RemoveCertificate) {
if let Some(_data) = self.certificates.get(&remove_certificate.fingerprint) {
//let cert = &data.cert.cert[0];
if remove_certificate.names.is_empty() {
//FIXME: waiting for https://github.com/briansmith/webpki/pull/65 to merge to get the DNS n... | remove_certificate | identifier_name |
resolver.rs | use std::sync::{Arc,Mutex};
use std::collections::HashMap;
use std::io::BufReader;
use rustls::{ResolvesServerCert, ClientHello};
use rustls::sign::{CertifiedKey, RSASigningKey};
use rustls::internal::pemfile;
use sozu_command::proxy::{CertificateAndKey, CertFingerprint, AddCertificate, RemoveCertificate};
use sozu_co... |
}
error!("could not look up a certificate for server name '{}'", name);
None
}
}
pub fn generate_certified_key(certificate_and_key: CertificateAndKey) -> Option<CertifiedKey> {
let mut chain = Vec::new();
let mut cert_reader = BufReader::new(certificate_and_key.certificate.as_bytes());
let parse... | {
trace!("looking for certificate for {:?} with fingerprint {:?}", name, kv.1);
return resolver.certificates.get(&kv.1).as_ref().map(|data| data.cert.clone());
} | conditional_block |
resolver.rs | use std::sync::{Arc,Mutex};
use std::collections::HashMap;
use std::io::BufReader;
use rustls::{ResolvesServerCert, ClientHello};
use rustls::sign::{CertifiedKey, RSASigningKey};
use rustls::internal::pemfile;
use sozu_command::proxy::{CertificateAndKey, CertFingerprint, AddCertificate, RemoveCertificate};
use sozu_co... | self.certificates.insert(fingerprint.clone(), data);
for name in names.drain(..) {
self.domains.domain_insert(name.into_bytes(), fingerprint.clone());
}
Some(fingerprint)
} else {
None
}
}
pub fn remove_certificate(&mut self, remove_certificate: RemoveCertificate) {
... | cert: certified_key,
};
let fingerprint = CertFingerprint(fingerprint); | random_line_split |
resolver.rs | use std::sync::{Arc,Mutex};
use std::collections::HashMap;
use std::io::BufReader;
use rustls::{ResolvesServerCert, ClientHello};
use rustls::sign::{CertifiedKey, RSASigningKey};
use rustls::internal::pemfile;
use sozu_command::proxy::{CertificateAndKey, CertFingerprint, AddCertificate, RemoveCertificate};
use sozu_co... | }
self.certificates.remove(&remove_certificate.fingerprint);
}
}
pub struct CertificateResolverWrapper(pub Mutex<CertificateResolver>);
impl CertificateResolverWrapper {
pub fn new() -> CertificateResolverWrapper {
CertificateResolverWrapper(Mutex::new(CertificateResolver::new()))
}
pub fn add_... | {
if let Some(_data) = self.certificates.get(&remove_certificate.fingerprint) {
//let cert = &data.cert.cert[0];
if remove_certificate.names.is_empty() {
//FIXME: waiting for https://github.com/briansmith/webpki/pull/65 to merge to get the DNS names
// create a untrusted::Input
/... | identifier_body |
load_length_frequency_data.py | # -*- coding: utf-8 -*-
from api.connectors import *
from seafood.models import *
from api.imports import *
import time
import datetime
from django.utils.timezone import get_current_timezone, make_aware
def convert_date(dt):
return time.strptime(dt, "%d.%m.%Y")
def convert_date_time(dt, default=datetime.datet... | (ImportOp):
ob_ct = 0
@staticmethod
def LoadFishDataOp(line, succ):
sp, created = Species.objects.get_or_create(name=line['Species'])
vessel, created = Vessel.objects.get_or_create(name=line['Vessel'])
trip, created = Trip.objects.get_or_create(
name='Trip_' + line['Voy... | ImportFish | identifier_name |
load_length_frequency_data.py | # -*- coding: utf-8 -*-
from api.connectors import *
from seafood.models import *
from api.imports import *
import time
import datetime
from django.utils.timezone import get_current_timezone, make_aware
def convert_date(dt):
return time.strptime(dt, "%d.%m.%Y")
def convert_date_time(dt, default=datetime.datet... |
class ImportFish(ImportOp):
ob_ct = 0
@staticmethod
def LoadFishDataOp(line, succ):
sp, created = Species.objects.get_or_create(name=line['Species'])
vessel, created = Vessel.objects.get_or_create(name=line['Vessel'])
trip, created = Trip.objects.get_or_create(
name=... | try:
return int(val)
except Exception:
return None | identifier_body |
load_length_frequency_data.py | # -*- coding: utf-8 -*-
from api.connectors import *
from seafood.models import *
from api.imports import *
import time
import datetime
from django.utils.timezone import get_current_timezone, make_aware
def convert_date(dt):
return time.strptime(dt, "%d.%m.%Y")
def convert_date_time(dt, default=datetime.datet... | fob.tow=tow
SaveKVs(fob, line)
fob.save()
ImportFish.ob_ct += 1
return True
@staticmethod
def CleanOp():
FishOb.objects.filter(datasource=ImportFish.ds).delete()
Trip.objects.filter(datasource=ImportFish.ds).delete()
Tow.objects.filter(datasour... | fob.species = sp
fob.trip = trip
fob.vessel = vessel
fob.datasource = ImportFish.ds
fob.study = ImportFish.study | random_line_split |
load_length_frequency_data.py | # -*- coding: utf-8 -*-
from api.connectors import *
from seafood.models import *
from api.imports import *
import time
import datetime
from django.utils.timezone import get_current_timezone, make_aware
def convert_date(dt):
return time.strptime(dt, "%d.%m.%Y")
def convert_date_time(dt, default=datetime.datet... |
else:
return make_aware(default, tz)
def convert_boolean(val):
if val == 'Y':
return True
else:
return False
def convert_int(val):
try:
return int(val)
except Exception:
return None
class ImportFish(ImportOp):
ob_ct = 0
@staticmethod
def Lo... | dt = time.strptime(dt, fmt)
dt = datetime.datetime.fromtimestamp(time.mktime(dt))
return make_aware(dt, tz) | conditional_block |
footer.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{generated::css_classes::C, Msg};
use chrono::{offset::Local, Datelike};
use iml_wire_types::{Branding, Conf};
use seed::{prelude::*, *};
pub fn view(conf:... | "© 2020 - DDN EXAScaler ".to_string()
}
}
};
let footer_text = match conf.branding {
Branding::Whamcloud => div![
footer_string,
year.to_string(),
" DDN. All rights reserved.".to_string(),
],
_ => div![footer_string... | } else { | random_line_split |
footer.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{generated::css_classes::C, Msg};
use chrono::{offset::Local, Datelike};
use iml_wire_types::{Branding, Conf};
use seed::{prelude::*, *};
pub fn view(conf:... | year.to_string(),
" DDN. All rights reserved.".to_string(),
],
_ => div![footer_string],
};
footer![
class![C.h_5, C.flex, C.justify_center],
div![class![C.px_5, C.text_sm, C.items_center,], footer_text]
]
}
| {
let year = Local::now().year();
let footer_string = match conf.branding {
Branding::Whamcloud => format!(
"Integrated Manager for Lustre software {} is Copyright © ",
conf.version
),
_ => {
if let Some(version) = &conf.exa_version {
... | identifier_body |
footer.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{generated::css_classes::C, Msg};
use chrono::{offset::Local, Datelike};
use iml_wire_types::{Branding, Conf};
use seed::{prelude::*, *};
pub fn | (conf: &Conf) -> impl View<Msg> {
let year = Local::now().year();
let footer_string = match conf.branding {
Branding::Whamcloud => format!(
"Integrated Manager for Lustre software {} is Copyright © ",
conf.version
),
_ => {
if let Some(version) = &con... | view | identifier_name |
object_path_spec.js | describe('Wheel.Utils.ObjectPath', function() {
describe('#write', function() {
it('builds the full path with object literals, if none are found in window', function() {
if (window.Foo) |
Wheel.Utils.ObjectPath.write('Foo.Bar.Zardoz', 3);
expect(window.Foo).toEqual({Bar: {Zardoz: 3}});
});
it('does not overwrite existing objects', function() {
var func = function () {};
window.Bar = func;
Wheel.Utils.ObjectPath.write('Bar.Foo.Zardoz', 42);
expect(window.Bar)... | { window.Foo = undefined; } | conditional_block |
object_path_spec.js | describe('Wheel.Utils.ObjectPath', function() {
describe('#write', function() {
it('builds the full path with object literals, if none are found in window', function() {
if (window.Foo) { window.Foo = undefined; }
Wheel.Utils.ObjectPath.write('Foo.Bar.Zardoz', 3);
expect(window.Foo).toEqual({Bar... | });
it('will return null if the path does not exist', function() {
expect(Wheel.Utils.ObjectPath.read('Funk.The.Dunk')).toBe(null);
});
});
}); | expect(Wheel.Utils.ObjectPath.read('Kiss.My.App')).toBe(13); | random_line_split |
webpack.config.prod.js | "
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
// It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delim... | // https://github.com/facebookincubator/create-react-app/issues/2235 | random_line_split | |
webpack.config.prod.js | be safe.
// Development builds of React are slow and not intended for production.
if (env.stringified['process.env'].NODE_ENV !== '"production"') |
// Note: defined here because it will be used more than once.
const cssFilename = 'static/css/[name].[contenthash:8].css'
// ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
// However, our output is structured with css, js and m... | {
throw new Error('Production builds must have NODE_ENV=production.')
} | conditional_block |
webpack.config.prod.js | entries to original disk location
devtoolModuleFilenameTemplate: info =>
path.relative(paths.appSrc, info.absoluteResourcePath)
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
... | {
if (message.indexOf('Total precache size is') === 0) {
// This message occurs for every build and is a bit too noisy.
return
}
console.log(message)
} | identifier_body | |
webpack.config.prod.js | : 'static/js/[name].[chunkhash:8].chunk.js',
// We inferred the "public path" (such as / or /my-project) from homepage.
publicPath: publicPath,
// Point sourcemap entries to original disk location
devtoolModuleFilenameTemplate: info =>
path.relative(paths.appSrc, info.absoluteResourcePath)
},
... | logger | identifier_name | |
collectOfflineEnvVariables.spec.js | 'use strict'
const collectOfflineEnvVariables = require('../../src/lib/collectOfflineEnvVariables.js')
describe('collectOfflineEnvVariables', () => {
let serverless
beforeAll(() => {
serverless = {
service: {
}
}
})
describe('default options', () => {
it('should return environment va... | expect(collectOfflineEnvVariables(serverless, options)).toEqual(expectedEnvVars)
})
})
describe('prefix', () => {
it('should be part of the path in API_ENDPOINT', () => {
const expectedEnvVars = {
IS_OFFLINE: true,
API_ENDPOINT: 'http://localhost:3000/v1/'
}
const o... | random_line_split | |
compositor_thread.rs | Modifiers, KeyState, PipelineId, TopLevelBrowsingContextId};
use net_traits::image::base::Image;
use profile_traits::mem;
use profile_traits::time;
use script_traits::{AnimationState, ConstellationMsg, EventResult, LoadData};
use servo_url::ServoUrl;
use std::fmt::{Debug, Error, Formatter};
use std::sync::mpsc::{Receiv... | (&self, f: &mut Formatter) -> Result<(), Error> {
match *self {
Msg::Exit => write!(f, "Exit"),
Msg::ShutdownComplete => write!(f, "ShutdownComplete"),
Msg::ChangeRunningAnimationsState(..) => write!(f, "ChangeRunningAnimationsState"),
Msg::SetFrameTree(..) => wri... | fmt | identifier_name |
compositor_thread.rs | KeyModifiers, KeyState, PipelineId, TopLevelBrowsingContextId};
use net_traits::image::base::Image;
use profile_traits::mem;
use profile_traits::time;
use script_traits::{AnimationState, ConstellationMsg, EventResult, LoadData};
use servo_url::ServoUrl;
use std::fmt::{Debug, Error, Formatter};
use std::sync::mpsc::{Re... | }
}
/// Sends messages to the compositor.
pub struct CompositorProxy {
pub sender: Sender<Msg>,
pub event_loop_waker: Box<EventLoopWaker>,
}
impl CompositorProxy {
pub fn send(&self, msg: Msg) {
// Send a message and kick the OS event loop awake.
if let Err(err) = self.sender.send(msg)... | random_line_split | |
_index.ts | <%#
Copyright 2013-2017 the original author or authors from the JHipster project.
This file is part of the JHipster project, see https://jhipster.github.io/
for more information.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You ... | export * from './profiles/profile.service';
export * from './profiles/profile-info.model';
export * from './layout-routing.module'; | export * from './navbar/navbar.component';
<%_ if (enableTranslation) { _%>
export * from './navbar/active-menu.directive';
<%_ } _%>
export * from './profiles/page-ribbon.component'; | random_line_split |
search-form.js | (function() {
'use strict';
//module: django.shop, TODO: move this into a summary JS file
var djangoShopModule = angular.module('django.shop.search', ['django.shop.utils']);
// Directive <form shop-product-search ...> to be used in the form containing the input field
// for entering the search query
djangoShopModule.... | else {
params = {
q: $scope.searchQuery
};
$scope.filters = {}; // remove content in filters
$location.search(params);
}
// delay the execution of reloading products
if (acPromise) {
$timeout.cancel(acPromise);
}
acPromise = $timeout(function() {
$scope.$emit('s... | {
params = null;
$location.search({});
} | conditional_block |
search-form.js | (function() {
'use strict';
//module: django.shop, TODO: move this into a summary JS file
var djangoShopModule = angular.module('django.shop.search', ['django.shop.utils']);
// Directive <form shop-product-search ...> to be used in the form containing the input field
// for entering the search query
djangoShopModule.... | restrict: 'AC',
controller: ['$scope', function($scope) {
var acPromise = null;
// handle typeahead search using autocomplete
$scope.autocomplete = function() {
var params;
if (!angular.isString($scope.searchQuery) || $scope.searchQuery.length < 3) {
params = null;
$location.search({});
... | random_line_split | |
testMixin.js | 'use strict';
function A() {
this._va = 0;
console.log('A');
}
A.prototype = {
va: 1,
fa: function() {
console.log('A->fa()');
}
};
function B() {
this._vb = 0;
console.log('B');
}
B.prototype = {
vb: 1,
fb: function() {
console.log('B->fb()');
}
};
function C() {
this._vc = 0;
consol... | (){
this._vd = 0;
console.log('D');
}
D.prototype = {
vd: 1,
fd: function() {
this.fa();
this.fb();
this.fc();
console.log('D->fd()');
}
};
var mixin = require('../mixin');
D = mixin(D, A);
D = mixin(D, B);
D = mixin(D, C);
var d = new D();
console.log(d);
console.log(d.constructor.name);
d.fd();... | D | identifier_name |
testMixin.js | 'use strict';
function A() |
A.prototype = {
va: 1,
fa: function() {
console.log('A->fa()');
}
};
function B() {
this._vb = 0;
console.log('B');
}
B.prototype = {
vb: 1,
fb: function() {
console.log('B->fb()');
}
};
function C() {
this._vc = 0;
console.log('C');
}
C.prototype = {
vc: 1,
fc: function() {
conso... | {
this._va = 0;
console.log('A');
} | identifier_body |
testMixin.js | 'use strict';
function A() {
this._va = 0;
console.log('A');
}
A.prototype = {
va: 1,
fa: function() {
console.log('A->fa()');
}
};
function B() {
this._vb = 0;
console.log('B');
}
B.prototype = {
vb: 1,
fb: function() {
console.log('B->fb()');
}
};
function C() {
this._vc = 0;
consol... | }
};
var mixin = require('../mixin');
D = mixin(D, A);
D = mixin(D, B);
D = mixin(D, C);
var d = new D();
console.log(d);
console.log(d.constructor.name);
d.fd();
var a = new A();
console.log(a);
console.log(a.__proto__);
console.log(a.va); | this.fc();
console.log('D->fd()'); | random_line_split |
Border.py | __author__ = 'amentis'
from RxAPI.RxGUI import Color, RxGUIObject
class Border(RxGUIObject):
"""
Drawable border for any drawable RxGUIObject.
"""
def __init__(self, name, color=None, style="solid", width="1px"):
"""
@param name: str name of the REXI object
@param color: Color ... |
def get(self):
"""
@return : str CSS code defining the border
"""
return "border: %s %s %s ;" % (self._width, self._style, self._color.get()) | self._color = Color.Color('borderColor', color) | conditional_block |
Border.py | __author__ = 'amentis'
from RxAPI.RxGUI import Color, RxGUIObject
class Border(RxGUIObject):
"""
Drawable border for any drawable RxGUIObject.
"""
def __init__(self, name, color=None, style="solid", width="1px"):
"""
@param name: str name of the REXI object
@param color: Color ... | self._width = width
if color is None:
self._color = Color.Color('borderColor')
self._color.color_by_name('Black')
else:
self._color = Color.Color('borderColor', color)
def get(self):
"""
@return : str CSS code defining the border
"... | thin, medium, thick, N%/px/cm/etc., inherit
"""
RxGUIObject.__init__(self, name, None)
self._style = style | random_line_split |
Border.py | __author__ = 'amentis'
from RxAPI.RxGUI import Color, RxGUIObject
class Border(RxGUIObject):
"""
Drawable border for any drawable RxGUIObject.
"""
def __init__(self, name, color=None, style="solid", width="1px"):
"""
@param name: str name of the REXI object
@param color: Color ... | """
@return : str CSS code defining the border
"""
return "border: %s %s %s ;" % (self._width, self._style, self._color.get()) | identifier_body | |
Border.py | __author__ = 'amentis'
from RxAPI.RxGUI import Color, RxGUIObject
class Border(RxGUIObject):
"""
Drawable border for any drawable RxGUIObject.
"""
def __init__(self, name, color=None, style="solid", width="1px"):
"""
@param name: str name of the REXI object
@param color: Color ... | (self):
"""
@return : str CSS code defining the border
"""
return "border: %s %s %s ;" % (self._width, self._style, self._color.get()) | get | identifier_name |
com_google_android_feedback.py | '''
NFI -- Silensec's Nyuki Forensics Investigator
Copyright (C) 2014 George Nicolaou (george[at]silensec[dot]com)
Silensec Ltd.
Juma Fredrick (j.fredrick[at]silensec[dot]com)
Silensec Ltd.
This file is part of Nyuki Forensics Investigator (NFI).
NFI is fr... | name = "com.google.android.feedback"
cname = "Google Android Feedback"
databases = {
"webviewCookiesChromium.db": [
KnownTable("cookies", None,
{"creation_utc":ConvertUtils.WebkitToUnix,
"expires_utc":ConvertUtils.WebkitToUnix,
"last_access_u... | identifier_body | |
com_google_android_feedback.py | '''
NFI -- Silensec's Nyuki Forensics Investigator
Copyright (C) 2014 George Nicolaou (george[at]silensec[dot]com) | Silensec Ltd.
Juma Fredrick (j.fredrick[at]silensec[dot]com)
Silensec Ltd.
This file is part of Nyuki Forensics Investigator (NFI).
NFI is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published ... | random_line_split | |
com_google_android_feedback.py | '''
NFI -- Silensec's Nyuki Forensics Investigator
Copyright (C) 2014 George Nicolaou (george[at]silensec[dot]com)
Silensec Ltd.
Juma Fredrick (j.fredrick[at]silensec[dot]com)
Silensec Ltd.
This file is part of Nyuki Forensics Investigator (NFI).
NFI is fr... | (self):
self.known = True
| __init__ | identifier_name |
CreateDatabaseCommand.ts | import {RavenCommand} from '../RavenCommand';
import {ServerNode} from '../../Http/ServerNode';
import {IRavenResponse} from "../RavenCommandResponse";
import {IResponse} from "../../Http/Response/IResponse";
import {RequestMethods} from "../../Http/Request/RequestMethod";
import {InvalidOperationException, ErrorRespon... | }
} | return result; | random_line_split |
CreateDatabaseCommand.ts | import {RavenCommand} from '../RavenCommand';
import {ServerNode} from '../../Http/ServerNode';
import {IRavenResponse} from "../RavenCommandResponse";
import {IResponse} from "../../Http/Response/IResponse";
import {RequestMethods} from "../../Http/Request/RequestMethod";
import {InvalidOperationException, ErrorRespon... |
public createRequest(serverNode: ServerNode): void {
const dbName: string = this.databaseDocument.databaseId.replace('Raven/Databases/', '');
StringUtil.validateDBName(dbName);
if (!('Raven/DataDir' in this.databaseDocument.settings)) {
throw new InvalidOperationException("The Raven/DataDir sett... | {
super('', RequestMethods.Put);
this.databaseDocument = databaseDocument;
this.replicationFactor = replicationFactor || 1;
} | identifier_body |
CreateDatabaseCommand.ts | import {RavenCommand} from '../RavenCommand';
import {ServerNode} from '../../Http/ServerNode';
import {IRavenResponse} from "../RavenCommandResponse";
import {IResponse} from "../../Http/Response/IResponse";
import {RequestMethods} from "../../Http/Request/RequestMethod";
import {InvalidOperationException, ErrorRespon... |
return result;
}
}
| {
throw new ErrorResponseException('Response is invalid.')
} | conditional_block |
CreateDatabaseCommand.ts | import {RavenCommand} from '../RavenCommand';
import {ServerNode} from '../../Http/ServerNode';
import {IRavenResponse} from "../RavenCommandResponse";
import {IResponse} from "../../Http/Response/IResponse";
import {RequestMethods} from "../../Http/Request/RequestMethod";
import {InvalidOperationException, ErrorRespon... | (response: IResponse): IRavenResponse | IRavenResponse[] | void {
const result: IRavenResponse = <IRavenResponse>super.setResponse(response);
if (!response.body) {
throw new ErrorResponseException('Response is invalid.')
}
return result;
}
}
| setResponse | identifier_name |
minmax-stability-issue-23687.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(iter_min_max, cmp_partial, iter_cmp)]
use std::fmt::Debug;
use std::cmp::{self, PartialOrd, Ordering};
#[derive(Debug, Copy, Clone, PartialEq... | // 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 | random_line_split |
minmax-stability-issue-23687.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
impl Ord for Foo {
fn cmp(&self, other: &Foo) -> Ordering {
self.n.cmp(&other.n)
}
}
fn main() {
let a = Foo { n: 4, name: "a" };
let b = Foo { n: 4, name: "b" };
let c = Foo { n: 8, name: "c" };
let d = Foo { n: 8, name: "d" };
let e = Foo { n: 22, name: "e" };
let f = Foo ... | {
Some(self.cmp(other))
} | identifier_body |
minmax-stability-issue-23687.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let a = Foo { n: 4, name: "a" };
let b = Foo { n: 4, name: "b" };
let c = Foo { n: 8, name: "c" };
let d = Foo { n: 8, name: "d" };
let e = Foo { n: 22, name: "e" };
let f = Foo { n: 22, name: "f" };
let data = [a, b, c, d, e, f];
// `min` should return the left when the values ar... | main | identifier_name |
modadd.rs | use num::{Zero, BigUint, BigInt, Integer, PrimInt};
/// The `ModAdd` trait defines an interface for calculating the sum of two integers
/// modulo a modulus.
pub trait ModAdd {
/// The function `mod_add` computes the sum
/// ```text
/// x + y (mod m)
/// ```
/// where x, y, and m are integers, an... |
}
| {
let x = BigInt::from(735172765);
let y = BigInt::from(446253906);
let modulus = BigInt::from(0);
x.mod_add(&y, &modulus);
} | identifier_body |
modadd.rs | use num::{Zero, BigUint, BigInt, Integer, PrimInt};
/// The `ModAdd` trait defines an interface for calculating the sum of two integers
/// modulo a modulus.
pub trait ModAdd {
/// The function `mod_add` computes the sum
/// ```text
/// x + y (mod m)
/// ```
/// where x, y, and m are integers, an... | TestCase {
x: BigInt::from(464283712),
y: BigInt::from(559073817),
modulus: BigInt::from(635717262),
sum: BigInt::from(387640267),
},
TestCase {
x: BigInt::from(-812470905)... | data: vec! [ | random_line_split |
modadd.rs | use num::{Zero, BigUint, BigInt, Integer, PrimInt};
/// The `ModAdd` trait defines an interface for calculating the sum of two integers
/// modulo a modulus.
pub trait ModAdd {
/// The function `mod_add` computes the sum
/// ```text
/// x + y (mod m)
/// ```
/// where x, y, and m are integers, an... | {
data: Vec<TestCase>,
}
fn mod_add_test_cases() -> Test {
Test {
data: vec! [
TestCase {
x: BigInt::from(464283712),
y: BigInt::from(559073817),
modulus: BigInt::from(635717262),
sum: B... | Test | identifier_name |
inversify.ts | /// <reference path="../../../node_modules/inversify-dts/inversify/inversify.d.ts" />
/// <reference path="../../../node_modules/@types/node/index.d.ts" />
import { IModelCreationParams, ILib, factory } from './index'
type Schema = JSON
type StaticData = IModelCreationParams[]
type Factory = () => ILib
let TYPES = {... | //console.log('in factory func', arguments)
return factory({
schema: context.kernel.get<Schema>(TYPES.Schema)
})
}
})
})
export {
ILib,
Schema,
StaticData,
Factory,
TYPES,
kernel_module
} | //console.log('in factory', context)
return () => { | random_line_split |
[id].tsx | import { Provider } from 'mobx-react'
import { ROUTE, ARTICLE_THREAD, METRIC } from '@/constant'
import {
ssrBaseStates,
ssrFetchPrepare,
ssrError,
articleSEO,
ssrGetParam,
refreshIfneed,
} from '@/utils'
import { useStore } from '@/stores/init'
import GlobalLayout from '@/containers/layout/GlobalLayout'
... | const id = ssrGetParam(context, 'id')
const { gqClient, userHasLogin } = ssrFetchPrepare(context, opt)
// query data
const sessionState = gqClient.request(P.sessionState)
const blog = gqClient.request(P.blog, { id, userHasLogin })
const subscribedCommunities = gqClient.request(P.subscribedCommunities, {
... | random_line_split | |
range.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 ... | pub fn new(low: X, high: X) -> Range<X> {
assert!(low < high, "Range::new called with `low >= high`");
SampleRange::construct_range(low, high)
}
}
impl<Sup: SampleRange> Sample<Sup> for Range<Sup> {
#[inline]
fn sample<R: Rng>(&mut self, rng: &mut R) -> Sup { self.ind_sample(rng) }
}
im... | /// `[low, high)`. Panics if `low >= high`. | random_line_split |
range.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 ... | (low: X, high: X) -> Range<X> {
assert!(low < high, "Range::new called with `low >= high`");
SampleRange::construct_range(low, high)
}
}
impl<Sup: SampleRange> Sample<Sup> for Range<Sup> {
#[inline]
fn sample<R: Rng>(&mut self, rng: &mut R) -> Sup { self.ind_sample(rng) }
}
impl<Sup: Sample... | new | identifier_name |
serviceworkerglobalscope.rs | ::jsval::UndefinedValue;
use js::rust::Runtime;
use net_traits::{load_whole_resource, IpcSend, CustomResponseMediator};
use net_traits::request::{CredentialsMode, Destination, RequestInit, Type as RequestType};
use script_runtime::{CommonScriptMsg, StackRootTLS, get_reports, new_rt_and_cx, ScriptChan};
use script_trait... | impl ServiceWorkerGlobalScope {
fn new_inherited(init: WorkerGlobalScopeInit,
worker_url: ServoUrl,
from_devtools_receiver: Receiver<DevtoolScriptControlMsg>,
runtime: Runtime,
own_sender: Sender<ServiceWorkerScriptMsg>,
... | scope_url: ServoUrl,
}
| random_line_split |
serviceworkerglobalscope.rs | jsval::UndefinedValue;
use js::rust::Runtime;
use net_traits::{load_whole_resource, IpcSend, CustomResponseMediator};
use net_traits::request::{CredentialsMode, Destination, RequestInit, Type as RequestType};
use script_runtime::{CommonScriptMsg, StackRootTLS, get_reports, new_rt_and_cx, ScriptChan};
use script_traits:... |
fn clone(&self) -> Box<ScriptChan + Send> {
box ServiceWorkerChan {
sender: self.sender.clone(),
}
}
}
#[dom_struct]
pub struct ServiceWorkerGlobalScope {
workerglobalscope: WorkerGlobalScope,
#[ignore_heap_size_of = "Defined in std"]
receiver: Receiver<ServiceWorkerSc... | {
self.sender
.send(ServiceWorkerScriptMsg::CommonWorker(WorkerScriptMsg::Common(msg)))
.map_err(|_| ())
} | identifier_body |
serviceworkerglobalscope.rs | "]
own_sender: Sender<ServiceWorkerScriptMsg>,
#[ignore_heap_size_of = "Defined in std"]
timer_event_port: Receiver<()>,
#[ignore_heap_size_of = "Defined in std"]
swmanager_sender: IpcSender<ServiceWorkerMsg>,
scope_url: ServoUrl,
}
impl ServiceWorkerGlobalScope {
fn new_inherited(init: Wor... | process_event | identifier_name | |
registration.component.ts | import { Component, AfterViewInit, OnInit } from '@angular/core';
import { Router } from '@angular/router'
import { RegistrationService } from './registration.service';
import { User, UserType } from '../../sharedClasses/user';
import { districtList, District } from './districts';
import { NotificationsService, SimpleN... | (
private registrationService: RegistrationService,
private _notification: NotificationsService,
private _router: Router
) { }
ngAfterViewInit() {
$.material.init()
}
onChange(id) {
this.selectedUserTypeID = id;
}
onSelectDistrict(district: string) {
... | constructor | identifier_name |
registration.component.ts | import { Component, AfterViewInit, OnInit } from '@angular/core';
import { Router } from '@angular/router'
import { RegistrationService } from './registration.service';
import { User, UserType } from '../../sharedClasses/user';
import { districtList, District } from './districts';
import { NotificationsService, SimpleN... | selectedUserTypeID: number;
submitted: boolean;
districts = districtList;
validationMessage: string;
options = {
position: ['top', 'right'],
timeOut: 3000,
lastOnBottom: true,
clickToClose: true
};
model: any = {};
error: boolean = false;
constructo... | selectedDistrict: string;
password: string;
cnfrmPassword: string; | random_line_split |
registration.component.ts | import { Component, AfterViewInit, OnInit } from '@angular/core';
import { Router } from '@angular/router'
import { RegistrationService } from './registration.service';
import { User, UserType } from '../../sharedClasses/user';
import { districtList, District } from './districts';
import { NotificationsService, SimpleN... |
}
onSubmit(form) {
let newUser = new User();
newUser.first_name = form.value.inputFName;
newUser.last_name = form.value.inputLName;
newUser.email = form.value.inputEmail;
newUser.email_verified = false;
newUser.password = form.value.inputPassword; //use bcrypt
... | {
return true;
} | conditional_block |
registration.component.ts | import { Component, AfterViewInit, OnInit } from '@angular/core';
import { Router } from '@angular/router'
import { RegistrationService } from './registration.service';
import { User, UserType } from '../../sharedClasses/user';
import { districtList, District } from './districts';
import { NotificationsService, SimpleN... |
onSelectDistrict(district: string) {
this.selectedDistrict = district;
}
validForm(): boolean {
if ((this.password && this.cnfrmPassword) && (this.password != this.cnfrmPassword)) {
this.validationMessage = "Password does not match";
return false;
}
... | {
this.selectedUserTypeID = id;
} | identifier_body |
mod.rs | /// Chapter 4.23 - Closures
/// [Chapter 4.23] https://doc.rust-lang.org/book/closures.html
pub use self::closures::*;
pub mod closures {
pub fn main() {
println!("====\nClosure:\n");
// We did not need to annotate the
// types of arguments the closure
// takes or the values it retu... |
} | {
let mut num = 5;
// `num` will be changed
{
let mut add_num = |x: i32| num += x;
add_num(5);
}
assert_eq!(10, num);
// For move closure
let mut num = 5;
{
// Move -> copied `num` value
// We took ownership... | identifier_body |
mod.rs | /// Chapter 4.23 - Closures
/// [Chapter 4.23] https://doc.rust-lang.org/book/closures.html
pub use self::closures::*;
pub mod closures {
pub fn main() {
println!("====\nClosure:\n");
// We did not need to annotate the
// types of arguments the closure
// takes or the values it retu... | res += 1;
res
};
println!("Assert check: {}", 4 == plus_two(2));
println!("Assert check: {}", simelar_closures());
// The environment for a closure can include bindings
// from its enclosing
// It borrows the binding!
// we took ownership... | let mut res: i32 = x;
res += 1; | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.