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 |
|---|---|---|---|---|
indexTree.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
updateElementHeight(location: number[], height: number): void {
this.model.updateElementHeight(location, height);
}
protected createModel(user: string, view: IList<ITreeNode<T, TFilterData>>, options: IIndexTreeOptions<T, TFilterData>): ITreeModel<T, TFilterData, number[]> {
return new IndexTreeModel(user, vi... | {
if (location === undefined) {
this.view.rerender();
return;
}
this.model.rerender(location);
} | identifier_body |
indexTree.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | }
protected createModel(user: string, view: IList<ITreeNode<T, TFilterData>>, options: IIndexTreeOptions<T, TFilterData>): ITreeModel<T, TFilterData, number[]> {
return new IndexTreeModel(user, view, this.rootElement, options);
}
} | this.model.updateElementHeight(location, height); | random_line_split |
summary.rs | use std::collections::HashMap;
use std::mem;
use std::rc::Rc;
use semver::Version;
use core::{Dependency, PackageId, SourceId};
use util::CargoResult;
/// Subset of a `Manifest`. Contains only the most important informations about
/// a package.
///
/// Summaries are cloned, and should not be mutated after creation
... | (&self) -> &str { self.package_id().name() }
pub fn version(&self) -> &Version { self.package_id().version() }
pub fn source_id(&self) -> &SourceId { self.package_id().source_id() }
pub fn dependencies(&self) -> &[Dependency] { &self.inner.dependencies }
pub fn features(&self) -> &HashMap<String, Vec<St... | name | identifier_name |
summary.rs | use std::collections::HashMap;
use std::mem;
use std::rc::Rc;
use semver::Version;
use core::{Dependency, PackageId, SourceId};
use util::CargoResult;
/// Subset of a `Manifest`. Contains only the most important informations about
/// a package.
///
/// Summaries are cloned, and should not be mutated after creation
... |
}
impl PartialEq for Summary {
fn eq(&self, other: &Summary) -> bool {
self.inner.package_id == other.inner.package_id
}
}
| {
let me = if self.package_id().source_id() == to_replace {
let new_id = self.package_id().with_source_id(replace_with);
self.override_id(new_id)
} else {
self
};
me.map_dependencies(|dep| {
dep.map_source(to_replace, replace_with)
... | identifier_body |
summary.rs | use std::collections::HashMap;
use std::mem;
use std::rc::Rc;
use semver::Version;
use core::{Dependency, PackageId, SourceId};
use util::CargoResult;
/// Subset of a `Manifest`. Contains only the most important informations about
/// a package.
///
/// Summaries are cloned, and should not be mutated after creation
... | }
}
impl PartialEq for Summary {
fn eq(&self, other: &Summary) -> bool {
self.inner.package_id == other.inner.package_id
}
} | dep.map_source(to_replace, replace_with)
}) | random_line_split |
summary.rs | use std::collections::HashMap;
use std::mem;
use std::rc::Rc;
use semver::Version;
use core::{Dependency, PackageId, SourceId};
use util::CargoResult;
/// Subset of a `Manifest`. Contains only the most important informations about
/// a package.
///
/// Summaries are cloned, and should not be mutated after creation
... |
None if is_reexport => {
bail!("Feature `{}` requires `{}` which is not an \
optional dependency", feature, dep)
}
None => {
bail!("Feature `{}` includes `{}` which is neither \
... | {
if d.is_optional() || is_reexport { continue }
bail!("Feature `{}` depends on `{}` which is not an \
optional dependency.\nConsider adding \
`optional = true` to the dependency",
... | conditional_block |
urls.py | """myproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-b... | import debug_toolbar
urlpatterns += [
url(r'^__debug__/', include(debug_toolbar.urls)),
] | conditional_block | |
urls.py | """myproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-b... |
if settings.DEBUG:
import debug_toolbar
urlpatterns += [
url(r'^__debug__/', include(debug_toolbar.urls)),
] | url(r'^admin/', admin.site.urls),
] | random_line_split |
products.module.ts | /*
Copyright 2020 Google LLC
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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writi... | { } | ProductsModule | identifier_name |
products.module.ts | /*
Copyright 2020 Google LLC
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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writi... |
import { ProductsRoutingModule } from './products-routing.module';
import { ProductComponent } from './components/product.component';
import { SharedModule } from '../shared/shared.module';
import { ProductsFacade } from './products.facade';
@NgModule({
declarations: [
ProductComponent
],
imports: [
Sh... | See the License for the specific language governing permissions and
limitations under the License.
*/
import { NgModule } from '@angular/core'; | random_line_split |
index.d.ts | import * as React from "react";
declare module "react-css-themr" {
type TReactCSSThemrTheme = {
[key: string]: string | TReactCSSThemrTheme
}
type TMapThemrProps<P> = (ownProps: P, theme: TReactCSSThemrTheme) => P & { theme: TReactCSSThemrTheme }
export function themeable(...themes: Array<TReactCSSThemrTh... | extends React.Component<ThemeProviderProps, any> {
}
interface ThemedComponent<P, S> extends React.Component<P, S> {
}
interface ThemedComponentClass<P, S> extends React.ComponentClass<P> {
new(props?: P, context?: any): ThemedComponent<P, S>;
}
export function themr(
identifier: string | number... | ThemeProvider | identifier_name |
index.d.ts | import * as React from "react";
declare module "react-css-themr" {
type TReactCSSThemrTheme = {
[key: string]: string | TReactCSSThemrTheme
}
type TMapThemrProps<P> = (ownProps: P, theme: TReactCSSThemrTheme) => P & { theme: TReactCSSThemrTheme }
export function themeable(...themes: Array<TReactCSSThemrTh... | ): <P, S>(component: (new(props?: P, context?: any) => React.Component<P, S>) | React.SFC<P>) =>
ThemedComponentClass<P & { mapThemrProps?: TMapThemrProps<P> }, S>;
} | random_line_split | |
logging.py | ._log_cli_enabled():
terminal_reporter = config.pluginmanager.get_plugin("terminalreporter")
capture_manager = config.pluginmanager.get_plugin("capturemanager")
# if capturemanager plugin is disabled, live logging still works.
self.log_cli_handler: Union[
... | pass | identifier_body | |
logging.py | return 0
return 0
def format(self, record: logging.LogRecord) -> str:
if "\n" in record.message:
if hasattr(record, "auto_indent"):
# Passed in from the "extra={}" kwarg on the call to logging.log().
auto_indent = self._get_auto_indent(re... | dest="log_cli_date_format",
default=None,
help="log date format as used by the logging module.",
)
add_option_ini(
"--log-file",
dest="log_file",
default=None,
help="path to a file when logging will be written to.",
)
add_option_ini(
"--log... | "--log-cli-date-format", | random_line_split |
logging.py | return 0
return 0
def format(self, record: logging.LogRecord) -> str:
if "\n" in record.message:
if hasattr(record, "auto_indent"):
# Passed in from the "extra={}" kwarg on the call to logging.log().
auto_indent = self._get_auto_indent(re... |
root_logger.addHandler(self.handler)
if self.level is not None:
self.orig_level = root_logger.level
root_logger.setLevel(min(self.orig_level, self.level))
return self.handler
def __exit__(self, type, value, traceback):
root_logger = logging.getLogger()
... | self.handler.setLevel(self.level) | conditional_block |
logging.py | return 0
return 0
def format(self, record: logging.LogRecord) -> str:
if "\n" in record.message:
if hasattr(record, "auto_indent"):
# Passed in from the "extra={}" kwarg on the call to logging.log().
auto_indent = self._get_auto_indent(re... | (self, level: Union[int, str], logger: Optional[str] = None) -> None:
"""Set the level of a logger for the duration of a test.
.. versionchanged:: 3.4
The levels of the loggers changed by this function will be
restored to their initial values at the end of the test.
:pa... | set_level | identifier_name |
error.rs | > {
pub fn struct_error(&self,
tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
message: &str)
-> Result<DiagnosticBuilder<'tcx>, ErrorHandled>
{
self.struct_generic(tcx, message, None)
}
pub fn report_as_error(&self,
tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
message: &str
) -> E... | "pointer offset outside bounds of allocation",
InvalidNullPointerUsage =>
"invalid use of NULL pointer",
ValidationFailure(..) =>
"type validation failed",
ReadPointerAsBytes =>
"a raw memory access tried to access part ... | {
use self::EvalErrorKind::*;
match *self {
MachineError(ref inner) => inner,
FunctionAbiMismatch(..) | FunctionArgMismatch(..) | FunctionRetMismatch(..)
| FunctionArgCountMismatch =>
"tried to call a function through a function pointer of incompatible... | identifier_body |
error.rs | _ => None,
};
EvalError {
kind,
backtrace,
}
}
}
pub type AssertMessage<'tcx> = EvalErrorKind<'tcx, mir::Operand<'tcx>>;
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub enum EvalErrorKind<'tcx, O> {
/// This variant is used by machines to signal their own ... | fmt | identifier_name | |
error.rs | > {
pub fn struct_error(&self,
tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
message: &str)
-> Result<DiagnosticBuilder<'tcx>, ErrorHandled>
{
self.struct_generic(tcx, message, None)
}
pub fn report_as_error(&self,
tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
message: &str
) -> E... | "tried to read from foreign (extern) static",
InvalidPointerMath =>
"attempted to do invalid arithmetic on pointers that would leak base addresses, \
e.g., comparing pointers into different allocations",
ReadUndefBytes(_) =>
"attemp... | ReadBytesAsPointer =>
"a memory access tried to interpret some bytes as a pointer",
ReadForeignStatic => | random_line_split |
CloudClusterPrinterStatus.py | # Copyright (c) 2018 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from typing import List, Union, Dict, Optional, Any
from cura.PrinterOutput.PrinterOutputController import PrinterOutputController
from cura.PrinterOutput.Models.PrinterOutputModel import PrinterOutputModel
from .CloudClust... | (BaseCloudModel):
## Creates a new cluster printer status
# \param enabled: A printer can be disabled if it should not receive new jobs. By default every printer is enabled.
# \param firmware_version: Firmware version installed on the printer. Can differ for each printer in a cluster.
# \param friend... | CloudClusterPrinterStatus | identifier_name |
CloudClusterPrinterStatus.py | # Copyright (c) 2018 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from typing import List, Union, Dict, Optional, Any
from cura.PrinterOutput.PrinterOutputController import PrinterOutputController
from cura.PrinterOutput.Models.PrinterOutputModel import PrinterOutputModel
from .CloudClust... |
## Updates the given output model.
# \param model - The output model to update.
def updateOutputModel(self, model: PrinterOutputModel) -> None:
model.updateKey(self.uuid)
model.updateName(self.friendly_name)
model.updateType(self.machine_variant)
model.updateState(self.sta... | model = PrinterOutputModel(controller, len(self.configuration), firmware_version = self.firmware_version)
self.updateOutputModel(model)
return model | identifier_body |
CloudClusterPrinterStatus.py | # Copyright (c) 2018 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from typing import List, Union, Dict, Optional, Any
from cura.PrinterOutput.PrinterOutputController import PrinterOutputController
from cura.PrinterOutput.Models.PrinterOutputModel import PrinterOutputModel
from .CloudClust... | for configuration, extruder_output, extruder_config in \
zip(self.configuration, model.extruders, model.printerConfiguration.extruderConfigurations):
configuration.updateOutputModel(extruder_output)
configuration.updateConfigurationModel(extruder_config) | random_line_split | |
CloudClusterPrinterStatus.py | # Copyright (c) 2018 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from typing import List, Union, Dict, Optional, Any
from cura.PrinterOutput.PrinterOutputController import PrinterOutputController
from cura.PrinterOutput.Models.PrinterOutputModel import PrinterOutputModel
from .CloudClust... | configuration.updateOutputModel(extruder_output)
configuration.updateConfigurationModel(extruder_config) | conditional_block | |
utils.py | master date for section, subsection or a unit.
:param ccx: ccx instance
:param node: chapter, subsection or unit
:param date_type: start or due
:param parent_node: parent of node
:return: start or due date
"""
date = get_override_for_ccx(ccx, node, date_type, None)
if date_type == "sta... | add_master_course_staff_to_ccx | identifier_name | |
utils.py | identifiers
def validate_date(year, month, day, hour, minute):
"""
avoid corrupting db if bad dates come in
"""
valid = True
if year < 0:
valid = False
if month < 1 or month > 12:
valid = False
if day < 1 or day > 31:
valid = False
if hour < 0 or hour > 23:
... | except SMTPException: | random_line_split | |
utils.py | )
}
return context
def get_ccx_from_ccx_locator(course_id):
""" helper function to allow querying ccx fields from templates """
ccx_id = getattr(course_id, 'ccx', None)
ccx = None
if ccx_id:
ccx = CustomCourseForEdX.objects.filter(id=ccx_id)
if not ccx:
|
return ccx[0]
def get_date(ccx, node, date_type=None, parent_node=None):
"""
This returns override or master date for section, subsection or a unit.
:param ccx: ccx instance
:param node: chapter, subsection or unit
:param date_type: start or due
:param parent_node: parent of node
:re... | log.warning(
"CCX does not exist for course with id %s",
course_id
)
return None | conditional_block |
utils.py | )
}
return context
def get_ccx_from_ccx_locator(course_id):
""" helper function to allow querying ccx fields from templates """
ccx_id = getattr(course_id, 'ccx', None)
ccx = None
if ccx_id:
ccx = CustomCourseForEdX.objects.filter(id=ccx_id)
if not ccx:
log.warning(
... | admins = CourseInstructorRole(course_locator).users_with_role()
for identifier in identifiers:
must_enroll = False
try:
email, student = get_valid_student_with_email(identifier)
if student:
must_enroll = student in staff or stu... | """
Function to enroll or unenroll/revoke students.
Arguments:
action (str): type of action to perform (Enroll, Unenroll/revoke)
identifiers (list): list of students username/email
email_students (bool): Flag to send an email to students
course_key (CCXLocator): a CCX course key... | identifier_body |
item-attributes.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 ... |
#[attr1 = "val"]
#[attr2 = "val"]
pub mod mod1 {}
pub mod rustrt {
#[attr1 = "val"]
#[attr2 = "val"]
extern {}
}
#[attr1 = "val"]
#[attr2 = "val"]
struct t {x: int}
}
mod test_stmt_single_attr_outer {
pub fn f() {
#[attr = "val"]
static x:... | { } | identifier_body |
item-attributes.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 ... |
extern {
#[attr];
#[attr]
fn rust_get_test_int() -> libc::intptr_t;
}
}
}
mod test_literals {
#[str = "s"];
#[char = 'c'];
#[int = 100];
#[uint = 100u];
#[mach_int = 100u32];
#[float = 1.0];
#[mach_float = 1.0f32];
#[nil = ()];
... | random_line_split | |
item-attributes.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 ... | () { }
}
mod test_foreign_items {
pub mod rustrt {
use std::libc;
extern {
#[attr];
#[attr]
fn rust_get_test_int() -> libc::intptr_t;
}
}
}
mod test_literals {
#[str = "s"];
#[char = 'c'];
#[int = 100];
#[uint = 100u];
#[mach_in... | f | identifier_name |
lib.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | #![cfg_attr(rust_build,
unstable(feature = "rustc_private",
reason = "use the crates.io `rustc-serialize` library instead"))]
#[cfg(test)] extern crate rand;
pub use self::serialize::{Decoder, Encoder, Decodable, Encodable,
DecoderHelpers, EncoderHelpers};
m... | #![cfg_attr(rust_build, staged_api)] | random_line_split |
db.ts | /// Module for interacting with the mongodb through the standard node driver.
/// Will get the URL for the mongodb from the global config `app-config.ts`.
import { MongoClient, Collection, ObjectID } from 'mongodb';
import { APP_CONFIG } from '../app-config';
/**
* Promise will resolve to the db.
*/
const DB_PROM... | * @param idString The id as a string
* @returns A new mongo ObjectID object with idString as the ID
*/
export const ID = (idString: string): ObjectID => {
return new ObjectID(idString);
} | }
/**
* Get the ObjectID from an ID, basic convenience method.
* | random_line_split |
test.array.js | /* global describe, it, require */
'use strict';
// MODULES //
var // Expectation library:
chai = require( 'chai' ),
// Deep close to:
deepCloseTo = require( './utils/deepcloseto.js' ),
// Module to be tested: |
// VARIABLES //
var expect = chai.expect,
assert = chai.assert;
// TESTS //
describe( 'array log10', function tests() {
it( 'should export a function', function test() {
expect( log10 ).to.be.a( 'function' );
});
it( 'should compute the base-10 logarithm', function test() {
var data, actual, expected;
... | log10 = require( './../lib/array.js' ); | random_line_split |
iso_8859_9.rs | ", // 0xd
"\x0e", // 0xe
"\x0f", // 0xf
"\x10", // 0x10
"\x11", // 0x11
"\x12", // 0x12
"\x13", // 0x13
"\x14", // 0x14
"\x15", // 0x15
"\x16", // 0x16
"\x17", // 0x17
"\x18", // 0x18
"\x19", // 0x19
"\x1a", // 0x1a
"\x1b", // 0x1b
"\x1c", // 0x1c
"\x1d", // 0x1d
"\x1e", // 0x1e
"\x1f", // 0x1f
" ", // 0x20
"!", // 0x2... | "\xcb", // 0xcb
"\xcc", // 0xcc
"\xcd", // 0xcd
"\xce", // 0xce
"\xcf", // 0xcf
"\u011e", // 0xd0
"\xd1", // 0xd1
"\xd2", // 0xd2
"\xd3", // 0xd3
"\xd4", // 0xd4
"\xd5", // 0xd5
"\xd6", // 0xd6
"\xd7", // 0xd7
"\xd8", // 0xd8
"\xd9", // | "\xc7", // 0xc7
"\xc8", // 0xc8
"\xc9", // 0xc9
"\xca", // 0xca | random_line_split |
iso_8859_9.rs | () -> [&'static str, .. 256]{ return ["\x00", // 0x0
"\x01", // 0x1
"\x02", // 0x2
"\x03", // 0x3
"\x04", // 0x4
"\x05", // 0x5
"\x06", // 0x6
"\x07", // 0x7
"\x08", // 0x8
"\t", // 0x9
"\n", // 0xa
"\x0b", // 0xb
"\x0c", // 0xc
"\r", // 0xd
"\x0e", // 0xe
"\x0f", // 0xf
"\x10", // 0x10
"\x11", // 0x11
"\x12", // 0x12
... | charmap | identifier_name | |
iso_8859_9.rs | "\x14", // 0x14
"\x15", // 0x15
"\x16", // 0x16
"\x17", // 0x17
"\x18", // 0x18
"\x19", // 0x19
"\x1a", // 0x1a
"\x1b", // 0x1b
"\x1c", // 0x1c
"\x1d", // 0x1d
"\x1e", // 0x1e
"\x1f", // 0x1f
" ", // 0x20
"!", // 0x21
"\"", // 0x22
"#", // 0x23
"$", // 0x24
"%", // 0x25
"&", // 0x26
"'", // 0x27
"(", // 0x28
")", // 0x... | { return ["\x00", // 0x0
"\x01", // 0x1
"\x02", // 0x2
"\x03", // 0x3
"\x04", // 0x4
"\x05", // 0x5
"\x06", // 0x6
"\x07", // 0x7
"\x08", // 0x8
"\t", // 0x9
"\n", // 0xa
"\x0b", // 0xb
"\x0c", // 0xc
"\r", // 0xd
"\x0e", // 0xe
"\x0f", // 0xf
"\x10", // 0x10
"\x11", // 0x11
"\x12", // 0x12
"\x13", // 0x13 | identifier_body | |
angular-route.js | `$routeUpdate` event is broadcasted on the root scope.
*
* - `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive
*
* If the option is set to `true`, then the particular route can be matched without being
* case sensitive
*
* @returns {Object} self
... | * @eventOf ngRoute.$route
* @eventType broadcast on root scope
* @description
* Broadcasted before a route change. At this point the route services starts
* resolving all of the dependencies needed for the route change to occur.
* Typically this involves fetching the view template as well... | * @ngdoc event
* @name ngRoute.$route#$routeChangeStart | random_line_split |
angular-route.js | ` - The current route template HTML.
*
* @property {Array.<Object>} routes Array of all configured routes.
*
* @description
* `$route` is used for deep-linking URLs to controllers and views (HTML partials).
* It watches `$location.url()` and tries to map the path to an existing route defin... | seRoute(),
last = $route.current;
if (next && last && next.$$route === last.$$route
&& angular.equals(next.pathParams, last.pathParams)
&& !next.reloadOnSearch && !forceReload) {
last.params = next.params;
angular.copy(last.params, $routeParams);
$rootScope.$... | identifier_body | |
angular-route.js | >
* // Given:
* // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
* // Route: /Chapter/:chapterId/Section/:sectionId
* //
* // Then
* $routeParams ==> {chapterId:1, sectionId:2, search:'moby'}
* </pre>
*/
function $RouteParamsProvider() {
this.$get = function() { return {}; };
}
ngR... | ry($compile, $controller | identifier_name | |
angular-route.js | inherit(routes[null], {params: {}, pathParams:{}});
}
/**
* @returns interpolation of the redirect path with the parameters
*/
function interpolate(string, params) {
var result = [];
angular.forEach((string||'').split(':'), function(segment, i) {
if (i === 0) {
resu... | cope.$destroy();
currentScope = null;
}
if(currentE | conditional_block | |
test_input.py | import numpy
import pytest
import theano
class TestInputLayer:
@pytest.fixture
def layer(self):
from lasagne.layers.input import InputLayer
return InputLayer((3, 2))
def test_input_var(self, layer):
assert layer.input_var.ndim == 2
def test_get_output_shape(self, layer):
... |
def test_get_output_input_is_variable(self, layer):
variable = theano.Variable("myvariable")
assert layer.get_output(variable) is variable
def test_get_output_input_is_array(self, layer):
input = [[1,2,3]]
output = layer.get_output(input)
assert numpy.all(output.eval() ... | random_line_split | |
test_input.py | import numpy
import pytest
import theano
class TestInputLayer:
@pytest.fixture
def layer(self):
from lasagne.layers.input import InputLayer
return InputLayer((3, 2))
def test_input_var(self, layer):
assert layer.input_var.ndim == 2
def | (self, layer):
assert layer.get_output_shape() == (3, 2)
def test_get_output_without_arguments(self, layer):
assert layer.get_output() is layer.input_var
def test_get_output_input_is_variable(self, layer):
variable = theano.Variable("myvariable")
assert layer.get_output(variabl... | test_get_output_shape | identifier_name |
test_input.py | import numpy
import pytest
import theano
class TestInputLayer:
@pytest.fixture
def layer(self):
from lasagne.layers.input import InputLayer
return InputLayer((3, 2))
def test_input_var(self, layer):
assert layer.input_var.ndim == 2
def test_get_output_shape(self, layer):
... |
def test_get_output_without_arguments(self, layer):
assert layer.get_output() is layer.input_var
def test_get_output_input_is_variable(self, layer):
variable = theano.Variable("myvariable")
assert layer.get_output(variable) is variable
def test_get_output_input_is_array(self, lay... | assert layer.get_output_shape() == (3, 2) | identifier_body |
diskImage.py |
import devon.maker
from devon.tags import *
import datetime, os.path, shutil
# **************************************************************************************************
class DiskImage(devon.maker.MakerManyToOne):
path = "hdiutil"
def getTarget(self, project):
return "%s.dmg" % project.... |
def __copyFile(self, source, destDir):
if os.path.isdir(source):
newDest = os.path.join(destDir, os.path.basename(source))
if not os.path.exists(newDest):
os.makedirs(newDest)
paths = os.listdir(source)
for fileName in [name for name in path... | out << Block << text << Close | identifier_body |
diskImage.py | import devon.maker
from devon.tags import *
import datetime, os.path, shutil
# **************************************************************************************************
class DiskImage(devon.maker.MakerManyToOne):
path = "hdiutil"
def getTarget(self, project):
return "%s.dmg" % project.n... | # Unmount the disk image
line = "%s detach '%s'" % (self.path, volumeName)
result = devon.make.executeCommand(project, self, line, out)
return result
def printAction(self, project, out, target):
out << Block("progressBox progress-build") << "Archiving " \
... | random_line_split | |
diskImage.py |
import devon.maker
from devon.tags import *
import datetime, os.path, shutil
# **************************************************************************************************
class DiskImage(devon.maker.MakerManyToOne):
path = "hdiutil"
def getTarget(self, project):
return "%s.dmg" % project.... |
# XXXjoe On OS X at least, the number is double its actual size for some reason
return size/2
| print "%s" % files
size += sum([os.path.getsize(os.path.join(root, name)) for name in files]) | conditional_block |
diskImage.py |
import devon.maker
from devon.tags import *
import datetime, os.path, shutil
# **************************************************************************************************
class DiskImage(devon.maker.MakerManyToOne):
path = "hdiutil"
def getTarget(self, project):
return "%s.dmg" % project.... | (self, project, out, target):
out << Block("progressBox progress-build") << "Archiving " \
<< FileLink(path=target) << target << Close << "..." \
<< Close
def printResult(self, project, out, text):
out << Block << text << Close
def __copyFile(self, source, destDir):... | printAction | identifier_name |
macro_parser.rs | - - - (this looks exactly like the last step)
//!
//! Remaining input: `b`
//! cur: [a $( a · )* a b] next: [a $( a )* a · b]
//! Finish/Repeat (first item)
//! next: [a $( a )* · a b] [a $( · a )* a b]
//!
//! - - - Advance over a `b`. - - -
//!
//! Remaining input: ``
//! eof: [a $( a )* a b ·]
pub use self::Name... | count_names(&delim.tts)
}
&TtToken(_, MatchNt(..)) => {
1
}
&TtToken(_, _) => 0,
}
})
}
pub fn initial_matcher_pos(ms: Rc<Vec<TokenTree>>, sep: Option<Token>, lo: BytePos)
-> Box<MatcherPos> {
let... | }
&TtDelimited(_, ref delim) => { | random_line_split |
macro_parser.rs | - - (this looks exactly like the last step)
//!
//! Remaining input: `b`
//! cur: [a $( a · )* a b] next: [a $( a )* a · b]
//! Finish/Repeat (first item)
//! next: [a $( a )* · a b] [a $( · a )* a b]
//!
//! - - - Advance over a `b`. - - -
//!
//! Remaining input: ``
//! eof: [a $( a )* a b ·]
pub use self::NamedM... | > TokenTree {
match self {
&TtSeq(ref v) => v[index].clone(),
&Tt(ref tt) => tt.get_tt(index),
}
}
}
/// an unzipping of `TokenTree`s
#[derive(Clone)]
struct MatcherTtFrame {
elts: TokenTreeOrTokenTreeVec,
idx: usize,
}
#[derive(Clone)]
pub struct MatcherPos {
s... | ize) - | identifier_name |
macro_parser.rs | None,
matches: matches,
match_lo: 0,
match_cur: 0,
match_hi: match_idx_hi,
sp_lo: lo
}
}
/// NamedMatch is a pattern-match result for a single token::MATCH_NONTERMINAL:
/// so it is associated with a single ident in a parse, and all
/// `MatchedNonterminal`s in the NamedMat... | // Built-in nonterminals never start with these tokens,
// so we can eliminate them from consideration.
match tok {
token::CloseDelim(_) => {},
_ => bb_eis.push(ei),
}
}... | conditional_block | |
_metrics_advisor.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | (MetricsAdvisorOperationsMixin):
"""Microsoft Azure Metrics Advisor REST API (OpenAPI v2).
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param endpoint: Supported Cognitive Services endpoints (protocol and ... | MetricsAdvisor | identifier_name |
_metrics_advisor.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
async def __aenter__(self) -> "MetricsAdvisor":
await self._client.__aenter__()
return self
async def __aexit__(self, *exc_details) -> None:
await self._client.__aexit__(*exc_details)
| await self._client.close() | identifier_body |
_metrics_advisor.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | """
def __init__(
self,
credential: "AsyncTokenCredential",
endpoint: str,
**kwargs: Any
) -> None:
base_url = '{endpoint}/metricsadvisor/v1.0'
self._config = MetricsAdvisorConfiguration(credential, endpoint, **kwargs)
self._client = AsyncPipelineClie... | :type endpoint: str | random_line_split |
_metrics_advisor.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
from ._configuration import MetricsAdvisorConfiguration
from .operations import MetricsAdvisorOperationsMixin
from .. import models
class MetricsAdvisor(MetricsAdvisorOperationsMixin):
"""Microsoft Azure Metrics Advisor REST API (OpenAPI v2).
:param credential: Credential needed for the client to connect t... | from azure.core.credentials_async import AsyncTokenCredential | conditional_block |
macro_crate_test.rs | // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
}
}
pub fn foo() {}
| {
let mut new_it = (*tt).clone();
new_it.attrs.clear();
new_it.ident = copy_name;
push(Annotatable::TraitItem(P(new_it)));
} | conditional_block |
macro_crate_test.rs | // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (cx: &mut ExtCtxt,
sp: Span,
attr: &MetaItem,
it: Annotatable) -> Annotatable {
match it {
Annotatable::Item(it) => {
Annotatable::Item(P(Item {
attrs: it.attrs.clone(),
..(*quote_item!(cx,... | expand_into_foo_multi | identifier_name |
macro_crate_test.rs | // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | cx.span_fatal(sp, "make_a_1 takes no arguments");
}
MacEager::expr(quote_expr!(cx, 1))
}
// See Issue #15750
fn expand_identity(cx: &mut ExtCtxt, _span: Span, tts: &[TokenTree])
-> Box<MacResult+'static> {
// Parse an expression and emit it unchanged.
let mut parser = parse::... |
fn expand_make_a_1(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree])
-> Box<MacResult+'static> {
if !tts.is_empty() { | random_line_split |
macro_crate_test.rs | // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
fn expand_into_foo_multi(cx: &mut ExtCtxt,
sp: Span,
attr: &MetaItem,
it: Annotatable) -> Annotatable {
match it {
Annotatable::Item(it) => {
Annotatable::Item(P(Item {
attrs: it.attrs.clone(),
... | {
P(Item {
attrs: it.attrs.clone(),
..(*quote_item!(cx, enum Foo { Bar, Baz }).unwrap()).clone()
})
} | identifier_body |
token.js | import RepositoryService from 'consul-ui/services/repository';
import { get } from '@ember/object';
import { Promise } from 'rsvp';
import { PRIMARY_KEY, SLUG_KEY } from 'consul-ui/models/token';
import statusFactory from 'consul-ui/utils/acls-status';
import isValidServerErrorFactory from 'consul-ui/utils/http/acl/is-... |
return Promise.reject(e);
});
},
clone: function(item) {
return this.store.clone(this.getModelName(), get(item, PRIMARY_KEY));
},
findByPolicy: function(id, dc, nspace) {
return this.store.query(this.getModelName(), {
policy: id,
dc: dc,
ns: nspace,
});
},
findBy... | {
return {
AccessorID: null,
SecretID: secret,
};
} | conditional_block |
token.js | import RepositoryService from 'consul-ui/services/repository';
import { get } from '@ember/object';
import { Promise } from 'rsvp';
import { PRIMARY_KEY, SLUG_KEY } from 'consul-ui/models/token';
import statusFactory from 'consul-ui/utils/acls-status';
import isValidServerErrorFactory from 'consul-ui/utils/http/acl/is-... | return PRIMARY_KEY;
},
getSlugKey: function() {
return SLUG_KEY;
},
status: function(obj) {
return status(obj);
},
self: function(secret, dc) {
return this.store
.self(this.getModelName(), {
secret: secret,
dc: dc,
})
.catch(e => {
// If we get this ... | },
getPrimaryKey: function() { | random_line_split |
mod.rs | mod sender;
mod bus;
use std::error;
use std::fmt;
use std::collections::HashMap;
pub use self::sender::Reader;
#[derive(Debug)]
pub enum BusError {
NoSuchChannel(String),
}
impl fmt::Display for BusError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
BusError::... |
}
}
}
impl error::Error for BusError {
fn description(&self) -> &str {
match *self {
BusError::NoSuchChannel(_) => "No such channel",
}
}
}
pub struct BusSystem {
busses: HashMap<String, bus::Bus<f64>>,
}
impl BusSystem {
// ok, there's a big fat leak : when th... | {
fmt.debug_struct("NoSuchChannel")
.field("channel", &chan)
.finish()
} | conditional_block |
mod.rs | mod sender;
mod bus;
use std::error;
use std::fmt;
use std::collections::HashMap;
pub use self::sender::Reader;
#[derive(Debug)]
pub enum BusError {
NoSuchChannel(String),
}
impl fmt::Display for BusError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
BusError::... | {
a: Reader<f64>,
b: Reader<f64>,
}
impl Stuff {
fn doit(&self) -> f64 {
self.a.value() + self.b.value()
}
}
#[test]
fn test_bus_system() {
let mut bus = BusSystem::new();
let stuff = Stuff {
a: bus.sub("a"),
b:... | Stuff | identifier_name |
mod.rs | mod sender;
mod bus;
use std::error;
use std::fmt;
use std::collections::HashMap;
pub use self::sender::Reader;
#[derive(Debug)]
pub enum BusError {
NoSuchChannel(String),
}
impl fmt::Display for BusError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
BusError::... |
pub fn publish(&mut self, chan: &str, value: f64) -> Result<(), BusError> {
self.busses.get_mut(chan).map(|c| c.publish(value)).ok_or(
BusError::NoSuchChannel(chan.to_string()),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
struct Stuff {
a: Reader<f64>,
b... | {
self.busses
.entry(chan.to_string())
.or_insert(bus::Bus::new(0.0))
.subscribe()
} | identifier_body |
mod.rs | mod sender;
mod bus;
use std::error;
use std::fmt;
use std::collections::HashMap;
pub use self::sender::Reader;
#[derive(Debug)]
pub enum BusError {
NoSuchChannel(String),
}
impl fmt::Display for BusError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
BusError::... | pub struct BusSystem {
busses: HashMap<String, bus::Bus<f64>>,
}
impl BusSystem {
// ok, there's a big fat leak : when there are no listenner to a bus, it stays in the map.
pub fn new() -> BusSystem {
BusSystem { busses: HashMap::new() }
}
// ideally sub<T> -> Receiver<T>
pub fn sub(&m... | } | random_line_split |
pluggable_scm.ts | /*
* Copyright 2022 ThoughtWorks, Inc.
*
* 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 agr... |
static fromJSON(data: ScmJSON[]): Scms {
return new Scms(...data.map((a) => Scm.fromJSON(a)));
}
}
class ScmUsage {
group: string;
pipeline: string;
constructor(group: string, pipeline: string) {
this.group = group;
this.pipeline = pipeline;
}
static fromJSON(data: ScmUsageJSON): ScmUs... | {
super(...vals);
Object.setPrototypeOf(this, Object.create(Scms.prototype));
} | identifier_body |
pluggable_scm.ts | /*
* Copyright 2022 ThoughtWorks, Inc.
*
* 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 agr... | this.version = Stream(version);
this.validatePresenceOf("id");
}
static fromJSON(data: PluginMetadataJSON): PluginMetadata {
return new PluginMetadata(data.id, data.version);
}
}
export class Scm extends ValidatableMixin {
id: Stream<string>;
name: Stream<string>;
autoUpdate: Stream<boolean>;... | this.id = Stream(id); | random_line_split |
pluggable_scm.ts | /*
* Copyright 2022 ThoughtWorks, Inc.
*
* 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 agr... | (...vals: ScmUsage[]) {
super(...vals);
Object.setPrototypeOf(this, Object.create(ScmUsages.prototype));
}
static fromJSON(data: ScmUsagesJSON): ScmUsages {
return new ScmUsages(...data.usages.map((a) => ScmUsage.fromJSON(a)));
}
}
| constructor | identifier_name |
lib.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use std::{collections::BTreeSet, env};
pub mod api;
pub mod api_utils;
pub mod display_utils;
pub mod error;
pub mod filesystem;
pub mod nginx;
pub mod ostpool;
pub mo... |
pub fn selfname(suffix: Option<&str>) -> Option<String> {
match env::var("CLI_NAME") {
Ok(n) => suffix.map(|s| format!("{}-{}", n, s)).or_else(|| Some(n)),
Err(_) => exe_name(),
}
}
| {
Some(
std::env::current_exe()
.ok()?
.file_stem()?
.to_str()?
.to_string(),
)
} | identifier_body |
lib.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use std::{collections::BTreeSet, env};
pub mod api;
pub mod api_utils;
pub mod display_utils;
pub mod error;
pub mod filesystem;
pub mod nginx;
pub mod ostpool;
pub mo... | }
} |
pub fn selfname(suffix: Option<&str>) -> Option<String> {
match env::var("CLI_NAME") {
Ok(n) => suffix.map(|s| format!("{}-{}", n, s)).or_else(|| Some(n)),
Err(_) => exe_name(), | random_line_split |
lib.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use std::{collections::BTreeSet, env};
pub mod api;
pub mod api_utils;
pub mod display_utils;
pub mod error;
pub mod filesystem;
pub mod nginx;
pub mod ostpool;
pub mo... | (hosts: &[String]) -> Result<BTreeSet<String>, error::ImlManagerCliError> {
let parsed: Vec<BTreeSet<String>> = hosts
.iter()
.map(|x| hostlist_parser::parse(x))
.collect::<Result<_, _>>()?;
let union = parsed
.into_iter()
.fold(BTreeSet::new(), |acc, h| acc.union(&h).cl... | parse_hosts | identifier_name |
chip-set.ts | Event,
MdcChipNavigationEvent,
MdcChipSelectionEvent,
MdcChipRemovalEvent
} from './chip-config';
import {
MdcChip,
MDC_CHIPSET_PARENT_COMPONENT
} from './chip';
import {MDCChipSetFoundation, MDCChipSetAdapter} from '@material/chips';
/**
* Provider Expression that allows mdc-chip-set to register as a Cont... | this._chipRemovalSubscription?.unsubscribe();
this._foundation?.destroy();
}
// Implemented as part of ControlValueAccessor.
writeValue(value: any): void {
this.selectByValue(value, true);
}
// Implemented as part of ControlValueAccessor.
registerOnChange(fn: (value: any) => void): void {
... |
this._dropSubscriptions(); | random_line_split |
chip-set.ts | Event,
MdcChipNavigationEvent,
MdcChipSelectionEvent,
MdcChipRemovalEvent
} from './chip-config';
import {
MdcChip,
MDC_CHIPSET_PARENT_COMPONENT
} from './chip';
import {MDCChipSetFoundation, MDCChipSetAdapter} from '@material/chips';
/**
* Provider Expression that allows mdc-chip-set to register as a Cont... |
set input(value: boolean) {
this._input = coerceBooleanProperty(value);
}
private _input = false;
@Input()
get value(): string | string[] | undefined {
return this._value;
}
set value(value: string | string[] | undefined) {
this._value = value;
this.writeValue(value);
}
private _valu... | {
return this._input;
} | identifier_body |
chip-set.ts | Event,
MdcChipNavigationEvent,
MdcChipSelectionEvent,
MdcChipRemovalEvent
} from './chip-config';
import {
MdcChip,
MDC_CHIPSET_PARENT_COMPONENT
} from './chip';
import {MDCChipSetFoundation, MDCChipSetAdapter} from '@material/chips';
/**
* Provider Expression that allows mdc-chip-set to register as a Cont... |
if (Array.isArray(value)) {
value.forEach(currentValue => this._selectValue(currentValue, shouldIgnore));
} else {
this._selectValue(value, shouldIgnore);
}
this._value = value;
}
/**
* Finds and selects the chip based on its value.
* @returns Chip that has the corresponding val... | {
return;
} | conditional_block |
chip-set.ts | InteractionEvent,
MdcChipNavigationEvent,
MdcChipSelectionEvent,
MdcChipRemovalEvent
} from './chip-config';
import {
MdcChip,
MDC_CHIPSET_PARENT_COMPONENT
} from './chip';
import {MDCChipSetFoundation, MDCChipSetAdapter} from '@material/chips';
/**
* Provider Expression that allows mdc-chip-set to registe... | (): ReadonlyArray<string> {
return this._foundation.getSelectedChipIds();
}
select(chipId: string): void {
this._foundation.select(chipId);
}
selectByValue(value: string | string[] | undefined, shouldIgnore = true): void {
if (!this.chips) {
return;
}
if (Array.isArray(value)) {
... | getSelectedChipIds | identifier_name |
osl.py | #
# Copyright 2011-2013 Blender Foundation
#
# 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... |
if ok:
# read bytecode
try:
oso = open(oso_path, 'r')
node.bytecode = oso.read()
oso.close()
except:
import traceback
traceback.print_exc()
report({'ERROR'}, "Can't read OSO byt... | ok, oso_path = osl_compile(osl_path, report)
oso_file_remove = False | conditional_block |
osl.py | #
# Copyright 2011-2013 Blender Foundation
#
# 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... | # copy .oso from temporary path to .osl directory
dst_path = script_path_noext + ".oso"
try:
shutil.copy2(oso_path, dst_path)
except:
report({'ERROR'}, "Failed to write .oso file next to external .osl file at " + dst... | """compile and update shader script node"""
import os
import shutil
import tempfile
if node.mode == 'EXTERNAL':
# compile external script file
script_path = bpy.path.abspath(node.filepath, library=node.id_data.library)
script_path_noext, script_ext = os.path.splitext(script_path... | identifier_body |
osl.py | #
# Copyright 2011-2013 Blender Foundation
#
# 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... | (node, report):
"""compile and update shader script node"""
import os
import shutil
import tempfile
if node.mode == 'EXTERNAL':
# compile external script file
script_path = bpy.path.abspath(node.filepath, library=node.id_data.library)
script_path_noext, script_ext = os.path.... | update_script_node | identifier_name |
osl.py | #
# Copyright 2011-2013 Blender Foundation
#
# 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... | # now update node with new sockets
ok = _cycles.osl_update_node(node.id_data.as_pointer(), node.as_pointer(), oso_path)
if not ok:
report({'ERROR'}, "OSL query failed to open " + oso_path)
else:
report({'ERROR'}, "OSL script compilation failed, see console for errors")
... | else:
report({'WARNING'}, "No text or file specified in node, nothing to compile")
return
if ok: | random_line_split |
vivado.py | def check_vivado(args):
vivado_path = get_command("vivado")
if vivado_path == None:
# Look for the default Vivado install directory
if os.name == 'nt':
base_dir = r"C:\Xilinx\Vivado"
else:
|
if os.path.exists(base_dir):
for file in os.listdir(base_dir):
bin_dir = base_dir + os.path.sep + file + os.path.sep + "bin"
if os.path.exists(bin_dir + os.path.sep + "vivado"):
os.environ["PATH"] += os.pathsep + bin_dir
vivado... | base_dir = "/opt/Xilinx/Vivado" | conditional_block |
vivado.py | def check_vivado(args):
| vivado_path = get_command("vivado")
if vivado_path == None:
# Look for the default Vivado install directory
if os.name == 'nt':
base_dir = r"C:\Xilinx\Vivado"
else:
base_dir = "/opt/Xilinx/Vivado"
if os.path.exists(base_dir):
for file in os.listdir... | identifier_body | |
vivado.py | def | (args):
vivado_path = get_command("vivado")
if vivado_path == None:
# Look for the default Vivado install directory
if os.name == 'nt':
base_dir = r"C:\Xilinx\Vivado"
else:
base_dir = "/opt/Xilinx/Vivado"
if os.path.exists(base_dir):
for file i... | check_vivado | identifier_name |
vivado.py | def check_vivado(args):
vivado_path = get_command("vivado")
if vivado_path == None:
# Look for the default Vivado install directory
if os.name == 'nt':
base_dir = r"C:\Xilinx\Vivado"
else:
base_dir = "/opt/Xilinx/Vivado"
if os.path.exists(base_dir): | break
if vivado_path == None:
return (False, "toolchain not found in your PATH", "download it from https://www.xilinx.com/support/download.html")
return (True, "found at {}".format(vivado_path)) | for file in os.listdir(base_dir):
bin_dir = base_dir + os.path.sep + file + os.path.sep + "bin"
if os.path.exists(bin_dir + os.path.sep + "vivado"):
os.environ["PATH"] += os.pathsep + bin_dir
vivado_path = bin_dir | random_line_split |
bottomTabsConfig.tsx | import { OwnerType, TappedTabBarArgs } from "@artsy/cohesion"
import { BottomTabType } from "./BottomTabType"
export type BottomTabRoute = "/" | "/search" | "/inbox" | "/sales" | "/my-profile"
export const BottomTabRoutes = ["/", "/search", "/inbox", "/sales", "/my-profile"]
export const bottomTabsConfig: {
[k in B... | route: "/inbox",
analyticsDescription: OwnerType.inbox,
},
sell: {
route: "/sales",
analyticsDescription: OwnerType.sell,
},
profile: {
route: "/my-profile",
analyticsDescription: OwnerType.profile,
},
} | inbox: { | random_line_split |
Icon.tsx | import * as React from 'react'
import Base from '../../libs/Base'
import './Icon.less'
const colors = ['normal', 'gray', 'blue', 'red', 'orange', 'green']
export interface IIconProps {
name?: string,
spinning?: boolean,
fit?: boolean,
clickable?: boolean,
color?: 'normal' | 'gray' | 'blue' | 'red' | 'orange... |
}
| {
const {name, children, color: _color = 'normal', onClick} = this.props
const colorClass = colors.indexOf(_color) > -1 ? `whc-icon--${_color}` : ''
const colorStyle = !colorClass && _color ? {color: _color} : undefined
const fit = this.props.fit ? ' fa-fw' : ''
const spin = this.props.spinning ? ' ... | identifier_body |
Icon.tsx | import * as React from 'react'
import Base from '../../libs/Base'
import './Icon.less'
const colors = ['normal', 'gray', 'blue', 'red', 'orange', 'green']
export interface IIconProps {
name?: string,
spinning?: boolean,
fit?: boolean,
clickable?: boolean,
color?: 'normal' | 'gray' | 'blue' | 'red' | 'orange... | extends Base<IIconProps> {
render () {
const {name, children, color: _color = 'normal', onClick} = this.props
const colorClass = colors.indexOf(_color) > -1 ? `whc-icon--${_color}` : ''
const colorStyle = !colorClass && _color ? {color: _color} : undefined
const fit = this.props.fit ? ' fa-fw' : ''
... | Icon | identifier_name |
Icon.tsx | import * as React from 'react'
import Base from '../../libs/Base'
import './Icon.less'
const colors = ['normal', 'gray', 'blue', 'red', 'orange', 'green']
export interface IIconProps {
name?: string,
spinning?: boolean,
fit?: boolean,
clickable?: boolean,
color?: 'normal' | 'gray' | 'blue' | 'red' | 'orange... | render () {
const {name, children, color: _color = 'normal', onClick} = this.props
const colorClass = colors.indexOf(_color) > -1 ? `whc-icon--${_color}` : ''
const colorStyle = !colorClass && _color ? {color: _color} : undefined
const fit = this.props.fit ? ' fa-fw' : ''
const spin = this.props.s... | onClick?: React.MouseEventHandler<any>
}
export default class Icon extends Base<IIconProps> { | random_line_split |
Rule.ts | `@sanity/types` package because classes
// create an actual javascript class while simultaneously creating a type
// definition.
//
// This implicitly creates two types:
// 1. the instance type — `Rule` and
// 2. the static/class type - `RuleClass`
//
// The `RuleClass` type contains the static methods and the `Rule` ... | throw new Error('scheme must have at least 1 scheme specified')
}
| conditional_block | |
Rule.ts | 'Boolean',
'Date',
'Number',
'Object',
'String',
]
// Note: `RuleClass` and `Rule` are split to fit the current `@sanity/types`
// setup. Classes are a bit weird in the `@sanity/types` package because classes
// create an actual javascript class while simultaneously creating a type
// definition.
//
// This i... | pattern: RegExp,
a?: string | {name?: string; invert?: boolean},
b?: {name?: string; invert?: boolean}
): Rule {
const name = typeof a === 'string' ? a : a?.name ?? b?.name
const invert = typeof a === 'string' ? false : a?.invert ?? b?.invert
const constraint: RuleSpecConstraint<'regex'> = {
... | gex(
| identifier_name |
Rule.ts | the current `@sanity/types`
// setup. Classes are a bit weird in the `@sanity/types` package because classes
// create an actual javascript class while simultaneously creating a type
// definition.
//
// This implicitly creates two types:
// 1. the instance type — `Rule` and
// 2. the static/class type - `RuleClass`
/... | }): Rule {
const optsScheme = opts?.scheme || ['http', 'https']
const schemes = Array.isArray(optsScheme) ? optsScheme : [optsScheme]
if (!schemes.length) { | random_line_split | |
Rule.ts | 'Boolean',
'Date',
'Number',
'Object',
'String',
]
// Note: `RuleClass` and `Rule` are split to fit the current `@sanity/types`
// setup. Classes are a bit weird in the `@sanity/types` package because classes
// create an actual javascript class while simultaneously creating a type
// definition.
//
// This i... | all(children: Rule[]): Rule {
return this.cloneWithRules([{flag: 'all', constraint: children}])
}
either(children: Rule[]): Rule {
return this.cloneWithRules([{flag: 'either', constraint: children}])
}
// Shared rules
optional(): Rule {
const rule = this.cloneWithRules([{flag: 'presence', cons... | const type = `${targetType.slice(0, 1).toUpperCase()}${targetType.slice(1)}` as Capitalize<
typeof targetType
>
if (!ruleConstraintTypes.includes(type)) {
throw new Error(`Unknown type "${targetType}"`)
}
const rule = this.cloneWithRules([{flag: 'type', constraint: type}])
rule._ty... | identifier_body |
smd.py | import numpy as np
import sys
from trw_utils import *
from heterogenous_crf import inference_gco
from pyqpbo import binary_general_graph
from scipy.optimize import fmin_l_bfgs_b
def trw(node_weights, edges, edge_weights, y,
max_iter=100, verbose=0, tol=1e-3,
get_energy=None):
n_nodes, n_states =... | (x, node_weights, pairwise, edges):
n_nodes, n_states = node_weights.shape
dual = 0
dlambda = np.zeros(n_nodes)
for k in xrange(n_states):
new_unaries = np.zeros((n_nodes, 2))
new_unaries[:,1] = node_weights[:,k] + x
y_hat, energy = binary_general_graph(edges, new_unaries, pair... | f | identifier_name |
smd.py | import numpy as np
import sys
from trw_utils import *
from heterogenous_crf import inference_gco
from pyqpbo import binary_general_graph
from scipy.optimize import fmin_l_bfgs_b
def trw(node_weights, edges, edge_weights, y,
max_iter=100, verbose=0, tol=1e-3,
get_energy=None):
n_nodes, n_states =... |
for iteration in xrange(max_iter):
dmu = np.zeros((n_nodes, n_states))
unaries = node_weights + mu
x, f_val, d = fmin_l_bfgs_b(f, np.zeros(n_nodes),
args=(unaries, pairwise, edges),
maxiter=50,
... | e1, e2 = edges[i]
node_weights[e1,:] += 0.5 * np.diag(edge_weights[i,:,:])
node_weights[e2,:] += 0.5 * np.diag(edge_weights[i,:,:]) | conditional_block |
smd.py | import numpy as np
import sys
from trw_utils import *
from heterogenous_crf import inference_gco
from pyqpbo import binary_general_graph
from scipy.optimize import fmin_l_bfgs_b
def trw(node_weights, edges, edge_weights, y,
max_iter=100, verbose=0, tol=1e-3,
get_energy=None):
| e1, e2 = edges[i]
node_weights[e1,:] += 0.5 * np.diag(edge_weights[i,:,:])
node_weights[e2,:] += 0.5 * np.diag(edge_weights[i,:,:])
for iteration in xrange(max_iter):
dmu = np.zeros((n_nodes, n_states))
unaries = node_weights + mu
x, f_val, d = fmin_l_bfgs_b(f, np.... | n_nodes, n_states = node_weights.shape
n_edges = edges.shape[0]
y_hat = []
lambdas = np.zeros(n_nodes)
mu = np.zeros((n_nodes, n_states))
learning_rate = 0.1
energy_history = []
primal_history = []
pairwise = []
for k in xrange(n_states):
y_hat.append(np.zeros(n_states))
... | identifier_body |
smd.py | import numpy as np
import sys
from trw_utils import *
from heterogenous_crf import inference_gco
from pyqpbo import binary_general_graph
from scipy.optimize import fmin_l_bfgs_b
def trw(node_weights, edges, edge_weights, y,
max_iter=100, verbose=0, tol=1e-3,
get_energy=None):
n_nodes, n_states =... |
for k in xrange(n_states):
new_unaries = np.zeros((n_nodes, 2))
new_unaries[:,1] = node_weights[:,k] + x
y_hat, energy = binary_general_graph(edges, new_unaries, pairwise[k])
dual += 0.5 * energy
dlambda += y_hat
dlambda -= 1
dual -= np.sum(x)
#print dual
r... | dlambda = np.zeros(n_nodes) | random_line_split |
associated-types-no-suitable-supertrait.rs | // Check that we get an error when you use `<Self as Get>::Value` in
// the trait definition but `Self` does not, in fact, implement `Get`.
//
// See also associated-types-no-suitable-supertrait-2.rs, which checks
// that we see the same error if we get around to checking the default
// method body.
//
// See also run-... | <U:Get>(&self, foo: U, bar: <Self as Get>::Value) {}
//~^ ERROR the trait bound `Self: Get` is not satisfied
}
impl<T:Get> Other for T {
fn uhoh<U:Get>(&self, foo: U, bar: <(T, U) as Get>::Value) {}
//~^ ERROR the trait bound `(T, U): Get` is not satisfied
}
fn main() { }
| uhoh | identifier_name |
associated-types-no-suitable-supertrait.rs | // Check that we get an error when you use `<Self as Get>::Value` in
// the trait definition but `Self` does not, in fact, implement `Get`.
//
// See also associated-types-no-suitable-supertrait-2.rs, which checks
// that we see the same error if we get around to checking the default
// method body.
//
// See also run-... |
//~^ ERROR the trait bound `(T, U): Get` is not satisfied
}
fn main() { }
| {} | identifier_body |
associated-types-no-suitable-supertrait.rs | // Check that we get an error when you use `<Self as Get>::Value` in
// the trait definition but `Self` does not, in fact, implement `Get`.
//
// See also associated-types-no-suitable-supertrait-2.rs, which checks
// that we see the same error if we get around to checking the default
// method body. | trait Get {
type Value;
}
trait Other {
fn uhoh<U:Get>(&self, foo: U, bar: <Self as Get>::Value) {}
//~^ ERROR the trait bound `Self: Get` is not satisfied
}
impl<T:Get> Other for T {
fn uhoh<U:Get>(&self, foo: U, bar: <(T, U) as Get>::Value) {}
//~^ ERROR the trait bound `(T, U): Get` is not sati... | //
// See also run-pass/associated-types-projection-to-unrelated-trait.rs,
// which checks that the trait interface itself is not considered an
// error as long as all impls satisfy the constraint.
| random_line_split |
package.js | Package.describe({
name: 'ndemoreau:azimulti-views-bootstrap',
summary: 'Azimuth Multilanguage CMS frontend templates (using Bootstrap 3.x)',
version: '0.4.3',
git: 'https://github.com/ndemoreau/azimulti-views-bootstrap'
});
Package.on_use(function (api) {
api.use(['less@1.0.11', 'templating@1.0.9', 'mizzao:... | api.add_files('pages/home_page/home_page.html', 'client');
api.add_files('pages/page_default/page_default.html', 'client');
api.add_files('pages/sidebar_left/sidebar_left.html', 'client');
api.add_files('pages/sidebar_left_fixed/sidebar_left_fixed.html', 'client');
api.add_files('pages/sidebar_right/sidebar_r... | random_line_split | |
exceptions.js | import { ListWrapper } from 'angular2/src/facade/collection';
import { stringify, isBlank } from 'angular2/src/facade/lang';
import { BaseException, WrappedException } from 'angular2/src/facade/exceptions';
function findFirstClosedCycle(keys) {
var res = [];
for (var i = 0; i < keys.length; ++i) {
if (L... | (index) {
super(`Index ${index} is out-of-bounds.`);
}
}
// TODO: add a working example after alpha38 is released
/**
* Thrown when a multi provider and a regular provider are bound to the same token.
*
* ### Example
*
* ```typescript
* expect(() => Injector.resolveAndCreate([
* new Provider("Strin... | constructor | identifier_name |
exceptions.js | import { ListWrapper } from 'angular2/src/facade/collection';
import { stringify, isBlank } from 'angular2/src/facade/lang';
import { BaseException, WrappedException } from 'angular2/src/facade/exceptions';
function findFirstClosedCycle(keys) {
var res = [];
for (var i = 0; i < keys.length; ++i) {
if (L... | else {
return "";
}
}
/**
* Base class for all errors arising from misconfigured providers.
*/
export class AbstractProviderError extends BaseException {
constructor(injector, key, constructResolvingMessage) {
super("DI Exception");
this.keys = [key];
this.injectors = [inje... | } | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.