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 |
|---|---|---|---|---|
test_statistics.py | import numpy as np
import pytest
from numpy.testing import assert_allclose
try:
import scipy
except ImportError:
HAS_SCIPY = False
else:
HAS_SCIPY = True
import astropy.units as u
from astropy.timeseries.periodograms.lombscargle import LombScargle
from astropy.timeseries.periodograms.lombscargle._statisti... |
METHOD_KWDS = dict(bootstrap={'n_bootstraps': 20, 'random_seed': 42})
NORMALIZATIONS = ['standard', 'psd', 'log', 'model']
def make_data(N=100, period=1, theta=[10, 2, 3], dy=1, rseed=0, units=False):
"""Generate some data for testing"""
rng = np.random.RandomState(rseed)
t = 5 * period * rng.rand(N)
... | METHODS)
from astropy.timeseries.periodograms.lombscargle.utils import convert_normalization, compute_chi2_ref | random_line_split |
gce.js | Scalr.regPage('Scalr.ui.account2.environments.clouds.gce', function (loadParams, moduleParams) {
var params = moduleParams['params'];
var form = Ext.create('Ext.form.Panel', {
bodyCls: 'x-container-fieldset',
fieldDefaults: {
anchor: '100%',
labelWidth: 110
},
autoScro... | form.resumeLayouts(true);
}
}
},{
xtype: 'textfield',
fieldLabel: 'Project ID',
name: 'gce.project_id',
value: params['gce.project_id']
},{
xtype: 'container',
layout: 'anchor',
itemId: 'manual',
items:... | random_line_split | |
decoder.py | #
# This file is part of pyasn1 software.
#
# Copyright (c) 2005-2017, Ilya Etingof <etingof@gmail.com>
# License: http://pyasn1.sf.net/license.html
#
from pyasn1.type import univ
from pyasn1.codec.cer import decoder
__all__ = ['decode']
class BitStringDecoder(decoder.BitStringDecoder):
supportConstructedForm = ... | (decoder.OctetStringDecoder):
supportConstructedForm = False
# TODO: prohibit non-canonical encoding
RealDecoder = decoder.RealDecoder
tagMap = decoder.tagMap.copy()
tagMap.update(
{univ.BitString.tagSet: BitStringDecoder(),
univ.OctetString.tagSet: OctetStringDecoder(),
univ.Real.tagSet: RealDecode... | OctetStringDecoder | identifier_name |
decoder.py | #
# This file is part of pyasn1 software.
#
# Copyright (c) 2005-2017, Ilya Etingof <etingof@gmail.com>
# License: http://pyasn1.sf.net/license.html
#
from pyasn1.type import univ
from pyasn1.codec.cer import decoder
__all__ = ['decode']
class BitStringDecoder(decoder.BitStringDecoder):
supportConstructedForm = ... |
class Decoder(decoder.Decoder):
supportIndefLength = False
#: Turns DER octet stream into an ASN.1 object.
#:
#: Takes DER octetstream and decode it into an ASN.1 object
#: (e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative) which
#: may be a scalar or an arbitrary nested structure.
#:
#: Parameters
#: ... | if typeDecoder.protoComponent is not None:
typeId = typeDecoder.protoComponent.__class__.typeId
if typeId is not None and typeId not in typeMap:
typeMap[typeId] = typeDecoder | conditional_block |
decoder.py | #
# This file is part of pyasn1 software.
#
# Copyright (c) 2005-2017, Ilya Etingof <etingof@gmail.com>
# License: http://pyasn1.sf.net/license.html
#
from pyasn1.type import univ
from pyasn1.codec.cer import decoder
__all__ = ['decode']
class BitStringDecoder(decoder.BitStringDecoder):
supportConstructedForm = ... | decode = Decoder(tagMap, typeMap) | random_line_split | |
decoder.py | #
# This file is part of pyasn1 software.
#
# Copyright (c) 2005-2017, Ilya Etingof <etingof@gmail.com>
# License: http://pyasn1.sf.net/license.html
#
from pyasn1.type import univ
from pyasn1.codec.cer import decoder
__all__ = ['decode']
class BitStringDecoder(decoder.BitStringDecoder):
|
class OctetStringDecoder(decoder.OctetStringDecoder):
supportConstructedForm = False
# TODO: prohibit non-canonical encoding
RealDecoder = decoder.RealDecoder
tagMap = decoder.tagMap.copy()
tagMap.update(
{univ.BitString.tagSet: BitStringDecoder(),
univ.OctetString.tagSet: OctetStringDecoder(),
u... | supportConstructedForm = False | identifier_body |
FormRigDisplay.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'UI_RigDisplay.ui'
#
# Created: Wed Mar 21 21:43:33 2018
# by: pyside-uic 0.2.14 running on PySide 1.2.0
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class | (object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(236, 179)
self.verticalLayout = QtGui.QVBoxLayout(Form)
self.verticalLayout.setObjectName("verticalLayout")
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName("horiz... | Ui_Form | identifier_name |
FormRigDisplay.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'UI_RigDisplay.ui'
#
# Created: Wed Mar 21 21:43:33 2018
# by: pyside-uic 0.2.14 running on PySide 1.2.0
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_Form(object):
def setupUi(s... | Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8))
self.ChangeJointdrawStyle.setText(QtGui.QApplication.translate("Form", "Joint DrawStyle", None, QtGui.QApplication.UnicodeUTF8)) | identifier_body | |
FormRigDisplay.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'UI_RigDisplay.ui'
#
# Created: Wed Mar 21 21:43:33 2018
# by: pyside-uic 0.2.14 running on PySide 1.2.0
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_Form(object):
def setupUi(s... | Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8))
self.ChangeJointdrawStyle.setText(QtGui.QApplication.translate("Form", "Joint DrawStyle", None, QtGui.QApplication.UnicodeUTF8)) | QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form): | random_line_split |
filter-demo.component.ts | import {
Component
} from '@angular/core';
import {
SkyModalCloseArgs,
SkyModalService
} from '@skyux/modals';
import {
SkyFilterDemoModalComponent
} from './filter-demo-modal.component';
import {
SkyFilterDemoModalContext
} from './filter-demo-modal-context';
@Component({
selector: 'sky-filter-demo',
... | }
private filterItems(items: any[], filters: any[]) {
let i: number,
passesFilter: boolean,
result: any[] = [];
for (i = 0; i < items.length; i++) {
passesFilter = this.itemIsShown(filters, items[i]);
if (passesFilter) {
result.push(items[i]);
}
}
return resu... | return passesFilter; | random_line_split |
filter-demo.component.ts | import {
Component
} from '@angular/core';
import {
SkyModalCloseArgs,
SkyModalService
} from '@skyux/modals';
import {
SkyFilterDemoModalComponent
} from './filter-demo-modal.component';
import {
SkyFilterDemoModalContext
} from './filter-demo-modal-context';
@Component({
selector: 'sky-filter-demo',
... |
private orangeFilterFailed(filter: any, item: any) {
return filter.name === 'hideOrange' && filter.value && item.color === 'orange';
}
private fruitTypeFilterFailed(filter: any, item: any) {
return filter.name === 'fruitType' && filter.value !== 'any' && filter.value !== item.type;
}
private itemI... | {
this.appliedFilters.splice(index, 1);
this.filteredItems = this.filterItems(this.items, this.appliedFilters);
} | identifier_body |
filter-demo.component.ts | import {
Component
} from '@angular/core';
import {
SkyModalCloseArgs,
SkyModalService
} from '@skyux/modals';
import {
SkyFilterDemoModalComponent
} from './filter-demo-modal.component';
import {
SkyFilterDemoModalContext
} from './filter-demo-modal-context';
@Component({
selector: 'sky-filter-demo',
... | (
private modal: SkyModalService
) {
this.filteredItems = this.items.slice();
}
public filterButtonClicked() {
let modalInstance = this.modal.open(
SkyFilterDemoModalComponent,
[{
provide: SkyFilterDemoModalContext,
useValue: {
appliedFilters: this.appliedFilters... | constructor | identifier_name |
BeachAccess.js | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let BeachAccess = props =>
<SvgIcon {...props}>
<path d="M13.127 14.56l1.43-1.43 6.44 6.443L19.57 21zm4.293-5.73l2.86-2.86c-3.95-3.95-10.35-3.96-14.3-.02 3.93-1.3 8.31-.25 11.44 2.88zM5.95 5.98c-3.94 3.95-3.9... | BeachAccess = pure(BeachAccess);
BeachAccess.muiName = 'SvgIcon';
export default BeachAccess; | random_line_split | |
hmac.py | = """
gsutil hmac delete [-p <project>] <access_id>
"""
_GET_SYNOPSIS = """
gsutil hmac get [-p <project>] <access_id>
"""
_LIST_SYNOPSIS = """
gsutil hmac list [-a] [-l] [-p <project>] [-u <service_account_email>]
"""
_UPDATE_SYNOPSIS = """
gsutil hmac update -s (ACTIVE|INACTIVE) [-e <etag>] [-p <project>]... | The ``hmac get`` command retrieves the specified HMAC key's metadata:
gsutil hmac get GOOG56JBMFZX6PMPTQ62VD2
Note that there is no option to retrieve a key's secret material after it has
been created.
<B>GET OPTIONS</B>
The ``get`` sub-command has the following option
-p <project_id> Spec... | """
_GET_DESCRIPTION = """
<B>GET</B> | random_line_split |
hmac.py | _DESCRIPTION = """
<B>CREATE</B>
The ``hmac create`` command creates an HMAC key for the specified service
account:
gsutil hmac create test.service.account@test_project.iam.gserviceaccount.com
The secret key material is only available upon creation, so be sure to store
the returned secret along with the a... | """Lists HMAC keys for a project or service account."""
if self.args:
raise CommandException(
'%s %s received unexpected arguments.\n%s' %
(self.command_name, self.action_subcommand, _LIST_SYNOPSIS))
gsutil_api = GetCloudApiInstance(self, thread_state=thread_state)
response = gsu... | identifier_body | |
hmac.py | <project>] <access_id>
"""
_CREATE_DESCRIPTION = """
<B>CREATE</B>
The ``hmac create`` command creates an HMAC key for the specified service
account:
gsutil hmac create test.service.account@test_project.iam.gserviceaccount.com
The secret key material is only available upon creation, so be sure to store
... | print(_KeyMetadataOutput(item))
print() | conditional_block | |
hmac.py | """
gsutil hmac delete [-p <project>] <access_id>
"""
_GET_SYNOPSIS = """
gsutil hmac get [-p <project>] <access_id>
"""
_LIST_SYNOPSIS = """
gsutil hmac list [-a] [-l] [-p <project>] [-u <service_account_email>]
"""
_UPDATE_SYNOPSIS = """
gsutil hmac update -s (ACTIVE|INACTIVE) [-e <etag>] [-p <project>] <... | (self, thread_state=None):
"""Gets HMAC key from its Access Id."""
if self.args:
access_id = self.args[0]
else:
raise _AccessIdException(self.command_name, self.action_subcommand,
_GET_SYNOPSIS)
gsutil_api = GetCloudApiInstance(self, thread_state=thread_state)... | _GetHmacKey | identifier_name |
3sum-closest.py | # Time: O(n^2)
# Space: O(1)
#
# Given an array S of n integers,
# find three integers in S such that the sum is closest to a given number, target.
# Return the sum of the three integers.
# You may assume that each input would have exactly one solution.
#
# For example, given array S = {-1 2 1 -4}, and target = 1.
... | (self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums, result, min_diff, i = sorted(nums), float("inf"), float("inf"), 0
while i < len(nums) - 2:
if i == 0 or nums[i] != nums[i - 1]:
j, k = i + 1, len(nu... | threeSumClosest | identifier_name |
3sum-closest.py | # Time: O(n^2)
# Space: O(1)
#
# Given an array S of n integers,
# find three integers in S such that the sum is closest to a given number, target.
# Return the sum of the three integers.
# You may assume that each input would have exactly one solution.
#
# For example, given array S = {-1 2 1 -4}, and target = 1.
... | return target
i += 1
return result
if __name__ == '__main__':
result = Solution().threeSumClosest([-1, 2, 1, -4], 1)
print result
| def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums, result, min_diff, i = sorted(nums), float("inf"), float("inf"), 0
while i < len(nums) - 2:
if i == 0 or nums[i] != nums[i - 1]:
j... | identifier_body |
3sum-closest.py | # Time: O(n^2)
# Space: O(1)
#
# Given an array S of n integers,
# find three integers in S such that the sum is closest to a given number, target.
# Return the sum of the three integers.
# You may assume that each input would have exactly one solution.
#
# For example, given array S = {-1 2 1 -4}, and target = 1.
... | if abs(diff) < min_diff:
min_diff = abs(diff)
result = nums[i] + nums[j] + nums[k]
if diff < 0:
j += 1
elif diff > 0:
k -= 1
else:
... | while j < k:
diff = nums[i] + nums[j] + nums[k] - target | random_line_split |
3sum-closest.py | # Time: O(n^2)
# Space: O(1)
#
# Given an array S of n integers,
# find three integers in S such that the sum is closest to a given number, target.
# Return the sum of the three integers.
# You may assume that each input would have exactly one solution.
#
# For example, given array S = {-1 2 1 -4}, and target = 1.
... | result = Solution().threeSumClosest([-1, 2, 1, -4], 1)
print result | conditional_block | |
no-unexpected-multiline.js | /**
* @fileoverview Rule to spot scenarios where a newline looks like it is ending a statement, but is not.
* @author Glen Mailer
* @copyright 2015 Glen Mailer
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------... |
//--------------------------------------------------------------------------
// Public API
//--------------------------------------------------------------------------
return {
"MemberExpression": function(node) {
if (!node.computed) {
return;
}
... | {
var tokens = context.getTokensBefore(node, 2);
var paren = tokens[1];
var before = tokens[0];
if (paren.loc.start.line !== before.loc.end.line) {
context.report(node, paren.loc.start, msg, { char: paren.value });
}
} | identifier_body |
no-unexpected-multiline.js | /**
* @fileoverview Rule to spot scenarios where a newline looks like it is ending a statement, but is not.
* @author Glen Mailer
* @copyright 2015 Glen Mailer
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------... |
}
//--------------------------------------------------------------------------
// Public API
//--------------------------------------------------------------------------
return {
"MemberExpression": function(node) {
if (!node.computed) {
return;
}
... | {
context.report(node, paren.loc.start, msg, { char: paren.value });
} | conditional_block |
no-unexpected-multiline.js | /**
* @fileoverview Rule to spot scenarios where a newline looks like it is ending a statement, but is not.
* @author Glen Mailer
* @copyright 2015 Glen Mailer
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------... | (node, msg) {
var tokens = context.getTokensBefore(node, 2);
var paren = tokens[1];
var before = tokens[0];
if (paren.loc.start.line !== before.loc.end.line) {
context.report(node, paren.loc.start, msg, { char: paren.value });
}
}
//--------------------------... | checkForBreakBefore | identifier_name |
no-unexpected-multiline.js | /**
* @fileoverview Rule to spot scenarios where a newline looks like it is ending a statement, but is not.
* @author Glen Mailer
* @copyright 2015 Glen Mailer
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------... | * @returns {void}
* @private
*/
function checkForBreakBefore(node, msg) {
var tokens = context.getTokensBefore(node, 2);
var paren = tokens[1];
var before = tokens[0];
if (paren.loc.start.line !== before.loc.end.line) {
context.report(node, paren.loc.start,... | * line's expression
* @param {ASTNode} node The node to check.
* @param {string} msg The error message to use. | random_line_split |
wager_test_01.py | import os
import sys
import pygame
import signal
import time
import ConfigParser
from twython import TwythonStreamer
#-----------------------------------------------------------------------------
# Import custom modules
#-----------------------------------------------------------------------------
# Add pyscope modul... |
return False
#-----------------------------------------------------------------------------
# Main
#-----------------------------------------------------------------------------
def main():
global g_bet_loop
global g_scope
global g_terms
# Setup Twitter streamer
tf = twit_feed.TwitFeed(AUTH... | if ''.join(['#', entry]) == term:
return True | conditional_block |
wager_test_01.py | import os
import sys
import pygame
import signal
import time
import ConfigParser
from twython import TwythonStreamer
#-----------------------------------------------------------------------------
# Import custom modules
#-----------------------------------------------------------------------------
# Add pyscope modul... | ():
global g_bet_loop
global g_scope
global g_terms
# Setup Twitter streamer
tf = twit_feed.TwitFeed(AUTH)
#tf = tf_test_02.TwitFeed(AUTH)
# Tweet that we are accepting bets
# Start streamer to search for terms
tf.start_track_streamer(BET_TERM)
# Setup display
pygame.ini... | main | identifier_name |
wager_test_01.py | import os
import sys
import pygame
import signal
import time
import ConfigParser
from twython import TwythonStreamer
#-----------------------------------------------------------------------------
# Import custom modules
#-----------------------------------------------------------------------------
# Add pyscope modul... |
# Draw title
title1 = "The Great American"
title2 = "Tweet Race"
text_title_1 = font_title_1.render(title1,1,BLACK)
text_title_2 = font_title_2.render(title2,1,BLACK)
g_scope.screen.blit(text_title_1, (40, 25))
g_scope.screen.blit(text_title_2, (130, 70))
# Draw game mode
mode_... | rect_tweets = pygame.draw.rect(g_scope.screen, WHITE, \
(20, 340, 500, 300), 0) | random_line_split |
wager_test_01.py | import os
import sys
import pygame
import signal
import time
import ConfigParser
from twython import TwythonStreamer
#-----------------------------------------------------------------------------
# Import custom modules
#-----------------------------------------------------------------------------
# Add pyscope modul... |
#-----------------------------------------------------------------------------
# Main
#-----------------------------------------------------------------------------
def main():
global g_bet_loop
global g_scope
global g_terms
# Setup Twitter streamer
tf = twit_feed.TwitFeed(AUTH)
#tf = tf_te... | global g_terms
for term in g_terms:
if ''.join(['#', entry]) == term:
return True
return False | identifier_body |
grid.js | (function() {
'use strict';
/*
* This feature allows you to specify a grid over a portion or the entire chart area. | * @name grid
*/
d4.feature('grid', function(name) {
var xAxis = d3.svg.axis();
var yAxis = d3.svg.axis();
return {
accessors: {
formatXAxis: function(xAxis) {
return xAxis.orient('bottom');
},
formatYAxis: function(yAxis) {
return yAxis.orient('le... | * | random_line_split |
ZHHantWeekdayParser.ts | import dayjs from "dayjs";
import { ParsingContext } from "../../../../chrono";
import { AbstractParserWithWordBoundaryChecking } from "../../../../common/parsers/AbstractParserWithWordBoundary";
import { ParsingResult } from "../../../../results";
import { WEEKDAY_OFFSET } from "../constants";
const PATTERN = new Reg... | rExtract(context: ParsingContext, match: RegExpMatchArray): ParsingResult {
const result = context.createParsingResult(match.index, match[0]);
const dayOfWeek = match.groups.weekday;
const offset = WEEKDAY_OFFSET[dayOfWeek];
if (offset === undefined) return null;
let startMomen... | return PATTERN;
}
inne | identifier_body |
ZHHantWeekdayParser.ts | import dayjs from "dayjs";
import { ParsingContext } from "../../../../chrono";
import { AbstractParserWithWordBoundaryChecking } from "../../../../common/parsers/AbstractParserWithWordBoundary";
import { ParsingResult } from "../../../../results";
import { WEEKDAY_OFFSET } from "../constants";
const PATTERN = new Reg... | ParsingContext, match: RegExpMatchArray): ParsingResult {
const result = context.createParsingResult(match.index, match[0]);
const dayOfWeek = match.groups.weekday;
const offset = WEEKDAY_OFFSET[dayOfWeek];
if (offset === undefined) return null;
let startMoment = dayjs(context.... | ct(context: | identifier_name |
ZHHantWeekdayParser.ts |
const PATTERN = new RegExp("(?:星期|禮拜|週)(?<weekday>" + Object.keys(WEEKDAY_OFFSET).join("|") + ")");
export default class ZHHantWeekdayParser extends AbstractParserWithWordBoundaryChecking {
innerPattern(): RegExp {
return PATTERN;
}
innerExtract(context: ParsingContext, match: RegExpMatchArray): ... | import dayjs from "dayjs";
import { ParsingContext } from "../../../../chrono";
import { AbstractParserWithWordBoundaryChecking } from "../../../../common/parsers/AbstractParserWithWordBoundary";
import { ParsingResult } from "../../../../results";
import { WEEKDAY_OFFSET } from "../constants"; | random_line_split | |
solicit_reviews.py | from django.core.management.base import BaseCommand
from aspc.courses.models import Schedule
from datetime import datetime, timedelta
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
from aspc.settings import EMAIL_HOST_USER
# Assum... | for schedule in schedules:
try:
context = Context({'user': schedule.user, 'courses': schedule.sections.all()})
text_content = plaintext.render(context)
html_content = htmly.render(context)
user_data = schedule.user.user.all()
... | schedules = Schedule.objects.filter(create_ts__lte=datetime.now()-timedelta(days=MIN_DAYS),
create_ts__gte=datetime.now()-timedelta(days=MAX_DAYS))
emails_sent = 0 | random_line_split |
solicit_reviews.py | from django.core.management.base import BaseCommand
from aspc.courses.models import Schedule
from datetime import datetime, timedelta
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
from aspc.settings import EMAIL_HOST_USER
# Assum... | except Exception as e:
self.stdout.write('Error: %s\n' % e)
self.stdout.write('Successfully send %s emails\n' % emails_sent)
| args = ''
help = 'imports terms'
def handle(self, *args, **options):
plaintext = get_template('email/solicit_reviews.txt')
htmly = get_template('email/solicit_reviews.html')
schedules = Schedule.objects.filter(create_ts__lte=datetime.now()-timedelta(days=MIN_DAYS),
... | identifier_body |
solicit_reviews.py | from django.core.management.base import BaseCommand
from aspc.courses.models import Schedule
from datetime import datetime, timedelta
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
from aspc.settings import EMAIL_HOST_USER
# Assum... | (self, *args, **options):
plaintext = get_template('email/solicit_reviews.txt')
htmly = get_template('email/solicit_reviews.html')
schedules = Schedule.objects.filter(create_ts__lte=datetime.now()-timedelta(days=MIN_DAYS),
create_ts__gte=datetime.n... | handle | identifier_name |
solicit_reviews.py | from django.core.management.base import BaseCommand
from aspc.courses.models import Schedule
from datetime import datetime, timedelta
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
from aspc.settings import EMAIL_HOST_USER
# Assum... |
except Exception as e:
self.stdout.write('Error: %s\n' % e)
self.stdout.write('Successfully send %s emails\n' % emails_sent)
| msg = EmailMultiAlternatives(EMAIL_TITLE, text_content, EMAIL_HOST_USER, [schedule.user.email])
msg.attach_alternative(html_content, "text/html")
msg.send()
emails_sent += 1 | conditional_block |
hooks.py | # Copyright 2020 Tecnativa - Alexandre Díaz
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from copy import deepcopy
from xml.sax.saxutils import escape
from lxml import etree as ElementTree
from odoo import SUPERUSER_ID, api
def _ | env, xmlids):
old_view_ids = env["ir.ui.view"].search(
[("key", "in", xmlids), ("active", "=", True)]
)
# Get only the edited version of the views (if has it)
old_view_ids_edited = old_view_ids.filtered("website_id")
old_view_ids_edited_keys = old_view_ids_edited.mapped("key")
views_to_d... | merge_views( | identifier_name |
hooks.py | # Copyright 2020 Tecnativa - Alexandre Díaz
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from copy import deepcopy
from xml.sax.saxutils import escape
from lxml import etree as ElementTree
from odoo import SUPERUSER_ID, api
def _merge_views(env, xmlids):
old_view_ids = env["ir.ui.view"].searc... | ith api.Environment.manage():
env = api.Environment(cr, SUPERUSER_ID, {})
is_website_sale_installed = (
env["ir.module.module"].search_count(
[("name", "=", "website_sale"), ("state", "=", "installed")]
)
> 0
)
if is_website_sale_instal... | identifier_body | |
hooks.py | # Copyright 2020 Tecnativa - Alexandre Díaz
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from copy import deepcopy
from xml.sax.saxutils import escape
from lxml import etree as ElementTree
from odoo import SUPERUSER_ID, api
def _merge_views(env, xmlids):
old_view_ids = env["ir.ui.view"].searc... | merge_views(env, ["website_sale.terms"])
| conditional_block | |
hooks.py | # Copyright 2020 Tecnativa - Alexandre Díaz
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from copy import deepcopy
from xml.sax.saxutils import escape
from lxml import etree as ElementTree
from odoo import SUPERUSER_ID, api
def _merge_views(env, xmlids):
old_view_ids = env["ir.ui.view"].searc... | "<a class='legal_anchor' id='%s'/>" % anchor_name
)
)
for children in old_content.getchildren():
sections_content.append(children)
views_done |= old_view_id
old_view_ids -= views_done
# Create a new page with the cha... | sections_content.append(deepcopy(separator))
sections_content.append(
ElementTree.fromstring( | random_line_split |
cacconsole.py | #!/usr/bin/python
# CACConsole Copyright (C) 2015 foospidy
# https://github.com/foospidy/CACConsole
# See LICENSE for details
# This software includes/uses the python-cloudatcost library which
# is MIT licensed, see https://github.com/adc4392/python-cloudatcost/blob/master/LICENSE
import os
import sys
from twisted.int... |
log_file = DailyLogFile(log_file_name, log_path)
file_log_observer = FileLogObserver(log_file)
file_log_observer.timeFormat = "%Y-%m-%d %H:%M:%S,%f,"
# start logging
log.startLoggingWithObserver(file_log_observer.emit, False)
# setup local database
dbfile = os.path.dirname(os.path.abs... | os.makedirs(os.path.dirname(log_path)) | conditional_block |
cacconsole.py | #!/usr/bin/python
# CACConsole Copyright (C) 2015 foospidy
# https://github.com/foospidy/CACConsole
# See LICENSE for details
# This software includes/uses the python-cloudatcost library which | from twisted.python import log
from twisted.python.log import ILogObserver, FileLogObserver
from twisted.python.logfile import DailyLogFile
from modules.CloudAtCostConsole import CloudAtCostConsole
# prevent creation of compiled bytecode files
sys.dont_write_bytecode = True
# setup log file
log_path = os.path.di... | # is MIT licensed, see https://github.com/adc4392/python-cloudatcost/blob/master/LICENSE
import os
import sys
from twisted.internet import reactor, stdio | random_line_split |
grouputils.py | #
# 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, software
# ... |
return [r.FnGetRefId() for r in members
if r.FnGetRefId() not in exclude]
def get_member_names(group):
"""Get a list of resource names of the resources in the specified group.
Failed resources will be ignored.
"""
return [r.name for r in get_members(group)]
def get_resource(stack, r... | exclude = [] | conditional_block |
grouputils.py | #
# 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, software
# ... |
def get_rsrc_id(stack, key, use_indices, resource_name):
resource = get_resource(stack, resource_name, use_indices, key)
if resource:
return resource.FnGetRefId()
def get_nested_attrs(stack, key, use_indices, *path):
path = key.split(".", 2)[1:] + list(path)
if len(path) > 1:
return ... | resource = get_resource(stack, resource_name, use_indices, key)
if resource:
return resource.FnGetAtt(*attr_path) | random_line_split |
grouputils.py | #
# 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, software
# ... |
def get_member_names(group):
"""Get a list of resource names of the resources in the specified group.
Failed resources will be ignored.
"""
return [r.name for r in get_members(group)]
def get_resource(stack, resource_name, use_indices, key):
nested_stack = stack.nested()
if not nested_stack... | """Get a list of member resources managed by the specified group.
The list of resources is sorted first by created_time then by name.
"""
members = get_members(group)
if len(members) == 0:
return []
if exclude is None:
exclude = []
return [r.FnGetRefId() for r in members
... | identifier_body |
grouputils.py | #
# 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, software
# ... | (stack, key, use_indices, resource_name, *attr_path):
resource = get_resource(stack, resource_name, use_indices, key)
if resource:
return resource.FnGetAtt(*attr_path)
def get_rsrc_id(stack, key, use_indices, resource_name):
resource = get_resource(stack, resource_name, use_indices, key)
if re... | get_rsrc_attr | identifier_name |
viewportConfiguration.js | /*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file ... |
} else{
this.removeClass(moduleMenuSnappingClass);
}
}
}
},
{
region: 'center',
layout: 'border',
border: false,
items: [
{
region: 'west',
layout: 'fit',
id: 'typo3-navigationContainer',
width: 300,
minWidth: 20,
floatable: true,
animCollap... | {
TYPO3.Backend.syncSize();
} | conditional_block |
viewportConfiguration.js | /*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file ... | cards: [
// add the old card to be compatible
{
id: 'typo3-contentContainer',
border: false,
xtype: 'backendContentIframePanel',
name: 'content'
}
]
};
/**
* The backend viewport configuration
*/
TYPO3.Viewport.configuration = {
layout: 'border',
id: 'typo3-viewport',
renderTo: Ext.getBody(),... | this.cards.push(config);
}
}, | random_line_split |
pulp_simulator.py | () :
return load_features_json('linrel_features.json')
def load_topics() :
return load_features_json('linrel_topics.json')
def get_machine_learning_articles() :
return [ int(k) for k,v in load_topics().iteritems() if 'stat.ML' in v ]
def order_keys_by_value(d) :
return [ i[0] for i in sorted(d.items(... | load_features | identifier_name | |
pulp_simulator.py |
def load_topics() :
return load_features_json('linrel_topics.json')
def get_machine_learning_articles() :
return [ int(k) for k,v in load_topics().iteritems() if 'stat.ML' in v ]
def order_keys_by_value(d) :
return [ i[0] for i in sorted(d.items(), key=lambda x : x[1], reverse=True) ]
def okapi_bm25(qu... | return load_features_json('linrel_features.json') | identifier_body | |
pulp_simulator.py |
return top_n, \
mean[ numpy.array(top_n) ].transpose().tolist()[0], \
variance[ numpy.array(top_n) ].transpose().tolist()[0]
def average_distance_to_target(articles, target, distances) :
return numpy.min(distances[ numpy.array(articles) ])
def main() :
if len(argv) != 4 :
p... | feedback = [ int(i) for i in feedback ]
for i in zip(iterations, articles, feedback, means, variances) :
print >> f, "%d %d %d %e %e" % i | random_line_split | |
pulp_simulator.py | :
return [ i[0] for i in sorted(d.items(), key=lambda x : x[1], reverse=True) ]
def okapi_bm25(query, n, data, features) :
stemmer = SnowballStemmer('english')
query_terms = [ stemmer.stem(term) for term in query.lower().split() ]
tmp = {}
for qt in query_terms :
if qt not in features :
... |
return order_keys_by_value(tmp)[:n]
def linrel(articles, feedback, n, data, features, mew=1.0, exploration_rate=0.1) :
assert len(articles) == len(feedback), "articles and feedback are not the same length"
X = data
num_articles = X.shape[0]
num_features = X.shape[1]
X_t = X[ numpy.array(ar... | akey = aindex.item()
if akey not in tmp :
tmp[akey] = 1.0
tmp[akey] *= data[aindex,findex] | conditional_block |
word_model.py | # -*- coding: utf-8 -*-
"""
Module to handle word vectors and initializing embeddings.
"""
| from collections import Counter
################################################################################
# WordModel Class #
################################################################################
class GloveModel(object):
def __init__(self, filename):
self.word_vecs = {}
self.v... | import numpy as np
from gensim.models.keyedvectors import KeyedVectors
from utils import constants as Constants
from utils.timer import Timer | random_line_split |
word_model.py | # -*- coding: utf-8 -*-
"""
Module to handle word vectors and initializing embeddings.
"""
import numpy as np
from gensim.models.keyedvectors import KeyedVectors
from utils import constants as Constants
from utils.timer import Timer
from collections import Counter
###################################################... | self.vocab[key] = len(self.vocab) + 1
n_added = 0
for w, count in additional_vocab.most_common():
if w not in self.vocab:
self.vocab[w] = len(self.vocab) + 1
n_added += 1
if n_added <= 10:
print('Added word:... | """Class to get pretrained word vectors for a list of sentences. Can be used
for any pretrained word vectors.
"""
def __init__(self, embed_size=None, filename=None, embed_type='glove', top_n=None, additional_vocab=Counter()):
if filename is None:
if embed_size is None:
r... | identifier_body |
word_model.py | # -*- coding: utf-8 -*-
"""
Module to handle word vectors and initializing embeddings.
"""
import numpy as np
from gensim.models.keyedvectors import KeyedVectors
from utils import constants as Constants
from utils.timer import Timer
from collections import Counter
###################################################... | (self, filename):
self.word_vecs = {}
self.vocab = []
with open(filename, 'r') as input_file:
for line in input_file.readlines():
splitLine = line.split(' ')
w = splitLine[0]
self.word_vecs[w] = np.array([float(val) for val in splitLine... | __init__ | identifier_name |
word_model.py | # -*- coding: utf-8 -*-
"""
Module to handle word vectors and initializing embeddings.
"""
import numpy as np
from gensim.models.keyedvectors import KeyedVectors
from utils import constants as Constants
from utils.timer import Timer
from collections import Counter
###################################################... |
self.embed_size = embed_size
self._model = None
else:
self.set_model(filename, embed_type)
self.embed_size = self._model.vector_size
# padding: 0
self.vocab = {Constants._UNK_TOKEN: 1}
if self._model is not None:
for i, key in... | raise Exception('Either embed_file or embed_size needs to be specified.') | conditional_block |
api.rs | //! The Api system is responsible for talking to our Turtl server, and manages
//! our user authentication.
use ::std::io::Read;
use ::std::time::Duration;
use ::config;
use ::reqwest::{Method, blocking::RequestBuilder, blocking::Client, Url, Proxy};
use ::reqwest::header::{HeaderMap, HeaderValue};
pub use ::reqwest::... | (&self, req: RequestBuilder) -> RequestBuilder {
match self.config.auth.as_ref() {
Some(x) => req.header("Authorization", x.clone()),
None => req,
}
}
/// Set our standard auth header into a Headers set
fn set_standard_headers(&self, req: RequestBuilder) -> RequestBu... | set_auth_headers | identifier_name |
api.rs | //! The Api system is responsible for talking to our Turtl server, and manages
//! our user authentication.
use ::std::io::Read;
use ::std::time::Duration;
use ::config;
use ::reqwest::{Method, blocking::RequestBuilder, blocking::Client, Url, Proxy};
use ::reqwest::header::{HeaderMap, HeaderValue};
pub use ::reqwest::... | pub fn new() -> Api {
Api {
config: ApiConfig::new(),
}
}
/// Set the API's authentication
pub fn set_auth(&mut self, auth: String) -> MResult<()> {
let auth_str = String::from("user:") + &auth;
let base_auth = crypto::to_base64(&Vec::from(auth_str.as_bytes()... |
impl Api {
/// Create an Api | random_line_split |
urls.py | # This file is part of authapi.
# Copyright (C) 2014-2020 Agora Voting SL <contact@nvotes.com>
# authapi is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License.
# authapi is... | ] | random_line_split | |
divide.ts | import { isBigInt, toBigIntOrThrow } from '@terascope/utils';
import { FieldType } from '@terascope/types';
import {
FieldTransformConfig,
ProcessMode,
FunctionDefinitionType,
FunctionDefinitionCategory
} from '../interfaces';
export interface DivideArgs {
readonly value: number
}
function isLarge... | fields: { testField: { type: FieldType.Long } }
},
field: 'testField',
input: 10,
output: 5
}
],
create({ args: { value }, inputConfig }) {
if (isLargeNumberType(inputConfig?.field_config.type as FieldType|undefined)) {
... | config: {
version: 1, | random_line_split |
divide.ts | import { isBigInt, toBigIntOrThrow } from '@terascope/utils';
import { FieldType } from '@terascope/types';
import {
FieldTransformConfig,
ProcessMode,
FunctionDefinitionType,
FunctionDefinitionCategory
} from '../interfaces';
export interface DivideArgs {
readonly value: number
}
function isLarge... | (value: number|bigint): (input: unknown) => number|bigint {
const bigInt = isBigInt(value);
return function _divide(num) {
if (bigInt && !isBigInt(num)) {
return toBigIntOrThrow(num) / (value as bigint);
}
return (num as number) / (value as number);
};
}
| divideFP | identifier_name |
divide.ts | import { isBigInt, toBigIntOrThrow } from '@terascope/utils';
import { FieldType } from '@terascope/types';
import {
FieldTransformConfig,
ProcessMode,
FunctionDefinitionType,
FunctionDefinitionCategory
} from '../interfaces';
export interface DivideArgs {
readonly value: number
}
function isLarge... |
export const divideConfig: FieldTransformConfig<DivideArgs> = {
name: 'divide',
type: FunctionDefinitionType.FIELD_TRANSFORM,
process_mode: ProcessMode.INDIVIDUAL_VALUES,
category: FunctionDefinitionCategory.NUMERIC,
description: 'Returns the quotient from the input divided by the args value.',
... | {
if (type == null) return false;
return type === FieldType.Long;
} | identifier_body |
retry.py | # Copyright 2022 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, ... |
time.sleep(interval)
time_elapsed = time.time() - start_time
raise exc_type("Timeout in {}s. Tried calling {} {} times.".format(
time_elapsed, func.__name__, tried_times))
| return func_result | conditional_block |
retry.py | # Copyright 2022 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, ... |
def is_true(val: Any) -> bool:
"""Returns True if bool(val) evaluates to True."""
return bool(val)
_FuncReturnType = TypeVar("_FuncReturnType")
def retry(
func: Callable[..., _FuncReturnType],
func_args: Sequence[Any] = (),
func_kwargs: Optional[Mapping[str, Any]] = None,
is_successful: Calla... | """Returns True if bool(val) evaluates to False."""
return not bool(val) | identifier_body |
retry.py | # Copyright 2022 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, ... |
Returns:
Return value of first successful func() call.
Raises:
Exception: if timeout is reached, or if an Exception occurs in func() with
reraise=True.
"""
if func_kwargs is None:
func_kwargs = {}
tried_times = 0
start_time = time.time()
end_time = start_time + timeout
while time.tim... | re-raise any exceptions from func(). If False, considers execution of
func() a failure if an Exception is raised. is_successful() will NOT be
called if an Exception occurs.
exc_type: Type of exception to raise when timeout is reached. Note that the
class constructor will be called with just 1 ... | random_line_split |
retry.py | # Copyright 2022 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, ... | (_: Any) -> bool:
return True
def not_func(val: Any) -> bool:
"""Returns True if bool(val) evaluates to False."""
return not bool(val)
def is_true(val: Any) -> bool:
"""Returns True if bool(val) evaluates to True."""
return bool(val)
_FuncReturnType = TypeVar("_FuncReturnType")
def retry(
func: Ca... | _default_is_successful | identifier_name |
loader.rs | set of candidates
// keyed of the filename hash listed. For each filename, we also have a
// list of rlibs/dylibs that apply. Here, we map each of these lists
// (per hash), to a Library candidate for returning.
//
// A Library candidate is created if the metadata for the set of... | random_line_split | ||
loader.rs | {
archive: ArchiveRO,
// See comments in ArchiveMetadata::new for why this is static
data: &'static [u8],
}
pub struct CratePaths {
pub ident: String,
pub dylib: Option<Path>,
pub rlib: Option<Path>
}
impl CratePaths {
fn paths(&self) -> Vec<Path> {
match (&self.dylib, &self.rlib)... | ArchiveMetadata | identifier_name | |
loader.rs | }
Err(_) => {
info!("no metadata found");
continue
}
};
if ret.is_some() {
self.sess.span_err(self.span,
format!("multiple {} candidates for `{}` \
... | {
match get_metadata_section(os, path) {
Ok(bytes) => decoder::list_crate_metadata(bytes.as_slice(), out),
Err(msg) => {
write!(out, "{}\n", msg)
}
}
} | identifier_body | |
index.js | // @ts-nocheck
'use strict';
const _ = require('lodash');
const isStandardSyntaxAtRule = require('../../utils/isStandardSyntaxAtRule');
const report = require('../../utils/report');
const ruleMessages = require('../../utils/ruleMessages');
const validateOptions = require('../../utils/validateOptions');
const vendor =... | message: messages.rejected(name),
node: atRule,
result,
ruleName,
});
});
};
}
rule.primaryOptionArray = true;
rule.ruleName = ruleName;
rule.messages = messages;
rule.meta = { deprecated: true };
module.exports = rule; | random_line_split | |
index.js | // @ts-nocheck
'use strict';
const _ = require('lodash');
const isStandardSyntaxAtRule = require('../../utils/isStandardSyntaxAtRule');
const report = require('../../utils/report');
const ruleMessages = require('../../utils/ruleMessages');
const validateOptions = require('../../utils/validateOptions');
const vendor =... |
report({
message: messages.rejected(name),
node: atRule,
result,
ruleName,
});
});
};
}
rule.primaryOptionArray = true;
rule.ruleName = ruleName;
rule.messages = messages;
rule.meta = { deprecated: true };
module.exports = rule;
| {
return;
} | conditional_block |
index.js | // @ts-nocheck
'use strict';
const _ = require('lodash');
const isStandardSyntaxAtRule = require('../../utils/isStandardSyntaxAtRule');
const report = require('../../utils/report');
const ruleMessages = require('../../utils/ruleMessages');
const validateOptions = require('../../utils/validateOptions');
const vendor =... | (listInput) {
// To allow for just a string as a parameter (not only arrays of strings)
const list = [].concat(listInput);
return (root, result) => {
const validOptions = validateOptions(result, ruleName, {
actual: list,
possible: [_.isString],
});
if (!validOptions) {
return;
}
result.warn(`'$... | rule | identifier_name |
index.js | // @ts-nocheck
'use strict';
const _ = require('lodash');
const isStandardSyntaxAtRule = require('../../utils/isStandardSyntaxAtRule');
const report = require('../../utils/report');
const ruleMessages = require('../../utils/ruleMessages');
const validateOptions = require('../../utils/validateOptions');
const vendor =... | const name = atRule.name;
if (!isStandardSyntaxAtRule(atRule)) {
return;
}
if (list.includes(vendor.unprefixed(name).toLowerCase())) {
return;
}
report({
message: messages.rejected(name),
node: atRule,
result,
ruleName,
});
});
};
}
rule.primaryOptionArray = true;
r... | {
// To allow for just a string as a parameter (not only arrays of strings)
const list = [].concat(listInput);
return (root, result) => {
const validOptions = validateOptions(result, ruleName, {
actual: list,
possible: [_.isString],
});
if (!validOptions) {
return;
}
result.warn(`'${ruleName}' ... | identifier_body |
Find.ts | import { Universe } from '@ephox/boss';
import { Optional } from '@ephox/katamari';
import { PositionArray } from '@ephox/polaris';
import * as Spot from '../api/data/Spot';
import { SpotPoint } from '../api/data/Types';
import * as Extract from './Extract';
import * as TypedList from './TypedList';
/**
* Finds an e... | return Spot.point(v.element, offset - v.start);
});
};
export {
find
}; | random_line_split | |
HttpRequest.ts |
/*
* HttpRequest
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Mient-jan Stelling
* Copyright (c) 2015 MediaMonks B.V
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
... |
};
client.onerror = function () {
reject(this.statusText);
};
});
// Return the promise
return promise;
}
/**
*
* @param {string} url
* @param {IHashMap<any>} query
* @returns {Promise<string>}
*/
public static getString<T>(url:string, query:IHashMap<any> = {}):Promise<T>
{
return... | {
// Performs the function "reject" when this.status is different than 200
reject(this.statusText);
} | conditional_block |
HttpRequest.ts | /*
* HttpRequest
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Mient-jan Stelling
* Copyright (c) 2015 MediaMonks B.V
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
*... | {
/**
* @static
* @method request
* @param {string} method
* @param {string} url
* @param {Array<string>} args
* @returns {Promise}
*/
private static request(method:string, url:string, args:IHashMap<string>):Promise<any>
{
// Creating a promise
var promise = new Promise(function(resolve:Function, r... | random_line_split | |
HttpRequest.ts |
/*
* HttpRequest
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Mient-jan Stelling
* Copyright (c) 2015 MediaMonks B.V
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
... |
{
/**
* @static
* @method request
* @param {string} method
* @param {string} url
* @param {Array<string>} args
* @returns {Promise}
*/
private static request(method:string, url:string, args:IHashMap<string>):Promise<any>
{
// Creating a promise
var promise = new Promise(function(resolve:Function, ... | HttpRequest | identifier_name |
HttpRequest.ts |
/*
* HttpRequest
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Mient-jan Stelling
* Copyright (c) 2015 MediaMonks B.V
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
... |
}
| {
return HttpRequest.getString(url, query).then((response:string) => {
return JSON.parse(response);
});
} | identifier_body |
dft.py | import numpy as np
from pyquante2.dft.functionals import xs,cvwn5
# Maybe move these to the functionals module and import from there?
xname = dict(lda=xs,xs=xs,svwn=xs)
cname = dict(lda=cvwn5,svwn=cvwn5,xs=None)
def get_xc(grid,D,**kwargs):
xcname = kwargs.get('xcname','lda')
# Does not work on either gradien... |
w = grid.points[:,3]
Vxc = np.einsum('g,g,gI,gJ->IJ',w,dfxa+dfca,grid.bfamps,grid.bfamps)
# The fx comes from either the up or the down spin, whereas the fc comes from
# both (which is why x is called with either one, and c is called with both
Exc = np.dot(w,2*fx+fc)
return Exc,Vxc
... | fc=dfca=dfcb=0 | conditional_block |
dft.py | import numpy as np
from pyquante2.dft.functionals import xs,cvwn5
# Maybe move these to the functionals module and import from there?
xname = dict(lda=xs,xs=xs,svwn=xs)
cname = dict(lda=cvwn5,svwn=cvwn5,xs=None)
def get_xc(grid,D,**kwargs):
| xcname = kwargs.get('xcname','lda')
# Does not work on either gradient corrected functionals or spin-polarized functionals yet.
xfunc = xname[xcname]
cfunc = cname[xcname]
rho = grid.getdens(D)
fx,dfxa = xfunc(rho)
if cfunc:
fc,dfca,dfcb = cfunc(rho,rho)
else:
fc=df... | identifier_body | |
dft.py | import numpy as np
from pyquante2.dft.functionals import xs,cvwn5
# Maybe move these to the functionals module and import from there?
xname = dict(lda=xs,xs=xs,svwn=xs)
cname = dict(lda=cvwn5,svwn=cvwn5,xs=None)
def get_xc(grid,D,**kwargs):
xcname = kwargs.get('xcname','lda')
# Does not work on either gradien... | return Exc,Vxc | random_line_split | |
dft.py | import numpy as np
from pyquante2.dft.functionals import xs,cvwn5
# Maybe move these to the functionals module and import from there?
xname = dict(lda=xs,xs=xs,svwn=xs)
cname = dict(lda=cvwn5,svwn=cvwn5,xs=None)
def | (grid,D,**kwargs):
xcname = kwargs.get('xcname','lda')
# Does not work on either gradient corrected functionals or spin-polarized functionals yet.
xfunc = xname[xcname]
cfunc = cname[xcname]
rho = grid.getdens(D)
fx,dfxa = xfunc(rho)
if cfunc:
fc,dfca,dfcb = cfunc(rho,rho)
... | get_xc | identifier_name |
demo_tunneling_spawn_propagation_norm_threshold.py | algorithm = "spawning_adiabatic"
#algorithm = "hagedorn"
potential = "eckart"
T = 70
dt = 0.005
eps = 0.0234218**0.5
basis_size = 300 |
parameters = [ (0.1935842258501978j, 5.1657101481699996, 0.0, 0.24788547371, -7.55890450883) ]
coefficients = [[(0, 1.0)]]
leading_component = 0
f = 9.0
ngn = 4096
write_nth = 20
spawn_method = "projection"
spawn_max_order = 16
spawn_order = 0
spawn_condition = "high_k_norm_threshold"
spawn_K0 = 100
# 'Magic numb... | random_line_split | |
test_base_comment_template.py | # Copyright 2020 NextERP Romania SRL
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests import common
from .fake_models import ResUsers, setup_test_model, teardown_test_model
class TestCommentTemplate(common.SavepointCase):
@classmeth... | def test_template_name_get(self):
self.assertEqual(
self.before_template_id.display_name,
"Top template (Top)",
)
self.assertEqual(
self.after_template_id.display_name,
"Bottom template (Bottom)",
)
def test_general_template(self):... | ardown_test_model(cls.env, ResUsers)
super(TestCommentTemplate, cls).tearDownClass()
| identifier_body |
test_base_comment_template.py | # Copyright 2020 NextERP Romania SRL
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests import common
from .fake_models import ResUsers, setup_test_model, teardown_test_model
class TestCommentTemplate(common.SavepointCase):
@classmeth... | ls):
teardown_test_model(cls.env, ResUsers)
super(TestCommentTemplate, cls).tearDownClass()
def test_template_name_get(self):
self.assertEqual(
self.before_template_id.display_name,
"Top template (Top)",
)
self.assertEqual(
self.after_temp... | arDownClass(c | identifier_name |
test_base_comment_template.py | # Copyright 2020 NextERP Romania SRL
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests import common
from .fake_models import ResUsers, setup_test_model, teardown_test_model
class TestCommentTemplate(common.SavepointCase):
@classmeth... | ) | random_line_split | |
version_helpers.py | ropy.version module, the `major`, `minor`, and `bugfix`
variables hold the respective parts of the version number (bugfix is '0' if
absent). The `release` variable is True if this is a release, and False if this
is a development version of astropy. For the actual version string, use::
from astropy.version import v... | (packagename, fromlist=None):
"""Returns the package's .version module generated by
`astropy_helpers.version_helpers.generate_version_py`. Raises an
ImportError if the version module is not found.
If ``fromlist`` is an iterable, return a tuple of the members of the
version module corresponding to ... | get_pkg_version_module | identifier_name |
version_helpers.py | astropy.version module, the `major`, `minor`, and `bugfix`
variables hold the respective parts of the version number (bugfix is '0' if
absent). The `release` variable is True if this is a release, and False if this
is a development version of astropy. For the actual version string, use::
from astropy.version impo... | ========
>>> _version_split('1.2.3')
(1, 2, 3)
>>> _version_split('1.2')
(1, 2, 0)
>>> _version_split('1.2rc1')
(1, 2, 0)
>>> _version_split('1')
(1, 0, 0)
>>> _version_split('')
(0, 0, 0)
"""
parsed_version = pkg_resources.parse_version(version)
if hasattr(pars... | random_line_split | |
version_helpers.py | ropy.version module, the `major`, `minor`, and `bugfix`
variables hold the respective parts of the version number (bugfix is '0' if
absent). The `release` variable is True if this is a release, and False if this
is a development version of astropy. For the actual version string, use::
from astropy.version import v... |
else:
parts = []
for part in parsed_version:
if part.startswith('*'):
# Ignore any .dev, a, b, rc, etc.
break
parts.append(int(part))
if len(parts) < 3:
parts += [0] * (3 - len(parts))
# In principle a version could have more... | if parsed_version.base_version:
parts = [int(part)
for part in parsed_version.base_version.split('.')]
else:
parts = [] | conditional_block |
version_helpers.py | from . import git_helpers
from .distutils_helpers import is_distutils_display_option
from .utils import invalidate_caches
PY3 = sys.version_info[0] == 3
def _version_split(version):
"""
Split a version string into major, minor, and bugfix numbers. If any of
those numbers are missing the default is zero.... | """Returns the package's .version module generated by
`astropy_helpers.version_helpers.generate_version_py`. Raises an
ImportError if the version module is not found.
If ``fromlist`` is an iterable, return a tuple of the members of the
version module corresponding to the member names given in ``fromli... | identifier_body | |
ng2-wizard.component.ts | import { Component, ContentChildren, Input, Output, EventEmitter, QueryList, OnInit, AfterContentInit } from 'angular2/core';
import { Ng2WizardTab } from './ng2-wizard-tab.component';
import { Ng2WizardStep } from './ng2-wizard-step.component';
import { INg2WizardConfig } from './ng2-wizard.config';
@Component({
... |
}
private selectTab(newStep: Ng2WizardStep): void {
let previousTab: Ng2WizardTab = this.currentTab;
this.deactivateAllTabs();
this.tabs.forEach((tab) => {
tab.steps.forEach((step) => {
if (newStep === step) {
tab.active = ... | {
let step: Ng2WizardStep = this.steps[this.currentStepIndex - 1];
this.deactivateAllSteps();
step.active = true;
this.onPrevious.emit(null);
this.selectTab(step);
} | conditional_block |
ng2-wizard.component.ts | import { Component, ContentChildren, Input, Output, EventEmitter, QueryList, OnInit, AfterContentInit } from 'angular2/core';
import { Ng2WizardTab } from './ng2-wizard-tab.component';
import { Ng2WizardStep } from './ng2-wizard-step.component';
import { INg2WizardConfig } from './ng2-wizard.config';
@Component({
... |
private next(): void {
if (this.hasNextStep) {
let step: Ng2WizardStep = this.steps[this.currentStepIndex + 1];
this.deactivateAllSteps();
step.active = true;
this.onNext.emit(null);
this.selectTab(step);
}
}
private prev... | {
switch (direction) {
case NavigationDirection.NEXT:
this.next();
break;
case NavigationDirection.PREVIOUS:
this.previous();
break;
default:
throw new Error(direction + " is not a valid Navigatio... | identifier_body |
ng2-wizard.component.ts | import { Component, ContentChildren, Input, Output, EventEmitter, QueryList, OnInit, AfterContentInit } from 'angular2/core';
import { Ng2WizardTab } from './ng2-wizard-tab.component';
import { Ng2WizardStep } from './ng2-wizard-step.component';
import { INg2WizardConfig } from './ng2-wizard.config';
@Component({
... | // Allow usage of enum in template
private NavigationDirection = NavigationDirection;
private get activeStep(): Ng2WizardStep {
return this.steps.find(step => step.active);
}
private get currentStepIndex(): number {
return this.steps.indexOf(this.activeStep);
}
... | }
| random_line_split |
ng2-wizard.component.ts | import { Component, ContentChildren, Input, Output, EventEmitter, QueryList, OnInit, AfterContentInit } from 'angular2/core';
import { Ng2WizardTab } from './ng2-wizard-tab.component';
import { Ng2WizardStep } from './ng2-wizard-step.component';
import { INg2WizardConfig } from './ng2-wizard.config';
@Component({
... | (): boolean {
return this.combinedConfig.showNavigationButtons &&
(this.combinedConfig.navigationButtonLocation === "top" || this.combinedConfig.navigationButtonLocation === "both");
}
private get showBottomNavigationButtons(): boolean {
return this.combinedConfig.showNavigation... | showTopNavigationButtons | identifier_name |
signer.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... |
/// Check if the given address is the signing address.
pub fn is_address(&self, address: &Address) -> bool {
*self.address.read() == *address
}
}
| {
self.address.read().clone()
} | identifier_body |
signer.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... | (&self, ap: Arc<AccountProvider>, address: Address, password: String) {
*self.account_provider.lock() = ap;
*self.address.write() = address;
*self.password.write() = Some(password);
debug!(target: "poa", "Setting Engine signer to {}", address);
}
/// Sign a consensus message hash.
pub fn sign(&self, hash: H... | set | identifier_name |
signer.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... | fn default() -> Self {
EngineSigner {
account_provider: Mutex::new(Arc::new(AccountProvider::transient_provider())),
address: Default::default(),
password: Default::default(),
}
}
}
impl EngineSigner {
/// Set up the signer to sign with given address and password.
pub fn set(&self, ap: Arc<AccountProv... | impl Default for EngineSigner { | random_line_split |
credential.rs | use std::collections::HashMap;
use ursa::cl::{
CredentialSignature,
RevocationRegistry,
SignatureCorrectnessProof,
Witness
};
use indy_api_types::validation::Validatable;
use super::credential_definition::CredentialDefinitionId;
use super::revocation_registry_definition::RevocationRegistryId;
use sup... | (pub HashMap<String, AttributeValues>);
#[derive(Debug, Clone, Deserialize, Serialize, Eq, PartialEq)]
pub struct AttributeValues {
pub raw: String,
pub encoded: String
}
impl Validatable for CredentialValues {
fn validate(&self) -> Result<(), String> {
if self.0.is_empty() {
return Er... | CredentialValues | identifier_name |
credential.rs | use std::collections::HashMap;
use ursa::cl::{
CredentialSignature,
RevocationRegistry,
SignatureCorrectnessProof,
Witness
};
use indy_api_types::validation::Validatable;
use super::credential_definition::CredentialDefinitionId;
use super::revocation_registry_definition::RevocationRegistryId;
use sup... |
if self.values.0.is_empty() {
return Err(String::from("Credential validation failed: `values` is empty"));
}
Ok(())
}
} | {
return Err(String::from("Credential validation failed: `witness` and `rev_reg` must be passed for revocable Credential"));
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.