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 |
|---|---|---|---|---|
test_determine_repository_should_use_local_repo.py | # -*- coding: utf-8 -*-
import os
from cookiecutter import repository, exceptions
import pytest
def test_finds_local_repo(tmpdir):
"""A valid local repository should be returned."""
project_dir = repository.determine_repo_dir(
'tests/fake-repo',
abbreviations={},
clone_to_dir=str(tmpd... | (tmpdir):
"""A local repository without a cookiecutter.json should raise a
`RepositoryNotFound` exception.
"""
template_path = os.path.join('tests', 'fake-repo-bad')
with pytest.raises(exceptions.RepositoryNotFound) as err:
repository.determine_repo_dir(
template_path,
... | test_local_repo_with_no_context_raises | identifier_name |
test_determine_repository_should_use_local_repo.py | # -*- coding: utf-8 -*-
import os
from cookiecutter import repository, exceptions
import pytest
def test_finds_local_repo(tmpdir):
"""A valid local repository should be returned."""
project_dir = repository.determine_repo_dir(
'tests/fake-repo',
abbreviations={},
clone_to_dir=str(tmpd... |
assert 'tests/fake-repo' == project_dir
def test_local_repo_with_no_context_raises(tmpdir):
"""A local repository without a cookiecutter.json should raise a
`RepositoryNotFound` exception.
"""
template_path = os.path.join('tests', 'fake-repo-bad')
with pytest.raises(exceptions.RepositoryNotFo... | ) | random_line_split |
test_determine_repository_should_use_local_repo.py | # -*- coding: utf-8 -*-
import os
from cookiecutter import repository, exceptions
import pytest
def test_finds_local_repo(tmpdir):
"""A valid local repository should be returned."""
project_dir = repository.determine_repo_dir(
'tests/fake-repo',
abbreviations={},
clone_to_dir=str(tmpd... |
def test_local_repo_typo(tmpdir):
"""An unknown local repository should raise a `RepositoryNotFound`
exception.
"""
template_path = os.path.join('tests', 'unknown-repo')
with pytest.raises(exceptions.RepositoryNotFound) as err:
repository.determine_repo_dir(
template_path,
... | """A local repository without a cookiecutter.json should raise a
`RepositoryNotFound` exception.
"""
template_path = os.path.join('tests', 'fake-repo-bad')
with pytest.raises(exceptions.RepositoryNotFound) as err:
repository.determine_repo_dir(
template_path,
abbreviation... | identifier_body |
timeout.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
#[unsafe_destructor]
impl<T> Drop for AccessTimeout<T> {
fn drop(&mut self) {
match self.timer {
Some(ref timer) => unsafe {
let data = uvll::get_data_for_uv_handle(timer.handle);
let _data: Box<TimerContext> = mem::transmute(data);
},
... | {
match *self.state {
TimeoutPending(NoWaiter) | TimeoutPending(AccessPending) =>
unreachable!(),
NoTimeout | TimedOut => {}
TimeoutPending(RequestPending) => {
*self.state = TimeoutPending(NoWaiter);
}
}
} | identifier_body |
timeout.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&mut self) {
match *self.state {
TimeoutPending(NoWaiter) | TimeoutPending(AccessPending) =>
unreachable!(),
NoTimeout | TimedOut => {}
TimeoutPending(RequestPending) => {
*self.state = TimeoutPending(NoWaiter);
}
}
}
... | drop | identifier_name |
timeout.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | match self.timer {
Some(ref timer) => unsafe {
let data = uvll::get_data_for_uv_handle(timer.handle);
let _data: Box<TimerContext> = mem::transmute(data);
},
None => {}
}
}
}
////////////////////////////////////////////////////////... | random_line_split | |
test.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: test.py
#
# Copyright 2018 Costas Tyfoxylos
#
# 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 li... |
def test(stage):
emojize = bootstrap()
exit_code = _test(stage)
success = not exit_code
if success:
LOGGER.info('%s Tested stage "%s" successfully! %s',
emojize(':white_heavy_check_mark:'),
stage,
emojize(':thumbs_up:'))
else:
... | from cookiecutter.main import cookiecutter
template = os.path.abspath('.')
context = os.path.abspath('cookiecutter.json')
with tempdir():
cookiecutter(template,
extra_context=json.loads(open(context).read()),
no_input=True)
os.chdir(os.listdir('.')[0... | identifier_body |
test.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: test.py
#
# Copyright 2018 Costas Tyfoxylos
#
# 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 li... | (stage):
emojize = bootstrap()
exit_code = _test(stage)
success = not exit_code
if success:
LOGGER.info('%s Tested stage "%s" successfully! %s',
emojize(':white_heavy_check_mark:'),
stage,
emojize(':thumbs_up:'))
else:
LOGGE... | test | identifier_name |
test.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: test.py
#
# Copyright 2018 Costas Tyfoxylos
#
# 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 li... | args = get_arguments()
stage = next((argument for argument in ('lint', 'test', 'build', 'document')
if getattr(args, argument)), None)
test(stage) | conditional_block | |
test.py | # File: test.py
#
# Copyright 2018 Costas Tyfoxylos
#
# 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, m... | #!/usr/bin/env python
# -*- coding: utf-8 -*- | random_line_split | |
doc.py | # (c) 2014, James Tanner <tanner.jc@gmail.com>
#
# Ansible 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.
#
# Ansible is distributed i... | maintainers.update(doc['author'])
if 'maintainers' in doc:
if isinstance(doc['maintainers'], string_types):
maintainers.add(doc['author'])
else:
maintainers.update(doc['author'])
text.append('MAINTAINERS: ' + ', '.join(maintainers... | random_line_split | |
doc.py | # (c) 2014, James Tanner <tanner.jc@gmail.com>
#
# Ansible 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.
#
# Ansible is distributed i... |
def find_modules(self, path):
for module in os.listdir(path):
full_path = '/'.join([path, module])
if module.startswith('.'):
continue
elif os.path.isdir(full_path):
continue
elif any(module.endswith(x) for x in C.BLACKLIST_E... | super(DocCLI, self).run()
if self.options.module_path is not None:
for i in self.options.module_path.split(os.pathsep):
module_loader.add_directory(i)
# list modules
if self.options.list_dir:
paths = module_loader._get_paths()
for path in pat... | identifier_body |
doc.py | # (c) 2014, James Tanner <tanner.jc@gmail.com>
#
# Ansible 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.
#
# Ansible is distributed i... |
elif module in C.IGNORE_FILES:
continue
elif module.startswith('_'):
if os.path.islink(full_path): # avoids aliases
continue
module = os.path.splitext(module)[0] # removes the extension
module = module.lstrip('_') #... | continue | conditional_block |
doc.py | # (c) 2014, James Tanner <tanner.jc@gmail.com>
#
# Ansible 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.
#
# Ansible is distributed i... | (self, doc):
opt_indent=" "
text = []
text.append("> %s\n" % doc['module'].upper())
pad = display.columns * 0.20
limit = max(display.columns - int(pad), 70)
if isinstance(doc['description'], list):
desc = " ".join(doc['description'])
else:
... | get_man_text | identifier_name |
q2_sigmoid.py | import numpy as np
def | (x):
"""
Compute the sigmoid function for the input here.
"""
x = 1. / (1. + np.exp(-x))
return x
def sigmoid_grad(f):
"""
Compute the gradient for the sigmoid function here. Note that
for this implementation, the input f should be the sigmoid
function value of your origin... | sigmoid | identifier_name |
q2_sigmoid.py | import numpy as np
def sigmoid(x):
"""
Compute the sigmoid function for the input here.
"""
x = 1. / (1. + np.exp(-x))
return x
def sigmoid_grad(f):
|
def test_sigmoid_basic():
"""
Some simple tests to get you started.
Warning: these are not exhaustive.
"""
print "Running basic tests..."
x = np.array([[1, 2], [-1, -2]])
f = sigmoid(x)
g = sigmoid_grad(f)
print f
assert np.amax(f - np.array([[0.73105858, 0.88079708],
... | """
Compute the gradient for the sigmoid function here. Note that
for this implementation, the input f should be the sigmoid
function value of your original input x.
"""
f = f * (1. - f)
return f | identifier_body |
q2_sigmoid.py | import numpy as np
def sigmoid(x):
"""
Compute the sigmoid function for the input here.
"""
x = 1. / (1. + np.exp(-x))
return x
def sigmoid_grad(f):
"""
Compute the gradient for the sigmoid function here. Note that
for this implementation, the input f should be the sigmoid
... | test_sigmoid_basic();
#test_sigmoid() | conditional_block | |
q2_sigmoid.py | import numpy as np
def sigmoid(x):
"""
Compute the sigmoid function for the input here.
"""
x = 1. / (1. + np.exp(-x))
return x
def sigmoid_grad(f):
"""
Compute the gradient for the sigmoid function here. Note that
for this implementation, the input f should be the sigmoid
... | #test_sigmoid() | random_line_split | |
views.py | # -*- coding: utf-8 -*-
#
# Copyright 2015, Foxugly. All rights reserved.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any late... | (request, patient_id, text):
p = get_object_or_404(Patient, id=patient_id, confirm=text)
if p:
p.active = True
p.confirm = None
p.save()
return render(request, 'valid.tpl')
def confirm_remove(request, patient_id, slot_id):
s = get_object_or_404(Slot, id=slot_id, patient__id... | confirm_create | identifier_name |
views.py | # -*- coding: utf-8 -*-
#
# Copyright 2015, Foxugly. All rights reserved.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any late... |
def search_patient(request):
if request.is_ajax():
email = request.GET['email']
if len(email) > 5:
p = Patient.objects.filter(email=email)
if len(p):
return HttpResponse(json.dumps({'return': True, 'patient': p[0].as_json()}))
else:
... | import json
from agenda.models import Slot
from django.shortcuts import render
from django.shortcuts import get_object_or_404
| random_line_split |
views.py | # -*- coding: utf-8 -*-
#
# Copyright 2015, Foxugly. All rights reserved.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any late... |
def confirm_create(request, patient_id, text):
p = get_object_or_404(Patient, id=patient_id, confirm=text)
if p:
p.active = True
p.confirm = None
p.save()
return render(request, 'valid.tpl')
def confirm_remove(request, patient_id, slot_id):
s = get_object_or_404(Slot, id... | email = request.GET['email']
if len(email) > 5:
p = Patient.objects.filter(email=email)
if len(p):
return HttpResponse(json.dumps({'return': True, 'patient': p[0].as_json()}))
else:
return HttpResponse(json.dumps({'return': False}))
els... | conditional_block |
views.py | # -*- coding: utf-8 -*-
#
# Copyright 2015, Foxugly. All rights reserved.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any late... | s = get_object_or_404(Slot, id=slot_id, patient__id=patient_id)
# s = Slot.objects.get(id=slot_id, patient__id=patient_id)
# TODO SEND MAIL PATIENT_REMOVE_BOOKING
s.clean_slot()
s.save()
return render(request, 'valid.tpl') | identifier_body | |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import setuptools
from setuptools import setup, find_packages
if setuptools.__version__ < '0.7':
raise RuntimeError("setuptools must be newer than 0.7")
version = "0.1.3"
setup(
name="pinger",
version=version,
author="Pedro Palhares (pedrospdc)",
aut... | ],
install_requires=[
"requests>=2.4.3",
"peewee>=2.4.0"
],
scripts=["bin/pinger"],
) | "Operating System :: OS Independent",
"Programming Language :: Python", | random_line_split |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import setuptools
from setuptools import setup, find_packages
if setuptools.__version__ < '0.7':
|
version = "0.1.3"
setup(
name="pinger",
version=version,
author="Pedro Palhares (pedrospdc)",
author_email="pedrospdc@gmail.com",
description="Website monitoring tool",
url="https://github.com/pedrospdc/pinger",
download_url="https://github.com/pedrospdc/pinger/tarball/{}".format(version)... | raise RuntimeError("setuptools must be newer than 0.7") | conditional_block |
app.component.ts | import { ScheduleService } from './services/schedule.service';
import { Router, ActivatedRoute } from '@angular/router';
import { Component, HostListener } from '@angular/core';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import * as XLSX from 'xlsx';
@Component({
selector: 'sch-app',
templa... | //need to cast html tag
//reference: http://stackoverflow.com/questions/12989741/the-property-value-does-not-exist-on-value-of-type-htmlelement
var file = (<HTMLInputElement>document.getElementById("xls")).files[0];
//new fileReader
let fileReader = new FileReader();
fileReader.readAsBinaryStri... | //get file | random_line_split |
app.component.ts | import { ScheduleService } from './services/schedule.service';
import { Router, ActivatedRoute } from '@angular/router';
import { Component, HostListener } from '@angular/core';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import * as XLSX from 'xlsx';
@Component({
selector: 'sch-app',
templa... | downloadConfig(): void {
var blob = new Blob([JSON.stringify(this.scheduleService.config, null, 1)], { "type": "text/plain;charset=utf-8" });
if (window.navigator.msSaveOrOpenBlob) // IE hack; see http://msdn.microsoft.com/en-us/library/ie/hh779016.aspx
window.navigator.msSaveBlob(blob, "config.json");
... | //get file
//need to cast html tag
//reference: http://stackoverflow.com/questions/12989741/the-property-value-does-not-exist-on-value-of-type-htmlelement
var file = (<HTMLInputElement>document.getElementById("xls")).files[0];
//new fileReader
let fileReader = new FileReader();
fileReader.r... | identifier_body |
app.component.ts | import { ScheduleService } from './services/schedule.service';
import { Router, ActivatedRoute } from '@angular/router';
import { Component, HostListener } from '@angular/core';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import * as XLSX from 'xlsx';
@Component({
selector: 'sch-app',
templa... | ($event): void {
//get file
//need to cast html tag
//reference: http://stackoverflow.com/questions/12989741/the-property-value-does-not-exist-on-value-of-type-htmlelement
var file = (<HTMLInputElement>document.getElementById("file")).files[0];
//new fileReader
let fileReader = new FileReader()... | fileChanged | identifier_name |
wikiPlugin.ts | /**
* @module Wiki
* @main Wiki
*/
/// <reference path="wikiHelpers.ts"/>
/// <reference path="../../ui/js/dropDown.ts"/>
/// <reference path="../../core/js/workspace.ts"/>
/// <reference path="../../git/js/git.ts"/>
/// <reference path="../../git/js/gitHelpers.ts"/>
/// <reference path="../../helpers/js/pluginHelpe... |
}
};
return self;
});
_module.factory('fileExtensionTypeRegistry', () => {
return {
"image": ["svg", "png", "ico", "bmp", "jpg", "gif"],
"markdown": ["md", "markdown", "mdown", "mkdn", "mkd"],
"htmlmixed": ["html", "xhtml", "htm"],
"text/x-java": ["java"],
"text/x-s... | {
menu.add(extendedMenu);
} | conditional_block |
wikiPlugin.ts | /**
* @module Wiki
* @main Wiki
*/
/// <reference path="wikiHelpers.ts"/> | /// <reference path="../../core/js/workspace.ts"/>
/// <reference path="../../git/js/git.ts"/>
/// <reference path="../../git/js/gitHelpers.ts"/>
/// <reference path="../../helpers/js/pluginHelpers.ts"/>
/// <reference path="../../helpers/js/urlHelpers.ts"/>
/// <reference path="./wikiRepository.ts"/>
module Wiki {
... | /// <reference path="../../ui/js/dropDown.ts"/> | random_line_split |
login.rs | use command_prelude::*;
use std::io::{self, BufRead};
use cargo::core::{Source, SourceId};
use cargo::sources::RegistrySource;
use cargo::util::{CargoError, CargoResultExt};
use cargo::ops;
pub fn cli() -> App {
subcommand("login")
.about(
"Save an api token from the registry locally. \
... | {
let registry = args.registry(config)?;
let token = match args.value_of("token") {
Some(token) => token.to_string(),
None => {
let host = match registry {
Some(ref _registry) => {
return Err(format_err!(
"token must be pro... | identifier_body | |
login.rs | use command_prelude::*;
use std::io::{self, BufRead};
use cargo::core::{Source, SourceId};
use cargo::sources::RegistrySource;
use cargo::util::{CargoError, CargoResultExt};
use cargo::ops;
pub fn cli() -> App {
subcommand("login")
.about(
"Save an api token from the registry locally. \
... | (config: &mut Config, args: &ArgMatches) -> CliResult {
let registry = args.registry(config)?;
let token = match args.value_of("token") {
Some(token) => token.to_string(),
None => {
let host = match registry {
Some(ref _registry) => {
return Err(f... | exec | identifier_name |
login.rs | use command_prelude::*;
use std::io::{self, BufRead};
use cargo::core::{Source, SourceId}; | use cargo::ops;
pub fn cli() -> App {
subcommand("login")
.about(
"Save an api token from the registry locally. \
If token is not specified, it will be read from stdin.",
)
.arg(Arg::with_name("token"))
.arg(opt("host", "Host to set the token for").value_nam... | use cargo::sources::RegistrySource;
use cargo::util::{CargoError, CargoResultExt}; | random_line_split |
dialog-container.ts | /**
* @license
* Copyright Google Inc. 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 {
Component,
ComponentRef,
ViewChild,
ViewEncapsulation,
NgZone,
ElementRef,
EventEmitter,
In... |
}
| {
this._state = 'exit';
// Mark the container for check so it can react if the
// view container is using OnPush change detection.
this._changeDetectorRef.markForCheck();
} | identifier_body |
dialog-container.ts | /**
* @license
* Copyright Google Inc. 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 {
Component,
ComponentRef,
ViewChild,
ViewEncapsulation,
NgZone,
ElementRef,
EventEmitter,
In... | ChangeDetectorRef,
} from '@angular/core';
import {
animate,
trigger,
state,
style,
transition,
AnimationEvent,
} from '@angular/animations';
import {DOCUMENT} from '@angular/platform-browser';
import {BasePortalHost, ComponentPortal, PortalHostDirective, TemplatePortal} from '../core';
import {MdDialogCo... | Optional, | random_line_split |
dialog-container.ts | /**
* @license
* Copyright Google Inc. 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 {
Component,
ComponentRef,
ViewChild,
ViewEncapsulation,
NgZone,
ElementRef,
EventEmitter,
In... | <T>(portal: ComponentPortal<T>): ComponentRef<T> {
if (this._portalHost.hasAttached()) {
throwMdDialogContentAlreadyAttachedError();
}
this._savePreviouslyFocusedElement();
return this._portalHost.attachComponentPortal(portal);
}
/**
* Attach a TemplatePortal as content to this dialog con... | attachComponentPortal | identifier_name |
dialog-container.ts | /**
* @license
* Copyright Google Inc. 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 {
Component,
ComponentRef,
ViewChild,
ViewEncapsulation,
NgZone,
ElementRef,
EventEmitter,
In... |
}
/** Saves a reference to the element that was focused before the dialog was opened. */
private _savePreviouslyFocusedElement() {
if (this._document) {
this._elementFocusedBeforeDialogWasOpened = this._document.activeElement as HTMLElement;
}
}
/** Callback, invoked whenever an animation on ... | {
this._focusTrap.destroy();
} | conditional_block |
wanderer.py | '''
Created on Jan 19, 2013
@author: dsnowdon
'''
import os
import tempfile
import datetime
import json
import logging
from naoutil.jsonobj import to_json_string, from_json_string
from naoutil.general import find_class
import robotstate
from event import *
from action import *
from naoutil.naoenv import make_enviro... |
def save_direction(env, hRad):
env.memory.insertData(MEM_HEADING, hRad)
'''
Get the entire path
'''
def get_path(env):
return env.memory.getData(MEM_WALK_PATH)
def set_path(env, path):
env.memory.insertData(MEM_WALK_PATH, path)
'''
Get the last position the robot was at by looking at the path
'''
def g... | env.log(msg)
for p in plan:
env.log(str(p)) | identifier_body |
wanderer.py | '''
Created on Jan 19, 2013
@author: dsnowdon
'''
import os
import tempfile
import datetime
import json
import logging
from naoutil.jsonobj import to_json_string, from_json_string
from naoutil.general import find_class
import robotstate
from event import *
from action import *
from naoutil.naoenv import make_enviro... |
'''
Get the instance of the planner, creating an instance of the configured class if we don't already
have a planner instance
'''
def get_planner_instance(env):
global planner_instance
if not planner_instance:
fqcn = env.get_property(DEFAULT_CONFIG_FILE, PROPERTY_PLANNER_CLASS, DEFAULT_PLANNER_CLASS)... | self.logFile.close() | conditional_block |
wanderer.py | '''
Created on Jan 19, 2013
@author: dsnowdon
'''
import os
import tempfile
import datetime
import json
import logging
from naoutil.jsonobj import to_json_string, from_json_string
from naoutil.general import find_class
import robotstate
from event import *
from action import *
from naoutil.naoenv import make_enviro... | (self, fp, buffer_size=1024):
if self.logFile:
self.logFile.seek(0)
fp.write('[\n')
while 1:
copy_buffer = self.logFile.read(buffer_size)
if copy_buffer:
fp.write(copy_buffer)
else:
break
... | write_sensor_data_to_file | identifier_name |
wanderer.py | '''
Created on Jan 19, 2013
@author: dsnowdon
'''
import os
import tempfile
import datetime
import json
import logging
from naoutil.jsonobj import to_json_string, from_json_string
from naoutil.general import find_class
import robotstate
from event import *
from action import *
from naoutil.naoenv import make_enviro... | WANDERER_NAME = "wanderer"
# START GLOBALS
# We put instances of planners, executors and mappers here so we don't need to continually create
# new instances
planner_instance = None
executor_instance = None
mapper_instance = None
updater_instances = None
# END GLOBALS
wanderer_logger = logging.getLogger("wanderer.wan... | HEAD_HORIZONTAL_OFFSET = 0 | random_line_split |
server.ts | import * as ws from "ws";
import { SERVER_HOST, SERVER_PATH, SERVER_PORT } from "../shared/config";
import { HEARTBEAT_INTERVAL_MS } from "../shared/const";
import { ServerRooms } from "./room/serverRooms";
import { ServerPlayer } from "./room/serverPlayer";
export interface Socket extends ws {
pingSent: number;
... | {
private roomManager = new ServerRooms();
private ws: ws.Server;
private pingInterval: NodeJS.Timeout;
constructor() {
this.ws = new ws.Server({
host: "0.0.0.0",
port: SERVER_PORT,
path: SERVER_PATH,
maxPayload: 256,
clientTracking: ... | Server | identifier_name |
server.ts | import * as ws from "ws";
import { SERVER_HOST, SERVER_PATH, SERVER_PORT } from "../shared/config";
import { HEARTBEAT_INTERVAL_MS } from "../shared/const";
import { ServerRooms } from "./room/serverRooms";
import { ServerPlayer } from "./room/serverPlayer";
export interface Socket extends ws {
pingSent: number;
... |
}
| {
this.ws = new ws.Server({
host: "0.0.0.0",
port: SERVER_PORT,
path: SERVER_PATH,
maxPayload: 256,
clientTracking: true,
});
this.ws.on("connection", (socket: Socket) => {
const player = new ServerPlayer(socket, this.roomM... | identifier_body |
server.ts | import * as ws from "ws";
import { SERVER_HOST, SERVER_PATH, SERVER_PORT } from "../shared/config";
import { HEARTBEAT_INTERVAL_MS } from "../shared/const";
import { ServerRooms } from "./room/serverRooms";
import { ServerPlayer } from "./room/serverPlayer";
export interface Socket extends ws {
pingSent: number;
... |
client.pingSent = new Date().getTime();
client.ping();
});
}, HEARTBEAT_INTERVAL_MS);
console.debug(`Running WebSocket server at ${SERVER_HOST}:${SERVER_PATH}${SERVER_PORT}`);
}
}
| {
return client.terminate();
} | conditional_block |
server.ts | import * as ws from "ws";
import { SERVER_HOST, SERVER_PATH, SERVER_PORT } from "../shared/config";
import { HEARTBEAT_INTERVAL_MS } from "../shared/const";
import { ServerRooms } from "./room/serverRooms";
import { ServerPlayer } from "./room/serverPlayer";
export interface Socket extends ws {
pingSent: number;
... | }, HEARTBEAT_INTERVAL_MS);
console.debug(`Running WebSocket server at ${SERVER_HOST}:${SERVER_PATH}${SERVER_PORT}`);
}
} | random_line_split | |
parametric_system.py | import floq.core.fixed_system as fs
import floq.evolution as ev
import floq.errors as er
import floq.helpers.index as h
class ParametricSystemBase(object):
"""
Base class to specify a physical system that still has open parameters,
such as the control amplitudes, the control duration, or other arbitrary
... |
def calculate_dhf(self, controls):
return self.dhf(controls, self.parameters, self.omega)
def get_system(self, controls, t):
hf = self.calculate_hf(controls)
dhf = self.calculate_dhf(controls)
return fs.FixedSystem(hf, dhf, self.nz, self.omega, t)
| return self.hf(controls, self.parameters, self.omega) | identifier_body |
parametric_system.py | import floq.core.fixed_system as fs
import floq.evolution as ev
import floq.errors as er
import floq.helpers.index as h
class ParametricSystemBase(object):
"""
Base class to specify a physical system that still has open parameters,
such as the control amplitudes, the control duration, or other arbitrary
... |
def is_nz_ok(self, controls, t):
system = self.get_system(controls, t)
try:
u = ev.evolve_system(system)
except er.EigenvalueNumberError:
return False
return h.is_unitary(u)
def set_nz(self, controls, t):
if self.is_nz_ok(controls, t):
... | """
def get_system(self, controls, t):
raise NotImplementedError("get_system not implemented.") | random_line_split |
parametric_system.py | import floq.core.fixed_system as fs
import floq.evolution as ev
import floq.errors as er
import floq.helpers.index as h
class ParametricSystemBase(object):
"""
Base class to specify a physical system that still has open parameters,
such as the control amplitudes, the control duration, or other arbitrary
... |
def increase_nz_until_ok(self, controls, t, step=2):
while self.is_nz_ok(controls, t) is False:
self.nz += h.make_even(step)
def decrease_nz_until_not_ok(self, controls, t, step=2):
while self.is_nz_ok(controls, t) and self.nz-step > 3:
self.nz -= h.make_even(step)
... | self.increase_nz_until_ok(controls, t, step=max(10, self.nz/5))
self.decrease_nz_until_not_ok(controls, t, step=2)
self.increase_nz_until_ok(controls, t, step=2) | conditional_block |
parametric_system.py | import floq.core.fixed_system as fs
import floq.evolution as ev
import floq.errors as er
import floq.helpers.index as h
class ParametricSystemBase(object):
"""
Base class to specify a physical system that still has open parameters,
such as the control amplitudes, the control duration, or other arbitrary
... | (self, controls, t):
system = self.get_system(controls, t)
try:
u = ev.evolve_system(system)
except er.EigenvalueNumberError:
return False
return h.is_unitary(u)
def set_nz(self, controls, t):
if self.is_nz_ok(controls, t):
self.decrease... | is_nz_ok | identifier_name |
_Dialign.py | # Copyright 2009 by Cymon J. Cox. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Command line wrapper for the multiple alignment program DIALIGN2-2.
"""
from __future__ impo... |
if __name__ == "__main__":
_test()
| """Run the module's doctests (PRIVATE)."""
print("Running modules doctests...")
import doctest
doctest.testmod()
print("Done") | identifier_body |
_Dialign.py | # Copyright 2009 by Cymon J. Cox. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Command line wrapper for the multiple alignment program DIALIGN2-2.
"""
from __future__ impo... | _test() | conditional_block | |
_Dialign.py | # Copyright 2009 by Cymon J. Cox. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Command line wrapper for the multiple alignment program DIALIGN2-2.
"""
from __future__ impo... | (AbstractCommandline):
"""Command line wrapper for the multiple alignment program DIALIGN2-2.
http://bibiserv.techfak.uni-bielefeld.de/dialign/welcome.html
Example:
--------
To align a FASTA file (unaligned.fasta) with the output files names
aligned.* including a FASTA output file (aligned.fa... | DialignCommandline | identifier_name |
_Dialign.py | # Copyright 2009 by Cymon J. Cox. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Command line wrapper for the multiple alignment program DIALIGN2-2.
"""
from __future__ impo... | the Python subprocess module, as described in the Biopython tutorial.
Citation:
---------
B. Morgenstern (2004). DIALIGN: Multiple DNA and Protein Sequence
Alignment at BiBiServ. Nucleic Acids Research 32, W33-W36.
Last checked against version: 2.2
"""
def __init__(self, cmd="dialign2... | random_line_split | |
abi.rs | use std::{fmt::Debug, result::Result};
use wasm_bindgen::{
convert::FromWasmAbi,
describe::{inform, WasmDescribe},
JsValue,
};
pub type JsResult<T> = Result<T, JsValue>;
pub trait Context<T> {
fn context(self, msg: &dyn Debug) -> JsResult<T>;
}
impl<T, TError> Context<T> for Result<T, TError>
where
... | 2 => LogLevel(log::Level::Info),
3 => LogLevel(log::Level::Warn),
_ => LogLevel(log::Level::Error),
}
}
} | 0 => LogLevel(log::Level::Trace),
1 => LogLevel(log::Level::Debug), | random_line_split |
abi.rs | use std::{fmt::Debug, result::Result};
use wasm_bindgen::{
convert::FromWasmAbi,
describe::{inform, WasmDescribe},
JsValue,
};
pub type JsResult<T> = Result<T, JsValue>;
pub trait Context<T> {
fn context(self, msg: &dyn Debug) -> JsResult<T>;
}
impl<T, TError> Context<T> for Result<T, TError>
where
... |
}
pub struct LogLevel(pub log::Level);
impl WasmDescribe for LogLevel {
fn describe() {
inform(wasm_bindgen::describe::I8);
}
}
impl FromWasmAbi for LogLevel {
type Abi = u32;
unsafe fn from_abi(js: Self::Abi) -> Self {
match js {
0 => LogLevel(log::Level::Trace),
... | {
match self {
Ok(v) => Ok(v),
Err(err) => Err(format!("{:?} {:?}", msg, err).into()),
}
} | identifier_body |
abi.rs | use std::{fmt::Debug, result::Result};
use wasm_bindgen::{
convert::FromWasmAbi,
describe::{inform, WasmDescribe},
JsValue,
};
pub type JsResult<T> = Result<T, JsValue>;
pub trait Context<T> {
fn context(self, msg: &dyn Debug) -> JsResult<T>;
}
impl<T, TError> Context<T> for Result<T, TError>
where
... | (self, msg: &dyn Debug) -> JsResult<T> {
match self {
Ok(v) => Ok(v),
Err(err) => Err(format!("{:?} {:?}", msg, err).into()),
}
}
}
pub struct LogLevel(pub log::Level);
impl WasmDescribe for LogLevel {
fn describe() {
inform(wasm_bindgen::describe::I8);
}
}
... | context | identifier_name |
will-members.ts | // Source file from duniter: Crypto-currency software to manage libre currency such as Ğ1
// Copyright (C) 2018 Cedric Moreau <cem.moreau@gmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Soft... | await tac.cert(cat)
await cat.join()
await tac.join()
const head = await s1.commit({ time: now })
assertEqual(head.number, 0);
assertEqual(head.membersCount, 2);
await initMonitDB(s1._server)
})
test('toc tries to join', async (s1, cat, tac, toc) => {
await toc.createIdentity()
... | random_line_split | |
vis_utils_test.py | # Copyright 2018 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 test_plot_model_cnn(self):
model = keras.Sequential()
model.add(
keras.layers.Conv2D(
filters=2, kernel_size=(2, 3), input_shape=(3, 5, 5), name='conv'))
model.add(keras.layers.Flatten(name='flat'))
model.add(keras.layers.Dense(5, name='dense'))
dot_img_file = 'model_1.png... | from tensorflow.python.platform import test
class ModelToDotFormatTest(test.TestCase): | random_line_split |
vis_utils_test.py | # Copyright 2018 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... | test.main() | conditional_block | |
vis_utils_test.py | # Copyright 2018 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 test_plot_model_with_wrapped_layers_and_models(self):
inputs = keras.Input(shape=(None, 3))
lstm = keras.layers.LSTM(6, return_sequences=True, name='lstm')
x = lstm(inputs)
# Add layer inside a Wrapper
bilstm = keras.layers.Bidirectional(
keras.layers.LSTM(16, return_sequences=True, ... | model = keras.Sequential()
model.add(
keras.layers.Conv2D(
filters=2, kernel_size=(2, 3), input_shape=(3, 5, 5), name='conv'))
model.add(keras.layers.Flatten(name='flat'))
model.add(keras.layers.Dense(5, name='dense'))
dot_img_file = 'model_1.png'
try:
vis_utils.plot_model(... | identifier_body |
vis_utils_test.py | # Copyright 2018 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... | (self):
inputs = keras.Input(shape=(None, 3))
outputs = keras.layers.Dense(1)(inputs)
model = keras.Model(inputs, outputs)
model.add_loss(math_ops.reduce_mean(outputs))
dot_img_file = 'model_3.png'
try:
vis_utils.plot_model(
model,
to_file=dot_img_file,
show_s... | test_plot_model_with_add_loss | identifier_name |
flowers_test.py | # Copyright (c) 2016 PaddlePaddle 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 applic... | self.assertEqual(l[0].size, size)
if l[1] > label:
label = l[1]
sum += 1
return sum, label
def test_train(self):
instances, max_label_value = self.check_reader(
paddle.dataset.flowers.train())
self.assertEqual(instances, 6149)
... | def check_reader(self, reader):
sum = 0
label = 0
size = 224 * 224 * 3
for l in reader(): | random_line_split |
flowers_test.py | # Copyright (c) 2016 PaddlePaddle 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 applic... | (self, reader):
sum = 0
label = 0
size = 224 * 224 * 3
for l in reader():
self.assertEqual(l[0].size, size)
if l[1] > label:
label = l[1]
sum += 1
return sum, label
def test_train(self):
instances, max_label_value =... | check_reader | identifier_name |
flowers_test.py | # Copyright (c) 2016 PaddlePaddle 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 applic... |
sum += 1
return sum, label
def test_train(self):
instances, max_label_value = self.check_reader(
paddle.dataset.flowers.train())
self.assertEqual(instances, 6149)
self.assertEqual(max_label_value, 102)
def test_test(self):
instances, max_label_v... | label = l[1] | conditional_block |
flowers_test.py | # Copyright (c) 2016 PaddlePaddle 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 applic... |
if __name__ == '__main__':
unittest.main()
| instances, max_label_value = self.check_reader(
paddle.dataset.flowers.valid())
self.assertEqual(instances, 1020)
self.assertEqual(max_label_value, 102) | identifier_body |
more.d.ts | import TelegramBotApiEvent from './events';
/**
* @class TelegramBotApi
*/
export default class | extends TelegramBotApiEvent {
/**
* Create a TelegramBotApi
* @param {string} token
* @param {Object} options
*/
constructor(token?: string, options?: {
gzip?: boolean;
autoChatAction?: boolean;
autoChatActionUploadOnly?: boolean;
autoUpdate?: boolean;
... | TelegramBotApi | identifier_name |
more.d.ts | import TelegramBotApiEvent from './events';
/**
* @class TelegramBotApi
*/
export default class TelegramBotApi extends TelegramBotApiEvent {
/**
* Create a TelegramBotApi
* @param {string} token
* @param {Object} options
*/
constructor(token?: string, options?: {
gzip?: boolean;
... | });
/**
* Array of onMessage listeners
* @private
*/
private _onMsgListenerArray;
/**
* last _onMsgListenerArray item.id
* @private
*/
private _onMsgLastId;
/**
* Make loop on _onMsgListenerArray and if callBackFn return false break the loop
* @private
... | random_line_split | |
canteen_website_tags.py | # -*- coding: utf-8 -*-
from django import template
from CanteenWebsite.models import Category
from CanteenWebsite.utils.functions import setting_get
register = template.Library()
@register.simple_tag
def | (name, default=None):
return setting_get(name, default)
@register.inclusion_tag('CanteenWebsite/inclusions/sidebar_category_list.html', takes_context=True)
def sidebar_category_list(context):
categories = Category.objects.all()
try:
current_category = context['current_category']
except:
... | get_setting | identifier_name |
canteen_website_tags.py | # -*- coding: utf-8 -*-
from django import template
from CanteenWebsite.models import Category
from CanteenWebsite.utils.functions import setting_get
register = template.Library()
@register.simple_tag
def get_setting(name, default=None):
return setting_get(name, default)
@register.inclusion_tag('CanteenWebsit... | DOT = '...'
if page.number > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(1, ON_ENDS))
page_range.append(DOT)
page_range.extend(range(page.number - ON_EACH_SIDE, page.number + 1))
else:
page_range.extend(range(1, page.number + 1))
if p... | ON_ENDS = 2 | random_line_split |
canteen_website_tags.py | # -*- coding: utf-8 -*-
from django import template
from CanteenWebsite.models import Category
from CanteenWebsite.utils.functions import setting_get
register = template.Library()
@register.simple_tag
def get_setting(name, default=None):
return setting_get(name, default)
@register.inclusion_tag('CanteenWebsit... |
@register.inclusion_tag('CanteenWebsite/inclusions/pagination.html')
def show_pagination(page):
pagination = page.paginator
page_range = list()
if pagination.num_pages <= 10:
page_range = pagination.page_range
else:
ON_EACH_SIDE = 2
ON_ENDS = 2
DOT = '...'
if ... | categories = Category.objects.all()
try:
current_category = context['current_category']
except:
current_category = None
return {
'current': current_category,
'categories': categories,
} | identifier_body |
canteen_website_tags.py | # -*- coding: utf-8 -*-
from django import template
from CanteenWebsite.models import Category
from CanteenWebsite.utils.functions import setting_get
register = template.Library()
@register.simple_tag
def get_setting(name, default=None):
return setting_get(name, default)
@register.inclusion_tag('CanteenWebsit... |
else:
ON_EACH_SIDE = 2
ON_ENDS = 2
DOT = '...'
if page.number > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(1, ON_ENDS))
page_range.append(DOT)
page_range.extend(range(page.number - ON_EACH_SIDE, page.number + 1))
else:
p... | page_range = pagination.page_range | conditional_block |
map.rs | use std::ops::Range;
use cgmath::{Vector3, InnerSpace, Zero};
use noise::{BasicMulti, Seedable, NoiseModule};
use spherical_voronoi as sv;
use rand::{thread_rng, Rng, Rand};
use color::Color;
use ideal::{IdVec, IdsIter};
use settings;
#[derive(Copy, Clone, PartialEq)]
#[derive(Serialize, Deserialize)]
pub enum CornerK... |
}
for corner in map.corners() {
let elevation = {
let regions = map.corner_regions(corner);
let len = regions.len() as f64;
regions.iter().map(|®ion| map.region_elevation(region)).sum::<f64>() / len
};
map.corners[co... | {
map.regions[region].biome = self.sea;
} | conditional_block |
map.rs | use std::ops::Range;
use cgmath::{Vector3, InnerSpace, Zero};
use noise::{BasicMulti, Seedable, NoiseModule};
use spherical_voronoi as sv;
use rand::{thread_rng, Rng, Rand};
use color::Color;
use ideal::{IdVec, IdsIter};
use settings;
#[derive(Copy, Clone, PartialEq)]
#[derive(Serialize, Deserialize)]
pub enum CornerK... | {
regions: Vec<Region>,
position: Vector3<f64>,
kind: CornerKind,
elevation: f64,
}
create_id!(Corner);
#[derive(Copy, Clone, PartialEq)]
#[derive(Serialize, Deserialize)]
pub enum BorderKind {
River,
Coast,
None,
}
#[derive(Clone)]
#[derive(Serialize, Deserialize)]
pub struct BorderData ... | CornerData | identifier_name |
map.rs | use std::ops::Range;
use cgmath::{Vector3, InnerSpace, Zero};
use noise::{BasicMulti, Seedable, NoiseModule};
use spherical_voronoi as sv;
use rand::{thread_rng, Rng, Rand};
use color::Color;
use ideal::{IdVec, IdsIter};
use settings;
#[derive(Copy, Clone, PartialEq)]
#[derive(Serialize, Deserialize)]
pub enum CornerK... | borders: &'a IdVec<Border, BorderData>,
region: Region,
inner: ::std::slice::Iter<'b, Border>,
}
impl<'a, 'b> ::std::iter::Iterator for Neighbors<'a, 'b> {
type Item = Region;
fn next(&mut self) -> Option<Self::Item> {
if let Some(border) = self.inner.next() {
let (region0, reg... | }
pub struct Neighbors<'a, 'b> { | random_line_split |
train.py | # coding=utf-8
# Copyright 2019 The Interval Bound Propagation 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 ... |
def main(unused_args):
logging.info('Training IBP on %s...', FLAGS.dataset.upper())
step = tf.train.get_or_create_global_step()
# Learning rate.
learning_rate = ibp.parse_learning_rate(step, FLAGS.learning_rate)
# Dataset.
input_bounds = (0., 1.)
num_classes = 10
if FLAGS.dataset == 'mnist':
da... | """Returns the layer specification for a given model name."""
if model_size == 'tiny':
return (
('linear', 100),
('activation', 'relu'))
elif model_size == 'small':
return (
('conv2d', (4, 4), 16, 'VALID', 2),
('activation', 'relu'),
('conv2d', (4, 4), 32, 'VALID', 1)... | identifier_body |
train.py | # coding=utf-8
# Copyright 2019 The Interval Bound Propagation 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 ... |
saver.save(sess._tf_sess(), # pylint: disable=protected-access
os.path.join(FLAGS.output_dir, 'model'),
global_step=FLAGS.steps - 1)
if __name__ == '__main__':
app.run(main)
| metric_values, summary = sess.run([test_metrics, test_summaries])
test_writer.add_summary(summary, iteration)
show_metrics(iteration, metric_values, loss_value=loss_value) | conditional_block |
train.py | # coding=utf-8
# Copyright 2019 The Interval Bound Propagation 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 ... | total_metrics = [tf.constant(0, dtype=tf.float32)
for _ in range(len(ibp.ScalarMetrics._fields))]
total_count, total_metrics = tf.while_loop(
cond,
body,
loop_vars=[total_count, total_metrics],
back_prop=False,
parallel_iterations=1)
total_count =... | return i + 1, new_metrics
total_count = tf.constant(0, dtype=tf.int32) | random_line_split |
train.py | # coding=utf-8
# Copyright 2019 The Interval Bound Propagation 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 ... | (i, metrics):
"""Compute the sum of all metrics."""
test_data = ibp.build_dataset(data_test, batch_size=batch_size,
sequential=True)
predictor(test_data.image, override=True, is_training=False)
input_interval_bounds = ibp.IntervalBounds(
tf.maximum(t... | body | identifier_name |
lib.rs | //! This crate provides the basic environments for Kailua.
//!
//! * Location types ([`Unit`](./struct.Unit.html), [`Pos`](./struct.Pos.html),
//! [`Span`](./struct.Span.html)) and a location-bundled container | //!
//! * The resolver for locations
//! ([`kailua_env::source`](./source/index.html))
//!
//! * An arbitrary mapping from location ranges to values
//! ([`kailua_env::spanmap`](./spanmap/index.html))
mod loc;
pub mod scope;
pub mod source;
pub mod spanmap;
pub use loc::{Unit, Pos, Span, Spanned, WithLoc};
pub us... | //! ([`Spanned`](./struct.Spanned.html))
//!
//! * Scope identifiers and a location-to-scope map
//! ([`kailua_env::scope`](./scope/index.html)) | random_line_split |
template.py | from boto.resultset import ResultSet
class Template: | def startElement(self, name, attrs, connection):
if name == "Parameters":
self.template_parameters = ResultSet([('member', TemplateParameter)])
return self.template_parameters
else:
return None
def endElement(self, name, value, connection):
if name ==... | def __init__(self, connection=None):
self.connection = connection
self.description = None
self.template_parameters = None
| random_line_split |
template.py | from boto.resultset import ResultSet
class Template:
def __init__(self, connection=None):
self.connection = connection
self.description = None
self.template_parameters = None
def startElement(self, name, attrs, connection):
if name == "Parameters":
self.template_par... |
class TemplateParameter:
def __init__(self, parent):
self.parent = parent
self.default_value = None
self.description = None
self.no_echo = None
self.parameter_key = None
def startElement(self, name, attrs, connection):
return None
def endElement(self, name... | setattr(self, name, value) | conditional_block |
template.py | from boto.resultset import ResultSet
class Template:
def | (self, connection=None):
self.connection = connection
self.description = None
self.template_parameters = None
def startElement(self, name, attrs, connection):
if name == "Parameters":
self.template_parameters = ResultSet([('member', TemplateParameter)])
retur... | __init__ | identifier_name |
template.py | from boto.resultset import ResultSet
class Template:
|
class TemplateParameter:
def __init__(self, parent):
self.parent = parent
self.default_value = None
self.description = None
self.no_echo = None
self.parameter_key = None
def startElement(self, name, attrs, connection):
return None
def endElement(self, name... | def __init__(self, connection=None):
self.connection = connection
self.description = None
self.template_parameters = None
def startElement(self, name, attrs, connection):
if name == "Parameters":
self.template_parameters = ResultSet([('member', TemplateParameter)])
... | identifier_body |
extensions.rs | use serde::{Deserialize, Serialize, Serializer};
use std::convert::From;
use std::fmt;
#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
/// Represents all the possible [CloudEvents extension](https://github.com/cloudevents/spec/blob/master/spec.md#extension-context-attributes) values
p... |
}
impl From<bool> for ExtensionValue {
fn from(s: bool) -> Self {
ExtensionValue::Boolean(s)
}
}
impl From<i64> for ExtensionValue {
fn from(s: i64) -> Self {
ExtensionValue::Integer(s)
}
}
impl ExtensionValue {
pub fn from_string<S>(s: S) -> Self
where
S: Into<String... | {
ExtensionValue::String(s)
} | identifier_body |
extensions.rs | use serde::{Deserialize, Serialize, Serializer};
use std::convert::From;
use std::fmt;
#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
/// Represents all the possible [CloudEvents extension](https://github.com/cloudevents/spec/blob/master/spec.md#extension-context-attributes) values
p... | (s: String) -> Self {
ExtensionValue::String(s)
}
}
impl From<bool> for ExtensionValue {
fn from(s: bool) -> Self {
ExtensionValue::Boolean(s)
}
}
impl From<i64> for ExtensionValue {
fn from(s: i64) -> Self {
ExtensionValue::Integer(s)
}
}
impl ExtensionValue {
pub fn ... | from | identifier_name |
extensions.rs | use std::convert::From;
use std::fmt;
#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
/// Represents all the possible [CloudEvents extension](https://github.com/cloudevents/spec/blob/master/spec.md#extension-context-attributes) values
pub enum ExtensionValue {
/// Represents a [`S... | use serde::{Deserialize, Serialize, Serializer}; | random_line_split | |
Main.spec.js | describe( 'MainController', function() {
var MainCtrl, $location, $httpBackend, $scope, MapService, state, queryService;
beforeEach( module( 'SolrHeatmapApp' ) );
beforeEach( inject( function( $controller, _$location_, $rootScope, _$httpBackend_, _Map_, _$state_, _queryService_) {
$location = _$lo... | it( 'calls MapService getExtentForProjectionFromQuery', function() {
MainCtrl.response({data: {mapConfig: { view: { projection: 'EPSG:4326'}}}});
expect(serviceSpy).toHaveBeenCalled();
});
});
});
});
describe('#badRespo... | serviceSpy = spyOn(queryService, 'getExtentForProjectionFromQuery');
spyOn(MapService, 'calculateFullScreenExtentFromBoundingBox');
MainCtrl.$state = { geo: '[1,1 TO 1,1]'};
}); | random_line_split |
options.js | 'use strict'
const defaultAPIURL = 'https://api.runmycode.online/run'
const $ = s => document.querySelector(s)
const $$ = s => document.querySelectorAll(s)
const editBtn = $('#edit')
const error = $('#error')
const apiUrl = $('#api-url')
const apiKey = $('#api-key')
const saveBtn = $('#save')
const inputs = Array.from... |
error.style.display = 'none'
browser.storage.local.set({
'apiUrl': apiUrl.value,
'apiKey': apiKey.value
})
saveBtn.value = 'Saved'
if (e) toggleInputs() // toggle inputs only if save from btn click
}
const restoreOptions = () => {
const getApiUrl = browser.storage.local.get('apiUrl')
const getA... | {
error.textContent = 'Key cannot be empty for https://api.runmycode.online/run'
return
// key may be not required for custom RunMyCode deployment
} | conditional_block |
options.js | 'use strict'
const defaultAPIURL = 'https://api.runmycode.online/run'
const $ = s => document.querySelector(s)
const $$ = s => document.querySelectorAll(s)
const editBtn = $('#edit')
const error = $('#error')
const apiUrl = $('#api-url')
const apiKey = $('#api-key')
const saveBtn = $('#save')
const inputs = Array.from... | }
const saveOptions = (e) => {
if (apiUrl.value === '') apiUrl.value = defaultAPIURL
error.style.display = 'block'
if (apiUrl.value !== defaultAPIURL && apiUrl.value.indexOf('.amazonaws.com') === -1) {
error.textContent = `Only ${defaultAPIURL} and AWS API Gateway URLs are supported as API URL`
return
... | }
const enableEdit = () => {
saveBtn.value = 'Save'
toggleInputs() | random_line_split |
issue-7867.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
fn main() {
match (true, false) {
A::B => (), //~ ERROR expected `(bool, bool)`, found `A` (expected tuple, found enum A)
_ => ()
}
match &Some(42i) {
Some(x) => (), //~ ERROR expected `&core::option::Option<int>`,
// found `core::option::Option<_>`... | {} | identifier_body |
issue-7867.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {} }
fn main() {
match (true, false) {
A::B => (), //~ ERROR expected `(bool, bool)`, found `A` (expected tuple, found enum A)
_ => ()
}
match &Some(42i) {
Some(x) => (), //~ ERROR expected `&core::option::Option<int>`,
// found `core::option::Optio... | bar | identifier_name |
issue-7867.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | match (true, false) {
A::B => (), //~ ERROR expected `(bool, bool)`, found `A` (expected tuple, found enum A)
_ => ()
}
match &Some(42i) {
Some(x) => (), //~ ERROR expected `&core::option::Option<int>`,
// found `core::option::Option<_>`
None =>... | enum A { B, C }
mod foo { pub fn bar() {} }
fn main() { | random_line_split |
file.component.ts | import {
ChangeDetectorRef,
Component,
EventEmitter,
Input,
OnChanges,
OnDestroy,
OnInit,
Output,
SimpleChanges,
} from "@angular/core";
import { Dataset, Job, Tool } from "chipster-js-common";
import * as _ from "lodash";
import { Subject } from "rxjs";
import { mergeMap, takeUntil } from "rxjs/opera... |
},
});
}
renameDataset() {
const dataset = _.clone(this.dataset);
this.dialogModalService
.openStringModal("Rename file", "File name", dataset.name, "Rename")
.pipe(
mergeMap((name) => {
dataset.name = name;
return this.sessionDataService.updateDataset... | {
this.datasetName = this.sessionData.datasetsMap.get(this.dataset.datasetId)?.name;
} | conditional_block |
file.component.ts | import {
ChangeDetectorRef,
Component,
EventEmitter,
Input,
OnChanges,
OnDestroy,
OnInit,
Output,
SimpleChanges,
} from "@angular/core";
import { Dataset, Job, Tool } from "chipster-js-common";
import * as _ from "lodash";
import { Subject } from "rxjs";
import { mergeMap, takeUntil } from "rxjs/opera... |
defineDatasetGroups() {
this.datasetModalService.openGroupsModal(this.selectionService.selectedDatasets, this.sessionData);
}
selectChildren() {
const children = this.getSessionDataService.getChildren(this.selectionService.selectedDatasets);
this.selectionHandlerService.setDatasetSelection(children... | {
this.datasetModalService.openWrangleModal(this.dataset, this.sessionData);
} | identifier_body |
file.component.ts | import {
ChangeDetectorRef,
Component,
EventEmitter,
Input,
OnChanges,
OnDestroy,
OnInit,
Output,
SimpleChanges,
} from "@angular/core";
import { Dataset, Job, Tool } from "chipster-js-common";
import * as _ from "lodash";
import { Subject } from "rxjs";
import { mergeMap, takeUntil } from "rxjs/opera... | () {
this.unsubscribe.next();
this.unsubscribe.complete();
}
}
| ngOnDestroy | identifier_name |
file.component.ts | import {
ChangeDetectorRef,
Component,
EventEmitter,
Input,
OnChanges,
OnDestroy,
OnInit,
Output,
SimpleChanges,
} from "@angular/core";
import { Dataset, Job, Tool } from "chipster-js-common";
import * as _ from "lodash";
import { Subject } from "rxjs";
import { mergeMap, takeUntil } from "rxjs/opera... |
constructor(
public selectionService: SelectionService, // used in template
private sessionDataService: SessionDataService,
private datasetModalService: DatasetModalService,
private dialogModalService: DialogModalService,
private restErrorService: RestErrorService,
private sessionEventService... | @Output() doScrollFix = new EventEmitter();
datasetName: string;
private unsubscribe: Subject<any> = new Subject(); | random_line_split |
set-replication-status.ts | import type { AdapterPool } from './types'
import type { ReplicationState, OldEvent } from '@resolve-js/eventstore-base'
import initReplicationStateTable from './init-replication-state-table'
const setReplicationStatus = async (
pool: AdapterPool,
lockId: string,
{
statusAndData,
lastEvent,
iterator,... |
}
export default setReplicationStatus
| {
return null
} | conditional_block |
set-replication-status.ts | import type { AdapterPool } from './types'
import type { ReplicationState, OldEvent } from '@resolve-js/eventstore-base'
import initReplicationStateTable from './init-replication-state-table'
const setReplicationStatus = async (
pool: AdapterPool,
lockId: string,
{
statusAndData,
lastEvent, | lastEvent?: OldEvent
iterator?: ReplicationState['iterator']
}
): Promise<ReplicationState | null> => {
const { executeStatement, escapeId, escape } = pool
const replicationStateTableName = await initReplicationStateTable(pool)
const rows = await executeStatement(
`UPDATE ${escapeId(replicationSta... | iterator,
}: {
statusAndData: ReplicationState['statusAndData'] | random_line_split |
asm-target-clobbers.rs | // only-x86_64
// revisions: base avx512
// [avx512]compile-flags: -C target-feature=+avx512f
#![crate_type = "rlib"]
#![feature(asm)]
// CHECK-LABEL: @avx512_clobber
// base: call void asm sideeffect inteldialect "", "~{xmm31}"()
// avx512: call float asm sideeffect inteldialect "", "=&{xmm31}"()
#[no_mangle]
pub un... |
// CHECK-LABEL: @eax_clobber
// CHECK: call i32 asm sideeffect inteldialect "", "=&{ax}"()
#[no_mangle]
pub unsafe fn eax_clobber() {
asm!("", out("eax") _, options(nostack, nomem, preserves_flags));
}
| {
asm!("", out("zmm31") _, options(nostack, nomem, preserves_flags));
} | identifier_body |
asm-target-clobbers.rs | // only-x86_64
// revisions: base avx512
// [avx512]compile-flags: -C target-feature=+avx512f
#![crate_type = "rlib"]
#![feature(asm)]
// CHECK-LABEL: @avx512_clobber
// base: call void asm sideeffect inteldialect "", "~{xmm31}"()
// avx512: call float asm sideeffect inteldialect "", "=&{xmm31}"()
#[no_mangle]
pub un... | () {
asm!("", out("zmm31") _, options(nostack, nomem, preserves_flags));
}
// CHECK-LABEL: @eax_clobber
// CHECK: call i32 asm sideeffect inteldialect "", "=&{ax}"()
#[no_mangle]
pub unsafe fn eax_clobber() {
asm!("", out("eax") _, options(nostack, nomem, preserves_flags));
}
| avx512_clobber | identifier_name |
asm-target-clobbers.rs | // only-x86_64
// revisions: base avx512
// [avx512]compile-flags: -C target-feature=+avx512f
#![crate_type = "rlib"]
#![feature(asm)]
// CHECK-LABEL: @avx512_clobber
// base: call void asm sideeffect inteldialect "", "~{xmm31}"() | pub unsafe fn avx512_clobber() {
asm!("", out("zmm31") _, options(nostack, nomem, preserves_flags));
}
// CHECK-LABEL: @eax_clobber
// CHECK: call i32 asm sideeffect inteldialect "", "=&{ax}"()
#[no_mangle]
pub unsafe fn eax_clobber() {
asm!("", out("eax") _, options(nostack, nomem, preserves_flags));
} | // avx512: call float asm sideeffect inteldialect "", "=&{xmm31}"()
#[no_mangle] | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.