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 |
|---|---|---|---|---|
__init__.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... |
__all__ = ['classification', 'clustering', 'feature', 'fpm', 'linalg', 'random',
'recommendation', 'regression', 'stat', 'tree', 'util']
| raise Exception("MLlib requires NumPy 1.4+") | conditional_block |
test_new_instance.py | from django.contrib.auth.models import User
from django.test import TestCase, Client
from django.urls import reverse
# Declaration of Username and Password
username = 'admin'
password = 'Test1234$'
"""
Method to replicate
~~~~~~~~~~~~~~~~~~~
1. Bring up a new instance of NearBeach (grab from fixtures)
2. Try and log ... |
def test_admin_login(self):
c = Client()
# User will be logged in
login_user(c, self)
# Make sure the admin user can open up the project
response = c.get(reverse('dashboard'))
self.assertEqual(response.status_code, 200)
| self.credentials = {
'username': username,
'password': password
} | identifier_body |
test_new_instance.py | from django.contrib.auth.models import User
from django.test import TestCase, Client
from django.urls import reverse
# Declaration of Username and Password
username = 'admin'
password = 'Test1234$'
"""
Method to replicate
~~~~~~~~~~~~~~~~~~~
1. Bring up a new instance of NearBeach (grab from fixtures)
2. Try and log ... | (TestCase):
fixtures = ['NearBeach_no_setup.json']
def setUp(self):
self.credentials = {
'username': username,
'password': password
}
def test_admin_login(self):
c = Client()
# User will be logged in
login_user(c, self)
# Make sure ... | NewInstanceLoginTest | identifier_name |
test_new_instance.py | from django.contrib.auth.models import User
from django.test import TestCase, Client
from django.urls import reverse
# Declaration of Username and Password
username = 'admin' | 1. Bring up a new instance of NearBeach (grab from fixtures)
2. Try and log in as the admin user
Expected Results
~~~~~~~~~~~~~~~~
User will log in with no issues, system will create all of the user's permission sets and groups
"""
def login_user(c: object, self: object) -> object:
response = c.post(
rev... | password = 'Test1234$'
"""
Method to replicate
~~~~~~~~~~~~~~~~~~~ | random_line_split |
image.ts | /**
* Entry point for Embed Images
*/
/// <reference path="./embed.d.ts" />
// require('html5shiv');
//import _ = require('underscore');
let pym = require('pym.js');
import ConfigService from '../components/embed/config/service';
import ResizeEl from '../components/utils/resizeEl';
export default class Embed {
... | }
}
(<any>window).embedPlugin = new Embed(); | });
this.resizer.resize(); | random_line_split |
image.ts | /**
* Entry point for Embed Images
*/
/// <reference path="./embed.d.ts" />
// require('html5shiv');
//import _ = require('underscore');
let pym = require('pym.js');
import ConfigService from '../components/embed/config/service';
import ResizeEl from '../components/utils/resizeEl';
export default class | {
private configService;
private resourceOriginalWidth;
private resourceOriginalHeight;
private $embedContainer;
private $embedResource;
private resizer;
private pymChild;
constructor() {
let that = this;
this.configService = new ConfigService();
this.$embedCont... | Embed | identifier_name |
image.ts | /**
* Entry point for Embed Images
*/
/// <reference path="./embed.d.ts" />
// require('html5shiv');
//import _ = require('underscore');
let pym = require('pym.js');
import ConfigService from '../components/embed/config/service';
import ResizeEl from '../components/utils/resizeEl';
export default class Embed {
... | else {
this.$embedResource.style.width = '100%';
this.$embedResource.style.height = 'auto';
this.pymChild = new (<any>pym).Child({id: 'phraseanet-embed-frame', renderCallback: function(windowWidth) {
let ratio = that.resourceOriginalHeight / that.resourceOriginalWidt... | {
this.initResizer();
} | conditional_block |
image.ts | /**
* Entry point for Embed Images
*/
/// <reference path="./embed.d.ts" />
// require('html5shiv');
//import _ = require('underscore');
let pym = require('pym.js');
import ConfigService from '../components/embed/config/service';
import ResizeEl from '../components/utils/resizeEl';
export default class Embed {
... |
}
(<any>window).embedPlugin = new Embed();
| {
this.resizer = new ResizeEl({
target: this.$embedResource,
container: this.$embedContainer,
resizeOnWindowChange: this.configService.get('resource.fitIn') === true ? true : false
});
this.resizer.setContainerDimensions({
width: <any>window.inner... | identifier_body |
RecipeReviewCard.js | import * as React from 'react';
import { experimentalStyled as styled } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardHeader from '@material-ui/core/CardHeader';
import CardMedia from '@material-ui/core/CardMedia';
import CardContent from '@material-ui/core/CardContent';
import ... | title="Shrimp and Chorizo Paella"
subheader="September 14, 2016"
/>
<CardMedia
sx={{
height: 0,
paddingTop: '56.25%', // 16:9
}}
image="/static/images/cards/paella.jpg"
title="Paella dish"
/>
<CardContent>
<Typography va... | <MoreVertIcon />
</IconButton>
} | random_line_split |
RecipeReviewCard.js | import * as React from 'react';
import { experimentalStyled as styled } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardHeader from '@material-ui/core/CardHeader';
import CardMedia from '@material-ui/core/CardMedia';
import CardContent from '@material-ui/core/CardContent';
import ... | {
const [expanded, setExpanded] = React.useState(false);
const handleExpandClick = () => {
setExpanded(!expanded);
};
return (
<Card sx={{ maxWidth: 345 }}>
<CardHeader
avatar={
<Avatar sx={{ bgcolor: red[500] }} aria-label="recipe">
R
</Avatar>
}
... | identifier_body | |
RecipeReviewCard.js | import * as React from 'react';
import { experimentalStyled as styled } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardHeader from '@material-ui/core/CardHeader';
import CardMedia from '@material-ui/core/CardMedia';
import CardContent from '@material-ui/core/CardContent';
import ... | () {
const [expanded, setExpanded] = React.useState(false);
const handleExpandClick = () => {
setExpanded(!expanded);
};
return (
<Card sx={{ maxWidth: 345 }}>
<CardHeader
avatar={
<Avatar sx={{ bgcolor: red[500] }} aria-label="recipe">
R
</Avatar>
... | RecipeReviewCard | identifier_name |
WebRtcProducer.ts | ///<reference path="../../../lib/RTCPeerConnection.d.ts"/>
///<reference path="WebRtcCommons.ts"/>
"use strict";
class WebRtcProducer {
private _id : string;
private _debugMode : boolean = false;
private _successCalled : boolean = false;
private connection: RTCPeerConnection = null;
private channel: RTCDa... | (msg: string): void {
if (this._debugMode)
this.log('Sending message: "' +msg +'"');
if (!this.isConnected())
throw new WebRtcConnectionNotInitializedError('');
this.channel.send(msg);
}
/**
* open
*/
open(): void{
if (this._debugMode)
this.log('Creating new; iceSer... | sendMessage | identifier_name |
WebRtcProducer.ts | ///<reference path="../../../lib/RTCPeerConnection.d.ts"/>
///<reference path="WebRtcCommons.ts"/>
"use strict";
class WebRtcProducer {
private _id : string;
private _debugMode : boolean = false;
private _successCalled : boolean = false;
private connection: RTCPeerConnection = null;
private channel: RTCDa... | if (typeof webkitRTCPeerConnection === 'function') {
this.connection = new webkitRTCPeerConnection( this._config );
} else if (typeof mozRTCPeerConnection === 'function') {
throw new Error('Not implemented yet.');
//this.connection = new mozRTCPeerConnection( this._config );
} else
throw new Error(... | random_line_split | |
WebRtcProducer.ts | ///<reference path="../../../lib/RTCPeerConnection.d.ts"/>
///<reference path="WebRtcCommons.ts"/>
"use strict";
class WebRtcProducer {
private _id : string;
private _debugMode : boolean = false;
private _successCalled : boolean = false;
private connection: RTCPeerConnection = null;
private channel: RTCDa... | else
throw new Error('unknown implementation of RTCPeerConnection');
this.internalInit();
this._successCalled = false;
}
/**
* close
*/
close(): void{
this._successCalled = false;
if (this.channel != null)
this.channel.close();
if (this.connection != null)
this.connection.close();... | {
throw new Error('Not implemented yet.');
//this.connection = new mozRTCPeerConnection( this._config );
} | conditional_block |
WebRtcProducer.ts | ///<reference path="../../../lib/RTCPeerConnection.d.ts"/>
///<reference path="WebRtcCommons.ts"/>
"use strict";
class WebRtcProducer {
private _id : string;
private _debugMode : boolean = false;
private _successCalled : boolean = false;
private connection: RTCPeerConnection = null;
private channel: RTCDa... |
/**
* open
*/
open(): void{
if (this._debugMode)
this.log('Creating new; iceServers: ' +JSON.stringify(this._config));
if (typeof webkitRTCPeerConnection === 'function') {
this.connection = new webkitRTCPeerConnection( this._config );
} else if (typeof mozRTCPeerConnection === 'f... | {
if (this._debugMode)
this.log('Sending message: "' +msg +'"');
if (!this.isConnected())
throw new WebRtcConnectionNotInitializedError('');
this.channel.send(msg);
} | identifier_body |
bspline_surface_pure.py | """
Experiment with bezier surface and bspline surface
"""
from OCC.gp import *
from OCC.Geom import *
from OCC.TColGeom import *
from OCC.TColgp import *
from OCC.TColStd import *
from OCC.GeomConvert import *
from OCC.BRepBuilderAPI import *
from OCC.TopoDS import *
from OCC.STEPControl import *
def bezier_surfa... | print(umult.Value(i))
print("vmult: ", vmult)
for j in range(vmult.Lower(), vmult.Length() + 1, 1):
print(vmult.Value(i))
print()
udeg = BB.UDegree()
vdeg = BB.VDegree()
print("udeg, vdeg: ", udeg, vdeg)
BSPLSURF = Geom_BSplineSurface(pol... | print("umult: ", umult)
for i in range(umult.Lower(), umult.Length() + 1, 1): | random_line_split |
bspline_surface_pure.py | """
Experiment with bezier surface and bspline surface
"""
from OCC.gp import *
from OCC.Geom import *
from OCC.TColGeom import *
from OCC.TColgp import *
from OCC.TColStd import *
from OCC.GeomConvert import *
from OCC.BRepBuilderAPI import *
from OCC.TopoDS import *
from OCC.STEPControl import *
def bezier_surfa... |
print("vknots: ", vknots)
for j in range(vknots.Lower(), vknots.Length() + 1, 1):
print(vknots.Value(j))
print()
# Multi U and V
umult = BB.UMultiplicities().GetObject().Array1()
vmult = BB.VMultiplicities().GetObject().Array1()
print("umult: ", umul... | print(uknots.Value(i)) | conditional_block |
bspline_surface_pure.py | """
Experiment with bezier surface and bspline surface
"""
from OCC.gp import *
from OCC.Geom import *
from OCC.TColGeom import *
from OCC.TColgp import *
from OCC.TColStd import *
from OCC.GeomConvert import *
from OCC.BRepBuilderAPI import *
from OCC.TopoDS import *
from OCC.STEPControl import *
def bezier_surfa... |
if __name__ == '__main__':
#bezier_surfaces()
bspline_surface() | """
Try to create B-spline surface directly
"""
# Set U and V degree to 2
udeg = 2
vdeg = 2
# Non-periodic surface
uperiod = False
vperiod = False
# Create 2D array of poles (control points)
poles = TColgp_Array2OfPnt(1, 3, 1, 3)
poles.SetValue(1, 1, gp_Pnt(1, 1, 1))
p... | identifier_body |
bspline_surface_pure.py | """
Experiment with bezier surface and bspline surface
"""
from OCC.gp import *
from OCC.Geom import *
from OCC.TColGeom import *
from OCC.TColgp import *
from OCC.TColStd import *
from OCC.GeomConvert import *
from OCC.BRepBuilderAPI import *
from OCC.TopoDS import *
from OCC.STEPControl import *
def | (event=None):
"""
Create bezier surface, then create bspline surface from import
it and search, what is inside created bspline surface.
"""
array = TColgp_Array2OfPnt(1, 3, 1, 3)
array.SetValue(1, 1, gp_Pnt(1, 1, 1))
array.SetValue(1, 2, gp_Pnt(2, 1, 2))
array.SetValue(1, 3, gp_Pnt(3, 1... | bezier_surfaces | identifier_name |
all_14.js | var searchData=
[ | ['user',['user',['../class_cool_m_q_t_t.html#a8cd47e45d457f908d4b4390b35aaee83',1,'CoolMQTT']]],
['useractive',['userActive',['../class_cool_board.html#a6395459131d6889a3005f79c7a35e964',1,'CoolBoard']]],
['userdata',['userData',['../class_cool_board.html#ae7358fb6e623cfc81b775f5f1734909b',1,'CoolBoard']]],
['u... | ['udp',['Udp',['../class_cool_time.html#a4e23216a8121ca79d0fb019f30884b92',1,'CoolTime']]],
['unsubscribe',['unsubscribe',['../class_cool_pub_sub_client.html#a850554280e314d6b5c33c73fd9e809fc',1,'CoolPubSubClient']]],
['update',['update',['../class_cool_board.html#a8612756d3f73198cdde857a66f0fe690',1,'CoolBoard::... | random_line_split |
TUTableImpl.js | /*
* Name: TUTableImpl.js
* Module:
* Location: Norris/test/unit
* Date: 2015-05-25
* Version: v1.00 | * ================================================================================
* v1.00 2015-06-15 Carlon Chiara Approved
* ================================================================================
* v0.02 2015-06-02 Pavanello Fabio Matteo Verify
* ========================================================... | *
* History:
*
* ================================================================================
* Version Date Programmer Changes | random_line_split |
bootstrap.js | // "node scripts/create-package-app-test.js && node packages/app-test/synchronize.js && node packages/react-boilerplate-app-scripts/scripts/link-react-boilerplates.js && lerna bootstrap",
'use strict';
require('./create-package-app-test.js');
require('../packages/app-test/synchronize.js');
require('../packages/react-b... | resolve(__dirname, '../lerna.json'),
JSON.stringify(lernaJson, null, 2)
);
//end----加上packages/app-test
execSync('npm run lerna-bootstrap', { stdio: 'inherit' });
//begin----移除packages/app-test,发布的时候不会发布这个的,只是用来测试
if (lernaJson.packages.indexOf(packagesFolderName) !== -1) {
lernaJson.packages.splice(
... | //可能中途ctr+c,导致包名没被删除
lernaJson.packages.push(packagesFolderName);
}
fs.writeFileSync(
path. | conditional_block |
bootstrap.js | // "node scripts/create-package-app-test.js && node packages/app-test/synchronize.js && node packages/react-boilerplate-app-scripts/scripts/link-react-boilerplates.js && lerna bootstrap",
'use strict';
require('./create-package-app-test.js');
require('../packages/app-test/synchronize.js');
require('../packages/react-b... | } | random_line_split | |
_hasreltype.py | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2006 Donald N. Allingham
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at you... | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 US... | #
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of | random_line_split |
_hasreltype.py | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2006 Donald N. Allingham
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at you... | if self.rtype:
if self.rtype.is_custom() and self.use_regex:
if self.regex[0].search(str(family.get_relationship())) is None:
return False
elif self.rtype != family.get_relationship():
return False
return True | identifier_body | |
_hasreltype.py | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2006 Donald N. Allingham
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at you... | (self, db, family):
if self.rtype:
if self.rtype.is_custom() and self.use_regex:
if self.regex[0].search(str(family.get_relationship())) is None:
return False
elif self.rtype != family.get_relationship():
return False
return Tru... | apply | identifier_name |
_hasreltype.py | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2006 Donald N. Allingham
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at you... |
elif self.rtype != family.get_relationship():
return False
return True
| return False | conditional_block |
set.rs | use liner::KeyBindings;
use shell::Shell;
use shell::flags::*;
use std::io::{self, Write};
use std::iter;
const HELP: &'static str = r#"NAME
set - Set or unset values of shell options and positional parameters.
SYNOPSIS
set [ --help ] [-e | +e] [-x | +x] [-o [vi | emacs]] [- | --] [STRING]...
DESCRIPTION
... |
} else if arg.starts_with('-') {
if arg.len() == 1 {
positionals = Some(RetainIfNone);
break;
}
for flag in arg.bytes().skip(1) {
match flag {
b'e' => shell.flags |= ERR_EXIT,
b'o' => mat... | {
return 0;
} | conditional_block |
set.rs | use liner::KeyBindings;
use shell::Shell;
use shell::flags::*;
use std::io::{self, Write}; |
const HELP: &'static str = r#"NAME
set - Set or unset values of shell options and positional parameters.
SYNOPSIS
set [ --help ] [-e | +e] [-x | +x] [-o [vi | emacs]] [- | --] [STRING]...
DESCRIPTION
Shell options may be set using the '-' character, and unset using the '+' character.
OPTIONS
-e Exi... | use std::iter; | random_line_split |
set.rs | use liner::KeyBindings;
use shell::Shell;
use shell::flags::*;
use std::io::{self, Write};
use std::iter;
const HELP: &'static str = r#"NAME
set - Set or unset values of shell options and positional parameters.
SYNOPSIS
set [ --help ] [-e | +e] [-x | +x] [-o [vi | emacs]] [- | --] [STRING]...
DESCRIPTION
... | (args: &[&str], shell: &mut Shell) -> i32 {
let stdout = io::stdout();
let stderr = io::stderr();
let mut args_iter = args.iter();
let mut positionals = None;
while let Some(arg) = args_iter.next() {
if arg.starts_with("--") {
if arg.len() == 2 {
positionals = So... | set | identifier_name |
__init__.py | from __future__ import unicode_literals
__author__ = ", ".join(["Shyue Ping Ong", "Anubhav Jain", "Geoffroy Hautier",
"William Davidson Richard", "Stephen Dacek",
"Sai Jayaraman", "Michael Kocher", "Dan Gunter",
"Shreyas Cholia", "Vincent L Chevri... | from .io.smartio import read_structure, write_structure, read_mol, write_mol
from .matproj.rest import MPRester
from monty.json import MontyEncoder, MontyDecoder, MSONable | from .core import *
from .serializers.json_coders import pmg_dump, pmg_load
from .electronic_structure.core import Spin, Orbital | random_line_split |
mod.rs | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
fn from_pb(pb: Self::ProtoStruct) -> Result<Self, Error> {
ensure!(
u16::try_from(pb).is_ok(),
"{} is out of range for valid ValidatorId",
pb
);
Ok(Self(pb as u16))
}
}
| {
u32::from(self.0)
} | identifier_body |
mod.rs | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | (&self) -> Self::ProtoStruct {
self.0
}
fn from_pb(pb: Self::ProtoStruct) -> Result<Self, Error> {
Ok(Self(pb))
}
}
impl ProtobufConvert for Round {
type ProtoStruct = u32;
fn to_pb(&self) -> Self::ProtoStruct {
self.0
}
fn from_pb(pb: Self::ProtoStruct) -> Result... | to_pb | identifier_name |
mod.rs | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | u16::try_from(pb).is_ok(),
"{} is out of range for valid ValidatorId",
pb
);
Ok(Self(pb as u16))
}
} | ensure!( | random_line_split |
properties_e.js | var searchData=
[
['text',['text',['../class_politechnikon_1_1game__elements_1_1_text.html#aa18ff5a85e90a5d19b62976a65863932',1,'Politechnikon::game_elements::Text']]], | ['textbuffor',['TextBuffor',['../class_politechnikon_1_1game__elements_1_1_field.html#a35f9c0081c0928be00204ca03ca56f1e',1,'Politechnikon::game_elements::Field']]],
['texture',['Texture',['../class_politechnikon_1_1engine_1_1_initialized_object_texture.html#a01631ef3363a7c274d3b89d5032a4407',1,'Politechnikon::engin... | random_line_split | |
dropbox_account.py | #!/usr/bin/env python
# coding: utf8
"""
Dropbox Authentication for web2py
Developed by Massimo Di Pierro (2011)
Same License as Web2py License
"""
# mind here session is dropbox session, not current.session
import os
import re
import urllib
from dropbox import client, rest, session
from gluon import *
fro... | def put(self,filename,file):
return json.loads(self.client.put_file(filename,file))['bytes']
def get(self,filename,file):
return self.client.get_file(filename)
def dir(self,path):
return json.loads(self.client.metadata(path))
def use_dropbox(auth,filename='private/dropbox.key',**kwa... | return next | random_line_split |
dropbox_account.py | #!/usr/bin/env python
# coding: utf8
"""
Dropbox Authentication for web2py
Developed by Massimo Di Pierro (2011)
Same License as Web2py License
"""
# mind here session is dropbox session, not current.session
import os
import re
import urllib
from dropbox import client, rest, session
from gluon import *
fro... | (self,filename,file):
return self.client.get_file(filename)
def dir(self,path):
return json.loads(self.client.metadata(path))
def use_dropbox(auth,filename='private/dropbox.key',**kwargs):
path = os.path.join(current.request.folder,filename)
if os.path.exists(path):
request = curren... | get | identifier_name |
dropbox_account.py | #!/usr/bin/env python
# coding: utf8
"""
Dropbox Authentication for web2py
Developed by Massimo Di Pierro (2011)
Same License as Web2py License
"""
# mind here session is dropbox session, not current.session
import os
import re
import urllib
from dropbox import client, rest, session
from gluon import *
fro... |
def use_dropbox(auth,filename='private/dropbox.key',**kwargs):
path = os.path.join(current.request.folder,filename)
if os.path.exists(path):
request = current.request
key,secret,access_type = open(path,'r').read().strip().split(':')
host = current.request.env.http_host
login_ur... | return json.loads(self.client.metadata(path)) | identifier_body |
dropbox_account.py | #!/usr/bin/env python
# coding: utf8
"""
Dropbox Authentication for web2py
Developed by Massimo Di Pierro (2011)
Same License as Web2py License
"""
# mind here session is dropbox session, not current.session
import os
import re
import urllib
from dropbox import client, rest, session
from gluon import *
fro... | request = current.request
key,secret,access_type = open(path,'r').read().strip().split(':')
host = current.request.env.http_host
login_url = "http://%s/%s/default/user/login" % \
(host,request.application)
auth.settings.actions_disabled = \
['register','change_pas... | conditional_block | |
iana.py | #!/usr/bin/env python
#-----------------------------------------------------------------------------
# Copyright (c) 2008-2012, David P. D. Moss. All rights reserved.
#
# Released under the BSD license. See the LICENSE file for details.
#-----------------------------------------------------------------------------
... |
#-----------------------------------------------------------------------------
def get_latest_files():
"""Download the latest files from IANA"""
if _sys.version_info[0] == 3:
# Python 3.x
from urllib.request import Request, urlopen
else:
# Python 2.x
from urllib2 import... | """
Returns informational data specific to this IP address.
"""
info = {}
def within_bounds(ip, ip_range):
# Boundary checking for multiple IP classes.
if hasattr(ip_range, 'first'):
# IP network or IP range.
return ip in ip_range
elif hasattr(ip_rang... | identifier_body |
iana.py | #!/usr/bin/env python
#-----------------------------------------------------------------------------
# Copyright (c) 2008-2012, David P. D. Moss. All rights reserved.
#
# Released under the BSD license. See the LICENSE file for details.
#-----------------------------------------------------------------------------
... |
- http://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xml
"""
def __init__(self, fh, **kwargs):
"""
Constructor.
fh - a valid, open file handle to an IANA IPv6 address space file.
kwargs - additional parser options.
"""
super(IPv6Parse... | It can be found online here :- | random_line_split |
iana.py | #!/usr/bin/env python
#-----------------------------------------------------------------------------
# Copyright (c) 2008-2012, David P. D. Moss. All rights reserved.
#
# Released under the BSD license. See the LICENSE file for details.
#-----------------------------------------------------------------------------
... | (handler.ContentHandler):
def __init__(self, callback=None):
self._level = 0
self._is_active = False
self._record = None
self._tag_level = None
self._tag_payload = None
self._tag_feeding = None
self._callback = callback
def startElement(self, name, attrs... | SaxRecordParser | identifier_name |
iana.py | #!/usr/bin/env python
#-----------------------------------------------------------------------------
# Copyright (c) 2008-2012, David P. D. Moss. All rights reserved.
#
# Released under the BSD license. See the LICENSE file for details.
#-----------------------------------------------------------------------------
... |
raise Exception('Unsupported IP range or address: %r!' % ip_range)
if ip_addr.version == 4:
for cidr, record in _dict_items(IANA_INFO['IPv4']):
if within_bounds(ip_addr, cidr):
info.setdefault('IPv4', [])
info['IPv4'].append(record)
if ip_addr.... | return ip == ip_range | conditional_block |
index.d.ts | // Type definitions for simple-oauth2 1.0
// Project: https://github.com/lelylan/simple-oauth2
// Definitions by: [Michael Müller] <https://github.com/mad-mike>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import Bluebird = require("bluebird");
/** Creates a new simple-oauth2 client with the pas... | /** A string that represents the registered password. */
password: string;
/** A string that represents the application privileges */
scope: string;
}
interface ClientCredentialTokenConfig {
/** A string that represents the application privileges */
scope?: string;
}
export interface OAuthClie... |
interface PasswordTokenConfig {
/** A string that represents the registered username */
username: string; | random_line_split |
dataStore.js | var _ = require("lodash");
var fs = require("fs-extra");
module.exports = function(options) {
options = _.extend({
file: "data.json",
saveFrequency: 1,
indexing: false
}, options);
var lastSaved = 0;
//If the specified file doesn't exist, we create an empty JSON object
if (!fs.existsSync(options.file)) {... |
/**
* Sync the data currently in memory to the target file
*/
function syncData() {
if (options.saveFrequency === 0) return;
lastSaved++;
if (lastSaved === options.saveFrequency) {
fs.writeFile(options.file, JSON.stringify(_data, null, "\t"), function(err) {
if (err) {
console.log(err);
... | {
for (var key in _indexes) {
if (key.indexOf(pathIdentifier) === 0) {
delete _indexes[key];
}
}
} | identifier_body |
dataStore.js | var _ = require("lodash");
var fs = require("fs-extra");
module.exports = function(options) {
options = _.extend({
file: "data.json",
saveFrequency: 1,
indexing: false
}, options);
var lastSaved = 0;
//If the specified file doesn't exist, we create an empty JSON object
if (!fs.existsSync(options.file)) {... | return b;
}
});
syncData();
//Reset the matching indexes if it's turned on
if (options.indexing) {
resetIndex(path);
}
return clone(target);
} else {
//PUT
var parent = _parent(path);
var toPut = _.last(path.split("/"));
if (toPut === "") {
... | } else if (_.isObject(target)) {
//PATCH
if (patch) {
target = _.merge(target, data, function(a, b) {
if (_.isArray(a)) { | random_line_split |
dataStore.js | var _ = require("lodash");
var fs = require("fs-extra");
module.exports = function(options) {
options = _.extend({
file: "data.json",
saveFrequency: 1,
indexing: false
}, options);
var lastSaved = 0;
//If the specified file doesn't exist, we create an empty JSON object
if (!fs.existsSync(options.file)) {... | () {
if (options.saveFrequency === 0) return;
lastSaved++;
if (lastSaved === options.saveFrequency) {
fs.writeFile(options.file, JSON.stringify(_data, null, "\t"), function(err) {
if (err) {
console.log(err);
}
});
lastSaved = 0;
}
}
/**
* Private function for getting the reference ... | syncData | identifier_name |
dataStore.js | var _ = require("lodash");
var fs = require("fs-extra");
module.exports = function(options) {
options = _.extend({
file: "data.json",
saveFrequency: 1,
indexing: false
}, options);
var lastSaved = 0;
//If the specified file doesn't exist, we create an empty JSON object
if (!fs.existsSync(options.file)) {... | else {
temp = _.find(node, function(obj) {
return obj[options.idAttribute] === path[i];
});
//If it's not undefined, then assign it as the value
if (temp !== undefined) {
node = temp;
} else {
return null;
}
}
}
}
return node || null;
};
function getParent... | {
node = node[path[i]];
//If the given key doesn't exist, try the _id
} | conditional_block |
mod.rs |
prelude!();
use ::vga;
use super::pic::{PIC_1, PIC_2};
mod item;
pub use self::item::*;
mod idt_ptr;
pub use self::idt_ptr::*;
extern "C" {
fn interrupt0();
fn interrupt1();
}
extern {
fn __kernel_timer_tick();
}
const IDT_SIZE: usize = 64;
static mut IDT_TABLE: [IdtItem; IDT_SIZE] = [IdtItem::new();... |
vga::print(b"!! Interrupt !!");
println!("!! Interrupt: {:#x}, Error code: {:#x}", num, error_code);
if PIC_1.has_interrupt(num) {
PIC_1.end_of_interrupt();
}
if PIC_2.has_interrupt(num) {
PIC_1.end_of_interrupt();
PIC_2.end_of_interrupt();
}
}
pub unsafe fn init() {
... | {
__kernel_timer_tick();
// it will send EOI itself
return;
} | conditional_block |
mod.rs | prelude!();
use ::vga;
use super::pic::{PIC_1, PIC_2};
mod item; | pub use self::item::*;
mod idt_ptr;
pub use self::idt_ptr::*;
extern "C" {
fn interrupt0();
fn interrupt1();
}
extern {
fn __kernel_timer_tick();
}
const IDT_SIZE: usize = 64;
static mut IDT_TABLE: [IdtItem; IDT_SIZE] = [IdtItem::new(); IDT_SIZE];
#[no_mangle]
pub unsafe extern "C" fn handle_interrupt(... | random_line_split | |
mod.rs |
prelude!();
use ::vga;
use super::pic::{PIC_1, PIC_2};
mod item;
pub use self::item::*;
mod idt_ptr;
pub use self::idt_ptr::*;
extern "C" {
fn interrupt0();
fn interrupt1();
}
extern {
fn __kernel_timer_tick();
}
const IDT_SIZE: usize = 64;
static mut IDT_TABLE: [IdtItem; IDT_SIZE] = [IdtItem::new();... | {
let diff = interrupt1 as usize - interrupt0 as usize;
for i in 0..IDT_SIZE {
IDT_TABLE[i].set_offset(interrupt0 as usize + diff * i);
}
// 0 pic interrupt is used by thread scheduler
// { // FIXME
// let idx = PIC_1.get_interrupt_idt_num(0) as usize;
// IDT_TABLE[idx].type_at... | identifier_body | |
mod.rs |
prelude!();
use ::vga;
use super::pic::{PIC_1, PIC_2};
mod item;
pub use self::item::*;
mod idt_ptr;
pub use self::idt_ptr::*;
extern "C" {
fn interrupt0();
fn interrupt1();
}
extern {
fn __kernel_timer_tick();
}
const IDT_SIZE: usize = 64;
static mut IDT_TABLE: [IdtItem; IDT_SIZE] = [IdtItem::new();... | () {
let diff = interrupt1 as usize - interrupt0 as usize;
for i in 0..IDT_SIZE {
IDT_TABLE[i].set_offset(interrupt0 as usize + diff * i);
}
// 0 pic interrupt is used by thread scheduler
// { // FIXME
// let idx = PIC_1.get_interrupt_idt_num(0) as usize;
// IDT_TABLE[idx].type... | init | identifier_name |
Dfn.ts | /*
* Copyright (c) 2014 Jose Carlos Lama. www.typedom.org
*
* 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, modi... | * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
*... | random_line_split | |
Dfn.ts | /*
* Copyright (c) 2014 Jose Carlos Lama. www.typedom.org
*
* 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, modi... | extends Container<Dfn, HTMLElement>
{
public static DFN: string = 'dfn';
constructor();
constructor(id: string)
constructor(attributes: Object)
constructor(element: HTMLElement)
constructor(idOrAttributesOrElement?: any) {
super(idOrAttributesOrElement, Dfn.DFN);
}
} | Dfn | identifier_name |
strip.ts | /**
* Strips given string from source string.
*
* @ignore
* @param source is the source string to be cleaned.
* @param prefix is the string to delete.
* @returns cleaned string.
*/
export default function | (source: string, strings: string | string[]): string {
let result = source;
const stringArray = Array.isArray(strings) ? strings : [strings];
stringArray.forEach((string) => {
const prefixRx = new RegExp(`^${string}[_\\s-]+`);
const middleRx = new RegExp(`${string}[_\\s-]+`);
const suffixRx = new RegE... | strip | identifier_name |
strip.ts | /**
* Strips given string from source string.
*
* @ignore
* @param source is the source string to be cleaned.
* @param prefix is the string to delete.
* @returns cleaned string.
*/
export default function strip(source: string, strings: string | string[]): string | {
let result = source;
const stringArray = Array.isArray(strings) ? strings : [strings];
stringArray.forEach((string) => {
const prefixRx = new RegExp(`^${string}[_\\s-]+`);
const middleRx = new RegExp(`${string}[_\\s-]+`);
const suffixRx = new RegExp(`[_\\s-]*${string}$`);
if (result.match(prefi... | identifier_body | |
strip.ts | /**
* Strips given string from source string.
*
* @ignore
* @param source is the source string to be cleaned.
* @param prefix is the string to delete.
* @returns cleaned string.
*/
export default function strip(source: string, strings: string | string[]): string {
let result = source;
const stringArray = Arr... | if (result.match(prefixRx)) {
result = result.replace(prefixRx, "");
} else if (result.match(middleRx)) {
result = result.replace(middleRx, "");
} else {
result = result.replace(suffixRx, "");
}
});
return result;
} | const suffixRx = new RegExp(`[_\\s-]*${string}$`);
| random_line_split |
strip.ts | /**
* Strips given string from source string.
*
* @ignore
* @param source is the source string to be cleaned.
* @param prefix is the string to delete.
* @returns cleaned string.
*/
export default function strip(source: string, strings: string | string[]): string {
let result = source;
const stringArray = Arr... | else if (result.match(middleRx)) {
result = result.replace(middleRx, "");
} else {
result = result.replace(suffixRx, "");
}
});
return result;
}
| {
result = result.replace(prefixRx, "");
} | conditional_block |
eval_paths.rs | use std::time::{Instant, Duration};
use rand::Rng;
use crate::progress::Progress;
use crate::sim::TestPacket;
use crate::dijkstra::Dijkstra;
use crate::graph::*;
/*
* Test if all paths allow for routing.
* This test does not allow the state of the routing algorithm to change.
*/
pub struct EvalPaths {
show_progr... | }
pub fn stretch(&self) -> f32 {
(self.route_costs_sum as f32) / (self.route_costs_min_sum as f32)
}
pub fn arrived(&self) -> f32 {
100.0 * (self.packets_arrived as f32) / (self.packets_send as f32)
}
pub fn connectivity(&self) -> f32 {
100.0 * (self.nodes_connected as f32) / (self.nodes_connected + self... | random_line_split | |
eval_paths.rs | use std::time::{Instant, Duration};
use rand::Rng;
use crate::progress::Progress;
use crate::sim::TestPacket;
use crate::dijkstra::Dijkstra;
use crate::graph::*;
/*
* Test if all paths allow for routing.
* This test does not allow the state of the routing algorithm to change.
*/
pub struct EvalPaths {
show_progr... | (&mut self) {
self.dijkstra.clear();
self.clear_stats();
}
pub fn show_progress(&mut self, show_progress: bool) {
self.show_progress = true;
}
fn test_path(&mut self, graph: &Graph, mut route: impl FnMut(&TestPacket) -> Option<u32>,
source: ID, target: ID, costs_min: u32) {
// maximum stretch we record... | clear | identifier_name |
eval_paths.rs | use std::time::{Instant, Duration};
use rand::Rng;
use crate::progress::Progress;
use crate::sim::TestPacket;
use crate::dijkstra::Dijkstra;
use crate::graph::*;
/*
* Test if all paths allow for routing.
* This test does not allow the state of the routing algorithm to change.
*/
pub struct EvalPaths {
show_progr... | else {
// invalid next hop
self.packets_lost += 1;
break;
}
} else {
// no next hop
self.packets_lost += 1;
break;
}
}
self.route_costs_sum += path_costs;
self.route_costs_min_sum += costs_min;
}
pub fn run_samples(&mut self, graph: &Graph, mut route: impl FnMut(&TestPack... | {
path_costs += link.cost() as u32;
if next == packet.destination {
// packet arrived
self.packets_arrived += 1;
break;
} else {
// forward packet
packet.transmitter = packet.receiver;
packet.receiver = next;
}
} | conditional_block |
lexer.py | # -*- coding: utf-8 -*-
# EDIS - a simple cross-platform IDE for C
#
# This file is part of Edis
# Copyright 2014-2015 - Gabriel Acosta <acostadariogabriel at gmail>
# License: GPLv3 (see http://www.gnu.org/licenses/gpl.html)
from PyQt4.Qsci import QsciLexerCPP
from PyQt4.QtGui import QColor
from src import editor_sc... | super(Lexer, self).keywords(kset) | rn ('fprintf fscanf printf scanf sprintf sscanf vfprintf '
'vprintf vsprintf fclose fflush fopen freopen remove '
'rename setbuf tmpfile tmpnam fgetc fgets fputc fputs '
'getc getchar gets putc putchar puts ungetc fread fseek '
'fsetpos fte... | conditional_block |
lexer.py | # -*- coding: utf-8 -*-
# EDIS - a simple cross-platform IDE for C
#
# This file is part of Edis
# Copyright 2014-2015 - Gabriel Acosta <acostadariogabriel at gmail>
# License: GPLv3 (see http://www.gnu.org/licenses/gpl.html)
from PyQt4.Qsci import QsciLexerCPP
from PyQt4.QtGui import QColor
from src import editor_sc... |
def load_highlighter(self):
""" Método público: carga el resaltado de sintáxis """
scheme = editor_scheme.get_scheme(
settings.get_setting('editor/scheme'))
self.setDefaultPaper(QColor(scheme['BackgroundEditor']))
self.setPaper(self.defaultPaper(0))
self.setColo... | super(Lexer, self).__init__(*args, **kwargs)
# Configuración
self.setStylePreprocessor(True)
self.setFoldComments(True)
self.setFoldPreprocessor(True)
self.setFoldCompact(False)
self.load_highlighter()
| identifier_body |
lexer.py | # -*- coding: utf-8 -*-
# EDIS - a simple cross-platform IDE for C | # Copyright 2014-2015 - Gabriel Acosta <acostadariogabriel at gmail>
# License: GPLv3 (see http://www.gnu.org/licenses/gpl.html)
from PyQt4.Qsci import QsciLexerCPP
from PyQt4.QtGui import QColor
from src import editor_scheme
from src.core import settings
class Lexer(QsciLexerCPP):
""" Lexer class """
def... | #
# This file is part of Edis | random_line_split |
lexer.py | # -*- coding: utf-8 -*-
# EDIS - a simple cross-platform IDE for C
#
# This file is part of Edis
# Copyright 2014-2015 - Gabriel Acosta <acostadariogabriel at gmail>
# License: GPLv3 (see http://www.gnu.org/licenses/gpl.html)
from PyQt4.Qsci import QsciLexerCPP
from PyQt4.QtGui import QColor
from src import editor_sc... | f, kset):
super(Lexer, self).keywords(kset)
if kset == 1:
# Palabras reservadas
return ('auto break case const continue default do else enum '
'extern for goto if register return short sizeof static '
'struct switch typedef union unsigned v... | ords(sel | identifier_name |
decorators.ts | export type SpotifyQueryDecorated = any;
// Allow to decoration class methods using the following pattern :
// const SpotifyQuery = SpotifyDecorators(client);
// class A {
// @SpotifyQuery(`
// query {
// me {
// tracks { name }
// }
// }
// `)... |
}
} | {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
var originalMethod = descriptor.value;
descriptor.value = function (variables?: any): Promise<any> {
return new Promise((resolve, reject) => {
client.query(query, nul... | identifier_body |
decorators.ts | export type SpotifyQueryDecorated = any;
// Allow to decoration class methods using the following pattern :
// const SpotifyQuery = SpotifyDecorators(client);
// class A {
// @SpotifyQuery(`
// query {
// me {
// tracks { name }
// }
// }
// `)... |
}, reject).catch(reject);
});
};
return descriptor;
};
}
}
} | {
reject(executionResult.errors);
} | conditional_block |
decorators.ts | export type SpotifyQueryDecorated = any;
// Allow to decoration class methods using the following pattern :
// const SpotifyQuery = SpotifyDecorators(client);
// class A {
// @SpotifyQuery(`
// query {
// me {
// tracks { name }
// }
// }
// `)... | (query: string) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
var originalMethod = descriptor.value;
descriptor.value = function (variables?: any): Promise<any> {
return new Promise((resolve, reject) => {
client.... | SpotifyQuery | identifier_name |
decorators.ts | export type SpotifyQueryDecorated = any;
// Allow to decoration class methods using the following pattern :
// const SpotifyQuery = SpotifyDecorators(client);
// class A {
// @SpotifyQuery(`
// query {
// me {
// tracks { name }
// }
// }
// `)... | // }
export function SpotifyDecorators (client): any {
return {
SpotifyQuery(query: string) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
var originalMethod = descriptor.value;
descriptor.value = function (variables?: any): Promise<a... | random_line_split | |
endian.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// 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, inc... | (&self) -> f32 {
unsafe { mem::transmute(mem::transmute::<f32, u32>(*self).to_le()) }
}
fn set(&mut self, value : f32) {
*self = unsafe { mem::transmute(mem::transmute::<f32, u32>(value).to_le()) };
}
}
impl Endian for f64 {
fn get(&self) -> f64 {
unsafe { mem::transmute(mem::tr... | get | identifier_name |
endian.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// 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, inc... | } | random_line_split | |
converttojson.py | #import results # Not using results?
import loc
import json
#asinfo = results.asinfo
locinfo = loc.locinfo
#fields = asinfo["fields"]
#del asinfo["fields"]
#print fields
# for asn, dat in asinfo.items():
# if int(asn) in locinfo:
# dat.extend(locinfo[int(asn)])
# else:
# dat.extend([0, 0])
#
# for asn, dat in... | f = open("asinfo.json", "w")
json.dump(locinfo, f)
f.close() | # val[0] = udata.encode("ascii", "ignore")
# val[0] = unicode(val[0])
# print val | random_line_split |
1234_1243_2134_2431_4213.py | from __future__ import print_function
from permuta import *
import permstruct
import permstruct.dag
from permstruct import * | from permstruct.dag import taylor_dag
import sys
# -- Example from Kuszmaul paper -- #
# STATUS ================================================ >
task = '1234_1243_2134_2431_4213'
patts = [ Permutation([ int(c) for c in p ]) for p in task.split('_') ]
# patts = [Permutation([5,2,3,4,1]), Permutation([5,3,2,4,1]), ... | random_line_split | |
total_dos_plotter.py | #!/usr/bin/env python |
__author__ = "Yuji Ikeda"
class TotalDOSPlotter(DOSPlotter):
def load_data(self, data_file='total_dos.dat'):
super(TotalDOSPlotter, self).load_data(data_file)
return self
def run(self):
variables = self._variables
primitive = self.create_primitive()
natoms = primiti... | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from .dos_plotter import DOSPlotter
| random_line_split |
total_dos_plotter.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from .dos_plotter import DOSPlotter
__author__ = "Yuji Ikeda"
class TotalDOSPlotter(DOSPlotter):
def | (self, data_file='total_dos.dat'):
super(TotalDOSPlotter, self).load_data(data_file)
return self
def run(self):
variables = self._variables
primitive = self.create_primitive()
natoms = primitive.get_number_of_atoms()
symbols = primitive.get_chemical_symbols()
... | load_data | identifier_name |
total_dos_plotter.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from .dos_plotter import DOSPlotter
__author__ = "Yuji Ikeda"
class TotalDOSPlotter(DOSPlotter):
def load_data(self, data_file='total_dos.dat'):
supe... | variables = self._variables
primitive = self.create_primitive()
natoms = primitive.get_number_of_atoms()
symbols = primitive.get_chemical_symbols()
print("natoms:", natoms)
print("symbols:", symbols)
self.set_figure_name_prefix("total_dos")
self.set_plot_symbol(... | identifier_body | |
computed-pane-properties_test.ts | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {assert} from 'chai';
import {getBrowserAndPages, goToResource, waitForFunction} from '../../shared/helper.js';
import {describe, it} from '../../... | assert.exists(backgroundProperty, 'H2 element should have a background-color computed property');
assert.deepEqual(backgroundProperty, {
name: 'background-color',
value: 'rgb(255, 215, 0)',
});
});
it('can display inherited CSS properties of the selected element', async () => {
const {f... | assert.strictEqual(h2Properties.length, 11, 'There should be 11 computed properties on the H2 element');
const backgroundProperty = h2Properties.find(property => property && property.name === 'background-color'); | random_line_split |
console.rs | // Copyright (c) 2019 Jason White
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, d... | (mut self) -> Result<(), io::Error> {
for task in self.tasks.iter_mut() {
task.pb
.finish_with_message(&style("Done").dim().to_string());
}
self.tick_thread.join().unwrap();
self.pb_thread.join().unwrap()?;
Ok(())
}
pub fn end_build(
... | finish | identifier_name |
console.rs | // Copyright (c) 2019 Jason White
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, d... | start_time: timestamp,
pb_thread,
tick_thread,
name,
}
}
pub fn finish(mut self) -> Result<(), io::Error> {
for task in self.tasks.iter_mut() {
task.pb
.finish_with_message(&style("Done").dim().to_string());
}
... | });
Inner {
tasks, | random_line_split |
console.rs | // Copyright (c) 2019 Jason White
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, d... |
pub fn begin_task(
&mut self,
timestamp: Timestamp,
event: BeginTaskEvent,
) -> Result<(), io::Error> {
let mut task = &mut self.tasks[event.id];
task.start = timestamp;
let name = event.task.to_string();
task.pb.reset_elapsed();
task.pb.set_st... | {
let duration = (timestamp - self.start_time).to_std().unwrap();
let duration = format_duration(duration);
let msg = match event.result {
Ok(()) => format!(
"{} {} in {}",
style("Finished").bold().green(),
style(&self.name).yellow(),
... | identifier_body |
console.rs | // Copyright (c) 2019 Jason White
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, d... | }
Event::EndTask(event) => {
if let Some(inner) = &mut self.inner {
inner.end_task(timestamp, event)?;
}
}
Event::Delete(event) => {
if let Some(inner) = &mut self.inner {
inner.delete(time... | inner.tasks[event.id].buf.extend(event.chunk);
}
| conditional_block |
EasyController.py | # Copyright 2009 by Tiago Antao <tiagoantao@gmail.com>. 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.
"""
This module allows to control GenePop through an easier interface.
... |
def get_allele_frequency(self, pop_pos, locus_name):
geno_freqs = self._controller.calc_allele_genotype_freqs(self._fname)
pop_iter, loc_iter = geno_freqs
for locus_info in loc_iter:
if locus_info[0] == locus_name:
alleles = locus_info[1]
pop_na... | if locus_info[0] == locus_name:
return locus_info[1] | conditional_block |
EasyController.py | # Copyright 2009 by Tiago Antao <tiagoantao@gmail.com>. 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.
"""
This module allows to control GenePop through an easier interface.
... | (self, pop_pos, test_type = "probability"):
if test_type=="deficiency":
hw_res = self._controller.test_pop_hz_deficiency(self._fname)
elif test_type=="excess":
hw_res = self._controller.test_pop_hz_excess(self._fname)
else:
loci_res, hw_res, fisher_full = self... | test_hw_pop | identifier_name |
EasyController.py | # Copyright 2009 by Tiago Antao <tiagoantao@gmail.com>. 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. | This module allows to control GenePop through an easier interface.
This interface is less efficient than the standard GenePopControler
"""
from Controller import GenePopController
from Bio.PopGen import GenePop
class EasyController:
def __init__(self, fname, genepop_dir = None):
"""Initializes the cont... |
""" | random_line_split |
EasyController.py | # Copyright 2009 by Tiago Antao <tiagoantao@gmail.com>. 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.
"""
This module allows to control GenePop through an easier interface.
... |
def estimate_nm(self):
""" Estimate Nm. Just a simple bridge.
"""
return self._controller.estimate_nm(self._fname)
def get_heterozygosity_info(self, pop_pos, locus_name):
"""Returns the heterozygosity info for a certain locus on a population.
Returns (Expected homo... | all_ld = self._controller.test_ld(self._fname, dememorization, batches, iterations)[1]
for ld_case in all_ld:
(l1, l2), result = ld_case
if (l1==locus1 and l2==locus2) or (l1==locus2 and l2==locus1):
return result | identifier_body |
align_of_val.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::mem::align_of_val;
use core::default::Default;
// pub fn align_of_val<T: ?Sized>(val: &T) -> usize {
// unsafe { intrinsics::min_align_of_val(val) }
// }
macro_rules! align_of_val_test {
($T:ty, $size:expr) => ({
... |
}
| {
align_of_val_test!( (u8), 1 );
align_of_val_test!( (u8, u16), 2 );
align_of_val_test!( (u8, u16, u32), 4 );
align_of_val_test!( (u8, u16, u32, u64), 8 );
} | identifier_body |
align_of_val.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::mem::align_of_val;
use core::default::Default;
// pub fn align_of_val<T: ?Sized>(val: &T) -> usize {
// unsafe { intrinsics::min_align_of_val(val) }
// }
macro_rules! align_of_val_test {
($T:ty, $size:expr) => ({
... | () {
align_of_val_test!( (u8), 1 );
align_of_val_test!( (u8, u16), 2 );
align_of_val_test!( (u8, u16, u32), 4 );
align_of_val_test!( (u8, u16, u32, u64), 8 );
}
}
| align_of_val_test2 | identifier_name |
align_of_val.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::mem::align_of_val;
use core::default::Default;
// pub fn align_of_val<T: ?Sized>(val: &T) -> usize {
// unsafe { intrinsics::min_align_of_val(val) }
// }
macro_rules! align_of_val_test {
($T:ty, $size:expr) => ({
... | align_of_val_test!( (u8, u16, u32, u64), 8 );
}
} | random_line_split | |
package.ts | import { getFilePath } from './utils';
import { join } from 'path';
import {
ensureDirectory,
readJsonFile,
writeTarball,
writeJsonFile,
exists
} from './fs';
export interface IPackage {
_id: string;
_rev: string;
name: string;
description: string;
'dist-tags': { [tag: string]: string };
versions... | this.tarballRoot = getFilePath(`tarballs/${this.data.name}`);
}
if (name) {
this.packageRoot = getFilePath(`packages/${name}`);
this.tarballRoot = getFilePath(`tarballs/${name}`);
}
this.pkgJsonPath = join(this.packageRoot, 'package.json');
}
init(): Promise<null> {
return t... | if (data) {
this.data = data;
this.packageRoot = getFilePath(`packages/${this.data.name}`); | random_line_split |
package.ts | import { getFilePath } from './utils';
import { join } from 'path';
import {
ensureDirectory,
readJsonFile,
writeTarball,
writeJsonFile,
exists
} from './fs';
export interface IPackage {
_id: string;
_rev: string;
name: string;
description: string;
'dist-tags': { [tag: string]: string };
versions... |
this.pkgJsonPath = join(this.packageRoot, 'package.json');
}
init(): Promise<null> {
return this.ensureRootFolders()
.then(() => this.initDataFromPkgJson());
}
private prepareData(data: IPackage): IPackage {
if (!data.time) {
data.time = { modified: new Date().toISOString(), created:... | {
this.packageRoot = getFilePath(`packages/${name}`);
this.tarballRoot = getFilePath(`tarballs/${name}`);
} | conditional_block |
package.ts | import { getFilePath } from './utils';
import { join } from 'path';
import {
ensureDirectory,
readJsonFile,
writeTarball,
writeJsonFile,
exists
} from './fs';
export interface IPackage {
_id: string;
_rev: string;
name: string;
description: string;
'dist-tags': { [tag: string]: string };
versions... | (data?: IPackage, name?: string) {
if (data) {
this.data = data;
this.packageRoot = getFilePath(`packages/${this.data.name}`);
this.tarballRoot = getFilePath(`tarballs/${this.data.name}`);
}
if (name) {
this.packageRoot = getFilePath(`packages/${name}`);
this.tarballRoot = get... | constructor | identifier_name |
package.ts | import { getFilePath } from './utils';
import { join } from 'path';
import {
ensureDirectory,
readJsonFile,
writeTarball,
writeJsonFile,
exists
} from './fs';
export interface IPackage {
_id: string;
_rev: string;
name: string;
description: string;
'dist-tags': { [tag: string]: string };
versions... |
initDataFromPkgJson(): Promise<null> {
return readJsonFile(this.pkgJsonPath)
.then((jsonData: IPackage) => this.data = jsonData)
.catch(err => console.error(err));
}
initPkgJsonFromData(): Promise<null> {
let data = this.data;
data._attachments = {};
return this.ensureRootFolders()... | {
if (!this.data) {
return this.initDataFromPkgJson()
.then(() => this.data);
} else {
return Promise.resolve(this.data);
}
} | identifier_body |
mod.rs | //! Variable header in MQTT
use std::io;
use std::string::FromUtf8Error;
use crate::topic_name::{TopicNameDecodeError, TopicNameError};
pub use self::connect_ack_flags::ConnackFlags;
pub use self::connect_flags::ConnectFlags;
pub use self::connect_ret_code::ConnectReturnCode; | pub use self::packet_identifier::PacketIdentifier;
pub use self::protocol_level::ProtocolLevel;
pub use self::protocol_name::ProtocolName;
pub use self::topic_name::TopicNameHeader;
mod connect_ack_flags;
mod connect_flags;
mod connect_ret_code;
mod keep_alive;
mod packet_identifier;
pub mod protocol_level;
mod protoc... | pub use self::keep_alive::KeepAlive; | random_line_split |
mod.rs | //! Variable header in MQTT
use std::io;
use std::string::FromUtf8Error;
use crate::topic_name::{TopicNameDecodeError, TopicNameError};
pub use self::connect_ack_flags::ConnackFlags;
pub use self::connect_flags::ConnectFlags;
pub use self::connect_ret_code::ConnectReturnCode;
pub use self::keep_alive::KeepAlive;
pub... | (err: TopicNameDecodeError) -> VariableHeaderError {
match err {
TopicNameDecodeError::IoError(e) => Self::IoError(e),
TopicNameDecodeError::InvalidTopicName(e) => Self::TopicNameError(e),
}
}
}
| from | identifier_name |
mod.rs | //! Variable header in MQTT
use std::io;
use std::string::FromUtf8Error;
use crate::topic_name::{TopicNameDecodeError, TopicNameError};
pub use self::connect_ack_flags::ConnackFlags;
pub use self::connect_flags::ConnectFlags;
pub use self::connect_ret_code::ConnectReturnCode;
pub use self::keep_alive::KeepAlive;
pub... |
}
| {
match err {
TopicNameDecodeError::IoError(e) => Self::IoError(e),
TopicNameDecodeError::InvalidTopicName(e) => Self::TopicNameError(e),
}
} | identifier_body |
shootout-chameneos-redux.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted... | // track some statistics
creatures_met += 1;
if other_creature.name == name {
evil_clones_met += 1;
}
}
None => break
}
}
// log creatures met and evil clones of self
let report = format!("{}{:... | // log and change, or quit
match rendezvous.next() {
Some(other_creature) => {
color = transform(color, other_creature.color);
| random_line_split |
shootout-chameneos-redux.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted... |
fn show_digit(nn: uint) -> &'static str {
match nn {
0 => {" zero"}
1 => {" one"}
2 => {" two"}
3 => {" three"}
4 => {" four"}
5 => {" five"}
6 => {" six"}
7 => {" seven"}
8 => {" eight"}
9 => {" nine"}
_ => {panic!("expected ... | {
let mut out = String::new();
for col in &set {
out.push(' ');
out.push_str(&format!("{:?}", col));
}
out
} | identifier_body |
shootout-chameneos-redux.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted... |
8 => {" eight"}
9 => {" nine"}
_ => {panic!("expected digits from 0 to 9...")}
}
}
struct Number(uint);
impl fmt::Debug for Number {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut out = vec![];
let Number(mut num) = *self;
if num == 0 { out.push(... | {" seven"} | conditional_block |
shootout-chameneos-redux.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted... | (aa: Color, bb: Color) -> Color {
match (aa, bb) {
(Red, Red ) => { Red }
(Red, Yellow) => { Blue }
(Red, Blue ) => { Yellow }
(Yellow, Red ) => { Blue }
(Yellow, Yellow) => { Yellow }
(Yellow, Blue ) => { Red }
(Blue, Red ) => { Y... | transform | identifier_name |
paragraph.tsx | import { Editor, EditorState, RichUtils } from "draft-js"
import { debounce } from "lodash"
import React, { Component } from "react"
import ReactDOM from "react-dom"
import styled from "styled-components"
import { TextInputUrl } from "../components/text_input_url"
import { TextNav } from "../components/text_nav"
import... | (props: Props) {
super(props)
this.allowedStyles = styleMapFromNodes(
props.allowedStyles || allowedStylesParagraph
)
this.state = {
editorPosition: null,
editorState: this.setEditorState(),
html: props.html || "",
showNav: false,
showUrlInput: false,
urlValue:... | constructor | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.