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 |
|---|---|---|---|---|
bytenet_test.py | # coding=utf-8
# Copyright 2018 The Tensor2Tensor Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | (tf.test.TestCase):
def testByteNet(self):
vocab_size = 9
x = np.random.random_integers(1, high=vocab_size - 1, size=(3, 5, 1, 1))
y = np.random.random_integers(1, high=vocab_size - 1, size=(3, 6, 1, 1))
hparams = bytenet.bytenet_base()
p_hparams = problem_hparams.test_problem_hparams(vocab_size,... | ByteNetTest | identifier_name |
index.tsx | import * as React from 'react';
import { action } from 'mobx';
import { observer } from 'mobx-react';
import { get, set } from 'lodash';
import * as URI from 'urijs';
import * as FileSaver from 'file-saver';
import { Modal } from 'office-ui-fabric-react/lib/Modal';
import { TextField } from 'office-ui-fabric-react/lib... | private async resetSettingsToDefaults() {
await ScriptsStore.removeSettings();
await PagesStore.removeSettings();
await AppSettingsStore.removeSettings();
location.reload();
}
}
export interface WorkspaceSettingsProps {
showWorkspaceSettingsModal: boolean;
onDismiss: (e... |
@action.bound | random_line_split |
index.tsx | import * as React from 'react';
import { action } from 'mobx';
import { observer } from 'mobx-react';
import { get, set } from 'lodash';
import * as URI from 'urijs';
import * as FileSaver from 'file-saver';
import { Modal } from 'office-ui-fabric-react/lib/Modal';
import { TextField } from 'office-ui-fabric-react/lib... | () {
await ScriptsStore.removeSettings();
await PagesStore.removeSettings();
await AppSettingsStore.removeSettings();
location.reload();
}
}
export interface WorkspaceSettingsProps {
showWorkspaceSettingsModal: boolean;
onDismiss: (ev?: React.MouseEvent<HTMLButtonElement>) ... | resetSettingsToDefaults | identifier_name |
main.js | $('input').each(function() {
var default_value = this.value;
$(this).focus(function(){
if(this.value == default_value) {
this.value = '';
}
});
$(this).blur(function(){
if(this.value == '') |
});
});
var clock;
$(document).ready(function() {
// Grab the current date
var currentDate = new Date();
// Set date in the future.
var futureDate = new Date("October 13, 2014 08:00:00");
// Calculate the difference in seconds between the future and current date
var diff = futureDate.getTime() / 1... | {
this.value = default_value;
} | conditional_block |
main.js | $('input').each(function() {
var default_value = this.value;
$(this).focus(function(){
if(this.value == default_value) {
this.value = '';
}
});
$(this).blur(function(){
if(this.value == '') {
this.v... |
}); | random_line_split | |
regions-infer-borrow-scope.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn main() {
let p: Box<_> = box Point {x: 3, y: 4};
let xc = x_coord(&*p);
assert_eq!(*xc, 3);
}
| {
return &p.x;
} | identifier_body |
regions-infer-borrow-scope.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | pub fn main() {
let p: Box<_> = box Point {x: 3, y: 4};
let xc = x_coord(&*p);
assert_eq!(*xc, 3);
} | random_line_split | |
regions-infer-borrow-scope.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {x: isize, y: isize}
fn x_coord(p: &Point) -> &isize {
return &p.x;
}
pub fn main() {
let p: Box<_> = box Point {x: 3, y: 4};
let xc = x_coord(&*p);
assert_eq!(*xc, 3);
}
| Point | identifier_name |
template_exp_standalone.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'exp_std.ui'
#
# Created: Sat Apr 18 15:55:49 2015
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except Attrib... | " padding: 0px;\n"
" }\n"
"\n"
" QDockWidget::close-button:hover, QDockWidget::float-button:hover {\n"
" background: gray;\n"
" }\n"
"\n"
" QDockWidget::close-button:pressed, QDockWidget::float-button:pressed {\n"
" padding: 1px -1px -1px 1px;\n"
" }\n"
"\n"
"\n"
"\n"
"border-color: rgb(29, 122, 162);\n"
""... | " QDockWidget::close-button, QDockWidget::float-button {\n"
" border: 1px solid transparent;\n"
" background: darkgray;\n" | random_line_split |
template_exp_standalone.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'exp_std.ui'
#
# Created: Sat Apr 18 15:55:49 2015
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except Attrib... | (context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
Mai... | _translate | identifier_name |
template_exp_standalone.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'exp_std.ui'
#
# Created: Sat Apr 18 15:55:49 2015
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except Attrib... | MainWindow.setWindowTitle(_translate("MainWindow", "Experiments", None)) | identifier_body | |
test_status6e6_enum.py | # coding: utf-8 |
OpenAPI spec version: 2.0 (v2)
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import nordigen
from nordigen.models.status6e6_enum import Status6e6Enum # noqa: E501
from nordigen.rest import ApiException
class TestStatus6e6E... |
"""
Nordigen Account Information Services API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 | random_line_split |
test_status6e6_enum.py | # coding: utf-8
"""
Nordigen Account Information Services API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 2.0 (v2)
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ i... | (self):
pass
def testStatus6e6Enum(self):
"""Test Status6e6Enum"""
# FIXME: construct object with mandatory attributes with example values
# model = nordigen.models.status6e6_enum.Status6e6Enum() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
| tearDown | identifier_name |
test_status6e6_enum.py | # coding: utf-8
"""
Nordigen Account Information Services API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 2.0 (v2)
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ i... |
if __name__ == '__main__':
unittest.main()
| """Status6e6Enum unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testStatus6e6Enum(self):
"""Test Status6e6Enum"""
# FIXME: construct object with mandatory attributes with example values
# model = nordigen.models.status6e6_enum.Status6e6Enum()... | identifier_body |
test_status6e6_enum.py | # coding: utf-8
"""
Nordigen Account Information Services API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 2.0 (v2)
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ i... | unittest.main() | conditional_block | |
task_queue_manager.py | ://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import multiprocessing
import os
import tempfile
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.executor.play_iterator import Play... |
def _initialize_notified_handlers(self, handlers):
'''
Clears and initializes the shared notified handlers dict with entries
for each handler in the play, which is an empty array that will contain
inventory hostnames for those hosts triggering the handler.
'''
# Ze... | self._workers = []
for i in range(num):
rslt_q = multiprocessing.Queue()
self._workers.append([None, rslt_q])
self._result_prc = ResultProcess(self._final_q, self._workers)
self._result_prc.start() | identifier_body |
task_queue_manager.py | ://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import multiprocessing
import os
import tempfile
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.executor.play_iterator import Play... |
def _process_block(b):
temp_list = []
for t in b.block:
if isinstance(t, Block):
temp_list.extend(_process_block(t))
else:
temp_list.append(t)
return temp_list
handler_list = []
for han... | del self._notified_handlers[key] | conditional_block |
task_queue_manager.py | # GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import multipro... | random_line_split | ||
task_queue_manager.py | ://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import multiprocessing
import os
import tempfile
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.executor.play_iterator import Play... | (self):
'''
Loads all available callbacks, with the exception of those which
utilize the CALLBACK_TYPE option. When CALLBACK_TYPE is set to 'stdout',
only one such callback plugin will be loaded.
'''
if self._callbacks_loaded:
return
stdout_callback_... | load_callbacks | identifier_name |
stability-attribute-sanity-2.rs | // Copyright 2015 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() { }
| f3 | identifier_name |
stability-attribute-sanity-2.rs | // Copyright 2015 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() { } | fn f3() { }
| random_line_split |
stability-attribute-sanity-2.rs | // Copyright 2015 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() { }
| { } | identifier_body |
game.py | # _*_ coding:utf-8 _*_
import random
from parser_xml import doxml
__author__ = 'Administrator'
import pygame
def item_to_int(array=[]):
arr = []
for a in array:
arr.append(int(a))
return arr
pygame.init()
keys = [False, False, False, False]
screen = pygame.display.set_mode((450, 650), 0, 32)
... | lif event.key == pygame.K_a:
keys[1] = False
elif event.key == pygame.K_s:
keys[2] = False
elif event.key == pygame.K_d:
keys[3] = False
if keys[0]:
hero_1_pos[1] -= 5
elif keys[2]:
hero_1_pos[1] += 5
if keys[1]:
... | True
elif event.key == pygame.K_s:
keys[2] = True
elif event.key == pygame.K_d:
keys[3] = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_w:
keys[0] = False
e | conditional_block |
game.py | # _*_ coding:utf-8 _*_
import random
from parser_xml import doxml
__author__ = 'Administrator'
import pygame
def | (array=[]):
arr = []
for a in array:
arr.append(int(a))
return arr
pygame.init()
keys = [False, False, False, False]
screen = pygame.display.set_mode((450, 650), 0, 32)
pygame.display.set_caption(u'飞机大战'.encode('utf-8'))
plane = pygame.image.load('resources/plane.png').convert_alpha()
pos = dox... | item_to_int | identifier_name |
game.py | # _*_ coding:utf-8 _*_
import random
from parser_xml import doxml
__author__ = 'Administrator'
import pygame
def item_to_int(array=[]):
arr = []
for a in array:
arr.append(int(a))
return arr
pygame.init()
keys = [False, False, False, False]
screen = pygame.display.set_mode((450, 650), 0, 32)
... | screen.blit(enemy_m, me)
# 绘制大飞机
if not enemytimer[2]:
bigenemy.append([random.randint(0, 340), -100])
enemytimer[2] = 300 - (enemytimers[2] * 2)
enemytimers[2] = 65 if enemytimers[2] > 65 else enemytimers[2] + 5
index = 0
for be in bigenemy:
if be[1] > 650:
... | midenemy.pop(index)
me[1] += 2
index += 1
for me in midenemy: | random_line_split |
game.py | # _*_ coding:utf-8 _*_
import random
from parser_xml import doxml
__author__ = 'Administrator'
import pygame
def item_to_int(array=[]):
|
pygame.init()
keys = [False, False, False, False]
screen = pygame.display.set_mode((450, 650), 0, 32)
pygame.display.set_caption(u'飞机大战'.encode('utf-8'))
plane = pygame.image.load('resources/plane.png').convert_alpha()
pos = doxml('resources/plane.xml')
# hero_1
hero_1_p = pos['hero_1']
hero_1_p = item_to_int(he... | arr = []
for a in array:
arr.append(int(a))
return arr | identifier_body |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from setuptools import setup
this_dir = os.path.abspath(os.path.dirname(__file__))
VERSIONFILE = os.path.join(this_dir, "textx", "__init__.py")
VERSION = None
for line in open(VERSIONFILE, "r").readlines():
if line.startswith('__version__'):
... |
if sys.argv[-1].startswith('publish'):
if os.system("pip list | grep twine"):
print("twine not installed.\nUse `pip install twine`.\nExiting.")
sys.exit()
os.system("python setup.py sdist bdist_wheel")
if sys.argv[-1] == 'publishtest':
os.system("twine upload -r test dist/*")
e... | raise RuntimeError('No version defined in textx.__init__.py') | conditional_block |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from setuptools import setup
this_dir = os.path.abspath(os.path.dirname(__file__))
VERSIONFILE = os.path.join(this_dir, "textx", "__init__.py")
VERSION = None
for line in open(VERSIONFILE, "r").readlines():
if line.startswith('__version__'):
... | print("twine not installed.\nUse `pip install twine`.\nExiting.")
sys.exit()
os.system("python setup.py sdist bdist_wheel")
if sys.argv[-1] == 'publishtest':
os.system("twine upload -r test dist/*")
else:
os.system("twine upload dist/*")
print("You probably want to al... | if sys.argv[-1].startswith('publish'):
if os.system("pip list | grep twine"): | random_line_split |
status-bar.js | var StatusBarView, View;
var __hasProp = {}.hasOwnProperty;
var __extends = function(child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor()... | () {
return StatusBarView.__super__.constructor.apply(this, arguments);
}
StatusBarView.content = function() {
return this.div({
"class": 'inline-block'
}, (function(_this) {
return function() {
return _this.div({
outlet: "statusText"
});
};
})(this));
... | StatusBarView | identifier_name |
status-bar.js | var StatusBarView, View;
var __hasProp = {}.hasOwnProperty;
var __extends = function(child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() |
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
return child;
};
View = require('atom').View;
module.exports = StatusBarView = (function(_super) {
__extends(StatusBarView, _super);
function StatusBarView() {
return StatusBarView.__super__.constru... | {
this.constructor = child;
} | identifier_body |
status-bar.js | var StatusBarView, View;
var __hasProp = {}.hasOwnProperty;
var __extends = function(child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor()... | return StatusBarView.__super__.constructor.apply(this, arguments);
}
StatusBarView.content = function() {
return this.div({
"class": 'inline-block'
}, (function(_this) {
return function() {
return _this.div({
outlet: "statusText"
});
};
})(this));
};
... | __extends(StatusBarView, _super);
function StatusBarView() { | random_line_split |
content_script.js | new Promise((resolve) => setTimeout(resolve, 1000000)).then(() => {
var now = new Date().getTime();
if (now - last_message_time > 500000) {
sendAlert('Not having message from background for at least 500s, force reloading');
reloadPage();
}
});
chrome.runtime.onMessage.addListener(function(r... | console.log("VS: loading content_script.js..." + new Date());
// Check if the communication between page and background.js has broken.
var last_message_time = new Date().getTime(); | random_line_split | |
content_script.js |
console.log("VS: loading content_script.js..." + new Date());
// Check if the communication between page and background.js has broken.
var last_message_time = new Date().getTime();
new Promise((resolve) => setTimeout(resolve, 1000000)).then(() => {
var now = new Date().getTime();
if (now - last_message_time >... | (request) {
var links = $('A');
for (var i in links) {
var link = links[i];
if (link.href == LOGIN_PAGE) {
link.click();
}
}
}
function asyncLogin(request) {
if (already_logging_in) {
console.log("VS: already logging in. This is possible, ignoring.." + new Da... | homePage | identifier_name |
content_script.js |
console.log("VS: loading content_script.js..." + new Date());
// Check if the communication between page and background.js has broken.
var last_message_time = new Date().getTime();
new Promise((resolve) => setTimeout(resolve, 1000000)).then(() => {
var now = new Date().getTime();
if (now - last_message_time >... |
function homePage(request) {
var links = $('A');
for (var i in links) {
var link = links[i];
if (link.href == LOGIN_PAGE) {
link.click();
}
}
}
function asyncLogin(request) {
if (already_logging_in) {
console.log("VS: already logging in. This is possible, ig... | {
if (request) {
asyncLogin(request);
} else {
chrome.runtime.sendMessage({"action": ACTION_FOR_ASYNC_LOGIN});
}
} | identifier_body |
kickoff.py | from flask import url_for
from decksite.view import View
from magic import tournaments
from shared import dtutil
# pylint: disable=no-self-use
class KickOff(View):
def __init__(self) -> None:
super().__init__()
kick_off_date = tournaments.kick_off_date()
if dtutil.now() > kick_off_date:
... | self.cardhoarder_loan_url = 'https://www.cardhoarder.com/free-loan-program-faq'
self.tournaments_url = url_for('tournaments')
self.discord_url = url_for('discord')
def page_title(self) -> str:
return 'The Season Kick Off' | self.faqs_url = url_for('faqs') | random_line_split |
kickoff.py | from flask import url_for
from decksite.view import View
from magic import tournaments
from shared import dtutil
# pylint: disable=no-self-use
class KickOff(View):
def __init__(self) -> None:
|
def page_title(self) -> str:
return 'The Season Kick Off'
| super().__init__()
kick_off_date = tournaments.kick_off_date()
if dtutil.now() > kick_off_date:
self.date_info = 'The Season Kick Off is on the second Saturday of the season'
else:
self.date_info = 'The next Season Kick Off is on ' + dtutil.display_date_with_date_and_year... | identifier_body |
kickoff.py | from flask import url_for
from decksite.view import View
from magic import tournaments
from shared import dtutil
# pylint: disable=no-self-use
class KickOff(View):
def __init__(self) -> None:
super().__init__()
kick_off_date = tournaments.kick_off_date()
if dtutil.now() > kick_off_date:
... |
self.faqs_url = url_for('faqs')
self.cardhoarder_loan_url = 'https://www.cardhoarder.com/free-loan-program-faq'
self.tournaments_url = url_for('tournaments')
self.discord_url = url_for('discord')
def page_title(self) -> str:
return 'The Season Kick Off'
| self.date_info = 'The next Season Kick Off is on ' + dtutil.display_date_with_date_and_year(kick_off_date) | conditional_block |
kickoff.py | from flask import url_for
from decksite.view import View
from magic import tournaments
from shared import dtutil
# pylint: disable=no-self-use
class KickOff(View):
def | (self) -> None:
super().__init__()
kick_off_date = tournaments.kick_off_date()
if dtutil.now() > kick_off_date:
self.date_info = 'The Season Kick Off is on the second Saturday of the season'
else:
self.date_info = 'The next Season Kick Off is on ' + dtutil.display... | __init__ | identifier_name |
pubsub.js | (function(){
/**
* PubSub implementation (fast)
*/
var PubSub = function PubSub( defaultScope ){
if (!(this instanceof PubSub)) |
this._topics = {};
this.defaultScope = defaultScope || this;
};
PubSub.prototype = {
/**
* Subscribe a callback (or callbacks) to a topic (topics).
*
* @param {String|Object} topic The topic name, or a config with key/value pairs of { topic: callbackFn,... | {
return new PubSub( defaultScope );
} | conditional_block |
pubsub.js | (function(){
/** | if (!(this instanceof PubSub)){
return new PubSub( defaultScope );
}
this._topics = {};
this.defaultScope = defaultScope || this;
};
PubSub.prototype = {
/**
* Subscribe a callback (or callbacks) to a topic (topics).
*
* @param ... | * PubSub implementation (fast)
*/
var PubSub = function PubSub( defaultScope ){
| random_line_split |
transform-img.ts | /**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... |
/**
* Prepares an animation from one image to another. Creates a temporary
* transition image that is transitioned between the position, size and crop of
* two images.
* @param options
* @param options.transitionContainer The container to place the transition
* image in. This could be useful if you need to p... | {
const style = getComputedStyle(img);
const objectFit = style.getPropertyValue('object-fit');
const objectPosition = style.getPropertyValue('object-position');
return {
objectFit,
objectPosition,
rect,
cropRect,
img,
dimensions: getRenderedDimensions(img, rect, objectFit),
area: re... | identifier_body |
transform-img.ts | /**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... | rect: ClientRect,
cropRect: ClientRect,
img: HTMLImageElement,
dimensions: Size,
area: number,
} {
const style = getComputedStyle(img);
const objectFit = style.getPropertyValue('object-fit');
const objectPosition = style.getPropertyValue('object-position');
return {
objectFit,
objectPosition,... | random_line_split | |
transform-img.ts | /**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... | (
img: HTMLImageElement,
rect: ClientRect,
cropRect: ClientRect
): {
objectFit: string,
objectPosition: string,
rect: ClientRect,
cropRect: ClientRect,
img: HTMLImageElement,
dimensions: Size,
area: number,
} {
const style = getComputedStyle(img);
const objectFit = style.getPropertyValue('object... | getImgProperties | identifier_name |
litmail-message.ts | import {LitElement, css, html, customElement, property, PropertyValues} from 'lit-element';
import {messageBody} from './message-body.js';
import '@material/mwc-icon';
import {parseMessage, Message, ParsedMessage } from './gmail-api.js';
@customElement('litmail-message')
export class LitMailMessage extends LitElemen... |
render () {
const body = this._parsedMessage?.textHtml || this._parsedMessage?.textPlain;
const {snippet} = this._parsedMessage ?? {};
return html`
<h5 class="from">${this._parsedMessage?.from?.name}</h5>
${this.open
? html`<div class="body">${messageBody(body)}</div>`
: html... | {
if (changedProperties.has('message')) {
if (this.message === undefined) {
this._parsedMessage = undefined;
} else {
this._parsedMessage = parseMessage(this.message);
}
}
this.open = this.open ??
((this.index !== undefined && this.index + 1 === this.totalCount) || ... | identifier_body |
litmail-message.ts | import {LitElement, css, html, customElement, property, PropertyValues} from 'lit-element';
import {messageBody} from './message-body.js';
import '@material/mwc-icon';
import {parseMessage, Message, ParsedMessage } from './gmail-api.js';
@customElement('litmail-message')
export class LitMailMessage extends LitElemen... |
this.open = this.open ??
((this.index !== undefined && this.index + 1 === this.totalCount) ||
(this._parsedMessage?.labelIds?.includes('UNREAD') ?? true));
super.update(changedProperties);
}
render () {
const body = this._parsedMessage?.textHtml || this._parsedMessage?.textPlain;
... | {
if (this.message === undefined) {
this._parsedMessage = undefined;
} else {
this._parsedMessage = parseMessage(this.message);
}
} | conditional_block |
litmail-message.ts | import {LitElement, css, html, customElement, property, PropertyValues} from 'lit-element';
import {messageBody} from './message-body.js';
import '@material/mwc-icon';
import {parseMessage, Message, ParsedMessage } from './gmail-api.js';
@customElement('litmail-message')
export class LitMailMessage extends LitElemen... | }
} | ? html`<div class="body">${messageBody(body)}</div>`
: html`<div class="snippet">${messageBody(snippet)}</div>`
}
`; | random_line_split |
litmail-message.ts | import {LitElement, css, html, customElement, property, PropertyValues} from 'lit-element';
import {messageBody} from './message-body.js';
import '@material/mwc-icon';
import {parseMessage, Message, ParsedMessage } from './gmail-api.js';
@customElement('litmail-message')
export class LitMailMessage extends LitElemen... | () {
super();
this.addEventListener('click', (e) => {
console.log('message click', e.target);
this.open = !this.open;
e.stopPropagation();
});
}
update(changedProperties: PropertyValues) {
if (changedProperties.has('message')) {
if (this.message === undefined) {
this... | constructor | identifier_name |
date-range-selection-strategy.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injectable, InjectionToken, Optional, SkipSelf, FactoryProvider} from '@angular/core';
import {DateAdapter} f... | return parent || new DefaultMatCalendarRangeStrategy(adapter);
}
/** @docs-private */
export const MAT_CALENDAR_RANGE_STRATEGY_PROVIDER: FactoryProvider = {
provide: MAT_DATE_RANGE_SELECTION_STRATEGY,
deps: [[new Optional(), new SkipSelf(), MAT_DATE_RANGE_SELECTION_STRATEGY], DateAdapter],
useFactory: MAT_CALE... | /** @docs-private */
export function MAT_CALENDAR_RANGE_STRATEGY_PROVIDER_FACTORY(
parent: MatDateRangeSelectionStrategy<unknown>, adapter: DateAdapter<unknown>) { | random_line_split |
date-range-selection-strategy.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injectable, InjectionToken, Optional, SkipSelf, FactoryProvider} from '@angular/core';
import {DateAdapter} f... | (activeDate: D | null, currentRange: DateRange<D>) {
let start: D | null = null;
let end: D | null = null;
if (currentRange.start && !currentRange.end && activeDate) {
start = currentRange.start;
end = activeDate;
}
return new DateRange<D>(start, end);
}
}
/** @docs-private */
expo... | createPreview | identifier_name |
date-range-selection-strategy.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injectable, InjectionToken, Optional, SkipSelf, FactoryProvider} from '@angular/core';
import {DateAdapter} f... |
return new DateRange<D>(start, end);
}
createPreview(activeDate: D | null, currentRange: DateRange<D>) {
let start: D | null = null;
let end: D | null = null;
if (currentRange.start && !currentRange.end && activeDate) {
start = currentRange.start;
end = activeDate;
}
return ... | {
start = date;
end = null;
} | conditional_block |
date-range-selection-strategy.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injectable, InjectionToken, Optional, SkipSelf, FactoryProvider} from '@angular/core';
import {DateAdapter} f... |
}
/** @docs-private */
export function MAT_CALENDAR_RANGE_STRATEGY_PROVIDER_FACTORY(
parent: MatDateRangeSelectionStrategy<unknown>, adapter: DateAdapter<unknown>) {
return parent || new DefaultMatCalendarRangeStrategy(adapter);
}
/** @docs-private */
export const MAT_CALENDAR_RANGE_STRATEGY_PROVIDER: FactoryPr... | {
let start: D | null = null;
let end: D | null = null;
if (currentRange.start && !currentRange.end && activeDate) {
start = currentRange.start;
end = activeDate;
}
return new DateRange<D>(start, end);
} | identifier_body |
sticky-elements.js | /**
* This script contains helper functions that make any element with `.sticky-element` class sticky.
*/
'use strict';
const stickyElement = $('.sticky-element');
const stickyElementFixed = stickyElement.hasClass('initially-fixed');
const stickyElTopOffset = 32;
const startPointToFixElement = initialHeadHeight + s... |
/**
* Sets max-height for the sticky element depends on the scroll position.
*/
function setStickyElMaxHeight() {
if (stickyElement.length) {
const elHeights = calcStickyElHeight();
/**
* Determines that the max-height value is less than browser window when the scroll
* positi... | {
if (stickyElement.length && !stickyElementFixed) {
if (window.pageYOffset > startPointToFixElement) {
stickyElement.addClass('sticky');
stickyElement.css('margin-top', -startPointToFixElement);
}
else {
stickyElement.removeClass('sticky');
st... | identifier_body |
sticky-elements.js | /**
* This script contains helper functions that make any element with `.sticky-element` class sticky.
*/
'use strict';
const stickyElement = $('.sticky-element');
const stickyElementFixed = stickyElement.hasClass('initially-fixed');
const stickyElTopOffset = 32;
const startPointToFixElement = initialHeadHeight + s... | const cookieContainerHeight = $('#cookieChoiceInfo').innerHeight();
const contentMarginBottom = 20;
const initialHeight = windowHeight - startPointToFixElement - contentMarginBottom - cookieContainerHeight;
const maxHeight = footerTopPoint - scrollPosition - startPointToFixElement - contentMarginBottom... | function calcStickyElHeight() {
const windowHeight = $(window).height();
const scrollPosition = $(window).scrollTop();
const footerTopPoint = $('.footer').position().top; | random_line_split |
sticky-elements.js | /**
* This script contains helper functions that make any element with `.sticky-element` class sticky.
*/
'use strict';
const stickyElement = $('.sticky-element');
const stickyElementFixed = stickyElement.hasClass('initially-fixed');
const stickyElTopOffset = 32;
const startPointToFixElement = initialHeadHeight + s... |
}
/**
* Sets max-height for the sticky element depends on the scroll position.
*/
function setStickyElMaxHeight() {
if (stickyElement.length) {
const elHeights = calcStickyElHeight();
/**
* Determines that the max-height value is less than browser window when the scroll
* posi... | {
if (window.pageYOffset > startPointToFixElement) {
stickyElement.addClass('sticky');
stickyElement.css('margin-top', -startPointToFixElement);
}
else {
stickyElement.removeClass('sticky');
stickyElement.css('margin-top', initialMarginTop);
... | conditional_block |
sticky-elements.js | /**
* This script contains helper functions that make any element with `.sticky-element` class sticky.
*/
'use strict';
const stickyElement = $('.sticky-element');
const stickyElementFixed = stickyElement.hasClass('initially-fixed');
const stickyElTopOffset = 32;
const startPointToFixElement = initialHeadHeight + s... | () {
const windowHeight = $(window).height();
const scrollPosition = $(window).scrollTop();
const footerTopPoint = $('.footer').position().top;
const cookieContainerHeight = $('#cookieChoiceInfo').innerHeight();
const contentMarginBottom = 20;
const initialHeight = windowHeight - startPointToFi... | calcStickyElHeight | identifier_name |
similarity_matrix.rs | ) -> SimilarityMatrix<'a, F, G, E, N> {
// `x` is the node-similarity matrix.
// we initialize `x`, so that x[i,j]=1 for all i in A.edges() and j in
// B.edges().
let shape = (graph_a.num_nodes(), graph_b.num_nodes());
let x = Matrix::from_shape_fn(shape, |(i, j)| {
... | score_average | identifier_name | |
similarity_matrix.rs | &'a G,
node_color_matching: F,
) -> SimilarityMatrix<'a, F, G, E, N> {
// `x` is the node-similarity matrix.
// we initialize `x`, so that x[i,j]=1 for all i in A.edges() and j in
// B.edges().
let shape = (graph_a.num_nodes(), graph_b.num_nodes());
let x = Matrix::f... | pub fn max_nodes(&self) -> usize {
cmp::max(self.current.nrows(), self.current.ncols())
}
pub fn optimal_node_assignment(&self) -> Vec<Position> {
let n = self.min_nodes();
let assignment = if n > 0 {
let mut w = WeightMatrix::from_fn(n, |ij| similarity_cost(self.current... |
pub fn min_nodes(&self) -> usize {
cmp::min(self.current.nrows(), self.current.ncols())
}
| random_line_split |
similarity_matrix.rs | a G,
node_color_matching: F,
) -> SimilarityMatrix<'a, F, G, E, N> {
// `x` is the node-similarity matrix.
// we initialize `x`, so that x[i,j]=1 for all i in A.edges() and j in
// B.edges().
let shape = (graph_a.num_nodes(), graph_b.num_nodes());
let x = Matrix::from... |
/// Calculates the next iteration of the similarity matrix (x[k+1]).
pub fn next(&mut self) {
{
let x = &self.current;
for ((i, j), new_x_ij) in self.previous.indexed_iter_mut() {
let scale = self
.node_color_matching
.nod... | {
Zip::from(&self.previous)
.and(&self.current)
.fold_while(true, |all_prev_in_eps, x, y| {
if all_prev_in_eps && relative_eq!(x, y, epsilon = eps) {
FoldWhile::Continue(true)
} else {
FoldWhile::Done(false)
... | identifier_body |
script.js | 'use strict';
$(document).ready(function() {
try {
var restServer = 'http://192.168.88.213:3100/api/';
var service = 'DgrpEntradas/abiertasXtipo';
var dataset;
//Load data from the server
function | () {
/*$.ajax({
url: restServer + service
}).then(function(resp) {
dataset = resp;
drawGraph(dataset);
});
dataset= [
{label: "Usuarios bloqueados", value: 12},
{label: "Usuarios logueados", value: 30},
{label: "Usuarios activos", value... | loadData | identifier_name |
script.js | 'use strict';
$(document).ready(function() {
try {
var restServer = 'http://192.168.88.213:3100/api/';
var service = 'DgrpEntradas/abiertasXtipo';
var dataset;
//Load data from the server
function loadData() {
/*$.ajax({
url: restServer + service
}).then(function(re... |
//Init
loadData();
} catch (e){
console.log('widget error', e);
}
}); | });
| random_line_split |
script.js | 'use strict';
$(document).ready(function() {
try {
var restServer = 'http://192.168.88.213:3100/api/';
var service = 'DgrpEntradas/abiertasXtipo';
var dataset;
//Load data from the server
function loadData() | config.IP.carpeta = 'kerp';
config.init();
ajax_dyd.data = {usuario: 'admin', contrasena:contra};
ajax_dyd.type = 'POST';
ajax_dyd.url = 'pxp/lib/rest/seguridad/Auten/verificarCredenciales';
ajax_dyd.dataType = 'json';
ajax_dyd.async = true;
ajax_dyd.sesi... | {
/*$.ajax({
url: restServer + service
}).then(function(resp) {
dataset = resp;
drawGraph(dataset);
});
dataset= [
{label: "Usuarios bloqueados", value: 12},
{label: "Usuarios logueados", value: 30},
{label: "Usuarios activos", value: 2... | identifier_body |
script.js | 'use strict';
$(document).ready(function() {
try {
var restServer = 'http://192.168.88.213:3100/api/';
var service = 'DgrpEntradas/abiertasXtipo';
var dataset;
//Load data from the server
function loadData() {
/*$.ajax({
url: restServer + service
}).then(function(re... |
});
}
function drawGraph(data) {
Morris.Area({
element: 'wid-user',
data: data,
xkey: 'periodo',
ykeys: ['exito', 'error'],
labels: ['Exito', 'Error']
});
};
//Onresize method for adjust size
$(window).on('resize', function(... | {
console.log('Credenciales invalidas');
} | conditional_block |
schema.py | # ----------------------------------------------------------------------------
# Copyright (c) 2011-2015, The American Gut Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# -----------------------------------... |
def create_tables():
"""Create the tables"""
c = connect(user=agr.admin_db_user, password=agr.admin_db_password,
host=agr.db_host, dbname=agr.db_name)
c.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur = c.cursor()
for _, table in tables:
cur.execute(table)
if __name... | c.close()
create_tables() | random_line_split |
schema.py | # ----------------------------------------------------------------------------
# Copyright (c) 2011-2015, The American Gut Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# -----------------------------------... | except:
return False
else:
c.close()
return True
def schema_is_sane():
"""Check to see if the expected tables exist
Notes
-----
Assumes we have connectivity and the database exists.
The structure of the tables is _not_ verified, only checks that the table
nam... | """Determine if the database exists
Paramters
---------
user : str
The database usermame
password : str
The password for the user
host : str
The database host
dbname : str
The name of the database to connect to
Returns
-------
bool
True if th... | identifier_body |
schema.py | # ----------------------------------------------------------------------------
# Copyright (c) 2011-2015, The American Gut Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# -----------------------------------... | import sys
if not database_connectivity():
sys.stderr.write("Cannot connect to the database\n")
sys.exit(1)
if not agr.test_environment:
if sys.argv[1] == 'FORCE_CREATE_TABLES':
create_tables()
sys.exit(0)
else:
sys.stderr.write("This does not... | conditional_block | |
schema.py | # ----------------------------------------------------------------------------
# Copyright (c) 2011-2015, The American Gut Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# -----------------------------------... | ():
"""Check to see if the schema appears to have data
Notes
-----
Assumes we have connectivity and the database exists.
The structure of the tables is _not_ verified, only checks that there
appears to be rows in the tables.
Database credentials are sourced from the agr module (e.g., the ... | schema_has_data | identifier_name |
serialwin32.py | Check
elif self._parity == serial.PARITY_MARK:
comDCB.Parity = win32.MARKPARITY
comDCB.fParity = 1 # Enable Parity Check
elif self._parity == serial.PARITY_SPACE:
comDCB.Parity = win32.SPACEPARITY
comDCB.fParity = 1 # Enable Parity Check
else:
... | """\
Flush of file like objects. In this case, wait until all data
is written.
"""
while self.out_waiting:
time.sleep(0.05)
# XXX could also use WaitCommEvent with mask EV_TXEMPTY, but it would
# require overlapped IO and its also only possible to set a single... | identifier_body | |
serialwin32.py | RS485Settings.delay_before_rx: %r' % (
self._rs485_mode.delay_before_rx,))
if self._rs485_mode.loopback:
raise ValueError(
'Unsupported value for RS485Settings.loopback: %r' % (
self._rs485_mode.loopback,))
... | cd | identifier_name | |
serialwin32.py | 4096)
# Save original timeout values:
self._orgTimeouts = win32.COMMTIMEOUTS()
win32.GetCommTimeouts(self._port_handle, ctypes.byref(self._orgTimeouts))
self._reconfigure_port()
# Clear buffers:
# Remove anything that was there
win3... | if not self._port_handle:
raise SerialException("Can only operate on a valid port handle")
# Set Windows timeout values
# timeouts is a tuple with the following items:
# (ReadIntervalTimeout,ReadTotalTimeoutMultiplier,
# ReadTotalTimeoutConstant,WriteTotalTimeoutMul... | self.is_open = True
def _reconfigure_port(self):
"""Set communication parameters on opened port.""" | random_line_split |
serialwin32.py | 4096)
# Save original timeout values:
self._orgTimeouts = win32.COMMTIMEOUTS()
win32.GetCommTimeouts(self._port_handle, ctypes.byref(self._orgTimeouts))
self._reconfigure_port()
# Clear buffers:
# Remove anything that was there
win3... |
elif self._write_timeout == 0:
timeouts.WriteTotalTimeoutConstant = win32.MAXDWORD
else:
timeouts.WriteTotalTimeoutConstant = max(int(self._write_timeout * 1000), 1)
win32.SetCommTimeouts(self._port_handle, ctypes.byref(timeouts))
win32.SetCommMask(self._port_ha... | pass | conditional_block |
parallel.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Implements parallel traversals over the DOM and flow trees.
//!
//! This code is highly unsafe. Keep this file... | }, shared_layout_context);
} | }); | random_line_split |
parallel.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Implements parallel traversals over the DOM and flow trees.
//!
//! This code is highly unsafe. Keep this file... | () -> FlowParallelInfo {
FlowParallelInfo {
children_count: AtomicIsize::new(0),
parent: null_unsafe_flow(),
}
}
}
/// A parallel bottom-up flow traversal.
trait ParallelPostorderFlowTraversal : PostorderFlowTraversal {
/// Process current flow and potentially traverse i... | new | identifier_name |
parallel.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Implements parallel traversals over the DOM and flow trees.
//!
//! This code is highly unsafe. Keep this file... | {
if opts::get().bubble_inline_sizes_separately {
let layout_context = LayoutContext::new(shared_layout_context);
let bubble_inline_sizes = BubbleISizes { layout_context: &layout_context };
flow_ref::deref_mut(root).traverse_postorder(&bubble_inline_sizes);
}
run_queue_with_custom_w... | identifier_body | |
parallel.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Implements parallel traversals over the DOM and flow trees.
//!
//! This code is highly unsafe. Keep this file... |
if self.should_process(flow) {
// Perform the appropriate traversal.
self.process(flow);
}
// Possibly enqueue the children.
for kid in flow::child_iter(flow) {
had_children = true;
... | {
flow::mut_base(flow).thread_id = proxy.worker_index();
} | conditional_block |
logger.py | #!/usr/bin/env python
# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... |
def stdout(rec, msg, *args):
if rec.verbose >= DEBUG:
flush(rec, msg, *args)
sys.stdout.write('>>> %s\n' % msg)
def timer(rec, msg, cpu0=None, wall0=None):
if cpu0 is None:
cpu0 = rec._t0
if wall0:
rec._t0, rec._w0 = process_clock(), perf_counter()
if rec.verbose >= TI... | flush(rec, msg, *args) | conditional_block |
logger.py | #!/usr/bin/env python
# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... |
def debug(rec, msg, *args):
if rec.verbose >= DEBUG:
flush(rec, msg, *args)
def debug1(rec, msg, *args):
if rec.verbose >= DEBUG1:
flush(rec, msg, *args)
def debug2(rec, msg, *args):
if rec.verbose >= DEBUG2:
flush(rec, msg, *args)
def debug3(rec, msg, *args):
if rec.verbose ... | flush(rec, msg, *args) | random_line_split |
logger.py | #!/usr/bin/env python
# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... | (rec, msg, *args):
if rec.verbose >= DEBUG4:
flush(rec, msg, *args)
def stdout(rec, msg, *args):
if rec.verbose >= DEBUG:
flush(rec, msg, *args)
sys.stdout.write('>>> %s\n' % msg)
def timer(rec, msg, cpu0=None, wall0=None):
if cpu0 is None:
cpu0 = rec._t0
if wall0:
... | debug4 | identifier_name |
logger.py | #!/usr/bin/env python
# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... |
def stdout(rec, msg, *args):
if rec.verbose >= DEBUG:
flush(rec, msg, *args)
sys.stdout.write('>>> %s\n' % msg)
def timer(rec, msg, cpu0=None, wall0=None):
if cpu0 is None:
cpu0 = rec._t0
if wall0:
rec._t0, rec._w0 = process_clock(), perf_counter()
if rec.verbose >= TI... | if rec.verbose >= DEBUG4:
flush(rec, msg, *args) | identifier_body |
transpose4x4-opt.py | # This file is part of Peach-Py package and is licensed under the Simplified BSD license.
# See license.rst for the full text of the license.
from peachpy.x86_64 import *
from peachpy import *
matrix = Argument(ptr(float_))
with Function("transpose4x4_opt", (matrix,)):
reg_matrix = GeneralPurposeRegister64()
... |
xmm_temps = [XMMRegister() for _ in range(2)]
# xmm_temps[0] = ( m00, m01, m02, m03 )
MOVAPS(xmm_temps[0], xmm_rows[0])
# xmm_temps[1] = ( m20, m21, m22, m23 )
MOVAPS(xmm_temps[1], xmm_rows[2])
# xmm_rows[0] = ( m00, m10, m01, m11 )
UNPCKLPS(xmm_rows[0], xmm_rows[1])
# xmm_rows[2] = (... | MOVUPS(xmm_row, [reg_matrix + i * XMMRegister.size]) | conditional_block |
transpose4x4-opt.py | # This file is part of Peach-Py package and is licensed under the Simplified BSD license.
# See license.rst for the full text of the license.
from peachpy.x86_64 import *
from peachpy import *
matrix = Argument(ptr(float_))
with Function("transpose4x4_opt", (matrix,)):
reg_matrix = GeneralPurposeRegister64()
... | RETURN() | random_line_split | |
rule-contains.js | 'use strict';
/*eslint no-unused-vars: 0 no-undefined:0 */
var tester = require('./_lib/tester');
exports.examples = tester([
{
rules: {
contains: null
},
value: null,
error: true
},
{
rules: {
contains: [ 123, 234, 345 ]
},
value: 333,
verr: {
rule: 'contains',
params: [ 123, 234, 345 ... | expect: true
},
{
rules: {
contains: [ 123, 234, 345 ]
},
value: '123',
verr: {
rule: 'contains',
params: [ 123, 234, 345 ]
}
}
]); | random_line_split | |
register.py | framework.exceptions import HTTPError
from framework.flask import redirect # VOL-aware redirect
from framework.auth.decorators import must_be_signed
from website.archiver import ARCHIVER_SUCCESS, ARCHIVER_FAILURE
from addons.base.views import DOWNLOAD_ACTIONS
from website import settings
from osf.exceptions import... | (auth, node, **kwargs):
"""Handles retraction of public registrations
:param auth: Authentication object for User
:return: Redirect URL for successful POST
"""
if node.is_pending_retraction:
raise HTTPError(http_status.HTTP_400_BAD_REQUEST, data={
'message_short': 'Invalid Reque... | node_registration_retraction_post | identifier_name |
register.py | framework.exceptions import HTTPError
from framework.flask import redirect # VOL-aware redirect
from framework.auth.decorators import must_be_signed
from website.archiver import ARCHIVER_SUCCESS, ARCHIVER_FAILURE
from addons.base.views import DOWNLOAD_ACTIONS
from website import settings
from osf.exceptions import... |
error_messages = list(errors.values())
prompts = [
m['message'].format(util.conjunct(m['addons']))
for m in messages.values() if m['addons']
]
if node.has_pointers_recursive:
prompts.append(
language.BEFORE_REGISTER_HAS_POINTERS.format(
category=nod... | if not addon.complete:
continue
archive_errors = getattr(addon, 'archive_errors', None)
error = None
if archive_errors:
error = archive_errors()
if error:
errors[addon.config.short_name] = error
continue
name = addon.con... | conditional_block |
register.py | from framework.exceptions import HTTPError
from framework.flask import redirect # VOL-aware redirect
from framework.auth.decorators import must_be_signed
from website.archiver import ARCHIVER_SUCCESS, ARCHIVER_FAILURE
from addons.base.views import DOWNLOAD_ACTIONS
from website import settings
from osf.exceptions im... | },
'partial': {
'addons': set(),
'message': 'The current version of the content in <strong>{0}</strong> will be copied to the registration, but version history will be lost.'
},
'none': {
'addons': set(),
'message': 'The contents of <strong... | 'addons': set(),
'message': 'The content and version history of <strong>{0}</strong> will be copied to the registration.', | random_line_split |
register.py | _project, must_be_contributor_or_public,
must_have_permission, must_be_contributor_and_not_group_member,
must_not_be_registration, must_be_registration,
must_not_be_retracted_registration
)
from osf import features
from osf.models import Identifier, RegistrationSchema
from website.project.utils import seria... | if payload.get('action', None) in DOWNLOAD_ACTIONS:
return {'status': 'success'}
errors = payload.get('errors')
src_provider = payload['source']['provider']
if errors:
node.archive_job.update_target(
src_provider,
ARCHIVER_FAILURE,
errors=errors,
)... | identifier_body | |
error.rs | use std::error;
use std::ffi::CStr;
use std::fmt;
use std::os::raw::c_int;
use std::result;
use std::str;
/// Error codes that the library might return.
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash, PartialOrd, Ord)]
pub enum Error {
/// DNS server returned answer with no data.
ENODATA = c_ares_sys::ARES_E... | (&self, fmt: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
let text = unsafe {
let ptr = c_ares_sys::ares_strerror(*self as c_int);
let buf = CStr::from_ptr(ptr).to_bytes();
str::from_utf8_unchecked(buf)
};
fmt.write_str(text)
}
}
impl From<i32... | fmt | identifier_name |
error.rs | use std::error;
use std::ffi::CStr;
use std::fmt;
use std::os::raw::c_int;
use std::result;
use std::str;
/// Error codes that the library might return. | ENODATA = c_ares_sys::ARES_ENODATA as isize,
/// DNS server claims query was misformatted.
EFORMERR = c_ares_sys::ARES_EFORMERR as isize,
/// DNS server returned general failure.
ESERVFAIL = c_ares_sys::ARES_ESERVFAIL as isize,
/// Domain name not found.
ENOTFOUND = c_ares_sys::ARES_ENOTF... | #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash, PartialOrd, Ord)]
pub enum Error {
/// DNS server returned answer with no data. | random_line_split |
error.rs | use std::error;
use std::ffi::CStr;
use std::fmt;
use std::os::raw::c_int;
use std::result;
use std::str;
/// Error codes that the library might return.
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash, PartialOrd, Ord)]
pub enum Error {
/// DNS server returned answer with no data.
ENODATA = c_ares_sys::ARES_E... |
}
impl From<i32> for Error {
fn from(code: i32) -> Self {
match code {
c_ares_sys::ARES_ENODATA => Error::ENODATA,
c_ares_sys::ARES_EFORMERR => Error::EFORMERR,
c_ares_sys::ARES_ESERVFAIL => Error::ESERVFAIL,
c_ares_sys::ARES_ENOTFOUND => Error::ENOTFOUND,
... | {
let text = unsafe {
let ptr = c_ares_sys::ares_strerror(*self as c_int);
let buf = CStr::from_ptr(ptr).to_bytes();
str::from_utf8_unchecked(buf)
};
fmt.write_str(text)
} | identifier_body |
workflowgraphicsview.py | of Auckland
This file is part of MAP Client. (http://launchpad.net/mapclient)
MAP Client 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) ... |
self.setAcceptDrops(True)
def clear(self):
self.scene().clear()
def setUndoStack(self, stack):
self._undoStack = stack
def setLocation(self, location):
self._location = location
def connectNodes(self, node1, node2):
# Check if nodes are already connected
... | # self.setResizeAnchor(QtGui.QGraphicsView.AnchorViewCenter) | random_line_split |
workflowgraphicsview.py | of Auckland
This file is part of MAP Client. (http://launchpad.net/mapclient)
MAP Client 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) ... | self._grid_brush = QtGui.QBrush(grid_pic)
# self.setTransformationAnchor(QtGui.QGraphicsView.AnchorUnderMouse)
# self.setResizeAnchor(QtGui.QGraphicsView.AnchorViewCenter)
self.setAcceptDrops(True)
def clear(self):
self.scene().clear()
def setUndoStack(self, stack):
... | QtGui.QGraphicsView.__init__(self, parent)
self._selectedNodes = []
self._errorIconTimer = QtCore.QTimer()
self._errorIconTimer.setInterval(2000)
self._errorIconTimer.setSingleShot(True)
self._errorIconTimer.timeout.connect(self.errorIconTimeout)
self._errorIcon = None
... | identifier_body |
workflowgraphicsview.py | of Auckland
This file is part of MAP Client. (http://launchpad.net/mapclient)
MAP Client 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) ... | (self, event):
if self._connectLine:
newLine = QtCore.QLineF(self._connectLine.line().p1(), self.mapToScene(event.pos()))
self._connectLine.setLine(newLine)
else:
QtGui.QGraphicsView.mouseMoveEvent(self, event)
def mouseReleaseEvent(self, event):
if self.... | mouseMoveEvent | identifier_name |
workflowgraphicsview.py | of Auckland
This file is part of MAP Client. (http://launchpad.net/mapclient)
MAP Client 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) ... |
if len(self._selectedNodes) == 2:
self.connectNodes(self._selectedNodes[0], self._selectedNodes[1])
def keyPressEvent(self, event):
# super(WorkflowGraphicsView, self).keyPressEvent(event)
if event.key() == QtCore.Qt.Key_Backspace or event.key() == QtCore.Qt.Key_Delete:
... | found = self._selectedNodes.index(node)
del self._selectedNodes[found] | conditional_block |
rest_helpers.py | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
def _is_primitive_value(obj):
if obj is None:
return False
if isinstance(obj, (list, dict)):
raise ValueError("query params may not contain repeated dicts or lists")
return True
def _flatten_value(obj, key_path):
return [(".".join(key_path), obj)]
def _flatten_dict(obj, key_path... | if obj is None:
return []
if isinstance(obj, dict):
return _flatten_dict(obj, key_path=key_path)
if isinstance(obj, list):
return _flatten_list(obj, key_path=key_path)
return _flatten_value(obj, key_path=key_path) | identifier_body |
rest_helpers.py | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
return _flatten(obj, key_path=[])
def _flatten(obj, key_path):
if obj is None:
return []
if isinstance(obj, dict):
return _flatten_dict(obj, key_path=key_path)
if isinstance(obj, list):
return _flatten_list(obj, key_path=key_path)
return _flatten_value(obj, key_path=key_p... | raise TypeError("flatten_query_params must be called with dict object") | conditional_block |
rest_helpers.py | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
def _flatten_dict(obj, key_path):
items = (_flatten(value, key_path=key_path + [key]) for key, value in obj.items())
return functools.reduce(operator.concat, items, [])
def _flatten_list(elems, key_path):
# Only lists of scalar values are supported.
# The name (key_path) is repeated for each value.
... | random_line_split | |
rest_helpers.py | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | (obj, key_path):
items = (_flatten(value, key_path=key_path + [key]) for key, value in obj.items())
return functools.reduce(operator.concat, items, [])
def _flatten_list(elems, key_path):
# Only lists of scalar values are supported.
# The name (key_path) is repeated for each value.
items = (
... | _flatten_dict | identifier_name |
entry-popup.service.ts | import { Injectable, Component } from '@angular/core';
import { Router } from '@angular/router';
import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { DatePipe } from '@angular/common';
import { Entry } from './entry.model';
import { EntryService } from './entry.service';
@Injectable()
export cl... |
entryModalRef(component: Component, entry: Entry): NgbModalRef {
const modalRef = this.modalService.open(component, { size: 'lg', backdrop: 'static'});
modalRef.componentInstance.entry = entry;
modalRef.result.then((result) => {
this.router.navigate([{ outlets: { popup: null }}... | {
if (this.isOpen) {
return;
}
this.isOpen = true;
if (id) {
this.entryService.find(id).subscribe((entry) => {
entry.date = this.datePipe
.transform(entry.date, 'yyyy-MM-ddThh:mm');
this.entryModalRef(component,... | identifier_body |
entry-popup.service.ts | import { Injectable, Component } from '@angular/core';
import { Router } from '@angular/router';
import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { DatePipe } from '@angular/common';
import { Entry } from './entry.model';
import { EntryService } from './entry.service';
@Injectable()
export cl... | (component: Component, entry: Entry): NgbModalRef {
const modalRef = this.modalService.open(component, { size: 'lg', backdrop: 'static'});
modalRef.componentInstance.entry = entry;
modalRef.result.then((result) => {
this.router.navigate([{ outlets: { popup: null }}], { replaceUrl: tr... | entryModalRef | identifier_name |
entry-popup.service.ts | import { Injectable, Component } from '@angular/core';
import { Router } from '@angular/router';
import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { DatePipe } from '@angular/common';
import { Entry } from './entry.model';
import { EntryService } from './entry.service';
@Injectable()
export cl... | else {
return this.entryModalRef(component, new Entry());
}
}
entryModalRef(component: Component, entry: Entry): NgbModalRef {
const modalRef = this.modalService.open(component, { size: 'lg', backdrop: 'static'});
modalRef.componentInstance.entry = entry;
modalRef.r... | {
this.entryService.find(id).subscribe((entry) => {
entry.date = this.datePipe
.transform(entry.date, 'yyyy-MM-ddThh:mm');
this.entryModalRef(component, entry);
});
} | conditional_block |
entry-popup.service.ts | import { Injectable, Component } from '@angular/core';
import { Router } from '@angular/router';
import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { DatePipe } from '@angular/common';
import { Entry } from './entry.model';
import { EntryService } from './entry.service';
@Injectable()
export cl... | if (this.isOpen) {
return;
}
this.isOpen = true;
if (id) {
this.entryService.find(id).subscribe((entry) => {
entry.date = this.datePipe
.transform(entry.date, 'yyyy-MM-ddThh:mm');
this.entryModalRef(component, e... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.