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 |
|---|---|---|---|---|
snippet-extractor.ts | declare var require;
import {SnippetInjector} from "./snippet-injector";
var fs = require("fs");
var path = require("path");
export class SnippetExtractor extends SnippetInjector {
public targetDir: string = null;
private fileForSnippet(id: string) {
return path.join(this.targetDir, id) + ".json";
... | fs.writeFileSync(snippetPath, JSON.stringify(snippetData, null, " "));
}
} | }
snippetData[this.keyForExtension(fileExtension)] = snippet; | random_line_split |
snippet-extractor.ts | declare var require;
import {SnippetInjector} from "./snippet-injector";
var fs = require("fs");
var path = require("path");
export class SnippetExtractor extends SnippetInjector {
public targetDir: string = null;
private fileForSnippet(id: string) {
return path.join(this.targetDir, id) + ".json";
... |
protected addSnippet(fileExtension: string, id: string, snippet: string): void {
let snippetPath = this.fileForSnippet(id);
let snippetData = {};
if (fs.existsSync(snippetPath)) {
const contents = fs.readFileSync(snippetPath, "utf8");
snippetData = JSON.parse(conten... | {
let snippetPath = this.fileForSnippet(id);
let snippetData = {};
if (fs.existsSync(snippetPath)) {
const contents = fs.readFileSync(snippetPath, "utf8");
snippetData = JSON.parse(contents);
}
if (snippetData[this.keyForExtension(fileExtension)]) {
... | identifier_body |
multiple_files.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {
let args: Vec<String> = env::args().collect();
let rustc = &args[1];
let tmpdir = Path::new(&args[2]);
let main_file = tmpdir.join("unicode_input_multiple_files_main.rs");
{
let _ = File::create(&main_file).unwrap()
.write_all(b"mod unicode_input_multiple_files_cha... | {
let mut rng = thread_rng();
// a subset of the XID_start Unicode table (ensuring that the
// compiler doesn't fail with an "unrecognised token" error)
let (lo, hi): (u32, u32) = match rng.gen_range(1u32, 4u32 + 1) {
1 => (0x41, 0x5a),
2 => (0xf8, 0x1ba),
3 => (0x1401, 0x166c),
... | identifier_body |
multiple_files.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | let rustc = &args[1];
let tmpdir = Path::new(&args[2]);
let main_file = tmpdir.join("unicode_input_multiple_files_main.rs");
{
let _ = File::create(&main_file).unwrap()
.write_all(b"mod unicode_input_multiple_files_chars;").unwrap();
}
for _ in 0..100 {
{
... | }
fn main() {
let args: Vec<String> = env::args().collect(); | random_line_split |
multiple_files.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let args: Vec<String> = env::args().collect();
let rustc = &args[1];
let tmpdir = Path::new(&args[2]);
let main_file = tmpdir.join("unicode_input_multiple_files_main.rs");
{
let _ = File::create(&main_file).unwrap()
.write_all(b"mod unicode_input_multiple_files_chars;").unw... | main | identifier_name |
test_cube_to_pp.py | 64),
standard_name='time',
units='hours since epoch')
cube.add_aux_coord(coord)
self.assertCML(cube, ['cube_to_pp', 'no_forecast_time.cml'])
reference_txt_path = tests.get_result_path(('cube_to_pp', 'no_forecast_time.txt'... | (self):
GeogCS = iris.coord_systems.GeogCS
cube = iris.tests.stock.lat_lon_cube()
reference_txt | test_default_coord_system | identifier_name |
test_cube_to_pp.py | =cube) as temp_pp_path:
iris.save(cube, temp_pp_path) # Create file
iris.save(cube, temp_pp_path) # Replace file
def test_pp_append_lists(self):
# Test PP append saving - lists of cubes.
# For each of the first four time-steps in the 4D cube,
... | ll_cube = stock.lat_lon_cube()
ll_cube.attributes["ukmo__process_flags"] = descriptions
# Save cube to pp
temp_filename = iris.util.create_temp_filename(".pp")
iris.save(ll_cube, temp_filename)
# Check the lbproc is what we expect
... | conditional_block | |
test_cube_to_pp.py | _path:
iris.save(cubes[:2], temp_pp_path)
iris.save(cubes[2:], temp_pp_path)
def add_coords_to_cube_and_test(self, coord1, coord2):
# a wrapper for creating arbitrary 2d cross-sections and run pp-saving tests
dataarray = np.arange(16, dtype='>f4').reshape(4, 4)
cm = ... | self.assertEqual(field.lblev, lblev)
self.assertEqual(field.blev, blev)
def fields_from_cube(cubes): | random_line_split | |
test_cube_to_pp.py | 64),
standard_name='time',
units='hours since epoch')
cube.add_aux_coord(coord)
self.assertCML(cube, ['cube_to_pp', 'no_forecast_time.cml'])
reference_txt_path = tests.get_result_path(('cube_to_pp', 'no_forecast_time.txt'... |
class FakePPEnvironment(object):
''' fake a minimal PP environment for use in cross-section coords, as in PP save rules '''
y = [1, 2, 3, 4]
z = [111, 222, 333, 444]
y_bounds = [[0.9, 1.1], [1.9, 2.1], [2.9, 3.1], [3.9, 4.1]]
z_bounds = [[110.9, 111.1], [221.9, 222.1], [332.9, 333.1], [443.9, 444... | cube = stock.simple_pp()
new_unit = cf_units.Unit('hours since 1970-01-01 00:00:00',
calendar=cf_units.CALENDAR_365_DAY)
cube.coord('time').units = new_unit
# Add an extra "fill_value" property, as used by the save rules.
cube.fill_value = None
p... | identifier_body |
connector.py | # Copyright 2016 by Dai Trying
#
# This file is part of daixmms2client.
#
# daixmms2client is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your optio... | def toggleRead(self, bool_val):
self.rSock.setEnabled(bool_val)
def toggleWrite(self, bool_val):
self.wSock.setEnabled(bool_val)
def handleRead(self, i):
self.xmms.ioin()
def handleWrite(self, i):
self.xmms.ioout() | self.toggleWrite(False)
| random_line_split |
connector.py |
# Copyright 2016 by Dai Trying
#
# This file is part of daixmms2client.
#
# daixmms2client is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your opti... |
else:
self.toggleWrite(False)
def toggleRead(self, bool_val):
self.rSock.setEnabled(bool_val)
def toggleWrite(self, bool_val):
self.wSock.setEnabled(bool_val)
def handleRead(self, i):
self.xmms.ioin()
def handleWrite(self, i):
self.xmms.ioout()
| self.toggleWrite(True) | conditional_block |
connector.py |
# Copyright 2016 by Dai Trying
#
# This file is part of daixmms2client.
#
# daixmms2client is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your opti... | (self, i):
self.xmms.ioin()
def handleWrite(self, i):
self.xmms.ioout()
| handleRead | identifier_name |
connector.py |
# Copyright 2016 by Dai Trying
#
# This file is part of daixmms2client.
#
# daixmms2client is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your opti... | self.xmms.ioout() | identifier_body | |
utils.py | from django.template.loader import render_to_string
from oioioi.base.permissions import make_request_condition
from oioioi.programs.controllers import ProgrammingContestController
def render_head(requirements):
"""For a given list of paths for required files produces a HTML which
includes the paths. The ou... | (request):
controller = request.contest.controller
if not isinstance(controller, ProgrammingContestController):
return False
return bool(controller.statistics_available_plot_groups(request))
@make_request_condition
def can_see_stats(request):
return request.contest.controller.can_see_stats(req... | any_statistics_avaiable | identifier_name |
utils.py | from django.template.loader import render_to_string
from oioioi.base.permissions import make_request_condition
from oioioi.programs.controllers import ProgrammingContestController
def render_head(requirements):
"""For a given list of paths for required files produces a HTML which
includes the paths. The ou... |
for name in requirements:
if name not in unique:
unique.add(name)
ext = name.split('.')[-1].strip().lower()
if ext == 'css':
result += render_to_string('statistics/include_css.html',
{'file_name': prefix+name})
... | result = ''
prefix = '/static/' | random_line_split |
utils.py | from django.template.loader import render_to_string
from oioioi.base.permissions import make_request_condition
from oioioi.programs.controllers import ProgrammingContestController
def render_head(requirements):
"""For a given list of paths for required files produces a HTML which
includes the paths. The ou... |
@make_request_condition
def can_see_stats(request):
return request.contest.controller.can_see_stats(request)
| controller = request.contest.controller
if not isinstance(controller, ProgrammingContestController):
return False
return bool(controller.statistics_available_plot_groups(request)) | identifier_body |
utils.py | from django.template.loader import render_to_string
from oioioi.base.permissions import make_request_condition
from oioioi.programs.controllers import ProgrammingContestController
def render_head(requirements):
"""For a given list of paths for required files produces a HTML which
includes the paths. The ou... |
if ext == 'js':
result += render_to_string('statistics/include_js.html',
{'file_name': prefix+name})
return result
@make_request_condition
def any_statistics_avaiable(request):
controller = request.contest.controller
if not isinstance... | result += render_to_string('statistics/include_css.html',
{'file_name': prefix+name}) | conditional_block |
traffic.rs | use std::env;
use tokio::runtime::Runtime;
use hubcaps::traffic::TimeUnit;
use hubcaps::{Credentials, Github, Result};
fn | () -> Result<()> {
pretty_env_logger::init();
match env::var("GITHUB_TOKEN").ok() {
Some(token) => {
let mut rt = Runtime::new()?;
let github = Github::new(
concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")),
Credentials::Token(token),... | main | identifier_name |
traffic.rs | use std::env;
use tokio::runtime::Runtime;
use hubcaps::traffic::TimeUnit;
use hubcaps::{Credentials, Github, Result};
fn main() -> Result<()> {
pretty_env_logger::init();
match env::var("GITHUB_TOKEN").ok() {
Some(token) => | let views = rt.block_on(github.repo(owner, repo).traffic().views(TimeUnit::Day))?;
println!("{:#?}", views);
println!("Clones per day");
let clones = rt.block_on(github.repo(owner, repo).traffic().clones(TimeUnit::Day))?;
println!("{:#?}", clones);
... | {
let mut rt = Runtime::new()?;
let github = Github::new(
concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")),
Credentials::Token(token),
)?;
let owner = "softprops";
let repo = "hubcaps";
println!("Top ... | conditional_block |
traffic.rs | use std::env;
use tokio::runtime::Runtime;
use hubcaps::traffic::TimeUnit;
use hubcaps::{Credentials, Github, Result};
fn main() -> Result<()> | }
println!("Views per day");
let views = rt.block_on(github.repo(owner, repo).traffic().views(TimeUnit::Day))?;
println!("{:#?}", views);
println!("Clones per day");
let clones = rt.block_on(github.repo(owner, repo).traffic().clones(TimeUnit::Day... | {
pretty_env_logger::init();
match env::var("GITHUB_TOKEN").ok() {
Some(token) => {
let mut rt = Runtime::new()?;
let github = Github::new(
concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")),
Credentials::Token(token),
)?;
... | identifier_body |
traffic.rs | use std::env;
use tokio::runtime::Runtime;
use hubcaps::traffic::TimeUnit;
use hubcaps::{Credentials, Github, Result};
fn main() -> Result<()> {
pretty_env_logger::init(); | Credentials::Token(token),
)?;
let owner = "softprops";
let repo = "hubcaps";
println!("Top 10 referrers");
for referrer in rt.block_on(github.repo(owner, repo).traffic().referrers())? {
println!("{:#?}", referrer)
... | match env::var("GITHUB_TOKEN").ok() {
Some(token) => {
let mut rt = Runtime::new()?;
let github = Github::new(
concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")), | random_line_split |
index.js | 'use strict';
var path = require('path');
var gulp = require('gulp');
var gutil = require('gulp-util');
var _ = require('lodash');
var notify = require('gulp-notify');
var plumber = require('gulp-plumber');
var livereload = require('gulp-livereload');
var config = require('./config');
var loaded = [];
var ns = funct... | */
var LuminousGulp = function (name) {
var file = name.split(':')[0];
if (!_.includes(loaded, file)) {
loaded.push(file);
require(path.join(__dirname, 'tasks', file))(LuminousGulp);
}
return ns(name);
};
/**
* Get configuration.
*
* @param {string} path
* @return {Object}
*/
LuminousGulp.confi... | * @param {string} name
* @return {string} | random_line_split |
index.js | 'use strict';
var path = require('path');
var gulp = require('gulp');
var gutil = require('gulp-util');
var _ = require('lodash');
var notify = require('gulp-notify');
var plumber = require('gulp-plumber');
var livereload = require('gulp-livereload');
var config = require('./config');
var loaded = [];
var ns = funct... |
gulp.task(ns(name), deps.map(LuminousGulp), fn);
};
// Report file paths in the stream pipeline.
LuminousGulp.report = require('./report');
// https://www.npmjs.com/package/gulp-notify
LuminousGulp.notify = function (message) {
return notify({title: 'luminous-gulp', message: message});
};
LuminousGulp.onError = ... | {
fn = deps;
deps = [];
} | conditional_block |
defaults-fr_FR.min.js | /*!
* Bootstrap-select v1.13.14 (https://developer.snapappointments.com/bootstrap-select)
*
* Copyright 2012-2020 SnapAppointments, LLC
* Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE)
*/
| !function(e,t){void 0===e&&void 0!==window&&(e=window),"function"==typeof define&&define.amd?define(["jquery"],function(e){return t(e)}):"object"==typeof module&&module.exports?module.exports=t(require("jquery")):t(e.jQuery)}(this,function(e){e.fn.selectpicker.defaults={noneSelectedText:"Aucune s\xe9lection",noneResult... | random_line_split | |
diagnostic.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::Location;
use std::error::Error;
use std::fmt;
use std::fmt::Write;
pub type DiagnosticsResult<T> = Result<T, Vec<Diagn... | ]),
];
let output = combined_result(input.into_iter());
assert_eq!(
output.as_ref().unwrap_err()[0].message().to_string(),
"err0"
);
assert_eq!(
output.as_ref().unwrap_err()[1].message().to_string(),
"err1"
);
... | Err(vec![
Diagnostic::error("err1", Location::generated()),
Diagnostic::error("err2", Location::generated()), | random_line_split |
diagnostic.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::Location;
use std::error::Error;
use std::fmt;
use std::fmt::Write;
pub type DiagnosticsResult<T> = Result<T, Vec<Diagn... |
pub fn location(&self) -> Location {
self.0.location
}
pub fn related_information(&self) -> &[DiagnosticRelatedInformation] {
&self.0.related_information
}
pub fn print_without_source(&self) -> String {
let mut result = String::new();
writeln!(
result,... | {
&self.0.message
} | identifier_body |
diagnostic.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::Location;
use std::error::Error;
use std::fmt;
use std::fmt::Write;
pub type DiagnosticsResult<T> = Result<T, Vec<Diagn... |
}
/// Convert a list of DiagnosticsResult<T> into a DiagnosticsResult<Vec<T>>.
/// This is similar to Result::from_iter except that in the case of an error
/// result, Result::from_iter returns the first error in the list. Whereas
/// this function concatenates all the Vec<Diagnostic> into one flat list.
pub fn combi... | {
Err(diagnostics)
} | conditional_block |
diagnostic.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::Location;
use std::error::Error;
use std::fmt;
use std::fmt::Write;
pub type DiagnosticsResult<T> = Result<T, Vec<Diagn... | <T>(result: T, diagnostics: Vec<Diagnostic>) -> DiagnosticsResult<T> {
if diagnostics.is_empty() {
Ok(result)
} else {
Err(diagnostics)
}
}
/// Convert a list of DiagnosticsResult<T> into a DiagnosticsResult<Vec<T>>.
/// This is similar to Result::from_iter except that in the case of an err... | diagnostics_result | identifier_name |
defaults.d.ts | import * as strategies from "./strategies" | strategies: {
selection: Array<string | strategies.selectionStrategy<any>>
click: Array<string | strategies.clickStrategy<any>>,
fold: Array<string | strategies.foldStrategy<any>>
},
display: (Object) => string,
async: (Function) => Promise<any>,
openerOpts: { pos... |
export declare const defaults : {
labels: string,
css: { [key: string]: string }, | random_line_split |
views.py | from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse_lazy
from django.utils.decorators import method_decorator
from django.views.generic import (DetailView,
ListView)
from django.views.generic.edit import (CreateView,
... |
class CredentialsCreate(LoginRequiredMixin, CreateView):
model = Credentials
form_class = CredentialsForm
success_url = reverse_lazy('credentials-list')
def form_valid(self, form):
form.instance.owner = self.request.user
return super(CredentialsCreate, self).form_valid(form)
class ... | model = Credentials
def get_queryset(self):
return Credentials.objects.filter(owner=self.request.user).order_by('-created') | identifier_body |
views.py | from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse_lazy
from django.utils.decorators import method_decorator
from django.views.generic import (DetailView,
ListView) | DeleteView)
from .forms import CredentialsForm
from .models import Credentials
class LoginRequiredMixin(object):
"""
View mixin which requires that the user is authenticated.
"""
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
... | from django.views.generic.edit import (CreateView, | random_line_split |
views.py | from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse_lazy
from django.utils.decorators import method_decorator
from django.views.generic import (DetailView,
ListView)
from django.views.generic.edit import (CreateView,
... | (LoginRequiredMixin, CreateView):
model = Credentials
form_class = CredentialsForm
success_url = reverse_lazy('credentials-list')
def form_valid(self, form):
form.instance.owner = self.request.user
return super(CredentialsCreate, self).form_valid(form)
class CredentialsDetail(LoginReq... | CredentialsCreate | identifier_name |
values.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/. */
//! Helper types and traits for the handling of CSS values.
use app_units::Au;
use cssparser::UnicodeRange;
use s... | /// Whether value is valid for this allowed numeric type.
#[inline]
pub fn is_ok(&self, value: f32) -> bool {
match *self {
AllowedNumericType::All => true,
AllowedNumericType::NonNegative => value >= 0.,
}
}
/// Clamp the ... | random_line_split | |
values.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/. */
//! Helper types and traits for the handling of CSS values.
use app_units::Au;
use cssparser::UnicodeRange;
use s... | (&self, value: f32) -> bool {
match *self {
AllowedNumericType::All => true,
AllowedNumericType::NonNegative => value >= 0.,
}
}
/// Clamp the value following the rules of this numeric type.
#[inline]
pub fn clamp(&self, val: Au) -... | is_ok | identifier_name |
values.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/. */
//! Helper types and traits for the handling of CSS values.
use app_units::Au;
use cssparser::UnicodeRange;
use s... |
}
/// Marker trait to automatically implement ToCss for Vec<T>.
pub trait OneOrMoreCommaSeparated {}
impl OneOrMoreCommaSeparated for UnicodeRange {}
impl<T> ToCss for Vec<T> where T: ToCss + OneOrMoreCommaSeparated {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut iter = ... | {
let mut s = String::new();
self.to_css(&mut s).unwrap();
s
} | identifier_body |
paginators.py | # -*- coding: utf-8 -*-
import abc
import math
import six
import sqlalchemy as sa
from marshmallow_sqlalchemy.convert import ModelConverter
from marshmallow_pagination import pages
converter = ModelConverter()
def convert_value(row, attr):
field = converter._get_field_class_for_property(attr.property)
valu... | rhs += (sort_index, )
if last_index is not None:
lhs += (self.index_column, )
rhs += (last_index, )
lhs = sa.tuple_(*lhs)
rhs = sa.tuple_(*rhs)
if rhs.clauses:
filter = lhs > rhs if direction == sa.asc else lhs < rhs
cursor = cu... | lhs, rhs = (), ()
if sort_index is not None:
lhs += (self.sort_column[0], ) | random_line_split |
paginators.py | # -*- coding: utf-8 -*-
import abc
import math
import six
import sqlalchemy as sa
from marshmallow_sqlalchemy.convert import ModelConverter
from marshmallow_pagination import pages
converter = ModelConverter()
def convert_value(row, attr):
|
class BasePaginator(six.with_metaclass(abc.ABCMeta, object)):
def __init__(self, cursor, per_page, count=None):
self.cursor = cursor
self.count = count or self._count()
self.per_page = per_page or self.count
def _count(self):
return self.cursor.count()
@abc.abstractprope... | field = converter._get_field_class_for_property(attr.property)
value = getattr(row, attr.key)
return field()._serialize(value, None, None) | identifier_body |
paginators.py | # -*- coding: utf-8 -*-
import abc
import math
import six
import sqlalchemy as sa
from marshmallow_sqlalchemy.convert import ModelConverter
from marshmallow_pagination import pages
converter = ModelConverter()
def convert_value(row, attr):
field = converter._get_field_class_for_property(attr.property)
valu... |
query = self.cursor.offset(offset).limit(limit)
return query.all() if eager else query
class SeekPaginator(BasePaginator):
"""Paginator using keyset pagination for performance on large result sets.
See http://use-the-index-luke.com/no-offset for details.
"""
page_type = pages.SeekPage
... | limit = min(limit, self.cursor._limit - offset) | conditional_block |
paginators.py | # -*- coding: utf-8 -*-
import abc
import math
import six
import sqlalchemy as sa
from marshmallow_sqlalchemy.convert import ModelConverter
from marshmallow_pagination import pages
converter = ModelConverter()
def convert_value(row, attr):
field = converter._get_field_class_for_property(attr.property)
valu... | (self):
pass
@property
def pages(self):
if self.per_page:
return int(math.ceil(self.count / self.per_page))
return 0
@abc.abstractproperty
def get_page(self):
pass
class OffsetPaginator(BasePaginator):
"""Paginator based on offsets and limits. Not perfo... | page_type | identifier_name |
ptb_word_lm.py | steps of LSTM
- hidden_size - the number of LSTM units
- max_epoch - the number of epochs trained with the initial learning rate
- max_max_epoch - the total number of epochs for training
- keep_prob - the probability of keeping weights in the dropout layer
- lr_decay - the decay of the learning rate for each epoch aft... | main | identifier_name | |
ptb_word_lm.py | learning rate for each epoch after "max_epoch"
- batch_size - the batch size
The data required for this example is in the data/ dir of the
PTB dataset from Tomas Mikolov's webpage:
$ wget http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz
$ tar xvf simple-examples.tgz
To run:
$ python ptb_word_lm.py --dat... | raw_data = reader.ptb_raw_data(FLAGS.data_path)
train_data, valid_data, test_data, _ = raw_data
config = get_config()
eval_config = get_config() | random_line_split | |
ptb_word_lm.py | | 115.91
| medium | 39 | 48.45 | 86.16 | 82.07
| large | 55 | 37.87 | 82.62 | 78.29
The exact results may vary depending on the random initialization.
The hyperparameters used in the model:
- init_scale - the initial scale of the weights
- learning_rate - the initial value of the learning rate
- max_grad... |
@property
def cost(self):
return self._cost
@property
def final_state(self):
return self._final_state
@property
def lr(self):
return self._lr
@property
def train_op(self):
return self._train_op
class SmallConfig(object):
"""Small config."""
init_scale = 0.1
learning_rate = 1... | return self._initial_state | identifier_body |
ptb_word_lm.py | | 115.91
| medium | 39 | 48.45 | 86.16 | 82.07
| large | 55 | 37.87 | 82.62 | 78.29
The exact results may vary depending on the random initialization.
The hyperparameters used in the model:
- init_scale - the initial scale of the weights
- learning_rate - the initial value of the learning rate
- max_grad... |
# Simplified version of tensorflow.models.rnn.rnn.py's rnn().
# This builds an unrolled LSTM for tutorial purposes only.
# In general, use the rnn() or state_saving_rnn() from rnn.py.
#
# The alternative version of the code below is:
#
# inputs = [tf.squeeze(input_, [1])
# fo... | inputs = tf.nn.dropout(inputs, config.keep_prob) | conditional_block |
orientable.rs | // This file is part of rgtk. | // it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// ME... | //
// rgtk is free software: you can redistribute it and/or modify | random_line_split |
orientable.rs | // This file is part of rgtk.
//
// rgtk 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 Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... |
}
| {
unsafe {
ffi::gtk_orientable_set_orientation(GTK_ORIENTABLE(self.get_widget()), orientation)
}
} | identifier_body |
orientable.rs | // This file is part of rgtk.
//
// rgtk 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 Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | (&mut self, orientation: Orientation) -> () {
unsafe {
ffi::gtk_orientable_set_orientation(GTK_ORIENTABLE(self.get_widget()), orientation)
}
}
}
| set_orientation | identifier_name |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class | (PythonPackage):
"""Tiny 'shelve'-like database with concurrency support"""
pypi = "pickleshare/pickleshare-0.7.4.tar.gz"
version('0.7.5', sha256='87683d47965c1da65cdacaf31c8441d12b8044cdec9aca500cd78fc2c683afca')
version('0.7.4', sha256='84a9257227dfdd6fe1b4be1319096c20eb85ff1e82c7932f36efccfe1b09737... | PyPickleshare | identifier_name |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyPickleshare(PythonPackage):
| """Tiny 'shelve'-like database with concurrency support"""
pypi = "pickleshare/pickleshare-0.7.4.tar.gz"
version('0.7.5', sha256='87683d47965c1da65cdacaf31c8441d12b8044cdec9aca500cd78fc2c683afca')
version('0.7.4', sha256='84a9257227dfdd6fe1b4be1319096c20eb85ff1e82c7932f36efccfe1b09737b')
depends_on('... | identifier_body | |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyPickleshare(PythonPackage):
"""Tiny 'shelve'-like database with concurrency support"""
... | depends_on('py-pathlib2', type=('build', 'run'), when='^python@2.6:2.8,3.2:3.3') | version('0.7.5', sha256='87683d47965c1da65cdacaf31c8441d12b8044cdec9aca500cd78fc2c683afca')
version('0.7.4', sha256='84a9257227dfdd6fe1b4be1319096c20eb85ff1e82c7932f36efccfe1b09737b')
depends_on('python@2.7:2.8,3:', type=('build', 'run'))
depends_on('py-setuptools', type='build') | random_line_split |
filter.ts | import { QueryValueError } from './error';
import { isPlainObject, isShallowEqual, isString, isNumber } from '../util/is';
import { clone } from '../util/clone';
/**
* Manage filters applied to a query.
* @public
*/
export class QueryFilter {
private _filters: Map<string, unknown> = new Map();
/**
* Retriev... | (name: string, value: unknown): void {
const normalized = this._normalize(value);
if (normalized instanceof Set) {
this._filters.set(name, normalized);
} else if (isPlainObject(normalized) && Object.entries(normalized).length === 0) {
throw new QueryValueError(`plain object filters can't be empt... | set | identifier_name |
filter.ts | import { QueryValueError } from './error';
import { isPlainObject, isShallowEqual, isString, isNumber } from '../util/is';
import { clone } from '../util/clone';
/**
* Manage filters applied to a query.
* @public
*/
export class QueryFilter {
private _filters: Map<string, unknown> = new Map();
/**
* Retriev... |
for (const key in data) {
this.set(key, data[key]);
}
}
/**
* Dump all filters as an object.
* @returns An object with fields as keys and filter values as values.
* @public
*/
public dump(): Record<string, any> {
const data: Record<string, any> = {};
this._filters.forEach((valu... | {
this.clear();
} | conditional_block |
filter.ts | import { QueryValueError } from './error';
import { isPlainObject, isShallowEqual, isString, isNumber } from '../util/is';
import { clone } from '../util/clone';
/**
* Manage filters applied to a query.
* @public
*/
export class QueryFilter {
private _filters: Map<string, unknown> = new Map();
/**
* Retriev... | /**
* Remove a filter by a field.
*
* @remarks
*
* - If the value is not provided, the filter is removed.
* - If the value is an object, the filter is removed.
* - Otherwise the value is removed from the list of terms.
*
* @param name - Name of the filter.
* @param value - Optional. Valu... | this._filters.set(name, added);
}
}
| random_line_split |
filter.ts | import { QueryValueError } from './error';
import { isPlainObject, isShallowEqual, isString, isNumber } from '../util/is';
import { clone } from '../util/clone';
/**
* Manage filters applied to a query.
* @public
*/
export class QueryFilter {
private _filters: Map<string, unknown> = new Map();
/**
* Retriev... |
private _denormalize(value: unknown): unknown {
return value instanceof Set ? [...value] : value;
}
private _filterContainsOrEqualsValue(name: string, value: unknown, checkEquality: boolean): boolean {
const normalized = this._normalize(value);
const filterValue = this._filters.get(name);
if (... | {
if (isString(value) || isNumber(value)) {
return new Set([value]);
} else if (Array.isArray(value)) {
return new Set(value);
} else {
return value;
}
} | identifier_body |
interrupts.rs | // "Tifflin" Kernel
// - By John Hodge (thePowersGang)
//
// Core/main.rs
//! Low-level interrupt handling and CPU error handling
//use prelude::*;
#[repr(C)]
/// A handler for an ISR
pub type ISRHandler = extern "C" fn(isrnum: usize,info:*const(),idx:usize);
struct IRQHandlersEnt
{
handler: Option<ISRHandler>,
inf... |
{
idx: usize,
}
static S_IRQ_HANDLERS_LOCK: ::sync::Spinlock<[IRQHandlersEnt; 256]> = ::sync::Spinlock::new( [IRQHandlersEnt{
handler: None,
info: 0 as *const _,
idx: 0
}; 256] );
#[no_mangle]
#[doc(hidden)]
#[tag_safe(irq)]
/// ISR handler called by assembly
pub extern "C" fn irq_handler(index: usize)
{
let l... | ISRHandle | identifier_name |
interrupts.rs | // "Tifflin" Kernel
// - By John Hodge (thePowersGang)
//
// Core/main.rs
//! Low-level interrupt handling and CPU error handling
//use prelude::*;
#[repr(C)]
/// A handler for an ISR
pub type ISRHandler = extern "C" fn(isrnum: usize,info:*const(),idx:usize);
struct IRQHandlersEnt
{
handler: Option<ISRHandler>,
inf... | };
return Ok( ISRHandle {
idx: i,
} )
}
}
Err( BindISRError::Used )
}
impl ISRHandle
{
/// Returns an unbound ISR handle (null)
pub fn unbound() -> ISRHandle {
ISRHandle {
idx: !0,
}
}
/// Returns the bound ISR index
pub fn idx(&self) -> usize { self.idx }
}
impl ::core::ops::Drop for... | info: info,
idx: idx, | random_line_split |
interrupts.rs | // "Tifflin" Kernel
// - By John Hodge (thePowersGang)
//
// Core/main.rs
//! Low-level interrupt handling and CPU error handling
//use prelude::*;
#[repr(C)]
/// A handler for an ISR
pub type ISRHandler = extern "C" fn(isrnum: usize,info:*const(),idx:usize);
struct IRQHandlersEnt
{
handler: Option<ISRHandler>,
inf... |
}
}
// vim: ft=rust
| {
let _irq_hold = ::arch::sync::hold_interrupts();
let mut mh = S_IRQ_HANDLERS_LOCK.lock();
let h = &mut mh[self.idx];
h.handler = None;
} | conditional_block |
darwin.js | 'use strict';
const {app} = require('electron');
const appName = app.getName();
module.exports = {
label: appName,
submenu: [{ | }
}, {
type: 'separator'
}, {
label: 'Preferences',
event: 'prefer',
params: 'optional params'
}, {
type: 'separator'
}, {
label: 'Hide ' + appName,
accelerator: 'Command+H',
role: 'hide'
}, {
label: 'Hide Others',
accelerator: 'Command+Shift+H',
role: 'hideothers'
}, {
label: 'Show All'... | label: 'About ' + appName,
role: 'about',
params: {
version: '1.0.0' | random_line_split |
index.d.ts | // Type definitions for compression 1.7
// Project: https://github.com/expressjs/compression
// Definitions by: Santi Albo <https://github.com/santialbo>
// Rob van der Burgt <https://github.com/rburgt>
// Neil Bryson Cargamento <https://github.com/neilbryson>
// Piotr Bł... | * `filter(req, res)` and is expected to return `true` to consider the response for compression, or `false` to
* not compress the response.
*
* The default filter function uses the `compressible` module to determine if `res.getHeader('Content-Type')`
* is compressible.
... | */
chunkSize?: number;
/**
* A function to decide if the response should be considered for compression. This function is called as | random_line_split |
kubectlutility.ts | import * as os from "os";
import * as path from "path";
import * as toolLib from 'azure-pipelines-tool-lib/tool';
import * as tl from "azure-pipelines-task-lib/task";
import * as downloadutility from "./downloadutility";
import * as util from "util";
import * as yaml from "js-yaml";
const uuidV4 = require('uuid/v4');
c... |
return version;
},
(reject) => {
tl.debug(reject);
tl.warning(tl.loc('DownloadStableVersionFailed', stableVersionUrl, stableKubectlVersion));
return stableKubectlVersion;
})
}
export async function downloadKubectl(version: string) : Promise<string> {
var cachedToolpath... | {
version = stableKubectlVersion;
} | conditional_block |
kubectlutility.ts | import * as os from "os";
import * as path from "path";
import * as toolLib from 'azure-pipelines-tool-lib/tool';
import * as tl from "azure-pipelines-task-lib/task";
import * as downloadutility from "./downloadutility";
import * as util from "util";
import * as yaml from "js-yaml";
const uuidV4 = require('uuid/v4');
c... | return version;
},
(reject) => {
tl.debug(reject);
tl.warning(tl.loc('DownloadStableVersionFailed', stableVersionUrl, stableKubectlVersion));
return stableKubectlVersion;
})
}
export async function downloadKubectl(version: string) : Promise<string> {
var cachedToolpath ... | version = stableKubectlVersion;
} | random_line_split |
kubectlutility.ts | import * as os from "os";
import * as path from "path";
import * as toolLib from 'azure-pipelines-tool-lib/tool';
import * as tl from "azure-pipelines-task-lib/task";
import * as downloadutility from "./downloadutility";
import * as util from "util";
import * as yaml from "js-yaml";
const uuidV4 = require('uuid/v4');
c... | (kubernetesServiceEndpoint: string): string
{
var kubeconfigTemplateString = '{"apiVersion":"v1","kind":"Config","clusters":[{"cluster":{"certificate-authority-data": null,"server": null}}], "users":[{"user":{"token": null}}]}';
var kubeconfigTemplate = JSON.parse(kubeconfigTemplateString);
//populate serv... | createKubeconfig | identifier_name |
kubectlutility.ts | import * as os from "os";
import * as path from "path";
import * as toolLib from 'azure-pipelines-tool-lib/tool';
import * as tl from "azure-pipelines-task-lib/task";
import * as downloadutility from "./downloadutility";
import * as util from "util";
import * as yaml from "js-yaml";
const uuidV4 = require('uuid/v4');
c... |
export function getKubeconfigForCluster(kubernetesServiceEndpoint: string): string
{
var kubeconfig = tl.getEndpointAuthorizationParameter(kubernetesServiceEndpoint, 'kubeconfig', false);
var clusterContext = tl.getEndpointAuthorizationParameter(kubernetesServiceEndpoint, 'clusterContext', true);
if (!clu... | {
switch(os.type())
{
case 'Linux':
return util.format("https://storage.googleapis.com/kubernetes-release/release/%s/bin/linux/amd64/kubectl", version);
case 'Darwin':
return util.format("https://storage.googleapis.com/kubernetes-release/release/%s/bin/darwin/amd64/kubec... | identifier_body |
user.py | # -*- coding: utf-8 -*-
"""
Copyright 2010 cloudControl UG (haftungsbeschraenkt)
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
... |
else:
question = 'Yes'
if question.lower() == 'yes':
self.api.delete_user_key(users[0]['username'], args.id[0])
else:
raise InputErrorException('SecurityQuestionDenied')
def logout(self, args):
"""
Logout a user by deleting the token.... | question = raw_input('Do you really want to remove your key? ' +
'Type "Yes" without the quotes to remove: ') | conditional_block |
user.py | # -*- coding: utf-8 -*-
"""
Copyright 2010 cloudControl UG (haftungsbeschraenkt)
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
... | self.api.set_token(None)
else:
raise InputErrorException('SecurityQuestionDenied')
def addKey(self, args):
"""
Add a given public key to cloudControl user account.
"""
default_key_path = get_default_ssh_key_path()
# Possibility #1: User ... | """
Delete your user account.
"""
users = self.api.read_users()
if not args.force_delete:
question = raw_input('Do you really want to delete your user? ' +
'Type "Yes" without the quotes to delete: ')
else:
question = ... | identifier_body |
user.py | # -*- coding: utf-8 -*-
"""
Copyright 2010 cloudControl UG (haftungsbeschraenkt)
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
... | raise InputErrorException('KeyDuplicate')
def listKeys(self, args):
"""
List your public keys.
"""
users = self.api.read_users()
if args.id:
key = self.api.read_user_key(users[0]['username'], args.id)
print_key(key)
else:
... |
except ConflictDuplicateError: | random_line_split |
user.py | # -*- coding: utf-8 -*-
"""
Copyright 2010 cloudControl UG (haftungsbeschraenkt)
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
... | (self, args):
user_config = get_user_config(self.settings)
ssh_key_path = self._get_setup_ssh_key_path(user_config, args)
if not is_key_valid(ssh_key_path):
# If given key path is not default and does not exist
# we raise an error
if ssh_key_path != get_defaul... | setup | identifier_name |
timeline_component.ts | /* Copyright 2020 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... | {
@Input()
activeRunId: string | null = null;
@Input()
loadingNumExecutions: boolean = false;
@Input()
numExecutions: number = 0;
@Input()
scrollBeginIndex: number = 0;
@Input()
scrollBeginIndexUpperLimit: number = 0;
@Input()
pageSize: number = 0;
@Input()
displayCount: number = 0;
... | TimelineComponent | identifier_name |
timeline_component.ts | /* Copyright 2020 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... | @Input()
focusedExecutionIndex: number | null = null;
@Input()
focusedExecutionDisplayIndex: number | null = null;
@Input()
focusedExecutionData: Execution | null = null;
@Output()
onNavigateLeft = new EventEmitter();
@Output()
onNavigateRight = new EventEmitter();
@Output()
onExecutionDige... | displayFocusedAlertTypes: Array<AlertType | null> = [];
| random_line_split |
mod.rs |
pub mod client_connection;
pub mod client_session;
pub mod local_router;
pub mod router_follower;
pub mod router_leader;
pub mod session_timer;
use std::fmt;
use std::net::SocketAddr;
use std::time::Instant;
use mqtt::{QualityOfService};
use mqtt::packet::{PublishPacket, SubscribePacket, UnsubscribePacket};
use comm... | {
_Shutdown
}
#[derive(Debug, Copy, Clone)]
pub enum SessionTimerAction {
Set(Instant), Cancel
}
#[derive(Debug, Eq, PartialEq, Hash, Clone)]
pub enum SessionTimerPacketType {
// [QoS.1.send] Receive PUBACK timeout
RecvPubackTimeout,
// [QoS.2.send] Receive PUBREC timeout
RecvPubrecTimeout,
... | RouterLeaderMsg | identifier_name |
mod.rs | pub mod client_connection;
pub mod client_session;
pub mod local_router;
pub mod router_follower;
pub mod router_leader;
pub mod session_timer;
use std::fmt;
use std::net::SocketAddr;
use std::time::Instant;
use mqtt::{QualityOfService};
use mqtt::packet::{PublishPacket, SubscribePacket, UnsubscribePacket};
use commo... | #[derive(Clone)]
pub enum ClientSessionMsg {
Data(SocketAddr, Vec<u8>),
// (user_id, client_identifier, qos, packet)
Publish(UserId, ClientIdentifier, QualityOfService, PublishPacket),
ClientDisconnect(SocketAddr, String),
// (user_id, addr, packets, subscribe_qos)
RetainPackets(UserId, SocketAd... | // Shutdown
}
| random_line_split |
app.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { MatSnackBar, MatSnackBarConfig } from '@angular/material';
import { Title } from '@angular/platform-browser';
import { Subject } from 'rxjs/Subject';
import { takeUntil, filter... | (isOpen) {
this.isOpen = isOpen;
}
canShowNavigation() {
return (
this.authTokenService.isLoggedIn() &&
location.pathname.indexOf(appConstants.routes.LANDING) === -1 &&
location.pathname.indexOf(appConstants.routes.LOGIN) === -1 &&
location.pathname.indexOf(appConstants.routes.PRACT... | openMenu | identifier_name |
app.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { MatSnackBar, MatSnackBarConfig } from '@angular/material';
import { Title } from '@angular/platform-browser';
import { Subject } from 'rxjs/Subject';
import { takeUntil, filter... | this.router.navigate([appConstants.routes.LOGIN]);
}
openSnackBar({ message, action = '', config }) {
const conf = new MatSnackBarConfig();
conf.duration = 8000;
conf.extraClasses = [config.extraClass];
this.snackBar.open(message, action, conf);
}
setDocumentTitle() {
this.router.event... |
logout(): void {
this.loginStoreService.logout();
this.loginApi.logout();
this.isOpen = false; | random_line_split |
app.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { MatSnackBar, MatSnackBarConfig } from '@angular/material';
import { Title } from '@angular/platform-browser';
import { Subject } from 'rxjs/Subject';
import { takeUntil, filter... |
openMenu(isOpen) {
this.isOpen = isOpen;
}
canShowNavigation() {
return (
this.authTokenService.isLoggedIn() &&
location.pathname.indexOf(appConstants.routes.LANDING) === -1 &&
location.pathname.indexOf(appConstants.routes.LOGIN) === -1 &&
location.pathname.indexOf(appConstants.... | {
window.document.removeEventListener('resize');
this.componentDestroyed.next();
this.componentDestroyed.unsubscribe();
} | identifier_body |
app.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { MatSnackBar, MatSnackBarConfig } from '@angular/material';
import { Title } from '@angular/platform-browser';
import { Subject } from 'rxjs/Subject';
import { takeUntil, filter... |
if (this.isOpen) {
this.isOpen = false;
}
});
}
}
| {
this.titleService.setTitle(title);
} | conditional_block |
syntax-extension-bytes.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 ... | {
let vec = bytes!("abc");
assert_eq!(vec, &[97_u8, 98_u8, 99_u8]);
let vec = bytes!("null", 0);
assert_eq!(vec, &[110_u8, 117_u8, 108_u8, 108_u8, 0_u8]);
let vec = bytes!(' ', " ", 32, 32u8);
assert_eq!(vec, &[32_u8, 32_u8, 32_u8, 32_u8]);
assert_eq!(static_vec, &[97_u8, 98_u8, 99_u8, 25... | identifier_body | |
syntax-extension-bytes.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 ... | } | random_line_split | |
syntax-extension-bytes.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 ... | () {
let vec = bytes!("abc");
assert_eq!(vec, &[97_u8, 98_u8, 99_u8]);
let vec = bytes!("null", 0);
assert_eq!(vec, &[110_u8, 117_u8, 108_u8, 108_u8, 0_u8]);
let vec = bytes!(' ', " ", 32, 32u8);
assert_eq!(vec, &[32_u8, 32_u8, 32_u8, 32_u8]);
assert_eq!(static_vec, &[97_u8, 98_u8, 99_u8,... | main | identifier_name |
config.py | class Config:
STREAMING_JOB_NAME = "streaming.job.name"
STREAMING_OP_NAME = "streaming.op_name"
TASK_JOB_ID = "streaming.task_job_id"
STREAMING_WORKER_NAME = "streaming.worker_name"
# channel
CHANNEL_TYPE = "channel_type"
MEMORY_CHANNEL = "memory_channel"
NATIVE_CHANNEL = "native_channel... | OPERATOR_TYPE = "operator_type" |
# operator type | random_line_split |
config.py | class Config:
| # operator type
OPERATOR_TYPE = "operator_type"
| STREAMING_JOB_NAME = "streaming.job.name"
STREAMING_OP_NAME = "streaming.op_name"
TASK_JOB_ID = "streaming.task_job_id"
STREAMING_WORKER_NAME = "streaming.worker_name"
# channel
CHANNEL_TYPE = "channel_type"
MEMORY_CHANNEL = "memory_channel"
NATIVE_CHANNEL = "native_channel"
CHANNEL_SIZE... | identifier_body |
config.py | class | :
STREAMING_JOB_NAME = "streaming.job.name"
STREAMING_OP_NAME = "streaming.op_name"
TASK_JOB_ID = "streaming.task_job_id"
STREAMING_WORKER_NAME = "streaming.worker_name"
# channel
CHANNEL_TYPE = "channel_type"
MEMORY_CHANNEL = "memory_channel"
NATIVE_CHANNEL = "native_channel"
CHANNE... | Config | identifier_name |
volume.py | #-*- coding: utf-8 -*-
'''
Created on 28 сент. 2010
@author: ivan
'''
from gi.repository import Gtk
from gi.repository import Gdk
from foobnix.fc.fc import FC
from foobnix.gui.state import LoadSave
from foobnix.gui.model.signal import FControl
class VolumeControls(LoadSave, Gtk.HBox, FControl):
MAX_VALUE = 100
... | def set_value(self, value):
self.volume_scale.set_value(value)
def volume_up(self):
value = self.volume_scale.get_value()
self.volume_scale.set_value(value + 3)
def volume_down(self):
value = self.volume_scale.get_value()
self.volume_scale.set_value(value - 3)
de... | .volume_scale.get_value()
| identifier_body |
volume.py | #-*- coding: utf-8 -*-
'''
Created on 28 сент. 2010
@author: ivan
'''
from gi.repository import Gtk
from gi.repository import Gdk
from foobnix.fc.fc import FC
from foobnix.gui.state import LoadSave
from foobnix.gui.model.signal import FControl
class VolumeControls(LoadSave, Gtk.HBox, FControl):
MAX_VALUE = 100
... | else:
self.volume_scale.set_value(value - 15)
self.controls.player_volume(value)
return True
def on_value_changed(self, widget):
percent = widget.get_value()
self.controls.player_volume(percent)
FC().volume = percent
self.controls.trayicon.popup_volu... | .volume_scale.set_value(value + 15)
| conditional_block |
volume.py | #-*- coding: utf-8 -*-
'''
Created on 28 сент. 2010
@author: ivan
'''
| from gi.repository import Gtk
from gi.repository import Gdk
from foobnix.fc.fc import FC
from foobnix.gui.state import LoadSave
from foobnix.gui.model.signal import FControl
class VolumeControls(LoadSave, Gtk.HBox, FControl):
MAX_VALUE = 100
def __init__(self, controls):
Gtk.HBox.__init__(self, False... | random_line_split | |
volume.py | #-*- coding: utf-8 -*-
'''
Created on 28 сент. 2010
@author: ivan
'''
from gi.repository import Gtk
from gi.repository import Gdk
from foobnix.fc.fc import FC
from foobnix.gui.state import LoadSave
from foobnix.gui.model.signal import FControl
class VolumeControls(LoadSave, Gtk.HBox, FControl):
MAX_VALUE = 100
... | f, widget):
percent = widget.get_value()
self.controls.player_volume(percent)
FC().volume = percent
self.controls.trayicon.popup_volume_contol.avc.set_volume(percent)
def on_save(self):
pass
def on_load(self):
self.volume_scale.set_value(FC().volume)
| alue_changed(sel | identifier_name |
ctr-playlist-item-modal.js | 'use strict';
angular.module('risevision.editorApp.controllers')
.controller('PlaylistItemModalController', ['$scope',
'placeholderPlaylistFactory', 'widgetModalFactory', 'gadgetFactory',
'$modalInstance', 'placeholderFactory', 'item', 'editorFactory',
'userState', 'RVA_URL',
function ($scope, placeh... |
}
$scope.save = function () {
angular.copy($scope.item, item);
placeholderPlaylistFactory.updateItem(item);
placeholderFactory.updateSubscriptionStatus();
$scope.dismiss();
};
$scope.dismiss = function () {
$modalInstance.dismiss();
};
}
... | {
gadgetFactory.getGadget(item.objectReference).then(function (gadget) {
$scope.widgetName = gadget.name;
});
} | conditional_block |
ctr-playlist-item-modal.js | 'use strict';
angular.module('risevision.editorApp.controllers')
.controller('PlaylistItemModalController', ['$scope',
'placeholderPlaylistFactory', 'widgetModalFactory', 'gadgetFactory',
'$modalInstance', 'placeholderFactory', 'item', 'editorFactory',
'userState', 'RVA_URL',
function ($scope, placeh... |
$scope.save = function () {
angular.copy($scope.item, item);
placeholderPlaylistFactory.updateItem(item);
placeholderFactory.updateSubscriptionStatus();
$scope.dismiss();
};
$scope.dismiss = function () {
$modalInstance.dismiss();
};
}
]); //ctr | gadgetFactory.getGadget(item.objectReference).then(function (gadget) {
$scope.widgetName = gadget.name;
});
}
} | random_line_split |
getter.js | //getter methods
console.log("Syntax: ");
console.log("The get syntax binds an object property \n to a function that will be called when that property is looked up.");
console.log("{get prop() { ... } }");
console.log("{get [expression]() { ... } }");
// prop: The name of the property to bind to the given function.
/... |
}
console.log(obj.latest);
console.log("If you want to remove the getter, you can just delete it: delete obj.latest;");
| {
if (log.length == 0) return undefined;
return log[log.length -1]
} | identifier_body |
getter.js | //getter methods
console.log("Syntax: ");
console.log("The get syntax binds an object property \n to a function that will be called when that property is looked up.");
console.log("{get prop() { ... } }");
console.log("{get [expression]() { ... } }");
// prop: The name of the property to bind to the given function.
/... | (){
if (log.length == 0) return undefined;
return log[log.length -1]
}
}
console.log(obj.latest);
console.log("If you want to remove the getter, you can just delete it: delete obj.latest;");
| latest | identifier_name |
getter.js | //getter methods
console.log("Syntax: ");
console.log("The get syntax binds an object property \n to a function that will be called when that property is looked up.");
console.log("{get prop() { ... } }");
console.log("{get [expression]() { ... } }");
// prop: The name of the property to bind to the given function.
/... |
var log = ['test'];
var obj ={
get latest(){
if (log.length == 0) return undefined;
return log[log.length -1]
}
}
console.log(obj.latest);
console.log("If you want to remove the getter, you can just delete it: delete obj.latest;"); | A getter can be removed using the delete operator
*/
console.log("Example"); | random_line_split |
ConfigResolver.ts | /* 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... |
}
get(key: string) {
return ConfigResolver.config[key]
}
set(key: string, value: any) {
ConfigResolver.config[key] = value
}
}
export const Config = new ConfigResolver()
| {
ConfigResolver.config = {
...ConfigResolver.config,
...options,
}
} | conditional_block |
ConfigResolver.ts | /* 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... | }
get(key: string) {
return ConfigResolver.config[key]
}
set(key: string, value: any) {
ConfigResolver.config[key] = value
}
}
export const Config = new ConfigResolver() | random_line_split | |
ConfigResolver.ts | /* 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... |
get(key: string) {
return ConfigResolver.config[key]
}
set(key: string, value: any) {
ConfigResolver.config[key] = value
}
}
export const Config = new ConfigResolver()
| {
if (options) {
ConfigResolver.config = {
...ConfigResolver.config,
...options,
}
}
} | identifier_body |
ConfigResolver.ts | /* 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... | (key: string, value: any) {
ConfigResolver.config[key] = value
}
}
export const Config = new ConfigResolver()
| set | identifier_name |
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
use crate::function_target_pipeline::FunctionTargetsHolder;
use move_model::model::GlobalEnv;
pub mod access_path;
pub mod access_path_trie;
pub mod annotations;
pub mod borrow_analysis;
pub mod clean_and_optim... |
}
}
}
text
}
| {
target.register_annotation_formatters_for_test();
text += &format!("\n[variant {}]\n{}\n", variant, target);
} | conditional_block |
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
use crate::function_target_pipeline::FunctionTargetsHolder;
use move_model::model::GlobalEnv;
pub mod access_path;
pub mod access_path_trie;
pub mod annotations;
pub mod borrow_analysis;
pub mod clean_and_optim... | {
let mut text = String::new();
text.push_str(&format!("============ {} ================\n", header));
for module_env in env.get_modules() {
for func_env in module_env.get_functions() {
for (variant, target) in targets.get_targets(&func_env) {
if !target.data.code.is_empt... | identifier_body | |
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
use crate::function_target_pipeline::FunctionTargetsHolder;
use move_model::model::GlobalEnv;
pub mod access_path;
pub mod access_path_trie;
pub mod annotations;
pub mod borrow_analysis;
pub mod clean_and_optim... | (
env: &GlobalEnv,
header: &str,
targets: &FunctionTargetsHolder,
) -> String {
let mut text = String::new();
text.push_str(&format!("============ {} ================\n", header));
for module_env in env.get_modules() {
for func_env in module_env.get_functions() {
for (variant... | print_targets_for_test | identifier_name |
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
use crate::function_target_pipeline::FunctionTargetsHolder;
use move_model::model::GlobalEnv; | pub mod clean_and_optimize;
pub mod compositional_analysis;
pub mod data_invariant_instrumentation;
pub mod dataflow_analysis;
pub mod debug_instrumentation;
pub mod eliminate_imm_refs;
pub mod function_data_builder;
pub mod function_target;
pub mod function_target_pipeline;
pub mod global_invariant_instrumentation;
pu... |
pub mod access_path;
pub mod access_path_trie;
pub mod annotations;
pub mod borrow_analysis; | random_line_split |
scatter.js |
import assert from './assert';
import Vertex from './vertex';
/**
* 2D scattering algorithms.
* @type {Object}
*/
const algorithms = {
/**
* Uniform-random scattering algorithm.
* @param {Integer} width - the width of the scattering area
* @param {Integer} height - the height of the scattering area
* @... | while (grid[x] && grid[x][y]);
// Create a new Vertex at the position that was found
vertices.push(new Vertex(x, y));
// Mark the position as occupied
grid[x] = grid[x] || [];
grid[x][y] = true;
}
return vertices;
}
};
/**
* Generate a scatter of vertices.
* @param {String} alg - the scatte... | {
x = Math.floor(Math.random() * width);
y = Math.floor(Math.random() * height);
} | conditional_block |
scatter.js |
import assert from './assert';
import Vertex from './vertex';
/**
* 2D scattering algorithms.
* @type {Object}
*/
const algorithms = {
/**
* Uniform-random scattering algorithm.
* @param {Integer} width - the width of the scattering area
* @param {Integer} height - the height of the scattering area
* @... |
export default { generate };
| {
assert.isNonEmptyString(alg);
assert.isIntegerGt0(width);
assert.isIntegerGt0(height);
assert.isIntegerGt0(count);
// Check that the algorithm is implemented
if (!algorithms[alg]) {
throw new Error(`algorithm not implemented: ${alg}`);
}
// Ensure that the area is big enough to accomodate the amount of ... | identifier_body |
scatter.js | import assert from './assert';
import Vertex from './vertex';
/**
* 2D scattering algorithms.
* @type {Object}
*/
const algorithms = {
/**
* Uniform-random scattering algorithm.
* @param {Integer} width - the width of the scattering area
* @param {Integer} height - the height of the scattering area
* @p... | }
export default { generate }; | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.