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 |
|---|---|---|---|---|
gama_data_fun.py | # gizela
#
# Copyright (C) 2010 Michal Seidl, Tomas Kubin
# Author: Tomas Kubin <tomas.kubin@fsv.cvut.cz>
# URL: <http://slon.fsv.cvut.cz/gizela>
#
# $Id$
"""
module with functions for
gama-data-obs.py and gama-data-adj.py scripts
"""
import sys
def read_configuration_file(configFile, localSystem2D, localSyst... |
return configDict, localSystem
| from gizela.util.CoordSystemLocal3D import CoordSystemLocal3D
localSystem = CoordSystemLocal3D()
localSystem.parse_config_dict(configDict) | conditional_block |
error.rs | //! # Keystore files (UTC / JSON) module errors
use super::core;
use std::{error, fmt};
/// Keystore file errors
#[derive(Debug)]
pub enum Error {
/// An unsupported cipher
UnsupportedCipher(String),
/// An unsupported key derivation function
UnsupportedKdf(String),
/// An unsupported pseudo-ran... |
}
| {
match *self {
Error::CoreFault(ref err) => Some(err),
_ => None,
}
} | identifier_body |
error.rs | //! # Keystore files (UTC / JSON) module errors
use super::core;
use std::{error, fmt};
/// Keystore file errors
#[derive(Debug)]
pub enum | {
/// An unsupported cipher
UnsupportedCipher(String),
/// An unsupported key derivation function
UnsupportedKdf(String),
/// An unsupported pseudo-random function
UnsupportedPrf(String),
/// `keccak256_mac` field validation failed
FailedMacValidation,
/// Core module error wrap... | Error | identifier_name |
error.rs | //! # Keystore files (UTC / JSON) module errors
use super::core;
use std::{error, fmt};
/// Keystore file errors
#[derive(Debug)]
pub enum Error {
/// An unsupported cipher
UnsupportedCipher(String),
/// An unsupported key derivation function
UnsupportedKdf(String),
/// An unsupported pseudo-ran... |
impl From<core::Error> for Error {
fn from(err: core::Error) -> Self {
Error::CoreFault(err)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::UnsupportedCipher(ref str) => write!(f, "Unsupported cipher: {}", str),
... | random_line_split | |
Renderer.d.ts | import { Scene } from './Scene';
/**
* The renderer is used to render graphics to a canvas.<br>
* Any game instance comes bundled with a renderer already.
*/
export declare class Renderer {
/** The game's background colour. Defaults to black (#000000). */
backgroundColour: string;
private _context;
/... | /**
* Set properties to apply to the context everytime the render method is called.<br>
* It could for example be used to apply a default fillStyle or a global composite
* operation to all your game objects.
* @param context The renderer's context, automatically passed in.
*/
contextPro... | random_line_split | |
Renderer.d.ts | import { Scene } from './Scene';
/**
* The renderer is used to render graphics to a canvas.<br>
* Any game instance comes bundled with a renderer already.
*/
export declare class | {
/** The game's background colour. Defaults to black (#000000). */
backgroundColour: string;
private _context;
/**
* Create a Renderer.
* @param context The context of the canvas to render to.
*/
constructor(context: CanvasRenderingContext2D);
/**
* The renderer's context.
... | Renderer | identifier_name |
donator.js | s();
this.loadHTML();
addEvent("load", window, function(){crypt.loadConfig();});
addEvent("resize", window, function(){crypt.changeSize();});
crypt.changeSize();
},
getLocation: function() { | //Script location
var scripts = document.getElementsByTagName("script");
for(var i=0;i < scripts.length;i++) {
var scriptLocation = scripts[i].src.split("donator.js");
if(scriptLocation.length === 2) {
this.serverLocation = scriptLocation[0];
}
}
if(!this.serverLocation) {console.log("Script loc... | random_line_split | |
donator.js | ();
this.loadHTML();
addEvent("load", window, function(){crypt.loadConfig();});
addEvent("resize", window, function(){crypt.changeSize();});
crypt.changeSize();
},
getLocation: function() {
//Script location
var scripts = document.getElementsByTagName("script");
for(var i=0;i < scripts.length;i++) {
... |
}
//Animator
function animateHTML(animator, customize) {
if(typeof(animator) === "string") {this.animator = document.getElementById(animator);}
else if(typeof(animator) === "object") {
this.animator = animator;
} else {
console.log("Not object or string for animator.");
return false; | { elem[evnt] = func;} | conditional_block |
donator.js | ();
this.loadHTML();
addEvent("load", window, function(){crypt.loadConfig();});
addEvent("resize", window, function(){crypt.changeSize();});
crypt.changeSize();
},
getLocation: function() {
//Script location
var scripts = document.getElementsByTagName("script");
for(var i=0;i < scripts.length;i++) {
... |
//Animator
function animateHTML(animator, customize) {
if(typeof(animator) === "string") {this.animator = document.getElementById(animator);}
else if(typeof(animator) === "object") {
this.animator = animator;
} else {
console.log("Not object or string for animator.");
return false; | {
if (elem.addEventListener) {
elem.addEventListener(evnt,func,bubble);
} else if (elem.attachEvent) {
elem.attachEvent("on"+evnt, func);
}
else { elem[evnt] = func;}
} | identifier_body |
donator.js | s();
this.loadHTML();
addEvent("load", window, function(){crypt.loadConfig();});
addEvent("resize", window, function(){crypt.changeSize();});
crypt.changeSize();
},
getLocation: function() {
//Script location
var scripts = document.getElementsByTagName("script");
for(var i=0;i < scripts.length;i++) {... | (text) {return text.replace(/^\s+|\s+$/g, '');}
function ajaxJson(page, callback) {
page = page || "";
var request = new XMLHttpRequest();
request.open("GET", page, true);
request.setRequestHeader("Content-Type", "application/json");
//request.responseType = "text";
request.onreadystatechange = function() {
... | trim | identifier_name |
settings.py | # Django settings for test_project project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.db',
}
}
TIME_ZONE = 'Etc/UTC'
LANGUAGE_CODE = 'en-u... | 'schedule': timedelta(seconds=10),
'args': ('validate', ),
},
} | random_line_split | |
idleoutd.py | in GROUP_BY_NAME[y][0]:
GROUP_BY_NAME[y] = (GROUP_BY_NAME[y][0][1:], param)
if GROUP_BY_NAME[y][0] == []:
del GROUP_BY_NAME[y]
else:
for usr in groups:
if usr not in NO_BANN:
GROUP_BY_NAME[spar] ... | reg1 = comp('(\s+)\=(\s+)')
for users in name:
users = reg1.sub("=", users.strip())
usrtmp = users.split()
usrname = usrtmp[0]
rest = usrtmp[1:]
usr_define(usrname, rest)
for groups in group:
groups = reg1.sub("=", groups.st... | global smtp
smtp = [host, int(port), domain] | random_line_split |
idleoutd.py | GROUP_BY_NAME[y][0]:
GROUP_BY_NAME[y] = (GROUP_BY_NAME[y][0][1:], param)
if GROUP_BY_NAME[y][0] == []:
|
else:
for usr in groups:
if usr not in NO_BANN:
GROUP_BY_NAME[spar] = (groups, param)
except Exception, err:
warning("%s -> %s " % (err.__class__ , err))
warning("I was unable to open file %s." % G_FILE)
#### end of group definded ####
#####... | del GROUP_BY_NAME[y] | conditional_block |
idleoutd.py | 0]
dev = x.split(',')[1]
time = int(y[0])
# Search in user define dictionary
if USR_BY_NAME.has_key(user):
idtm = int(USR_BY_NAME[user][0].split('=')[1])
if time >= idtm:
grace = int(USR_BY_NAME[user][1].split('=')[1])
silent = USR_... | """
Check for the SMTP service.
"""
try:
server = smtplib.SMTP(smtp[0], smtp[1])
except Exception, err:
warning("%s -> Exit code %s -> Message: %s" % (err.__class__ , err[0], err[1]))
return(1)
server.quit()
return(0) | identifier_body | |
idleoutd.py | # Search in user define dictionary
if USR_BY_NAME.has_key(user):
idtm = int(USR_BY_NAME[user][0].split('=')[1])
if time >= idtm:
grace = int(USR_BY_NAME[user][1].split('=')[1])
silent = USR_BY_NAME[user][3].split('=')[1]
if x in BANN.keys(... | send_mail | identifier_name | |
client.component.ts | import { Client, Clients } from '../models/client.model';
import { Component, OnInit } from '@angular/core';
import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { ClientService } from '../services/client.service';
import { ConfirmModalComponent } from '../components/index';
import { PagerService... | (
private modal: NgbModal,
private clientService: ClientService,
private pagerService: PagerService
) { }
public ngOnInit() {
this.getClients();
}
public refresh() {
this.clients = undefined;
this.filteredClient = undefined;
this.pagedClient = undefined;
this.page = 1;
this... | constructor | identifier_name |
client.component.ts | import { Client, Clients } from '../models/client.model';
import { Component, OnInit } from '@angular/core';
import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { ClientService } from '../services/client.service';
import { ConfirmModalComponent } from '../components/index';
import { PagerService... | public ngOnInit() {
this.getClients();
}
public refresh() {
this.clients = undefined;
this.filteredClient = undefined;
this.pagedClient = undefined;
this.page = 1;
this.totalSize = 0;
this.getClients();
}
public filtering(text: string) {
text = text.toLocaleLowerCase();
i... | private clientService: ClientService,
private pagerService: PagerService
) { }
| random_line_split |
client.component.ts | import { Client, Clients } from '../models/client.model';
import { Component, OnInit } from '@angular/core';
import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { ClientService } from '../services/client.service';
import { ConfirmModalComponent } from '../components/index';
import { PagerService... |
public pageChange() {
if (!this.filteredClient) return;
let pager = this.pagerService.getPager(this.filteredClient.length, this.page);
this.pagedClient = this.filteredClient.slice(pager.startIndex, pager.endIndex + 1);
}
private deleteClient(activeModal: NgbModalRef, id: number) {
this.clientSe... | {
return client.id;
} | identifier_body |
hashes.py | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
from cryptography import utils
from cryptography.exceptions import (
... |
@utils.register_interface(interfaces.HashAlgorithm)
class SHA256(object):
name = "sha256"
digest_size = 32
block_size = 64
@utils.register_interface(interfaces.HashAlgorithm)
class SHA384(object):
name = "sha384"
digest_size = 48
block_size = 128
@utils.register_interface(interfaces.HashA... | name = "sha224"
digest_size = 28
block_size = 64 | identifier_body |
hashes.py | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
from cryptography import utils
from cryptography.exceptions import (
... |
else:
self._ctx = ctx
algorithm = utils.read_only_property("_algorithm")
def update(self, data):
if self._ctx is None:
raise AlreadyFinalized("Context was already finalized.")
if not isinstance(data, bytes):
raise TypeError("data must be bytes.")
... | self._ctx = self._backend.create_hash_ctx(self.algorithm) | conditional_block |
hashes.py | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
from cryptography import utils
from cryptography.exceptions import (
... | (self, data):
if self._ctx is None:
raise AlreadyFinalized("Context was already finalized.")
if not isinstance(data, bytes):
raise TypeError("data must be bytes.")
self._ctx.update(data)
def copy(self):
if self._ctx is None:
raise AlreadyFinalized... | update | identifier_name |
hashes.py | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
from cryptography import utils
from cryptography.exceptions import (
... | if self._ctx is None:
raise AlreadyFinalized("Context was already finalized.")
if not isinstance(data, bytes):
raise TypeError("data must be bytes.")
self._ctx.update(data)
def copy(self):
if self._ctx is None:
raise AlreadyFinalized("Context was ... | def update(self, data): | random_line_split |
tree-map-cell.component.ts | import {
Component, Input, Output, EventEmitter, ElementRef,
OnChanges, ChangeDetectionStrategy
} from '@angular/core';
import { select } from 'd3-selection';
import { invertColor } from '../utils/color-utils';
import { trimLabel } from '../common/trim-label.helper';
import { id } from '../utils/id';
@Component({... | }];
}
} | },
{
offset: 100,
color: this.fill,
opacity: 1 | random_line_split |
tree-map-cell.component.ts | import {
Component, Input, Output, EventEmitter, ElementRef,
OnChanges, ChangeDetectionStrategy
} from '@angular/core';
import { select } from 'd3-selection';
import { invertColor } from '../utils/color-utils';
import { trimLabel } from '../common/trim-label.helper';
import { id } from '../utils/id';
@Component({... | else {
if (this.animations) {
this.loadAnimation();
}
this.initialized = true;
}
}
loadAnimation(): void {
const node = select(this.element).select('.cell');
node
.attr('opacity', 0)
.attr('x', this.x)
.attr('y', this.y);
this.animateToCurrentForm();
... | {
this.animateToCurrentForm();
} | conditional_block |
tree-map-cell.component.ts | import {
Component, Input, Output, EventEmitter, ElementRef,
OnChanges, ChangeDetectionStrategy
} from '@angular/core';
import { select } from 'd3-selection';
import { invertColor } from '../utils/color-utils';
import { trimLabel } from '../common/trim-label.helper';
import { id } from '../utils/id';
@Component({... | (): void {
const node = select(this.element).select('.cell');
node
.attr('opacity', 0)
.attr('x', this.x)
.attr('y', this.y);
this.animateToCurrentForm();
}
getTextColor(): string {
return invertColor(this.fill);
}
animateToCurrentForm(): void {
const node = select(this... | loadAnimation | identifier_name |
tree-map-cell.component.ts | import {
Component, Input, Output, EventEmitter, ElementRef,
OnChanges, ChangeDetectionStrategy
} from '@angular/core';
import { select } from 'd3-selection';
import { invertColor } from '../utils/color-utils';
import { trimLabel } from '../common/trim-label.helper';
import { id } from '../utils/id';
@Component({... |
}
| {
return [
{
offset: 0,
color: this.fill,
opacity: 0.3
},
{
offset: 100,
color: this.fill,
opacity: 1
}];
} | identifier_body |
tutorial.ts | import { Component } from '@angular/core';
import { MenuController, NavController } from 'ionic-angular';
import { WelcomePage } from '../welcome/welcome';
import { TranslateService } from 'ng2-translate/ng2-translate';
export interface Slide {
title: string;
description: string;
image: string;
}
@Component(... | (slider) {
this.showSkip = !slider.isEnd;
}
ionViewDidEnter() {
// the root left menu should be disabled on the tutorial page
this.menu.enable(false);
}
ionViewWillLeave() {
// enable the root left menu when leaving the tutorial page
this.menu.enable(true);
}
}
| onSlideChangeStart | identifier_name |
tutorial.ts | import { Component } from '@angular/core';
import { MenuController, NavController } from 'ionic-angular';
import { WelcomePage } from '../welcome/welcome';
import { TranslateService } from 'ng2-translate/ng2-translate';
export interface Slide {
title: string;
description: string;
image: string;
}
@Component(... |
onSlideChangeStart(slider) {
this.showSkip = !slider.isEnd;
}
ionViewDidEnter() {
// the root left menu should be disabled on the tutorial page
this.menu.enable(false);
}
ionViewWillLeave() {
// enable the root left menu when leaving the tutorial page
this.menu.enable(true);
}
}
| {
this.navCtrl.setRoot(WelcomePage, {}, {
animate: true,
direction: 'forward'
});
} | identifier_body |
tutorial.ts | import { Component } from '@angular/core';
import { MenuController, NavController } from 'ionic-angular';
import { WelcomePage } from '../welcome/welcome';
import { TranslateService } from 'ng2-translate/ng2-translate';
export interface Slide {
title: string;
description: string;
image: string;
}
@Component(... | }
];
});
}
startApp() {
this.navCtrl.setRoot(WelcomePage, {}, {
animate: true,
direction: 'forward'
});
}
onSlideChangeStart(slider) {
this.showSkip = !slider.isEnd;
}
ionViewDidEnter() {
// the root left menu should be disabled on the tutorial page
this.... | description: values['tutorial.slide3_description'],
image: 'assets/img/ica-slidebox-img-3.png', | random_line_split |
withFluidContainer.tsx | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDI... | {
class FluidContainerHoc extends React.Component<T> {
render(): JSX.Element {
return (
<div className={this.props.class}>
<div className="container-fluid">
<div className="row">
<WrappedComponent {...this.props} />
</div>
</div>
</di... | identifier_body | |
withFluidContainer.tsx | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDI... | extends React.Component<T> {
render(): JSX.Element {
return (
<div className={this.props.class}>
<div className="container-fluid">
<div className="row">
<WrappedComponent {...this.props} />
</div>
</div>
</div>
);
}
}
(Fl... | FluidContainerHoc | identifier_name |
withFluidContainer.tsx | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDI... | );
}
}
(FluidContainerHoc as React.ComponentType<T>).displayName = `withFluidContainer(${getDisplayName(WrappedComponent)})`;
return FluidContainerHoc;
} | <div className="row">
<WrappedComponent {...this.props} />
</div>
</div>
</div> | random_line_split |
base.py | """The base Controller API
Provides the BaseController class for subclassing.
"""
from pylons.controllers import WSGIController
from pylons.templating import render_mako as render
from quanthistling.model.meta import Session
#from quanthistling.lib.helpers import History
from pylons import request, response, session... | (WSGIController):
def __call__(self, environ, start_response):
"""Invoke the Controller"""
# WSGIController.__call__ dispatches to the Controller method
# the request is routed to. This routing information is
# available in environ['pylons.routes_dict']
try:
retu... | BaseController | identifier_name |
base.py | """The base Controller API
Provides the BaseController class for subclassing.
"""
from pylons.controllers import WSGIController
from pylons.templating import render_mako as render
| from quanthistling.model.meta import Session
#from quanthistling.lib.helpers import History
from pylons import request, response, session, tmpl_context as c, url
class BaseController(WSGIController):
def __call__(self, environ, start_response):
"""Invoke the Controller"""
# WSGIController.__call_... | random_line_split | |
base.py | """The base Controller API
Provides the BaseController class for subclassing.
"""
from pylons.controllers import WSGIController
from pylons.templating import render_mako as render
from quanthistling.model.meta import Session
#from quanthistling.lib.helpers import History
from pylons import request, response, session... |
# def __after__(self, action):
# if 'history' in session:
# c.history = session['history']
# print "History in session"
# else:
# c.history = History(20)
#
#
# if hasattr(c, 'heading'):
# c.history.add(c.heading, url)
#
# s... | """Invoke the Controller"""
# WSGIController.__call__ dispatches to the Controller method
# the request is routed to. This routing information is
# available in environ['pylons.routes_dict']
try:
return WSGIController.__call__(self, environ, start_response)
finally:
... | identifier_body |
util.py | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function) | """ mimics sympy.symbols """
tup = tuple(map(Symbol, s.replace(',', ' ').split()))
if len(tup) == 1:
return tup[0]
else:
return tup
def symarray(prefix, shape):
import numpy as np
arr = np.empty(shape, dtype=object)
for index in np.ndindex(shape):
arr[index] = Symbo... | from . import _wrap_numbers, Symbol, Number, Matrix
def symbols(s): | random_line_split |
util.py | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
from . import _wrap_numbers, Symbol, Number, Matrix
def symbols(s):
""" mimics sympy.symbols """
tup = tuple(map(Symbol, s.replace(',', ' ').split()))
if len(tup) == 1:
return tup[0]
else:
return... | (prefix, shape):
import numpy as np
arr = np.empty(shape, dtype=object)
for index in np.ndindex(shape):
arr[index] = Symbol('%s_%s' % (
prefix, '_'.join(map(str, index))))
return arr
def lambdify(args, exprs):
"""
lambdify mimics sympy.lambdify
"""
try:
narg... | symarray | identifier_name |
util.py | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
from . import _wrap_numbers, Symbol, Number, Matrix
def symbols(s):
""" mimics sympy.symbols """
tup = tuple(map(Symbol, s.replace(',', ' ').split()))
if len(tup) == 1:
return tup[0]
else:
return... | return _eval(exprs) | conditional_block | |
util.py | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
from . import _wrap_numbers, Symbol, Number, Matrix
def symbols(s):
""" mimics sympy.symbols """
tup = tuple(map(Symbol, s.replace(',', ' ').split()))
if len(tup) == 1:
return tup[0]
else:
return... |
exprs = self.exprs
if out is not None:
try:
out.flat = _eval(exprs.flatten())
except AttributeError:
out.flat = _eval(exprs)
elif isinstance(exprs, Matrix):
import numpy as np
nr, nc = exprs.nrows, exprs.ncols
... | return [expr.subs(subsd).evalf() for expr in expr_iter] | identifier_body |
crypto_util.py | """Let's Encrypt client crypto utility functions.
.. todo:: Make the transition to use PSS rather than PKCS1_v1_5 when the server
is capable of handling the signatures.
"""
import logging
import os
import OpenSSL
import zope.component
from acme import crypto_util as acme_crypto_util
from acme import jose
from ... | "subjectAltName",
critical=False,
value=", ".join("DNS:%s" % d for d in domains)
),
])
req.set_pubkey(pkey)
req.sign(pkey, "sha256")
return tuple(OpenSSL.crypto.dump_certificate_request(method, req)
for method in (OpenSSL.crypto.FILETYPE_PEM,
... | """Generate a CSR.
:param str key_str: PEM-encoded RSA key.
:param list domains: Domains included in the certificate.
.. todo:: Detect duplicates in `domains`? Using a set doesn't
preserve order...
:returns: new CSR in PEM and DER form containing all domains
:rtype: tuple
"""
... | identifier_body |
crypto_util.py | """Let's Encrypt client crypto utility functions.
.. todo:: Make the transition to use PSS rather than PKCS1_v1_5 when the server
is capable of handling the signatures.
"""
import logging
import os
import OpenSSL
import zope.component
from acme import crypto_util as acme_crypto_util
from acme import jose
from ... |
raise errors.Error("Unable to load: {0}".format(",".join(
str(error) for error in openssl_errors)))
def _get_sans_from_cert_or_req(cert_or_req_str, load_func,
typ=OpenSSL.crypto.FILETYPE_PEM):
try:
cert_or_req = load_func(typ, cert_or_req_str)
except OpenSSL... | try:
return OpenSSL.crypto.load_certificate(file_type, data), file_type
except OpenSSL.crypto.Error as error: # TODO: other errors?
openssl_errors.append(error) | conditional_block |
crypto_util.py | """Let's Encrypt client crypto utility functions.
.. todo:: Make the transition to use PSS rather than PKCS1_v1_5 when the server
is capable of handling the signatures.
"""
import logging
import os
import OpenSSL
import zope.component
from acme import crypto_util as acme_crypto_util
from acme import jose
from ... | (cert, typ=OpenSSL.crypto.FILETYPE_PEM):
"""Get a list of Subject Alternative Names from a certificate.
:param str cert: Certificate (encoded).
:param typ: `OpenSSL.crypto.FILETYPE_PEM` or `OpenSSL.crypto.FILETYPE_ASN1`
:returns: A list of Subject Alternative Names.
:rtype: list
"""
retur... | get_sans_from_cert | identifier_name |
crypto_util.py | """Let's Encrypt client crypto utility functions.
.. todo:: Make the transition to use PSS rather than PKCS1_v1_5 when the server
is capable of handling the signatures.
"""
import logging
import os
import OpenSSL
import zope.component
from acme import crypto_util as acme_crypto_util
from acme import jose
from ... | for method in (OpenSSL.crypto.FILETYPE_PEM,
OpenSSL.crypto.FILETYPE_ASN1))
# WARNING: the csr and private key file are possible attack vectors for TOCTOU
# We should either...
# A. Do more checks to verify that the CSR is trusted/valid
# B. Audit the parsing code for v... | random_line_split | |
has_props.ts | import {expect} from "assertions"
import {HasProps} from "@bokehjs/core/has_props"
import * as mixins from "@bokehjs/core/property_mixins"
import * as p from "@bokehjs/core/properties"
import {keys} from "@bokehjs/core/util/object"
class TestModel extends HasProps {}
namespace SubclassWithProps {
export type Attrs... |
// TODO {{{
class SubclassWithMixins extends HasProps {}
SubclassWithMixins.mixins([mixins.Line])
class SubSubclassWithMixins extends SubclassWithMixins {}
SubSubclassWithMixins.mixins([["foo_", mixins.Fill]])
class SubclassWithMultipleMixins extends HasProps {}
SubclassWithMultipleMixins.mixins([mixins.Line, ["bar_... | random_line_split | |
has_props.ts | import {expect} from "assertions"
import {HasProps} from "@bokehjs/core/has_props"
import * as mixins from "@bokehjs/core/property_mixins"
import * as p from "@bokehjs/core/properties"
import {keys} from "@bokehjs/core/util/object"
class TestModel extends HasProps {}
namespace SubclassWithProps {
export type Attrs... | extends SubclassWithProps {
override properties: SubSubclassWithProps.Props
constructor(attrs?: Partial<SubSubclassWithProps.Attrs>) {
super(attrs)
}
static {
this.define<SubSubclassWithProps.Props>(({String}) => ({
baz: [ String, "" ],
}))
}
}
// TODO {{{
class SubclassWithMixins extends ... | SubSubclassWithProps | identifier_name |
free.rs | //! Free functions that create iterator adaptors or call iterator methods.
//!
//! The benefit of free functions is that they accept any `IntoIterator` as
//! argument, so the resulting code may be easier to read.
use std::fmt::Display;
use std::iter::{self, Zip};
use Itertools;
pub use adaptors::{
interleave,
... | <I, J>(i: I, j: J) -> Zip<I::IntoIter, J::IntoIter>
where I: IntoIterator,
J: IntoIterator
{
i.into_iter().zip(j)
}
/// Create an iterator that first iterates `i` and then `j`.
///
/// `IntoIterator` enabled version of `i.chain(j)`.
///
/// ```
/// use itertools::chain;
///
/// for elt in chain(&[1, ... | zip | identifier_name |
free.rs | //! Free functions that create iterator adaptors or call iterator methods.
//!
//! The benefit of free functions is that they accept any `IntoIterator` as
//! argument, so the resulting code may be easier to read.
use std::fmt::Display;
use std::iter::{self, Zip};
use Itertools;
pub use adaptors::{
interleave,
... | /// `IntoIterator` enabled version of `.enumerate()`.
///
/// ```
/// use itertools::enumerate;
///
/// for (i, elt) in enumerate(&[1, 2, 3]) {
/// /* loop body */
/// }
/// ```
pub fn enumerate<I>(iterable: I) -> iter::Enumerate<I::IntoIter>
where I: IntoIterator
{
iterable.into_iter().enumerate()
}
/// I... |
/// Iterate `iterable` with a running index.
/// | random_line_split |
free.rs | //! Free functions that create iterator adaptors or call iterator methods.
//!
//! The benefit of free functions is that they accept any `IntoIterator` as
//! argument, so the resulting code may be easier to read.
use std::fmt::Display;
use std::iter::{self, Zip};
use Itertools;
pub use adaptors::{
interleave,
... |
/// Create an iterator that clones each element from &T to T
///
/// `IntoIterator` enabled version of `i.cloned()`.
///
/// ```
/// use itertools::cloned;
///
/// assert_eq!(cloned(b"abc").next(), Some(b'a'));
/// ```
pub fn cloned<'a, I, T: 'a>(iterable: I) -> iter::Cloned<I::IntoIter>
where I: IntoIterator<Ite... | {
i.into_iter().chain(j)
} | identifier_body |
__init__.py | # -*- coding: utf-8 -*-
"""
jinja2
~~~~~~
Jinja2 is a template engine written in pure Python. It provides a
Django inspired non-XML syntax but supports inline expressions and
an optional sandboxed environment.
Nutshell
--------
Here a small example of a Jinja2 template::
{% ... | DictLoader, FunctionLoader, PrefixLoader, ChoiceLoader, \
ModuleLoader
# bytecode caches
from jinja2.bccache import BytecodeCache, FileSystemBytecodeCache, \
MemcachedBytecodeCache
# undefined types
from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined
# exceptions
from jinja2.exceptio... | # high level interface
from jinja2.environment import Environment, Template
# loaders
from jinja2.loaders import BaseLoader, FileSystemLoader, PackageLoader, \ | random_line_split |
describe.js | module.exports = {
describe (label, fn) {
return this._descriptionBlock('describe')(label, fn)
},
context (label, fn) {
return this._descriptionBlock('context')(label, fn)
},
ddescribe (label, fn) {
return this._descriptionBlock('describe', { runOnly: true })(label, fn)
},
ccontext (label, fn)... | const T = this
return function analyzeOrExec (label, fn) {
if (
T.deepLevel === 0 &&
options.runOnly &&
!T.excludedSuite(T.onlySuites, label) &&
!T.onlySuitesAsUserParams
) {
T.onlySuites.push(label)
}
if (T.deepLevel === 0 && T.preventsSuiteFromR... | return this._descriptionBlock('context', { runOnly: true })(label, fn)
},
_descriptionBlock (type, options = {}) { | random_line_split |
describe.js | module.exports = {
describe (label, fn) {
return this._descriptionBlock('describe')(label, fn)
},
context (label, fn) {
return this._descriptionBlock('context')(label, fn)
},
ddescribe (label, fn) {
return this._descriptionBlock('describe', { runOnly: true })(label, fn)
},
ccontext (label, fn)... |
T.describeMessages.push(T.message(type, label, T.deepLevel))
T.deepLevel++
fn()
T.itBlockRunLevel = T.deepLevel
T.describeMessages = []
T._contextBlocks.forEach(filterFromSameLevel)
T.deepLevel--
}
function filterFromSameLevel (blockName) {
T[blockName + 'Blocks... | {
return
} | conditional_block |
describe.js | module.exports = {
describe (label, fn) {
return this._descriptionBlock('describe')(label, fn)
},
context (label, fn) {
return this._descriptionBlock('context')(label, fn)
},
ddescribe (label, fn) {
return this._descriptionBlock('describe', { runOnly: true })(label, fn)
},
ccontext (label, fn)... | (label, fn) {
if (T.deepLevel === 0) {
var testSuite = describeBlock.bind(this, label, fn)
T.currentRootDescribeBlock = testSuite
T.suites.push(testSuite)
}
T.deepLevel++
fn()
T.deepLevel--
}
function describeBlock (label, fn) {
if (T.deepLevel === 0... | analizeBlock | identifier_name |
describe.js | module.exports = {
describe (label, fn) {
return this._descriptionBlock('describe')(label, fn)
},
context (label, fn) | ,
ddescribe (label, fn) {
return this._descriptionBlock('describe', { runOnly: true })(label, fn)
},
ccontext (label, fn) {
return this._descriptionBlock('context', { runOnly: true })(label, fn)
},
_descriptionBlock (type, options = {}) {
const T = this
return function analyzeOrExec (label, f... | {
return this._descriptionBlock('context')(label, fn)
} | identifier_body |
DeleteOrganization.py | # -*- coding: utf-8 -*-
###############################################################################
#
# DeleteOrganization
# Deletes an existing organization.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this... |
class DeleteOrganizationChoreographyExecution(ChoreographyExecution):
def _make_result_set(self, response, path):
return DeleteOrganizationResultSet(response, path)
| """
Retrieve the value for the "ResponseStatusCode" output from this Choreo execution. ((integer) The response status code returned from Zendesk.)
"""
return self._output.get('ResponseStatusCode', None) | identifier_body |
DeleteOrganization.py | # -*- coding: utf-8 -*-
###############################################################################
#
# DeleteOrganization
# Deletes an existing organization.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this... | def set_ID(self, value):
"""
Set the value of the ID input for this Choreo. ((required, string) ID of the organization to delete.)
"""
super(DeleteOrganizationInputSet, self)._set_input('ID', value)
def set_Password(self, value):
"""
Set the value of the Password ... | Set the value of the Email input for this Choreo. ((required, string) The email address you use to login to your Zendesk account.)
"""
super(DeleteOrganizationInputSet, self)._set_input('Email', value) | random_line_split |
DeleteOrganization.py | # -*- coding: utf-8 -*-
###############################################################################
#
# DeleteOrganization
# Deletes an existing organization.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this... | (self, value):
"""
Set the value of the Email input for this Choreo. ((required, string) The email address you use to login to your Zendesk account.)
"""
super(DeleteOrganizationInputSet, self)._set_input('Email', value)
def set_ID(self, value):
"""
Set the value of t... | set_Email | identifier_name |
dbscan.rs | use rm::linalg::Matrix; | #[test]
fn test_basic_clusters() {
let inputs = Matrix::new(6, 2, vec![1.0, 2.0,
1.1, 2.2,
0.9, 1.9,
1.0, 2.1,
-2.0, 3.0,
... |
use rm::learning::dbscan::DBSCAN;
use rm::learning::UnSupModel;
| random_line_split |
dbscan.rs | use rm::linalg::Matrix;
use rm::learning::dbscan::DBSCAN;
use rm::learning::UnSupModel;
#[test]
fn test_basic_clusters() |
#[test]
fn test_basic_prediction() {
let inputs = Matrix::new(6, 2, vec![1.0, 2.0,
1.1, 2.2,
0.9, 1.9,
1.0, 2.1,
-2.0, 3.0,
... | {
let inputs = Matrix::new(6, 2, vec![1.0, 2.0,
1.1, 2.2,
0.9, 1.9,
1.0, 2.1,
-2.0, 3.0,
-2.2, 3.1]);
let mut m... | identifier_body |
dbscan.rs | use rm::linalg::Matrix;
use rm::learning::dbscan::DBSCAN;
use rm::learning::UnSupModel;
#[test]
fn | () {
let inputs = Matrix::new(6, 2, vec![1.0, 2.0,
1.1, 2.2,
0.9, 1.9,
1.0, 2.1,
-2.0, 3.0,
-2.2, 3.1]);
let mu... | test_basic_clusters | identifier_name |
scraper.py | __author__ = 'akilharris'
import httplib
from bs4 import BeautifulSoup
import os
#Load http://www.nyc.gov/html/nypd/html/traffic_reports/traffic_summons_reports.shtml
#grab all pdfs and save to a folder
path = "raw_data/pdf/"
def scrape(url):
conn = httplib.HTTPConnection("www.nyc.gov")
conn.request("GET", ... |
return links
def save_links(links):
if not os.path.exists(path):
parts = path.split("/")
for part in parts:
if len(part) > 0:
os.mkdir(part)
os.chdir(part)
else:
os.chdir(path)
# print(os.getcwd())
for link in links:
lin... | links.append(href) | conditional_block |
scraper.py | __author__ = 'akilharris'
import httplib
from bs4 import BeautifulSoup
import os
#Load http://www.nyc.gov/html/nypd/html/traffic_reports/traffic_summons_reports.shtml
#grab all pdfs and save to a folder
path = "raw_data/pdf/"
def scrape(url):
conn = httplib.HTTPConnection("www.nyc.gov")
conn.request("GET", ... |
def getPDFs():
raw_data = scrape("/html/nypd/html/traffic_reports/traffic_summons_reports.shtml")
links = parse(".pdf", raw_data)
save_links(links)
getPDFs()
| if not os.path.exists(path):
parts = path.split("/")
for part in parts:
if len(part) > 0:
os.mkdir(part)
os.chdir(part)
else:
os.chdir(path)
# print(os.getcwd())
for link in links:
link = str(link).replace("../..", "/html/nypd")
... | identifier_body |
scraper.py | __author__ = 'akilharris'
import httplib
from bs4 import BeautifulSoup
import os
#Load http://www.nyc.gov/html/nypd/html/traffic_reports/traffic_summons_reports.shtml
#grab all pdfs and save to a folder
path = "raw_data/pdf/"
def scrape(url):
conn = httplib.HTTPConnection("www.nyc.gov")
conn.request("GET", ... | ():
raw_data = scrape("/html/nypd/html/traffic_reports/traffic_summons_reports.shtml")
links = parse(".pdf", raw_data)
save_links(links)
getPDFs()
| getPDFs | identifier_name |
scraper.py | __author__ = 'akilharris'
import httplib
from bs4 import BeautifulSoup
import os
#Load http://www.nyc.gov/html/nypd/html/traffic_reports/traffic_summons_reports.shtml
#grab all pdfs and save to a folder
path = "raw_data/pdf/"
def scrape(url):
conn = httplib.HTTPConnection("www.nyc.gov")
conn.request("GET", ... | return links
def save_links(links):
if not os.path.exists(path):
parts = path.split("/")
for part in parts:
if len(part) > 0:
os.mkdir(part)
os.chdir(part)
else:
os.chdir(path)
# print(os.getcwd())
for link in links:
link... | links.append(href) | random_line_split |
irc.py | import re
import sys
import socket
from src.config import *
class | :
def __init__(self, queue):
self.queue = queue
def end_connection(self):
"""Send a goodbye message through irc and close the socket."""
try:
self.send_custom_message('goodbye')
channel = get_channel()
if channel:
self.sock.send('PART ... | IRC | identifier_name |
irc.py | import re
import sys
import socket
from src.config import *
class IRC:
def __init__(self, queue):
self.queue = queue
def end_connection(self):
"""Send a goodbye message through irc and close the socket."""
try:
self.send_custom_message('goodbye')
channel = get_... |
def send_custom_message(self, message, data=None):
"""Try to send given message (if defined in the config)."""
config = get_config()
try:
if config['messages'][message]['enabled']:
msg = self.format_custom_message(message, config['messages'][message]['msg'], dat... | """Try to send given message as PRIVMSG through the irc socket."""
if message == None:
return
try:
channel = get_channel()
if channel:
self.sock.send('PRIVMSG {0} : {1}\n'.format(channel, message.encode('utf-8')))
except Exception:
... | identifier_body |
irc.py | import re
import sys
import socket
from src.config import *
class IRC:
def __init__(self, queue):
self.queue = queue
def end_connection(self):
"""Send a goodbye message through irc and close the socket."""
try:
self.send_custom_message('goodbye')
channel = get_... |
return channel
| self.queue.put(("Login failed (possibly invalid oauth token)", 'BG_error'))
return False | conditional_block |
irc.py | import re
import sys
import socket
from src.config import *
class IRC:
def __init__(self, queue):
self.queue = queue
def end_connection(self):
"""Send a goodbye message through irc and close the socket."""
try:
self.send_custom_message('goodbye')
channel = get_... | self.sock.send('PART {0}\r\n'.format(channel))
self.sock.close()
except Exception:
self.queue.put(("{0}".format(sys.exc_info()[0]), 'BG_error'))
self.queue.put(("irc.end_connection() - Could not close socket!", 'BG_error'))
def check_for_message(self, dat... | if channel: | random_line_split |
jquery.paver.js | yPos: paver.settings.startPosition
});
// Turn on paver
paver.$t.addClass('paver--on');
// Bind events
_fun.bindEvents(paver);
// Update dimensions and recompute upon window resize, or custom event
$w.on('resize', $.throttle(paver.settings.resizeThrottle, func... | // Position panorama centrally the first time
paver.instanceData.panCounter = 0;
paver.pan({
xPos: paver.settings.startPosition, | random_line_split | |
__init__.py | # This file is heavily inspired from the django admin autodiscover
__version_info__ = {
'major': 1,
'minor': 0,
'micro': 2,
'releaselevel': 'final',
'serial': 0
}
def | ():
"""
Auto-discover INSTALLED_APPS admin.py modules and fail silently when
not present. This forces an import on them to register any admin bits they
may want.
"""
import copy
from django.conf import settings
from django.utils.importlib import import_module
from django.utils.modul... | autodiscover | identifier_name |
__init__.py | # This file is heavily inspired from the django admin autodiscover
__version_info__ = {
'major': 1,
'minor': 0,
'micro': 2,
'releaselevel': 'final',
'serial': 0
}
def autodiscover():
"""
Auto-discover INSTALLED_APPS admin.py modules and fail silently when
not present. This forces an i... |
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
... | raise | conditional_block |
__init__.py | # This file is heavily inspired from the django admin autodiscover
__version_info__ = {
'major': 1,
'minor': 0,
'micro': 2,
'releaselevel': 'final',
'serial': 0
} | not present. This forces an import on them to register any admin bits they
may want.
"""
import copy
from django.conf import settings
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
from health_check.plugins import plugin_dir... |
def autodiscover():
"""
Auto-discover INSTALLED_APPS admin.py modules and fail silently when | random_line_split |
__init__.py | # This file is heavily inspired from the django admin autodiscover
__version_info__ = {
'major': 1,
'minor': 0,
'micro': 2,
'releaselevel': 'final',
'serial': 0
}
def autodiscover():
"""
Auto-discover INSTALLED_APPS admin.py modules and fail silently when
not present. This forces an i... |
__version__ = get_version()
| assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_i... | identifier_body |
mod.rs | : RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>,
}
struct CoherenceCheckVisitor<'a, 'tcx: 'a> {
cc: &'a CoherenceChecker<'a, 'tcx>
}
impl<'a, 'tcx, 'v> visit::Visitor<'v> for CoherenceCheckVisitor<'a, 'tcx> {
fn visit_item(&mut self, item: &Item) {
//debug!("(checking coherence) item '{}'", token::... |
fn get_self_type_for_implementation(&self, impl_did: DefId)
-> TypeScheme<'tcx> {
self.crate_context.tcx.tcache.borrow()[impl_did].clone()
}
// Converts an implementation in the AST to a vector of items.
fn create_impl_from_item(&self, item: &Item) -> V... | {
debug!("add_trait_impl: base_def_id={:?} impl_def_id={:?}",
base_def_id, impl_def_id);
ty::record_trait_implementation(self.crate_context.tcx,
base_def_id,
impl_def_id);
} | identifier_body |
mod.rs | <'a, 'tcx: 'a> {
crate_context: &'a CrateCtxt<'a, 'tcx>,
inference_context: InferCtxt<'a, 'tcx>,
inherent_impls: RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>,
}
struct CoherenceCheckVisitor<'a, 'tcx: 'a> {
cc: &'a CoherenceChecker<'a, 'tcx>
}
impl<'a, 'tcx, 'v> visit::Visitor<'v> for CoherenceCheck... | CoherenceChecker | identifier_name | |
mod.rs |
ty_infer(..) | ty_closure(..) => {
// `ty` comes from a user declaration so we should only expect types
// that the user can type
inference_context.tcx.sess.span_bug(
span,
&format!("coherence encountered unexpected type searching for base ty... | {
None
} | conditional_block | |
mod.rs | match ty.sty {
ty_enum(def_id, _) |
ty_struct(def_id, _) => {
Some(def_id)
}
ty_trait(ref t) => {
Some(t.principal_def_id())
}
ty_uniq(_) => {
inference_context.tcx.lang_items.owned_box()
}
ty_bool | ty_char | ty_... | // Returns the def ID of the base type, if there is one.
fn get_base_type_def_id<'a, 'tcx>(inference_context: &InferCtxt<'a, 'tcx>,
span: Span,
ty: Ty<'tcx>)
-> Option<DefId> { | random_line_split | |
util.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... | (rt: &Runtime, app_name: &'static str) -> Result<RefConfig> {
use toml_query::read::TomlValueReadExt;
let setting_name = "ref.basepathes";
rt.config()
.ok_or_else(|| anyhow!("No configuration, cannot find collection name for {}", app_name))?
.read_deserialized::<RefConfig>(setting_name)?
... | get_ref_config | identifier_name |
util.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... | .ok_or_else(|| anyhow!("Setting missing: {}", setting_name))
} | rt.config()
.ok_or_else(|| anyhow!("No configuration, cannot find collection name for {}", app_name))?
.read_deserialized::<RefConfig>(setting_name)? | random_line_split |
util.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... | {
use toml_query::read::TomlValueReadExt;
let setting_name = "ref.basepathes";
rt.config()
.ok_or_else(|| anyhow!("No configuration, cannot find collection name for {}", app_name))?
.read_deserialized::<RefConfig>(setting_name)?
.ok_or_else(|| anyhow!("Setting missing: {}", setting... | identifier_body | |
struct-destructuring-cross-crate.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
let x = struct_destructuring_cross_crate::S { x: 1, y: 2 };
let struct_destructuring_cross_crate::S { x: a, y: b } = x;
assert_eq!(a, 1);
assert_eq!(b, 2);
} | identifier_body | |
struct-destructuring-cross-crate.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () {
let x = struct_destructuring_cross_crate::S { x: 1, y: 2 };
let struct_destructuring_cross_crate::S { x: a, y: b } = x;
assert_eq!(a, 1);
assert_eq!(b, 2);
}
| main | identifier_name |
struct-destructuring-cross-crate.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:struct_destructuring_cross_crate.rs
extern crate struct_destructuring_cro... | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | random_line_split |
synthrepo.py | if s == '-' and not line.startswith('--- '):
lineremove += 1
elif s == '+' and not line.startswith('+++ '):
lineadd[roundto(len(line) - 1, 5)] += 1
if filename:
yield filename, mar, lineadd, lineremove, binary
@command('analyze',
[('o', 'outp... |
for length, count in lineadd.iteritems():
linelengths[length] += count
fileschanged[filechanges] += 1
filesadded[fileadds] += 1
dirsadded[diradds] += 1
filesremoved[fileremoves] += 1
invchildren = zerodict()
for rev, count in... | fileremoves += 1 | conditional_block |
synthrepo.py | changed': pronk(lineschanged),
'children': pronk(invchildren),
'fileschanged': pronk(fileschanged),
'filesadded': pronk(filesadded),
'linesinfilesadded': pronk(linesinfilesadded),
'dirsadded': pronk(dirsadded),
'filesremoved': pro... | random_line_split | ||
synthrepo.py | if s == '-' and not line.startswith('--- '):
lineremove += 1
elif s == '+' and not line.startswith('+++ '):
lineadd[roundto(len(line) - 1, 5)] += 1
if filename:
yield filename, mar, lineadd, lineremove, binary
@command('analyze',
[('o', 'output', '', _(... | (cdf):
return cdf[0][bisect.bisect_left(cdf[1], random.random())]
def pickpath():
return os.path.join(pick(initdirscdf), random.choice(words))
| pick | identifier_name |
synthrepo.py | lineadd[roundto(len(line) - 1, 5)] += 1
if filename:
yield filename, mar, lineadd, lineremove, binary
@command('analyze',
[('o', 'output', '', _('write output to given file'), _('FILE')),
('r', 'rev', [], _('analyze specified revisions'), _('REV'))],
_('hg analy... | filename, mar, lineadd, lineremove = None, None, zerodict(), 0
binary = False
for line in lines:
start = line[:6]
if start == 'diff -':
if filename:
yield filename, mar, lineadd, lineremove, binary
mar, lineadd, lineremove, binary = 'm', zerodict(), 0, Fal... | identifier_body | |
issue-14919.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&mut self) -> Option<(usize, usize)> {
self.matcher.next_match()
}
}
fn match_indices<'a, M, T: IntoMatcher<'a, M>>(s: &'a str, from: T) -> MatchIndices<M> {
let string_matcher = from.into_matcher(s);
MatchIndices { matcher: string_matcher }
}
fn main() {
let s = "abcbdef";
match_indices(... | next | identifier_name |
issue-14919.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
trait Matcher {
fn next_match(&mut self) -> Option<(usize, usize)>;
}
struct CharPredMatcher<'a, 'b> {
str: &'a str,
pred: Box<FnMut(char) -> bool + 'b>,
}
impl<'a, 'b> Matcher for CharPredMatcher<'a, 'b> {
fn next_match(&mut self) -> Option<(usize, usize)> {
None
}
}
trait IntoMatcher<'... |
// pretty-expanded FIXME #23616 | random_line_split |
issue-14919.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {
let s = "abcbdef";
match_indices(s, |c: char| c == 'b')
.collect::<Vec<(usize, usize)>>();
}
| {
let string_matcher = from.into_matcher(s);
MatchIndices { matcher: string_matcher }
} | identifier_body |
watch-files.js | import watch from 'gulp-watch';
import browserSync from 'browser-sync';
import path from 'path';
/**
* Gulp task to watch files
* @return {function} Function task
*/
export default function watchFilesTask() {
const config = this.config;
const runSequence = require('run-sequence').use(this.gulp);
r... | config.customWatch(config, watch, browserSync);
} else {
watch(config.customWatch, () => {
runSequence('build', browserSync.reload);
});
}
}
};
} | if (config.customWatch) {
if (typeof config.customWatch === 'function') { | random_line_split |
watch-files.js | import watch from 'gulp-watch';
import browserSync from 'browser-sync';
import path from 'path';
/**
* Gulp task to watch files
* @return {function} Function task
*/
export default function watchFilesTask() | runSequence('postcss');
});
}
if (config.customWatch) {
if (typeof config.customWatch === 'function') {
config.customWatch(config, watch, browserSync);
} else {
watch(config.customWatch, () => {
runS... | {
const config = this.config;
const runSequence = require('run-sequence').use(this.gulp);
return () => {
if (config.entryHTML) {
watch(
path.join(
config.basePath,
config.browsersync.server.baseDir,
config.entry... | identifier_body |
watch-files.js | import watch from 'gulp-watch';
import browserSync from 'browser-sync';
import path from 'path';
/**
* Gulp task to watch files
* @return {function} Function task
*/
export default function watchFilesTask() {
const config = this.config;
const runSequence = require('run-sequence').use(this.gulp);
r... |
if (config.postcss) {
watch(path.join(config.sourcePath, '**/*.{css,scss,less}'), () => {
runSequence('postcss');
});
}
if (config.customWatch) {
if (typeof config.customWatch === 'function') {
config.customWatch(config, watc... | {
watch(
path.join(
config.basePath,
config.browsersync.server.baseDir,
config.entryHTML
),
() => {
runSequence('build', browserSync.reload);
}
);
... | conditional_block |
watch-files.js | import watch from 'gulp-watch';
import browserSync from 'browser-sync';
import path from 'path';
/**
* Gulp task to watch files
* @return {function} Function task
*/
export default function | () {
const config = this.config;
const runSequence = require('run-sequence').use(this.gulp);
return () => {
if (config.entryHTML) {
watch(
path.join(
config.basePath,
config.browsersync.server.baseDir,
config.en... | watchFilesTask | identifier_name |
triple_loop.rs | pub use matrix::{Scalar,Mat};
pub use composables::{GemmNode,AlgorithmStep};
pub use thread_comm::ThreadInfo;
pub struct TripleLoop{}
impl<T: Scalar, At: Mat<T>, Bt: Mat<T>, Ct: Mat<T>>
GemmNode<T, At, Bt, Ct> for TripleLoop {
unsafe fn run(&mut self, a: &mut At, b: &mut Bt, c: &mut Ct, _thr: &ThreadInfo<T>) ... | () -> Self { TripleLoop{} }
fn hierarchy_description() -> Vec<AlgorithmStep> { Vec::new() }
}
| new | identifier_name |
triple_loop.rs | pub use matrix::{Scalar,Mat};
pub use composables::{GemmNode,AlgorithmStep};
pub use thread_comm::ThreadInfo;
pub struct TripleLoop{}
impl<T: Scalar, At: Mat<T>, Bt: Mat<T>, Ct: Mat<T>>
GemmNode<T, At, Bt, Ct> for TripleLoop {
unsafe fn run(&mut self, a: &mut At, b: &mut Bt, c: &mut Ct, _thr: &ThreadInfo<T>) ... | fn new() -> Self { TripleLoop{} }
fn hierarchy_description() -> Vec<AlgorithmStep> { Vec::new() }
} | c.set(y, x, t);
}
}
}
} | random_line_split |
triple_loop.rs | pub use matrix::{Scalar,Mat};
pub use composables::{GemmNode,AlgorithmStep};
pub use thread_comm::ThreadInfo;
pub struct TripleLoop{}
impl<T: Scalar, At: Mat<T>, Bt: Mat<T>, Ct: Mat<T>>
GemmNode<T, At, Bt, Ct> for TripleLoop {
unsafe fn run(&mut self, a: &mut At, b: &mut Bt, c: &mut Ct, _thr: &ThreadInfo<T>) ... |
fn hierarchy_description() -> Vec<AlgorithmStep> { Vec::new() }
}
| { TripleLoop{} } | identifier_body |
electrical-generator.js | define(function(require) {
'use strict';
var PIXI = require('pixi');
var EnergyConverterView = require('views/energy-converter');
var Assets = require('assets');
var Constants = require('constants');
var ElectricalGenerator = Constants.ElectricalGenerator;
var ElectricalGeneratorView =... | this.frontLayer.addChild(housing);
this.frontLayer.addChild(connector);
this.frontLayer.addChild(spokes);
this.frontLayer.addChild(paddles);
this.frontLayer.addChild(hub);
this.spokes = spokes;
this.paddles = paddles;
... |
// Need to fudge the position a little...
curvedWire.x += 2;
this.backLayer.addChild(curvedWire); | random_line_split |
loading-mask.js | 'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) |
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _jquery = require('jquery');
var _jquery2 = _interopRequireDefault(_jquery);
require('./loading-mask.css!');
var _locale = require('../locale');
var Loadin... | { return obj && obj.__esModule ? obj : { 'default': obj }; } | identifier_body |
loading-mask.js | 'use strict';
exports.__esModule = true;
function | (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _jquery = require('jquery');
var _jquery2 = _interopRequireDefault(_jquery);
require('./loa... | _interopRequireDefault | identifier_name |
loading-mask.js | 'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _jquery = require('... | function LoadingMask(resources) {
_classCallCheck(this, LoadingMask);
this.loadingMask = undefined;
this.dimScreen = undefined;
this.dialog = undefined;
this.loadingTitle = undefined;
this.title = undefined;
this.locale = _locale.Locale.Repository['default'];
this._createLoadingMask()... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.