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
migrations.js
// File describing all migrations and their upward/downward changes // for API Usage Information see https://github.com/percolatestudio/meteor-migrations import {Meteor} from 'meteor/meteor'; import {ImageResources} from '../imports/modules/constants'; /* eslint-disable lodash/prefer-lodash-method */ if(Meteor.isServ...
/* eslint-enable */
{ Migrations.config({ log: true, logIfLatest: false }); Migrations.add({ version: 1, name: 'Adds profileImage field to every user if not already there. Uses the id `Default/default_<gender-name>`.', up: () => { const users = Meteor.users.find().fetch(); //eslint-disable-line _(us...
conditional_block
migrations.js
// File describing all migrations and their upward/downward changes // for API Usage Information see https://github.com/percolatestudio/meteor-migrations import {Meteor} from 'meteor/meteor'; import {ImageResources} from '../imports/modules/constants'; /* eslint-disable lodash/prefer-lodash-method */ if(Meteor.isServ...
_(users) .thru((user) => { user.apiAuthKey = user.stressApi.apiKey; user.apiAuthType = user.stressApi.apiAuthType; delete user.stressApi; return user; }).forEach((user) => Meteor.users.update({_id: user._id}, { $unset: { stressApi: "" ...
}, down() { const users = Meteor.users.find().fetch();
random_line_split
migrations.js
// File describing all migrations and their upward/downward changes // for API Usage Information see https://github.com/percolatestudio/meteor-migrations import {Meteor} from 'meteor/meteor'; import {ImageResources} from '../imports/modules/constants'; /* eslint-disable lodash/prefer-lodash-method */ if(Meteor.isServ...
() { const users = Meteor.users.find().fetch(); _(users) .thru((user) => { user.apiAuthKey = user.stressApi.apiKey; user.apiAuthType = user.stressApi.apiAuthType; delete user.stressApi; return user; }).forEach((user) => Meteor.users.update({_id: user...
down
identifier_name
digest.py
# -*- test-case-name: twisted.web.test.test_httpauth -*- # Copyright (c) 2009 Twisted Matrix Laboratories. # See LICENSE for details. """ Implementation of RFC2617: HTTP Digest Authentication @see: U{http://www.faqs.org/rfcs/rfc2617.html} """ from zope.interface import implements from twisted.cred import credentials...
response to which this challenge is being generated. @return: The C{dict} that can be used to generate a WWW-Authenticate header. """ return self.digest.getChallenge(request.getClientIP()) def decode(self, response, request): """ Create a L{twisted....
@param request: The L{IRequest} to with access was denied and for the
random_line_split
digest.py
# -*- test-case-name: twisted.web.test.test_httpauth -*- # Copyright (c) 2009 Twisted Matrix Laboratories. # See LICENSE for details. """ Implementation of RFC2617: HTTP Digest Authentication @see: U{http://www.faqs.org/rfcs/rfc2617.html} """ from zope.interface import implements from twisted.cred import credentials...
(object): """ Wrapper for L{digest.DigestCredentialFactory} that implements the L{ICredentialFactory} interface. """ implements(ICredentialFactory) scheme = 'digest' def __init__(self, algorithm, authenticationRealm): """ Create the digest credential factory that this objec...
DigestCredentialFactory
identifier_name
digest.py
# -*- test-case-name: twisted.web.test.test_httpauth -*- # Copyright (c) 2009 Twisted Matrix Laboratories. # See LICENSE for details. """ Implementation of RFC2617: HTTP Digest Authentication @see: U{http://www.faqs.org/rfcs/rfc2617.html} """ from zope.interface import implements from twisted.cred import credentials...
def getChallenge(self, request): """ Generate the challenge for use in the WWW-Authenticate header @param request: The L{IRequest} to with access was denied and for the response to which this challenge is being generated. @return: The C{dict} that can be used to gene...
""" Create the digest credential factory that this object wraps. """ self.digest = credentials.DigestCredentialFactory(algorithm, authenticationRealm)
identifier_body
postgres.py
# -*- coding: utf-8 -*- """ mchem.postgres ~~~~~~~~~~~~~~ Functions to build and benchmark PostgreSQL database for comparison. :copyright: Copyright 2014 by Matt Swain. :license: MIT, see LICENSE file for more details. """ from __future__ import print_function from __future__ import unicode_literals from __future__ ...
# Save results result = { 'median_time': np.median(times), 'mean_time': np.mean(times), 'fp': fp, 'threshold': threshold } log.info(result) cur.close() conn.close() @cli.command() @click.option('--sample', '-s', type=click.File('r'), help='File containing sampl...
log.debug('Query molecule %s of %s: %s' % (i+1, len(mol_ids), mol_id)) # ARGH! The CHEMBL ID vs. molregno thing is a nightmare cur.execute("select entity_id from chembl_id_lookup where chembl_id = %s", (mol_id,)) molregno = cur.fetchone()[0] #cur.execute("select m from rdk.mols where mol...
conditional_block
postgres.py
# -*- coding: utf-8 -*- """ mchem.postgres ~~~~~~~~~~~~~~ Functions to build and benchmark PostgreSQL database for comparison. :copyright: Copyright 2014 by Matt Swain. :license: MIT, see LICENSE file for more details.
import logging import time import click import numpy as np import psycopg2 from psycopg2.extensions import AsIs log = logging.getLogger(__name__) # Start by creating the database and loading the chembl dump via the command line: # createdb chembl # psql chembl < chembl_19.pgdump.sql @click.group() @click.option(...
""" from __future__ import print_function from __future__ import unicode_literals from __future__ import division
random_line_split
postgres.py
# -*- coding: utf-8 -*- """ mchem.postgres ~~~~~~~~~~~~~~ Functions to build and benchmark PostgreSQL database for comparison. :copyright: Copyright 2014 by Matt Swain. :license: MIT, see LICENSE file for more details. """ from __future__ import print_function from __future__ import unicode_literals from __future__ ...
"""Perform a similarity search on every molecule in sample and print results.""" click.echo('Fingerprint: %s, Threshold: %s' % (fp, threshold)) cur = conn.cursor() mol_ids = sample.read().strip().split('\n') cur.execute("set rdkit.tanimoto_threshold=%s;", (threshold,)) for i, mol_id in enumerate(mol...
identifier_body
postgres.py
# -*- coding: utf-8 -*- """ mchem.postgres ~~~~~~~~~~~~~~ Functions to build and benchmark PostgreSQL database for comparison. :copyright: Copyright 2014 by Matt Swain. :license: MIT, see LICENSE file for more details. """ from __future__ import print_function from __future__ import unicode_literals from __future__ ...
(conn, sample, fp, threshold): cur = conn.cursor() mol_ids = sample.read().strip().split('\n') times = [] cur.execute("set rdkit.tanimoto_threshold=%s;", (threshold,)) for i, mol_id in enumerate(mol_ids[:100]): log.debug('Query molecule %s of %s: %s' % (i+1, len(mol_ids), mol_id)) # ...
profile
identifier_name
patch-buildtools_wafsamba_samba__conftests.py
$NetBSD: patch-buildtools_wafsamba_samba__conftests.py,v 1.2 2019/11/10 17:01:58 adam Exp $
--- buildtools/wafsamba/samba_conftests.py.orig 2019-07-09 10:08:41.000000000 +0000 +++ buildtools/wafsamba/samba_conftests.py @@ -97,9 +97,9 @@ def CHECK_LARGEFILE(conf, define='HAVE_L if flag[:2] == "-D": flag_split = flag[2:].split('=') if len(flag_split) =...
Ensure defines are strings to avoid assertion failure, some returned values are unicode.
random_line_split
serializers.py
from rest_framework import serializers from .models import User, Activity, Period class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email') extra_kwargs = { 'url': {'view_name': 'timeperiod:user-detail'}, ...
class Meta: model = Period fields = ('url', 'activity', 'start', 'end', 'valid') extra_kwargs = { 'url': {'view_name': 'timeperiod:period-detail'}, 'activity': {'view_name': 'timeperiod:activity-detail'}, }
identifier_body
serializers.py
from rest_framework import serializers from .models import User, Activity, Period class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email') extra_kwargs = { 'url': {'view_name': 'timeperiod:user-detail'},
class ActivitySerializer(serializers.HyperlinkedModelSerializer): user = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = Activity fields = ('url', 'user', 'name', 'total', 'running') extra_kwargs = { 'url': {'view_name': 'timeperiod:acti...
}
random_line_split
serializers.py
from rest_framework import serializers from .models import User, Activity, Period class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email') extra_kwargs = { 'url': {'view_name': 'timeperiod:user-detail'}, ...
: model = Activity fields = ('url', 'user', 'name', 'total', 'running') extra_kwargs = { 'url': {'view_name': 'timeperiod:activity-detail'}, 'user': {'view_name': 'timeperiod:user-detail'}, } class PeriodSerializer(serializers.HyperlinkedModelSerializer): cl...
Meta
identifier_name
test_dhcp_for_vpcrouter_cidr.py
''' 1.create private vpc router network with cidr 2.check dhcp ip address @author Antony WeiJiang ''' import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_state as test_state import zstackwoodpecker.test_util as test_util import zstackwoodpecker.operations.resource_operations as res_ops import zs...
''' to be define ''' def env_recover(): pass
pass
identifier_body
test_dhcp_for_vpcrouter_cidr.py
''' 1.create private vpc router network with cidr 2.check dhcp ip address @author Antony WeiJiang ''' import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_state as test_state import zstackwoodpecker.test_util as test_util import zstackwoodpecker.operations.resource_operations as res_ops import zs...
test_util.test_logger("delete l3 network") private_vpcnetwork.del_l3uuid() test_util.test_pass("dhcp server ip create successfully") ''' to be define ''' def error_cleanup(): pass ''' to be define ''' def env_recover(): pass
test_util.test_fail("dhcp server ip create fail")
conditional_block
test_dhcp_for_vpcrouter_cidr.py
''' 1.create private vpc router network with cidr 2.check dhcp ip address @author Antony WeiJiang ''' import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_state as test_state import zstackwoodpecker.test_util as test_util import zstackwoodpecker.operations.resource_operations as res_ops import zs...
test_util.test_dsc("get no vlan network uuid") private_vpcnetwork = test_stub_dhcp.VpcNetwork_IP_For_Dhcp() private_vpcnetwork.set_l2_query_resource(l2_query_resource) private_vpcnetwork.set_l2_type(type_l2[1]) l2_no_vlan_uuid = private_vpcnetwork.get_l2uuid() test_util.test_logger("antony @@@debug : %s" %(l2_no...
def test(): test_util.test_logger("start dhcp test for l3 public network")
random_line_split
test_dhcp_for_vpcrouter_cidr.py
''' 1.create private vpc router network with cidr 2.check dhcp ip address @author Antony WeiJiang ''' import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_state as test_state import zstackwoodpecker.test_util as test_util import zstackwoodpecker.operations.resource_operations as res_ops import zs...
(): pass
env_recover
identifier_name
lyrics.py
#!/usr/bin/env python3 import os from typing import Optional import requests from bs4 import BeautifulSoup import pysonic.utils as utils base_url = "https://api.genius.com" def get_token() -> Optional[str]: user_home_path = utils.get_home() try: with open(os.path.join(user_home_path, "genius_api_...
""" Return the lyrics for a given song and artist. """ search_url = base_url + "/search" data = {'q': song_title + " " + artist_name} token = get_token() if not token: return None, None, None response = requests.get(search_url, params=data, headers={'Authorization': f'Bearer {token}'}) ...
identifier_body
lyrics.py
#!/usr/bin/env python3 import os from typing import Optional import requests from bs4 import BeautifulSoup import pysonic.utils as utils base_url = "https://api.genius.com" def get_token() -> Optional[str]: user_home_path = utils.get_home() try: with open(os.path.join(user_home_path, "genius_api_...
(song_api_path): song_url = base_url + song_api_path response = requests.get(song_url, headers={'Authorization': f'Bearer {get_token()}'}) json = response.json() path = json["response"]["song"]["path"] # Regular html scraping... page_url = "https://genius.com" + path page = requests.get(pag...
_lyrics_from_song_api_path
identifier_name
lyrics.py
#!/usr/bin/env python3 import os from typing import Optional import requests from bs4 import BeautifulSoup import pysonic.utils as utils base_url = "https://api.genius.com" def get_token() -> Optional[str]: user_home_path = utils.get_home() try: with open(os.path.join(user_home_path, "genius_api_...
with open(os.path.join(user_home_path, "genius_api_key"), "w") as token_file: token_file.write(token) return token def _lyrics_from_song_api_path(song_api_path): song_url = base_url + song_api_path response = requests.get(song_url, headers={'Authorization': f'Bearer {get_token()}'}) ...
return None
conditional_block
lyrics.py
#!/usr/bin/env python3 import os from typing import Optional import requests from bs4 import BeautifulSoup import pysonic.utils as utils base_url = "https://api.genius.com" def get_token() -> Optional[str]: user_home_path = utils.get_home() try: with open(os.path.join(user_home_path, "genius_api_...
def _lyrics_from_song_api_path(song_api_path): song_url = base_url + song_api_path response = requests.get(song_url, headers={'Authorization': f'Bearer {get_token()}'}) json = response.json() path = json["response"]["song"]["path"] # Regular html scraping... page_url = "https://genius.com" + p...
random_line_split
__init__.py
# #START_LICENSE########################################################### # # # This file is part of the Environment for Tree Exploration program # (ETE). http://etetoolkit.org # # ETE is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # t...
# ABOUT THE ETE PACKAGE # ===================== # # ETE is distributed under the GPL copyleft license (2008-2015). # # If you make use of ETE in published work, please cite: # # Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. # ETE: a python Environment for Tree Explorat...
# You should have received a copy of the GNU General Public License # along with ETE. If not, see <http://www.gnu.org/licenses/>. # #
random_line_split
publish.py
import gevent from cloudly.pubsub import RedisWebSocket from cloudly.tweets import Tweets, StreamManager, keep from cloudly import logger from webapp import config log = logger.init(__name__) pubsub = RedisWebSocket(config.pubsub_channel) pubsub.spawn() running = False def
(tweets): pubsub.publish(keep(['coordinates'], tweets), "tweets") return len(tweets) def run(): log.info("Starting Twitter stream manager.") streamer = StreamManager('locate', processor, is_queuing=False) tweets = Tweets() streamer.run(tweets.with_coordinates(), stop) log.info("Twitter str...
processor
identifier_name
publish.py
import gevent from cloudly.pubsub import RedisWebSocket from cloudly.tweets import Tweets, StreamManager, keep from cloudly import logger from webapp import config log = logger.init(__name__) pubsub = RedisWebSocket(config.pubsub_channel) pubsub.spawn() running = False def processor(tweets): pubsub.publish(kee...
return False
log.info("Stopping Twitter stream manager.") running = False return True
conditional_block
publish.py
import gevent from cloudly.pubsub import RedisWebSocket from cloudly.tweets import Tweets, StreamManager, keep from cloudly import logger from webapp import config log = logger.init(__name__) pubsub = RedisWebSocket(config.pubsub_channel) pubsub.spawn() running = False def processor(tweets): pubsub.publish(kee...
def subscribe(websocket): log.info("Subscribed a new websocket client.") pubsub.register(websocket) def stop(): global running if len(pubsub.websockets) == 0: log.info("Stopping Twitter stream manager.") running = False return True return False
global running if not running: running = True gevent.spawn(run)
identifier_body
publish.py
import gevent from cloudly.pubsub import RedisWebSocket from cloudly.tweets import Tweets, StreamManager, keep from cloudly import logger from webapp import config log = logger.init(__name__) pubsub = RedisWebSocket(config.pubsub_channel) pubsub.spawn() running = False def processor(tweets): pubsub.publish(kee...
tweets = Tweets() streamer.run(tweets.with_coordinates(), stop) log.info("Twitter stream manager has stopped.") def start(): global running if not running: running = True gevent.spawn(run) def subscribe(websocket): log.info("Subscribed a new websocket client.") pubsub.reg...
def run(): log.info("Starting Twitter stream manager.") streamer = StreamManager('locate', processor, is_queuing=False)
random_line_split
Map.py
#!/usr/bin/env python TestFileName = "data/TestMap.png" import wx from wx.lib.floatcanvas import NavCanvas, FloatCanvas #import sys #sys.path.append("..") #from floatcanvas import NavCanvas, FloatCanvas class DrawFrame(wx.Frame): """ A frame used for the FloatCanvas Demo """ def __init__(self...
F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) ) app.MainLoop()
""" self.SetStatusText("%.2f, %.2f"%tuple(event.Coords)) app = wx.App(False)
random_line_split
Map.py
#!/usr/bin/env python TestFileName = "data/TestMap.png" import wx from wx.lib.floatcanvas import NavCanvas, FloatCanvas #import sys #sys.path.append("..") #from floatcanvas import NavCanvas, FloatCanvas class DrawFrame(wx.Frame): """ A frame used for the FloatCanvas Demo """ def __init__(self...
def OnMove(self, event): """ Updates the status bar with the world coordinates And moves a point if there is one selected """ self.SetStatusText("%.2f, %.2f"%tuple(event.Coords)) app = wx.App(False) F = DrawFrame(None, title="FloatCanvas Demo App", size=(700,700) ) app....
print("Writing a png file:") self.Canvas.SaveAsImage("junk.png") print("Writing a jpeg file:") self.Canvas.SaveAsImage("junk.jpg",wx.BITMAP_TYPE_JPEG)
identifier_body
Map.py
#!/usr/bin/env python TestFileName = "data/TestMap.png" import wx from wx.lib.floatcanvas import NavCanvas, FloatCanvas #import sys #sys.path.append("..") #from floatcanvas import NavCanvas, FloatCanvas class
(wx.Frame): """ A frame used for the FloatCanvas Demo """ def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) self.CreateStatusBar() # Add the Canvas NC = NavCanvas.NavCanvas(self,-1, size = (500,500), ...
DrawFrame
identifier_name
IssueCreate.py
#!/usr/bin/python3 #!python3 #encoding:utf-8 import sys import os.path import subprocess import configparser import argparse import web.service.github.api.v3.AuthenticationsCreator import web.service.github.api.v3.Client import database.src.Database import cui.uploader.Main import web.log.Log import database.src.contri...
_args.username) self.__ssh_configures = self.__db.Accounts['SshConfigures'].find_one(AccountId=self.__account['Id']) self.__repo_name = os.path.basename(self.__args.path_dir_pj) self.__repos = self.__db.Repositories[self.__args.username]['Repositories'].find_one(Name=self.__repo_name) i...
ng('指定したユーザ {0} はDBに存在しません。UserRegister.pyで登録してください。'.format(self.__args.username)) return self.__account = self.__db.Accounts['Accounts'].find_one(Username=self._
conditional_block
IssueCreate.py
#!/usr/bin/python3 #!python3 #encoding:utf-8 import sys import os.path import subprocess import configparser import argparse import web.service.github.api.v3.AuthenticationsCreator import web.service.github.api.v3.Client import database.src.Database import cui.uploader.Main import web.log.Log import database.src.contri...
th_creator.Create() client = web.service.github.api.v3.Client.Client(self.__db, authentications, self.__args) title = self.__args.issues[0] body = None # 1行目タイトル, 2行目空行, 3行目以降本文。 if 1 < len(self.__args.issues): body = '\n'.join(self.__args.issues[1:]) return client.Issue...
tications = au
identifier_name
IssueCreate.py
#!/usr/bin/python3 #!python3 #encoding:utf-8 import sys import os.path import subprocess import configparser import argparse import web.service.github.api.v3.AuthenticationsCreator import web.service.github.api.v3.Client import database.src.Database import cui.uploader.Main import web.log.Log import database.src.contri...
authentications = auth_creator.Create() client = web.service.github.api.v3.Client.Client(self.__db, authentications, self.__args) title = self.__args.issues[0] body = None # 1行目タイトル, 2行目空行, 3行目以降本文。 if 1 < len(self.__args.issues): body = '\n'.join(self.__args.issues[1:]) ...
アド: {0}'.format(self.__account['MailAddress'])) web.log.Log.Log().Logger.info('SSH HOST: {0}'.format(self.__ssh_configures['HostName'])) # web.log.Log.Log().Logger.info('リポジトリ名: {0}'.format(self.__repos['Name'])) # web.log.Log.Log().Logger.info('説明: {0}'.format(self.__repos['Description'])) # ...
identifier_body
IssueCreate.py
#!/usr/bin/python3 #!python3 #encoding:utf-8 import sys import os.path import subprocess import configparser import argparse import web.service.github.api.v3.AuthenticationsCreator import web.service.github.api.v3.Client import database.src.Database import cui.uploader.Main import web.log.Log import database.src.contri...
main.Run()
random_line_split
github.js
var async = require('async'), fs = require('graceful-fs'), path = require('path'), colors = require('colors'), swig = require('swig'), spawn = require('child_process').spawn,
commitMessage = require('./util').commitMessage; // http://git-scm.com/docs/git-clone var rRepo = /(:|\/)([^\/]+)\/([^\/]+)\.git\/?$/; module.exports = function(args, callback){ var baseDir = hexo.base_dir, deployDir = path.join(baseDir, '.deploy'), publicDir = hexo.public_dir; if (!args.repo && !args....
util = require('../../util'), file = util.file2,
random_line_split
ConditionObserver.ts
import * as $ from "jquery"; import ConditionType from "@enhavo/form/Type/ConditionType"; import ConditionObserverConfig from "@enhavo/form/Type/ConditionObserverConfig"; export default class ConditionObserver { private $element: JQuery; private configs: ConditionObserverConfig[]; private $row: JQuery; ...
private show() { this.$row.show(); } }
{ this.$row.hide(); }
identifier_body
ConditionObserver.ts
import * as $ from "jquery"; import ConditionType from "@enhavo/form/Type/ConditionType"; import ConditionObserverConfig from "@enhavo/form/Type/ConditionObserverConfig"; export default class ConditionObserver { private $element: JQuery; private configs: ConditionObserverConfig[]; private $row: JQuery; ...
} return null; } public wakeUp(subject: ConditionType) { let condition = null; for (let subject of this.subjects) { let config = this.getConfig(subject); let subjectCondition = config.values.indexOf(subject.getValue()) >= 0; if(condition ...
{ return config; }
conditional_block
ConditionObserver.ts
import * as $ from "jquery"; import ConditionType from "@enhavo/form/Type/ConditionType"; import ConditionObserverConfig from "@enhavo/form/Type/ConditionObserverConfig"; export default class ConditionObserver { private $element: JQuery; private configs: ConditionObserverConfig[]; private $row: JQuery; ...
{ this.$row.hide(); } private show() { this.$row.show(); } }
this.hide(); } } private hide()
random_line_split
ConditionObserver.ts
import * as $ from "jquery"; import ConditionType from "@enhavo/form/Type/ConditionType"; import ConditionObserverConfig from "@enhavo/form/Type/ConditionObserverConfig"; export default class
{ private $element: JQuery; private configs: ConditionObserverConfig[]; private $row: JQuery; private subjects: ConditionType[] = []; constructor(element: HTMLElement) { this.$element = $(element); this.configs = this.$element.data('condition-type-observer'); let par...
ConditionObserver
identifier_name
srgb.rs
// Copyright 2013 The color-rs developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License.
// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the Licen...
// You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0
random_line_split
srgb.rs
// Copyright 2013 The color-rs developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // 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 o...
}
{ Srgb { r: r, g: g, b: b } }
identifier_body
srgb.rs
// Copyright 2013 The color-rs developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // 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 o...
<T> { pub r: T, pub g: T, pub b: T } impl<T> Srgb<T> { #[inline] pub fn new(r: T, g: T, b: T) -> Srgb<T> { Srgb { r: r, g: g, b: b } } }
Srgb
identifier_name
scene.rs
// Robigo Luculenta -- Proof of concept spectral path tracer in Rust // Copyright (C) 2014-2015 Ruud van Asseldonk // // 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 L...
(&self, ray: &Ray) -> Option<(Intersection, &Object)> { // Assume Nothing is found, and that Nothing is Very Far Away (tm). let mut result = None; let mut distance = 1.0e12f32; // Then intersect all surfaces. for obj in &self.objects { match obj.surface.intersect(ray...
intersect
identifier_name
scene.rs
// Robigo Luculenta -- Proof of concept spectral path tracer in Rust // Copyright (C) 2014-2015 Ruud van Asseldonk // // 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 L...
// TODO: apparently there is no such thing as an immutable closure // any more, but I'd prefer to be able to use a pure function here, // which might be a closure. pub get_camera_at_time: fn (f32) -> Camera } impl Scene { /// Intersects the specified ray with the scene. pub fn intersect(&self, ...
/// A function that returns the camera through which the scene /// will be seen. The function takes one parameter, the time (in /// the range 0.0 - 1.0), which will be sampled randomly to create /// effects like motion blur and zoom blur.
random_line_split
scene.rs
// Robigo Luculenta -- Proof of concept spectral path tracer in Rust // Copyright (C) 2014-2015 Ruud van Asseldonk // // 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 L...
} } } result } }
{ result = Some((isect, obj)); distance = isect.distance; }
conditional_block
app.js
'use strict'; angular.module('pizzaApp', []) .factory('shopCartService', function(){ var factoryInstance = {}; var pizzaListCart = []; factoryInstance.addPizzaToCart = function(pizza) { pizzaListCart.push({name: pizza.name, price: pizza.price}); }; factoryInstance.getCart = function(){ return pizzaL...
.controller('shopCartController', function($scope, shopCartService){ $scope.shopCartList = shopCartService.getCart(); $scope.totalPrice = function () { var total = 0; angular.forEach($scope.shopCartList, function (pizza){ total += pizza.price; }); return total; }; $scope.removeFromCart = fun...
); $scope.orderValue = 'name'; })
random_line_split
SoapEventDecoder.ts
/* * Copyright (C) 2017 ZeXtras S.r.l. * * 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, version 2 of * the License. * * This program is distributed in the hope that it will be useful, ...
(eventCode: number) { this.mEventCode = eventCode; this.Log = LogEngine.getLogger(LogEngine.CHAT); } public getEventCode(): number { return this.mEventCode; } public abstract decodeEvent(eventObj: ISoapEventObject, originEvent?: IChatEvent): T; }
constructor
identifier_name
SoapEventDecoder.ts
/* * Copyright (C) 2017 ZeXtras S.r.l. * * 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, version 2 of * the License. * * This program is distributed in the hope that it will be useful, ...
public abstract decodeEvent(eventObj: ISoapEventObject, originEvent?: IChatEvent): T; }
{ return this.mEventCode; }
identifier_body
SoapEventDecoder.ts
/* * Copyright (C) 2017 ZeXtras S.r.l. * * 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, version 2 of * the License. * * This program is distributed in the hope that it will be useful, ...
} public getEventCode(): number { return this.mEventCode; } public abstract decodeEvent(eventObj: ISoapEventObject, originEvent?: IChatEvent): T; }
constructor(eventCode: number) { this.mEventCode = eventCode; this.Log = LogEngine.getLogger(LogEngine.CHAT);
random_line_split
annotateable.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
<'a>(&self, store: &'a Store) -> Result<AnnotationIter<'a>> { self.get_internal_links() .map_err(From::from) .map(|iter| StoreIdIterator::new(Box::new(iter.map(|e| e.get_store_id().clone())))) .map(|i| AnnotationIter::new(i, store)) } fn is_annotation(&self) -> Resul...
annotations
identifier_name
annotateable.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
fn is_annotation(&self) -> Result<bool> { self.is::<IsAnnotation>().map_err(From::from) } }
{ self.get_internal_links() .map_err(From::from) .map(|iter| StoreIdIterator::new(Box::new(iter.map(|e| e.get_store_id().clone())))) .map(|i| AnnotationIter::new(i, store)) }
identifier_body
annotateable.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
{ let _ = anno.set_isflag::<IsAnnotation>()?; let _ = anno .get_header_mut() .insert("annotation.name", Value::String(String::from(ann_name)))?; } Ok(anno) }) ....
fn annotate<'a>(&mut self, store: &'a Store, ann_name: &str) -> Result<FileLockEntry<'a>> { use module_path::ModuleEntryPath; store.retrieve(ModuleEntryPath::new(ann_name).into_storeid()?) .map_err(From::from) .and_then(|mut anno| {
random_line_split
textdecoder.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::TextDecoderBinding; use dom::bindings::codegen::Bindings::TextDecoderBinding...
#[allow(unsafe_code)] fn Decode(self, _cx: *mut JSContext, input: Option<*mut JSObject>) -> Fallible<USVString> { let input = match input { Some(input) => input, None => return Ok(USVString("".to_owned())), }; let mut length = 0; let mut d...
{ self.fatal }
identifier_body
textdecoder.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::TextDecoderBinding; use dom::bindings::codegen::Bindings::TextDecoderBinding...
(encoding: EncodingRef, fatal: bool) -> TextDecoder { TextDecoder { reflector_: Reflector::new(), encoding: encoding, fatal: fatal, } } fn make_range_error() -> Fallible<Root<TextDecoder>> { Err(Error::Range("The given encoding is not supported.".to_o...
new_inherited
identifier_name
textdecoder.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::TextDecoderBinding; use dom::bindings::codegen::Bindings::TextDecoderBinding...
} }
match self.encoding.decode(buffer, trap) { Ok(s) => Ok(USVString(s)), Err(_) => Err(Error::Type("Decoding failed".to_owned())), }
random_line_split
save_results.py
# argv[1] - file path to main folder (like $HOME/dsge-models) # argv[2] - name of model (e.g. 'dsf' or 'nk' or 'ca') from scipy.io import loadmat from sys import argv from json import load TT = 30 # how many periods of results to send model = argv[2] fpath = argv[1] + '/' + model + '_mfiles/' jso...
f.close()
f.write(str(names[key]) + ', ' + str(data[key])[1:-1] + '\n')
conditional_block
save_results.py
# argv[1] - file path to main folder (like $HOME/dsge-models) # argv[2] - name of model (e.g. 'dsf' or 'nk' or 'ca') from scipy.io import loadmat from sys import argv from json import load TT = 30 # how many periods of results to send model = argv[2] fpath = argv[1] + '/' + model + '_mfiles/' jso...
json_data = open(fpath + model + '_results.json') data = load(json_data) json_data.close() # pull JSON of short+long var names into python dict json_names = open(fpath + 'json/var_list.json') names = load(json_names) json_names.close() # make string of public directory pub_fpath = fpath[:fpath[:-1].rfind('/')] + '/pu...
# pull JSON data into python dict
random_line_split
vsw-602_mp_queue_stats.py
from ryu.base.app_manager import RyuApp from ryu.controller.ofp_event import EventOFPSwitchFeatures from ryu.controller.ofp_event import EventOFPQueueStatsReply from ryu.controller.handler import set_ev_cls from ryu.controller.handler import CONFIG_DISPATCHER from ryu.controller.handler import MAIN_DISPATCHER from ryu....
queues.append('port_no=%d queue_id=%d ' 'tx_bytes=%d tx_packets=%d tx_errors=%d ' 'duration_sec=%d duration_nsec=%d' % (stat.port_no, stat.queue_id, stat.tx_bytes, stat.tx_packets, stat.tx_errors, ...
queues = [] for stat in ev.msg.body:
random_line_split
vsw-602_mp_queue_stats.py
from ryu.base.app_manager import RyuApp from ryu.controller.ofp_event import EventOFPSwitchFeatures from ryu.controller.ofp_event import EventOFPQueueStatsReply from ryu.controller.handler import set_ev_cls from ryu.controller.handler import CONFIG_DISPATCHER from ryu.controller.handler import MAIN_DISPATCHER from ryu....
self.logger.info('QueueStats: %s', queues)
queues.append('port_no=%d queue_id=%d ' 'tx_bytes=%d tx_packets=%d tx_errors=%d ' 'duration_sec=%d duration_nsec=%d' % (stat.port_no, stat.queue_id, stat.tx_bytes, stat.tx_packets, stat.tx_errors, ...
conditional_block
vsw-602_mp_queue_stats.py
from ryu.base.app_manager import RyuApp from ryu.controller.ofp_event import EventOFPSwitchFeatures from ryu.controller.ofp_event import EventOFPQueueStatsReply from ryu.controller.handler import set_ev_cls from ryu.controller.handler import CONFIG_DISPATCHER from ryu.controller.handler import MAIN_DISPATCHER from ryu....
queues = [] for stat in ev.msg.body: queues.append('port_no=%d queue_id=%d ' 'tx_bytes=%d tx_packets=%d tx_errors=%d ' 'duration_sec=%d duration_nsec=%d' % (stat.port_no, stat.queue_id, stat.tx_b...
identifier_body
vsw-602_mp_queue_stats.py
from ryu.base.app_manager import RyuApp from ryu.controller.ofp_event import EventOFPSwitchFeatures from ryu.controller.ofp_event import EventOFPQueueStatsReply from ryu.controller.handler import set_ev_cls from ryu.controller.handler import CONFIG_DISPATCHER from ryu.controller.handler import MAIN_DISPATCHER from ryu....
(self, datapath, table_id): parser = datapath.ofproto_parser ofproto = datapath.ofproto req = parser.OFPQueueStatsRequest(datapath, 0, ofproto.OFPP_ANY, ofproto.OFPQ_ALL) datapath.send_msg(req) @set_ev_cls(EventOFPQueueStatsReply, MAIN_DISP...
install_sample
identifier_name
cap-clause-move.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 ...
{ let x = ~3; let y = ptr::to_unsafe_ptr(&(*x)) as uint; let snd_move: ~fn() -> uint = || ptr::to_unsafe_ptr(&(*x)) as uint; assert_eq!(snd_move(), y); let x = ~4; let y = ptr::to_unsafe_ptr(&(*x)) as uint; let lam_move: ~fn() -> uint = || ptr::to_unsafe_ptr(&(*x)) as uint; assert_eq!(l...
identifier_body
cap-clause-move.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 ...
() { let x = ~3; let y = ptr::to_unsafe_ptr(&(*x)) as uint; let snd_move: ~fn() -> uint = || ptr::to_unsafe_ptr(&(*x)) as uint; assert_eq!(snd_move(), y); let x = ~4; let y = ptr::to_unsafe_ptr(&(*x)) as uint; let lam_move: ~fn() -> uint = || ptr::to_unsafe_ptr(&(*x)) as uint; assert_eq...
main
identifier_name
cap-clause-move.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::ptr; pub fn main() { let x = ~3; let y = ptr::to_unsafe_ptr(&(*x)) as uint; let snd_move: ~fn() -> uint = || ptr::to_unsafe_ptr(&(*x...
random_line_split
context_discovery.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 '../util/ng_dev_mode'; import {assertDomNode} from '../util/assert'; import {EMPTY_ARRAY} from './empty'; im...
tNode = traverseNextElement(tNode); } return -1; } /** * Returns a list of directives extracted from the given view based on the * provided list of directive index values. * * @param nodeIndex The node index * @param lView The target view data * @param includeComponents Whether or not to include component...
if (lView[i] === directiveInstance) { return tNode.index; } }
conditional_block
context_discovery.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 '../util/ng_dev_mode'; import {assertDomNode} from '../util/assert'; import {EMPTY_ARRAY} from './empty'; im...
const parentContext = readPatchedData(parent); if (parentContext) { let lView: LView|null; if (Array.isArray(parentContext)) { lView = parentContext as LView; } else { lView = parentContext.lView; } // the edge of the app was also reached here thr...
random_line_split
context_discovery.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 '../util/ng_dev_mode'; import {assertDomNode} from '../util/assert'; import {EMPTY_ARRAY} from './empty'; im...
(target: any): LContext|null { let mpValue = readPatchedData(target); if (mpValue) { // only when it's an array is it considered an LView instance // ... otherwise it's an already constructed LContext instance if (Array.isArray(mpValue)) { const lView: LView = mpValue !; let nodeIndex: numbe...
getLContext
identifier_name
context_discovery.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 '../util/ng_dev_mode'; import {assertDomNode} from '../util/assert'; import {EMPTY_ARRAY} from './empty'; im...
/** * Locates the component within the given LView and returns the matching index */ function findViaComponent(lView: LView, componentInstance: {}): number { const componentIndices = lView[TVIEW].components; if (componentIndices) { for (let i = 0; i < componentIndices.length; i++) { const elementCompone...
if (tNode.child) { return tNode.child; } else if (tNode.next) { return tNode.next; } else { // Let's take the following template: <div><span>text</span></div><component/> // After checking the text node, we need to find the next parent that has a "next" TNode, // in this case the parent `div`,...
identifier_body
buffer.py
class Buffer(object): """ A Buffer is a simple FIFO buffer. You write() stuff to it, and you read() them back. You can also peek() or drain() data. """ def __init__(self, data=''): """ Initialize a buffer with 'data'. """ self.buffer = bytes(data) def read(self,...
def write(self, data): """ Append 'data' to the buffer. """ self.buffer = self.buffer + data def peek(self, n=-1): """ Return 'n' bytes from the buffer, without draining them. If 'n' is negative, return the whole buffer. If 'n' is larger than the...
self.buffer = self.buffer[n:] return data
random_line_split
buffer.py
class Buffer(object): """ A Buffer is a simple FIFO buffer. You write() stuff to it, and you read() them back. You can also peek() or drain() data. """ def __init__(self, data=''): """ Initialize a buffer with 'data'. """ self.buffer = bytes(data) def read(self,...
return self.buffer[:n] def drain(self, n=-1): """ Drain 'n' bytes from the buffer. If 'n' is negative, drain the whole buffer. If 'n' is larger than the size of the buffer, drain the whole buffer. """ if (n < 0) or (n > len(self.buffer)): ...
return self.buffer
conditional_block
buffer.py
class Buffer(object): """ A Buffer is a simple FIFO buffer. You write() stuff to it, and you read() them back. You can also peek() or drain() data. """ def __init__(self, data=''): """ Initialize a buffer with 'data'. """ self.buffer = bytes(data) def read(self,...
def __nonzero__(self): """ Returns True if the buffer is non-empty. Used in truth-value testing. """ return True if len(self.buffer) else False
"""Returns length of buffer. Used in len().""" return len(self.buffer)
identifier_body
buffer.py
class Buffer(object): """ A Buffer is a simple FIFO buffer. You write() stuff to it, and you read() them back. You can also peek() or drain() data. """ def __init__(self, data=''): """ Initialize a buffer with 'data'. """ self.buffer = bytes(data) def read(self,...
(self, n=-1): """ Return 'n' bytes from the buffer, without draining them. If 'n' is negative, return the whole buffer. If 'n' is larger than the size of the buffer, return the whole buffer. """ if (n < 0) or (n > len(self.buffer)): return self.buffe...
peek
identifier_name
test_dumpgenerator.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # Copyright (C) 2011-2014 WikiTeam developers # 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 optio...
this directory #shutil.copy2('../dumpgenerator.py', './dumpgenerator.py') unittest.main()
tests = [ # Alone wikis ['http://archiveteam.org', 'http://archiveteam.org/api.php', 'http://archiveteam.org/index.php'], ['http://skilledtests.com/wiki/', 'http://skilledtests.com/wiki/api.php', 'http://skilledtests.com/wiki/index.php'], # Editthis wik...
identifier_body
test_dumpgenerator.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # Copyright (C) 2011-2014 WikiTeam developers # 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 optio...
(unittest.TestCase): # Documentation # http://revista.python.org.ar/1/html/unittest.html # https://docs.python.org/2/library/unittest.html # Ideas: # - Check one wiki per wikifarm at least (page titles & images, with/out API) def test_delay(self): # This test checks several del...
TestDumpgenerator
identifier_name
test_dumpgenerator.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # Copyright (C) 2011-2014 WikiTeam developers # 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 optio...
ad the title list using API and index.php # Compare both lists in length and title by title # Check the presence of some special titles, like odd chars # The tested wikis are from different wikifarms and some alone print '\n', '#'*73, '\n', 'test_getPageTitles', '\n', '#'*73 ...
re different'.format(filename_api, result_index[c][0])) self.assertEqual(url_api, result_index[c][1], u'{0} and {1} are different'.format(url_api, result_index[c][1])) self.assertEqual(uploader_api, result_index[c][2], u'{0} and {1} are different'.format(uploader_api, result_index[c][2])...
conditional_block
test_dumpgenerator.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # Copyright (C) 2011-2014 WikiTeam developers # 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 optio...
getPageTitles(config=config_index, session=session) titles_index = './%s-%s-titles.txt' % (domain2prefix(config=config_index), config_index['date']) result_index = open(titles_index, 'r').read().splitlines() os.remove(titles_index) self.assertTrue(pagetocheck ...
print 'Testing', index print 'Trying to parse', pagetocheck, 'with index' config_index = {'index': index, 'api': '', 'delay': 0, 'namespaces': ['all'], 'exnamespaces': [], 'date': datetime.datetime.now().strftime('%Y%m%d'), 'path': '.'}
random_line_split
account.rs
// droplet_limit number The total number of droplets the user may have // email string The email the user has registered for Digital // Ocean with // uuid string The universal identifier for this user // email_verified boolean If true, the user has verified their account /...
pub uuid: String, pub email_verified: bool, } impl NotArray for Account {} impl fmt::Display for Account { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Email: {}\n\ Droplet Limit: {:.0}\n\ UUID: {}\n\ E-Ma...
pub droplet_limit: f64, pub email: String,
random_line_split
account.rs
// droplet_limit number The total number of droplets the user may have // email string The email the user has registered for Digital // Ocean with // uuid string The universal identifier for this user // email_verified boolean If true, the user has verified their account /...
} // TODO: Implement response headers: // content-type: application/json; charset=utf-8 // status: 200 OK // ratelimit-limit: 1200 // ratelimit-remaining: 1137 // ratelimit-reset: 1415984218
{ "account".into() }
identifier_body
account.rs
// droplet_limit number The total number of droplets the user may have // email string The email the user has registered for Digital // Ocean with // uuid string The universal identifier for this user // email_verified boolean If true, the user has verified their account /...
<'a>() -> Cow<'a, str> { "account".into() } } // TODO: Implement response headers: // content-type: application/json; charset=utf-8 // status: 200 OK // ratelimit-limit: 1200 // ratelimit-remaining: 1137 // ratelimit-reset: 1415984218
name
identifier_name
projecttags.py
from django import template from django.conf import settings from django.template.defaultfilters import stringfilter import os register = template.Library() @register.filter(name='basename') @stringfilter def basename(value): return os.path.basename(value) @register.filter(name='replace_macros') @stringfilter...
return {'submission': submission}
identifier_body
projecttags.py
from django import template from django.conf import settings from django.template.defaultfilters import stringfilter import os register = template.Library() @register.filter(name='basename') @stringfilter def basename(value): return os.path.basename(value) @register.filter(name='replace_macros') @stringfilter...
return {'submission': submission}
def grading(submission):
random_line_split
projecttags.py
from django import template from django.conf import settings from django.template.defaultfilters import stringfilter import os register = template.Library() @register.filter(name='basename') @stringfilter def basename(value): return os.path.basename(value) @register.filter(name='replace_macros') @stringfilter...
(assignment): return {'assignment': assignment, 'show_timeout': True} @register.inclusion_tag('inclusion_tags/deadline.html') def deadline(assignment): return {'assignment': assignment, 'show_timeout': False} @register.inclusion_tag('inclusion_tags/grading.html') def grading(submission): return {'submis...
deadline_timeout
identifier_name
projecttags.py
from django import template from django.conf import settings from django.template.defaultfilters import stringfilter import os register = template.Library() @register.filter(name='basename') @stringfilter def basename(value): return os.path.basename(value) @register.filter(name='replace_macros') @stringfilter...
if subm.state in [subm.SUBMITTED_TESTED, subm.SUBMITTED, subm.TEST_FULL_PENDING, subm.GRADED, subm.TEST_FULL_FAILED]: return green_label if subm.state == subm.TEST_VALIDITY_FAILED: return red_label retur...
if subm.grading.means_passed: return green_label else: return red_label
conditional_block
state_script.rs
use crate::state::*; use std; use std::process::Command; struct StateScript { script_path: String, shared_state: SharedState, state_observer: StateObserver, } impl StateScript { fn new(script_path: &str, shared_state: SharedState) -> StateScript { let state_observer = shared_state.lock().add_o...
fn run(&mut self) { let mut stream_state; let mut output_name: String; { let state = self.shared_state.lock(); output_name = state.current_output().name.clone(); stream_state = state.state().stream_state; }; self.run_script(stream_state, ...
{ let result = Command::new(&self.script_path) .arg(state.as_str()) .arg(output) .status(); match result { Ok(status) => { if !status.success() { println!( "ERROR: {} {} failed with error code {}"...
identifier_body
state_script.rs
use crate::state::*; use std; use std::process::Command; struct StateScript { script_path: String, shared_state: SharedState, state_observer: StateObserver, } impl StateScript { fn
(script_path: &str, shared_state: SharedState) -> StateScript { let state_observer = shared_state.lock().add_observer(); StateScript { script_path: String::from(script_path), shared_state, state_observer, } } fn run_script(&self, state: StreamState, o...
new
identifier_name
state_script.rs
use crate::state::*; use std; use std::process::Command; struct StateScript { script_path: String, shared_state: SharedState, state_observer: StateObserver, } impl StateScript { fn new(script_path: &str, shared_state: SharedState) -> StateScript { let state_observer = shared_state.lock().add_o...
state.as_str(), status.code().unwrap_or(0) ); } } Err(e) => println!("ERROR: Failed to run {}: {}", self.script_path, e), } } fn run(&mut self) { let mut stream_state; let mut out...
"ERROR: {} {} failed with error code {}", self.script_path,
random_line_split
main.py
from __future__ import absolute_import import re, os, sys from clay import app import clay.config from flask import make_response, request, redirect, render_template, url_for from epubber.fimfic_epubgen import FimFictionEPubGenerator site_epub_classes = [ FimFictionEPubGenerator ] accesslog = clay.config.get...
epgen = epgenclass() if epgen.handle_url(story): epub_file, data = epgen.gen_epub() accesslog.info('%(title)s - %(url)s' % epgen.metas) del epgen response = make_response(data) response.headers["Content-Type"] = "app...
for epgenclass in site_epub_classes:
random_line_split
main.py
from __future__ import absolute_import import re, os, sys from clay import app import clay.config from flask import make_response, request, redirect, render_template, url_for from epubber.fimfic_epubgen import FimFictionEPubGenerator site_epub_classes = [ FimFictionEPubGenerator ] accesslog = clay.config.get...
(path): ''' Make shorter URLs for image files. ''' path = re.sub(r'[^A-Za-z0-9_.-]', r'_', path) return redirect(url_for('static', filename=os.path.join('img', path))) @app.route('/js/<path>', methods=['GET', 'POST']) def static_js_proxy_view(path): ''' Make shorter URLs for javascript fil...
static_img_proxy_view
identifier_name
main.py
from __future__ import absolute_import import re, os, sys from clay import app import clay.config from flask import make_response, request, redirect, render_template, url_for from epubber.fimfic_epubgen import FimFictionEPubGenerator site_epub_classes = [ FimFictionEPubGenerator ] accesslog = clay.config.get...
return render_template("main.html") ##################################################################### # Secondary Views Section ##################################################################### @app.route('/health', methods=['GET']) def health_view(): ''' Heartbeat view, because why not? '...
data = None for epgenclass in site_epub_classes: epgen = epgenclass() if epgen.handle_url(story): epub_file, data = epgen.gen_epub() accesslog.info('%(title)s - %(url)s' % epgen.metas) del epgen response = make_response(data...
conditional_block
main.py
from __future__ import absolute_import import re, os, sys from clay import app import clay.config from flask import make_response, request, redirect, render_template, url_for from epubber.fimfic_epubgen import FimFictionEPubGenerator site_epub_classes = [ FimFictionEPubGenerator ] accesslog = clay.config.get...
main() # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 nowrap
reload(sys) sys.setdefaultencoding('utf-8') # App Config app.secret_key = clay.config.get('flask.secret_key')
identifier_body
targetCenterList.py
import numpy as np import dnfpy.core.utils as utils from dnfpyUtils.stats.trajectory import Trajectory class TargetCenterList(Trajectory):
""" Input: inputMap (constructor) targetList (children) Output: the center of the followed track from target lsit """ def __init__(self,name,inputMap,inputSize,dim=1,dt=0.1,wrap=True,**kwargs): super().__init__(name=nam...
identifier_body
targetCenterList.py
import numpy as np import dnfpy.core.utils as utils from dnfpyUtils.stats.trajectory import Trajectory class
(Trajectory): """ Input: inputMap (constructor) targetList (children) Output: the center of the followed track from target lsit """ def __init__(self,name,inputMap,inputSize,dim=1,dt=0.1,wrap=True,**kwargs): sup...
TargetCenterList
identifier_name
targetCenterList.py
import numpy as np import dnfpy.core.utils as utils from dnfpyUtils.stats.trajectory import Trajectory class TargetCenterList(Trajectory): """ Input: inputMap (constructor) targetList (children) Output: the center of the followed track from tar...
def getViewSpace(self): dim = self.getArg('dim') return (1,)*dim
li.append(np.array(target.getCenter())/inputSize) self._data = li self.trace.append(np.copy(self._data))
random_line_split
targetCenterList.py
import numpy as np import dnfpy.core.utils as utils from dnfpyUtils.stats.trajectory import Trajectory class TargetCenterList(Trajectory): """ Input: inputMap (constructor) targetList (children) Output: the center of the followed track from tar...
self._data = li self.trace.append(np.copy(self._data)) def getViewSpace(self): dim = self.getArg('dim') return (1,)*dim
target = self.inputMap.getTracks()[targetList[i]] li.append(np.array(target.getCenter())/inputSize)
conditional_block
2PopDNAnorec_1_711.js
USETEXTLINKS = 1 STARTALLOPEN = 0 WRAPTEXT = 1 PRESERVESTATE = 0
foldersTree = gFld("<i>ARLEQUIN RESULTS (2PopDNAnorec_1_711.arp)</i>", "") insDoc(foldersTree, gLnk("R", "Arlequin log file", "Arlequin_log.txt")) aux1 = insFld(foldersTree, gFld("Run of 31/07/18 at 17:02:27", "2PopDNAnorec_1_711.xml#31_07_18at17_02_27")) insDoc(aux1, gLnk("R", "Settings", "2PopDNAnorec_1_711.xml#31_...
HIGHLIGHT = 1 ICONPATH = 'file:////Users/eric/github/popgenDB/sims_for_structure_paper/2PopDNAnorec_0.5_1000/' //change if the gif's folder is a subfolder, for example: 'images/'
random_line_split
15.4.4.21-9-c-i-26.js
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-26.js * @description Array.prototype.reduce - This object is the Arguments object which implements its own property get method (number of arguments equals number of parameters) */ function testc...
var func = function (a, b, c) { Array.prototype.reduce.call(arguments, callbackfn, initialValue); }; func(0, 1, 2); return testResult; } runTestCase(testcase);
{ if (idx === 2) { testResult = (curVal === 2); } }
identifier_body
15.4.4.21-9-c-i-26.js
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-26.js * @description Array.prototype.reduce - This object is the Arguments object which implements its own property get method (number of arguments equals number of parameters) */ function
() { var testResult = false; var initialValue = 0; function callbackfn(prevVal, curVal, idx, obj) { if (idx === 2) { testResult = (curVal === 2); } } var func = function (a, b, c) { Array.prototype.reduce.call(arguments, callb...
testcase
identifier_name
15.4.4.21-9-c-i-26.js
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-26.js * @description Array.prototype.reduce - This object is the Arguments object which implements its own property get method (number of arguments equals number of parameters) */ function testc...
} var func = function (a, b, c) { Array.prototype.reduce.call(arguments, callbackfn, initialValue); }; func(0, 1, 2); return testResult; } runTestCase(testcase);
{ testResult = (curVal === 2); }
conditional_block
15.4.4.21-9-c-i-26.js
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-26.js * @description Array.prototype.reduce - This object is the Arguments object which implements its own property get method (number of arguments equals number of parameters) */ function testc...
func(0, 1, 2); return testResult; } runTestCase(testcase);
Array.prototype.reduce.call(arguments, callbackfn, initialValue); };
random_line_split
test-amp-vk.js
/** * Copyright 2017 The AMP HTML 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 require...
return element.build().then(() => { const resource = Resource.forElement(element); resource.measure(); return element.layoutCallback(); }).then(() => element); } it('requires data-embedtype', () => { const params = Object.assign({}, POST_PARAMS); delete params['embedtype']; r...
if (layout) { element.setAttribute('layout', layout); } doc.body.appendChild(element);
random_line_split