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 |
|---|---|---|---|---|
network.py | import numpy as np
from vanilla_neural_nets.neural_network.training_batch_generator import MiniBatchGenerator
from vanilla_neural_nets.neural_network.optimization_algorithm import GradientDescent
from vanilla_neural_nets.neural_network.loss_function import MeanSquaredError
from vanilla_neural_nets.neural_network.activ... |
return activation_matrix
def _update_network_layers_with_training_batch(self, training_batch):
return self.optimization_algorithm_class(
training_batch=training_batch,
network_layers=self.parameters,
loss_function_class=self.loss_function_class,
acti... | activation_function_class = self.output_layer_activation_function_class if layer.is_output_layer\
else self.activation_function_class
linear_combination = np.dot(activation_matrix, layer.weight_parameter.value.T) + layer.bias_parameter.value
activation_matrix = activation_functi... | conditional_block |
network.py | import numpy as np
from vanilla_neural_nets.neural_network.training_batch_generator import MiniBatchGenerator
from vanilla_neural_nets.neural_network.optimization_algorithm import GradientDescent
from vanilla_neural_nets.neural_network.loss_function import MeanSquaredError
from vanilla_neural_nets.neural_network.activ... |
def predict(self, x):
activation_matrix = x
for layer in self.parameters.layers:
activation_function_class = self.output_layer_activation_function_class if layer.is_output_layer\
else self.activation_function_class
linear_combination = np.dot(activation_mat... | for epoch in range(self.n_epochs):
training_batch_generator = self.training_batch_generator_class(X=X, y=y, batch_size=self.training_batch_size,
random_number_generator=self.random_number_generator)
for training_batch in training_batch_generator:
self.parameters ... | identifier_body |
network.py | import numpy as np
from vanilla_neural_nets.neural_network.training_batch_generator import MiniBatchGenerator
from vanilla_neural_nets.neural_network.optimization_algorithm import GradientDescent
from vanilla_neural_nets.neural_network.loss_function import MeanSquaredError
from vanilla_neural_nets.neural_network.activ... | self.holdout_data = holdout_data
self.random_number_generator = np.random.RandomState(random_state)
self.parameters = NetworkLayersCollection(
layer_sizes=layer_sizes,
weight_initializer=weight_initializer,
bias_initializer=bias_initializer
)
def ... | self.optimization_algorithm_class = optimization_algorithm_class
self.learning_rate = learning_rate
self.n_epochs = n_epochs
self.training_batch_size = training_batch_size | random_line_split |
DateArrayField.js | import ArrayFieldMixin from '../../mixins/ArrayField';
import DateInput from '../../components/DateInput';
import Field from '../Field';
import React from 'react';
import moment from 'moment';
const DEFAULT_INPUT_FORMAT = 'YYYY-MM-DD';
const DEFAULT_FORMAT_STRING = 'Do MMM YYYY';
module.exports = Field.create({
dis... | ,
processInputValue (value) {
if (!value) return;
let m = moment(value);
return m.isValid() ? m.format(this.props.inputFormat) : value;
},
formatValue (value) {
return value ? this.moment(value).format(this.props.formatString) : '';
},
getInputComponent () {
return DateInput;
},
});
| {
return {
formatString: DEFAULT_FORMAT_STRING,
inputFormat: DEFAULT_INPUT_FORMAT,
};
} | identifier_body |
DateArrayField.js | import ArrayFieldMixin from '../../mixins/ArrayField';
import DateInput from '../../components/DateInput';
import Field from '../Field';
import React from 'react';
import moment from 'moment';
const DEFAULT_INPUT_FORMAT = 'YYYY-MM-DD';
const DEFAULT_FORMAT_STRING = 'Do MMM YYYY';
module.exports = Field.create({
dis... | }); | random_line_split | |
DateArrayField.js | import ArrayFieldMixin from '../../mixins/ArrayField';
import DateInput from '../../components/DateInput';
import Field from '../Field';
import React from 'react';
import moment from 'moment';
const DEFAULT_INPUT_FORMAT = 'YYYY-MM-DD';
const DEFAULT_FORMAT_STRING = 'Do MMM YYYY';
module.exports = Field.create({
dis... | (value) {
return value ? this.moment(value).format(this.props.formatString) : '';
},
getInputComponent () {
return DateInput;
},
});
| formatValue | identifier_name |
file.rs | use std::io;
use std::io::{ BufRead, BufReader, Read, Seek, SeekFrom };
use std::fs::File;
use models::Grid;
pub fn read_grid_from_file(input_file_path: &String) -> Result<Grid, io::Error> | Ok(grid)
}
| {
let file = try!(File::open(input_file_path));
let mut reader = BufReader::new(file);
let x = reader.by_ref().lines().next().unwrap().unwrap().chars().count();
reader.seek(SeekFrom::Start(0)).unwrap();
let y = reader.by_ref().lines().count();
reader.seek(SeekFrom::Start(0)).unwrap();
let... | identifier_body |
file.rs | use std::io;
use std::io::{ BufRead, BufReader, Read, Seek, SeekFrom };
use std::fs::File;
use models::Grid;
pub fn | (input_file_path: &String) -> Result<Grid, io::Error> {
let file = try!(File::open(input_file_path));
let mut reader = BufReader::new(file);
let x = reader.by_ref().lines().next().unwrap().unwrap().chars().count();
reader.seek(SeekFrom::Start(0)).unwrap();
let y = reader.by_ref().lines().count();
... | read_grid_from_file | identifier_name |
file.rs | use std::io;
use std::io::{ BufRead, BufReader, Read, Seek, SeekFrom };
use std::fs::File;
use models::Grid;
pub fn read_grid_from_file(input_file_path: &String) -> Result<Grid, io::Error> {
let file = try!(File::open(input_file_path));
let mut reader = BufReader::new(file);
let x = reader.by_ref().lines... | } | random_line_split | |
file.rs | use std::io;
use std::io::{ BufRead, BufReader, Read, Seek, SeekFrom };
use std::fs::File;
use models::Grid;
pub fn read_grid_from_file(input_file_path: &String) -> Result<Grid, io::Error> {
let file = try!(File::open(input_file_path));
let mut reader = BufReader::new(file);
let x = reader.by_ref().lines... | ,
_ => { grid[y][x].die() }
}
}
}
Ok(grid)
}
| { grid[y][x].arise() } | conditional_block |
locked_env_var.rs | //! Unit test helpers for dealing with environment variables.
//!
//! A lot of our functionality can change depending on how certain
//! environment variables are set. This complicates unit testing,
//! because Rust runs test cases in parallel on separate threads, but
//! environment variables are shared across threads... | <V>(&self, value: V)
where V: AsRef<OsStr>
{
env::set_var(&*self.lock, value.as_ref());
}
/// Unsets an environment variable.
pub fn unset(&self) { env::remove_var(&*self.lock); }
}
impl Drop for LockedEnvVar {
fn drop(&mut self) {
match self.original_value {
So... | set | identifier_name |
locked_env_var.rs | //! Unit test helpers for dealing with environment variables.
//!
//! A lot of our functionality can change depending on how certain
//! environment variables are set. This complicates unit testing,
//! because Rust runs test cases in parallel on separate threads, but
//! environment variables are shared across threads... | /// use locking function generated by the `locked_env_var!` macro.
///
/// The current value of the variable is recorded at the time of
/// creation; it will be reset when the lock is dropped.
pub fn new(lock: MutexGuard<'static, String>) -> Self {
let original = match env::var(&*lock) {
... | impl LockedEnvVar {
/// Create a new lock. Users should not call this directly, but | random_line_split |
manufactureGAP_vertical.py | import polyadcirc.run_framework.domain as dom
import polyadcirc.pyGriddata.manufacture_gap as manu
grid_dir = '.'
domain = dom.domain(grid_dir)
domain.read_spatial_grid()
| yu = max(y_values)
yl = min(y_values)
x_points = (xl, 150, 750, xr)
p1 = [0, 0, 0, 1]
p2 = [0, 0, 0, 1]
p3 = [.2, .3, .4, .1]
rand_rect = manu.random_vertical(x_points, yl, yu, [1, 2, 3, 4], p_sections=
[p1, p2, p3])
manu.write_gapfile(rand_rect, xl, yl, 'sections.asc') | x_values = [n.x for n in domain.node.values()]
y_values = [n.y for n in domain.node.values()]
xr = max(x_values)
xl = min(x_values) | random_line_split |
tick_formats_spec.js | import { dateTickFormat, initDateFormats } from '~/lib/utils/tick_formats';
import { setLanguage } from '../../helpers/locale_helper';
describe('tick formats', () => {
describe('dateTickFormat', () => {
beforeAll(() => {
setLanguage('de');
initDateFormats();
});
afterAll(() => {
setLa... | expect(tick).toBe('Februar');
});
it('returns day and month for second of February', () => {
const tick = dateTickFormat(new Date('2001-02-02'));
expect(tick).toBe('2. Feb.');
});
it('ignores time', () => {
const tick = dateTickFormat(new Date('2001-02-02 12:34:56'));
e... | random_line_split | |
filename.py | #!/usr/bin/env python3
#
# Copyright 2014 Simone Campagna
#
# 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 ... | (Filename):
pass
class OutputFilename(Filename):
pass
class Mode(object):
MODES = set()
DEFAULT_MODE = 'rb'
def __init__(self, mode=None):
if mode is None:
mode = self.DEFAULT_MODE
mode = mode.lower()
for m in self.MODES:
if set(mode) == set(m):
... | InputFilename | identifier_name |
filename.py | #!/usr/bin/env python3
#
# Copyright 2014 Simone Campagna
#
# 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 ... |
elif isinstance(init, BASE_STRING):
filename = self._from_string(init)
else:
raise ValueError("cannot make a {c} from {t} object {o!r}".format(
c=self.__class__.__name__,
t=type(init).__name__,
o=init))
self._filename = fil... | filename = init._filename | conditional_block |
filename.py | #!/usr/bin/env python3
#
# Copyright 2014 Simone Campagna
#
# 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 ... | MODES = {'w', 'wb', 'a', 'ab', 'w+b', 'r+b', 'a+b'}
DEFAULT_MODE = 'wb'
def is_append_mode(self):
return 'a' in self.mode |
class OutputMode(Mode): | random_line_split |
filename.py | #!/usr/bin/env python3
#
# Copyright 2014 Simone Campagna
#
# 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 ... |
def __str__(self):
return self.mode
def __repr__(self):
return "{}({!r})".format(self.__class__.__name__, self.mode)
class InputMode(Mode):
MODES = {'r', 'rb'}
DEFAULT_MODE = 'rb'
class OutputMode(Mode):
MODES = {'w', 'wb', 'a', 'ab', 'w+b', 'r+b', 'a+b'}
DEFAULT_MODE = ... | if mode is None:
mode = self.DEFAULT_MODE
mode = mode.lower()
for m in self.MODES:
if set(mode) == set(m):
break
else:
raise ValueError("invalid {} {!r}: allowed modes are {}".format(
self.__class__.__name__,
mod... | identifier_body |
artifact_utils.py | # Copyright 2021 The Kubeflow 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 in... |
try:
jsonschema.validate(instance=instance, schema=yaml.full_load(schema))
except jsonschema.exceptions.SchemaError:
raise RuntimeError('Invalid schema schema: {} used for \
verification'.format(schema))
except jsonschema.exceptions.ValidationError:
raise RuntimeError('Inva... | return | conditional_block |
artifact_utils.py | # Copyright 2021 The Kubeflow 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 in... | # limitations under the License.
"""Helper utils used in artifact and ontology_artifact classes."""
from typing import Any, Dict, Tuple
import enum
import jsonschema
import os
import yaml
class SchemaFieldType(enum.Enum):
"""Supported Schema field types."""
NUMBER = 'number'
INTEGER = 'integer'
STRI... | # See the License for the specific language governing permissions and | random_line_split |
artifact_utils.py | # Copyright 2021 The Kubeflow 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 in... |
def parse_schema(yaml_schema: str) -> Tuple[str, Dict[str, SchemaFieldType]]:
"""Parses yaml schema.
Ensures that schema is well-formed and returns dictionary of properties and
its type for type-checking.
Args:
yaml_schema: Yaml schema to be parsed.
Returns:
str: Title set in the s... | """Supported Schema field types."""
NUMBER = 'number'
INTEGER = 'integer'
STRING = 'string'
BOOL = 'bool'
OBJECT = 'object'
ARRAY = 'array' | identifier_body |
artifact_utils.py | # Copyright 2021 The Kubeflow 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 in... | (schema: str, instance: Dict[str, Any]):
"""Verifies instnace is well-formed against the schema.
Args:
schema: Schema to use for verification.
instance: Object represented as Dict to be verified.
Raises:
RuntimeError if schema is not well-formed or instance is invalid against
the ... | verify_schema_instance | identifier_name |
constants.ts | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
export enum DiagnosticCodes {
InvalidEnvironmentPathVariableDiagnostic = 'InvalidEnvironmentPathVariableDiagnostic',
InvalidDebuggerTypeDiagnostic = 'InvalidDebuggerTypeDiagnostic',
NoPythonInterp... | LSNotSupportedDiagnostic = 'LSNotSupportedDiagnostic',
PythonPathDeprecatedDiagnostic = 'PythonPathDeprecatedDiagnostic',
JustMyCodeDiagnostic = 'JustMyCodeDiagnostic',
ConsoleTypeDiagnostic = 'ConsoleTypeDiagnostic',
ConfigPythonPathDiagnostic = 'ConfigPythonPathDiagnostic',
UpgradeCodeRunnerDi... | InvalidPythonPathInDebuggerLaunchDiagnostic = 'InvalidPythonPathInDebuggerLaunchDiagnostic',
EnvironmentActivationInPowerShellWithBatchFilesNotSupportedDiagnostic = 'EnvironmentActivationInPowerShellWithBatchFilesNotSupportedDiagnostic',
NoCurrentlySelectedPythonInterpreterDiagnostic = 'InvalidPythonInterpr... | random_line_split |
start.ts | /// <reference path="../../observable.ts"/>
/// <reference path="../../concurrency/scheduler.ts" />
module Rx {
export interface ObservableStatic {
/**
* Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence.
*
*... | }); | var o : Rx.Observable<string> = Rx.Observable.start(() => 'abc', Rx.Scheduler.default, {}); | random_line_split |
httpheader.rs | // Copyright (c) 2014 Nathan Sizemore
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// pu... |
}
}
return request_header;
}
// TODO - Create real logic that will actually verifiy this
pub fn is_valid(&self) -> bool {
if self.sec_websocket_key.as_slice() != "" {
return true;
}
return false;
}
}
impl ReturnHeader {
/*
* R... | { /* Do nothing */ } | conditional_block |
httpheader.rs | // Copyright (c) 2014 Nathan Sizemore
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// pu... |
/*
* SHA-1 Hash performed on passed value
* Bytes placed in passed out buffer
*/
fn sha1_hash(value: &str, out: &mut [u8]) {
let mut sha = box Sha1::new();
(*sha).input_str(value);
sha.result(out);
}
}
| {
let mut stringified = String::new();
stringified.push_str(self.heading.as_slice());
stringified.push_str(self.upgrade.as_slice());
stringified.push_str(self.connection.as_slice());
stringified.push_str("Sec-Websocket-Accept: ");
stringified.push_str(self.sec_websocket_a... | identifier_body |
httpheader.rs | // Copyright (c) 2014 Nathan Sizemore
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// pu... | (value: &str, out: &mut [u8]) {
let mut sha = box Sha1::new();
(*sha).input_str(value);
sha.result(out);
}
}
| sha1_hash | identifier_name |
httpheader.rs | // Copyright (c) 2014 Nathan Sizemore
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// pu... |
// Get the SHA-1 Hash as bytes
let mut out = [0u8; 20];
ReturnHeader::sha1_hash(pre_hash.as_slice(), &mut out);
// Base64 encode the buffer
let config = STANDARD;
let encoded = out.to_base64(config);
ReturnHeader {
heading: String::from_str("HTTP/1.... | let mut pre_hash = String::from_str(key);
pre_hash.push_str("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); | random_line_split |
pherf-standalone.py | #!/usr/bin/env python
############################################################################
#
# 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 A... |
elif os.name == 'nt':
hbase_env_path = os.path.join(hbase_config_path, 'hbase-env.cmd')
hbase_env_cmd = ['cmd.exe', '/c', 'call %s & set' % hbase_env_path]
if not hbase_env_path or not hbase_env_cmd:
sys.stderr.write("hbase-env file unknown on platform {}{}".format(os.name, os.linesep))
sys.exit(-1)
h... | hbase_env_path = os.path.join(hbase_config_path, 'hbase-env.sh')
hbase_env_cmd = ['bash', '-c', 'source %s && env' % hbase_env_path] | conditional_block |
pherf-standalone.py | #!/usr/bin/env python
############################################################################
#
# 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 not use this file except in compliance
# with the License. You ma... | random_line_split | |
mediastream.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::{DomRefCell, Ref};
use crate::dom::bindings::codegen::Bindings::MediaStreamBindin... | (&self) -> Vec<DomRoot<MediaStreamTrack>> {
self.tracks
.borrow()
.iter()
.filter(|x| x.ty() == MediaStreamType::Video)
.map(|x| DomRoot::from_ref(&**x))
.collect()
}
/// https://w3c.github.io/mediacapture-main/#dom-mediastream-gettrackbyid
... | GetVideoTracks | identifier_name |
mediastream.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::{DomRefCell, Ref};
use crate::dom::bindings::codegen::Bindings::MediaStreamBindin... |
self.add_track(track)
}
/// https://w3c.github.io/mediacapture-main/#dom-mediastream-removetrack
fn RemoveTrack(&self, track: &MediaStreamTrack) {
self.tracks.borrow_mut().retain(|x| *x != track);
}
/// https://w3c.github.io/mediacapture-main/#dom-mediastream-clone
fn Clone(&s... | {
return;
} | conditional_block |
mediastream.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::{DomRefCell, Ref};
use crate::dom::bindings::codegen::Bindings::MediaStreamBindin... | self.tracks
.borrow()
.iter()
.filter(|x| x.ty() == MediaStreamType::Video)
.map(|x| DomRoot::from_ref(&**x))
.collect()
}
/// https://w3c.github.io/mediacapture-main/#dom-mediastream-gettrackbyid
fn GetTrackById(&self, id: DOMString) -> O... | /// https://w3c.github.io/mediacapture-main/#dom-mediastream-getvideotracks
fn GetVideoTracks(&self) -> Vec<DomRoot<MediaStreamTrack>> { | random_line_split |
mediastream.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::{DomRefCell, Ref};
use crate::dom::bindings::codegen::Bindings::MediaStreamBindin... |
pub fn Constructor__(
global: &Window,
tracks: Vec<DomRoot<MediaStreamTrack>>,
) -> Fallible<DomRoot<MediaStream>> {
let new = MediaStream::new(&global.global());
for track in tracks {
// this is quadratic, but shouldn't matter much
// if this becomes a ... | {
Ok(stream.Clone())
} | identifier_body |
TestValidator_float.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 ... |
if __name__=='__main__':
unittest.main()
| self.assertEqual(n-1, v.elementValidator().getNDims()) | conditional_block |
TestValidator_float.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 ... | (self, n, s, tc, clss, good, bad):
v = Validator_float.get(n)
self.assertEqual(n, v.getNDims())
self.assertEqual(clss, v.getExpectedClass())
self.assertEqual(s, repr(v))
self.assertEqual(True, v.validate(good))
self.assertEqual(False, v.validate(bad))
self.asser... | _test | identifier_name |
TestValidator_float.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 ... |
if __name__=='__main__':
unittest.main()
| v = Validator_float.get(n)
self.assertEqual(n, v.getNDims())
self.assertEqual(clss, v.getExpectedClass())
self.assertEqual(s, repr(v))
self.assertEqual(True, v.validate(good))
self.assertEqual(False, v.validate(bad))
self.assertEqual(tc, v.checkValue(good))
self... | identifier_body |
TestValidator_float.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 ... | # KIND, either express or implied. See the License for the *
# specific language governing permissions and limitations *
# under the License.
import unittest
from etch.python.Types import *
from etch.binding.support.Validator_float import *
from etch.binding.transport.fmt.TypeCode import *
class Test_Etc... | # *
# Unless required by applicable law or agreed to in writing, *
# software distributed under the License is distributed on an *
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * | random_line_split |
paste.tsx | import * as React from "react";
interface Props {
size: number;
color: string;
}
export default function PasteIcon(props: Props) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width={props.size}
height={props.size}
viewBox="0 0 24 24"
> | strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
fill="none"
>
<path d="M12.513 13.5h9l2 2v8h-11zM9.513 23.5h-9v-20h4M12.513 3.5h4v7" />
<path d="M10.513 2.5c0-1.104-.895-2-2-2-1.104 0-2 .896-2 2h-2v4h8v-4h-2zM14.513 10.5v-5h-2M4.513 5.5h-2v15h7M14... | <g
stroke={props.color} | random_line_split |
paste.tsx | import * as React from "react";
interface Props {
size: number;
color: string;
}
export default function | (props: Props) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width={props.size}
height={props.size}
viewBox="0 0 24 24"
>
<g
stroke={props.color}
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
fill="none"
>
... | PasteIcon | identifier_name |
paste.tsx | import * as React from "react";
interface Props {
size: number;
color: string;
}
export default function PasteIcon(props: Props) | }
PasteIcon.defaultProps = {
size: 18,
color: "#fff",
};
| {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width={props.size}
height={props.size}
viewBox="0 0 24 24"
>
<g
stroke={props.color}
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
fill="none"
>
<path d="... | identifier_body |
mod.rs | use iron::prelude::*;
use mount::Mount;
use config::CONFIG;
mod handlers;
pub fn | () {
let mut mount = Mount::new();
mount.mount("/pullrequests/",
router!(get "/" => handlers::pull_requests));
mount.mount("/issues/", router!(get "/" => handlers::issues));
mount.mount("/buildbots/", router!(get "/" => handlers::buildbots));
mount.mount("/releases/", router!(get "/... | serve | identifier_name |
mod.rs | use iron::prelude::*;
use mount::Mount;
use config::CONFIG;
mod handlers;
pub fn serve() | let server_addr = format!("0.0.0.0:{}", CONFIG.server_port);
info!("Starting API server running at {}", &server_addr);
Iron::new(chain).http(&*server_addr).unwrap();
}
| {
let mut mount = Mount::new();
mount.mount("/pullrequests/",
router!(get "/" => handlers::pull_requests));
mount.mount("/issues/", router!(get "/" => handlers::issues));
mount.mount("/buildbots/", router!(get "/" => handlers::buildbots));
mount.mount("/releases/", router!(get "/" =... | identifier_body |
mod.rs | use iron::prelude::*;
use mount::Mount;
use config::CONFIG;
mod handlers;
pub fn serve() {
let mut mount = Mount::new();
mount.mount("/pullrequests/",
router!(get "/" => handlers::pull_requests));
mount.mount("/issues/", router!(get "/" => handlers::issues));
mount.mount("/buildbots/... | } | info!("Starting API server running at {}", &server_addr);
Iron::new(chain).http(&*server_addr).unwrap(); | random_line_split |
root.service.ts | import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { GeoLocation } from '../models/geolocation'; | import * as io from 'socket.io-client';
@Injectable()
export class RootService {
private _ipaddress: string;
private socket = io(window.location.origin);
constructor(private http: Http) {
// this.socket = io('https://localhost:3001');
}
getIpAddress(){
return this.http
... | random_line_split | |
root.service.ts | import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { GeoLocation } from '../models/geolocation';
import * as io from 'socket.io-client';
@Injectable()
export class RootService {
private _ipaddress: string;
private socket = io(window.location.origin);
| (private http: Http) {
// this.socket = io('https://localhost:3001');
}
getIpAddress(){
return this.http
.get("//jsonip.com/")
.map((res:Response) => this.setIp(res.json()));
}
getUserLocation(callback){
if (navigator.geolocation) {
navigato... | constructor | identifier_name |
root.service.ts | import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { GeoLocation } from '../models/geolocation';
import * as io from 'socket.io-client';
@Injectable()
export class RootService {
private _ipaddress: string;
private socket = io(window.location.origin);
c... |
}
setIp(resp){
this._ipaddress = resp.ip;
}
getIp(){
return this._ipaddress;
}
getSocketIO(){
return this.socket;
}
} | {
var location = new GeoLocation();
location.latitude = 34.05;
location.longitude = -117.19;
callback(location);
} | conditional_block |
pie-chart.component.ts | // Copyright 2014 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by ap... |
});
$scope.$watch('data()', redrawChart);
ctrl.resizeSubscription = WindowDimensionsService.getResizeEvent()
.subscribe(evt => {
redrawChart();
$scope.$applyAsync();
});
};
ctrl.$onDestroy = function() {
if (ctrl.resizeSubscription) {
ctrl.... | {
chart = new google.visualization.PieChart($element[0]);
redrawChart();
$scope.$applyAsync();
} | conditional_block |
pie-chart.component.ts | // Copyright 2014 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by ap... | },
pieSliceBorderColor: options.pieSliceBorderColor,
pieSliceText: 'none',
chartArea: {
left: options.left,
width: options.chartAreaWidth
},
colors: options.colors,
height: options.height,
legend:... | pieHole: options.pieHole,
pieSliceTextStyle: {
color: options.pieSliceTextStyleColor, | random_line_split |
atari.js | define(['src/components/cpu', 'src/components/memory'], function(CPU, Memory) {
var Atari;
Atari = {
CPU: CPU,
Memory: Memory,
init: function init() {
this.attachMemory();
},
attachMemory: function attachMemory() {
CPU.memory = Memory;
}
... | 0xB9, 0x02, 0x00, // LDA $02,Y
0xA1, 0x09, // LDA ($09,X)
0xB1, 0x0A // LDA ($0A),Y
];
return Atari;
}); | 0xA0, 0x02, // LDY #$02
0xA9, 0x69, // LDA #$69
0xAD, 0x00, 0x00, // LDA $00
0xAD, 0x01, 0x00, // LDA $0001
0xBD, 0x01, 0x00, // LDA $01,X | random_line_split |
state_set.rs | use ena::unify::{UnifyKey, UnifyValue};
use lr1::lane_table::table::context_set::{ContextSet, OverlappingLookahead};
/// The unification key for a set of states in the lane table
/// algorithm. Each set of states is associated with a
/// `ContextSet`. When two sets of states are merged, their conflict
/// sets are me... | // (for example, we could have each state set be associated with an
// index that maps to a `ContextSet`), and do the merging ourselves.
// But this is easier for now, and cloning a `ContextSet` isn't THAT
// expensive, right? :)
impl UnifyValue for ContextSet {
type Error = (Self, Self);
fn unify_values(value... | // FIXME: The `ena` interface is really designed around `UnifyValue`
// being cheaply cloneable; we should either refactor `ena` a bit or
// find some other way to associate a `ContextSet` with a state set | random_line_split |
state_set.rs | use ena::unify::{UnifyKey, UnifyValue};
use lr1::lane_table::table::context_set::{ContextSet, OverlappingLookahead};
/// The unification key for a set of states in the lane table
/// algorithm. Each set of states is associated with a
/// `ContextSet`. When two sets of states are merged, their conflict
/// sets are me... | {
index: u32,
}
impl UnifyKey for StateSet {
type Value = ContextSet;
fn index(&self) -> u32 {
self.index
}
fn from_index(u: u32) -> Self {
StateSet { index: u }
}
fn tag() -> &'static str {
"StateSet"
}
}
// FIXME: The `ena` interface is really designed aro... | StateSet | identifier_name |
state_set.rs | use ena::unify::{UnifyKey, UnifyValue};
use lr1::lane_table::table::context_set::{ContextSet, OverlappingLookahead};
/// The unification key for a set of states in the lane table
/// algorithm. Each set of states is associated with a
/// `ContextSet`. When two sets of states are merged, their conflict
/// sets are me... |
fn from_index(u: u32) -> Self {
StateSet { index: u }
}
fn tag() -> &'static str {
"StateSet"
}
}
// FIXME: The `ena` interface is really designed around `UnifyValue`
// being cheaply cloneable; we should either refactor `ena` a bit or
// find some other way to associate a `ContextSe... | {
self.index
} | identifier_body |
DropdownMenu.tsx | import React, {SFC} from 'react'
import {Link} from 'react-router'
import classnames from 'classnames'
import {DROPDOWN_MENU_MAX_HEIGHT} from 'src/shared/constants/index'
import FancyScrollbar from 'src/shared/components/fancy_scrollbar/FancyScrollbar'
import DropdownMenuItem from 'src/shared/components/DropdownMenuIt... | onHighlight?: OnHighlightHandler
highlightedItemIndex?: number
}
const DropdownMenu: SFC<Props> = ({
items,
addNew,
actions,
selected,
onAction,
menuClass,
menuWidth,
menuLabel,
onSelection,
onHighlight,
useAutoComplete,
highlightedItemIndex,
}) => {
return (
<ul
className={clas... | onSelection?: OnSelectionHandler | random_line_split |
index.js | 'use strict'
var opbeat = require('opbeat').start()
var fs = require('fs')
var http = require('http')
var handlebars = require('handlebars')
var afterAll = require('after-all')
var AWS = require('aws-sdk')
var s3 = new AWS.S3()
var tmpl = handlebars.compile(fs.readFileSync('index.handlebars').toString())
var BUCKET =... |
return doc
})
})
}
function fetchKeys (cb) {
s3.listObjects({ Bucket: BUCKET }, function (err, data) {
if (err) return cb(err)
var keys = data.Contents
.sort(function (a, b) {
return b.LastModified.getTime() - a.LastModified.getTime()
})
.map(function (obj) {
r... | {
console.log('Caching document name for %s...', key)
var done = next()
var params = { Bucket: BUCKET, Key: key }
s3.headObject(params, function (err, data) {
if (err) return done(err)
doc.name = names[key] = data.Metadata.name || key
done()
})
... | conditional_block |
index.js | 'use strict'
var opbeat = require('opbeat').start()
var fs = require('fs')
var http = require('http')
var handlebars = require('handlebars')
var afterAll = require('after-all')
var AWS = require('aws-sdk')
var s3 = new AWS.S3()
var tmpl = handlebars.compile(fs.readFileSync('index.handlebars').toString())
var BUCKET =... | (cb) {
fetchKeys(function (err, keys) {
if (err) return cb(err)
var next = afterAll(function (err) {
if (err) return cb(err)
cb(null, docs)
})
var docs = keys.map(function (key) {
var doc = { key: key, name: names[key] }
if (!doc.name) {
console.log('Caching documen... | fetchDocuments | identifier_name |
index.js | 'use strict'
var opbeat = require('opbeat').start()
var fs = require('fs')
var http = require('http')
var handlebars = require('handlebars')
var afterAll = require('after-all')
var AWS = require('aws-sdk')
var s3 = new AWS.S3()
var tmpl = handlebars.compile(fs.readFileSync('index.handlebars').toString())
var BUCKET =... | })
cb(null, keys)
})
} | return obj.Key | random_line_split |
index.js | 'use strict'
var opbeat = require('opbeat').start()
var fs = require('fs')
var http = require('http')
var handlebars = require('handlebars')
var afterAll = require('after-all')
var AWS = require('aws-sdk')
var s3 = new AWS.S3()
var tmpl = handlebars.compile(fs.readFileSync('index.handlebars').toString())
var BUCKET =... | })
}
return doc
})
})
}
function fetchKeys (cb) {
s3.listObjects({ Bucket: BUCKET }, function (err, data) {
if (err) return cb(err)
var keys = data.Contents
.sort(function (a, b) {
return b.LastModified.getTime() - a.LastModified.getTime()
})
.map(functio... | {
fetchKeys(function (err, keys) {
if (err) return cb(err)
var next = afterAll(function (err) {
if (err) return cb(err)
cb(null, docs)
})
var docs = keys.map(function (key) {
var doc = { key: key, name: names[key] }
if (!doc.name) {
console.log('Caching document name... | identifier_body |
document_renderer.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import os
from document_parser import ParseDocument
from third_party.json_schema_compiler.model import UnixName
class DocumentRenderer(objec... |
def _RenderLinks(self, document, path):
''' Replaces all $(ref:...) references in |document| with html links.
References have two forms:
$(ref:api.node) - Replaces the reference with a link to node on the
API page. The title is set to the name of the node.
... | self._table_of_contents_renderer = table_of_contents_renderer
self._ref_resolver = ref_resolver | identifier_body |
document_renderer.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import os
from document_parser import ParseDocument
from third_party.json_schema_compiler.model import UnixName
class DocumentRenderer(objec... | cursor_index = 0
start_ref_index = document.find(START_REF)
while start_ref_index != -1:
end_ref_index = document.find(END_REF, start_ref_index)
if (end_ref_index == -1 or
end_ref_index - start_ref_index > MAX_REF_LENGTH):
end_ref_index = document.find(' ', start_ref_index)
... | # Keeps track of position within |document| | random_line_split |
document_renderer.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import os
from document_parser import ParseDocument
from third_party.json_schema_compiler.model import UnixName
class DocumentRenderer(objec... | (self, document, path, render_title=False):
# Render links first so that parsing and later replacements aren't
# affected by $(ref...) substitutions
document = self._RenderLinks(document, path)
parsed_document = ParseDocument(document, expect_title=render_title)
toc_text, toc_warnings = self._table... | Render | identifier_name |
document_renderer.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import os
from document_parser import ParseDocument
from third_party.json_schema_compiler.model import UnixName
class DocumentRenderer(objec... |
return (document.replace('$(table_of_contents)', toc_text, 1),
parsed_document.warnings + toc_warnings)
| document = document.replace('$(title)', parsed_document.title, 1) | conditional_block |
regions-ret-borrowed.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {
let x = return_it();
println!("foo={}", *x);
}
| {
with(|o| o) //~ ERROR mismatched types
//~^ ERROR lifetime of return value does not outlive the function call
//~^^ ERROR cannot infer
} | identifier_body |
regions-ret-borrowed.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | fn with<R>(f: |x: &int| -> R) -> R {
f(&3)
}
fn return_it<'a>() -> &'a int {
with(|o| o) //~ ERROR mismatched types
//~^ ERROR lifetime of return value does not outlive the function call
//~^^ ERROR cannot infer
}
fn main() {
let x = return_it();
println!("foo={}", *x);
} | // provides a value that is only good within its own stack frame. This
// used to successfully compile because we failed to account for the
// fact that fn(x: &int) rebound the region &.
| random_line_split |
regions-ret-borrowed.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>() -> &'a int {
with(|o| o) //~ ERROR mismatched types
//~^ ERROR lifetime of return value does not outlive the function call
//~^^ ERROR cannot infer
}
fn main() {
let x = return_it();
println!("foo={}", *x);
}
| return_it | identifier_name |
product.socket.js | "use strict";
/**
* Broadcast updates to client when the model changes
*/
Object.defineProperty(exports, "__esModule", { value: true });
var product_events_1 = require("./product.events");
// Model events to emit
var events = ['save', 'remove'];
function register(socket) {
// Bind model events to socket events
... |
//# sourceMappingURL=product.socket.js.map | {
return function () {
product_events_1.default.removeListener(event, listener);
};
} | identifier_body |
product.socket.js | "use strict";
/**
* Broadcast updates to client when the model changes
*/
Object.defineProperty(exports, "__esModule", { value: true });
var product_events_1 = require("./product.events");
// Model events to emit
var events = ['save', 'remove'];
function register(socket) {
// Bind model events to socket events
... | (event, listener) {
return function () {
product_events_1.default.removeListener(event, listener);
};
}
//# sourceMappingURL=product.socket.js.map | removeListener | identifier_name |
product.socket.js | "use strict"; | /**
* Broadcast updates to client when the model changes
*/
Object.defineProperty(exports, "__esModule", { value: true });
var product_events_1 = require("./product.events");
// Model events to emit
var events = ['save', 'remove'];
function register(socket) {
// Bind model events to socket events
for (var i =... | random_line_split | |
product.socket.js | "use strict";
/**
* Broadcast updates to client when the model changes
*/
Object.defineProperty(exports, "__esModule", { value: true });
var product_events_1 = require("./product.events");
// Model events to emit
var events = ['save', 'remove'];
function register(socket) {
// Bind model events to socket events
... |
}
exports.register = register;
function createListener(event, socket) {
return function (doc) {
socket.emit(event, doc);
};
}
function removeListener(event, listener) {
return function () {
product_events_1.default.removeListener(event, listener);
};
}
//# sourceMappingURL=product.socke... | {
var event = events[i];
var listener = createListener('product:' + event, socket);
product_events_1.default.on(event, listener);
socket.on('disconnect', removeListener(event, listener));
} | conditional_block |
config.rs | _edition) {
feature.set(&mut features, DUMMY_SP);
edition_enabled_features.insert(feature.name, crate_edition);
}
// Process the edition umbrella feature-gates first, to ensure
// `edition_enabled_features` is completed before it's queried.
for attr in krate_attrs {
if !attr.has... | data.attrs = attrs.into();
if self.in_cfg(&data.attrs) {
data.tokens = LazyTokenStream::new(
self.configure_tokens(&data.tokens.create_token_stream()),
);
Some((AttrAnnotatedToken... | .iter()
.flat_map(|(tree, spacing)| match tree.clone() {
AttrAnnotatedTokenTree::Attributes(mut data) => {
let mut attrs: Vec<_> = std::mem::take(&mut data.attrs).into();
attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr)); | random_line_split |
config.rs | Some(node)
} else {
None
}
}
fn try_configure_tokens<T: AstLike>(&mut self, node: &mut T) {
if self.config_tokens {
if let Some(Some(tokens)) = node.tokens_mut() {
let attr_annotated_tokens = tokens.create_token_stream();
*tokens ... | {
for attr in expr.attrs.iter() {
self.maybe_emit_expr_attr_err(attr);
}
// If an expr is valid to cfg away it will have been removed by the
// outer stmt or expression folder before descending in here.
// Anything else is always required, and thus has to error out
... | identifier_body | |
config.rs | _edition) {
feature.set(&mut features, DUMMY_SP);
edition_enabled_features.insert(feature.name, crate_edition);
}
// Process the edition umbrella feature-gates first, to ensure
// `edition_enabled_features` is completed before it's queried.
for attr in krate_attrs {
if !attr.has... |
let removed = REMOVED_FEATURES.iter().find(|f| name == f.name);
let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.name);
if let Some(Feature { state, .. }) = removed.or(stable_removed) {
if let FeatureState::Removed { reason } | FeatureState::St... | {
// Handled in the separate loop above.
continue;
} | conditional_block |
config.rs | else {
None
}
}
fn try_configure_tokens<T: AstLike>(&mut self, node: &mut T) {
if self.config_tokens {
if let Some(Some(tokens)) = node.tokens_mut() {
let attr_annotated_tokens = tokens.create_token_stream();
*tokens = LazyTokenStream::ne... | parse_cfg | identifier_name | |
resource_thread.rs | (start_chan, metadata)
}
/// For use by loaders in responding to a Load message.
/// It takes an optional NetworkError, so that we can extract the SSL Validation errors
/// and take it to the HTML parser
fn start_sending_opt(start_chan: LoadConsumer, metadata: Metadata) -> Result<ProgressSender, ()> {
match start_... | AuthCache {
version: 1,
entries: HashMap::new()
} | random_line_split | |
resource_thread.rs | progress_port: progress_port,
});
match result {
Ok(_) => Ok(ProgressSender::Channel(progress_chan)),
Err(_) => Err(())
}
}
}
}
/// Returns a tuple of (public, private) senders to the new threads.
pub fn new_resource_thread... | new | identifier_name | |
resource_thread.rs | hsts_list: Arc<RwLock<HstsList>>,
connector: Arc<Pool<Connector>>,
}
impl ProgressSender {
//XXXjdm return actual error
pub fn send(&self, msg: ProgressMsg) -> Result<(), ()> {
match *self {
ProgressSender::Channel(ref c) => c.send(msg).map_err(|_| ()),
}
}
}
pub fn sen... | });
let (toplevel, sublevel) = classifier.classify(context,
no_sniff,
check_for_apache_bug,
&supplied_type,
... | {
if PREFS.get("network.mime.sniff").as_boolean().unwrap_or(false) {
// TODO: should be calculated in the resource loader, from pull requeset #4094
let mut no_sniff = NoSniffFlag::Off;
let mut check_for_apache_bug = ApacheBugFlag::Off;
if let Some(ref headers) = metadata.headers {
... | identifier_body |
compositing.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/. */
#![crate_id = "github.com/mozilla/servo#compositing:0.1"]
#![crate_type = "lib"]
#![crate_type = "dylib"]
#![crate... | #[phase(plugin, link)]
extern crate log;
extern crate debug;
extern crate alert;
extern crate azure;
extern crate geom;
extern crate gfx;
#[cfg(not(target_os="android"))]
extern crate glfw;
#[cfg(target_os="android")]
extern crate glut;
extern crate layers;
extern crate layout;
extern crate opengles;
extern crate png... | random_line_split | |
common.ts | /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the 'License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
/**
* @fileoverview Common interfaces for the tensorflow graph vi... | distributed under the License is distributed on an 'AS IS' BASIS, | random_line_split |
lib.rs | use std::path::Path;
use binary::{
async_trait::async_trait,
binary_clone_box,
eyre::{bail, Result},
};
pub use binary::{Binary, BinaryInstallation, BinaryTrait};
mod versions;
pub struct NodeBinary;
#[async_trait]
impl BinaryTrait for NodeBinary {
#[rustfmt::skip]
fn spec(&self) -> Binary {
... | (&self, _os: &str) -> Result<Vec<String>> {
Ok(self.versions_update_maybe(
versions::VERSIONS,
self.versions_github_releases("nodejs", "node").await,
))
}
async fn install_version(
&self,
version: &str,
dest: &Path,
os: &str,
arch:... | versions | identifier_name |
lib.rs | use std::path::Path;
use binary::{
async_trait::async_trait,
binary_clone_box,
eyre::{bail, Result},
};
pub use binary::{Binary, BinaryInstallation, BinaryTrait};
mod versions;
pub struct NodeBinary;
#[async_trait]
impl BinaryTrait for NodeBinary {
#[rustfmt::skip]
fn spec(&self) -> Binary |
binary_clone_box!();
async fn versions(&self, _os: &str) -> Result<Vec<String>> {
Ok(self.versions_update_maybe(
versions::VERSIONS,
self.versions_github_releases("nodejs", "node").await,
))
}
async fn install_version(
&self,
version: &str,
... | {
Binary::new(
"node",
&[],
&["C:\\Program Files\\nodejs"]
)
} | identifier_body |
lib.rs | use std::path::Path;
use binary::{
async_trait::async_trait,
binary_clone_box,
eyre::{bail, Result},
};
pub use binary::{Binary, BinaryInstallation, BinaryTrait};
mod versions;
pub struct NodeBinary;
#[async_trait]
impl BinaryTrait for NodeBinary {
#[rustfmt::skip]
fn spec(&self) -> Binary {
... | arch: &str,
) -> Result<()> {
let url = format!(
"https://nodejs.org/dist/v{version}/node-v{version}-",
version = version
) + match os {
"macos" => match arch {
"arm" => "darwin-arm64.tar.gz",
_ => "darwin-x64.tar.gz",
... | random_line_split | |
lib.rs | //! details on the API, please see the documentation for the `Regex` type.
//!
//! # First example: find a date
//!
//! General use of regular expressions in this package involves compiling an
//! expression and then using it to search, split or replace text. For example,
//! to confirm that some text resembles a date:... | //! has excellent worst case performance. The specific syntax supported is
//! documented further down.
//!
//! This crate's documentation provides some simple examples, describes Unicode
//! support and exhaustively lists the supported syntax. For more specific | random_line_split | |
single_byte_xor_cipher.py | from binascii import unhexlify
from pprint import pprint
from xor import xor
def get_possible_keys(ciphertext):
key_len = len(ciphertext) // 2
# Generate list of potential keys
possible_keys = []
for i in range(256):
hex_num = hex(i).split('x')[1].zfill(2)
possible_keys.append(hex_num... |
def mostly_letters_rank(plaintexts, additional_allowed_chars=[" "]):
"""Return a list of (plaintext, rank) tuples where the higher the rank,
the less non-letter characters are in the plaintext
"""
ranked_plaintexts = []
for plaintext in plaintexts:
letter_count = 0
for byte in ... | """Return True if char_code is a letter character code from the ASCII
table. Otherwise return False.
"""
if isinstance(char_code, str) or isinstance(char_code, bytes):
char_code = ord(char_code)
if char_code >= 65 and char_code <= 90: # uppercase letters
return True
if char_code ... | identifier_body |
single_byte_xor_cipher.py | from binascii import unhexlify
from pprint import pprint
from xor import xor
def get_possible_keys(ciphertext):
key_len = len(ciphertext) // 2
# Generate list of potential keys
possible_keys = []
for i in range(256):
hex_num = hex(i).split('x')[1].zfill(2)
possible_keys.append(hex_num... |
def mostly_letters_rank(plaintexts, additional_allowed_chars=[" "]):
"""Return a list of (plaintext, rank) tuples where the higher the rank,
the less non-letter characters are in the plaintext
"""
ranked_plaintexts = []
for plaintext in plaintexts:
letter_count = 0
for byte in p... | return False | random_line_split |
single_byte_xor_cipher.py | from binascii import unhexlify
from pprint import pprint
from xor import xor
def | (ciphertext):
key_len = len(ciphertext) // 2
# Generate list of potential keys
possible_keys = []
for i in range(256):
hex_num = hex(i).split('x')[1].zfill(2)
possible_keys.append(hex_num * key_len)
return possible_keys
def get_possible_plaintexts(ciphertext, keys):
plaintexts... | get_possible_keys | identifier_name |
single_byte_xor_cipher.py | from binascii import unhexlify
from pprint import pprint
from xor import xor
def get_possible_keys(ciphertext):
key_len = len(ciphertext) // 2
# Generate list of potential keys
possible_keys = []
for i in range(256):
|
return possible_keys
def get_possible_plaintexts(ciphertext, keys):
plaintexts = []
for key in keys:
plaintext = unhexlify(xor(ciphertext, key))
plaintexts.append(plaintext)
return plaintexts
def printable_characters_rank(plaintexts):
"""Return a list of (plaintext, rank) tupl... | hex_num = hex(i).split('x')[1].zfill(2)
possible_keys.append(hex_num * key_len) | conditional_block |
strings.js | "generalSettings": {
"tabTitle": "Ustawienia ogólne",
"measurementUnitLabel": "Jednostka miary",
"currencyLabel": "Symbol miary",
"roundCostLabel": "Zaokrąglaj koszt",
"projectOutputSettings": "Ustawienia wynikowe projektu",
"typeOfProjectAreaLabel": "Typ obszaru projektu",
"bufferDistance... | define({
"configText": "Ustaw tekst konfiguracyjny:", | random_line_split | |
xlsx-util.ts | date. */
date: Date
/** the comment for this file. */
comment: string
/** The UNIX permissions of the file, if any. 16 bits number. */
unixPermissions: number
/** The DOS permissions of the file, if any. 6 bits number. */
dosPermissions: number
/** the options of the file. The available options. */
... |
return false
})
}
return name
}
/**
* Get a sheet data.
* @param zip Extract data of XLSX (Zip) file.
* @param index Index of sheet. Range of from 1 to XlsxExtractor.count.
* @returns Sheet data.
*/
export const getSheetData = async (
zip: ZipObject,
index: number
): Promise<SheetData> => {
... | {
name = sheet.$.name || ''
return true
} | conditional_block |
xlsx-util.ts | modification date. */
date: Date
/** the comment for this file. */
comment: string
/** The UNIX permissions of the file, if any. 16 bits number. */
unixPermissions: number
/** The DOS permissions of the file, if any. 6 bits number. */
dosPermissions: number
/** the options of the file. The available o... | * @return Column number, otherwise -1.
*/
export const numOfColumn = (text: string): number => {
const letters = [
'',
'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'I',
'J',
'K',
'L',
'M',
'N',
'O',
'P',
'Q',
'R',
'S',
'T',
'U',
... | }
/**
* Convert the column text to number.
* @param text Column text, such as A" and "AA". | random_line_split |
ident.rs | // Copyright 2013-2014 The Algebra Developers.
//
// 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... |
use ops::{Op, Additive, Multiplicative};
/// A type that is equipped with identity.
pub trait Identity<O: Op> {
/// The identity element.
fn id() -> Self;
}
/// The identity element.
pub fn id<T: Identity<O>, O: Op>(_: O) -> T {
Identity::id()
}
impl_ident!(Additive; 0; u8, u16, u32, u64, i8, i16, i32, ... |
//! Identities for binary operators. | random_line_split |
ident.rs | // Copyright 2013-2014 The Algebra Developers.
//
// 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... | <T: Identity<O>, O: Op>(_: O) -> T {
Identity::id()
}
impl_ident!(Additive; 0; u8, u16, u32, u64, i8, i16, i32, i64);
impl_ident!(Additive; 0.; f32, f64);
impl_ident!(Multiplicative; 1; u8, u16, u32, u64, i8, i16, i32, i64);
impl_ident!(Multiplicative; 1.; f32, f64);
| id | identifier_name |
ident.rs | // Copyright 2013-2014 The Algebra Developers.
//
// 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... |
impl_ident!(Additive; 0; u8, u16, u32, u64, i8, i16, i32, i64);
impl_ident!(Additive; 0.; f32, f64);
impl_ident!(Multiplicative; 1; u8, u16, u32, u64, i8, i16, i32, i64);
impl_ident!(Multiplicative; 1.; f32, f64);
| {
Identity::id()
} | identifier_body |
z-migrate-base-data.js |
module.exports = function(app){
var Rx = require('rxjs/Rx');
var emptyResult = (data) => { //see person.js for other usage
return Array.isArray(data) && data.length == 0;
}
var testAddModels = function(modelName,callback){
addModels(modelName).subscribe(app.observable.concatAndFinalize(... | else {
//if no models found in db, create them
console.log(modelName+' was not found in the database, creating...');
let newInstances = require(process.env.MIGRATE_HOME+modelName+'.json');
console.log('reading instances from: '+process.env.MIGRATE_HOME+modelName+'.json');
... | {
return Rx.Observable.from(results);
} | conditional_block |
z-migrate-base-data.js | module.exports = function(app){
var Rx = require('rxjs/Rx');
var emptyResult = (data) => { //see person.js for other usage
return Array.isArray(data) && data.length == 0;
}
var testAddModels = function(modelName,callback){
addModels(modelName).subscribe(app.observable.concatAndFinalize(c... | } //end of module | random_line_split | |
group-forms-csv.component.ts | import { Breadcrumb } from './../../shared/_components/breadcrumb/breadcrumb.component';
import { Component, OnInit, AfterViewInit, ElementRef, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { GroupsService } from '../services/groups.service';
import { UserService } f... | () {
const config = await this.serverConfig.getServerConfig()
const appendedForms = [
{id: 'participant',title:_TRANSLATE('Participant')},
{id: 'event-form',title:_TRANSLATE('Event Form')},
{id: 'case-event',title: _TRANSLATE('Case Event')}];
this.forms = (await this.tangerineForms.getForm... | getForms | identifier_name |
group-forms-csv.component.ts | import { Breadcrumb } from './../../shared/_components/breadcrumb/breadcrumb.component';
import { Component, OnInit, AfterViewInit, ElementRef, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { GroupsService } from '../services/groups.service';
import { UserService } f... |
this.activeForms = this.forms.filter(form => !form.archived);
this.archivedForms = this.forms.filter(form => form.archived);
}
}
| {
this.forms = [...this.forms, ...appendedForms]
} | conditional_block |
group-forms-csv.component.ts | import { Breadcrumb } from './../../shared/_components/breadcrumb/breadcrumb.component';
import { Component, OnInit, AfterViewInit, ElementRef, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { GroupsService } from '../services/groups.service';
import { UserService } f... |
async ngOnInit() {
this.breadcrumbs = [
<Breadcrumb>{
label: _TRANSLATE('Download CSVs'),
url: 'download-csv'
}
]
this.route.params.subscribe(async params => {
this.groupId = params.groupId;
this.group = await this.groupsService.getGroupInfo(this.groupId);
t... | { } | identifier_body |
group-forms-csv.component.ts | import { Breadcrumb } from './../../shared/_components/breadcrumb/breadcrumb.component';
import { Component, OnInit, AfterViewInit, ElementRef, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { GroupsService } from '../services/groups.service';
import { UserService } f... | private errorHandler: TangyErrorHandler,
private serverConfig: ServerConfigService,
private router: Router,
private http: HttpClient
) { }
async ngOnInit() {
this.breadcrumbs = [
<Breadcrumb>{
label: _TRANSLATE('Download CSVs'),
url: 'download-csv'
}
]
this.r... | private tangerineForms: TangerineFormsService, | random_line_split |
_isyclimate.py | """
This is a subfile for IsyClass.py
These funtions are accessable via the Isy class opj
"""
__author__ = 'Peter Shipley <peter.shipley@gmail.com>'
__copyright__ = "Copyright (C) 2013 Peter Shipley"
__license__ = "BSD"
import time
##
## Climate funtions
##
def | (self):
""" Load climate data from ISY device
args: none
internal function call
"""
if self.debug & 0x01:
print("load_clim")
clim_tree = self._getXMLetree("/rest/climate")
self.climateinfo = dict()
if clim_tree is None:
return
# Isy._printXML(self.climatein... | load_clim | identifier_name |
_isyclimate.py | """
This is a subfile for IsyClass.py
These funtions are accessable via the Isy class opj
"""
__author__ = 'Peter Shipley <peter.shipley@gmail.com>'
__copyright__ = "Copyright (C) 2013 Peter Shipley"
__license__ = "BSD"
import time
##
## Climate funtions |
def load_clim(self):
""" Load climate data from ISY device
args: none
internal function call
"""
if self.debug & 0x01:
print("load_clim")
clim_tree = self._getXMLetree("/rest/climate")
self.climateinfo = dict()
if clim_tree is None:
return
# Isy._printXML... | ## | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.