file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
option_addition.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 ... |
fn optint(in: int) -> Option<int> {
if in == 0 {
return None;
}
else {
return Some(in);
}
}
| {
let foo = 1;
let bar = 2;
let foobar = foo + bar;
let nope = optint(0) + optint(0);
let somefoo = optint(foo) + optint(0);
let somebar = optint(bar) + optint(0);
let somefoobar = optint(foo) + optint(bar);
match nope {
None => (),
Some(foo) => fail!(fmt!("expected Non... | identifier_body |
extrude.py | #!/usr/bin/env python
'''
Copyright (C) 2007
This program 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 2 of the License, or
(at your option) any later version.
This program is distributed in t... | ele = inkex.etree.Element('{http://www.w3.org/2000/svg}path')
g.append(ele)
ele.set('d', simplepath.formatPath(line))
if __name__ == '__main__': #pragma: no cover
e = Extrude()
e.affect() | line += [('M', comp[n][0])]
line += [('L', comp[n][1])]
line += [('L', comp[nn][1])]
line += [('L', comp[nn][0])]
line += [('L', comp[n][0])] | random_line_split |
extrude.py | #!/usr/bin/env python
'''
Copyright (C) 2007
This program 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 2 of the License, or
(at your option) any later version.
This program is distributed in t... | (self):
paths = []
for id, node in self.selected.iteritems():
if node.tag == '{http://www.w3.org/2000/svg}path':
paths.append(node)
if len(paths) < 2:
inkex.errormsg(_('Need at least 2 paths selected'))
return
pts = [cubicsuperpath.par... | effect | identifier_name |
extrude.py | #!/usr/bin/env python
'''
Copyright (C) 2007
This program 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 2 of the License, or
(at your option) any later version.
This program is distributed in t... |
if __name__ == '__main__': #pragma: no cover
e = Extrude()
e.affect()
| def __init__(self):
inkex.Effect.__init__(self)
opts = [('-m', '--mode', 'string', 'mode', 'Lines',
'Join paths with lines or polygons'),
]
for o in opts:
self.OptionParser.add_option(o[0], o[1], action="store", type=o[2],
... | identifier_body |
extrude.py | #!/usr/bin/env python
'''
Copyright (C) 2007
This program 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 2 of the License, or
(at your option) any later version.
This program is distributed in t... |
for n1 in range(0, len(paths)):
for n2 in range(n1 + 1, len(paths)):
verts = []
for i in range(0, min(map(len, pts))):
comp = []
for j in range(0, min(len(pts[n1][i]), len(pts[n2][i]))):
comp.append([pt... | trans = paths[i].get('transform')
trans = simpletransform.parseTransform(trans)
simpletransform.applyTransformToPath(trans, pts[i]) | conditional_block |
views.py | from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import Co... | ``User`` focused activity stream. (Eg: Profile page twitter.com/justquick)
"""
user = get_object_or_404(User, username=username)
return render_to_response('activity/actor.html', {
'ctype': ContentType.objects.get_for_model(User),
'actor':user,'action_list':actor_stream(user)
}, conte... | random_line_split | |
views.py | from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import Co... |
def followers(request, content_type_id, object_id):
"""
Creates a listing of ``User``s that follow the actor defined by ``content_type_id``, ``object_id``
"""
ctype = get_object_or_404(ContentType, pk=content_type_id)
follows = Follow.objects.filter(content_type=ctype, object_id=object_id)
... | """
Index page for authenticated user's activity stream. (Eg: Your feed at github.com)
"""
return render_to_response('activity/actor.html', {
'ctype': ContentType.objects.get_for_model(request.user),
'actor':request.user,'action_list':user_stream(request.user)
}, context_instance=Request... | identifier_body |
views.py | from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import Co... | (request, content_type_id, object_id, follow=True):
"""
Creates follow relationship st ``request.user`` starts following the actor defined by ``content_type_id``, ``object_id``
"""
ctype = get_object_or_404(ContentType, pk=content_type_id)
actor = get_object_or_404(ctype.model_class(), pk=object_id)... | follow_unfollow | identifier_name |
views.py | from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import Co... |
Follow.objects.get(**lookup).delete()
return type('Deleted', (HttpResponse,), {'status_code':204})()
@login_required
def stream(request):
"""
Index page for authenticated user's activity stream. (Eg: Your feed at github.com)
"""
return render_to_response('activity/actor.html', {
'c... | Follow.objects.get_or_create(**lookup)
return type('Created', (HttpResponse,), {'status_code':201})() | conditional_block |
test_run.py | # Copyright (C) 2013 Statoil ASA, Norway.
#
# The file 'test_run.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT 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, teither version 3 of... | (self , workflow):
self.workflows.append( workflow )
#-----------------------------------------------------------------
def get_args(self):
return self.args
#-----------------------------------------------------------------
def add_check( self , check_func , arg):
if callable... | add_workflow | identifier_name |
test_run.py | # Copyright (C) 2013 Statoil ASA, Norway.
#
# The file 'test_run.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT 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, teither version 3 of... |
def get_path_prefix(self):
return self.__path_prefix
path_prefix = property( get_path_prefix , set_path_prefix )
#-----------------------------------------------------------------
def get_ert_cmd(self):
return self.__ert_cmd
def set_ert_cmd(self , cmd):
self.__er... |
#-----------------------------------------------------------------
def set_path_prefix(self , path_prefix):
self.__path_prefix = path_prefix | random_line_split |
test_run.py | # Copyright (C) 2013 Statoil ASA, Norway.
#
# The file 'test_run.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT 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, teither version 3 of... |
status = subprocess.call( argList )
if status == 0:
return (True , "ert has run successfully")
else:
return (False , "ERROR:: ert exited with status code:%s" % status)
def run(self):
if len(self.workflows):
with TestAreaContext(self.name , ... | argList.append( wf ) | conditional_block |
test_run.py | # Copyright (C) 2013 Statoil ASA, Norway.
#
# The file 'test_run.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT 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, teither version 3 of... |
def get_config_file(self):
return self.__config_file
def set_config_file(self , input_config_file):
self.__config_file = os.path.basename( input_config_file )
self.abs_config_file = os.path.abspath( input_config_file )
config_file = property( get_config_file , set_config... | parser = argparse.ArgumentParser()
parser.add_argument("-v" , "--version" , default = self.default_ert_version)
parser.add_argument("args" , nargs="*")
result = parser.parse_args(args)
self.ert_version = result.version
self.args = result.args | identifier_body |
multipleblock.rs | //
/*
*/
#![feature(inclusive_range_syntax)]
#![feature(type_ascription)]
#![feature(more_struct_aliases)]
extern crate modbus_server;
extern crate futures;
extern crate tokio_proto;
extern crate tokio_service;
extern crate docopt;
extern crate rustc_serialize;
use std::sync::{Arc,Mutex};
use std::str;
use future... | () {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| {println!("DAMN {:?}",e); e.exit()});
println!("{:?}", args);
let mut blocks : HashMap<u8,Arc<Mutex<BlankRegisters>>> = HashMap::new();
for r in args.arg_resource {
let block = Arc::new(M... | main | identifier_name |
multipleblock.rs | //
/*
*/
#![feature(inclusive_range_syntax)]
#![feature(type_ascription)]
#![feature(more_struct_aliases)]
extern crate modbus_server;
extern crate futures;
extern crate tokio_proto;
extern crate tokio_service;
extern crate docopt;
extern crate rustc_serialize;
use std::sync::{Arc,Mutex};
use std::str;
use future... | let mut blocks : HashMap<u8,Arc<Mutex<BlankRegisters>>> = HashMap::new();
for r in args.arg_resource {
let block = Arc::new(Mutex::new(BlankRegisters::new()));
blocks.insert(r,block);
}
TcpServer::new(ModbusTCPProto, args.flag_addr.parse().unwrap())
.serve(move || Ok(Modbu... | random_line_split | |
zoom.js | // Custom reveal.js integration
(function(){
var isEnabled = true;
document.querySelector( '.reveal' ).addEventListener( 'mousedown', function( event ) {
if( event.altKey && isEnabled ) {
event.preventDefault();
zoom.to({ element: event.target, pan: false });
}
} );
Reveal.addEventListener( 'overviewsho... | * transforms but falls back on zoom for IE.
*
* @param {Number} pageOffsetX
* @param {Number} pageOffsetY
* @param {Number} elementOffsetX
* @param {Number} elementOffsetY
* @param {Number} scale
*/
function magnify( pageOffsetX, pageOffsetY, elementOffsetX, elementOffsetY, scale ) {
if( supportsTra... | }, false );
/**
* Applies the CSS required to zoom in, prioritizes use of CSS3 | random_line_split |
zoom.js | // Custom reveal.js integration
(function(){
var isEnabled = true;
document.querySelector( '.reveal' ).addEventListener( 'mousedown', function( event ) {
if( event.altKey && isEnabled ) {
event.preventDefault();
zoom.to({ element: event.target, pan: false });
}
} );
Reveal.addEventListener( 'overviewsho... |
else {
options.x = options.x || 0;
options.y = options.y || 0;
// If an element is set, that takes precedence
if( !!options.element ) {
// Space around the zoomed in element to leave on screen
var padding = 20;
options.width = options.element.getBoundingClientRect().width + ( paddin... | {
zoom.out();
} | conditional_block |
zoom.js | // Custom reveal.js integration
(function(){
var isEnabled = true;
document.querySelector( '.reveal' ).addEventListener( 'mousedown', function( event ) {
if( event.altKey && isEnabled ) {
event.preventDefault();
zoom.to({ element: event.target, pan: false });
}
} );
Reveal.addEventListener( 'overviewsho... | () {
return {
x: window.scrollX !== undefined ? window.scrollX : window.pageXOffset,
y: window.scrollY !== undefined ? window.scrollY : window.pageXYffset
}
}
return {
/**
* Zooms in on either a rectangle or HTML element.
*
* @param {Object} options
* - element: HTML element to zoom in on
... | getScrollOffset | identifier_name |
zoom.js | // Custom reveal.js integration
(function(){
var isEnabled = true;
document.querySelector( '.reveal' ).addEventListener( 'mousedown', function( event ) {
if( event.altKey && isEnabled ) {
event.preventDefault();
zoom.to({ element: event.target, pan: false });
}
} );
Reveal.addEventListener( 'overviewsho... |
return {
/**
* Zooms in on either a rectangle or HTML element.
*
* @param {Object} options
* - element: HTML element to zoom in on
* OR
* - x/y: coordinates in non-transformed space to zoom in on
* - width/height: the portion of the screen to zoom in on
* - scale: can be used inst... | {
return {
x: window.scrollX !== undefined ? window.scrollX : window.pageXOffset,
y: window.scrollY !== undefined ? window.scrollY : window.pageXYffset
}
} | identifier_body |
md-butane.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) Lumol's contributors — BSD license
//! Testing molecular dynamics of butane
use lumol::input::Input;
use std::path::Path;
use std::sync::Once;
static START: Once = Once::new();
#[test]
fn bonds_detection() {
START.call_once(::env_logger::init)... | let mut config = Input::new(path).unwrap().read().unwrap();
let e_initial = config.system.total_energy();
config.simulation.run(&mut config.system, config.nsteps);
let e_final = config.system.total_energy();
assert!(f64::abs((e_initial - e_final) / e_final) < 1e-3);
} | .join("nve.toml"); | random_line_split |
md-butane.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) Lumol's contributors — BSD license
//! Testing molecular dynamics of butane
use lumol::input::Input;
use std::path::Path;
use std::sync::Once;
static START: Once = Once::new();
#[test]
fn bo | {
START.call_once(::env_logger::init);
let path = Path::new(file!()).parent()
.unwrap()
.join("data")
.join("md-butane")
.join("nve.toml");
let system = Input::new(path).unwra... | nds_detection() | identifier_name |
md-butane.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) Lumol's contributors — BSD license
//! Testing molecular dynamics of butane
use lumol::input::Input;
use std::path::Path;
use std::sync::Once;
static START: Once = Once::new();
#[test]
fn bonds_detection() {
| #[test]
fn constant_energy() {
START.call_once(::env_logger::init);
let path = Path::new(file!()).parent()
.unwrap()
.join("data")
.join("md-butane")
.join("nve.toml");
let mut... | START.call_once(::env_logger::init);
let path = Path::new(file!()).parent()
.unwrap()
.join("data")
.join("md-butane")
.join("nve.toml");
let system = Input::new(path).unwrap()... | identifier_body |
macro-stack.js | 'use strict'
import Macro from './macro.js'
/**
* マクロスタック
*/
export default class MacroStack {
/**
* コンストラクタ
*/
constructor () {
/**
* [*store manual] スタックの中身
* @private
* @type {Array}
*/
this.stack = []
}
/**
* スタックへ積む
* @param {Macro} macro マクロ
*/
push (macro)... | store (tick) {
// Generated by genStoreMethod.js
let data = {}
// 保存
// 以下、手動で復元する
// store this.stack
data.stack = []
this.stack.forEach((macro) => {
data.stack.push(macro.store(tick))
})
return data
}
/**
* 状態を復元
* @param {object} data 復元データ
* @param {number... | n {object} 保存データ
*/
| conditional_block |
macro-stack.js | 'use strict'
import Macro from './macro.js'
/**
* マクロスタック
*/
export default class MacroStack {
/**
* コンストラクタ
*/
constructor () {
/**
| manual] スタックの中身
* @private
* @type {Array}
*/
this.stack = []
}
/**
* スタックへ積む
* @param {Macro} macro マクロ
*/
push (macro) {
this.stack.push(macro)
}
/**
* スタックから降ろす
* @return {Macro} マクロ
*/
pop () {
return this.stack.pop()
}
/**
* スタックが空かどうか
* @retur... | * [*store | identifier_name |
macro-stack.js | 'use strict'
import Macro from './macro.js'
/**
* マクロスタック
*/
export default class MacroStack {
/**
* コンストラクタ
*/
constructor () {
/**
* [*store manual] スタックの中身
* @private
* @type {Array}
*/
this.stack = []
}
/**
* スタックへ積む
* @param {Macro} macro マクロ
*/
push (macro)... | // 以下、手動で復元する
// restore this.stack
this.stack = []
// console.log(data)
data.stack.forEach((macroData) => {
let macro = new Macro('')
macro.restore(macroData, tick, task)
this.stock.push(macro)
})
}
} | // Generated by genRestoreMethod.js
// 復元
| random_line_split |
macro-stack.js | 'use strict'
import Macro from './macro.js'
/**
* マクロスタック
*/
export default class MacroStack {
/**
* コンストラクタ
*/
constructor () {
/**
* [*store manual] スタックの中身
* @private
* @type {Array}
*/
this.stack = []
}
/**
* スタックへ積む
* @param {Macro} macro マクロ
*/
push (macro)... | {
return this.stack.pop()
}
/**
* スタックが空かどうか
* @return {boolean} 空ならtrue
*/
isEmpty () {
return this.stack.length <= 0
}
/**
* スタックの一番上のマクロを返す
* @return {Macro} マクロ
*/
getTop () {
if (this.isEmpty()) {
return null
} else {
return this.stack[this.stack.length ... | eturn {Macro} マクロ
*/
pop () | identifier_body |
HTMLViewer.test.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agre... | });
it('renders a smaller snapshot version', () => {
const tree = mount(<HTMLViewer configs={[config]} maxDimension={100} />);
expect(tree).toMatchSnapshot();
});
it('uses srcdoc to insert HTML into the iframe', () => {
const tree = mount(<HTMLViewer configs={[config]} />);
expect((tree.instan... | random_line_split | |
01nn_otto.py | __author__ = 'alexs'
import theano.tensor as T
import theano
import numpy as np
import cPickle
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler
import numpy as np
import random
import json
def getReferenceLabels():
referenceLabels = dict()
fo... |
class Layer():
def __init__(self, size):
self.size = size
class SigmoidLayer(Layer):
def __init__(self, size):
self.size = size
class StandardOutputWithSigmoid(Layer):
def __init__(self, size):
self.size = size
class InverseOutputLayerWithSigmoid(Layer):
def __init__(sel... | reference_labels = getReferenceLabels()
for ep in range(0, nrOfEpochs):
# random.shuffle(train_data)
overallError = 0.0
for j in range(0, len(train_set_input), batch_size):
endInterval = j + batch_size
if j + batch_size > len(train_set_input):
... | identifier_body |
01nn_otto.py | __author__ = 'alexs'
import theano.tensor as T
import theano
import numpy as np
import cPickle
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler
import numpy as np
import random
import json
def getReferenceLabels():
referenceLabels = dict()
fo... | def __init__(self, size):
self.size = size
class StandardOutputWithSigmoid(Layer):
def __init__(self, size):
self.size = size
class InverseOutputLayerWithSigmoid(Layer):
def __init__(self, size):
self.size = size
def transformInput(inputList):
res = []
for input in inpu... |
class SigmoidLayer(Layer): | random_line_split |
01nn_otto.py | __author__ = 'alexs'
import theano.tensor as T
import theano
import numpy as np
import cPickle
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler
import numpy as np
import random
import json
def getReferenceLabels():
referenceLabels = dict()
fo... |
self.cost = T.mean(T.pow(labels - out, 2)) + 0.005 * l2 + 0.005 * l1
self.output = net
self.updates = updates_weights_function(self.weights, self.weights_memory, self.cost)
self.train = theano.function([inputVector, labels], outputs=self.cost, updates=self.updates)
self.activa... | w = self.weights[i]
l2 += T.sum(w * w)
l1 += T.sum(T.abs_(w))
out = T.dot(workingV, w)
net = T.maximum(0, out)
workingV = net | conditional_block |
01nn_otto.py | __author__ = 'alexs'
import theano.tensor as T
import theano
import numpy as np
import cPickle
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler
import numpy as np
import random
import json
def getReferenceLabels():
referenceLabels = dict()
fo... | (self, experimentId):
with open(str(experimentId) + ".dat", "w") as f:
for w in self.weights:
numeric_value = w.get_value().tolist()
f.write(json.dumps(numeric_value) + "\n")
def resume(self, experimentId="default"):
ww = []
with open(str(experime... | snapshotWeigths | identifier_name |
trace.py | # Copyright 2018, OpenCensus Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... |
class wrap_task_func(object):
"""Wrap the function given to apply_async to get the tracer from context,
execute the function then clear the context."""
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
kwds = kwargs.pop("kwds")
span_context_bin... | """Wrap the apply_async function of multiprocessing.pools. Get the function
that will be called and wrap it then add the opencensus context."""
def call(self, func, *args, **kwargs):
wrapped_func = wrap_task_func(func)
_tracer = execution_context.get_opencensus_tracer()
propagator = bin... | identifier_body |
trace.py | # Copyright 2018, OpenCensus Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | (submit_func):
"""Wrap the apply_async function of multiprocessing.pools. Get the function
that will be called and wrap it then add the opencensus context."""
def call(self, func, *args, **kwargs):
wrapped_func = wrap_task_func(func)
_tracer = execution_context.get_opencensus_tracer()
... | wrap_submit | identifier_name |
trace.py | # Copyright 2018, OpenCensus Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | self.func = func
def __call__(self, *args, **kwargs):
kwds = kwargs.pop("kwds")
span_context_binary = kwargs.pop("span_context_binary")
propagator = binary_format.BinaryFormatPropagator()
kwargs["span_context"] = propagator.from_header(span_context_binary)
_tracer ... | random_line_split | |
x86_64.rs | use std::mem;
use crate::runtime::Imp;
extern {
fn objc_msgSend();
fn objc_msgSend_stret();
fn objc_msgSendSuper();
fn objc_msgSendSuper_stret();
}
pub fn msg_send_fn<R>() -> Imp {
// If the size of an object is larger than two eightbytes, it has class MEMORY.
// If the type has class MEMORY... | <R>() -> Imp {
if mem::size_of::<R>() <= 16 {
objc_msgSendSuper
} else {
objc_msgSendSuper_stret
}
}
| msg_send_super_fn | identifier_name |
x86_64.rs | use std::mem;
use crate::runtime::Imp;
extern {
fn objc_msgSend();
fn objc_msgSend_stret();
fn objc_msgSendSuper();
fn objc_msgSendSuper_stret();
}
pub fn msg_send_fn<R>() -> Imp {
// If the size of an object is larger than two eightbytes, it has class MEMORY.
// If the type has class MEMORY... | } else {
objc_msgSend_stret
}
}
pub fn msg_send_super_fn<R>() -> Imp {
if mem::size_of::<R>() <= 16 {
objc_msgSendSuper
} else {
objc_msgSendSuper_stret
}
} | // value and passes the address of this storage.
// <http://people.freebsd.org/~obrien/amd64-elf-abi.pdf>
if mem::size_of::<R>() <= 16 {
objc_msgSend | random_line_split |
x86_64.rs | use std::mem;
use crate::runtime::Imp;
extern {
fn objc_msgSend();
fn objc_msgSend_stret();
fn objc_msgSendSuper();
fn objc_msgSendSuper_stret();
}
pub fn msg_send_fn<R>() -> Imp {
// If the size of an object is larger than two eightbytes, it has class MEMORY.
// If the type has class MEMORY... | else {
objc_msgSend_stret
}
}
pub fn msg_send_super_fn<R>() -> Imp {
if mem::size_of::<R>() <= 16 {
objc_msgSendSuper
} else {
objc_msgSendSuper_stret
}
}
| {
objc_msgSend
} | conditional_block |
x86_64.rs | use std::mem;
use crate::runtime::Imp;
extern {
fn objc_msgSend();
fn objc_msgSend_stret();
fn objc_msgSendSuper();
fn objc_msgSendSuper_stret();
}
pub fn msg_send_fn<R>() -> Imp {
// If the size of an object is larger than two eightbytes, it has class MEMORY.
// If the type has class MEMORY... | {
if mem::size_of::<R>() <= 16 {
objc_msgSendSuper
} else {
objc_msgSendSuper_stret
}
} | identifier_body | |
map.rs | use core::ptr;
use super::area::PhysMemoryRange;
use super::constants::*;
use super::page_align;
use super::prelude::*;
/// Maximum number of ok-to-use entries
pub const MAX_OK_ENTRIES: usize = 20;
#[rustfmt::skip]
fn read_item(index: usize) -> (u64, u64, u32, u32) {
let base = (BOOT_TMP_MMAP_BUFFER + 2u64).as_u... | } | MemoryInfo {
allocatable: allocatable.0,
max_memory,
} | random_line_split |
map.rs | use core::ptr;
use super::area::PhysMemoryRange;
use super::constants::*;
use super::page_align;
use super::prelude::*;
/// Maximum number of ok-to-use entries
pub const MAX_OK_ENTRIES: usize = 20;
#[rustfmt::skip]
fn read_item(index: usize) -> (u64, u64, u32, u32) {
let base = (BOOT_TMP_MMAP_BUFFER + 2u64).as_u... | () -> MemoryInfo {
// load memory map from where out bootloader left it
// http://wiki.osdev.org/Detecting_Memory_(x86)#BIOS_Function:_INT_0x15.2C_EAX_.3D_0xE820
let mut allocatable = MemoryRanges::new();
let mut max_memory = 0u64;
{
let entry_count: u8 =
unsafe { ptr::read_vol... | load_memory_map | identifier_name |
map.rs | use core::ptr;
use super::area::PhysMemoryRange;
use super::constants::*;
use super::page_align;
use super::prelude::*;
/// Maximum number of ok-to-use entries
pub const MAX_OK_ENTRIES: usize = 20;
#[rustfmt::skip]
fn read_item(index: usize) -> (u64, u64, u32, u32) {
let base = (BOOT_TMP_MMAP_BUFFER + 2u64).as_u... |
} else if first_free.is_none() {
first_free = Some(i);
}
}
self.0[first_free.expect("No free entries left")] = Some(entry);
}
fn split_and_write_entry(&mut self, entry: PhysMemoryRange) {
// These are permanently reserved for the kernel
i... | {
self.0[i] = Some(ok.merge(entry));
return;
} | conditional_block |
map.rs | use core::ptr;
use super::area::PhysMemoryRange;
use super::constants::*;
use super::page_align;
use super::prelude::*;
/// Maximum number of ok-to-use entries
pub const MAX_OK_ENTRIES: usize = 20;
#[rustfmt::skip]
fn read_item(index: usize) -> (u64, u64, u32, u32) {
let base = (BOOT_TMP_MMAP_BUFFER + 2u64).as_u... |
fn split_and_write_entry(&mut self, entry: PhysMemoryRange) {
// These are permanently reserved for the kernel
if let Some(ok) = entry.above(MEMORY_RESERVED_BELOW) {
// These are permanently reserved for the heap
if let Some(below) = ok.below(PhysAddr::new(HEAP_START)) {
... | {
let mut first_free = None;
for i in 0..MAX_OK_ENTRIES {
if let Some(ok) = self.0[i] {
if ok.can_merge(entry) {
self.0[i] = Some(ok.merge(entry));
return;
}
} else if first_free.is_none() {
f... | identifier_body |
billing.ts | namespace pages {
export class billing extends Bootstrap {
public get appName(): string {
return "billing";
}
private goods: Dictionary<{ item: models.goods, count: number }>;
private scanner: Scanner;
private card_prefix: string = <any>$ts("@card_prefix");
... | tr.appendElement($ts("<td>", { class: "alignright" }).display(pay));
return tr;
}
/**
* 点击账单结算按钮进行支付结算
*
*/
public settlement() {
let vip_id = isNullOrUndefined(this.vip_info) ? -1 : this.vip_info.id;
let data = {
... | width = "60%";
if (this.vip_info.balance >= cost) {
pay = pay + "<br />" + "可以使用余额全额支付";
} else {
pay = pay + "<br />" + `<span style="color: darkred; font-size: 0.95em;">余额不足,还需要支付</span> ¥${cost - this.vip_info.balance}`;
... | conditional_block |
billing.ts | namespace pages {
export class billing extends Bootstrap {
public get appName(): string {
return "billing";
}
private goods: Dictionary<{ item: models.goods, count: number }>;
private scanner: Scanner;
private card_prefix: string = <any>$ts("@card_prefix");
... | for (let item of this.goods.Values.ToArray()) {
data.goods[item.item.id] = item.count;
}
$ts("#settlement").display("结算中").classList.add("disabled");
$ts.post('@trade', data, function (result) {
if (result.code == 400) {
... | random_line_split | |
billing.ts | namespace pages {
export class billing extends Bootstrap {
public get appName(): string {
return "billing";
}
private goods: Dictionary<{ item: models.goods, count: number }>;
private scanner: Scanner;
private card_prefix: string = <any>$ts("@card_prefix");
... | let tr = $ts("<tr>");
let displayText: string;
if (count == 1) {
displayText = item.name;
} else {
displayText = `${item.name} x${count}`;
}
tr.appendElement($ts("<td>").display(displayText));
tr.appendE... | ) {
| identifier_name |
billing.ts | namespace pages {
export class billing extends Bootstrap {
public get appName(): string {
return "billing";
}
private goods: Dictionary<{ item: models.goods, count: number }>;
private scanner: Scanner;
private card_prefix: string = <any>$ts("@card_prefix");
... | ivate showVIP(card_id: string) {
let vm = this;
$ts.get(`@get_vip?card_id=${card_id}`, function (result) {
if (result.code == 0) {
vm.vip_info = <models.VIP_members>result.info;
vm.refresh();
$ts("#vip_name").display(`... | let vm = this;
if (item_id.startsWith(this.card_prefix)) {
// 是vip卡
vm.showVIP(item_id);
} else if (this.goods.ContainsKey(item_id)) {
this.goods.Item(item_id).count += 1;
this.refresh();
} else {
... | identifier_body |
app.py | import flask
import json
import bson
import os
from flask import request, redirect
import sys
from fontana import twitter
import pymongo
DEFAULT_PORT = 2014
DB = 'fontana'
connection = pymongo.Connection("localhost", 27017)
db = connection[DB]
latest_headers = {}
MODERATED_SIZE = 40
class MongoEncoder(json.JSONE... | params['since_id'] = max(last, since_id)
# Query twitter and cache result into DB
(text, status_code, headers) = twitter.search(app.config, token, params)
data = json.loads(text)
for s in data['statuses']:
s['exclude'] = s['text'].startswith('RT ')
s['classes'] = []
if s[... | random_line_split | |
app.py | import flask
import json
import bson
import os
from flask import request, redirect
import sys
from fontana import twitter
import pymongo
DEFAULT_PORT = 2014
DB = 'fontana'
connection = pymongo.Connection("localhost", 27017)
db = connection[DB]
latest_headers = {}
MODERATED_SIZE = 40
class MongoEncoder(json.JSONE... | (ident):
"""Include given post.
"""
db['tweets'].update( { 'id_str': ident },
{ '$set': { 'exclude': False } })
return redirect('/admin.html')
@app.route('/api/session/clear/', methods=['POST'])
def signout():
"""
Perform a sign out, clears the user's session.
"""
... | include | identifier_name |
app.py | import flask
import json
import bson
import os
from flask import request, redirect
import sys
from fontana import twitter
import pymongo
DEFAULT_PORT = 2014
DB = 'fontana'
connection = pymongo.Connection("localhost", 27017)
db = connection[DB]
latest_headers = {}
MODERATED_SIZE = 40
class MongoEncoder(json.JSONE... |
def twitter_authorisation_done():
"""
Step 3 of the Twitter oAuth flow.
"""
if 'oauth_token' in flask.request.args:
token = flask.request.args
if flask.session['twitter_oauth_token'] != token['oauth_token']:
return flask.abort(403, 'oauth_token mismatch!')
auth = t... | """
Step 1 and 2 of the Twitter oAuth flow.
"""
callback = absolute_url('twitter_signin')
if 'next' in flask.request.args:
callback = '%s?next=%s' % (callback, flask.request.args['next'])
try:
token = twitter.request_token(app.config, callback)
flask.session['twitter_oauth_to... | identifier_body |
app.py | import flask
import json
import bson
import os
from flask import request, redirect
import sys
from fontana import twitter
import pymongo
DEFAULT_PORT = 2014
DB = 'fontana'
connection = pymongo.Connection("localhost", 27017)
db = connection[DB]
latest_headers = {}
MODERATED_SIZE = 40
class MongoEncoder(json.JSONE... |
else:
return twitter_authorisation_done()
@app.route('/api/twitter/session/')
def twitter_session():
"""
Check for an active Twitter session. Returns a JSON response with the
active sceen name or a 403 if there is no active session.
"""
if not flask.session.get('twitter_user_id'):
... | return twitter_authorisation_begin() | conditional_block |
MissedMessage.ts | /*
* Wire
* Copyright (C) 2018 Wire Swiss GmbH
*
* This program 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 option) any later version.
*
* This progr... | this.super_type = SuperType.MISSED;
this.affect_order(false);
}
} | random_line_split | |
MissedMessage.ts | /*
* Wire
* Copyright (C) 2018 Wire Swiss GmbH
*
* This program 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 option) any later version.
*
* This progr... | extends Message {
constructor() {
super();
this.super_type = SuperType.MISSED;
this.affect_order(false);
}
}
| MissedMessage | identifier_name |
MissedMessage.ts | /*
* Wire
* Copyright (C) 2018 Wire Swiss GmbH
*
* This program 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 option) any later version.
*
* This progr... |
}
| {
super();
this.super_type = SuperType.MISSED;
this.affect_order(false);
} | identifier_body |
encoding.rs | // Copyright (c) 2015, Sam Payson
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
// associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, dist... | (&mut self) {
self.target.sort_fields();
for dep in self.depends.iter_mut() {
dep.sort_fields();
}
}
}
pub use encoding::doc_workaround::COMPLETE_ENC;
mod doc_workaround {
#![allow(missing_docs)]
use encoding::*;
use encoding::Quantifier::*;
// These are indices into COMPLE... | sort_fields | identifier_name |
encoding.rs | // Copyright (c) 2015, Sam Payson
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
// associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, dist... | id: FieldID(2),
name: "req_fields".to_string(),
quant: Repeated,
typ: FIELD_ENCODING_TYP,
bounds: None
},
FieldEncoding {
id:... | ],
opt_rep_fields: vec![
FieldEncoding { | random_line_split |
cisco_xr_ssh.py | from __future__ import print_function
from __future__ import unicode_literals
import re
from netmiko.cisco_base_connection import CiscoSSHConnection
class CiscoXrSSH(CiscoSSHConnection):
def session_preparation(self):
"""Prepare the session after the connection has been established."""
self.set... |
label = str(label)
error_marker = 'Failed to'
alt_error_marker = 'One or more commits have occurred from other'
# Select proper command string based on arguments provided
if label:
if comment:
command_string = 'commit label {0} comment {1}'.format(l... | if '"' in comment:
raise ValueError("Invalid comment contains double quote")
comment = '"{0}"'.format(comment) | conditional_block |
cisco_xr_ssh.py | from __future__ import print_function
from __future__ import unicode_literals
import re
from netmiko.cisco_base_connection import CiscoSSHConnection
class CiscoXrSSH(CiscoSSHConnection):
def session_preparation(self):
"""Prepare the session after the connection has been established."""
self.set... |
def commit(self, confirm=False, confirm_delay=None, comment='', label='', delay_factor=1):
"""
Commit the candidate configuration.
default (no options):
command_string = commit
confirm and confirm_delay:
command_string = commit confirmed <confirm_delay>
... | """IOS-XR requires you not exit from configuration mode."""
return super(CiscoXrSSH, self).send_config_set(config_commands=config_commands,
exit_config_mode=False, **kwargs) | identifier_body |
cisco_xr_ssh.py | from __future__ import print_function
from __future__ import unicode_literals
import re
from netmiko.cisco_base_connection import CiscoSSHConnection
class CiscoXrSSH(CiscoSSHConnection):
def session_preparation(self):
"""Prepare the session after the connection has been established."""
self.set... | (self, confirm=False, confirm_delay=None, comment='', label='', delay_factor=1):
"""
Commit the candidate configuration.
default (no options):
command_string = commit
confirm and confirm_delay:
command_string = commit confirmed <confirm_delay>
label (whic... | commit | identifier_name |
cisco_xr_ssh.py | from __future__ import print_function
from __future__ import unicode_literals
import re
from netmiko.cisco_base_connection import CiscoSSHConnection
class CiscoXrSSH(CiscoSSHConnection):
def session_preparation(self):
"""Prepare the session after the connection has been established."""
self.set... | # Enter config mode (if necessary)
output = self.config_mode()
output += self.send_command_expect(command_string, strip_prompt=False, strip_command=False,
delay_factor=delay_factor)
if error_marker in output:
raise ValueError("Commit... | else:
command_string = 'commit'
| random_line_split |
button.js | // This file is part of Moodle - http://moodle.org/
//
// Moodle 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 option) any later version.
//
// Moodle is dis... | name: 'blue',
color: '#7D9FD3'
}, {
name: 'black',
color: '#333333'
}
];
Y.namespace('M.atto_fontcolor').Button = Y.Base.create('button', Y.M.editor_atto.EditorPlugin, [], {
initializer: function() {
var items = [];
Y.Array.each(co... | }, { | random_line_split |
CustomEditor.ts | /**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import { AddEventsBehaviour, AlloyEvents, Behaviour, Memento, Represe... | ]),
Representing.config({
store: {
mode: 'manual',
getValue: () => editorApi.get().fold(
() => initialValue.get().getOr(''),
(ed) => ed.getValue()
),
setValue: (component, value) => {
editorApi.get().fold(
() =... | initialValue.set(Option.none());
editorApi.set(Option.some(ea));
});
});
}) | random_line_split |
adamatch.py | # Copyright 2019 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 writing, ... | FLAGS.uratio)
elif FLAGS.augment.startswith('CTA('):
train = CTAData(source.train, target_labeled.train, target_unlabeled.train, source.nclass, FLAGS.batch,
FLAGS.uratio)
else:
raise ValueError(f'Augment flag value {FLAGS.augment} not supported.')
... | for k, v in testset.items())
if FLAGS.augment.startswith('('):
train = MixData(source.train, target_labeled.train, target_unlabeled.train, source.nclass, FLAGS.batch, | random_line_split |
adamatch.py | # Copyright 2019 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 writing, ... |
def main(argv):
del argv
print('JAX host: %d / %d' % (jax.host_id(), jax.host_count()))
print('JAX devices:\n%s' % '\n'.join(str(d) for d in jax.devices()), flush=True)
setup_tf()
source = FSL_DATASETS()[f'{FLAGS.dataset}_{FLAGS.source}-0']()
target_name, target_samples_per_class, target_seed... | def __init__(self, nclass: int, model: Callable, **kwargs):
super().__init__(nclass, kwargs)
self.model: objax.Module = model(colors=3, nclass=nclass, **kwargs)
self.model_ema = objax.optimizer.ExponentialMovingAverageModule(self.model, momentum=0.999)
if FLAGS.arch.endswith('pretrain'):... | identifier_body |
adamatch.py | # Copyright 2019 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 writing, ... | (x: JaxArray, domain: int) -> JaxArray:
return objax.functional.softmax(self.model_ema(x, training=False, domain=domain))
def loss_function(sx, sy, tx, ty, tu, progress):
sx_domain = jn.ones(2 * sx.shape[0], dtype=jn.int32)
tx_domain = jn.zeros(2 * tx.shape[0], dtype=jn.int3... | eval_op | identifier_name |
adamatch.py | # Copyright 2019 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 writing, ... |
pseudo_labels = objax.functional.softmax(logit_tu_weak)
p_labeled = self.stats.p_labeled(objax.functional.softmax(logit_sx_weak).mean(0))
p_unlabeled = self.stats.p_unlabeled(pseudo_labels.mean(0))
pseudo_labels *= (1e-6 + p_labeled) / (1e-6 + p_unlabeled)
p... | confidence_ratio = self.params.confidence | conditional_block |
backend.py | # -*- coding: utf-8 -*-
"""Simple functions for dealing with posts, replies, votes and subscriptions
within Redis and MongoDB
:license: AGPL v3, see LICENSE for more details
:copyright: 2014-2021 Joe Doherty
"""
# 3rd party imports
from flask import current_app as app, url_for
from jinja2.filters import do_capital... | total = m.db.posts.find_one({'_id': post_id}).get('comment_count')
cursor = m.db.posts.find(
{'reply_to': post_id}
).sort(
[('created', sort_order)]
).skip((page - 1) * per_page).limit(per_page)
replies = []
for reply in cursor:
# We have to get the users email for each ... | random_line_split | |
backend.py | # -*- coding: utf-8 -*-
"""Simple functions for dealing with posts, replies, votes and subscriptions
within Redis and MongoDB
:license: AGPL v3, see LICENSE for more details
:copyright: 2014-2021 Joe Doherty
"""
# 3rd party imports
from flask import current_app as app, url_for
from jinja2.filters import do_capital... | (post_id):
"""Return a list of subscribers 'user_id's for a given post
"""
return r.zrange(k.POST_SUBSCRIBERS.format(post_id), 0, -1)
def is_subscribed(user_id, post_id):
"""Returns a boolean to denote if a user is subscribed or not
"""
return r.zrank(k.POST_SUBSCRIBERS.format(post_id), user... | get_subscribers | identifier_name |
backend.py | # -*- coding: utf-8 -*-
"""Simple functions for dealing with posts, replies, votes and subscriptions
within Redis and MongoDB
:license: AGPL v3, see LICENSE for more details
:copyright: 2014-2021 Joe Doherty
"""
# 3rd party imports
from flask import current_app as app, url_for
from jinja2.filters import do_capital... |
def check_post(user_id, post_id, reply_id=None):
"""Ensure reply_id is a reply_to post_id and that post_id was created by
user_id.
.. note:: Think before testing. user_id is the person wrote post_id,
reply_id if assigned has to have been a reply to post_id.
This for checking ... | timestamp = post.get('created')
post_id = post.get('_id')
# Place on the feed
r.zadd(k.USER_FEED.format(who_id), {str(post_id): timestamp})
# Trim the feed to the 1000 max
r.zremrangebyrank(k.USER_FEED.format(who_id), 0, -1000) | conditional_block |
backend.py | # -*- coding: utf-8 -*-
"""Simple functions for dealing with posts, replies, votes and subscriptions
within Redis and MongoDB
:license: AGPL v3, see LICENSE for more details
:copyright: 2014-2021 Joe Doherty
"""
# 3rd party imports
from flask import current_app as app, url_for
from jinja2.filters import do_capital... |
class CantFlagOwn(Exception):
"""Can't flag your own post."""
pass
class AlreadyFlagged(Exception):
"""You can't flag a post twice."""
pass
class SubscriptionReasons(object):
"""Constants describing subscriptions to a post
"""
# You are the original poster
POSTER = 1
# You co... | """Raised when a user tries to vote on a post they have already voted on
"""
pass | identifier_body |
spaces.js | //Version 1.0
/**
* highlightRow and highlight are used to show a visual feedback. If the row has been successfully modified, it will be highlighted in green. Otherwise, in red
*/
function highlightRow(rowId, bgColor, after)
{
var rowSelector = $("#" + rowId);
rowSelector.css("background-color", bgColor);
rowSele... |
$('select').change(function() {
if ($(this).children('option:first-child').is(':selected')) {
$(this).addClass('placeholder');
} else {
$(this).removeClass('placeholder');
}
});
| {
if ( $("#addform").is(':visible') )
$("#addform").hide();
else
$("#addform").show();
} | identifier_body |
spaces.js | //Version 1.0
/**
* highlightRow and highlight are used to show a visual feedback. If the row has been successfully modified, it will be highlighted in green. Otherwise, in red
*/
function highlightRow(rowId, bgColor, after)
{
var rowSelector = $("#" + rowId);
rowSelector.css("background-color", bgColor);
rowSele... | if (!grid.canGoBack()) link.css({ opacity : 0.4, filter: "alpha(opacity=40)" });
else link.css("cursor", "pointer").click(function(event) { grid.prevPage(); });
paginator.append(link);
// pages
for (p = 0; p < pages.length; p++) paginator.append(pages[p]).append(" ");
// "next" link
link = $("<a class='nobg'>... | random_line_split | |
spaces.js | //Version 1.0
/**
* highlightRow and highlight are used to show a visual feedback. If the row has been successfully modified, it will be highlighted in green. Otherwise, in red
*/
function highlightRow(rowId, bgColor, after)
{
var rowSelector = $("#" + rowId);
rowSelector.css("background-color", bgColor);
rowSele... | () {
if ( $("#addform").is(':visible') )
$("#addform").hide();
else
$("#addform").show();
}
$('select').change(function() {
if ($(this).children('option:first-child').is(':selected')) {
$(this).addClass('placeholder');
} else {
$(this).removeClass('placeholder');
}
});
| showAddForm | identifier_name |
strength_and_resolution.py | ############################################
# [config.py]
# CONFIGURATION SETTINGS FOR A PARTICULAR METER
#
#
# Set the long-form name of this meter
name = "*PEAK only"
#
# [Do not remove or uncomment the following line]
Cs={}
############################################
############################################
#... | #
# A strong metrical position should contain at least one stressed syllable:
#Cs['stress.s=>p']=2
#
# A weak metrical position must contain at least one unstressed syllable;
#Cs['stress.w=>u']=2
#
#
#
######
# [Constraints regulating the WEIGHT of a syllable]
#
# The weight of a syllable is its "quantity": short or lo... | random_line_split | |
range-type-infer.rs | // run-pass
#![allow(unused_must_use)]
// Make sure the type inference for the new range expression work as
// good as the old one. Check out issue #21672, #21595 and #21649 for
// more details.
fn | () {
let xs = (0..8).map(|i| i == 1u64).collect::<Vec<_>>();
assert_eq!(xs[1], true);
let xs = (0..8).map(|i| 1u64 == i).collect::<Vec<_>>();
assert_eq!(xs[1], true);
let xs: Vec<u8> = (0..10).collect();
assert_eq!(xs.len(), 10);
for x in 0..10 { x % 2; }
for x in 0..100 { x as f32; }
... | main | identifier_name |
range-type-infer.rs | // run-pass
#![allow(unused_must_use)]
// Make sure the type inference for the new range expression work as | // more details.
fn main() {
let xs = (0..8).map(|i| i == 1u64).collect::<Vec<_>>();
assert_eq!(xs[1], true);
let xs = (0..8).map(|i| 1u64 == i).collect::<Vec<_>>();
assert_eq!(xs[1], true);
let xs: Vec<u8> = (0..10).collect();
assert_eq!(xs.len(), 10);
for x in 0..10 { x % 2; }
for x... | // good as the old one. Check out issue #21672, #21595 and #21649 for | random_line_split |
range-type-infer.rs | // run-pass
#![allow(unused_must_use)]
// Make sure the type inference for the new range expression work as
// good as the old one. Check out issue #21672, #21595 and #21649 for
// more details.
fn main() | {
let xs = (0..8).map(|i| i == 1u64).collect::<Vec<_>>();
assert_eq!(xs[1], true);
let xs = (0..8).map(|i| 1u64 == i).collect::<Vec<_>>();
assert_eq!(xs[1], true);
let xs: Vec<u8> = (0..10).collect();
assert_eq!(xs.len(), 10);
for x in 0..10 { x % 2; }
for x in 0..100 { x as f32; }
... | identifier_body | |
regions-variance-contravariant-use-covariant.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that a t... | // http://rust-lang.org/COPYRIGHT. | random_line_split |
regions-variance-contravariant-use-covariant.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <'a> {
f: &'a int
}
fn use_<'short,'long>(c: Contravariant<'short>,
s: &'short int,
l: &'long int,
_where:Option<&'short &'long ()>) {
// Test whether Contravariant<'short> <: Contravariant<'long>. Since
// 'short <= 'long, this would be t... | Contravariant | identifier_name |
font_awesome.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::generated::css_classes::C;
use seed::{prelude::*, virtual_dom::Attrs, *};
pub fn font_awesome_outline<T>(more_attrs: Attrs, icon_name: &str) -> Node<T> {
... | ]
]
} | At::Href => format!("sprites/{}.svg#{}", sprite_sheet, icon_name),
} | random_line_split |
font_awesome.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::generated::css_classes::C;
use seed::{prelude::*, virtual_dom::Attrs, *};
pub fn font_awesome_outline<T>(more_attrs: Attrs, icon_name: &str) -> Node<T> {
... | <T>(sprite_sheet: &str, more_attrs: Attrs, icon_name: &str) -> Node<T> {
let mut attrs = class![C.fill_current];
attrs.merge(more_attrs);
svg![
attrs,
r#use![
class![C.pointer_events_none],
attrs! {
At::Href => format!("sprites/{}.svg#{}", sprite_shee... | font_awesome_base | identifier_name |
font_awesome.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::generated::css_classes::C;
use seed::{prelude::*, virtual_dom::Attrs, *};
pub fn font_awesome_outline<T>(more_attrs: Attrs, icon_name: &str) -> Node<T> |
pub fn font_awesome<T>(more_attrs: Attrs, icon_name: &str) -> Node<T> {
font_awesome_base("solid", more_attrs, icon_name)
}
fn font_awesome_base<T>(sprite_sheet: &str, more_attrs: Attrs, icon_name: &str) -> Node<T> {
let mut attrs = class![C.fill_current];
attrs.merge(more_attrs);
svg![
attr... | {
font_awesome_base("regular", more_attrs, icon_name)
} | identifier_body |
smooth-scroll-to.js | /*
Smoothly scroll element to the given target (element.scrollTop)
for the given duration
Returns a promise that's fulfilled when done, or rejected if
interrupted
Taken from https://coderwall.com/p/hujlhg/smooth-scrolling-without-jquery
*/
var smoothScrollTo = function(element, target, duration) {
target ... |
var x = (point - start) / (end - start); // interpolation
return x*x*(3 - 2*x);
}
return new Promise(function(resolve, reject) {
// This is to keep track of where the element's scrollTop is
// supposed to be, based on what we're doing
var previous_top = element.scrollTop;
// T... | { return 1; } | conditional_block |
smooth-scroll-to.js | /*
Smoothly scroll element to the given target (element.scrollTop)
for the given duration
Returns a promise that's fulfilled when done, or rejected if
interrupted
Taken from https://coderwall.com/p/hujlhg/smooth-scrolling-without-jquery
*/
var smoothScrollTo = function(element, target, duration) {
target ... | var end_time = start_time + duration;
var start_top = element.scrollTop;
var distance = target - start_top;
// based on http://en.wikipedia.org/wiki/Smoothstep
var smooth_step = function(start, end, point) {
if(point <= start) { return 0; }
if(point >= end) { return 1; }
var x = (point - s... | random_line_split | |
star-rating.component.ts | import { Component, Input } from '@angular/core';
@Component({
selector: 'star-rating',
templateUrl: './star-rating.component.html',
styleUrls: ['./star-rating.component.css']
})
export class StarRatingComponent {
private readonly star = {
full: 'fa-star',
half: 'fa-star-half-o',
empty: 'fa-star-o'
};
sta... | (): void {
this.createStars();
}
onClick(rating: number): void {
if (this.readonly) {
this.rating = rating;
this.createStars();
}
}
private createStars(): void {
for (let i = 1; i <= 5; i++) {
const diff = this.rating - i;
if (diff >= 0) {
this.stars.push(this.star.full);
} else if (di... | ngOnInit | identifier_name |
star-rating.component.ts | import { Component, Input } from '@angular/core';
@Component({
selector: 'star-rating',
templateUrl: './star-rating.component.html',
styleUrls: ['./star-rating.component.css']
})
export class StarRatingComponent {
private readonly star = {
full: 'fa-star',
half: 'fa-star-half-o',
empty: 'fa-star-o'
};
sta... | this.createStars();
}
onClick(rating: number): void {
if (this.readonly) {
this.rating = rating;
this.createStars();
}
}
private createStars(): void {
for (let i = 1; i <= 5; i++) {
const diff = this.rating - i;
if (diff >= 0) {
this.stars.push(this.star.full);
} else if (diff >= -0.67... | @Input() readonly: boolean = true;
ngOnInit(): void { | random_line_split |
star-rating.component.ts | import { Component, Input } from '@angular/core';
@Component({
selector: 'star-rating',
templateUrl: './star-rating.component.html',
styleUrls: ['./star-rating.component.css']
})
export class StarRatingComponent {
private readonly star = {
full: 'fa-star',
half: 'fa-star-half-o',
empty: 'fa-star-o'
};
sta... |
}
| {
for (let i = 1; i <= 5; i++) {
const diff = this.rating - i;
if (diff >= 0) {
this.stars.push(this.star.full);
} else if (diff >= -0.67) {
this.stars.push(this.star.half);
} else {
this.stars.push(this.star.empty);
}
}
} | identifier_body |
star-rating.component.ts | import { Component, Input } from '@angular/core';
@Component({
selector: 'star-rating',
templateUrl: './star-rating.component.html',
styleUrls: ['./star-rating.component.css']
})
export class StarRatingComponent {
private readonly star = {
full: 'fa-star',
half: 'fa-star-half-o',
empty: 'fa-star-o'
};
sta... |
}
}
}
| {
this.stars.push(this.star.empty);
} | conditional_block |
resource_loader.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | def readahead_file_path(path, readahead='128M'): # pylint: disable=unused-argument
"""Readahead files not implemented; simply returns given path."""
return path | random_line_split | |
resource_loader.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
# pylint: disable=protected-access
@tf_export(v1=['resource_loader.get_data_files_path'])
def get_data_files_path():
"""Get a direct path to the data files colocated with the script.
Returns:
The directory where files specified in data attribute of py_test
and py_binary are stored.
"""
return _os.pa... | """Load the resource at given path, where path is relative to tensorflow/.
Args:
path: a string resource path relative to tensorflow/.
Returns:
The contents of that resource.
Raises:
IOError: If the path is not found, or the resource can't be opened.
"""
with open(get_path_to_datafile(path), 'r... | identifier_body |
resource_loader.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ():
"""Get a root directory containing all the data attributes in the build rule.
Returns:
The path to the specified file present in the data attribute of py_test
or py_binary. Falls back to returning the same as get_data_files_path if it
fails to detect a bazel runfiles directory.
"""
script_dir =... | get_root_dir_with_all_resources | identifier_name |
resource_loader.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
return data_files_dir or script_dir
@tf_export(v1=['resource_loader.get_path_to_datafile'])
def get_path_to_datafile(path):
"""Get the path to the specified file in the data dependencies.
The path is relative to tensorflow/
Args:
path: a string resource path relative to tensorflow/
Returns:
The... | directories.append(new_candidate_dir) | conditional_block |
path.js | const path = require('path')
const config = require('config')
const git = require('git-rev-sync')
const CDN = config.get('cdn')
const appVersion = git.short()
const CDN_URI = appVersion
const CDN_URL = CDN ? `${CDN}/${CDN_URI}` : ''
const PUBLIC_PATH = CDN ? `${CDN}/${CDN_URI}/assets/` : '/assets/'
const ROOT_PATH =... | ENTRY_PATH,
SOURCE_PATH,
ASSETS_PATH
} | random_line_split | |
perform_compile.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {isSyntaxError, Position} from '@angular/compiler';
import * as ts from 'typescript';
import {absoluteFrom, A... |
// Return 2 if any of the errors were unknown.
return diags.some(d => d.source === 'angular' && d.code === api.UNKNOWN_ERROR_CODE) ? 2 : 1;
}
export function performCompilation({
rootNames,
options,
host,
oldProgram,
emitCallback,
mergeEmitResultsCallback,
gatherDiagnostics = defaultGatherDiagnosti... | {
// If we have a result and didn't get any errors, we succeeded.
return 0;
} | conditional_block |
perform_compile.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {isSyntaxError, Position} from '@angular/compiler';
import * as ts from 'typescript';
import {absoluteFrom, A... | (diags: Diagnostics|undefined) {
if (diags) {
allDiagnostics.push(...diags);
return !hasErrors(diags);
}
return true;
}
let checkOtherDiagnostics = true;
// Check parameter diagnostics
checkOtherDiagnostics = checkOtherDiagnostics &&
checkDiagnostics([...program.getTsOptionDiagnos... | checkDiagnostics | identifier_name |
perform_compile.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {isSyntaxError, Position} from '@angular/compiler';
import * as ts from 'typescript';
import {absoluteFrom, A... |
export function formatDiagnostic(
diagnostic: api.Diagnostic, host: ts.FormatDiagnosticsHost = defaultFormatHost) {
let result = '';
const newLine = host.getNewLine();
const span = diagnostic.span;
if (span) {
result += `${
formatDiagnosticPosition(
{fileName: span.start.file.url, ... | {
const newLine = host.getNewLine();
let result = '';
if (indent) {
result += newLine;
for (let i = 0; i < indent; i++) {
result += ' ';
}
}
result += chain.messageText;
const position = chain.position;
// add position if available, and we are not at the depest frame
if (position &&... | identifier_body |
perform_compile.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {isSyntaxError, Position} from '@angular/compiler';
import * as ts from 'typescript';
import {absoluteFrom, A... | return diags
.map(diagnostic => {
if (api.isTsDiagnostic(diagnostic)) {
return replaceTsWithNgInErrors(
ts.formatDiagnosticsWithColorAndContext([diagnostic], host));
} else {
return formatDiagnostic(diagnostic, host);
}
})
... | if (diags && diags.length) { | random_line_split |
notrootView.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
return this._element;
}
private render(): void {
this._element = $([
'<div class="notroot-view">',
'<p>', nls.localize('wrongRoot', "This directory seems to be contained in a git repository."), '</p>',
'<p>', nls.localize('pleaseRestart', "Open the repository's root directory in order to access Git fe... | {
this.render();
} | conditional_block |
notrootView.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (): actions.IAction[] {
return [];
}
} | getSecondaryActions | identifier_name |
notrootView.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
private render(): void {
this._element = $([
'<div class="notroot-view">',
'<p>', nls.localize('wrongRoot', "This directory seems to be contained in a git repository."), '</p>',
'<p>', nls.localize('pleaseRestart', "Open the repository's root directory in order to access Git features."), '</p>',
'</div... | {
if (!this._element) {
this.render();
}
return this._element;
} | identifier_body |
notrootView.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | '<div class="notroot-view">',
'<p>', nls.localize('wrongRoot', "This directory seems to be contained in a git repository."), '</p>',
'<p>', nls.localize('pleaseRestart', "Open the repository's root directory in order to access Git features."), '</p>',
'</div>'
].join('')).getHTMLElement();
}
public foc... |
private render(): void {
this._element = $([ | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.