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 |
|---|---|---|---|---|
bootstrap.py | IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Bootstrap a buildout-b... | (parsed_version):
for part in parsed_version:
if (part[:1] == '*') and (part not in _final_parts):
return False
return True
index = setuptools.package_index.PackageIndex(
search_path=[setup_requirement_path])
if find_links:
index.add_find_links((find_l... | _final_version | identifier_name |
meteorite.js | // meteorite namespace
var Meteorite = Meteorite || {};
// initialize websocket
Meteorite.websocket = new WebSocket("ws://" + location.hostname + ":8080/");
console.log('starting meteorite websockets. . .');
// when a new websocket message is received
Meteorite.websocket.onmessage = function(msg) {
// parse the js... | else {
Meteorite.update(json, $(this));
}
}
});
}
// add an item
Meteorite.add = function(json, $element) {
// add to the dom
$element.append(json.bind_data);
// listen to subscribe events
Meteorite.subscribe($(json.bind_data).find('.meteorite').data('bind-key'));
}
// update a s... | {
Meteorite.add(json, $(this));
// else update the element
} | conditional_block |
meteorite.js | // meteorite namespace
var Meteorite = Meteorite || {};
// initialize websocket
Meteorite.websocket = new WebSocket("ws://" + location.hostname + ":8080/");
console.log('starting meteorite websockets. . .');
// when a new websocket message is received
Meteorite.websocket.onmessage = function(msg) {
// parse the js... | Meteorite.subscribe($(json.bind_data).find('.meteorite').data('bind-key'));
}
// update a single attribute
Meteorite.update = function(json, $element) {
// get the bind data
var bind_data = JSON.parse(json.bind_data);
// desired attribute
var bind_attr = $element.data('bind-attr');
// get the attribute d... | // add an item
Meteorite.add = function(json, $element) {
// add to the dom
$element.append(json.bind_data);
// listen to subscribe events | random_line_split |
instr_cvtdq2ps.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn cvtdq2ps_1() |
#[test]
fn cvtdq2ps_2() {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledDisplaced(ECX, Two, 829617393, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, ... | {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM2)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 210], OperandSize::Dword)
} | identifier_body |
instr_cvtdq2ps.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn cvtdq2ps_1() {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direc... | () {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledDisplaced(RBX, Two, 1952076968, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[1... | cvtdq2ps_4 | identifier_name |
instr_cvtdq2ps.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test] | fn cvtdq2ps_1() {
run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM2)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 210], OperandSize::Dword)
}
#[test]
fn cvtdq2p... | random_line_split | |
node.js | 'use strict';
var i18n = require('./i18n.js')
i18n.add_translation("pt-BR", { | welcome: 'Bem vindo'
}
});
i18n.locale = 'pt-BR';
console.log(i18n.t('greetings.hello'));
console.log(i18n.t('greetings.welcome'));
console.log("Hallo");
// Example 2
i18n.add_translation("pt-BR", {
greetings: {
hello: 'Olá',
welcome: 'Bem vindo'
}
});
console.log(i18n.t('greetings.hello'));
i18n.... | test: 'OK',
greetings: {
hello: 'Olá', | random_line_split |
decorators.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Red Hat, Inc
#
# 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 applicab... | def reject():
"""Sends a 401 reject response that enables basic auth."""
auth_message = (
"Could not verify your access level for that URL."
"Please login with proper credentials."
)
auth_message = json.dumps({"_status": "Unauthorized", "message": auth_message})
headers = {"WWW-Aut... |
from dci.db import models2
| random_line_split |
decorators.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Red Hat, Inc
#
# 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 applicab... |
def log(f):
@wraps(f)
def decorated(*args, **kwargs):
user = args[0]
try:
log = models2.Log(
**{
"user_id": user.id,
"action": f.__name__,
"created_at": datetime.datetime.utcnow().isoformat(),
... | @wraps(f)
def decorated(*args, **kwargs):
auth_class = _get_auth_class_from_headers(flask.request.headers)
auth_scheme = auth_class(flask.request)
auth_scheme.authenticate()
return f(auth_scheme.identity, *args, **kwargs)
return decorated | identifier_body |
decorators.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Red Hat, Inc
#
# 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 applicab... |
raise dci_exc.DCIException(
"Authorization scheme %s unknown" % auth_type, status_code=401
)
def login_required(f):
@wraps(f)
def decorated(*args, **kwargs):
auth_class = _get_auth_class_from_headers(flask.request.headers)
auth_scheme = auth_class(flask.request)
auth_... | return am.BasicAuthMechanism | conditional_block |
decorators.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Red Hat, Inc
#
# 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 applicab... | (f):
@wraps(f)
def decorated(*args, **kwargs):
user = args[0]
try:
log = models2.Log(
**{
"user_id": user.id,
"action": f.__name__,
"created_at": datetime.datetime.utcnow().isoformat(),
}
... | log | identifier_name |
scan.ts | import { isBrowser, target } from '@vue-devtools/shared-utils'
const rootInstances = []
let rootUID = 0
/**
* Scan the page for root level Vue instances.
*/
export function scan () {
rootInstances.length = 0
let inFragment = false
let currentFragment = null
// eslint-disable-next-line no-inner-declaration... | (node, fn) {
if (node.childNodes) {
for (let i = 0, l = node.childNodes.length; i < l; i++) {
const child = node.childNodes[i]
const stop = fn(child)
if (!stop) {
walk(child, fn)
}
}
}
// also walk shadow DOM
if (node.shadowRoot) {
walk(node.shadowRoot, fn)
}
}
| walk | identifier_name |
scan.ts | import { isBrowser, target } from '@vue-devtools/shared-utils'
const rootInstances = []
let rootUID = 0
/**
* Scan the page for root level Vue instances.
*/
export function scan () | baseVue = baseVue.super
}
if (baseVue.config && baseVue.config.devtools) {
// give a unique id to root instance so we can
// 'namespace' its children
if (typeof instance.__VUE_DEVTOOLS_ROOT_UID__ === 'undefined') {
instance.__VUE_DEVTOOLS_ROOT_UID__ = ++rootUID
... | {
rootInstances.length = 0
let inFragment = false
let currentFragment = null
// eslint-disable-next-line no-inner-declarations
function processInstance (instance) {
if (instance) {
if (rootInstances.indexOf(instance.$root) === -1) {
instance = instance.$root
}
if (instance._isF... | identifier_body |
scan.ts | import { isBrowser, target } from '@vue-devtools/shared-utils'
const rootInstances = []
let rootUID = 0
/**
* Scan the page for root level Vue instances.
*/
export function scan () {
rootInstances.length = 0
let inFragment = false
let currentFragment = null
// eslint-disable-next-line no-inner-declaration... |
return true
}
}
if (isBrowser) {
const walkDocument = document => {
walk(document, function (node) {
if (inFragment) {
if (node === currentFragment._fragmentEnd) {
inFragment = false
currentFragment = null
}
return true
}
... | {
// give a unique id to root instance so we can
// 'namespace' its children
if (typeof instance.__VUE_DEVTOOLS_ROOT_UID__ === 'undefined') {
instance.__VUE_DEVTOOLS_ROOT_UID__ = ++rootUID
}
rootInstances.push(instance)
} | conditional_block |
scan.ts | import { isBrowser, target } from '@vue-devtools/shared-utils'
const rootInstances = []
let rootUID = 0
/**
* Scan the page for root level Vue instances.
*/
export function scan () {
rootInstances.length = 0
let inFragment = false
let currentFragment = null
// eslint-disable-next-line no-inner-declaration... | function processInstance (instance) {
if (instance) {
if (rootInstances.indexOf(instance.$root) === -1) {
instance = instance.$root
}
if (instance._isFragment) {
inFragment = true
currentFragment = instance
}
// respect Vue.config.devtools option
let ba... | random_line_split | |
index.js | /*
The MIT License (MIT)
Copyright (c) 2015 Bryan Hughes <bryan@nebri.us>
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 restriction, including without limitation the rights
to use, copy... | The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFR... | random_line_split | |
index.js | /*
The MIT License (MIT)
Copyright (c) 2015 Bryan Hughes <bryan@nebri.us>
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 restriction, including without limitation the rights
to use, copy... |
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var fs_1 = require("fs");
var raspi_peripheral_1 = require("raspi-peripheral");
var hasLed = fs_1.existsSync('/sys/class/leds/led0') &&
fs_1.existsSync('/sys/class/leds/led0/trigger') &&
fs_1.existsSync('/sys/class/led... | { this.constructor = d; } | identifier_body |
index.js | /*
The MIT License (MIT)
Copyright (c) 2015 Bryan Hughes <bryan@nebri.us>
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 restriction, including without limitation the rights
to use, copy... |
};
return LED;
}(raspi_peripheral_1.Peripheral));
exports.LED = LED;
//# sourceMappingURL=index.js.map | {
fs_1.writeFileSync('/sys/class/leds/led0/brightness', value ? '255' : '0');
} | conditional_block |
index.js | /*
The MIT License (MIT)
Copyright (c) 2015 Bryan Hughes <bryan@nebri.us>
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 restriction, including without limitation the rights
to use, copy... | () { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var fs_1 = require("fs");
var raspi_peripheral_1 = require("raspi-peripheral");
var hasLed = fs_1.existsSync('/sys/class/leds/led0') &&
fs_1.existsSync('/sys/class/leds/led0/trigger') &&
fs_... | __ | identifier_name |
util.py | """Contains utility methods used by and with the pyebnf package."""
import math
def esc_split(text, delimiter=" ", maxsplit=-1, escape="\\", *, ignore_empty=False):
"""Escape-aware text splitting:
Split text on on a delimiter, recognizing escaped delimiters."""
is_escaped = False
split_count = 0
yval = []... | if char_no >= len(tail_body):
tail = " " * (char_no - len(tail_body)) + tail_body + pointer_char
else:
tail = " " * char_no + pointer_char + tail_body
if show_line_numbers:
line_no_width = int(math.ceil(math.log10(max(1, line_no + surrounding_lines))) + 1)
line_fmt = "{0:" + str(line_no_width) + ... | """Point to a position in source code.
source is the text we're pointing in.
position is a 2-tuple of (line_number, character_number) to point to.
fmt is a 4-tuple of formatting parameters, they are:
name default description
---- ------- -----------
surrounding_lines 2 ... | identifier_body |
util.py | """Contains utility methods used by and with the pyebnf package."""
import math
def esc_split(text, delimiter=" ", maxsplit=-1, escape="\\", *, ignore_empty=False):
"""Escape-aware text splitting:
Split text on on a delimiter, recognizing escaped delimiters."""
is_escaped = False
split_count = 0
yval = []... | (text):
"""Returns a list of the positions in the text where all new lines occur. This is used by
get_line_and_char to efficiently find coordinates represented by offset positions.
"""
pos = []
for i, c in enumerate(text):
if c == "\n":
pos.append(i)
return pos
def get_line_and_char(newline_posi... | get_newline_positions | identifier_name |
util.py | """Contains utility methods used by and with the pyebnf package."""
import math
def esc_split(text, delimiter=" ", maxsplit=-1, escape="\\", *, ignore_empty=False):
"""Escape-aware text splitting:
Split text on on a delimiter, recognizing escaped delimiters."""
is_escaped = False
split_count = 0
yval = []... | return pos
def get_line_and_char(newline_positions, position):
"""Given a list of newline positions, and an offset from the start of the source code
that newline_positions was pulled from, return a 2-tuple of (line, char) coordinates.
"""
if newline_positions:
for line_no, nl_pos in enumerate(newline_po... | random_line_split | |
util.py | """Contains utility methods used by and with the pyebnf package."""
import math
def esc_split(text, delimiter=" ", maxsplit=-1, escape="\\", *, ignore_empty=False):
"""Escape-aware text splitting:
Split text on on a delimiter, recognizing escaped delimiters."""
is_escaped = False
split_count = 0
yval = []... |
yield "".join(yval)
def esc_join(iterable, delimiter=" ", escape="\\"):
"""Join an iterable by a delimiter, replacing instances of delimiter in items
with escape + delimiter.
"""
rep = escape + delimiter
return delimiter.join(i.replace(delimiter, rep) for i in iterable)
def get_newline_positions(text)... | yval.append(char) | conditional_block |
SlackReader.spec.ts | import { API } from '@spinnaker/core';
import { ISlackChannel, SlackReader } from './SlackReader';
const mockSlackChannels: ISlackChannel[] = [
{
id: '0-test',
name: 'testchannel',
is_channel: true,
creator: 'creator',
is_archived: false,
name_normalized: 'testchannel',
num_members: 25,
... | expect(API.one).toHaveBeenCalledWith('slack/channels');
});
});
}); | random_line_split | |
search_history_item.py | __author__ = 'bromix'
from .directory_item import DirectoryItem
from .. import constants
class SearchHistoryItem(DirectoryItem):
def | (self, context, query, image=None, fanart=None):
if image is None:
image = context.create_resource_path('media/search.png')
pass
DirectoryItem.__init__(self, query, context.create_uri([constants.paths.SEARCH, 'query'], {'q': query}),
image=image)
... | __init__ | identifier_name |
search_history_item.py | __author__ = 'bromix'
from .directory_item import DirectoryItem
from .. import constants
class SearchHistoryItem(DirectoryItem):
def __init__(self, context, query, image=None, fanart=None):
if image is None:
image = context.create_resource_path('media/search.png')
pass
Di... | (context.localize(constants.localize.SEARCH_RENAME),
'RunPlugin(%s)' % context.create_uri([constants.paths.SEARCH, 'rename'], params={'q': query})),
(context.localize(constants.localize.SEARCH_CLEAR),
'RunPlugin(%s)' % con... | context_menu = [(context.localize(constants.localize.SEARCH_REMOVE),
'RunPlugin(%s)' % context.create_uri([constants.paths.SEARCH, 'remove'], params={'q': query})), | random_line_split |
search_history_item.py | __author__ = 'bromix'
from .directory_item import DirectoryItem
from .. import constants
class SearchHistoryItem(DirectoryItem):
def __init__(self, context, query, image=None, fanart=None):
if image is None:
|
DirectoryItem.__init__(self, query, context.create_uri([constants.paths.SEARCH, 'query'], {'q': query}),
image=image)
if fanart:
self.set_fanart(fanart)
pass
else:
self.set_fanart(context.get_fanart())
pass
... | image = context.create_resource_path('media/search.png')
pass | conditional_block |
search_history_item.py | __author__ = 'bromix'
from .directory_item import DirectoryItem
from .. import constants
class SearchHistoryItem(DirectoryItem):
| self.set_context_menu(context_menu)
pass
pass
| def __init__(self, context, query, image=None, fanart=None):
if image is None:
image = context.create_resource_path('media/search.png')
pass
DirectoryItem.__init__(self, query, context.create_uri([constants.paths.SEARCH, 'query'], {'q': query}),
im... | identifier_body |
index.tsx | import React from 'react'
import moment from 'moment'
import { RouteComponentProps } from 'react-router-dom'
import { DatePicker, Button, Form, Input } from 'antd'
import { FormInstance } from 'antd/lib/form'
import BaseContainer from 'ROOT_SOURCE/base/BaseContainer'
import request from 'ROOT_SOURCE/utils/request'
imp... |
/**
* 提交表单
*/
submitForm = async (values: object) => {
// 提交表单最好新起一个事务,不受其他事务影响
await this.sleep()
// 提交请求
await request.post('/asset/updateAsset', values)
// 提交后返回list页
this.props.history.push(`${this.context.CONTAINER_ROUTE_PREFIX}/list`)
}
... | export default class extends BaseContainer<IFormProps4Item> {
formRef = React.createRef<FormInstance>(); | random_line_split |
index.tsx | import React from 'react'
import moment from 'moment'
import { RouteComponentProps } from 'react-router-dom'
import { DatePicker, Button, Form, Input } from 'antd'
import { FormInstance } from 'antd/lib/form'
import BaseContainer from 'ROOT_SOURCE/base/BaseContainer'
import request from 'ROOT_SOURCE/utils/request'
imp... | <Form ref={this.formRef} onFinish={this.submitForm}>
<Form.Item name='id' noStyle>
<Input type='hidden' />
</Form.Item>
<Form.Item name='assetName' label='资产方名称' rules={[{ required: true }]}>
<Input... | >
| identifier_name |
index.tsx | import React from 'react'
import moment from 'moment'
import { RouteComponentProps } from 'react-router-dom'
import { DatePicker, Button, Form, Input } from 'antd'
import { FormInstance } from 'antd/lib/form'
import BaseContainer from 'ROOT_SOURCE/base/BaseContainer'
import request from 'ROOT_SOURCE/utils/request'
imp... | </Form.Item>
<Form.Item name='contactsPhone' label='联系电话' rules={[{ pattern: Rules.phone, message: '无效' }]}>
<Input maxLength={11} />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType... | <Form ref={this.formRef} onFinish={this.submitForm}>
<Form.Item name='id' noStyle>
<Input type='hidden' />
</Form.Item>
<Form.Item name='assetName' label='资产方名称' rules={[{ required: true }]}>
<Input di... | identifier_body |
index.tsx | import React from 'react'
import moment from 'moment'
import { RouteComponentProps } from 'react-router-dom'
import { DatePicker, Button, Form, Input } from 'antd'
import { FormInstance } from 'antd/lib/form'
import BaseContainer from 'ROOT_SOURCE/base/BaseContainer'
import request from 'ROOT_SOURCE/utils/request'
imp... | i-background">
<Form ref={this.formRef} onFinish={this.submitForm}>
<Form.Item name='id' noStyle>
<Input type='hidden' />
</Form.Item>
<Form.Item name='assetName' label='资产方名称' rules={[{ required: true }]}>
... | .data,
contractDate: data.contractDate ? moment(data.contractDate) : undefined,
});
}
}
render() {
return (
<div className="u | conditional_block |
import_prescribing.py | """
Import prescribing data from CSV files into SQLite
"""
from collections import namedtuple
import csv
from itertools import groupby
import logging
import os
import sqlite3
import gzip
import heapq
from matrixstore.matrix_ops import sparse_matrix, finalise_matrix
from matrixstore.serializer import serialize_compress... | (prescriptions, practices, dates):
"""
Accepts an iterable of prescriptions plus mappings of pratice codes and
date strings to their respective row/column offsets. Yields tuples of the
form:
bnf_code, items_matrix, quantity_matrix, actual_cost_matrix, net_cost_matrix
Where the matrices con... | build_matrices | identifier_name |
import_prescribing.py | """
from collections import namedtuple
import csv
from itertools import groupby
import logging
import os
import sqlite3
import gzip
import heapq
from matrixstore.matrix_ops import sparse_matrix, finalise_matrix
from matrixstore.serializer import serialize_compressed
from .common import get_prescribing_filename
logg... | """
Import prescribing data from CSV files into SQLite | random_line_split | |
import_prescribing.py | """
Import prescribing data from CSV files into SQLite
"""
from collections import namedtuple
import csv
from itertools import groupby
import logging
import os
import sqlite3
import gzip
import heapq
from matrixstore.matrix_ops import sparse_matrix, finalise_matrix
from matrixstore.serializer import serialize_compress... | yield (
serialize_compressed(row.items),
serialize_compressed(row.quantity),
serialize_compressed(row.actual_cost),
serialize_compressed(row.net_cost),
row.bnf_code,
)
logger.info("Finished writing data for %s presentations", count)
def ... | """
Given an iterable of MatrixRows (which contain a BNF code plus all
prescribing data for that presentation) yield tuples of values ready for
insertion into SQLite
"""
cursor = connection.cursor()
num_presentations = next(cursor.execute("SELECT COUNT(*) FROM presentation"))[0]
count = 0
... | identifier_body |
import_prescribing.py | """
Import prescribing data from CSV files into SQLite
"""
from collections import namedtuple
import csv
from itertools import groupby
import logging
import os
import sqlite3
import gzip
import heapq
from matrixstore.matrix_ops import sparse_matrix, finalise_matrix
from matrixstore.serializer import serialize_compress... |
yield MatrixRow(
bnf_code,
finalise_matrix(items_matrix),
finalise_matrix(quantity_matrix),
finalise_matrix(actual_cost_matrix),
finalise_matrix(net_cost_matrix),
)
def format_as_sql_rows(matrices, connection):
"""
Given an iterable ... | practice_offset = practices[practice]
date_offset = dates[date]
items_matrix[practice_offset, date_offset] = items
quantity_matrix[practice_offset, date_offset] = quantity
actual_cost_matrix[practice_offset, date_offset] = actual_cost
net_cost_matrix[practice_... | conditional_block |
emailMixin.js | Augments the apos object with a mixin method for attaching
* a simple self.email method to modules, so that they can delivewr email
* conveniently using templates rendered in the context of that module.
* @see static
*/
module.exports = function(self) {
// This mixin adds a self.email method to the specified mo... | (to) {
if (typeof(to) === 'string') {
return to;
}
return (to.fullName || to.title).replace(/[ | fixAddress | identifier_name |
emailMixin.js | Augments the apos object with a mixin method for attaching
* a simple self.email method to modules, so that they can delivewr email
* conveniently using templates rendered in the context of that module.
* @see static
*/
module.exports = function(self) {
// This mixin adds a self.email method to the specified mo... | // PLEASE NOTE: if you pass an object as the "from" argument, configuration options are
// always ignored in favor of what you passed. However if you pass a string it is
// assumed to be a hard-coded default and options are allowed to override it.
self.mixinModuleEmail = function(module) {
module.email = f... | // Or use an object with fullName and email properties.
// | random_line_split |
emailMixin.js | to modules, so that they can delivewr email
* conveniently using templates rendered in the context of that module.
* @see static
*/
module.exports = function(self) {
// This mixin adds a self.email method to the specified module object.
//
// Your module must also have mixinModuleAssets.
//
// IF YOU ARE... | {
if (typeof(to) === 'string') {
return to;
}
return (to.fullName || to.title).replace(/[<\>]/g, '') + ' <' + to.email + '>';
} | identifier_body | |
emailMixin.js | Augments the apos object with a mixin method for attaching
* a simple self.email method to modules, so that they can delivewr email
* conveniently using templates rendered in the context of that module.
* @see static
*/
module.exports = function(self) {
// This mixin adds a self.email method to the specified mo... | else {
// An alternative for those not using apostrophe-site
module._mailer = nodemailer.createTransport(options.transport, options.transportOptions);
}
}
var message = {
from: fixAddress(from),
to: fixAddress(to),
subject: module.renderString(subject, fi... | {
// This will always work with apostrophe-site
module._mailer = moduleOptions.mailer;
} | conditional_block |
setup_wizard.py | .eboot_path)
hacked_eboot, offset = apply_eboot_patches(hacked_eboot)
with open(os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "EBOOT.BIN"), "wb") as f:
hacked_eboot.tofile(f)
# shutil.copy(self.eboot_path, os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "EBOOT.BIN"))
progres... | = get_save_file(self, self.ui.txtTerminology.text(), filter = "Terminology.csv (*.csv)")
if not dir == "":
self.ui.txtTerminology.setText(dir)
| identifier_body | |
setup_wizard.py |
iso_dir = common.qt_to_unicode(self.ui.txtIso.text(), normalize = False)
if not os.path.isdir(iso_dir):
self.show_error("ISO directory does not exist.")
return
validated = True
with open("data/file_order.txt", "rb") as file_order:
# Since we're reappropriating this from the fil... |
self.workspace_dir = workspace_dir
self.ui.grpStep2.setEnabled(False)
self.ui.grpStep3.setEnabled(True)
##############################################################################
### STEP 3
##############################################################################
def check_eboot(sel... | f.show_info("Workspace directory already exists.\n\nExisting data will be overwritten.")
| conditional_block |
setup_wizard.py | gfx_base.extractall(gfx_dir)
progress.setValue(5)
gfx_base.close()
gfx_dec.close()
gfx_enc.close()
gfx_bin.close()
# We can mostly loop this.
gfx_data = [
("ammo", "kotodama_icn_???.gim"),
("bgd", "bgd_???.gim"),
("cutin", "cutin_icn_???.gim"),
... | ect(se | identifier_name | |
setup_wizard.py | Reset(False)
progress.setLabelText("Creating directories...")
# Do the easy stuff first.
if not os.path.isdir(self.changes_dir):
os.makedirs(self.changes_dir)
progress.setValue(progress.value() + 1)
if not os.path.isdir(self.backup_dir):
os.makedirs(self.backup_dir)
pr... | # of the flash files we need in the gfx_base archive. So let's load that.
with open(os.path.join(gfx_dir, "fla.txt"), "rb") as fla:
fla_list = fla.readlines() | random_line_split | |
api.py | from .resources import (
AuthorResource, BookPrefixResource, ArticleResource, SomeOtherResource,
CustomResource, CSVResource)
from adrest.api import Api
from adrest.utils.auth import AnonimousAuthenticator, AccessKeyAuthenticator, \
UserAuthenticator
from adrest.utils.emitter import XMLTemplateEmitter, JSON... | (UserAuthenticator):
username_fieldname = 'nickname'
API = Api(
version=(1, 0, 0), emitters=(XMLTemplateEmitter, JSONEmitter),
throttle=CacheThrottle, api_prefix='main')
API.register(AuthorResource,
authenticators=(CustomUserAuth, AnonimousAuthenticator))
API.register(BookPrefixResource)
API... | CustomUserAuth | identifier_name |
api.py | from .resources import (
AuthorResource, BookPrefixResource, ArticleResource, SomeOtherResource,
CustomResource, CSVResource)
from adrest.api import Api
from adrest.utils.auth import AnonimousAuthenticator, AccessKeyAuthenticator, \
UserAuthenticator
from adrest.utils.emitter import XMLTemplateEmitter, JSON... |
API = Api(
version=(1, 0, 0), emitters=(XMLTemplateEmitter, JSONEmitter),
throttle=CacheThrottle, api_prefix='main')
API.register(AuthorResource,
authenticators=(CustomUserAuth, AnonimousAuthenticator))
API.register(BookPrefixResource)
API.register(CustomResource)
API.register(ArticleResource, ... | username_fieldname = 'nickname' | identifier_body |
api.py | from .resources import (
AuthorResource, BookPrefixResource, ArticleResource, SomeOtherResource,
CustomResource, CSVResource)
from adrest.api import Api
from adrest.utils.auth import AnonimousAuthenticator, AccessKeyAuthenticator, \
UserAuthenticator
from adrest.utils.emitter import XMLTemplateEmitter, JSON... | API.register(ArticleResource, authenticators=AccessKeyAuthenticator)
API.register(SomeOtherResource, url_name='test', url_regex='test/mem/$')
API.register(CSVResource)
# lint_ignore=C |
API.register(AuthorResource,
authenticators=(CustomUserAuth, AnonimousAuthenticator))
API.register(BookPrefixResource)
API.register(CustomResource) | random_line_split |
run_trf_2.py | import os
import sys
import numpy as np
import matplotlib.pyplot as plt
sys.path.insert(0, os.getcwd() + '/../../tools/')
import wb
import trf
import wer
def process_nbest(fread, fwrite):
nEmptySentNum = 0
with open(fread, 'rt') as f1, open(fwrite, 'wt') as f2:
for a in [line.split() for line in f1]:
... | ():
if len(sys.argv) == 1:
print('\"python run.py -train\" train LSTM\n',
'\"python run.py -rescore\" rescore nbest\n',
'\"python run.py -wer\" compute WER'
)
bindir = '../../tools/trf/bin/'
workdir = 'trflm/'
fres = wb.FRes('models_ppl.txt')
model ... | main | identifier_name |
run_trf_2.py | import os
import sys
import numpy as np
import matplotlib.pyplot as plt
sys.path.insert(0, os.getcwd() + '/../../tools/')
import wb
import trf
import wer
def process_nbest(fread, fwrite):
nEmptySentNum = 0
with open(fread, 'rt') as f1, open(fwrite, 'wt') as f2:
for a in [line.split() for line in f1]:
... | feat = 'g4_w_c_ws_cs_wsh_csh_tied.fs'
#feat = 'g4_w_c_ws_cs_wsh_csh.fs'
maxlen = 0
tmax = 20000
t0 = 0
minibatch = 100
gamma_lambda = '3000,0'
gamma_zeta = '0,0.6'
reg = 1e-6
thread = 8
write_model = workdir + 'trf_c{}_{}_2'.format(class_num, feat[0:-3])
if '-train' in s... | if len(sys.argv) == 1:
print('\"python run.py -train\" train LSTM\n',
'\"python run.py -rescore\" rescore nbest\n',
'\"python run.py -wer\" compute WER'
)
bindir = '../../tools/trf/bin/'
workdir = 'trflm/'
fres = wb.FRes('models_ppl.txt')
model = trf.mo... | identifier_body |
run_trf_2.py | import os
import sys
import numpy as np
import matplotlib.pyplot as plt
sys.path.insert(0, os.getcwd() + '/../../tools/')
import wb
import trf
import wer
def process_nbest(fread, fwrite):
nEmptySentNum = 0
with open(fread, 'rt') as f1, open(fwrite, 'wt') as f2:
for a in [line.split() for line in f1]:
... |
f2.write(' '.join(a) + '\n')
print('[nbest] empty sentence num = {}'.format(nEmptySentNum))
def main():
if len(sys.argv) == 1:
print('\"python run.py -train\" train LSTM\n',
'\"python run.py -rescore\" rescore nbest\n',
'\"python run.py -wer\" compute WER'
... | nEmptySentNum += 1
a.append('<UNK>') | conditional_block |
run_trf_2.py | import os
import sys
import numpy as np
import matplotlib.pyplot as plt
sys.path.insert(0, os.getcwd() + '/../../tools/')
import wb
import trf
import wer
def process_nbest(fread, fwrite):
nEmptySentNum = 0
with open(fread, 'rt') as f1, open(fwrite, 'wt') as f2:
for a in [line.split() for line in f1]:
... |
if __name__ == '__main__':
main() | random_line_split | |
termactions.py | import lxml
from lxml.etree import (
XPath,
)
from lxml.cssselect import CSSSelector
import re
from .utils import (
raise_again,
generic_translator,
preprocess_selector,
)
class BaseTermAction(object):
in_type = None
out_type = None
@staticmethod
def _... |
else:
sflags = ''
(self._count, flags) = self._handle_flags(sflags)
self._re = re.compile(args[0], flags=flags)
def _handle_flags(self, flags):
flags = set(flags)
bflags = 0
if not flags <= self.allowed_flags:
raise ValueError("Unknown f... | sflags = args[2] | conditional_block |
termactions.py | import lxml
from lxml.etree import (
XPath,
)
from lxml.cssselect import CSSSelector
import re
from .utils import (
raise_again,
generic_translator,
preprocess_selector,
)
class BaseTermAction(object):
in_type = None
out_type = None
@staticmethod
def _... |
class GenericSelectorTermAction(GenericTermAction):
def __init__(self, f, selector, in_type=None, out_type=None, identification=None, args=None):
super(GenericSelectorTermAction, self).__init__(f, in_type=in_type, out_type=out_type, identification=identification, args=args)
self._selector = sele... | def __init__(self, f, in_type=None, out_type=None, args=None, identification=None):
self._f = f
self._id = identification
self.in_type = in_type
self.out_type = out_type
if args is None:
args = []
self._args = list(args)
def sub_execute(self, value):
... | identifier_body |
termactions.py | import lxml
from lxml.etree import (
XPath,
)
from lxml.cssselect import CSSSelector
import re
from .utils import ( |
class BaseTermAction(object):
in_type = None
out_type = None
@staticmethod
def _check_types_match(t1, t2):
return (t1 is None) or (t2 is None) or (t1 == t2)
def can_precede(self, other):
return BaseTermAction._check_types_match(self.out_type, other.in_type)
def can_follow(... | raise_again,
generic_translator,
preprocess_selector,
) | random_line_split |
termactions.py | import lxml
from lxml.etree import (
XPath,
)
from lxml.cssselect import CSSSelector
import re
from .utils import (
raise_again,
generic_translator,
preprocess_selector,
)
class BaseTermAction(object):
in_type = None
out_type = None
@staticmethod
def _... | (self, anchor, out_type, identification=None):
self._anchor = anchor
self._id = identification
self.out_type = out_type
def execute(self, context):
# value must be a context
return context.get_anchor(self._anchor)
class RegexTermAction(BaseTermAction):
in_type = 'stri... | __init__ | identifier_name |
execute-1.py | ##########################################################################
#
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
# Copyright (c) 2014-2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted prov... | ( self ) :
Gaffer.Application.__init__(
self,
"""
Executes task nodes such as ImageWriters, SystemCommands and Render nodes
from within a .gfr file. This is used by Gaffer's dispatchers when executing
nodes in a background process or on a render farm, but can also be used to
perform a manual execut... | __init__ | identifier_name |
execute-1.py | ##########################################################################
#
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
# Copyright (c) 2014-2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted prov... | nodes.append( node )
else :
for node in scriptNode.children() :
if hasattr( node, "execute" ) :
nodes.append( node )
if not nodes :
IECore.msg( IECore.Msg.Level.Error, "gaffer execute", "Script has no executable nodes" )
return 1
if len(args["context"]) % 2 :
IECore.msg( IECore.Msg.Le... | scriptNode = Gaffer.ScriptNode()
scriptNode["fileName"].setValue( os.path.abspath( args["script"].value ) )
try :
scriptNode.load( continueOnError = args["ignoreScriptLoadErrors"].value )
except Exception as exception :
IECore.msg( IECore.Msg.Level.Error, "gaffer execute : loading \"%s\"" % scriptNode["file... | identifier_body |
execute-1.py | ##########################################################################
#
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
# Copyright (c) 2014-2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted prov... |
if len(args["context"]) % 2 :
IECore.msg( IECore.Msg.Level.Error, "gaffer execute", "Context parameter must have matching entry/value pairs" )
return 1
context = Gaffer.Context( scriptNode.context() )
for i in range( 0, len(args["context"]), 2 ) :
entry = args["context"][i].lstrip( "-" )
context[en... | IECore.msg( IECore.Msg.Level.Error, "gaffer execute", "Script has no executable nodes" )
return 1 | conditional_block |
execute-1.py | ##########################################################################
#
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
# Copyright (c) 2014-2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted prov... | "flagless" : IECore.StringVectorData( [ "script" ] )
}
)
def _run( self, args ) :
scriptNode = Gaffer.ScriptNode()
scriptNode["fileName"].setValue( os.path.abspath( args["script"].value ) )
try :
scriptNode.load( continueOnError = args["ignoreScriptLoadErrors"].value )
except Exception as excepti... | random_line_split | |
telegram.service.js | Key, {
polling: true,
filepath: false
});
var errorCounter = 0;
bot.on('polling_error', function(err) {
if(errorCounter < 5) {
console.error('Telegram polling failure', err.code, err.response && err.response.body);
} else if((errorCounter % 40) === 0) {
console.error('Telegram polling failure (... 9 mo... | eckPreconditions(msg, callbac | identifier_name | |
telegram.service.js | telegram-bot-api');
var bot = new TelegramBot(apiKey, {
polling: true,
filepath: false
});
var errorCounter = 0;
bot.on('polling_error', function(err) {
if(errorCounter < 5) {
console.error('Telegram polling failure', err.code, err.response && err.response.body);
} else if((errorCounter % 40) === 0) {
... | Id = msg.chat.id;
ZiviService.findBy({chart: chatId}, function (err, zivi) {
if (!err && zivi) {
callback(zivi);
} else {
return bot.sendMessage(msg.chat.id, 'You have not yet registered with the El Señor Chefzimon Telegram Integration. ' +
'Type /help for more information.');
}
});
... | identifier_body | |
telegram.service.js | module.exports = TelegramService;
return;
}
var TelegramBot = require('node-telegram-bot-api');
var bot = new TelegramBot(apiKey, {
polling: true,
filepath: false
});
var errorCounter = 0;
bot.on('polling_error', function(err) {
if(errorCounter < 5) {
console.error('Telegram polling failure', err.code, ... | var TelegramService = require('./telegram-dummy.service');
if (!apiKey || process.env.zimonTest) {
console.warn('Using dummy Telegram service, i.e. ignoring all calls.');
console.warn('Set an API key in ./config/local-config.json to change this.'); | random_line_split | |
telegram.service.js | .warn('Using dummy Telegram service, i.e. ignoring all calls.');
console.warn('Set an API key in ./config/local-config.json to change this.');
module.exports = TelegramService;
return;
}
var TelegramBot = require('node-telegram-bot-api');
var bot = new TelegramBot(apiKey, {
polling: true,
filepath: false
});... | ;
});
});
bot.onText(/\/next/, function (msg) {
checkAccountInitialisedOrFail(msg, function () {
findPostAndCheckPreconditions(msg, function (err) {
if (err) {
return bot.sendMessage(msg.chat.id, err);
} else {
PostService.nextZivi(function (err, post) {
bot.sendMessage(ms... | PostService.acceptPost(function (err, post) {
if (err) {
bot.sendMessage(msg.chat.id, 'Internal error accepting. Try again later.');
console.error('Failed to accept post', err);
} else {
bot.sendMessage(msg.chat.id, 'You have agreed to carry out the Honourable... | conditional_block |
regress-96526-noargsub.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the Lic... |
exitFunc ('test');
}
| {
reportCompare(expectedvalues[i], actualvalues[i], statusitems[i]);
} | conditional_block |
regress-96526-noargsub.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the Lic... |
return a[2][j][k][z];
}
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function addThis()
{
statusitems[UBound] = status;
actualvalues[UBound] = actual;
expectedvalues[UBound] = expec... | {
status = inSection(2);
actual = formatArray(a[2]);
expect = formatArray([1,2,[3,4]]);
addThis();
status = inSection(3);
actual = formatArray(a[2][j]);
expect = formatArray([3,4]);
addThis();
status = inSection(4);
actual = a[2][j][k];
expect = 4;
addThis();
status = inSection(5);
actual... | identifier_body |
regress-96526-noargsub.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the Lic... | ()
{
enterFunc('test');
printBugNumber(BUGNUMBER);
printStatus(summary);
for (var i=0; i<UBound; i++)
{
reportCompare(expectedvalues[i], actualvalues[i], statusitems[i]);
}
exitFunc ('test');
}
| test | identifier_name |
regress-96526-noargsub.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the Lic... | * ***** END LICENSE BLOCK ***** */
/*
*
* Date: 29 Oct 2002
* SUMMARY: Testing "use" and "set" operations on expressions like a[i][j][k]
* See http://bugzilla.mozilla.org/show_bug.cgi?id=96526#c52
*
* Brendan: "The idea is to cover all the 'use' and 'set' (as in modify)
* operations you can do on an express... | * the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
* | random_line_split |
connectivity_source_py3.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | 'resource_id': {'key': 'resourceId', 'type': 'str'},
'port': {'key': 'port', 'type': 'int'},
}
def __init__(self, *, resource_id: str, port: int=None, **kwargs) -> None:
super(ConnectivitySource, self).__init__(**kwargs)
self.resource_id = resource_id
self.port = port | _attribute_map = { | random_line_split |
connectivity_source_py3.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | (Model):
"""Parameters that define the source of the connection.
All required parameters must be populated in order to send to Azure.
:param resource_id: Required. The ID of the resource from which a
connectivity check will be initiated.
:type resource_id: str
:param port: The source port fro... | ConnectivitySource | identifier_name |
connectivity_source_py3.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | super(ConnectivitySource, self).__init__(**kwargs)
self.resource_id = resource_id
self.port = port | identifier_body | |
GroupAlert.tsx | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
import * as React from 'react';
import { webAPI } from '@csegames/library/lib/camelotunchained';
import { C... |
export interface GroupAlertProps {
alert: GroupAlert;
remove: (alert: IInteractiveAlert) => void;
}
export class GroupAlertView extends React.Component<GroupAlertProps> {
public render() {
const { alert } = this.props;
return (
<Container>
<h4>
{alert.fromName || 'Unknown'} has ... | {
const alerts = [...alertsList];
if (alerts.findIndex(a => groupInviteID(a as GroupAlert) === groupInviteID(alert)) !== -1) {
return {
alerts,
};
}
alerts.push(alert);
return {
alerts,
};
} | identifier_body |
GroupAlert.tsx | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
import * as React from 'react';
import { webAPI } from '@csegames/library/lib/camelotunchained';
import { C... |
const data = JSON.parse(res.data);
if (data.FieldCodes && data.FieldCodes.length > 0) {
console.error(data.FieldCodes[0].Message);
} else {
// This means api server failed AcceptInvite request but did not provide a message about what happened
console.error('An erro... | {
return
} | conditional_block |
GroupAlert.tsx | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
import * as React from 'react';
import { webAPI } from '@csegames/library/lib/camelotunchained';
import { C... | (alert: GroupAlert) {
return `${alert.kind}:${alert.forGroup}`;
}
export function handleNewGroupAlert(alertsList: IInteractiveAlert[], alert: GroupAlert) {
const alerts = [...alertsList];
if (alerts.findIndex(a => groupInviteID(a as GroupAlert) === groupInviteID(alert)) !== -1) {
return {
aler... | groupInviteID | identifier_name |
GroupAlert.tsx | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
import * as React from 'react';
import { webAPI } from '@csegames/library/lib/camelotunchained';
import { C... | const { alert } = this.props;
this.props.remove(alert);
setTimeout(async () => {
try {
const res = await webAPI.GroupsAPI.JoinV1(
webAPI.defaultConfig,
alert.forGroup,
alert.code);
if (res.ok) {
return
}
const data = JSON.parse(re... | );
}
private joinGroup = () => { | random_line_split |
mut-ptr-cant-outlive-ref.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
trait Fake { fn use_mut(&mut self) { } fn use_ref(&self) { } }
impl<T> Fake for T { }
| {
let m = RefCell::new(0);
let p;
{
let b = m.borrow();
p = &*b;
}
//~^^ ERROR `b` does not live long enough
p.use_ref();
} | identifier_body |
mut-ptr-cant-outlive-ref.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&mut self) { } fn use_ref(&self) { } }
impl<T> Fake for T { }
| use_mut | identifier_name |
mut-ptr-cant-outlive-ref.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. | // option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cell::RefCell;
fn main() {
let m = RefCell::new(0);
let p;
{
let b = m.borrow();
p = &*b;
}
//~^^ ERROR `b` does not live long enough
p.use_ref();
}
trait Fake { fn us... | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | random_line_split |
serializers.py | from django.contrib.auth import get_user_model
User = get_user_model()
from rest_framework import serializers
from nodeshot.core.base.serializers import ModelValidationSerializer
from nodeshot.community.profiles.serializers import ProfileRelationSerializer
from .models import Comment, Vote, Rating, NodeRatingCount
... | :
model = NodeRatingCount
fields = ('likes', 'dislikes', 'rating_count',
'rating_avg', 'comment_count')
| Meta | identifier_name |
serializers.py | from django.contrib.auth import get_user_model
User = get_user_model()
from rest_framework import serializers
from nodeshot.core.base.serializers import ModelValidationSerializer
from nodeshot.community.profiles.serializers import ProfileRelationSerializer
from .models import Comment, Vote, Rating, NodeRatingCount
... |
class RatingSerializer(AutoNodeMixin, ModelValidationSerializer):
""" Rating serializer """
node = serializers.ReadOnlyField(source='node.name')
username = serializers.ReadOnlyField(source='user.username')
class Meta:
model = Rating
fields = ('node', 'username', 'value',)
rea... | """ display user info """
user = ProfileRelationSerializer()
class Meta:
model = Comment
fields = ('user', 'text', 'added',) | identifier_body |
serializers.py | from django.contrib.auth import get_user_model
User = get_user_model()
from rest_framework import serializers
from nodeshot.core.base.serializers import ModelValidationSerializer
from nodeshot.community.profiles.serializers import ProfileRelationSerializer
from .models import Comment, Vote, Rating, NodeRatingCount
... | class Meta:
model = Rating
fields = ('node', 'username', 'value',)
read_only_fields = ('added',)
class VoteSerializer(AutoNodeMixin, ModelValidationSerializer):
node = serializers.ReadOnlyField(source='node.name')
username = serializers.ReadOnlyField(source='user.username')
cl... | username = serializers.ReadOnlyField(source='user.username')
| random_line_split |
symbollist.py | #!/usr/bin/python
#
# Request for symbolList. Currently RFA only support refresh messages
# for symbolList. Hence, polling is required and symbolListRequest is called
# internally by getSymbolList.
#
# IMAGE/REFRESH: | # {'ACTION':'ADD','MTYPE':'IMAGE','SERVICE':'NIP','RIC':'0#BMD','KEY':'FKLI'},
# {'ACTION':'ADD','MTYPE':'IMAGE','SERVICE':'NIP','RIC':'0#BMD','KEY':'FKLL'},
# {'ACTION':'ADD','MTYPE':'IMAGE','SERVICE':'NIP','RIC':'0#BMD','KEY':'FKLM'})
#
import pyrfa
p = pyrfa.Pyrfa()
p.createConfigDb("./pyrfa.cfg")
p.acquir... | # ({'MTYPE':'REFRESH','RIC':'0#BMD','SERVICE':'NIP'}, | random_line_split |
index.js | import axios from 'axios'
const basePath = '/api'
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = 'X-CSRFToken'
export default {
Utils: {
getYearsChoiceList: (app, model) => axios({
url: `${basePath}/${app}/${model}/years/`,
method: 'GET'
}),
getModelOrderedList: ... | url: `${basePath}/${app}/${model}/${action}/?page=${page}`,
method: 'GET'
}),
getByMetadata: (m, query_string = '') => axios({
url: `${basePath}/${m.app}/${m.model}/${m.id}${m.id !== '' ? '/' : ''}${m.action}${m.action !== '' ? '/' : ''}${query_string !== '' ? '?' : ''}${query_string}`,
... | method: 'GET'
}),
getModelListAction: (app, model, action, page = 1) => axios({ | random_line_split |
gen_split.py | #!/opt/local/bin/python
import string
import os
def | (n) :
return "//\n\
// BAGEL - Brilliantly Advanced General Electronic Structure Library\n\
// Filename: SPCASPT2_gen" + str(n) + ".cc\n\
// Copyright (C) 2014 Toru Shiozaki\n\
//\n\
// Author: Toru Shiozaki <shiozaki@northwestern.edu>\n\
// Maintainer: Shiozaki group\n\
//\n\
// This file is part of the BAGEL pack... | header | identifier_name |
gen_split.py | #!/opt/local/bin/python
import string
import os
def header(n) :
return "//\n\
// BAGEL - Brilliantly Advanced General Electronic Structure Library\n\
// Filename: SPCASPT2_gen" + str(n) + ".cc\n\
// Copyright (C) 2014 Toru Shiozaki\n\
//\n\
// Author: Toru Shiozaki <shiozaki@northwestern.edu>\n\
// Maintainer: Sh... |
if (line != ""):
tmp += line + "\n"
if (line == "}"):
tmp += "\n"
tasks.append(tmp)
tmp = ""
num = 0
chunk = 50
for i in range(len(tasks)):
if (num != 0 and num % chunk == 0):
n = num / chunk
fout = open("SPCASPT2_gen" + str(n) + ".cc", "w")
out = header(n) ... | tasks.append(tmp)
tmp = "" | conditional_block |
gen_split.py | import string
import os
def header(n) :
return "//\n\
// BAGEL - Brilliantly Advanced General Electronic Structure Library\n\
// Filename: SPCASPT2_gen" + str(n) + ".cc\n\
// Copyright (C) 2014 Toru Shiozaki\n\
//\n\
// Author: Toru Shiozaki <shiozaki@northwestern.edu>\n\
// Maintainer: Shiozaki group\n\
//\n\
//... | #!/opt/local/bin/python | random_line_split | |
gen_split.py | #!/opt/local/bin/python
import string
import os
def header(n) :
| // You should have received a copy of the GNU General Public License\n\
// along with this program. If not, see <http://www.gnu.org/licenses/>.\n\
//\n\
\n\
#include <bagel_config.h>\n\
#ifdef COMPILE_SMITH\n\
\n\
#include <src/smith/caspt2/SPCASPT2_tasks" + str(n) + ".h>\n\
\n\
using namespace std;\n\
using namespace... | return "//\n\
// BAGEL - Brilliantly Advanced General Electronic Structure Library\n\
// Filename: SPCASPT2_gen" + str(n) + ".cc\n\
// Copyright (C) 2014 Toru Shiozaki\n\
//\n\
// Author: Toru Shiozaki <shiozaki@northwestern.edu>\n\
// Maintainer: Shiozaki group\n\
//\n\
// This file is part of the BAGEL package.\n\
//... | identifier_body |
ChunkTask.d.ts | import BaseTask from "./BaseTask";
/**
* 分块任务
*/
declare class ChunkTask extends BaseTask {
private _blocks;
private _blockSize;
private _chunkSize;
/**
* 构造函数
* @param file
* @param blockSize 块大小
* @param chunkSize 片大小
*/
constructor(file: File, blockSize: number, chunkSi... | readonly chunks: Chunk[];
/**
* 获取正在处理的chunk
* @returns {Block}
*/
readonly processingChunk: Chunk;
/**
* 总共分片数量(所有分块的分片数量总和)
* @returns {number}
*/
readonly totalChunkCount: number;
}
/**
* 分块,分块大小七牛固定是4M
*/
declare class Block {
private _data;
private _start... | */
readonly processingBlock: Block;
readonly finishedBlocksSize: number; | random_line_split |
ChunkTask.d.ts | import BaseTask from "./BaseTask";
/**
* 分块任务
*/
declare class ChunkTask extends BaseTask {
private _blocks;
private _blockSize;
private _chunkSize;
/**
* 构造函数
* @param file
* @param blockSize 块大小
* @param chunkSize 片大小
*/
constructor(file: File, blockSize: number, chunkSi... | rt: number, end: number, data: Blob, block: Block);
/**
* 返回chunk所属的Block对象
* @returns {Block}
*/
readonly block: Block;
/**
* 返回字节起始位置
* @returns {number}
*/
readonly start: number;
/**
* 返回字节结束位置
* @returns {number}
*/
readonly end: number;
/**
... | r(sta | identifier_name |
neuroml_via_neurounits_neuron.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Copyright (c) 2012 Michael Hull.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are m... |
NEURONEnvironment.channels.register_plugin(NeuroML_Via_NeuroUnits_Channel, NeuroML_Via_NeuroUnits_ChannelNEURON)
| def __init__(self, xml_filename, chlname=None,**kwargs):
(eqnset, chlinfo, default_params) = ChannelMLReader.BuildEqnset(xml_filename)
default_params = dict([(k, v.as_quantities_quantity()) for (k, v) in default_params.iteritems()])
super(NeuroML_Via_NeuroUnits_ChannelNEURON,self).__init__(eq... | identifier_body |
neuroml_via_neurounits_neuron.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Copyright (c) 2012 Michael Hull.
# All rights reserved. | # modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright
# notice, this list of condit... | #
# Redistribution and use in source and binary forms, with or without | random_line_split |
neuroml_via_neurounits_neuron.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Copyright (c) 2012 Michael Hull.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are m... | (Neuron_NeuroUnitEqnsetMechanism, NeuroML_Via_NeuroUnits_Channel):
def __init__(self, xml_filename, chlname=None,**kwargs):
(eqnset, chlinfo, default_params) = ChannelMLReader.BuildEqnset(xml_filename)
default_params = dict([(k, v.as_quantities_quantity()) for (k, v) in default_params.iteritems()... | NeuroML_Via_NeuroUnits_ChannelNEURON | identifier_name |
process_warnings.py | """
Script to process pytest warnings output by pytest-json-report plugin and output it as a html
"""
from __future__ import absolute_import
from __future__ import print_function
import json
import os
import io
import re
import argparse
from collections import Counter
import pandas as pd
from write_to_html import (
... | group_in_category, "high_location", "num"
)
for (
location,
group_in_location,
location_count,
) in locations_sorted_by_count:
# xss-lint: disable=python-wrap-html
html = u'<span class="c... | """
converts from panda dataframe to our html
"""
html_path = os.path.expanduser(html_path)
if "/" in html_path:
location_of_last_dir = html_path.rfind("/")
dir_path = html_path[:location_of_last_dir]
os.makedirs(dir_path, exist_ok=True)
with io.open(html_path, "w") as fout:
... | identifier_body |
process_warnings.py | """
Script to process pytest warnings output by pytest-json-report plugin and output it as a html
"""
from __future__ import absolute_import
from __future__ import print_function
import json
import os
import io
import re
import argparse
from collections import Counter
import pandas as pd
from write_to_html import (
... |
# go through each warning file and aggregate warnings into warnings_data
warnings_data = []
for temp_file in warnings_files:
with io.open(os.path.expanduser(dir_path + "/" + temp_file), "r") as read_file:
json_input = json.load(read_file)
if "warnings" in json_input:
... | if re.search(warnings_file_name_regex, temp_file) is not None:
warnings_files.append(temp_file) | conditional_block |
process_warnings.py | """
Script to process pytest warnings output by pytest-json-report plugin and output it as a html
"""
from __future__ import absolute_import
from __future__ import print_function
import json
import os
import io
import re
import argparse
from collections import Counter
import pandas as pd
from write_to_html import (
... | (warnings_dataframe, html_path):
"""
converts from panda dataframe to our html
"""
html_path = os.path.expanduser(html_path)
if "/" in html_path:
location_of_last_dir = html_path.rfind("/")
dir_path = html_path[:location_of_last_dir]
os.makedirs(dir_path, exist_ok=True)
w... | write_html_report | identifier_name |
process_warnings.py | """
Script to process pytest warnings output by pytest-json-report plugin and output it as a html
"""
from __future__ import absolute_import
from __future__ import print_function
import json
import os
import io
import re
import argparse
from collections import Counter
import pandas as pd
from write_to_html import (
... | def read_warning_data(dir_path):
"""
During test runs in jenkins, multiple warning json files are output. This function finds all files
and aggregates the warnings in to one large list
"""
# pdb.set_trace()
dir_path = os.path.expanduser(dir_path)
# find all files that exist in given director... | random_line_split | |
dict.js | var oper = {
width : 400,
height : 500,
form : document.form1,
jqgrid : function() {
var fields = $("form").serializeArray();
var jsonData = {};
jQuery.each( fields, function(i, field){
jsonData[field.name]=field.value;
});
$('#jqGrid').jqGrid('setGr... | {label: "类型",name: 'type',width: 120,sortable:true},
{label: "备注",name: 'remark',width: 120,sortable:true},
{label: "是否启用",name: 'enable',width: 120,sortable:true,hidden:true},
{label : "更新时间",name: 'updateTime',width: 240},
{label : "更新人",name: 'updateName',w... | datatype: "json",
colModel: [
{label: "id",name: 'id',width: 75,hidden:true,key:true},
{label: "名称",name: 'name',width: 120,sortable:true}, | random_line_split |
dict.js | var oper = {
width : 400,
height : 500,
form : document.form1,
jqgrid : function() {
var fields = $("form").serializeArray();
var jsonData = {};
jQuery.each( fields, function(i, field){
jsonData[field.name]=field.value;
});
$('#jqGrid').jqGrid('setGr... | ar editStr = $('#jqGridEdit').html();
$('#jqGrid').jqGrid({
url:"system/dict/jqgrid",
mtype: "POST",
styleUI : 'Bootstrap',
datatype: "json",
colModel: [
{label: "id",name: 'id',width: 75,hidden:true,key:true},
{label: "名称",name: 'name',width: 120,sort... | });
});
}
};
// 初始化
jQuery(function($) {
// 加载jqgrid
v | conditional_block |
crdb_mobile.js | title_list_url: 'Title List URL',
update_frequency: 'Update Frequency',
url: 'Connect',
user_documentation: 'User Documentation',
vendor: 'Vendor'
},
// Override display fields - if you want to show different fields in your mobile site than in your
// main site, you... | // Use HTML5 sessionStorage to get the current browse type and value
var resource_id = sessionStorage.resource_id;
$.getJSON( app.resource_json_url + '?resource_id=' + app.URLEncode(resource_id), function(data) {
var resource = data.resource;
content.... |
container.empty();
var loader = app.createLoader();
page.append(loader);
| random_line_split |
crdb_mobile.js | title_list_url: 'Title List URL',
update_frequency: 'Update Frequency',
url: 'Connect',
user_documentation: 'User Documentation',
vendor: 'Vendor'
},
// Override display fields - if you want to show different fields in your mobile site than in your
// main site, you... |
},
fullDisplayFieldURL: function(content, field_name, value, resource) {
if ( typeof(value) != 'undefined' && value != null ) {
content.append( this.getGotoURL(resource.id).attr('data-role', 'button').text('Connect') );
}
},
fullDisplayFieldGroupRecords: function(content, ... | {
content.append( $('<h3>').text( this.getDisplayFieldLabel(field_name) ) );
content.append( $('<div>').attr('class', 'resource-data').attr('id', 'resource-data-' + field_name).text( value ? 'yes' : 'no' ) );
} | conditional_block |
Map.js | import EntityService from './EntityService';
import LevelService from './LevelService';
import {Point} from 'pixi.js';
import {centeredToTopLeft} from '../../utils/coordinate';
// coordinate system:
// top-left origin
//
// 0---x+
// |
// y
// +
const WIDTH = 1000;
const HEIGHT = 1000;
export default class ... | (entities) {
this.blips = [];
entities.forEach(entity => {
let size = entity.getSize();
size = this.sizeScaledToCanvas(size);
let position = entity.getPosition();
position = this.positionScaledToCanvas(position);
position = centeredToTopLeft(position.x, position.y, WIDTH, HEIGHT);... | update | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.