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 |
|---|---|---|---|---|
runtime.js | // ECMAScript 5 strict mode
"use strict";
assert2(cr, "cr namespace not created");
assert2(cr.plugins_, "cr.plugins_ not created");
/////////////////////////////////////
// Plugin class
cr.plugins_.Rex_Parse_FileUpload = function(runtime)
{
this.runtime = runtime;
};
(function ()
{
var pluginProto = cr.plugins_.R... | {
this.type = type;
this.runtime = type.runtime;
};
var instanceProto = pluginProto.Instance.prototype;
instanceProto.onCreate = function()
{
if ((!window.RexC2IsParseInit) && (this.properties[0] !== ""))
{
window["Parse"]["initialize"](this.properties[0], this.properties[1]);
w... | random_line_split | |
logging.js | sap.ui.define([
"jquery.sap.global",
"unitTests/utils/loggerInterceptor"
], function ($, loggerInterceptor) {
"use strict";
// Opa5 needs to be unloaded because we want to intercept the logger
jQuery.sap.unloadResources("sap/ui/test/Opa5.js", false, true, true);
// Opa has a config inside remembering state
jQue... | sinon.assert.calledWith(this.debugSpy, "Found no view with the name: 'notExistingView'");
});
}); | random_line_split | |
test_intg_system_Atom_setLoc.py | '''
SASMOL: Copyright (C) 2011 Joseph E. Curtis, Ph.D.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
... | (self):
self.o=system.Atom(3,'1CRN-3frames.pdb')
def test_1CRN_3frames(self):
'''
test a regular pdb file with 3 frame
'''
#
expected = [' ']*327
#
self.o.setLoc(expected)
#
result = self.o.loc()
print result
#
self.assertEqual(expected, resu... | setUp | identifier_name |
test_intg_system_Atom_setLoc.py | '''
SASMOL: Copyright (C) 2011 Joseph E. Curtis, Ph.D.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
... |
def tearDown(self):
pass
if __name__ == '__main__':
main()
| '''
test a regular pdb file with 3 frame
'''
#
expected = [' ']*327
#
self.o.setLoc(expected)
#
result = self.o.loc()
print result
#
self.assertEqual(expected, result) | identifier_body |
test_intg_system_Atom_setLoc.py | '''
SASMOL: Copyright (C) 2011 Joseph E. Curtis, Ph.D.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
... | #
self.o.setLoc(expected)
#
result = self.o.loc()
print result
#
self.assertEqual(expected, result)
def tearDown(self):
pass
if __name__ == '__main__':
main() | random_line_split | |
test_intg_system_Atom_setLoc.py | '''
SASMOL: Copyright (C) 2011 Joseph E. Curtis, Ph.D.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
... | main() | conditional_block | |
myfeedbackcount.js | angular.module('feedback', [])
.directive('feedbackcount', function(FeedbackService) {
return {
restrict: 'A'
, link: function(scope, element, attrs) {
FeedbackService.get_feedback_count();
var feedback = FeedbackService.feedback; |
if(feedback) {
if(type == 'msg') {
if(feedback.msg) {
$(element).html("<sup class='count'>" + feedback.msg + "</sup>");
}
}
if(type == 'msg_ap') {
if(feedba... | var type = $(element).attr("show"); | random_line_split |
myfeedbackcount.js | angular.module('feedback', [])
.directive('feedbackcount', function(FeedbackService) {
return {
restrict: 'A'
, link: function(scope, element, attrs) {
FeedbackService.get_feedback_count();
var feedback = FeedbackService.feedback;
var type = $(element).attr("sh... |
}
if(type == 'msg_ap') {
if(feedback.msg_ap) {
$(element).html("<sup class='count'>" + feedback.msg_ap + "</sup>");
}
}
if(type == 'msg_topbar') {
if(feedback.ms... | {
$(element).html("<sup class='count'>" + feedback.msg + "</sup>");
} | conditional_block |
data_export_script_new.py | None
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import os
# simple json is a python 2.5 library you need to install
import json
# json comes bundled with python 2.6. use one or the other
#import json
def run():
print "starting"
from receiver.models import Submission
from xformmanager.... | print jsoned
fout.write(jsoned)
fout.write("\n\n")
xsd_file = open(file_loc, "r")
payload = xsd_file.read()
xsd_file.close()
fout.write(payload)
fout.close()
# this part of the script walks through... | jsoned = json.dumps(headers) | random_line_split |
data_export_script_new.py | None
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import os
# simple json is a python 2.5 library you need to install
import json
# json comes bundled with python 2.6. use one or the other
#import json
def | ():
print "starting"
from receiver.models import Submission
from xformmanager.models import FormDefModel
# this part of the script walks through all the registered
# form definitions and bundles them with the original xsd
# schema for resubmission
domain = None
# you can manually set... | run | identifier_name |
data_export_script_new.py | None
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import os
# simple json is a python 2.5 library you need to install
import json
# json comes bundled with python 2.6. use one or the other
#import json
def run():
| if file_loc:
headers = {
"original-submit-time" : str(schema.submit_time),
"original-submit-ip" : str(schema.submit_ip),
"bytes-received" : schema.bytes_received,
"form-name" : schema.form_name,
"form-display-name" : sch... | print "starting"
from receiver.models import Submission
from xformmanager.models import FormDefModel
# this part of the script walks through all the registered
# form definitions and bundles them with the original xsd
# schema for resubmission
domain = None
# you can manually set a singl... | identifier_body |
data_export_script_new.py | None
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import os
# simple json is a python 2.5 library you need to install
import json
# json comes bundled with python 2.6. use one or the other
#import json
def run():
print "starting"
from receiver.models import Submission
from xformmanager.... |
else:
all_submissions = Submission.objects.all()
for submission in all_submissions:
#print "processing %s (%s)" % (submission,submission.raw_post)
post_file = open(submission.raw_post, "r")
submit_time = str(submission.submit_time)
# first line is content type
co... | all_submissions = Submission.objects.filter(domain__name__iexact=domain) | conditional_block |
connector-definition-visitor.js | /**
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.o... |
});
_.forEach(connectorDefinition.getArguments(), function(argument, index){
argumentsSrc += argument.type + " ";
argumentsSrc += argument.identifier;
if (connectorDefinition.getArguments().length - 1 != index) {
argumentsSrc ... | {
var constructedPathAnnotation;
if (annotation.key.indexOf(":") === -1) {
constructedPathAnnotation = '@' + annotation.key + '("' + annotation.value + '")\n';
} else {
constructedPathAnnotation = '@' + annotatio... | conditional_block |
connector-definition-visitor.js | /**
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.o... | /**
* End visiting the connector definition
* @param {ConnectorDefinition} connectorDefinition - Connector Definition
*/
ConnectorDefinitionVisitor.prototype.endVisitConnectorDefinition = function(connectorDefinition){
this.appendSource("}\n");
this.get... |
ConnectorDefinitionVisitor.prototype.visitConnectorDefinition = function(connectorDefinition){
log.debug('Visit Connector Definition');
};
| random_line_split |
assign_public_addresses.py | import hyperdex.client
import smtplib
from bitcoin.core import COIN, b2lx
import bitcoin.wallet
import bitcoin.rpc
try:
from bitcoin.case58 import CBitcoinAddress
except:
from bitcoin.wallet import CBitcoinAddress
from config import SERVER_DB_ADDRESS, MAIL_USERNAME, MAIL_PASSWORD, NAME
c = hyperdex.client.C... |
break
else:
pub_key = ''
bitcoin_addresses = c.sorted_search('bitcoin_addresses', {}, 'pub_key_foo', 1, 'min')
for bitcoin_key in bitcoin_addresses:
pub_key = bitcoin_key['pub_key_foo']
x.delete('bitcoin_addresses', pub_key)
x.put('users', user['email'], ... | server.sendmail(EMAIL, EMAIL, "[BTC_KEY] Empty") | conditional_block |
assign_public_addresses.py | import hyperdex.client
import smtplib
from bitcoin.core import COIN, b2lx
import bitcoin.wallet
import bitcoin.rpc
try:
from bitcoin.case58 import CBitcoinAddress
except:
from bitcoin.wallet import CBitcoinAddress
from config import SERVER_DB_ADDRESS, MAIL_USERNAME, MAIL_PASSWORD, NAME
c = hyperdex.client.C... | for dogecoin_key in dogecoin_addresses:
pub_key = dogecoin_key['pub_key_foo']
x.delete('dogecoin_addresses', pub_key)
x.put('users', user['email'], {'dogecoin_address': pub_key})
# Dogecoin doesn't yet support import address :(
# dogecoin_rpc.importaddress(pub_key, la... | break
else:
pub_key = ''
dogecoin_addresses = c.sorted_search('dogecoin_addresses', {}, 'pub_key_foo', 1, 'min') | random_line_split |
config.py | = []
if val:
dic[key] = [] # never accumulate args
for it in shlex.split(val):
dic[key].append(it.strip())
return dic[key]
def parse_dict(key, val, dic, parse_val=parse_string):
"""ex. dict=A:1,B:2,C:3"""
if not key in dic: dic[key] = {}
if val:
... | aise AsyncConfigError("Unknown object section '%s'" % obj)
| conditional_block | |
config.py | # old: dictionary containing
def parse_string(key, val, dic):
if val:
dic[key] = val.strip()
return dic.get(key, None)
def parse_bool(key, val, dic):
if val:
val = val.strip().lower()
bval = False
if val in set(['on', 'true', '1', 'yes']): bval = True
elif val in... | key, val, dic):
return parse_list(key, val, dic, parse_path)
def parse_keyval_path(key, val, dic):
return parse_keyval(key, val, dic, parse_path)
class AsyncConfig(ConfigParser):
# default values and parsing functions
FIELDS={
'host': {
'dirs' : ([], parse_list),
... | arse_list_path( | identifier_name |
config.py | # old: dictionary containing
def parse_string(key, val, dic):
if val:
dic[key] = val.strip()
return dic.get(key, None)
def parse_bool(key, val, dic):
if val:
val = val.strip().lower()
bval = False
if val in set(['on', 'true', '1', 'yes']): bval = True
elif val in... | return dic[key]
def parse_keyval(key, val, dic, parse_val=parse_string):
"""ex. uuid:directory = blahblah"""
ret = {}
spl = key.strip().split('.', 1)
if len(spl) == 0:
return
elif len(spl) == 1:
parse_val(spl[0], val, dic)
elif len(spl) >= 2:
key = spl[0]
... | ""ex. dict=A:1,B:2,C:3"""
if not key in dic: dic[key] = {}
if val:
L = val.split(',')
# do not accumulate with previous values if the list starts with a comma.
if len(L[0].strip()) == 0: L=L[1:]
else: dic[key] = {}
for it in L:
spl = it... | identifier_body |
config.py | # old: dictionary containing
def parse_string(key, val, dic):
if val:
dic[key] = val.strip()
return dic.get(key, None)
def parse_bool(key, val, dic):
if val:
val = val.strip().lower()
bval = False
if val in set(['on', 'true', '1', 'yes']): bval = True
elif val in... | if val:
dic[key] = os.path.expandvars(os.path.expanduser(val.strip()))
return dic.get(key, None)
def parse_list(key, val, dic, parse_val=parse_string):
if not key in dic: dic[key] = []
if val:
L = val.split(',')
# do not accumulate with previous values if the list starts wit... |
def parse_path(key, val, dic): | random_line_split |
test_purchase_request_to_requisition.py | # -*- coding: utf-8 -*-
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp.tests import common
from openerp.tools import SUPERUSER_ID
class TestPurchaseRequestToRequisition(common.TransactionCase):
def | (self):
super(TestPurchaseRequestToRequisition, self).setUp()
self.purchase_request = self.env['purchase.request']
self.purchase_request_line = self.env['purchase.request.line']
self.wiz =\
self.env['purchase.request.line.make.purchase.requisition']
self.purchase_requ... | setUp | identifier_name |
test_purchase_request_to_requisition.py | # -*- coding: utf-8 -*-
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp.tests import common
from openerp.tools import SUPERUSER_ID
class TestPurchaseRequestToRequisition(common.TransactionCase):
def setUp(self):
super(Te... | purchase_request_line.product_id.id,
'Should have the same products')
self.assertEquals(
purchase_request.state,
requisition_id.state,
'Should have the same state')
requisition_id.tender_in_progress()
requisition_id.tender_open()
... | self.assertEquals(
requisition_line.product_id.id, | random_line_split |
test_purchase_request_to_requisition.py | # -*- coding: utf-8 -*-
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp.tests import common
from openerp.tools import SUPERUSER_ID
class TestPurchaseRequestToRequisition(common.TransactionCase):
| 'product_qty': 5.0,
}
purchase_request_line = self.purchase_request_line.create(vals)
wiz_id = self.wiz.with_context(
active_model="purchase.request.line",
active_ids=[purchase_request_line.id],
active_id=purchase_request_line.id,).create({})
... | def setUp(self):
super(TestPurchaseRequestToRequisition, self).setUp()
self.purchase_request = self.env['purchase.request']
self.purchase_request_line = self.env['purchase.request.line']
self.wiz =\
self.env['purchase.request.line.make.purchase.requisition']
self.purc... | identifier_body |
MultiSelect.js | define([
"dojo/_base/array", // array.indexOf, array.map
"dojo/_base/declare", // declare
"dojo/dom-geometry", // domGeometry.setMarginBox
"dojo/has",
"dojo/query", // query
"./_FormValueWidget",
"dojo/touch" // not used directly, but allows me to set dojoClick flag on node and get responsive click handling
], f... |
}
});
}
return MultiSelect;
});
| {
this._set("textDir", textDir);
query("option", this.containerNode).forEach(function(option){
// If the value wasn't defined explicitly, it the same object as
// option.text. Since the option.text will be modified (by wrapping of UCC)
// we want to save the original option.value for form s... | conditional_block |
MultiSelect.js | define([
"dojo/_base/array", // array.indexOf, array.map
"dojo/_base/declare", // declare | ], function(array, declare, domGeometry, has, query, _FormValueWidget){
// module:
// dijit/form/MultiSelect
var MultiSelect = declare("dijit.form.MultiSelect" + (has("dojo-bidi") ? "_NoBidi" : ""), _FormValueWidget, {
// summary:
// Widget version of a `<select multiple=true>` element,
// for selecting m... | "dojo/dom-geometry", // domGeometry.setMarginBox
"dojo/has",
"dojo/query", // query
"./_FormValueWidget",
"dojo/touch" // not used directly, but allows me to set dojoClick flag on node and get responsive click handling | random_line_split |
combined-slip-basic.py | from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
def coefficient(slipValue, extremumValue, extremumSlip, asymptoteValue, asymptoteSlip):
|
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(0, 0.4, 0.01)
Y = np.arange(0, 40, 1)
X, Y = np.meshgrid(X, Y)
longfunc = np.vectorize(lambda t: coefficient(t, 1, 0.2, 0.75, 0.4))
lateralfunc = np.vectorize(lambda t: coefficient(t, 1.0, 20.0, 0.75, 40))
Z = np.sqrt(longfunc(X)**2 + lateralfunc(Y)**2)
... | coefficient = asymptoteValue;
absoluteSlip = abs(slipValue);
if (absoluteSlip <= extremumSlip):
coefficient = (extremumValue / extremumSlip) * absoluteSlip;
elif (absoluteSlip > extremumSlip and absoluteSlip < asymptoteSlip):
coefficient = ((asymptoteValue - extremumValue) / (asymptoteSlip -... | identifier_body |
combined-slip-basic.py | from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
def coefficient(slipValue, extremumValue, extremumSlip, asymptoteValue, asymptoteSlip):
coefficient = asymptoteValue;
absoluteSlip... | Z = np.sqrt(longfunc(X)**2 + lateralfunc(Y)**2)
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
ax.set_zlim(0.0, 2.0)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, shrink=0.5, aspect=... | lateralfunc = np.vectorize(lambda t: coefficient(t, 1.0, 20.0, 0.75, 40)) | random_line_split |
combined-slip-basic.py | from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
def coefficient(slipValue, extremumValue, extremumSlip, asymptoteValue, asymptoteSlip):
coefficient = asymptoteValue;
absoluteSlip... |
return coefficient
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(0, 0.4, 0.01)
Y = np.arange(0, 40, 1)
X, Y = np.meshgrid(X, Y)
longfunc = np.vectorize(lambda t: coefficient(t, 1, 0.2, 0.75, 0.4))
lateralfunc = np.vectorize(lambda t: coefficient(t, 1.0, 20.0, 0.75, 40))
Z = np.sqrt(longfunc(X)**... | coefficient = ((asymptoteValue - extremumValue) / (asymptoteSlip - extremumSlip)) \
* (absoluteSlip - extremumSlip) + extremumValue; | conditional_block |
combined-slip-basic.py | from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
def | (slipValue, extremumValue, extremumSlip, asymptoteValue, asymptoteSlip):
coefficient = asymptoteValue;
absoluteSlip = abs(slipValue);
if (absoluteSlip <= extremumSlip):
coefficient = (extremumValue / extremumSlip) * absoluteSlip;
elif (absoluteSlip > extremumSlip and absoluteSlip < asymptoteSlip... | coefficient | identifier_name |
FontFamilyLayout.js | /* eslint-disable react/no-array-index-key */
/* @flow */
import React from 'react';
import type { Node } from 'react';
import cn from 'classnames';
import { Dropdown, DropdownOption } from '../../Dropdown';
import type { FontFamilyConfig } from '../../../core/config';
export type Props = {
expanded: boolean,
onE... | export default FontFamilyLayout; | random_line_split | |
mount_manager_extension.py | import gtk
class ExtensionFeatures:
SYSTEM_WIDE = 0
class MountManagerExtension:
"""Base class for mount manager extensions.
Mount manager has only one instance and is created on program startup.
Methods defined in this class are called automatically by the mount manager
so you need to implement them.
""... |
def get_container(self):
"""Return container widget"""
return self._container
def get_information(self):
"""Returns information about extension"""
icon = None
name = None
return icon, name
def unmount(self, uri):
"""Method called by the mount manager for unmounting the selected URI"""
pass
def... | """Returns boolean denoting if specified URI can be handled by this extension"""
return False | identifier_body |
mount_manager_extension.py | import gtk
class ExtensionFeatures:
SYSTEM_WIDE = 0
class MountManagerExtension:
"""Base class for mount manager extensions.
Mount manager has only one instance and is created on program startup.
Methods defined in this class are called automatically by the mount manager
so you need to implement them.
""... | (self, parent, window):
self._parent = parent
self._window = window
self._application = self._parent._application
# create user interface
self._container = gtk.VBox(False, 5)
self._controls = gtk.HBox(False, 5)
separator = gtk.HSeparator()
# pack interface
self._container.pack_end(separator, False,... | __init__ | identifier_name |
mount_manager_extension.py | import gtk
class ExtensionFeatures:
SYSTEM_WIDE = 0
class MountManagerExtension:
"""Base class for mount manager extensions.
Mount manager has only one instance and is created on program startup.
Methods defined in this class are called automatically by the mount manager
so you need to implement them.
""... | """Returns set of features supported by extension"""
return cls.features | pass
@classmethod
def get_features(cls): | random_line_split |
react-calendar-timeline.d.ts | // Type definitions for react-calendar-timeline v0.7.9
// Project: https://github.com/namespace-ee/react-calendar-timeline
// Definitions by: Rajab Shakirov <https://github.com/radziksh>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../react/react.d.ts"/>
declare module "reac... | let ReactCalendarTimeline : __React.ClassicComponentClass<ReactCalendarTimeline>;
export default ReactCalendarTimeline;
} | children?: any;
} | random_line_split |
list.js | define(['jquery', 'moment', 'bootstrap', 'datatables.net', 'datatables.net-bs'], function ($, moment) {
function PlansList(container) {
var that = this;
container = $(container);
var table;
function _init() {
table = container.DataTable({
columns: [
... | return '';
}
}
function load_data() {
var options = {
url: 'api/batch',
data: {'apprPlans': 1, 'apprUnfinished': 1},
dataType: 'json',
type: 'post',
success: load_succ_cb
};
... | return '<span class="label label-danger">未完成</span>'
} else {
| conditional_block |
list.js | define(['jquery', 'moment', 'bootstrap', 'datatables.net', 'datatables.net-bs'], function ($, moment) {
function PlansList(container) {
var that = this;
container = $(container);
var table;
function _init() {
table = container.DataTable({
columns: [
... | tion load_succ_cb(data) {
var plans = data.apprPlans;
var unfinished = data.apprUnfinished;
$.each(plans, function(_, plan) {
plan.unfinished = (unfinished.indexOf(plan.id) !== -1);
});
table.rows.add(plans);
table.draw();
}... | var options = {
url: 'api/batch',
data: {'apprPlans': 1, 'apprUnfinished': 1},
dataType: 'json',
type: 'post',
success: load_succ_cb
};
$.ajax(options);
}
func | identifier_body |
list.js | define(['jquery', 'moment', 'bootstrap', 'datatables.net', 'datatables.net-bs'], function ($, moment) {
function PlansList(container) {
var that = this;
container = $(container);
var table;
function _init() {
table = container.DataTable({
columns: [
... | var unfinished = data.apprUnfinished;
$.each(plans, function(_, plan) {
plan.unfinished = (unfinished.indexOf(plan.id) !== -1);
});
table.rows.add(plans);
table.draw();
}
_init();
}
return PlansList;
}); | var plans = data.apprPlans; | random_line_split |
list.js | define(['jquery', 'moment', 'bootstrap', 'datatables.net', 'datatables.net-bs'], function ($, moment) {
function PlansList(container) {
var that = this;
container = $(container);
var table;
function _init() {
table = container.DataTable({
columns: [
... | var plans = data.apprPlans;
var unfinished = data.apprUnfinished;
$.each(plans, function(_, plan) {
plan.unfinished = (unfinished.indexOf(plan.id) !== -1);
});
table.rows.add(plans);
table.draw();
}
_init();
}
r... | ata) {
| identifier_name |
map.js | function (doc) {
function get_date(doc) | case "EventLog":
return doc.date;
case "Application":
case "Application-Deleted":
case "RemoteApp":
case "RemoteApp-Deleted":
return doc.copy_of ? doc.built_on : null;
default:
return null;
}
... | {
switch (doc.doc_type){
case "CommCareCase":
case "CommCareCase-Deleted":
return doc.opened_on;
case "XFormInstance":
case "XFormInstance-Deleted":
case "XFormError":
case "XFormDuplicate":
case "XFormDeprecated... | identifier_body |
map.js | function (doc) {
function get_date(doc){
switch (doc.doc_type){
case "CommCareCase":
case "CommCareCase-Deleted":
return doc.opened_on;
case "XFormInstance":
case "XFormInstance-Deleted":
case "XFormError":
case "XFormD... | case "SubmissionErrorLog":
return doc.received_on;
case "CommCareUser":
case "WebUser":
return doc.created_on;
case "MessageLog":
case "CallLog":
case "SMSLog":
return doc.date;
case "Even... | case "XFormDeprecated":
case "XFormArchived": | random_line_split |
map.js | function (doc) {
function | (doc){
switch (doc.doc_type){
case "CommCareCase":
case "CommCareCase-Deleted":
return doc.opened_on;
case "XFormInstance":
case "XFormInstance-Deleted":
case "XFormError":
case "XFormDuplicate":
case "XFormDepre... | get_date | identifier_name |
map.js | function (doc) {
function get_date(doc){
switch (doc.doc_type){
case "CommCareCase":
case "CommCareCase-Deleted":
return doc.opened_on;
case "XFormInstance":
case "XFormInstance-Deleted":
case "XFormError":
case "XFormD... |
}
| {
emit([doc.domain, doc.doc_type, get_date(doc)], null);
} | conditional_block |
ItemRequest.ts | import * as Models from './'
export const ItemRequestPriority = [
'low',
'standard', | export type ItemRequestPriority = ItemRequestPriorityTuple[number]
export const ItemRequestDestination = ['Svařovna'] as const
export type ItemRequestDestinationTuple = typeof ItemRequestDestination
export type ItemRequestDestination = ItemRequestDestinationTuple[number]
export interface ErrorData {
errors: string[]... | 'high',
'highest'
] as const
export type ItemRequestPriorityTuple = typeof ItemRequestPriority | random_line_split |
file_util.py | import os
import unicodedata
from keras.applications import InceptionV3, VGG16, MobileNet
image_type = ['.jpg']
def check_img(file_name):
"""To check image
Args:
file_name : file name
Returns:
if this file is image
"""
file_name, file_ext = os.path.splitext(file_name)
if fil... | if model == "inceptionv3":
base_model = InceptionV3(include_top=False, input_shape=image_size + (3,))
elif model == "vgg16" or model is None:
base_model = VGG16(include_top=False, input_shape=image_size + (3,))
elif model == "mobilenet":
base_model = MobileNet(include_top=False, input_sh... | identifier_body | |
file_util.py | import os
import unicodedata
from keras.applications import InceptionV3, VGG16, MobileNet
image_type = ['.jpg']
def | (file_name):
"""To check image
Args:
file_name : file name
Returns:
if this file is image
"""
file_name, file_ext = os.path.splitext(file_name)
if file_ext in image_type:
return True
return False
def extract_type(file_name, delimiter):
"""To extract type from f... | check_img | identifier_name |
file_util.py | import os
import unicodedata
from keras.applications import InceptionV3, VGG16, MobileNet
image_type = ['.jpg']
def check_img(file_name):
"""To check image
Args:
file_name : file name
Returns:
if this file is image
"""
file_name, file_ext = os.path.splitext(file_name)
if fil... | elif model == "mobilenet":
base_model = MobileNet(include_top=False, input_shape=image_size + (3,))
return base_model | def make_model(model, image_size):
if model == "inceptionv3":
base_model = InceptionV3(include_top=False, input_shape=image_size + (3,))
elif model == "vgg16" or model is None:
base_model = VGG16(include_top=False, input_shape=image_size + (3,)) | random_line_split |
file_util.py | import os
import unicodedata
from keras.applications import InceptionV3, VGG16, MobileNet
image_type = ['.jpg']
def check_img(file_name):
"""To check image
Args:
file_name : file name
Returns:
if this file is image
"""
file_name, file_ext = os.path.splitext(file_name)
if fil... |
return base_model
| base_model = MobileNet(include_top=False, input_shape=image_size + (3,)) | conditional_block |
FtpCesarFtpd.py | import re
from ztag.annotation import Annotation
from ztag.annotation import OperatingSystem
from ztag import protocols
import ztag.test
class FtpCesarFtpd(Annotation):
protocol = protocols.FTP
subprotocol = protocols.FTP.BANNER
port = None
impl_re = re.compile("^220[- ]CesarFTP 0\.\d+", re.IGNORECAS... |
return meta
""" Tests
"220 CesarFTP 0.99g Server Welcome !\r\n"
"220 CesarFTP 0.99g Server Welcome !\r\n"
"220 CesarFTP 0.99g Server Welcome !\r\n"
"220 CesarFTP 0.99g Server Welcome !\r\n"
"220 CesarFTP 0.99g Server Welcome !\r\n"
"220 CesarFTP 0.99g Server Welcome !\r\n"
"22... | meta.global_metadata.os = OperatingSystem.WINDOWS
meta.local_metadata.product = "Cesar FTP"
version = self.version_re.search(banner).group(1)
meta.local_metadata.version = version
rev = self.version_re.search(banner).group(2)
meta.local_metadata.revision = ... | conditional_block |
FtpCesarFtpd.py | import re
from ztag.annotation import Annotation
from ztag.annotation import OperatingSystem
from ztag import protocols
import ztag.test
class FtpCesarFtpd(Annotation):
|
def process(self, obj, meta):
banner = obj["banner"]
if self.impl_re.search(banner):
meta.global_metadata.os = OperatingSystem.WINDOWS
meta.local_metadata.product = "Cesar FTP"
version = self.version_re.search(banner).group(1)
meta.local_metadata.v... | protocol = protocols.FTP
subprotocol = protocols.FTP.BANNER
port = None
impl_re = re.compile("^220[- ]CesarFTP 0\.\d+", re.IGNORECASE)
version_re = re.compile("CesarFTP (\d+\.\d+)([a-z])?", re.IGNORECASE)
tests = {
"FtpCesarFtpd_1": {
"global_metadata": {
"os": ... | identifier_body |
FtpCesarFtpd.py | import re
from ztag.annotation import Annotation
from ztag.annotation import OperatingSystem
from ztag import protocols
import ztag.test
class FtpCesarFtpd(Annotation):
protocol = protocols.FTP
subprotocol = protocols.FTP.BANNER
port = None
impl_re = re.compile("^220[- ]CesarFTP 0\.\d+", re.IGNORECAS... | (self, obj, meta):
banner = obj["banner"]
if self.impl_re.search(banner):
meta.global_metadata.os = OperatingSystem.WINDOWS
meta.local_metadata.product = "Cesar FTP"
version = self.version_re.search(banner).group(1)
meta.local_metadata.version = version... | process | identifier_name |
FtpCesarFtpd.py | import re
from ztag.annotation import Annotation
from ztag.annotation import OperatingSystem
from ztag import protocols
import ztag.test
class FtpCesarFtpd(Annotation):
protocol = protocols.FTP
subprotocol = protocols.FTP.BANNER
port = None
impl_re = re.compile("^220[- ]CesarFTP 0\.\d+", re.IGNORECAS... | meta.local_metadata.revision = rev
return meta
""" Tests
"220 CesarFTP 0.99g Server Welcome !\r\n"
"220 CesarFTP 0.99g Server Welcome !\r\n"
"220 CesarFTP 0.99g Server Welcome !\r\n"
"220 CesarFTP 0.99g Server Welcome !\r\n"
"220 CesarFTP 0.99g Server Welcome !\r\n"
"22... |
rev = self.version_re.search(banner).group(2) | random_line_split |
15.4.2.3.js | /* The contents of this file are subject to the Netscape Public
* License Version 1.1 (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.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" ... | () {
for ( tc=0; tc < testcases.length; tc++ ) {
testcases[tc].passed = writeTestCaseResult(
testcases[tc].expect,
testcases[tc].actual,
testcases[tc].description +" = "+ testcases[tc].actual );
testcases[tc].reason... | test | identifier_name |
15.4.2.3.js | /* The contents of this file are subject to the Netscape Public
* License Version 1.1 (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.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" ... |
stopTest();
return ( testcases );
}
| {
testcases[tc].passed = writeTestCaseResult(
testcases[tc].expect,
testcases[tc].actual,
testcases[tc].description +" = "+ testcases[tc].actual );
testcases[tc].reason += ( testcases[tc].passed ) ? "" : "wrong value ";... | conditional_block |
15.4.2.3.js | /* The contents of this file are subject to the Netscape Public
* License Version 1.1 (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.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" ... |
var SECTION = "15.4.2.3";
var VERSION = "ECMA_1";
startTest();
var TITLE = "The Array Constructor: new Array()";
writeHeaderToLog( SECTION + " "+ TITLE);
var testcases = getTestCases();
test();
function getTestCases() {
var array = new Array();
var item = 0;
array[item++] ... |
Author: christine@netscape.com
Date: 7 october 1997
*/ | random_line_split |
15.4.2.3.js | /* The contents of this file are subject to the Netscape Public
* License Version 1.1 (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.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" ... |
function test() {
for ( tc=0; tc < testcases.length; tc++ ) {
testcases[tc].passed = writeTestCaseResult(
testcases[tc].expect,
testcases[tc].actual,
testcases[tc].description +" = "+ testcases[tc].actual );
testca... | {
var array = new Array();
var item = 0;
array[item++] = new TestCase( SECTION, "new Array() +''", "", (new Array()) +"" );
array[item++] = new TestCase( SECTION, "typeof new Array()", "object", (typeof new Array()) );
array[item++] = new TestCase( SECTION,... | identifier_body |
intl.ts | {
Decimal,
Percent,
Currency,
}
export class NumberFormatter {
static format(
num: number, locale: string, style: NumberFormatStyle,
{minimumIntegerDigits, minimumFractionDigits, maximumFractionDigits, currency,
currencyAsSymbol = false}: {
minimumIntegerDigits?: number,
min... |
}
type DateFormatterFn = (date: Date, locale: string) => string;
const DATE_FORMATS_SPLIT =
/((?:[^yMLdHhmsazZEwGjJ']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|J+|j+|m+|s+|a|z|Z|G+|w+))(.*)/;
const PATTERN_ALIASES: {[format: string]: DateFormatterFn} = {
'yMMMdjms': datePartGetterFactory(combine([
digi... | {
const options: Intl.NumberFormatOptions = {
minimumIntegerDigits,
minimumFractionDigits,
maximumFractionDigits,
style: NumberFormatStyle[style].toLowerCase()
};
if (style == NumberFormatStyle.Currency) {
options.currency = currency;
options.currencyDisplay = currencyAs... | identifier_body |
intl.ts | Style {
Decimal,
Percent,
Currency,
}
export class NumberFormatter {
static format(
num: number, locale: string, style: NumberFormatStyle,
{minimumIntegerDigits, minimumFractionDigits, maximumFractionDigits, currency,
currencyAsSymbol = false}: {
minimumIntegerDigits?: number,
... | parts.push(format);
format = null;
}
}
DATE_FORMATTER_CACHE.set(format, | random_line_split | |
intl.ts | {
Decimal,
Percent,
Currency,
}
export class NumberFormatter {
static format(
num: number, locale: string, style: NumberFormatStyle,
{minimumIntegerDigits, minimumFractionDigits, maximumFractionDigits, currency,
currencyAsSymbol = false}: {
minimumIntegerDigits?: number,
min... | else {
parts.push(format);
format = null;
}
}
DATE_FORMATTER_CACHE.set(format, | {
parts = parts.concat(match.slice(1));
format = parts.pop();
} | conditional_block |
intl.ts | {
Decimal,
Percent,
Currency,
}
export class NumberFormatter {
static format(
num: number, locale: string, style: NumberFormatStyle,
{minimumIntegerDigits, minimumFractionDigits, maximumFractionDigits, currency,
currencyAsSymbol = false}: {
minimumIntegerDigits?: number,
min... | (inner: DateFormatterFn): DateFormatterFn {
return function(date: Date, locale: string): string {
const result = inner(date, locale);
return result.length == 1 ? '0' + result : result;
};
}
function hourClockExtractor(inner: DateFormatterFn): DateFormatterFn {
return function(date: Date, locale: string):... | digitModifier | identifier_name |
eo.js | /*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'image', 'eo', {
alertUrl: 'Bonvolu tajpi la retadreson de la bildo',
alt: 'Anstataŭiga Teksto',
border: 'Bordero',
btnUpload: 'Sendu al Servilo... | }); | validateHSpace: 'La horizontala spaco devas esti entjera nombro.',
validateVSpace: 'La vertikala spaco devas esti entjera nombro.' | random_line_split |
build.rs | /*
Copyright ⓒ 2017 cargo-script contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modifie... | /*
Before 1.13, there was no `?` operator. One of the tests needs this information.
*/
if version_matches(">=1.13.0") {
println!("cargo:rustc-cfg=has_qmark");
}
}
| println!("cargo:rustc-cfg=old_rustc_windows_linking_behaviour");
}
| conditional_block |
build.rs | /*
Copyright ⓒ 2017 cargo-script contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modifie... | {
println!("cargo:rerun-if-changed=build.rs");
/*
Environment might suffer from <https://github.com/DanielKeep/cargo-script/issues/50>.
*/
if cfg!(windows) {
println!("cargo:rustc-cfg=issue_50");
}
/*
With 1.15, linking on Windows was changed in regards to when it emits `dllim... | in() | identifier_name |
build.rs | /*
Copyright ⓒ 2017 cargo-script contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modifie... | */
if version_matches(">=1.13.0") {
println!("cargo:rustc-cfg=has_qmark");
}
}
| println!("cargo:rerun-if-changed=build.rs");
/*
Environment might suffer from <https://github.com/DanielKeep/cargo-script/issues/50>.
*/
if cfg!(windows) {
println!("cargo:rustc-cfg=issue_50");
}
/*
With 1.15, linking on Windows was changed in regards to when it emits `dllimpor... | identifier_body |
build.rs | /*
Copyright ⓒ 2017 cargo-script contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modifie... | extern crate rustc_version;
use rustc_version::{version_matches};
fn main() {
println!("cargo:rerun-if-changed=build.rs");
/*
Environment might suffer from <https://github.com/DanielKeep/cargo-script/issues/50>.
*/
if cfg!(windows) {
println!("cargo:rustc-cfg=issue_50");
}
/*
... | or distributed except according to those terms.
*/ | random_line_split |
monitor.rs | use winapi;
use std::collections::RingBuf;
/// Win32 implementation of the main `MonitorID` object.
pub struct MonitorID {
/// The system name of the monitor.
name: [winapi::WCHAR; 32],
/// Name to give to the user.
readable_name: String,
/// See the `StateFlags` element here:
/// http://msd... |
/// See the docs if the crate root file.
pub fn get_dimensions(&self) -> (uint, uint) {
// TODO: retreive the dimensions every time this is called
self.dimensions
}
/// This is a Win32-only function for `MonitorID` that returns the system name of the device.
pub fn get_system_name... | {
Some(self.readable_name.clone())
} | identifier_body |
monitor.rs | use winapi;
use std::collections::RingBuf;
/// Win32 implementation of the main `MonitorID` object.
pub struct MonitorID {
/// The system name of the monitor.
name: [winapi::WCHAR; 32],
/// Name to give to the user.
readable_name: String,
/// See the `StateFlags` element here:
/// http://msd... |
if (output.StateFlags & winapi::DISPLAY_DEVICE_ACTIVE) == 0 ||
(output.StateFlags & winapi::DISPLAY_DEVICE_MIRRORING_DRIVER) != 0
{
// the device is not active
// the Win32 api usually returns a lot of inactive devices
continue;
... | {
// the device doesn't exist, which means we have finished enumerating
break;
} | conditional_block |
monitor.rs | use winapi;
use std::collections::RingBuf;
/// Win32 implementation of the main `MonitorID` object.
pub struct MonitorID {
/// The system name of the monitor.
name: [winapi::WCHAR; 32],
/// Name to give to the user.
readable_name: String,
/// See the `StateFlags` element here:
/// http://msd... | () -> MonitorID {
// we simply get all available monitors and return the one with the `PRIMARY_DEVICE` flag
// TODO: it is possible to query the win32 API for the primary monitor, this should be done
// instead
for monitor in get_available_monitors().into_iter() {
if (monitor.flags & winapi::DI... | get_primary_monitor | identifier_name |
monitor.rs | use winapi;
use std::collections::RingBuf;
/// Win32 implementation of the main `MonitorID` object.
pub struct MonitorID {
/// The system name of the monitor.
name: [winapi::WCHAR; 32],
/// Name to give to the user.
readable_name: String,
/// See the `StateFlags` element here:
/// http://msd... | // TODO: it is possible to query the win32 API for the primary monitor, this should be done
// instead
for monitor in get_available_monitors().into_iter() {
if (monitor.flags & winapi::DISPLAY_DEVICE_PRIMARY_DEVICE) != 0 {
return monitor
}
}
panic!("Failed to find the p... | // we simply get all available monitors and return the one with the `PRIMARY_DEVICE` flag | random_line_split |
uniquify_subscriptions.py | from django.core.management import BaseCommand
from django.db.models import Count
from zds.notification.models import Subscription
class Command(BaseCommand):
help = "Delete all but last duplicate subscriptions"
def handle(self, *args, **options):
self.stdout.write("Starting uniquifying subscription... |
self.stdout.write(f"Deleted {count} duplicates")
| del sub["id__count"]
# Find PKs of duplicates, exclude the most recent one
pks = Subscription.objects.filter(**sub).order_by("-pubdate").values_list("id", flat=True)[1:]
count = count + len(pks)
# Delete each of them
for pk in pks:
Subscription... | conditional_block |
uniquify_subscriptions.py | from django.core.management import BaseCommand
from django.db.models import Count
from zds.notification.models import Subscription
class Command(BaseCommand):
help = "Delete all but last duplicate subscriptions"
def | (self, *args, **options):
self.stdout.write("Starting uniquifying subscriptions")
count = 0
# Find all duplicates
duplicates = (
Subscription.objects.values("user", "content_type", "object_id")
.annotate(Count("id"))
.filter(id__count__gt=1)
)
... | handle | identifier_name |
uniquify_subscriptions.py | from django.core.management import BaseCommand
from django.db.models import Count
from zds.notification.models import Subscription
class Command(BaseCommand):
help = "Delete all but last duplicate subscriptions"
def handle(self, *args, **options):
self.stdout.write("Starting uniquifying subscription... | Subscription.objects.filter(pk=pk).delete()
self.stdout.write(f"Deleted {count} duplicates") | for pk in pks: | random_line_split |
uniquify_subscriptions.py | from django.core.management import BaseCommand
from django.db.models import Count
from zds.notification.models import Subscription
class Command(BaseCommand):
help = "Delete all but last duplicate subscriptions"
def handle(self, *args, **options):
| self.stdout.write("Starting uniquifying subscriptions")
count = 0
# Find all duplicates
duplicates = (
Subscription.objects.values("user", "content_type", "object_id")
.annotate(Count("id"))
.filter(id__count__gt=1)
)
for sub in duplicates:
... | identifier_body | |
MeshDistanceMaterial.d.ts | import { MaterialParameters, Material } from './Material';
import { Vector3 } from './../math/Vector3';
import { Texture } from './../textures/Texture';
export interface MeshDistanceMaterialParameters extends MaterialParameters {
map?: Texture | null | undefined;
alphaMap?: Texture | null | undefined;
disp... |
/**
* @default null
*/
alphaMap: Texture | null;
/**
* @default null
*/
displacementMap: Texture | null;
/**
* @default 1
*/
displacementScale: number;
/**
* @default 0
*/
displacementBias: number;
/**
* @default 1000
*/
farD... | */
map: Texture | null; | random_line_split |
MeshDistanceMaterial.d.ts | import { MaterialParameters, Material } from './Material';
import { Vector3 } from './../math/Vector3';
import { Texture } from './../textures/Texture';
export interface MeshDistanceMaterialParameters extends MaterialParameters {
map?: Texture | null | undefined;
alphaMap?: Texture | null | undefined;
disp... | extends Material {
constructor(parameters?: MeshDistanceMaterialParameters);
/**
* @default 'MeshDistanceMaterial'
*/
type: string;
/**
* @default null
*/
map: Texture | null;
/**
* @default null
*/
alphaMap: Texture | null;
/**
* @default null
... | MeshDistanceMaterial | identifier_name |
views.py | import logging
import aiohttp_jinja2
from aiohttp import web
from aiohttp_session import get_session
from .sa import check_password, user_exist, create_user
auth_logger = logging.getLogger('auth.logger')
@aiohttp_jinja2.template('auth/login.html')
async def login(request):
session = await get_session(request)
... |
async def logout(request):
session = await get_session(request)
session.pop('user_id', None)
url = request.app.router['home'].url()
return web.HTTPFound(url)
| data = await request.post()
context = dict()
if all([data, data.get('email'), data.get('passwd'),
data.get('passwd') == data.get('passwd1')]):
already_exist = await user_exist(request.app['db'], **data)
if already_exist:
context['errors'] = ['User with this email already ... | identifier_body |
views.py | import logging
import aiohttp_jinja2
from aiohttp import web
from aiohttp_session import get_session
from .sa import check_password, user_exist, create_user
auth_logger = logging.getLogger('auth.logger')
@aiohttp_jinja2.template('auth/login.html')
async def login(request):
session = await get_session(request)
... | return web.HTTPFound(url) | async def logout(request):
session = await get_session(request)
session.pop('user_id', None)
url = request.app.router['home'].url() | random_line_split |
views.py | import logging
import aiohttp_jinja2
from aiohttp import web
from aiohttp_session import get_session
from .sa import check_password, user_exist, create_user
auth_logger = logging.getLogger('auth.logger')
@aiohttp_jinja2.template('auth/login.html')
async def login(request):
session = await get_session(request)
... | (request):
data = await request.post()
context = dict()
if all([data, data.get('email'), data.get('passwd'),
data.get('passwd') == data.get('passwd1')]):
already_exist = await user_exist(request.app['db'], **data)
if already_exist:
context['errors'] = ['User with this... | register | identifier_name |
views.py | import logging
import aiohttp_jinja2
from aiohttp import web
from aiohttp_session import get_session
from .sa import check_password, user_exist, create_user
auth_logger = logging.getLogger('auth.logger')
@aiohttp_jinja2.template('auth/login.html')
async def login(request):
session = await get_session(request)
... |
return context
async def logout(request):
session = await get_session(request)
session.pop('user_id', None)
url = request.app.router['home'].url()
return web.HTTPFound(url)
| session = await get_session(request)
user_id = await create_user(request.app['db'],
request.app['config'], **data)
session['user_id'] = user_id
auth_logger.info('Register user: %s' % data.get('email'))
url = request.app.router['devi... | conditional_block |
output.py | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... | #-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#------------------------------------------------------------------... | #-----------------------------------------------------------------------------
# Dev API | random_line_split |
output.py | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... | (resources=None, verbose=False, hide_banner=False, load_timeout=5000, notebook_type='jupyter'):
''' Configure the default output state to generate output in notebook cells
when :func:`show` is called. Note that, :func:`show` may be called multiple
times in a single cell to display multiple objects in the ou... | output_notebook | identifier_name |
output.py | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... |
Returns:
None
.. note::
Generally, this should be called at the beginning of an interactive
session or the top of a script.
'''
# verify notebook_type first in curstate().output_notebook
curstate().output_notebook(notebook_type)
run_notebook_hook(notebook_type, 'load',... | ''' Configure the default output state to generate output in notebook cells
when :func:`show` is called. Note that, :func:`show` may be called multiple
times in a single cell to display multiple objects in the output cell. The
objects will be displayed in order.
Args:
resources (Resource, optio... | identifier_body |
route.py |
name - name of the route
stateID - to which state the route belongs
routeID - route ID inside each state
length - length published by USGS
path - 2D numpy array of point coordinates along the route
in default projection: EPSG:5070 (USGS standard).
... | if fields[i][0] == 'rte_length':
self.length = float(records[0].record[i - 1])
i = i + 1
# generate a complete route path
if len(records) == 1:
self.rating = 'single'
self.path = np.array(records[0].shape.points)
self.path2 = s... | """
Initialize a Route using information in the USGS shapefile.
fields: field label used in shapefile
records: a list of route part records in the shapefile
"single" route contains only one part
"multiple" route contains multiple parts, but can be
... | identifier_body |
route.py | name - name of the route
stateID - to which state the route belongs
routeID - route ID inside each state
length - length published by USGS
path - 2D numpy array of point coordinates along the route
in default projection: EPSG:5070 (USGS standard).
... | (self, fields, records):
"""
Initialize a Route using information in the USGS shapefile.
fields: field label used in shapefile
records: a list of route part records in the shapefile
"single" route contains only one part
"multiple" route contains mult... | __init__ | identifier_name |
route.py |
name - name of the route
stateID - to which state the route belongs
routeID - route ID inside each state
length - length published by USGS
path - 2D numpy array of point coordinates along the route
in default projection: EPSG:5070 (USGS standard).
... | """
# header - for export and print use
header = '%s\t%s\t%s\t%s\t%s\t%s\t%s\n' % (
'ID', 'State ID', 'State',
'Route ID', 'Route Name', 'Route Length', 'Route Rating'
)
def __init__(self, fields, records):
"""
Initialize a Route using information in the USGS s... | distributed evenly along the route, i.e. stop_d = length / 49
rating - type of route (single or multiple)
TODO: specify details on this feature | random_line_split |
route.py | name - name of the route
stateID - to which state the route belongs
routeID - route ID inside each state
length - length published by USGS
path - 2D numpy array of point coordinates along the route
in default projection: EPSG:5070 (USGS standard).
... |
# python list of lengths of segments (between stops)
segments = np.zeros((len(self.path) - 1))
dxy = np.zeros((len(self.path) - 1, 2))
total_len = 0.0
for i in range(1, len(self.path)):
# !!! Only apply to EPSG:5070
# !!! Poor man's method to calc distan... | print('ERROR: Cannot calculate length for broken route')
exit(1) | conditional_block |
PartnerArtistItem_artist.graphql.ts | /* tslint:disable */
/* eslint-disable */
// @ts-nocheck
import { ReaderFragment } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type PartnerArtistItem_artist = {
readonly name: string | null;
readonly slug: string;
readonly href: string | null;
readonly " $refType": "Partn... | }
],
"type": "Artist",
"abstractKey": null
};
(node as any).hash = 'a7c7f0ed6a2189fa59092da9a63f33ce';
export default node; | "kind": "ScalarField",
"name": "href",
"storageKey": null | random_line_split |
main.py | import Orange
import logging
import random
from discretization import *
from FeatureSelector import *
from utils import *
from sklearn import svm
from sklearn import cross_validation
from sklearn.metrics import f1_score, precision_recall_fscore_support
from sklearn.feature_extraction import DictVectorizer
import numpy ... |
def copyDataset(dataset):
return Orange.data.Table(dataset)
# Compute S Threshold
# =============================================================================
boxmessage("Start", warning)
data = Orange.data.Table("dataset.tab")
data.randomGenerator = Orange.orange.RandomGenerator(random.randint(0, 10))
logmes... | print color(message)
logging.info(message) | identifier_body |
main.py | import Orange
import logging
import random
from discretization import *
from FeatureSelector import *
from utils import *
from sklearn import svm
from sklearn import cross_validation
from sklearn.metrics import f1_score, precision_recall_fscore_support
from sklearn.feature_extraction import DictVectorizer
import numpy ... |
else:
ds.findThresholds()
if progress:
try:
with open("discretized.tab"):
trainingSet = Orange.data.Table("discretized.tab")
print info("Discretized Dataset Loaded")
except IOError:
logmessage("IOError in loading discretized training dataset", error)
else:
trainingSet = ds.discretizeDataset(trainingS... | try:
with open("discretizer.K.gains"):
print info("Loading Previous Iteration")
ds.load()
except IOError:
logmessage("IOError in loading found gains", error)
pass | conditional_block |
main.py | import Orange
import logging
import random
from discretization import *
from FeatureSelector import *
from utils import *
from sklearn import svm
from sklearn import cross_validation
from sklearn.metrics import f1_score, precision_recall_fscore_support
from sklearn.feature_extraction import DictVectorizer
import numpy ... | (dataset):
return Orange.data.Table(dataset)
# Compute S Threshold
# =============================================================================
boxmessage("Start", warning)
data = Orange.data.Table("dataset.tab")
data.randomGenerator = Orange.orange.RandomGenerator(random.randint(0, 10))
logmessage("Main Dataset... | copyDataset | identifier_name |
main.py | import Orange
import logging
import random
from discretization import *
from FeatureSelector import *
from utils import *
from sklearn import svm
from sklearn import cross_validation
from sklearn.metrics import f1_score, precision_recall_fscore_support
from sklearn.feature_extraction import DictVectorizer
import numpy ... |
def copyDataset(dataset):
return Orange.data.Table(dataset)
# Compute S Threshold
# =============================================================================
boxmessage("Start", warning)
data = Orange.data.Table("dataset.tab")
data.randomGenerator = Orange.orange.RandomGenerator(random.randint(0, 10))
logmess... | random_line_split | |
mod.rs | /// Terminal functionality built upon core VGA driver
pub mod terminal;
pub const VIDEO_WIDTH: usize = 80;
pub const VIDEO_HEIGHT: usize = 25;
#[allow(dead_code)]
#[repr(u8)]
pub enum Color {
Black = 0,
Blue = 1,
Green = 2,
Cyan = 3,
Red = 4,
Magenta = 5,
Brown = 6,
LightGray = 7,
... | Yellow = 14,
White = 15,
}
pub const WHITE: u8 = Color::new(Color::White, Color::Black);
pub const GREEN: u8 = Color::new(Color::Green, Color::Black);
pub const RED: u8 = Color::new(Color::Red, Color::Black);
pub const LCYAN: u8 = Color::new(Color::LightCyan, Color::Black);
impl Color {
pub const fn new(f... | Pink = 13, | random_line_split |
mod.rs | /// Terminal functionality built upon core VGA driver
pub mod terminal;
pub const VIDEO_WIDTH: usize = 80;
pub const VIDEO_HEIGHT: usize = 25;
#[allow(dead_code)]
#[repr(u8)]
pub enum Color {
Black = 0,
Blue = 1,
Green = 2,
Cyan = 3,
Red = 4,
Magenta = 5,
Brown = 6,
LightGray = 7,
... | (u16);
impl Entry {
pub fn new(c: u8, color: u8) -> Entry {
Entry((color as u16) << 8 | (c as u16))
}
pub fn from_u16(data: u16) -> Entry {
Entry(data)
}
}
pub struct Writer {
ptr: usize,
}
impl Writer {
pub fn new(ptr: usize) -> Writer {
Writer { ptr: ptr }
}
... | Entry | identifier_name |
util.rs | #[cfg(test)]
use std::process::Command;
#[cfg(test)]
use rand::{self, Rng};
#[cfg(test)]
use std::env::temp_dir;
#[cfg(test)]
use std::ffi::{OsString};
#[cfg(test)]
use std::fs::File;
#[cfg(test)]
use std::io::prelude::*;
#[cfg(test)]
use std::str;
macro_rules! try_opt(
($e:expr) => (match $e { Some(e) => e, None ... |
#[inline(always)]
pub fn bit16(b: u16, pos: usize) -> u8 {
((b >> pos) & 1) as u8
}
#[inline(always)]
pub fn bitneg(b: u8, pos: usize) -> u8 {
!bit(b, pos) & 1
}
#[inline(always)]
pub fn bitneg16(b: u16, pos: usize) -> u8 {
!bit16(b, pos) & 1
}
#[cfg(test)]
pub fn assemble_to_file(code: &str) -> OsStr... | {
(b >> pos) & 1
} | identifier_body |
util.rs | #[cfg(test)]
use std::process::Command;
#[cfg(test)]
use rand::{self, Rng};
#[cfg(test)]
use std::env::temp_dir;
#[cfg(test)]
use std::ffi::{OsString};
#[cfg(test)]
use std::fs::File;
#[cfg(test)]
use std::io::prelude::*;
#[cfg(test)]
use std::str;
macro_rules! try_opt(
($e:expr) => (match $e { Some(e) => e, None ... |
let o = Command::new("avr-objcopy")
.arg("-O").arg("binary")
.arg(middle_name)
.arg(output_name.clone())
.output()
.expect("avr-objcopy failed");
if !o.status.success() {
println!("avr-objcopy: {:?}, {:?}",
str::from_utf8(&o.stdout).unwrap(),
... | {
println!("avr-gcc: {:?}, {:?}",
str::from_utf8(&o.stdout).unwrap(),
str::from_utf8(&o.stderr).unwrap());
} | conditional_block |
util.rs | #[cfg(test)]
use std::process::Command;
#[cfg(test)]
use rand::{self, Rng};
#[cfg(test)]
use std::env::temp_dir;
#[cfg(test)]
use std::ffi::{OsString};
#[cfg(test)]
use std::fs::File;
#[cfg(test)]
use std::io::prelude::*;
#[cfg(test)]
use std::str;
macro_rules! try_opt(
($e:expr) => (match $e { Some(e) => e, None ... | (b: u8, pos: usize) -> u8 {
!bit(b, pos) & 1
}
#[inline(always)]
pub fn bitneg16(b: u16, pos: usize) -> u8 {
!bit16(b, pos) & 1
}
#[cfg(test)]
pub fn assemble_to_file(code: &str) -> OsString {
let input_name = tmpfile();
let middle_name = tmpfile();
let output_name = tmpfile();
let mut input... | bitneg | identifier_name |
util.rs | #[cfg(test)]
use std::process::Command;
#[cfg(test)]
use rand::{self, Rng};
#[cfg(test)]
use std::env::temp_dir;
#[cfg(test)]
use std::ffi::{OsString};
#[cfg(test)]
use std::fs::File;
#[cfg(test)]
use std::io::prelude::*;
#[cfg(test)]
use std::str;
macro_rules! try_opt(
($e:expr) => (match $e { Some(e) => e, None ... | ((b >> pos) & 1) as u8
}
#[inline(always)]
pub fn bitneg(b: u8, pos: usize) -> u8 {
!bit(b, pos) & 1
}
#[inline(always)]
pub fn bitneg16(b: u16, pos: usize) -> u8 {
!bit16(b, pos) & 1
}
#[cfg(test)]
pub fn assemble_to_file(code: &str) -> OsString {
let input_name = tmpfile();
let middle_name = t... | pub fn bit16(b: u16, pos: usize) -> u8 { | random_line_split |
reducer.js | import { key, PLAY, PAUSE, MUTE, UNMUTE, UPDATE_VOLUME, UPDATE_TIME, SET_SONG, SET_TIME, updateTime } from './actions'
import { store } from '../store'
let audio = new Audio()
audio.addEventListener('timeupdate', event => store.dispatch(updateTime(event)))
const initialState = {
isPlaying: false,
muted: false,
... | default:
return state
}
} | return { ...state, src: payload }
} | random_line_split |
reducer.js | import { key, PLAY, PAUSE, MUTE, UNMUTE, UPDATE_VOLUME, UPDATE_TIME, SET_SONG, SET_TIME, updateTime } from './actions'
import { store } from '../store'
let audio = new Audio()
audio.addEventListener('timeupdate', event => store.dispatch(updateTime(event)))
const initialState = {
isPlaying: false,
muted: false,
... | (state = initialState, { type, payload }) {
switch (type) {
case PLAY:
{
audio.play()
return { ...state, isPlaying: !state.isPlaying }
}
case PAUSE:
{
audio.pause()
return { ...state, isPlaying: !state.isPlaying }
}
case MUTE:
{
audi... | reducer | identifier_name |
reducer.js | import { key, PLAY, PAUSE, MUTE, UNMUTE, UPDATE_VOLUME, UPDATE_TIME, SET_SONG, SET_TIME, updateTime } from './actions'
import { store } from '../store'
let audio = new Audio()
audio.addEventListener('timeupdate', event => store.dispatch(updateTime(event)))
const initialState = {
isPlaying: false,
muted: false,
... | case UNMUTE:
{
audio.muted = false
return { ...state, muted: false }
}
case UPDATE_TIME:
{
const { currentTime, duration, completed } = payload
return { ...state, currentTime, duration, completed }
}
case UPDATE_VOLUME:
{
audio.volume =... | {
switch (type) {
case PLAY:
{
audio.play()
return { ...state, isPlaying: !state.isPlaying }
}
case PAUSE:
{
audio.pause()
return { ...state, isPlaying: !state.isPlaying }
}
case MUTE:
{
audio.muted = true
return { ...state, ... | identifier_body |
content.rs | #![stable]
use libc;
use std;
/// Opaque struct which holds a reference to the underlying Clutter object.
#[repr(C)]
pub struct ContentRef {
opaque: *mut libc::c_void
}
/// Delegate for painting the content of an actor
///
/// Content is an interface to implement types responsible for painting the
/// content of a... | }
}
}
impl Content for ContentRef {
fn as_content(&self) -> *mut libc::c_void {
return self.opaque;
}
}
extern {
fn clutter_content_get_preferred_size(self_value: *mut libc::c_void, width: *mut f32, height: *mut f32) -> i32;
fn clutter_content_invalidate(self_value: *mut libc::c_void);
} | clutter_content_invalidate(self.as_content()); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.