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 |
|---|---|---|---|---|
versioncheck.py | """Tool specific version checking to identify out of date dependencies.
This provides infrastructure to check version strings against installed
tools, enabling re-installation if a version doesn't match. This is a
lightweight way to avoid out of date dependencies.
"""
from __future__ import print_function
from distuti... | """Check if the given command is up to date with the provided version.
"""
if shared._executable_not_on_path(cmd):
return False
if args:
cmd = cmd + " " + " ".join(args)
with quiet():
path_safe = ("export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:{s}/lib/pkgconfig && "
... | else:
return LooseVersion(iversion) == LooseVersion(version)
def get_installed_version(env, cmd, version, args=None, stdout_flag=None,
stdout_index=-1): | random_line_split |
versioncheck.py | """Tool specific version checking to identify out of date dependencies.
This provides infrastructure to check version strings against installed
tools, enabling re-installation if a version doesn't match. This is a
lightweight way to avoid out of date dependencies.
"""
from __future__ import print_function
from distuti... |
def is_version(env, cmd, version, args=None, stdout_flag=None,
stdout_index=-1):
iversion = get_installed_version(env, cmd, version, args, stdout_flag,
stdout_index)
if not iversion:
return False
else:
return LooseVersion(iversion) == Loo... | return LooseVersion(iversion) >= LooseVersion(version) | conditional_block |
versioncheck.py | """Tool specific version checking to identify out of date dependencies.
This provides infrastructure to check version strings against installed
tools, enabling re-installation if a version doesn't match. This is a
lightweight way to avoid out of date dependencies.
"""
from __future__ import print_function
from distuti... | (env, cmd, version, args=None, stdout_flag=None,
stdout_index=-1):
"""Check if the given command is up to date with the provided version.
"""
if shared._executable_not_on_path(cmd):
return False
if args:
cmd = cmd + " " + " ".join(args)
with quiet():
... | get_installed_version | identifier_name |
versioncheck.py | """Tool specific version checking to identify out of date dependencies.
This provides infrastructure to check version strings against installed
tools, enabling re-installation if a version doesn't match. This is a
lightweight way to avoid out of date dependencies.
"""
from __future__ import print_function
from distuti... |
def up_to_date(env, cmd, version, args=None, stdout_flag=None,
stdout_index=-1):
iversion = get_installed_version(env, cmd, version, args, stdout_flag,
stdout_index)
if not iversion:
return False
else:
return LooseVersion(iversion) >= Loo... | if x.startswith("upstream/"):
x = x.replace("upstream/", "")
if x.startswith("("):
x = x[1:].strip()
if x.endswith(")"):
x = x[:-1].strip()
if x.startswith("v"):
x = x[1:].strip()
return x | identifier_body |
inspecttarball.py | # ####################################################################
# gofed - set of tools to automize packaging of golang devel codes
# Copyright (C) 2014 Jan Chaloupka, jchaloup@redhat.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public Licen... | if "internal" in ip.split("/"):
continue
if options.spec != False:
if ip != ".":
print "Provides: golang(%%{import_path}/%s) = %%{version}-%%{release}" % (ip)
else:
print "Provides: golang(%{import_path}) = %{version}-%{release}"
elif options.prefix != "":
if ip != ".":
print "%... | # skip all provided packages with /internal/ keyword | random_line_split |
inspecttarball.py | # ####################################################################
# gofed - set of tools to automize packaging of golang devel codes
# Copyright (C) 2014 Jan Chaloupka, jchaloup@redhat.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public Licen... | print "%s/%s" % (options.prefix, ip)
else:
print options.prefix
else:
print ip
elif options.test:
sdirs = sorted(gse_obj.getTestDirectories())
for dir in sdirs:
if options.spec != False:
if dir != ".":
print "go test %%{import_path}/%s" % dir
else:
print "go test %{impor... | skip = False
for prefix in skipped_provides_with_prefix:
if ip.startswith(prefix):
skip = True
break
if skip:
continue
# skip all provided packages with /internal/ keyword
if "internal" in ip.split("/"):
continue
if options.spec != False:
if ip != ".":
print "Provides: g... | conditional_block |
MultiSelectPanel.js | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.MultiSelectPanel = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _reactDom = _interopRequireDefault(require("react-dom"));
var _classnames = _... | (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (super... | _inherits | identifier_name |
MultiSelectPanel.js | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.MultiSelectPanel = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _reactDom = _interopRequireDefault(require("react-dom"));
var _classnames = _... | else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot cal... | { _typeof = function _typeof(obj) { return typeof obj; }; } | conditional_block |
MultiSelectPanel.js | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.MultiSelectPanel = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _reactDom = _interopRequireDefault(require("react-dom"));
var _classnames = _... |
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super =... | { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(... | identifier_body |
MultiSelectPanel.js | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.MultiSelectPanel = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _reactDom = _interopRequireDefault(require("react-dom"));
var _classnames = _... |
return _super.apply(this, arguments);
}
_createClass(MultiSelectPanel, [{
key: "renderElement",
value: function renderElement() {
var _this = this;
var panelClassName = (0, _classnames.default)('p-multiselect-panel p-component', this.props.panelClassName);
return /*#__PURE__*/_react... | random_line_split | |
defaults-bg_BG.js | /*!
* Bootstrap-select v1.13.2 (https://developer.snapappointments.com/bootstrap-select)
*
* Copyright 2012-2018 SnapAppointments, LLC
* Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE)
*/
| return (factory(a0));
});
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require("jquery"));
} else {
factory(root["jQuery... | (function (root, factory) {
if (root === undefined && window !== undefined) root = window;
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module unless amdModuleId is set
define(["jquery"], function (a0) { | random_line_split |
defaults-bg_BG.js | /*!
* Bootstrap-select v1.13.2 (https://developer.snapappointments.com/bootstrap-select)
*
* Copyright 2012-2018 SnapAppointments, LLC
* Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE)
*/
(function (root, factory) {
if (root === undefined && window !== undefi... | else {
factory(root["jQuery"]);
}
}(this, function (jQuery) {
(function ($) {
$.fn.selectpicker.defaults = {
noneSelectedText: 'Нищо избрано',
noneResultsText: 'Няма резултат за {0}',
countSelectedText: function (numSelected, numTotal) {
return (numSelected == 1) ? "{0} избран елемент" ... | {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require("jquery"));
} | conditional_block |
bytes.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 lat... |
}
| {
let deserialized: Bytes = serde_json::from_str(r#""""#).unwrap();
assert_eq!(deserialized, Bytes(Vec::new()));
} | identifier_body |
bytes.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 lat... | struct BytesVisitor;
impl Visitor for BytesVisitor {
type Value = Bytes;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "a 0x-prefixed, hex-encoded vector of bytes")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: Error {
if value.is_empty() {
... | where D: Deserializer {
deserializer.deserialize(BytesVisitor)
}
}
| random_line_split |
bytes.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 lat... | else if value.len() >= 2 && &value[0..2] == "0x" && value.len() & 1 == 0 {
Ok(Bytes::new(FromHex::from_hex(&value[2..]).map_err(|_| Error::custom("invalid hex"))?))
} else {
Err(Error::custom("invalid format"))
}
}
fn visit_string<E>(self, value: String) -> Result<Self::Value, E> where E: Error {
self.v... | {
warn!(
target: "deprecated",
"Deserializing empty string as empty bytes. This is a non-standard behaviour that will be removed in future versions. Please update your code to send `0x` instead!"
);
Ok(Bytes::new(Vec::new()))
} | conditional_block |
bytes.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 lat... | <E>(self, value: String) -> Result<Self::Value, E> where E: Error {
self.visit_str(value.as_ref())
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json;
use rustc_serialize::hex::FromHex;
#[test]
fn test_bytes_serialize() {
let bytes = Bytes("0123456789abcdef".from_hex().unwrap());
let serialized = ... | visit_string | identifier_name |
it.js | tinymce.addI18n('it',{
"Cut": "Taglia",
"Your browser doesn't support direct access to the clipboard. Please use the Ctrl+X\/C\/V keyboard shortcuts instead.": "Il tuo browser non supporta l'accesso diretto negli Appunti. Per favore usa i tasti di scelta rapida Ctrl+X\/C\/V.",
"Paste": "Incolla",
"Close": "Chiudi",
"Al... | "Column group": "Gruppo di Colonne",
"Row": "Riga",
"Insert column before": "Inserisci una Colonna Prima",
"Split cell": "Dividi Cella",
"Cell padding": "Padding della Cella",
"Cell spacing": "Spaziatura della Cella",
"Row type": "Tipo di Riga",
"Insert table": "Inserisci Tabella",
"Body": "Body",
"Caption": "Didascali... | "Height": "Altezza",
"Paste row after": "Incolla una Riga Dopo",
"Alignment": "Allineamento", | random_line_split |
test_server.py | #!/usr/bin/python
# -- Content-Encoding: UTF-8 --
"""
Tests the pooled server
:license: Apache License 2.0
"""
# JSON-RPC library
from jsonrpclib import ServerProxy
from jsonrpclib.SimpleJSONRPCServer import PooledJSONRPCServer
from jsonrpclib.threadpool import ThreadPool
# Standard library
import random
import thre... |
class PooledServerTests(unittest.TestCase):
"""
These tests verify that the pooled server works correctly
"""
def test_default_pool(self, pool=None):
"""
Tests the default pool
"""
# Setup server
server = PooledJSONRPCServer(("localhost", 0), thread_pool=pool)
... | return a+b | identifier_body |
test_server.py | #!/usr/bin/python
# -- Content-Encoding: UTF-8 --
"""
Tests the pooled server
:license: Apache License 2.0
"""
# JSON-RPC library
from jsonrpclib import ServerProxy
from jsonrpclib.SimpleJSONRPCServer import PooledJSONRPCServer
from jsonrpclib.threadpool import ThreadPool
# Standard library
import random
import thre... | (self, pool=None):
"""
Tests the default pool
"""
# Setup server
server = PooledJSONRPCServer(("localhost", 0), thread_pool=pool)
server.register_function(add)
# Serve in a thread
thread = threading.Thread(target=server.serve_forever)
thread.daemo... | test_default_pool | identifier_name |
test_server.py | #!/usr/bin/python
# -- Content-Encoding: UTF-8 --
"""
Tests the pooled server
:license: Apache License 2.0
"""
# JSON-RPC library
from jsonrpclib import ServerProxy
from jsonrpclib.SimpleJSONRPCServer import PooledJSONRPCServer
from jsonrpclib.threadpool import ThreadPool
# Standard library
import random
import thre... |
# Close server
server.server_close()
thread.join()
def test_custom_pool(self):
"""
Tests the ability to have a custom pool
"""
# Setup the pool
pool = ThreadPool(2)
pool.start()
self.test_default_pool(pool)
| a, b = random.random(), random.random()
result = client.add(a, b)
self.assertEqual(result, a+b) | conditional_block |
test_server.py | #!/usr/bin/python
# -- Content-Encoding: UTF-8 --
"""
Tests the pooled server
:license: Apache License 2.0
"""
# JSON-RPC library
from jsonrpclib import ServerProxy
from jsonrpclib.SimpleJSONRPCServer import PooledJSONRPCServer
from jsonrpclib.threadpool import ThreadPool
# Standard library
import random
import thre... | # ------------------------------------------------------------------------------
def add(a, b):
return a+b
class PooledServerTests(unittest.TestCase):
"""
These tests verify that the pooled server works correctly
"""
def test_default_pool(self, pool=None):
"""
Tests the default p... | random_line_split | |
pin.component.ts | import { Component, OnInit } from '@angular/core';
import { Pin, GpioPinGroup } from './pin';
import { PinsApiService } from './pinsapi.service';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'app-pin',
templateUrl: './pin.component.html'... |
return GpioPinGroup[this.pin.pinType];
}
}
| {
return '';
} | conditional_block |
pin.component.ts | import { Component, OnInit } from '@angular/core';
import { Pin, GpioPinGroup } from './pin';
import { PinsApiService } from './pinsapi.service';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'app-pin',
templateUrl: './pin.component.html'... | () {
return this.pin.capabilities.indexOf(0) >= 0;
}
public toggle() {
console.log('toggle');
this.pinapi.toggle(this.pin.wiringPiPinNumber).subscribe(() => { });
}
ngOnInit() {
this.route.params.subscribe(x => {
this.pinapi.getPin(parseInt(x.id)).subscribe(... | isGpio | identifier_name |
pin.component.ts | import { Component, OnInit } from '@angular/core';
import { Pin, GpioPinGroup } from './pin';
import { PinsApiService } from './pinsapi.service';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'app-pin',
templateUrl: './pin.component.html'... | }
return GpioPinGroup[this.pin.pinType];
}
} | }
get pinTypeName() {
if (this.pin == null) {
return ''; | random_line_split |
IfcIndexedColourMap.g.ts |
import {BaseIfc} from "./BaseIfc"
import {IfcTessellatedFaceSet} from "./IfcTessellatedFaceSet.g"
import {IfcNormalisedRatioMeasure} from "./IfcNormalisedRatioMeasure.g"
import {IfcColourRgbList} from "./IfcColourRgbList.g"
import {IfcPositiveInteger} from "./IfcPositiveInteger.g"
import {IfcPresentationItem} from "./... | (mappedTo : IfcTessellatedFaceSet, colours : IfcColourRgbList, colourIndex : Array<IfcPositiveInteger>) {
super()
this.MappedTo = mappedTo
this.Colours = colours
this.ColourIndex = colourIndex
}
getStepParameters() : string {
var parameters = new Array<string>();
parameters.push(BaseIfc... | constructor | identifier_name |
IfcIndexedColourMap.g.ts | import {BaseIfc} from "./BaseIfc"
import {IfcTessellatedFaceSet} from "./IfcTessellatedFaceSet.g"
import {IfcNormalisedRatioMeasure} from "./IfcNormalisedRatioMeasure.g"
import {IfcColourRgbList} from "./IfcColourRgbList.g"
import {IfcPositiveInteger} from "./IfcPositiveInteger.g"
import {IfcPresentationItem} from "./I... | this.ColourIndex = colourIndex
}
getStepParameters() : string {
var parameters = new Array<string>();
parameters.push(BaseIfc.toStepValue(this.MappedTo))
parameters.push(BaseIfc.toStepValue(this.Opacity))
parameters.push(BaseIfc.toStepValue(this.Colours))
parameters.push(BaseIfc.toStepValue(t... | constructor(mappedTo : IfcTessellatedFaceSet, colours : IfcColourRgbList, colourIndex : Array<IfcPositiveInteger>) {
super()
this.MappedTo = mappedTo
this.Colours = colours | random_line_split |
emailutil.py | # Some useful functions to extract data out of emails | # the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# ... | # Copyright (C) 2002-2012 John Goerzen & 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 | random_line_split |
emailutil.py | # Some useful functions to extract data out of emails
# Copyright (C) 2002-2012 John Goerzen & 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 2 of the Lic... | """
Parses mail and returns resulting timestamp.
:param header: the header to extract date from;
:returns: timestamp or `None` in the case of failure.
"""
message = MailParser().parsestr(content, True)
dateheader = message.get(header)
# parsedate_tz returns a 10-tuple that can be passe... | identifier_body | |
emailutil.py | # Some useful functions to extract data out of emails
# Copyright (C) 2002-2012 John Goerzen & 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 2 of the Lic... |
return email.utils.mktime_tz(datetuple)
| return None | conditional_block |
emailutil.py | # Some useful functions to extract data out of emails
# Copyright (C) 2002-2012 John Goerzen & 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 2 of the Lic... | (content, header='Date'):
"""
Parses mail and returns resulting timestamp.
:param header: the header to extract date from;
:returns: timestamp or `None` in the case of failure.
"""
message = MailParser().parsestr(content, True)
dateheader = message.get(header)
# parsedate_tz return... | get_message_date | identifier_name |
console.rs | use front::stdlib::value::{Value, ResultValue, to_value, from_value};
use front::stdlib::function::Function;
use std::io::stdio::stderr;
use time::{now, strftime};
/// Print a javascript value to the standard output stream
pub fn log(args:Vec<Value>, _:Value, _:Value, _:Value) -> ResultValue {
let args : Vec<String... | (args:Vec<Value>, _:Value, _:Value, _:Value) -> ResultValue {
let args : Vec<String> = args.iter().map(|x|from_value::<String>(*x).unwrap()).collect();
match writeln!(&mut stderr().unwrap(), "{}: {}", strftime("%X", &now()), args.connect(" ")) {
Ok(_) => Ok(Value::undefined()),
Err(io_error) => ... | error | identifier_name |
console.rs | use front::stdlib::value::{Value, ResultValue, to_value, from_value};
use front::stdlib::function::Function;
use std::io::stdio::stderr;
use time::{now, strftime};
/// Print a javascript value to the standard output stream
pub fn log(args:Vec<Value>, _:Value, _:Value, _:Value) -> ResultValue {
let args : Vec<String... |
/// Create a new `console` object
pub fn _create(global : Value) -> Value {
js!(global, {
"log": Function::make(log, ["object"]),
"error": Function::make(error, ["error"]),
"exception": Function::make(error, ["error"])
})
}
/// Initialise the global object with the `console` object
pub ... | {
let args : Vec<String> = args.iter().map(|x|from_value::<String>(*x).unwrap()).collect();
match writeln!(&mut stderr().unwrap(), "{}: {}", strftime("%X", &now()), args.connect(" ")) {
Ok(_) => Ok(Value::undefined()),
Err(io_error) => Err(to_value(io_error.to_string()))
}
} | identifier_body |
console.rs | use front::stdlib::function::Function;
use std::io::stdio::stderr;
use time::{now, strftime};
/// Print a javascript value to the standard output stream
pub fn log(args:Vec<Value>, _:Value, _:Value, _:Value) -> ResultValue {
let args : Vec<String> = args.iter().map(|x|from_value::<String>(*x).unwrap()).collect();
... | use front::stdlib::value::{Value, ResultValue, to_value, from_value}; | random_line_split | |
models.py | import datetime
from django.conf import settings
from django.db import models
from django.template.defaultfilters import slugify
from django.utils import timezone
from blogtools.utils.embargo import EmbargoedContent, EmbargoedContentPublicManager, EmbargoedContentPrivateManager
#TODO, put this in glamkit somewhere.
... |
# by default, inheriting models assume the url namespace == the app_label.
# If you define another namespace, then either copy it to the url_namespace
# attribute here, or override get_absolute_url
url_namespace = ''
@models.permalink
def get_absolute_url(self):
# NB that URLs need exa... | return self.title | identifier_body |
models.py | import datetime
from django.conf import settings
from django.db import models
from django.template.defaultfilters import slugify
from django.utils import timezone
from blogtools.utils.embargo import EmbargoedContent, EmbargoedContentPublicManager, EmbargoedContentPrivateManager
#TODO, put this in glamkit somewhere.
... |
objects = models.Manager()
public_objects = EmbargoedContentPublicManager()
private_objects = EmbargoedContentPrivateManager()
section_title = "Blog"
class Meta:
verbose_name = "entry"
verbose_name_plural = "entries"
ordering = ['-byline_date',]
abstract = True
... | """
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=255, unique=True)
author = models.ForeignKey(user_model, related_name='%(app_label)s_entries', blank=True, null=True)
byline_date = models.DateTimeField(default=timezone.now) | random_line_split |
models.py | import datetime
from django.conf import settings
from django.db import models
from django.template.defaultfilters import slugify
from django.utils import timezone
from blogtools.utils.embargo import EmbargoedContent, EmbargoedContentPublicManager, EmbargoedContentPrivateManager
#TODO, put this in glamkit somewhere.
... | (self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
# Append the pk to slugs which have a collision with a pre-existing slug.
if type(self).objects.filter(slug=self.slug).exclude(pk=self.pk).exists():
self.slug = '%s-%s' % (self.slug, slugify(self.p... | save | identifier_name |
models.py | import datetime
from django.conf import settings
from django.db import models
from django.template.defaultfilters import slugify
from django.utils import timezone
from blogtools.utils.embargo import EmbargoedContent, EmbargoedContentPublicManager, EmbargoedContentPrivateManager
#TODO, put this in glamkit somewhere.
... |
super(EntryModel, self).save(*args, **kwargs)
def get_content(self):
return getattr(self, 'content', "")
def get_summary(self):
summary = getattr(self, 'summary')
if not summary:
return self.get_content()
return summary
class CommentedItemModel(models.Mod... | self.slug = '%s-%s' % (self.slug, slugify(self.pk)) | conditional_block |
index.ts | /**
* Copyright 2020 Google LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. | * https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language govern... | * You may obtain a copy of the License at
* | random_line_split |
Transport.ts | import {BrowserHeaders} from "browser-headers";
import fetchRequest from "./fetch";
import xhrRequest from "./xhr";
import msStreamRequest from "./msStream";
declare const Response: any;
declare const Headers: any;
export interface Transport {
(options: TransportOptions): void;
}
export type TransportOptions = {
... |
try {
xhr.responseType = type;
return xhr.responseType === type;
} catch (e) {}
return false
}
export class DefaultTransportFactory {
static selected: Transport;
static getTransport(): Transport {
if (!this.selected) {
this.selected = DefaultTransportFactory.detectTransport();
}
re... | {
return false;
} | conditional_block |
Transport.ts | import {BrowserHeaders} from "browser-headers";
import fetchRequest from "./fetch";
import xhrRequest from "./xhr";
import msStreamRequest from "./msStream";
declare const Response: any;
declare const Headers: any;
export interface Transport {
(options: TransportOptions): void;
}
export type TransportOptions = {
... | () {
if (typeof Response !== "undefined" && Response.prototype.hasOwnProperty("body") && typeof Headers === "function") {
return fetchRequest;
}
if (xhrSupportsResponseType("ms-stream")) {
return msStreamRequest;
}
return xhrRequest;
}
} | detectTransport | identifier_name |
Transport.ts | import {BrowserHeaders} from "browser-headers";
import fetchRequest from "./fetch";
import xhrRequest from "./xhr";
import msStreamRequest from "./msStream";
declare const Response: any;
declare const Headers: any;
export interface Transport {
(options: TransportOptions): void;
}
export type TransportOptions = {
... | } catch(e) {}
}
return xhr
}
function xhrSupportsResponseType(type: string) {
const xhr = getXHR();
if (!xhr) {
return false;
}
try {
xhr.responseType = type;
return xhr.responseType === type;
} catch (e) {}
return false
}
export class DefaultTransportFactory {
static selected: Trans... | xhr = new XMLHttpRequest();
try {
xhr.open('GET', 'https://localhost') | random_line_split |
Transport.ts | import {BrowserHeaders} from "browser-headers";
import fetchRequest from "./fetch";
import xhrRequest from "./xhr";
import msStreamRequest from "./msStream";
declare const Response: any;
declare const Headers: any;
export interface Transport {
(options: TransportOptions): void;
}
export type TransportOptions = {
... |
static detectTransport() {
if (typeof Response !== "undefined" && Response.prototype.hasOwnProperty("body") && typeof Headers === "function") {
return fetchRequest;
}
if (xhrSupportsResponseType("ms-stream")) {
return msStreamRequest;
}
return xhrRequest;
}
} | {
if (!this.selected) {
this.selected = DefaultTransportFactory.detectTransport();
}
return this.selected;
} | identifier_body |
CloudFoundryRecentLogs.tsx | import { bindAll } from 'lodash';
import React from 'react';
import { Button, Modal } from 'react-bootstrap';
import type { IInstanceConsoleOutput } from '@spinnaker/core';
import { InstanceReader } from '@spinnaker/core';
export enum CloudFoundryRecentLogsType {
APP = 'app',
TASK = 'task',
}
export interface IC... | public onClick() {
const { account, region } = this.props;
InstanceReader.getConsoleOutput(account, region, this.generateResourceId(), 'cloudfoundry')
.then((response: IInstanceConsoleOutput) => {
this.setState({
logs: response.output as string,
});
this.open();
}... | random_line_split | |
CloudFoundryRecentLogs.tsx | import { bindAll } from 'lodash';
import React from 'react';
import { Button, Modal } from 'react-bootstrap';
import type { IInstanceConsoleOutput } from '@spinnaker/core';
import { InstanceReader } from '@spinnaker/core';
export enum CloudFoundryRecentLogsType {
APP = 'app',
TASK = 'task',
}
export interface IC... |
public render() {
const { showModal, logs, errorMessage } = this.state;
if (this.canShow()) {
return (
<div>
<a onClick={this.onClick} className="clickable">
Recent
</a>
<Modal show={showModal} onHide={this.close} dialogClassName="modal-lg modal-fullsc... | {
const { account, region } = this.props;
InstanceReader.getConsoleOutput(account, region, this.generateResourceId(), 'cloudfoundry')
.then((response: IInstanceConsoleOutput) => {
this.setState({
logs: response.output as string,
});
this.open();
})
.catch((exc... | identifier_body |
CloudFoundryRecentLogs.tsx | import { bindAll } from 'lodash';
import React from 'react';
import { Button, Modal } from 'react-bootstrap';
import type { IInstanceConsoleOutput } from '@spinnaker/core';
import { InstanceReader } from '@spinnaker/core';
export enum CloudFoundryRecentLogsType {
APP = 'app',
TASK = 'task',
}
export interface IC... | () {
this.setState({ showModal: false });
}
public open() {
this.setState({ showModal: true });
}
public onClick() {
const { account, region } = this.props;
InstanceReader.getConsoleOutput(account, region, this.generateResourceId(), 'cloudfoundry')
.then((response: IInstanceConsoleOutput... | close | identifier_name |
progressevent.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindi... | );
{
let event = ev.upcast::<Event>();
event.init_event(type_, bool::from(can_bubble), bool::from(cancelable));
}
ev
}
pub fn Constructor(
global: &GlobalScope,
type_: DOMString,
init: &ProgressEventBinding::ProgressEventInit,
)... | )),
global,
ProgressEventBinding::Wrap, | random_line_split |
progressevent.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindi... |
pub fn new(
global: &GlobalScope,
type_: Atom,
can_bubble: EventBubbles,
cancelable: EventCancelable,
length_computable: bool,
loaded: u64,
total: u64,
) -> DomRoot<ProgressEvent> {
let ev = reflect_dom_object(
Box::new(ProgressEvent::... | {
reflect_dom_object(
Box::new(ProgressEvent::new_inherited(false, 0, 0)),
global,
ProgressEventBinding::Wrap,
)
} | identifier_body |
progressevent.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindi... | (&self) -> u64 {
self.loaded
}
// https://xhr.spec.whatwg.org/#dom-progressevent-total
fn Total(&self) -> u64 {
self.total
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
| Loaded | identifier_name |
08-maybe-and-optionals.js | /* @flow */
import assert from 'assert';
import { CONVERSION_TABLE } from './06-export';
import type { Unit, UnitValue } from './06-export';
// We didn't cover any edge cases yet, so let's do this now
export function | (from: Unit, to: Unit, value: number): ?number {
if (from === to) {
return value;
}
// If there is no conversion possible, return null
// Note how we are using '== null' instead of '=== null'
// because the first notation will cover both cases, 'null'
// and 'undefined', which spares us a lot of extra ... | convertUnit | identifier_name |
08-maybe-and-optionals.js | /* @flow */
import assert from 'assert';
import { CONVERSION_TABLE } from './06-export';
import type { Unit, UnitValue } from './06-export';
// We didn't cover any edge cases yet, so let's do this now
export function convertUnit(from: Unit, to: Unit, value: number): ?number |
// Intersection Type for assuming unit to be 'm'
// unit cannot be anything but a `Unit`, so we even
// prevent errors on definition
type MeterUnitValue = {
unit: 'm'
} & UnitValue;
// Convert whole UnitValues instead of single values
function convertToKm(unitValue: MeterUnitValue): ?UnitValue {
const { unit, va... | {
if (from === to) {
return value;
}
// If there is no conversion possible, return null
// Note how we are using '== null' instead of '=== null'
// because the first notation will cover both cases, 'null'
// and 'undefined', which spares us a lot of extra code.
// You will need to set eslint's 'eqeqe... | identifier_body |
08-maybe-and-optionals.js | /* @flow */
import assert from 'assert';
import { CONVERSION_TABLE } from './06-export';
import type { Unit, UnitValue } from './06-export';
// We didn't cover any edge cases yet, so let's do this now
export function convertUnit(from: Unit, to: Unit, value: number): ?number {
if (from === to) {
return value;
... | // prevent errors on definition
type MeterUnitValue = {
unit: 'm'
} & UnitValue;
// Convert whole UnitValues instead of single values
function convertToKm(unitValue: MeterUnitValue): ?UnitValue {
const { unit, value } = unitValue;
const converted = convertUnit(unit, 'km', value);
if (converted == null) {
... | random_line_split | |
08-maybe-and-optionals.js | /* @flow */
import assert from 'assert';
import { CONVERSION_TABLE } from './06-export';
import type { Unit, UnitValue } from './06-export';
// We didn't cover any edge cases yet, so let's do this now
export function convertUnit(from: Unit, to: Unit, value: number): ?number {
if (from === to) {
return value;
... |
return {
unit: 'km',
value: converted,
}
}
const value = convertToKm({ unit: 'm', value: 1500 });
assert.deepEqual(value, { unit: 'km', value: 1.5 });
| {
return null;
} | conditional_block |
HeaderResizer.js | use the last visible leaf header of the locked side.
if (!resizeHeader && ownerLockable && !ownerGrid.isLocked) {
headers = ownerLockable.lockedGrid.headerCt.visibleColumnManager.getColumns();
resizeHeader = headers[headers.length - 1];
}
... | {
tracker.enable();
} | conditional_block | |
HeaderResizer.js | ),
tolerance: 3,
autoStart: 300,
el: el
});
},
// As we mouse over individual headers, change the cursor to indicate
// that resizing is available, and cache the resize target header for use
// if/when they mousedown.
onHeaderCtMouseMove: function(e) {
... |
doResize: function() {
var me = this, | random_line_split | |
res_users.py | # -*- encoding: utf-8 -*-
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2014 Savoir-faire Linux
# (<http://www.savoirfairelinux.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import logging
from openerp.osv import... | # published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of | random_line_split |
res_users.py | # -*- encoding: utf-8 -*-
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2014 Savoir-faire Linux
# (<http://www.savoirfairelinux.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# ... | _inherit = "res.users"
_columns = {
'xis_user_external_id': fields.integer('XIS external user',
required=True),
} | identifier_body | |
res_users.py | # -*- encoding: utf-8 -*-
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2014 Savoir-faire Linux
# (<http://www.savoirfairelinux.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# ... | (osv.osv):
_inherit = "res.users"
_columns = {
'xis_user_external_id': fields.integer('XIS external user',
required=True),
}
| res_users | identifier_name |
create_file.py | #!/usr/bin/env python
#to create a file in codesnippets folder
import pyperclip
import os
import re
import subprocess
def get_extension(file_name):
if file_name.find('.')!=-1:
ext = file_name.split('.')
return (ext[1])
else:
return 'txt'
def cut(str, len1):
return str[len1 + ... |
try:
# code_snippets is the head folder
if not os.path.exists('/home/nikhil/code_snippets'):
os.makedirs('/home/nikhil/code_snippets') # creating the directory if not exists
extension = get_extension(file_name)
# creating a folder with res... | if re.search(r'\w+\.[a-z,A-Z]',str_lower[0])==None:
sendmessage("SPECIFY FILEEXTENSION (default file type is txt)")
str1 = str.split('\n')
str2 = str1[0].split(' ')
length = len(str2)
file_name = str2[length - 2]
new_str = cut(str, len(str1[0]))
# unti... | conditional_block |
create_file.py | #!/usr/bin/env python
#to create a file in codesnippets folder
import pyperclip
import os
import re
import subprocess
def get_extension(file_name):
if file_name.find('.')!=-1:
ext = file_name.split('.')
return (ext[1])
else:
return 'txt'
def cut(str, len1): | return str[len1 + 1:] #to remove first line which is meant for reading from which file
#for displaying contents
def find(name, path):
for root, dirs, files in os.walk(path):
if name in files:
return os.path.join(root, name)
#ubuntu notification (message sending)
def sendmessage(messag... | random_line_split | |
create_file.py | #!/usr/bin/env python
#to create a file in codesnippets folder
import pyperclip
import os
import re
import subprocess
def get_extension(file_name):
if file_name.find('.')!=-1:
ext = file_name.split('.')
return (ext[1])
else:
return 'txt'
def | (str, len1):
return str[len1 + 1:] #to remove first line which is meant for reading from which file
#for displaying contents
def find(name, path):
for root, dirs, files in os.walk(path):
if name in files:
return os.path.join(root, name)
#ubuntu notification (message sending)
def sendm... | cut | identifier_name |
create_file.py | #!/usr/bin/env python
#to create a file in codesnippets folder
import pyperclip
import os
import re
import subprocess
def get_extension(file_name):
|
def cut(str, len1):
return str[len1 + 1:] #to remove first line which is meant for reading from which file
#for displaying contents
def find(name, path):
for root, dirs, files in os.walk(path):
if name in files:
return os.path.join(root, name)
#ubuntu notification (message sending)... | if file_name.find('.')!=-1:
ext = file_name.split('.')
return (ext[1])
else:
return 'txt' | identifier_body |
0072_auto_20180502_0834.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-05-02 08:34
from __future__ import unicode_literals
import dirtyfields.dirtyfields
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.db.models.manager
class Migration(migrations.Migrati... | ('timesheet', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='ninetofiver.Timesheet')),
],
options={
'ordering': ['id'],
'abstract': False,
'base_manager_name': 'base_objects',
},
bases=(di... | ('ends_at', models.DateTimeField()),
('polymorphic_ctype', models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='polymorphic_ninetofiver.whereaboutdate_set+', to='contenttypes.ContentType')), | random_line_split |
0072_auto_20180502_0834.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-05-02 08:34
from __future__ import unicode_literals
import dirtyfields.dirtyfields
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.db.models.manager
class | (migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('contenttypes', '0002_remove_content_type_name'),
('ninetofiver', '0071_apikey_name'),
]
operations = [
migrations.CreateModel(
name='WhereaboutDate',
... | Migration | identifier_name |
0072_auto_20180502_0834.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-05-02 08:34
from __future__ import unicode_literals
import dirtyfields.dirtyfields
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.db.models.manager
class Migration(migrations.Migrati... | 'abstract': False,
'base_manager_name': 'base_objects',
},
bases=(dirtyfields.dirtyfields.DirtyFieldsMixin, models.Model),
managers=[
('objects', django.db.models.manager.Manager()),
('base_objects', django.db.models.man... | dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('contenttypes', '0002_remove_content_type_name'),
('ninetofiver', '0071_apikey_name'),
]
operations = [
migrations.CreateModel(
name='WhereaboutDate',
fields=[
('... | identifier_body |
wet-shark-and-42.py | # Enter your code here. Read input from STDIN. Print output to STDOUT
t = int(raw_input())
for i in range(t):
MOD = 10**9 + 7
s = int(input())
k = s/20
rem = s%20
if rem == 0:
print (42*k - 2)%MOD
else:
print (42*k + 2*rem)%MOD
# The following code times out on ... | #
# s = int(raw_input())%(10**9 + 7)
# # k = s/20
# # square = 2*s + k
# square = 0
# while s != 0:
# square += 1
# if square%2 == 0 and square%42 != 0:
# s -= 1
# print "square = " + str(square) + " s = " + str(s)
# print square | # but I think it works
| random_line_split |
wet-shark-and-42.py | # Enter your code here. Read input from STDIN. Print output to STDOUT
t = int(raw_input())
for i in range(t):
|
# print "square = " + str(square) + " s = " + str(s)
# print square
| MOD = 10**9 + 7
s = int(input())
k = s/20
rem = s%20
if rem == 0:
print (42*k - 2)%MOD
else:
print (42*k + 2*rem)%MOD
# The following code times out on the tests
# but I think it works
#
# s = int(raw_input())%(10**9 + 7)
# # k = s/20
# # square = 2*s +... | conditional_block |
intrinsic_3dlut.rs | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by app... | gDims.y = rsAllocationGetDimY(gCube);
gDims.z = rsAllocationGetDimZ(gCube);
gDims.w = 0;
gCoordMul = (float4)(1.f / 255.f) * convert_float4(gDims - 1);
}
uchar4 __attribute__((kernel)) root(uchar4 in) {
float4 baseCoord = convert_float4(in) * gCoordMul;
int4 coord1 = convert_int4(floor(baseCoor... |
void setCube(rs_allocation c) {
gCube = c;
gDims.x = rsAllocationGetDimX(gCube); | random_line_split |
processor.py | import json
import shapely.wkb
import shapely.geometry
import shapely.ops
import codecs
import os
import inspect
from osgeo import ogr
from osgeo import osr
infile = "/Users/kirilllebedev/Maps/ne_110m_admin_0_map_units/ne_110m_admin_0_map_units.shp"
outfile = "/Users/kirilllebedev/Maps/continents_wb/continents_wb.shp"... |
shp_ds = shp_driver.CreateDataSource( outfile )
shp_layer = shp_ds.CreateLayer( in_defn.GetName(),
geom_type = in_defn.GetGeomType(),
srs = in_layer.GetSpatialRef() )
fd = ogr.FieldDefn( 'code', 4 )
fd.SetWidth( 5 )
shp_layer.CreateField( fd )
fd = ogr.... | shp_driver.DeleteDataSource( outfile ) | conditional_block |
processor.py | import json
import shapely.wkb
import shapely.geometry
import shapely.ops
import codecs
import os
import inspect
from osgeo import ogr
from osgeo import osr
infile = "/Users/kirilllebedev/Maps/ne_110m_admin_0_map_units/ne_110m_admin_0_map_units.shp"
outfile = "/Users/kirilllebedev/Maps/continents_wb/continents_wb.shp"... |
shp_driver = ogr.GetDriverByName( 'ESRI Shapefile' )
if os.path.exists( outfile ):
shp_driver.DeleteDataSource( outfile )
shp_ds = shp_driver.CreateDataSource( outfile )
shp_layer = shp_ds.CreateLayer( in_defn.GetName(),
geom_type = in_defn.GetGeomType(),
... | in_defn = in_layer.GetLayerDefn() | random_line_split |
test_local_bindings.py | assert m.load_external2(cm.ExternalType2(22)) == 22
with pytest.raises(TypeError) as excinfo:
assert m.load_external2(cm.ExternalType1(21)) == 21
assert "incompatible function arguments" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
assert m.load_external1(cm.ExternalTyp... | v2.append(cm.LocalType(2))
# Returning the self pointer should get picked up as returning an existing
# instance (even when that instance is of a foreign, non-local type).
assert m.return_self(v1) is v1
assert cm.return_self(v2) is v2
assert m.return_self(v2) is v2
assert cm.return_self(v1)... | random_line_split | |
test_local_bindings.py | assert m.load_external2(cm.ExternalType2(22)) == 22
with pytest.raises(TypeError) as excinfo:
assert m.load_external2(cm.ExternalType1(21)) == 21
assert "incompatible function arguments" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
assert m.load_external1(cm.ExternalTyp... |
def test_mixed_local_global():
"""Local types take precedence over globally registered types: a module with a `module_local`
type can be registered even if the type is already registered globally. With the module,
casting will go to the local type; outside the module casting goes to the global type."""
... | import pybind11_cross_module_tests as cm
with pytest.raises(RuntimeError) as excinfo:
cm.register_nonlocal_map()
assert str(excinfo.value) == 'generic_type: type "NonLocalMap" is already registered!'
with pytest.raises(RuntimeError) as excinfo:
cm.register_nonlocal_vec()
assert str(exc... | identifier_body |
test_local_bindings.py | assert m.load_external2(cm.ExternalType2(22)) == 22
with pytest.raises(TypeError) as excinfo:
assert m.load_external2(cm.ExternalType1(21)) == 21
assert "incompatible function arguments" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
assert m.load_external1(cm.ExternalTyp... | ():
"""Tests that attempting to register a non-local type in multiple modules fails"""
import pybind11_cross_module_tests as cm
with pytest.raises(RuntimeError) as excinfo:
cm.register_nonlocal()
assert str(excinfo.value) == 'generic_type: type "NonLocalType" is already registered!'
def test_... | test_nonlocal_failure | identifier_name |
get_software_catalogue.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
#
# This file is part of FI-WARE project.
#
# 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 Li... | from xml.dom.minidom import parse, parseString
from xml.dom.minidom import getDOMImplementation
from xml.etree.ElementTree import Element, SubElement, tostring
import md5
import httplib, urllib
import utils
token = utils.obtainToken(keystone_ip, keystone_port, user, password, project)
print(token)
headers = {'Conte... | random_line_split | |
fs.rs | extern crate fuse;
extern crate libc;
extern crate slice_cast;
extern crate time;
use backend::Backend;
use self::libc::c_int;
use wfs::entry::FileEntry;
/// Number of total blocks in FS
const TOTAL_BLOCKS: usize = 16834;
/// Block indicating end of data
const BLOCK_FINAL: u16 = 0xfffe;
/// Block indicating no such b... |
fn read_dir<'a>(&self, data: &'a[u8]) -> &'a[FileEntry] {
unsafe { slice_cast::cast(&data) }
}
fn chain_length(&self, ino: u64) -> usize {
let mut i: usize = 0;
let mut cur = ino as usize;
while self.fat[cur - 2] != BLOCK_FINAL {
cur = self.fat[cur - 2] as usize... | }
Ok(())
} | random_line_split |
fs.rs | extern crate fuse;
extern crate libc;
extern crate slice_cast;
extern crate time;
use backend::Backend;
use self::libc::c_int;
use wfs::entry::FileEntry;
/// Number of total blocks in FS
const TOTAL_BLOCKS: usize = 16834;
/// Block indicating end of data
const BLOCK_FINAL: u16 = 0xfffe;
/// Block indicating no such b... | (&mut self, _req: &fuse::Request, ino: u64, reply: fuse::ReplyAttr) {
match ino {
1 => {
reply.attr(&TTL_TIMESEC, &self.produce_dir_attr(ino));
}
_ => reply.error(libc::ENOENT),
};
}
/**
* Check the availability of file system resouces.
... | getattr | identifier_name |
fs.rs | extern crate fuse;
extern crate libc;
extern crate slice_cast;
extern crate time;
use backend::Backend;
use self::libc::c_int;
use wfs::entry::FileEntry;
/// Number of total blocks in FS
const TOTAL_BLOCKS: usize = 16834;
/// Block indicating end of data
const BLOCK_FINAL: u16 = 0xfffe;
/// Block indicating no such b... |
Ok(())
}
/**
* Load the File Allocation Table into memory
*/
fn load_fat(&mut self) -> Result<(), c_int> {
unsafe {
let block_buf: &mut[u8] = slice_cast::cast_mut(&mut self.fat);
if let Err(_) = self.backend.read(BLOCK_TABLE_OFFSET, block_buf) {
... | {
// Panic because this method cannot return error states.
panic!("Invalid magic number");
} | conditional_block |
fs.rs | extern crate fuse;
extern crate libc;
extern crate slice_cast;
extern crate time;
use backend::Backend;
use self::libc::c_int;
use wfs::entry::FileEntry;
/// Number of total blocks in FS
const TOTAL_BLOCKS: usize = 16834;
/// Block indicating end of data
const BLOCK_FINAL: u16 = 0xfffe;
/// Block indicating no such b... |
fn chain_length(&self, ino: u64) -> usize {
let mut i: usize = 0;
let mut cur = ino as usize;
while self.fat[cur - 2] != BLOCK_FINAL {
cur = self.fat[cur - 2] as usize;
i += 1;
}
return i;
}
fn produce_dir_attr(&self, ino: u64) -> fuse::Fil... | {
unsafe { slice_cast::cast(&data) }
} | identifier_body |
layout_attributes.js | /**
* Copyright 2012-2016, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = {
barmode: {
valType: 'enumerated',
values: ['stack', 'group', 'overlay', ... | role: 'style',
description: [
'Sets the gap (in plot fraction) between bars of',
'adjacent location coordinates.'
].join(' ')
},
bargroupgap: {
valType: 'number',
min: 0,
max: 1,
dflt: 0,
role: 'style',
description: ... | max: 1, | random_line_split |
test_add.py | # (C) British Crown Copyright 2014, Met Office
#
# This file is part of Iris.
#
# Iris 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
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later ve... | (tests.IrisTest, CubeArithmeticMaskingTestMixin):
@property
def data_op(self):
return operator.add
@property
def cube_func(self):
return add
if __name__ == "__main__":
tests.main()
| TestMasking | identifier_name |
test_add.py | # (C) British Crown Copyright 2014, Met Office
#
# This file is part of Iris.
#
# Iris 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
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later ve... |
@property
def cube_func(self):
return add
class TestMasking(tests.IrisTest, CubeArithmeticMaskingTestMixin):
@property
def data_op(self):
return operator.add
@property
def cube_func(self):
return add
if __name__ == "__main__":
tests.main()
| return operator.add | identifier_body |
test_add.py | # (C) British Crown Copyright 2014, Met Office
#
# This file is part of Iris.
#
# Iris 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
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later ve... |
from iris.analysis.maths import add
from iris.tests.unit.analysis.maths import \
CubeArithmeticBroadcastingTestMixin, CubeArithmeticMaskingTestMixin
class TestBroadcasting(tests.IrisTest, CubeArithmeticBroadcastingTestMixin):
@property
def data_op(self):
return operator.add
@property
def... | random_line_split | |
test_add.py | # (C) British Crown Copyright 2014, Met Office
#
# This file is part of Iris.
#
# Iris 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
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later ve... | tests.main() | conditional_block | |
edit-question-modal.component.ts | import { Component, OnInit,Input, Output, OnChanges, EventEmitter } from '@angular/core';
import { Inject } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';
@Component({
selector: 'app-edit-question-modal',
templateUrl: './edit-question-modal.component.html'... | ]
})
export class EditQuestionModalComponent implements OnInit {
@Input() closable = true;
@Input() visible: boolean;
@Output() visibleChange: EventEmitter<boolean> = new EventEmitter<boolean>();
constructor() { }
ngOnInit() { }
close() {
this.visible = false;
this.visibleChange.emit(this.visi... | ])
]) | random_line_split |
edit-question-modal.component.ts | import { Component, OnInit,Input, Output, OnChanges, EventEmitter } from '@angular/core';
import { Inject } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';
@Component({
selector: 'app-edit-question-modal',
templateUrl: './edit-question-modal.component.html'... | () { }
close() {
this.visible = false;
this.visibleChange.emit(this.visible);
}
}
| ngOnInit | identifier_name |
0001_initial.py | # Generated by Django 3.0.7 on 2020-09-27 13:39
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| ),
]
| initial = True
dependencies = [
('edegal', '0025_photographer_flickr_handle'),
]
operations = [
migrations.CreateModel(
name='LarppikuvatPhotographerProfile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verb... | identifier_body |
0001_initial.py | # Generated by Django 3.0.7 on 2020-09-27 13:39
from django.db import migrations, models
import django.db.models.deletion
class | (migrations.Migration):
initial = True
dependencies = [
('edegal', '0025_photographer_flickr_handle'),
]
operations = [
migrations.CreateModel(
name='LarppikuvatPhotographerProfile',
fields=[
('id', models.AutoField(auto_created=True, primary_ke... | Migration | identifier_name |
0001_initial.py | # Generated by Django 3.0.7 on 2020-09-27 13:39
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
|
operations = [
migrations.CreateModel(
name='LarppikuvatPhotographerProfile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('contact', models.TextField(blank=True)),
('hour... | initial = True
dependencies = [
('edegal', '0025_photographer_flickr_handle'),
] | random_line_split |
app.js | 'use strict';
var gulp = require('gulp'),
path = require('path'),
del = require('del'),
sourcemaps = require('gulp-sourcemaps'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
rev = require('gulp-rev'),
sourcemaps = require('gulp-sourcemaps'),
annotate = require('gulp-ng-annotate'),
... | gulp.task('app:js', false, ['app:clean', 'app:templates'], function() {
return gulp.src(['src/**/*.js', 'build/templates.js'])
.pipe(sourcemaps.init())
.pipe(concat({ path: 'app.js', cwd: '.' }))
.pipe(annotate())
.pipe(uglify())
.pipe(rev())
.pipe(sourcemaps.write('.', { sourceRoot: 'src' }))
.pipe(gu... | .pipe(gulp.dest('build'));
});
| random_line_split |
raster.rs | //! Path rasterization.
use crate::{gpu::GpuVertex, Result, P2};
use lyon_path::Builder;
use lyon_tessellation::{
BuffersBuilder, FillAttributes, FillOptions, FillTessellator, LineJoin, StrokeAttributes,
StrokeOptions, StrokeTessellator, VertexBuffers,
};
use palette::LinSrgba;
/// The method by which the ras... | (
builder: Builder,
method: Method,
color: LinSrgba,
) -> Result<(Vec<GpuVertex>, Vec<u32>)> {
match method {
Method::Fill => {
let ctor = |v: P2, _: FillAttributes| -> P2 { v };
let mut buffers: VertexBuffers<P2, u32> = VertexBuffers::new();
let mut buffers_b... | raster_path | identifier_name |
raster.rs | //! Path rasterization.
use crate::{gpu::GpuVertex, Result, P2};
use lyon_path::Builder;
use lyon_tessellation::{
BuffersBuilder, FillAttributes, FillOptions, FillTessellator, LineJoin, StrokeAttributes,
StrokeOptions, StrokeTessellator, VertexBuffers,
};
use palette::LinSrgba;
/// The method by which the ras... | .expect("TODO: wrap error");
Ok((
buffers
.vertices
.into_iter()
.map(|v| GpuVertex {
vpos: [v.x, v.y],
vcol: [
color.color.red,
... | .with_tolerance(0.05),
&mut buffers_builder,
) | random_line_split |
raster.rs | //! Path rasterization.
use crate::{gpu::GpuVertex, Result, P2};
use lyon_path::Builder;
use lyon_tessellation::{
BuffersBuilder, FillAttributes, FillOptions, FillTessellator, LineJoin, StrokeAttributes,
StrokeOptions, StrokeTessellator, VertexBuffers,
};
use palette::LinSrgba;
/// The method by which the ras... | .vertices
.into_iter()
.map(|v| GpuVertex {
vpos: [v.x, v.y],
vcol: [
color.color.red,
color.color.green,
color.color.blue,
... | {
match method {
Method::Fill => {
let ctor = |v: P2, _: FillAttributes| -> P2 { v };
let mut buffers: VertexBuffers<P2, u32> = VertexBuffers::new();
let mut buffers_builder = BuffersBuilder::new(&mut buffers, ctor);
let mut tessellator = FillTessellator::new... | identifier_body |
batch_analyze_J10.py | # ################################################################
#
# Active Particles on Curved Spaces (APCS)
#
# Author: Silke Henkes
#
# ICSMB, Department of Physics
# University of Aberdeen
# Author: Rastko Sknepnek
#
# Division of Physics
# School of Engineering, Physics and Mathem... | s_tp_profile[isparticles]+=s_tp_profile0[isparticles]
s_pt_profile[isparticles]+=s_pt_profile0[isparticles]
s_pp_profile[isparticles]+=s_pp_profile0[isparticles]
alpha_profile[isparticles]+=alpha_profile0[isparticles]
alpha_v_profile[isparticles]+=alpha_v_profile0[isparticles]
tot +=1
orderpar/=(par... | press_profile[isparticles]+=press_profile0[isparticles]
s_tt_profile[isparticles]+=s_tt_profile0[isparticles] | random_line_split |
batch_analyze_J10.py | # ################################################################
#
# Active Particles on Curved Spaces (APCS)
#
# Author: Silke Henkes
#
# ICSMB, Department of Physics
# University of Aberdeen
# Author: Rastko Sknepnek
#
# Division of Physics
# School of Engineering, Physics and Mathem... | for f in files:
[theta_bin,rho_profile0,vel_profile0,eng_profile0,press_profile0,s_tt_profile0,s_tp_profile0,s_pt_profile0,s_pp_profile0,alpha_profile0,alpha_v_profile0,axis[tot,:],orderpar[tot,:]]=getProfiles(f,nbin,param.r,param.k,sigma)
isparticles=np.array([index for index,value in enumerate(rho_profile0) ... | print vList[i],JList[j]
folder=basefolder+'data_v0_'+vList[i]+'/data_j_'+JList[j]+'_sphere/'
print folder
param = Param(folder)
files = sorted(glob(folder+'*.dat'))[skip:]
rho_profile =np.zeros((nbin,))
vel_profile =np.zeros((nbin,))
eng_profile = np.zeros((nbin,))
press_profile = np.zeros((nbin,)... | conditional_block |
colour-setting.js | /* Extends the setting class for colour changing */
Setting.extend("Colour",{
init: function(data, serverUrl, roomId, deviceId, capType){
this._super(data, serverUrl, roomId, deviceId, capType);
this.cw = Raphael.colorwheel($(this.divId)[0], 200);
this.cw.input($(this.divId + "_input")[0])... | updateDisplay: function() {
var colour="#"+this.value;
this.cw.color(colour);
},
/* Get the user updated value from the colourwheel object */
getChangedValue: function() {
var colour = this.cw.color();
return colour.hex;
},
/* Override updateToServer so display ... | /* Update the colour wheel to display the new colour */ | random_line_split |
colour-setting.js | /* Extends the setting class for colour changing */
Setting.extend("Colour",{
init: function(data, serverUrl, roomId, deviceId, capType){
this._super(data, serverUrl, roomId, deviceId, capType);
this.cw = Raphael.colorwheel($(this.divId)[0], 200);
this.cw.input($(this.divId + "_input")[0])... |
return v.replace('#', '')
},
/* Update the colour wheel to display the new colour */
updateDisplay: function() {
var colour="#"+this.value;
this.cw.color(colour);
},
/* Get the user updated value from the colourwheel object */
getChangedValue: function() {
var ... | {
v = "000";
} | conditional_block |
eval_type.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use std::fmt;
/// Function implementations' parameter data types.
///
/// It is similar to the `EvalType` in TiDB, but doesn't provide type `Timestamp`, which is
/// handled by the same type as `DateTime` here, instead of a new type. Also, `String` is... |
#[test]
fn test_fieldtype_to_evaltype() {
let cases = vec![
(Unspecified, None),
(Tiny, Some(EvalType::Int)),
(Short, Some(EvalType::Int)),
(Long, Some(EvalType::Int)),
(Float, Some(EvalType::Real)),
(Double, Some(EvalType::Real)),... | use std::convert::TryFrom; | random_line_split |
eval_type.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use std::fmt;
/// Function implementations' parameter data types.
///
/// It is similar to the `EvalType` in TiDB, but doesn't provide type `Timestamp`, which is
/// handled by the same type as `DateTime` here, instead of a new type. Also, `String` is... | (self) -> crate::FieldTypeTp {
match self {
EvalType::Int => crate::FieldTypeTp::LongLong,
EvalType::Real => crate::FieldTypeTp::Double,
EvalType::Decimal => crate::FieldTypeTp::NewDecimal,
EvalType::Bytes => crate::FieldTypeTp::String,
EvalType::DateT... | into_certain_field_type_tp_for_test | identifier_name |
eval_type.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use std::fmt;
/// Function implementations' parameter data types.
///
/// It is similar to the `EvalType` in TiDB, but doesn't provide type `Timestamp`, which is
/// handled by the same type as `DateTime` here, instead of a new type. Also, `String` is... | (NewDecimal, Some(EvalType::Decimal)),
(Enum, Some(EvalType::Enum)),
(Set, None),
(TinyBlob, Some(EvalType::Bytes)),
(MediumBlob, Some(EvalType::Bytes)),
(LongBlob, Some(EvalType::Bytes)),
(Blob, Some(EvalType::Bytes)),
(Var... | {
let cases = vec![
(Unspecified, None),
(Tiny, Some(EvalType::Int)),
(Short, Some(EvalType::Int)),
(Long, Some(EvalType::Int)),
(Float, Some(EvalType::Real)),
(Double, Some(EvalType::Real)),
(Null, Some(EvalType::Bytes)),
... | identifier_body |
test.js | /**
* @license Apache-2.0
* | * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES ... | * Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); | random_line_split |
test_field.py | # test_field.py
#
# Copyright 2017 Daniel Mende <mail@c0decafe.de>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain th... | main() | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.