file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
reftypes.py | # ------------------------------------------------------------------------------
# Copyright (c) 2010-2013, EVEthing team
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# Redistributions of... | if reftype is None:
new.append(RefType(
id=refTypeID,
name=row.attrib['refTypeName'],
))
# RefType exists and name has changed, update it
elif reftype.name != row.attrib['refTypeName']:
reftype.n... | if self.init(taskstate_id, apikey_id) is False:
return
# Fetch the API data
if self.fetch_api(url, {}, use_auth=False) is False or self.root is None:
return
# Build a refTypeID:row dictionary
bulk_data = {}
for row in self.root.findall('result/rowset/row... | identifier_body |
reftypes.py | # ------------------------------------------------------------------------------
# Copyright (c) 2010-2013, EVEthing team
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# Redistributions of... | (self, url, taskstate_id, apikey_id, zero):
if self.init(taskstate_id, apikey_id) is False:
return
# Fetch the API data
if self.fetch_api(url, {}, use_auth=False) is False or self.root is None:
return
# Build a refTypeID:row dictionary
bulk_data = {}
... | run | identifier_name |
reftypes.py | # ------------------------------------------------------------------------------
# Copyright (c) 2010-2013, EVEthing team
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# Redistributions of... |
# RefType exists and name has changed, update it
elif reftype.name != row.attrib['refTypeName']:
reftype.name = row.attrib['refTypeName']
reftype.save()
# Create any new stations
if new:
RefType.objects.bulk_create(new)
retu... | new.append(RefType(
id=refTypeID,
name=row.attrib['refTypeName'],
)) | conditional_block |
tests_v1kpdb.rs | use chrono::{Timelike, Local, TimeZone, Datelike};
use kpdb::v1kpdb::V1Kpdb;
use kpdb::v1error::V1KpdbError;
#[test]
fn test_new() {
// No keyfile and password should give error as result
let mut result = V1Kpdb::new("test/test_password.kdb".to_string(), None, None);
match result {
Ok(_) => asser... |
let parent = new_group.parent.as_mut().unwrap();
assert_eq!(parent.borrow().id, 0);
assert_eq!(db.header.num_groups, num_groups_before + 1);
}
#[test]
fn test_create_group_w_everything() {
let mut result = V1Kpdb::new("test/test_parsing.kdb".to_string(),
Some("test".t... | (23, 59, 59));
assert_eq!(new_group.image, 0); | random_line_split |
tests_v1kpdb.rs | use chrono::{Timelike, Local, TimeZone, Datelike};
use kpdb::v1kpdb::V1Kpdb;
use kpdb::v1error::V1KpdbError;
#[test]
fn test_new() {
// No keyfile and password should give error as result
let mut result = V1Kpdb::new("test/test_password.kdb".to_string(), None, None);
match result {
Ok(_) => asser... | () {
let mut result = V1Kpdb::new("test/test_parsing.kdb".to_string(),
Some("test".to_string()), None);
match result {
Ok(ref mut e) => assert_eq!(e.load().is_ok(), true),
Err(_) => assert!(false),
};
let mut db = result.unwrap();
let num_groups_bef... | test_create_group_w_everything | identifier_name |
tests_v1kpdb.rs | use chrono::{Timelike, Local, TimeZone, Datelike};
use kpdb::v1kpdb::V1Kpdb;
use kpdb::v1error::V1KpdbError;
#[test]
fn test_new() | match db.load() {
Ok(_) => assert!(false),
Err(e) => assert_eq!(e, V1KpdbError::HashErr),
};
}
#[test]
fn test_create_group_w_title_only() {
let mut result = V1Kpdb::new("test/test_password.kdb".to_string(),
Some("test".to_string()), None);
match resul... | {
// No keyfile and password should give error as result
let mut result = V1Kpdb::new("test/test_password.kdb".to_string(), None, None);
match result {
Ok(_) => assert!(false),
Err(e) => assert_eq!(e, V1KpdbError::PassErr),
};
// Test load at all and parameters
result = V1Kpdb:... | identifier_body |
index.d.ts | // Type definitions for fluxible-router 1.5
// Project: https://github.com/yahoo/fluxible#readme
// Definitions by: xbim <https://github.com/xbim>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
/// <reference types="node" />
import * as React from 'react';
import { Fluxibl... |
rehydrate(state: any): void;
static withStaticRoutes(routes: object): typeof RouteStore;
}
export function handleHistory(Component: typeof React.Component, opts?: object): typeof React.Component;
export function navigateAction(context: FluxibleContext, params: object): undefined;
export class NavLinkProps ... | dehydrate(context?: FluxibleContext): any; | random_line_split |
index.d.ts | // Type definitions for fluxible-router 1.5
// Project: https://github.com/yahoo/fluxible#readme
// Definitions by: xbim <https://github.com/xbim>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
/// <reference types="node" />
import * as React from 'react';
import { Fluxibl... | {
href?: string;
routeName?: string;
activeStyle?: object;
preserveScrollPosition?: boolean;
className?: string;
type?: string;
}
| NavLinkProps | identifier_name |
subst.rs |
pub fn erased(t: VecPerParamSpace<Ty<'tcx>>) -> Substs<'tcx>
{
Substs { types: t, regions: ErasedRegions }
}
pub fn empty() -> Substs<'tcx> {
Substs {
types: VecPerParamSpace::empty(),
regions: NonerasedRegions(VecPerParamSpace::empty()),
}
}
p... | {
Substs::new(VecPerParamSpace::new(t, vec!(s), Vec::new()),
VecPerParamSpace::new(r, Vec::new(), Vec::new()))
} | identifier_body | |
subst.rs | pub fn trans_empty() -> Substs<'tcx> {
Substs {
types: VecPerParamSpace::empty(),
regions: ErasedRegions
}
}
pub fn is_noop(&self) -> bool {
let regions_is_noop = match self.regions {
ErasedRegions => false, // may be used to canonicalize
... | }
}
| random_line_split | |
subst.rs | Some(self.content.remove(limit - 1))
}
}
}
pub fn truncate(&mut self, space: ParamSpace, len: uint) {
// FIXME (#15435): slow; O(n^2); could enhance vec to make it O(n).
while self.len(space) > len {
self.pop(space);
}
}
pub fn replace(&mut self... | enter_region_binder | identifier_name | |
wsgi.py | resolvers import set_script_prefix
from django.utils import datastructures
from django.utils.encoding import force_str, force_text
from django.utils.functional import cached_property
from django.utils import six
# For backwards compatibility -- lots of code uses this in the wild!
from django.http.response import REASO... |
return self._request
@cached_property
def GET(self):
# The WSGI spec says 'QUERY_STRING' may be absent.
raw_query_string = get_bytes_from_wsgi(self.environ, 'QUERY_STRING', '')
return http.QueryDict(raw_query_string, encoding=self._encoding)
def _get_post(self):
if... | self._request = datastructures.MergeDict(self.POST, self.GET) | conditional_block |
wsgi.py | resolvers import set_script_prefix
from django.utils import datastructures
from django.utils.encoding import force_str, force_text
from django.utils.functional import cached_property
from django.utils import six
# For backwards compatibility -- lots of code uses this in the wild!
from django.http.response import REASO... | Returns the equivalent of the HTTP request's SCRIPT_NAME environment
variable. If Apache mod_rewrite has been used, returns what would have been
the script name prior to any rewriting (so it's the script name as seen
from the client's perspective), unless the FORCE_SCRIPT_NAME setting is
set (to any... | return path_info.decode(UTF_8)
def get_script_name(environ):
""" | random_line_split |
wsgi.py | resolvers import set_script_prefix
from django.utils import datastructures
from django.utils.encoding import force_str, force_text
from django.utils.functional import cached_property
from django.utils import six
# For backwards compatibility -- lots of code uses this in the wild!
from django.http.response import REASO... | (self):
# The WSGI spec says 'QUERY_STRING' may be absent.
raw_query_string = get_bytes_from_wsgi(self.environ, 'QUERY_STRING', '')
return http.QueryDict(raw_query_string, encoding=self._encoding)
def _get_post(self):
if not hasattr(self, '_post'):
self._load_post_and_fi... | GET | identifier_name |
wsgi.py | resolvers import set_script_prefix
from django.utils import datastructures
from django.utils.encoding import force_str, force_text
from django.utils.functional import cached_property
from django.utils import six
# For backwards compatibility -- lots of code uses this in the wild!
from django.http.response import REASO... |
def get_script_name(environ):
"""
Returns the equivalent of the HTTP request's SCRIPT_NAME environment
variable. If Apache mod_rewrite has been used, returns what would have been
the script name prior to any rewriting (so it's the script name as seen
from the client's perspective), unless the FOR... | """
Returns the HTTP request's PATH_INFO as a unicode string.
"""
path_info = get_bytes_from_wsgi(environ, 'PATH_INFO', '/')
# It'd be better to implement URI-to-IRI decoding, see #19508.
return path_info.decode(UTF_8) | identifier_body |
dependencies.py | import easydev
from cno import CNOGraph
def | (package='cno', show=False, filename=None):
main = easydev.dependencies.get_dependencies(package)
# first, we fetch all dependencies
c = CNOGraph()
deps = easydev.dependencies.get_dependencies(package)
package_version = [dep.version for dep in deps if dep.project_name == package][0]
for dep i... | plot_dependencies | identifier_name |
dependencies.py | import easydev
from cno import CNOGraph
def plot_dependencies(package='cno', show=False, filename=None):
| deps = [dep for dep in deps if
len(easydev.dependencies.get_dependencies(dep.project_name))>1]
for dep in deps:
for this in easydev.dependencies.get_dependencies(dep.project_name):
if this.project_name != dep.project_name:
newdeps.append(th... | main = easydev.dependencies.get_dependencies(package)
# first, we fetch all dependencies
c = CNOGraph()
deps = easydev.dependencies.get_dependencies(package)
package_version = [dep.version for dep in deps if dep.project_name == package][0]
for dep in deps:
version = dep.version
nam... | identifier_body |
dependencies.py | import easydev
from cno import CNOGraph
def plot_dependencies(package='cno', show=False, filename=None):
main = easydev.dependencies.get_dependencies(package)
# first, we fetch all dependencies
c = CNOGraph()
deps = easydev.dependencies.get_dependencies(package)
package_version = [dep.version fo... |
c2.plot(filename=filename, show=show)
| c2.add_edge(clique[i], clique[i+1]) | conditional_block |
dependencies.py | import easydev
from cno import CNOGraph
def plot_dependencies(package='cno', show=False, filename=None):
main = easydev.dependencies.get_dependencies(package)
# first, we fetch all dependencies
c = CNOGraph()
deps = easydev.dependencies.get_dependencies(package)
package_version = [dep.version fo... | #actually, dependencies themeselves depends on other packages
# that are all present in deps variable but we are missing
# the overall DAG so let us loop over the dependencies
deps = [dep for dep in deps if
len(easydev.dependencies.get_dependencies(dep.project_name))>1]
newdeps = []
... | for dep in deps:
version = dep.version
name= dep.project_name
c.add_reaction(package+'-'+package_version + "="+name + "-" + version)
| random_line_split |
signup-form.component.ts | import { Component, OnInit, NgZone } from '@angular/core'
import { Router } from '@angular/router'
import { FormBuilder, FormGroup, Validators } from '@angular/forms'
import { name, forceMail, passwd } from '/lib/validate'
import { RegisterUser } from '/both/models/user.model'
import { Accounts } from 'meteor/accounts-... |
ngOnInit() {
this.printSignup()
}
private printSignup() {
this.signupForm = this.formBuilder.group({
email: ['', forceMail],
confirmEmail : ['', forceMail],
password: ['', passwd],
confirmPassword : ['', passwd],
username: [... | }
| identifier_body |
signup-form.component.ts | import { Component, OnInit, NgZone } from '@angular/core'
import { Router } from '@angular/router'
import { FormBuilder, FormGroup, Validators } from '@angular/forms'
import { name, forceMail, passwd } from '/lib/validate'
import { RegisterUser } from '/both/models/user.model'
import { Accounts } from 'meteor/accounts-... | }
private checkPassword() {
if (this.signupForm.value.password == this.signupForm.value.password)
return true
else {
alert('Passwords are not sames')
return false
}
}
private checkConfirm() {
return this.checkPassword() && this.checkE... |
alert('Emails are not sames')
return false
}
| conditional_block |
signup-form.component.ts | import { Component, OnInit, NgZone } from '@angular/core'
import { Router } from '@angular/router'
import { FormBuilder, FormGroup, Validators } from '@angular/forms'
import { name, forceMail, passwd } from '/lib/validate'
import { RegisterUser } from '/both/models/user.model'
import { Accounts } from 'meteor/accounts-... | res : boolean) {
this.captchaRes = res
}
}
| andleResult( | identifier_name |
signup-form.component.ts | import { Component, OnInit, NgZone } from '@angular/core'
import { Router } from '@angular/router'
import { FormBuilder, FormGroup, Validators } from '@angular/forms'
import { name, forceMail, passwd } from '/lib/validate'
import { RegisterUser } from '/both/models/user.model'
import { Accounts } from 'meteor/accounts-... | handleResult(res : boolean) {
this.captchaRes = res
}
} | random_line_split | |
CrowdKernel.py | """
CrowdKernel algorithm of the Online Learning Library for Next.Discovery
author: Lalit Jain, kevin.g.jamieson@gmail.com
last updated: 4/22/2015
"""
import numpy
import numpy.random
from apps.PoolBasedTripletMDS.algs.CrowdKernel import utilsCrowdKernel
import time
class CrowdKernel:
def initExp(self,butler,n,d,f... | butler.algorithms.set(key='X',value=X.tolist())
butler.algorithms.set(key='tau',value=tau.tolist()) | if emp_loss_old < emp_loss_new:
X = X_old
tau = utilsCrowdKernel.getCrowdKernelTauDistribution(X,S,mu)
| random_line_split |
CrowdKernel.py | """
CrowdKernel algorithm of the Online Learning Library for Next.Discovery
author: Lalit Jain, kevin.g.jamieson@gmail.com
last updated: 4/22/2015
"""
import numpy
import numpy.random
from apps.PoolBasedTripletMDS.algs.CrowdKernel import utilsCrowdKernel
import time
class CrowdKernel:
def initExp(self,butler,n,d,f... | butler.algorithms.set(key='tau',value=tau.tolist())
def full_embedding_update(self,butler,args):
verbose = False
n = butler.algorithms.get(key='n')
d = butler.algorithms.get(key='d')
S = butler.algorithms.get(key='S')
X_old = numpy.array(butler.algorithms.get(key='X'))
# set maxim... | verbose = False
S = butler.algorithms.get(key='S')
X = numpy.array(butler.algorithms.get(key='X'))
# set maximum time allowed to update embedding
t_max = 1.0
epsilon = 0.00001 # a relative convergence criterion, see computeEmbeddingWithGD documentation
mu = .05
t_start = time.time()
... | identifier_body |
CrowdKernel.py | """
CrowdKernel algorithm of the Online Learning Library for Next.Discovery
author: Lalit Jain, kevin.g.jamieson@gmail.com
last updated: 4/22/2015
"""
import numpy
import numpy.random
from apps.PoolBasedTripletMDS.algs.CrowdKernel import utilsCrowdKernel
import time
class CrowdKernel:
def initExp(self,butler,n,d,f... | (self,butler,args):
verbose = False
n = butler.algorithms.get(key='n')
d = butler.algorithms.get(key='d')
S = butler.algorithms.get(key='S')
X_old = numpy.array(butler.algorithms.get(key='X'))
# set maximum time allowed to update embedding
t_max = 5.0
epsilon = 0.00001 # a relative con... | full_embedding_update | identifier_name |
CrowdKernel.py | """
CrowdKernel algorithm of the Online Learning Library for Next.Discovery
author: Lalit Jain, kevin.g.jamieson@gmail.com
last updated: 4/22/2015
"""
import numpy
import numpy.random
from apps.PoolBasedTripletMDS.algs.CrowdKernel import utilsCrowdKernel
import time
class CrowdKernel:
def initExp(self,butler,n,d,f... |
tauc = tauc/sum(tauc)
entropy = -p*utilsCrowdKernel.getEntropy(taub)-(1-p)*utilsCrowdKernel.getEntropy(tauc)
if entropy > best_entropy:
best_q = q
best_entropy = entropy
index_center = best_q[2]
index_left = best_q[0]
index_right = best_q[1]
return [index_center, in... | tauc[i] = tauc[i] * utilsCrowdKernel.getCrowdKernelTripletProbability(X[c],X[b],X[i]) | conditional_block |
MenuOptionWidget.js | /**
* MenuOptionWidget is an option widget that looks like a menu item. The class is used with
* OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
* the [OOjs UI documentation on MediaWiki] [1] for more information.
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and... |
// Parent constructor
OO.ui.MenuOptionWidget.super.call( this, config );
// Initialization
this.$element
.attr( 'role', 'menuitem' )
.addClass( 'oo-ui-menuOptionWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
/* Static Properties */
OO.ui.MenuOptionWidget.... | // Configuration initialization
config = $.extend( { icon: 'check' }, config ); | random_line_split |
home.service.ts | /**
* Created by chengfei on 16/9/19.
*/
import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class HomeService {
private URL = 'http://wx.51e.com.cn/app/index.php?i=18&c=entry&do=VoteSubmit&m=sxs_vote';
private heade... | let submitData = {
"uid":'1111222',
"openid":'222225',
"voteid":'6',
"optioniddata":['176'],
};
return this.http
.post(this.URL, JSON.stringify(submitData), {headers: this.headers})
.toPromise()
.then(res => res.... | random_line_split | |
home.service.ts | /**
* Created by chengfei on 16/9/19.
*/
import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class HomeService {
private URL = 'http://wx.51e.com.cn/app/index.php?i=18&c=entry&do=VoteSubmit&m=sxs_vote';
private heade... |
private handleError(error: any): Promise<any> {
console.error('请求失败', error);
return Promise.reject(error.message || error);
}
} | {
let submitData = {
"uid":'1111222',
"openid":'222225',
"voteid":'6',
"optioniddata":['176'],
};
return this.http
.post(this.URL, JSON.stringify(submitData), {headers: this.headers})
.toPromise()
.then(res => re... | identifier_body |
home.service.ts | /**
* Created by chengfei on 16/9/19.
*/
import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class HomeService {
private URL = 'http://wx.51e.com.cn/app/index.php?i=18&c=entry&do=VoteSubmit&m=sxs_vote';
private heade... | (private http:Http) {
}
getHomeData():Promise<any> {
let submitData = {
"uid":'1111222',
"openid":'222225',
"voteid":'6',
"optioniddata":['176'],
};
return this.http
.post(this.URL, JSON.stringify(submitData), {headers: this.he... | constructor | identifier_name |
views.py | # -*- coding: utf-8 -*-
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
try:
from django.http import StreamingHttpResponse as HttpResponse
except ImportError:
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from sse import S... | (self):
"""
This is a source of stream.
Must use ``yield`` statement to flush
content from sse object to the client.
Example:
def iterator(self):
counter = 0
while True:
self.sse.add_message('foo', 'bar')
self.sse.... | iterator | identifier_name |
views.py | # -*- coding: utf-8 -*-
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
try:
from django.http import StreamingHttpResponse as HttpResponse
except ImportError:
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from sse import S... |
return None
def _iterator(self):
for subiterator in self.iterator():
for bufferitem in self.sse:
yield bufferitem
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
self.sse = Sse()
self.request = request
self.... | return self.request.META['HTTP_LAST_EVENT_ID'] | conditional_block |
views.py | # -*- coding: utf-8 -*-
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
try: | except ImportError:
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from sse import Sse
class BaseSseView(View):
"""
This is a base class for sse streaming.
"""
def get_last_id(self):
if "HTTP_LAST_EVENT_ID" in self.request.META:
retu... | from django.http import StreamingHttpResponse as HttpResponse | random_line_split |
views.py | # -*- coding: utf-8 -*-
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
try:
from django.http import StreamingHttpResponse as HttpResponse
except ImportError:
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from sse import S... |
def _iterator(self):
for subiterator in self.iterator():
for bufferitem in self.sse:
yield bufferitem
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
self.sse = Sse()
self.request = request
self.args = args
... | if "HTTP_LAST_EVENT_ID" in self.request.META:
return self.request.META['HTTP_LAST_EVENT_ID']
return None | identifier_body |
message.py | bzrlib import (
debug,
errors,
)
from bzrlib.trace import mutter
class MessageHandler(object):
"""Base class for handling messages received via the smart protocol.
As parts of a message are received, the corresponding PART_received method
will be called.
"""
def __init__(self):
... | (self, exception):
"""Called when there is a protocol decoding error.
The default implementation just re-raises the exception.
"""
raise
def end_received(self):
"""Called when the end of the message is received."""
# No-op by default.
pass
class Convention... | protocol_error | identifier_name |
message.py | from bzrlib import (
debug,
errors,
)
from bzrlib.trace import mutter
class MessageHandler(object):
| byte.
"""
raise NotImplementedError(self.byte_received)
def bytes_part_received(self, bytes):
"""Called when a 'bytes' part is received.
A 'bytes' message part can contain any number of bytes. It should not
be confused with a 'byte' part, which is always a single b... | """Base class for handling messages received via the smart protocol.
As parts of a message are received, the corresponding PART_received method
will be called.
"""
def __init__(self):
self.headers = None
def headers_received(self, headers):
"""Called when message headers are recei... | identifier_body |
message.py | bzrlib import (
debug,
errors,
)
from bzrlib.trace import mutter
class MessageHandler(object):
"""Base class for handling messages received via the smart protocol.
As parts of a message are received, the corresponding PART_received method
will be called.
"""
def __init__(self):
... |
elif byte == 'E':
# Error. Expect an error structure.
self.expecting = 'error'
else:
raise errors.SmartProtocolError(
'Non-success status byte in request body: %r' % (byte,))
else:
raise errors.SmartProtoco... | self.expecting = 'end' | conditional_block |
message.py | from bzrlib import (
debug,
errors,
)
from bzrlib.trace import mutter
class MessageHandler(object):
"""Base class for handling messages received via the smart protocol.
As parts of a message are received, the corresponding PART_received method
will be called.
"""
def __init__(self):
... | self.finished_reading = True
self._medium_request.finished_reading()
raise
def read_response_tuple(self, expect_body=False):
"""Read a response tuple from | random_line_split | |
interactive.js | module("forge.contact");
if (forge.is.mobile()) {
asyncTest("Select all", 1, function() {
forge.contact.selectAll(['name'], function (data) {
askQuestion("We found "+data.length+" contacts - sound right?", {
Yes: function () {
var question = "Recognise these? <pre>";
for (var idx=0; idx<Math.min(3,... | No: function () {
ok(false, "User claims failure");
start();
}
});
}, function (e) {
ok(false, "Error callback fired: "+e.message);
start();
});
});
asyncTest("Select by ID", 1, function() {
forge.contact.selectAll(function (data) {
forge.contact.selectById(data[Math.floor(Math.ra... | });
}, | random_line_split |
interactive.js | module("forge.contact");
if (forge.is.mobile()) {
asyncTest("Select all", 1, function() {
forge.contact.selectAll(['name'], function (data) {
askQuestion("We found "+data.length+" contacts - sound right?", {
Yes: function () {
var question = "Recognise these? <pre>";
for (var idx=0; idx<Math.min(3,... |
question += "</pre>";
askQuestion(question, {
Yes: function () {
ok(true, "User claims success");
start();
},
No: function () {
ok(false, "User claims failure");
start();
}
});
},
No: function () {
ok(false, "User claims failure");
... | {
question += JSON.stringify(data[Math.floor(Math.random() * data.length)]);
question += "\n";
} | conditional_block |
App.tsx | import * as React from "react";
import { Menu } from 'semantic-ui-react'
import { PostBox } from './post-box/PostBox'
import { Post } from './post/Post'
import { IPost } from "../dto/Post";
import * as statuses from '../statuses';
require("!style-loader!css-loader!sass-loader!./App.scss");
export interface AppProps {... |
onAddedStatus(status:string){
console.log(status)
let post:IPost={
key:Math.random(),
message:status,
user:{
nombre:'Mauricio',
apellido:'Bello'
},
comments:[],
date:new Date()
};
... | {
this.setState({statuses:this.props.statuses, currentStatus:''});
} | identifier_body |
App.tsx | import * as React from "react";
import { Menu } from 'semantic-ui-react'
import { PostBox } from './post-box/PostBox'
import { Post } from './post/Post'
import { IPost } from "../dto/Post";
import * as statuses from '../statuses';
require("!style-loader!css-loader!sass-loader!./App.scss");
export interface AppProps {... | onAddedStatus(status:string){
console.log(status)
let post:IPost={
key:Math.random(),
message:status,
user:{
nombre:'Mauricio',
apellido:'Bello'
},
comments:[],
date:new Date()
};
... | this.setState({statuses:this.props.statuses, currentStatus:''});
}
| random_line_split |
App.tsx | import * as React from "react";
import { Menu } from 'semantic-ui-react'
import { PostBox } from './post-box/PostBox'
import { Post } from './post/Post'
import { IPost } from "../dto/Post";
import * as statuses from '../statuses';
require("!style-loader!css-loader!sass-loader!./App.scss");
export interface AppProps {... | (status:string){
console.log(status)
let post:IPost={
key:Math.random(),
message:status,
user:{
nombre:'Mauricio',
apellido:'Bello'
},
comments:[],
date:new Date()
};
let {statuses}=t... | onAddedStatus | identifier_name |
shutdown.rs | extern crate arg_parser;
extern crate extra;
extern crate syscall;
use std::env;
use std::io::{stderr, stdout, Error, Write};
use std::process::exit;
use arg_parser::ArgParser;
use extra::option::OptionalExt;
use syscall::flag::{SIGTERM, SIGKILL};
const MAN_PAGE: &'static str = /* @MANSTART{shutdown} */ r#"
NAME
... |
}
| {
syscall::kill(1, SIGKILL).map_err(|err| Error::from_raw_os_error(err.errno)).try(&mut stderr);
} | conditional_block |
shutdown.rs | extern crate arg_parser;
extern crate extra;
extern crate syscall;
use std::env;
use std::io::{stderr, stdout, Error, Write};
use std::process::exit;
use arg_parser::ArgParser;
use extra::option::OptionalExt;
use syscall::flag::{SIGTERM, SIGKILL};
const MAN_PAGE: &'static str = /* @MANSTART{shutdown} */ r#"
NAME
... | .add_flag(&["r", "reboot"]);
parser.parse(env::args());
if parser.found("help") {
stdout.write(MAN_PAGE.as_bytes()).try(&mut stderr);
stdout.flush().try(&mut stderr);
exit(0);
}
if parser.found("reboot") {
syscall::kill(1, SIGTERM).map_err(|err| Error::from_raw_... | random_line_split | |
shutdown.rs | extern crate arg_parser;
extern crate extra;
extern crate syscall;
use std::env;
use std::io::{stderr, stdout, Error, Write};
use std::process::exit;
use arg_parser::ArgParser;
use extra::option::OptionalExt;
use syscall::flag::{SIGTERM, SIGKILL};
const MAN_PAGE: &'static str = /* @MANSTART{shutdown} */ r#"
NAME
... | () {
let stdout = stdout();
let mut stdout = stdout.lock();
let mut stderr = stderr();
let mut parser = ArgParser::new(1)
.add_flag(&["h", "help"])
.add_flag(&["r", "reboot"]);
parser.parse(env::args());
if parser.found("help") {
stdout.write(MAN_PAGE.as_bytes()).try(&mu... | main | identifier_name |
shutdown.rs | extern crate arg_parser;
extern crate extra;
extern crate syscall;
use std::env;
use std::io::{stderr, stdout, Error, Write};
use std::process::exit;
use arg_parser::ArgParser;
use extra::option::OptionalExt;
use syscall::flag::{SIGTERM, SIGKILL};
const MAN_PAGE: &'static str = /* @MANSTART{shutdown} */ r#"
NAME
... | }
| {
let stdout = stdout();
let mut stdout = stdout.lock();
let mut stderr = stderr();
let mut parser = ArgParser::new(1)
.add_flag(&["h", "help"])
.add_flag(&["r", "reboot"]);
parser.parse(env::args());
if parser.found("help") {
stdout.write(MAN_PAGE.as_bytes()).try(&mut s... | identifier_body |
quartet_sampling.py | # Prev -T
required=True, default=1, dest="threads",
help=("The number of parallel threads to be used "
"by Python for quartet topology searches."))
parser.add_argument("--lnlike", "--lnlike-thresh", type=float, nar... | parser = argparse.ArgumentParser(
prog="quartet_sampling.py",
description=__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
epilog=LICENSE)
parser.add_argument("--tree", type=open, nargs=1, required=True,
# Prev -t
help=(... | identifier_body | |
quartet_sampling.py | and isomorphic!) input trees "
"in deterministic order."))
parser.add_argument("--engine", nargs=1, default=('raxml-ng',),
choices=('raxml-ng', 'raxml', 'paup', 'iqtree'),
help=("Name of the program to use to infer trees or"
... | print(file_path,
" does not contain 'QuartetSampling' "
"and will not be deleted for safety") | conditional_block | |
quartet_sampling.py | ():
parser = argparse.ArgumentParser(
prog="quartet_sampling.py",
description=__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
epilog=LICENSE)
parser.add_argument("--tree", type=open, nargs=1, required=True,
# Prev -t
... | generate_argparser | identifier_name | |
quartet_sampling.py | _argument("--reps", "--number-of-reps", type=int, nargs=1,
# Prev -N
required=True, default=100, dest="reps",
help=("The number of replicate quartet topology "
"searches to be performed at each node."))
parser.add_... | parser.add_argument("--temp-dir", type=os.path.abspath, nargs=1,
# Prev -e
help=("A directory to which temporary files will be "
"saved. If not supplied, 'QuartetSampling' "
"will be created in the current "
... | help=("Use partitions file (RAxML format) to divide "
"the alignment into separate gene tree regions. "
"Gene alignments will be sampled random for the "
"quartet topology searches.")) | random_line_split |
main.rs | extern crate dotenv;
extern crate rand;
extern crate serenity;
use std::env;
use std::sync::Arc;
use dotenv::dotenv;
use rand::Rng;
use serenity::framework::standard::*;
use serenity::framework::StandardFramework;
use serenity::model::prelude::*;
use serenity::prelude::*;
struct Handler;
impl EventHandler for Handle... | let result = rand::thread_rng().gen_range(0, up) + 1;
msg.reply(&format!("{}", result)).unwrap();
})
}
} | random_line_split | |
main.rs | extern crate dotenv;
extern crate rand;
extern crate serenity;
use std::env;
use std::sync::Arc;
use dotenv::dotenv;
use rand::Rng;
use serenity::framework::standard::*;
use serenity::framework::StandardFramework;
use serenity::model::prelude::*;
use serenity::prelude::*;
struct Handler;
impl EventHandler for Handle... | (_: &mut Context, msg: &Message, cmd: &str) {
msg.reply(&format!("{} is not a command.", cmd)).unwrap();
}
struct Flip;
impl Command for Flip {
fn options(&self) -> Arc<CommandOptions> {
let mut options = CommandOptions::default();
options.desc = Some("Flips a coin.".to_owned());
option... | unrecognised_command_handler | identifier_name |
main.rs | extern crate dotenv;
extern crate rand;
extern crate serenity;
use std::env;
use std::sync::Arc;
use dotenv::dotenv;
use rand::Rng;
use serenity::framework::standard::*;
use serenity::framework::StandardFramework;
use serenity::model::prelude::*;
use serenity::prelude::*;
struct Handler;
impl EventHandler for Handle... |
}
| {
let upper_bound = match args.single() {
Ok(num) => Ok(num),
Err(ArgError::Eos) => Ok(6),
Err(ArgError::Parse(err)) => Err(CommandError(format!("{}", err))),
};
upper_bound.map(|up| {
let result = rand::thread_rng().gen_range(0, up) + 1;
... | identifier_body |
opcode.py | #!/usr/bin/python
#
# Manage JSON database of Micro-BESM opcodes.
#
import sys, json, codecs
# Check parameters.
if len(sys.argv) != 2:
print "Usage:"
print " opcode [option] file.json"
print "Options:"
print " TODO"
sys.exit(1)
opcode = [] # List of all opcodes
#
# Proc... |
#
# Write the data to another JSON file.
#
def write_results(filename):
file = codecs.open(filename, 'w', encoding="utf-8")
json.dump(opcode, file, indent=4, sort_keys=True, ensure_ascii=False)
file.close()
print "Write file %s: %d opcodes" % (filename, len(opcode))
if __name__ == "__main__":
mai... | global opcode
try:
file = open(filename)
opcode = json.load(file)
file.close()
except:
print "Fatal error: Cannot load file '" + filename + "'"
sys.exit(1)
print "Load file '"+filename+"':",
print "%d opcodes" % len(opcode)
#print "Opcodes:", opcode | identifier_body |
opcode.py | #!/usr/bin/python
#
# Manage JSON database of Micro-BESM opcodes.
#
import sys, json, codecs
# Check parameters.
if len(sys.argv) != 2:
print "Usage:" | print " TODO"
sys.exit(1)
opcode = [] # List of all opcodes
#
# Process the input file.
#
def main(filename):
read_data(filename)
write_results("output.json")
#
# Load opcode[] from JSON file.
#
def read_data(filename):
global opcode
try:
file = open(filename)
... | print " opcode [option] file.json"
print "Options:" | random_line_split |
opcode.py | #!/usr/bin/python
#
# Manage JSON database of Micro-BESM opcodes.
#
import sys, json, codecs
# Check parameters.
if len(sys.argv) != 2:
print "Usage:"
print " opcode [option] file.json"
print "Options:"
print " TODO"
sys.exit(1)
opcode = [] # List of all opcodes
#
# Proc... | (filename):
file = codecs.open(filename, 'w', encoding="utf-8")
json.dump(opcode, file, indent=4, sort_keys=True, ensure_ascii=False)
file.close()
print "Write file %s: %d opcodes" % (filename, len(opcode))
if __name__ == "__main__":
main(sys.argv[1])
| write_results | identifier_name |
opcode.py | #!/usr/bin/python
#
# Manage JSON database of Micro-BESM opcodes.
#
import sys, json, codecs
# Check parameters.
if len(sys.argv) != 2:
print "Usage:"
print " opcode [option] file.json"
print "Options:"
print " TODO"
sys.exit(1)
opcode = [] # List of all opcodes
#
# Proc... | main(sys.argv[1]) | conditional_block | |
models.py | # Eve W-Space
# Copyright (C) 2013 Andrew Austin and other contributors
#
# 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 ... |
class GroupMap(models.Model):
"""Maps Django user groups to Teamspeak groups."""
tsserver = models.ForeignKey(TeamspeakServer, related_name="groupmaps")
usergroup = models.ForeignKey(Group, related_name="teamspeakgroups")
tsgroup = models.CharField(max_length=100)
| """Stores teamspeak server configuration."""
host = models.CharField(max_length=100)
queryuser = models.CharField(max_length=100)
querypass = models.CharField(max_length=100)
queryport = models.IntegerField()
voiceport = models.IntegerField()
# If enforcegroups = True, any TS users who do ... | identifier_body |
models.py | # Eve W-Space
# Copyright (C) 2013 Andrew Austin and other contributors
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
| # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. An additional term under section
# 7 of the GPL is included in the LICENSE file.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the ... | random_line_split | |
models.py | # Eve W-Space
# Copyright (C) 2013 Andrew Austin and other contributors
#
# 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 ... | (models.Model):
"""Stores teamspeak server configuration."""
host = models.CharField(max_length=100)
queryuser = models.CharField(max_length=100)
querypass = models.CharField(max_length=100)
queryport = models.IntegerField()
voiceport = models.IntegerField()
# If enforcegroups = True,... | TeamspeakServer | identifier_name |
gak_spider.py | from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, HtmlResponse
from scrapy.utils.url import urljoin_rfc
from product_spiders.items import Product, ProductLoaderWithNameStrip as ProductLoader
class | (BaseSpider):
name = 'gak.co.uk'
allowed_domains = ['gak.co.uk']
start_urls = ['http://www.gak.co.uk/']
def parse(self, response):
hxs = HtmlXPathSelector(response)
relative_urls = hxs.select('//div[@class="tabs_menu"]/ul/li/a/@href').extract()
for relative_url in relative_urls:... | GakSpider | identifier_name |
gak_spider.py | from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, HtmlResponse
from scrapy.utils.url import urljoin_rfc
from product_spiders.items import Product, ProductLoaderWithNameStrip as ProductLoader
class GakSpider(BaseSpider):
| url = urljoin_rfc('http://www.gak.co.uk/',
relative_url, response.encoding)
loader.add_value('url', url)
price = 0.0
if product.select('div/div/span/text()'):
price = product.select('div/div/span/text()').extract()[0]
... | name = 'gak.co.uk'
allowed_domains = ['gak.co.uk']
start_urls = ['http://www.gak.co.uk/']
def parse(self, response):
hxs = HtmlXPathSelector(response)
relative_urls = hxs.select('//div[@class="tabs_menu"]/ul/li/a/@href').extract()
for relative_url in relative_urls:
url =... | identifier_body |
gak_spider.py | from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, HtmlResponse
from scrapy.utils.url import urljoin_rfc
from product_spiders.items import Product, ProductLoaderWithNameStrip as ProductLoader
class GakSpider(BaseSpider):
name = 'gak.co.uk'
allow... | hxs = HtmlXPathSelector(response)
products = hxs.select('//div[@class="snapshot"]')
for product in products:
loader = ProductLoader(item=Product(), selector=product)
loader.add_xpath('name', 'div/a/text()')
relative_url = product.select('div[@class="dsc"]/a/@h... | def parse_products(self, response): | random_line_split |
gak_spider.py | from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, HtmlResponse
from scrapy.utils.url import urljoin_rfc
from product_spiders.items import Product, ProductLoaderWithNameStrip as ProductLoader
class GakSpider(BaseSpider):
name = 'gak.co.uk'
allow... |
def parse_products(self, response):
hxs = HtmlXPathSelector(response)
products = hxs.select('//div[@class="snapshot"]')
for product in products:
loader = ProductLoader(item=Product(), selector=product)
loader.add_xpath('name', 'div/a/text()')
relative_ur... | url = urljoin_rfc('http://www.gak.co.uk/',
relative_url, response.encoding)
yield Request(url, callback=self.parse_products) | conditional_block |
MemConfig.py | # Copyright (c) 2013 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality ... |
if _mem_aliases:
print "\nMemory aliases:"
for alias, target in _mem_aliases.items():
print "\t%s => %s" % (alias, target)
def mem_names():
"""Return a list of valid memory names."""
return _mem_classes.keys() + _mem_aliases.keys()
# Add all memory controllers in the object h... | for line in doc_wrapper.wrap(doc):
print line | conditional_block |
MemConfig.py | # Copyright (c) 2013 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality ... |
def mem_names():
"""Return a list of valid memory names."""
return _mem_classes.keys() + _mem_aliases.keys()
# Add all memory controllers in the object hierarchy.
for name, cls in inspect.getmembers(m5.objects, is_mem_class):
_mem_classes[name] = cls
for alias, target in _mem_aliases_all:
if isinsta... | """Print a list of available memory classes including their aliases."""
print "Available memory classes:"
doc_wrapper = TextWrapper(initial_indent="\t\t", subsequent_indent="\t\t")
for name, cls in _mem_classes.items():
print "\t%s" % name
# Try to extract the class documentation from the ... | identifier_body |
MemConfig.py | # Copyright (c) 2013 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality ... | ():
"""Return a list of valid memory names."""
return _mem_classes.keys() + _mem_aliases.keys()
# Add all memory controllers in the object hierarchy.
for name, cls in inspect.getmembers(m5.objects, is_mem_class):
_mem_classes[name] = cls
for alias, target in _mem_aliases_all:
if isinstance(target, tup... | mem_names | identifier_name |
MemConfig.py | # Copyright (c) 2013 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality ... | real_name = _mem_aliases.get(name, name)
try:
mem_class = _mem_classes[real_name]
return mem_class
except KeyError:
print "%s is not a valid memory controller." % (name,)
sys.exit(1)
def print_mem_list():
"""Print a list of available memory classes including their alias... |
def get(name):
"""Get a memory class from a user provided class name or alias."""
| random_line_split |
Config.js | /**
* @author mrdoob / http://mrdoob.com/
*/
export var Config = function ( name ) {
var storage = {
'autosave': true,
'theme': 'css/light.css',
'project/renderer': 'WebGLRenderer',
'project/renderer/antialias': true,
'project/renderer/gammaInput': false,
'project/renderer/gammaOutput': false,
'proj... |
return {
getKey: function ( key ) {
return storage[ key ];
},
setKey: function () { // key, value, key, value ...
for ( var i = 0, l = arguments.length; i < l; i += 2 ) {
storage[ arguments[ i ] ] = arguments[ i + 1 ];
}
window.localStorage[ name ] = JSON.stringify( storage );
conso... | {
var data = JSON.parse( window.localStorage[ name ] );
for ( var key in data ) {
storage[ key ] = data[ key ];
}
} | conditional_block |
Config.js | /**
* @author mrdoob / http://mrdoob.com/
*/
export var Config = function ( name ) {
var storage = {
'autosave': true,
'theme': 'css/light.css',
'project/renderer': 'WebGLRenderer',
'project/renderer/antialias': true,
'project/renderer/gammaInput': false,
'project/renderer/gammaOutput': false,
'proj... | },
setKey: function () { // key, value, key, value ...
for ( var i = 0, l = arguments.length; i < l; i += 2 ) {
storage[ arguments[ i ] ] = arguments[ i + 1 ];
}
window.localStorage[ name ] = JSON.stringify( storage );
console.log( '[' + /\d\d\:\d\d\:\d\d/.exec( new Date() )[ 0 ] + ']', 'Saved... |
getKey: function ( key ) {
return storage[ key ];
| random_line_split |
markup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2013-2014, Martín Gaitán
# Copyright (c) 2012-2013, Alexander Jung-Loddenkemper
# This file is part of Waliki (http://waliki.nqnwebs.com/)
# License: BSD (https://github.com/mgaitan/waliki/blob/master/LICENSE)
#============================================... | elf):
# Processes Markdown text to HTML, returns original markdown text,
# and adds meta
md = markdown.Markdown(['codehilite', 'fenced_code', 'meta'])
html = md.convert(self.raw_content)
meta_lines, body = self.raw_content.split('\n\n', 1)
meta = md.Meta
return ht... | ocess(s | identifier_name |
markup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2013-2014, Martín Gaitán
# Copyright (c) 2012-2013, Alexander Jung-Loddenkemper
# This file is part of Waliki (http://waliki.nqnwebs.com/)
# License: BSD (https://github.com/mgaitan/waliki/blob/master/LICENSE)
#============================================... | def _parse_meta(self, lines):
""" Parse Meta-Data. Taken from Python-Markdown"""
META_RE = re.compile(r'^\.\.\s(?P<key>.*?): (?P<value>.*)')
meta = {}
key = None
for line in lines:
if line.strip() == '':
continue
m1 = META_RE.match(line... | not writer:
writer = HTML5Writer()
# Taken from Nikola
# http://bit.ly/14CmQyh
output, pub = docutils.core.publish_programmatically(
source=source, source_path=source_path, source_class=source_class,
destination_class=docutils.io.StringOutput,
de... | identifier_body |
markup.py | #!/usr/bin/env python | # Copyright (c) 2013-2014, Martín Gaitán
# Copyright (c) 2012-2013, Alexander Jung-Loddenkemper
# This file is part of Waliki (http://waliki.nqnwebs.com/)
# License: BSD (https://github.com/mgaitan/waliki/blob/master/LICENSE)
#===============================================================================
# DOCS
#===... | # -*- coding: utf-8 -*-
| random_line_split |
markup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2013-2014, Martín Gaitán
# Copyright (c) 2012-2013, Alexander Jung-Loddenkemper
# This file is part of Waliki (http://waliki.nqnwebs.com/)
# License: BSD (https://github.com/mgaitan/waliki/blob/master/LICENSE)
#============================================... | return meta
#===============================================================================
# MAIN
#===============================================================================
if __name__ == "__main__":
print(__doc__)
| line.strip() == '':
continue
m1 = META_RE.match(line)
if m1:
key = m1.group('key').lower().strip()
value = m1.group('value').strip()
try:
meta[key].append(value)
except KeyError:
... | conditional_block |
Checkbox.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } }... | (obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
exports.default = (0, _createCom... | _interopRequireDefault | identifier_name |
Checkbox.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } }... |
exports.default = (0, _createComponent2.default)(_Checkbox2.default, function (_ref) {
var _ref$input = _ref.input,
onChange = _ref$input.onChange,
value = _ref$input.value,
inputProps = _objectWithoutProperties(_ref$input, ['onChange', 'value']),
meta = _ref.meta,
props = _objectWitho... | { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } | identifier_body |
Checkbox.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
| var _Checkbox = require('material-ui/Checkbox');
var _Checkbox2 = _interopRequireDefault(_Checkbox);
var _createComponent = require('./createComponent');
var _createComponent2 = _interopRequireDefault(_createComponent);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
... | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
| random_line_split |
topo_disc_constants.py | # Copyright 2017 Cisco Systems, Inc.
# 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 requi... | TOPO_DISC_SEND_THRESHOLD = 4 | random_line_split | |
write_tuple.rs | use std::io::Write;
use crate::pg::Pg;
use crate::serialize::{self, Output};
/// Helper trait for writing tuples as named composite types
///
/// This trait is essentially `ToSql<Record<ST>>` for tuples.
/// While we can provide a valid body of `to_sql`,
/// PostgreSQL doesn't allow the use of bind parameters for unn... | /// See trait documentation.
fn write_tuple<W: Write>(&self, out: &mut Output<W, Pg>) -> serialize::Result;
} | /// ```
pub trait WriteTuple<ST> { | random_line_split |
lower_array_len.rs | // compile-flags: -Z mir-opt-level=4
// EMIT_MIR lower_array_len.array_bound.NormalizeArrayLen.diff
// EMIT_MIR lower_array_len.array_bound.SimplifyLocals.diff
// EMIT_MIR lower_array_len.array_bound.InstCombine.diff
pub fn array_bound<const N: usize>(index: usize, slice: &[u8; N]) -> u8 {
if index < slice.len() {... | () {
let _ = array_bound(3, &[0, 1, 2, 3]);
let mut tmp = [0, 1, 2, 3, 4];
let _ = array_bound_mut(3, &mut [0, 1, 2, 3]);
let _ = array_len(&[0]);
let _ = array_len_by_value([0, 2]);
}
| main | identifier_name |
lower_array_len.rs | // compile-flags: -Z mir-opt-level=4
// EMIT_MIR lower_array_len.array_bound.NormalizeArrayLen.diff
// EMIT_MIR lower_array_len.array_bound.SimplifyLocals.diff
// EMIT_MIR lower_array_len.array_bound.InstCombine.diff
pub fn array_bound<const N: usize>(index: usize, slice: &[u8; N]) -> u8 {
if index < slice.len() {... | {
let _ = array_bound(3, &[0, 1, 2, 3]);
let mut tmp = [0, 1, 2, 3, 4];
let _ = array_bound_mut(3, &mut [0, 1, 2, 3]);
let _ = array_len(&[0]);
let _ = array_len_by_value([0, 2]);
} | identifier_body | |
lower_array_len.rs | // compile-flags: -Z mir-opt-level=4
// EMIT_MIR lower_array_len.array_bound.NormalizeArrayLen.diff
// EMIT_MIR lower_array_len.array_bound.SimplifyLocals.diff
// EMIT_MIR lower_array_len.array_bound.InstCombine.diff
pub fn array_bound<const N: usize>(index: usize, slice: &[u8; N]) -> u8 {
if index < slice.len() {... |
}
// EMIT_MIR lower_array_len.array_bound_mut.NormalizeArrayLen.diff
// EMIT_MIR lower_array_len.array_bound_mut.SimplifyLocals.diff
// EMIT_MIR lower_array_len.array_bound_mut.InstCombine.diff
pub fn array_bound_mut<const N: usize>(index: usize, slice: &mut [u8; N]) -> u8 {
if index < slice.len() {
slice... | {
42
} | conditional_block |
lower_array_len.rs | // compile-flags: -Z mir-opt-level=4
// EMIT_MIR lower_array_len.array_bound.NormalizeArrayLen.diff
// EMIT_MIR lower_array_len.array_bound.SimplifyLocals.diff
// EMIT_MIR lower_array_len.array_bound.InstCombine.diff
pub fn array_bound<const N: usize>(index: usize, slice: &[u8; N]) -> u8 {
if index < slice.len() {... | // EMIT_MIR lower_array_len.array_len_by_value.InstCombine.diff
pub fn array_len_by_value<const N: usize>(arr: [u8; N]) -> usize {
arr.len()
}
fn main() {
let _ = array_bound(3, &[0, 1, 2, 3]);
let mut tmp = [0, 1, 2, 3, 4];
let _ = array_bound_mut(3, &mut [0, 1, 2, 3]);
let _ = array_len(&[0]);
... | // EMIT_MIR lower_array_len.array_len_by_value.SimplifyLocals.diff | random_line_split |
me.js | //! moment.js locale configuration
//! locale : Montenegrin (me)
//! author : Miodrag Nikač <miodrag@restartit.me> : https://github.com/miodragnikac
import moment from '../moment';
var translator = {
words: { //Different grammatical cases
m: ['jedan minut', 'jednog minuta'],
mm: ['minut',... | week : {
dow : 1, // Monday is the first day of the week.
doy : 7 // The week that contains Jan 1st is the first week of the year.
}
}); | random_line_split | |
me.js | //! moment.js locale configuration
//! locale : Montenegrin (me)
//! author : Miodrag Nikač <miodrag@restartit.me> : https://github.com/miodragnikac
import moment from '../moment';
var translator = {
words: { //Different grammatical cases
m: ['jedan minut', 'jednog minuta'],
mm: ['minut',... |
}
};
export default moment.defineLocale('me', {
months: ['januar', 'februar', 'mart', 'april', 'maj', 'jun', 'jul', 'avgust', 'septembar', 'oktobar', 'novembar', 'decembar'],
monthsShort: ['jan.', 'feb.', 'mar.', 'apr.', 'maj', 'jun', 'jul', 'avg.', 'sep.', 'okt.', 'nov.', 'dec.'],
weekdays: ['n... |
return number + ' ' + translator.correctGrammaticalCase(number, wordKey);
}
| conditional_block |
zams_solutions.py |
from .ext_solutions import intrsc_values
def | (id_star, x_star, y_star, extin_list, zams_indxs, zams_inter, M_abs,
sp_type, m_obs, bv_obsrv, e_bv, ub_obsrv, e_ub):
"""
For each solution assigned to each observed star, find its absolute
magnitude, intrinsic colors, spectral types, and distances (in kpc).
"""
# Generate final lists for ... | main | identifier_name |
zams_solutions.py |
from .ext_solutions import intrsc_values
def main(id_star, x_star, y_star, extin_list, zams_indxs, zams_inter, M_abs,
sp_type, m_obs, bv_obsrv, e_bv, ub_obsrv, e_ub):
"""
For each solution assigned to each observed star, find its absolute
magnitude, intrinsic colors, spectral types, and distance... |
# Fill empty solutions with '--'.
if len(star_indxs) < 4:
for _ in range(4 - len(star_indxs)):
M_abs_final[indx].append('--')
bv_final[indx].append('--')
ub_final[indx].append('--')
sp_type_final[indx].append('--')
... | id_uniq.append(id_star[indx])
x_uniq.append(x_star[indx])
y_uniq.append(y_star[indx])
m_uniq.append(m_obs[indx])
bv_obs_uniq[0].append(bv_obsrv[indx])
bv_obs_uniq[1].append(e_bv[indx])
ub_obs_uniq[0].append(ub_obsrv[indx])
ub_obs_uniq[1... | conditional_block |
zams_solutions.py | from .ext_solutions import intrsc_values
def main(id_star, x_star, y_star, extin_list, zams_indxs, zams_inter, M_abs,
sp_type, m_obs, bv_obsrv, e_bv, ub_obsrv, e_ub):
"""
For each solution assigned to each observed star, find its absolute
magnitude, intrinsic colors, spectral types, and distances... | # Store absolute magnitudes.
M_abs_final[indx].append(round(zams_inter[2][ind], 3))
# Store intrinsic colors
bv_final[indx].append(round(zams_inter[0][ind], 3))
ub_final[indx].append(round(zams_inter[1][ind], 3))
# Get spect... | for indx, star_indxs in enumerate(zams_indxs):
if star_indxs and len(star_indxs) <= 4:
for indx2, ind in enumerate(star_indxs): | random_line_split |
zams_solutions.py |
from .ext_solutions import intrsc_values
def main(id_star, x_star, y_star, extin_list, zams_indxs, zams_inter, M_abs,
sp_type, m_obs, bv_obsrv, e_bv, ub_obsrv, e_ub):
| # Store unique solutions.
x_uniq, y_uniq, m_uniq, d_uniq = [], [], [], []
id_uniq, bv_obs_uniq, ub_obs_uniq, bv_int_uniq, ub_int_uniq =\
[], [[], [], [], []], [[], [], [], []], [], []
for indx, star_indxs in enumerate(zams_indxs):
if star_indxs and len(star_indxs) <= 4:
for... | """
For each solution assigned to each observed star, find its absolute
magnitude, intrinsic colors, spectral types, and distances (in kpc).
"""
# Generate final lists for writing to file.
M_abs_final = [[] for _ in range(len(id_star))]
bv_final = [[] for _ in range(len(id_star))]
ub_final ... | identifier_body |
inherited_box.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("InheritedBox", inherited=True, ge... |
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write {
Ok(()) // Internal property
}
}
#[inline]
pub fn derive_from_display(context: &mut Context) {
use super::display::computed_value::T as Display;
if context.st... | pub fn get_initial_value() -> computed_value::T {
SpecifiedValue(false)
} | random_line_split |
inherited_box.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("InheritedBox", inherited=True, ge... | (context: &mut Context) {
use super::display::computed_value::T as Display;
if context.style().get_box().clone_display() == Display::none {
context.mutate_style().mutate_inheritedbox()
.set__servo_under_display_none(SpecifiedValue(true));
}
}
</... | derive_from_display | identifier_name |
inherited_box.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("InheritedBox", inherited=True, ge... |
}
#[inline]
pub fn derive_from_display(context: &mut Context) {
use super::display::computed_value::T as Display;
if context.style().get_box().clone_display() == Display::none {
context.mutate_style().mutate_inheritedbox()
.set__servo_under_di... | {
Ok(()) // Internal property
} | identifier_body |
inherited_box.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("InheritedBox", inherited=True, ge... |
}
</%helpers:longhand>
| {
context.mutate_style().mutate_inheritedbox()
.set__servo_under_display_none(SpecifiedValue(true));
} | conditional_block |
Surgery.js | Ext.define('gov.va.cprs.Surgery', {
extend: 'Ext.container.Container',
requires: [
'gov.va.cpe.viewdef.HealthTimeColumn',
'gov.va.cpe.viewdef.FacilityColumn',
'gov.va.hmp.ux.UnderConstruction'
],
title: 'Surgery',
height: '100%', | xtype: 'viewdefgridpanel',
flex: 1,
viewID: 'gov.va.cprs.CprsClassicSurgeriesViewDef',
addFilterTool: true,
title: 'Surgeries',
detailTitleTpl: '{localTitle}',
detailType: 'right',
detail: {
width: 400
... | layout: {type: 'vbox', align: 'stretch'},
items: [
{ | random_line_split |
unwrap_or_else_default.rs | //! Lint for `some_result_or_option.unwrap_or_else(Default::default)`
use super::UNWRAP_OR_ELSE_DEFAULT;
use clippy_utils::{
diagnostics::span_lint_and_sugg, is_trait_item, source::snippet_with_applicability, ty::is_type_diagnostic_item,
};
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_lint::Lat... | <'tcx>(
cx: &LateContext<'tcx>,
expr: &'tcx hir::Expr<'_>,
recv: &'tcx hir::Expr<'_>,
u_arg: &'tcx hir::Expr<'_>,
) {
// something.unwrap_or_else(Default::default)
// ^^^^^^^^^- recv ^^^^^^^^^^^^^^^^- u_arg
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- expr
let recv_ty = cx.typ... | check | identifier_name |
unwrap_or_else_default.rs | //! Lint for `some_result_or_option.unwrap_or_else(Default::default)`
use super::UNWRAP_OR_ELSE_DEFAULT;
use clippy_utils::{
diagnostics::span_lint_and_sugg, is_trait_item, source::snippet_with_applicability, ty::is_type_diagnostic_item,
};
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_lint::Lat... | expr.span,
"use of `.unwrap_or_else(..)` to construct default value",
"try",
format!(
"{}.unwrap_or_default()",
snippet_with_applicability(cx, recv.span, "..", &mut applicability)
),
a... | UNWRAP_OR_ELSE_DEFAULT, | random_line_split |
unwrap_or_else_default.rs | //! Lint for `some_result_or_option.unwrap_or_else(Default::default)`
use super::UNWRAP_OR_ELSE_DEFAULT;
use clippy_utils::{
diagnostics::span_lint_and_sugg, is_trait_item, source::snippet_with_applicability, ty::is_type_diagnostic_item,
};
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_lint::Lat... | format!(
"{}.unwrap_or_default()",
snippet_with_applicability(cx, recv.span, "..", &mut applicability)
),
applicability,
);
}
}
}
| {
// something.unwrap_or_else(Default::default)
// ^^^^^^^^^- recv ^^^^^^^^^^^^^^^^- u_arg
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- expr
let recv_ty = cx.typeck_results().expr_ty(recv);
let is_option = is_type_diagnostic_item(cx, recv_ty, sym::Option);
let is_result = is_type_diag... | identifier_body |
result.rs | mod checked {
// For .ln() and .sqrt()
use std::num::Float;
// Mathematical "errors" we want to catch
#[deriving(Show)]
pub enum MathError {
DivisionByZero,
NegativeLogarithm,
NegativeSquareRoot,
}
pub type MathResult = Result<f64, MathError>;
pub fn div(x: f64,... | } | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.