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 |
|---|---|---|---|---|
ConciseIssuesListHeader.tsx | * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be... | /*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
* | random_line_split | |
utils.py | # -*- coding: utf-8 -*-
#
# This file is part of REANA.
# Copyright (C) 2021, 2022 CERN.
#
# REANA is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""REANA client validation utilities."""
import sys
from typing import Dict, NoReturn, ... |
def validate_workflow_name_parameter(
ctx: click.core.Context, _: click.core.Option, workflow_name: str
) -> Union[str, NoReturn]:
"""Validate workflow name parameter."""
try:
return validate_workflow_name(workflow_name)
except ValueError as e:
display_message(str(e), msg_type="error")
... | msg_type="error",
)
del live_parameters[parameter]
return live_parameters
| random_line_split |
utils.py | # -*- coding: utf-8 -*-
#
# This file is part of REANA.
# Copyright (C) 2021, 2022 CERN.
#
# REANA is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""REANA client validation utilities."""
import sys
from typing import Dict, NoReturn, ... | (live_parameters, original_parameters):
"""Return validated input parameters."""
parsed_input_parameters = dict(live_parameters)
for parameter in parsed_input_parameters.keys():
if parameter not in original_parameters:
display_message(
"Given parameter - {0}, is not in re... | validate_input_parameters | identifier_name |
utils.py | # -*- coding: utf-8 -*-
#
# This file is part of REANA.
# Copyright (C) 2021, 2022 CERN.
#
# REANA is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""REANA client validation utilities."""
import sys
from typing import Dict, NoReturn, ... |
return live_parameters
def validate_workflow_name_parameter(
ctx: click.core.Context, _: click.core.Option, workflow_name: str
) -> Union[str, NoReturn]:
"""Validate workflow name parameter."""
try:
return validate_workflow_name(workflow_name)
except ValueError as e:
display_messa... | if parameter not in original_parameters:
display_message(
"Given parameter - {0}, is not in reana.yaml".format(parameter),
msg_type="error",
)
del live_parameters[parameter] | conditional_block |
utils.py | # -*- coding: utf-8 -*-
#
# This file is part of REANA.
# Copyright (C) 2021, 2022 CERN.
#
# REANA is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""REANA client validation utilities."""
import sys
from typing import Dict, NoReturn, ... |
def validate_workflow_name_parameter(
ctx: click.core.Context, _: click.core.Option, workflow_name: str
) -> Union[str, NoReturn]:
"""Validate workflow name parameter."""
try:
return validate_workflow_name(workflow_name)
except ValueError as e:
display_message(str(e), msg_type="error"... | """Return validated input parameters."""
parsed_input_parameters = dict(live_parameters)
for parameter in parsed_input_parameters.keys():
if parameter not in original_parameters:
display_message(
"Given parameter - {0}, is not in reana.yaml".format(parameter),
... | identifier_body |
googleaccount.py | # -*- coding: utf-8 -*-
"""
Kay authentication backend using google account.
:Copyright: (c) 2009 Accense Technology, Inc.
Takashi Matsuo <tmatsuo@candit.jp>,
All rights reserved.
:license: BSD, see LICENSE for more details.
"""
from google.appengine.ext import db
from goog... |
def create_logout_url(self, url, **kwargs):
return users.create_logout_url(url, **kwargs)
def login(self, request, user_name, password):
return
def test_login(self, client, email='', is_admin=''):
import os
os.environ['USER_EMAIL'] = email
os.environ['USER_IS_ADMIN'] = '1' if is_admin else... | return users.create_login_url(url, **kwargs) | identifier_body |
googleaccount.py | # -*- coding: utf-8 -*-
"""
Kay authentication backend using google account.
:Copyright: (c) 2009 Accense Technology, Inc.
Takashi Matsuo <tmatsuo@candit.jp>,
All rights reserved.
:license: BSD, see LICENSE for more details.
"""
from google.appengine.ext import db
from goog... | (self, client, email='', is_admin=''):
import os
os.environ['USER_EMAIL'] = email
os.environ['USER_IS_ADMIN'] = '1' if is_admin else ''
def test_logout(self, client):
import os
os.environ['USER_EMAIL'] = ''
os.environ['USER_IS_ADMIN'] = ''
| test_login | identifier_name |
googleaccount.py | # -*- coding: utf-8 -*-
"""
Kay authentication backend using google account.
:Copyright: (c) 2009 Accense Technology, Inc.
Takashi Matsuo <tmatsuo@candit.jp>,
All rights reserved.
:license: BSD, see LICENSE for more details.
"""
from google.appengine.ext import db
from goog... | import os
os.environ['USER_EMAIL'] = ''
os.environ['USER_IS_ADMIN'] = '' |
def test_logout(self, client): | random_line_split |
googleaccount.py | # -*- coding: utf-8 -*-
"""
Kay authentication backend using google account.
:Copyright: (c) 2009 Accense Technology, Inc.
Takashi Matsuo <tmatsuo@candit.jp>,
All rights reserved.
:license: BSD, see LICENSE for more details.
"""
from google.appengine.ext import db
from goog... |
if entity.email != email:
entity.email = email
update_user = True
if update_user:
entity.put()
return entity
return db.run_in_transaction(txn)
else:
return AnonymousUser()
def create_login_url(self, url, **kwargs):
return users.crea... | entity.is_admin = is_current_user_admin
update_user = True | conditional_block |
group-dates-directive.ts | import moment from 'moment';
/**
* sdGroupDates directive will group list items by a date provided as a param.
* | * <li ng-repeat="item in items" ng-model="item" sd-group-dates="updated">
*
* Params:
* @scope {object} ngModel
* @scope {string} sdGroupDates - model field to group by
*/
angular.module('superdesk.core.datetime.groupdates', []).directive('sdGroupDates', [function() {
var lastDate = null;
var COMPARE_FORM... | * Usage: | random_line_split |
group-dates-directive.ts | import moment from 'moment';
/**
* sdGroupDates directive will group list items by a date provided as a param.
*
* Usage:
* <li ng-repeat="item in items" ng-model="item" sd-group-dates="updated">
*
* Params:
* @scope {object} ngModel
* @scope {string} sdGroupDates - model field to group by
*/
angular.module('... |
};
},
};
}]);
| {
var fdate;
var fday;
if (moment().format(COMPARE_FORMAT) === date.format(COMPARE_FORMAT)) {
fday = date.format(DISPLAY_TODAY_FORMAT);
} else {
fday = date.format(DISPLAY_DAY_FORMAT);
... | conditional_block |
my_task.rs | use std::collections::VecDeque;
use std::{thread, time};
use tokio::prelude::*;
const SLEEP_MILLIS: u64 = 100;
fn poll_number() -> Async<u32> {
Async::Ready(233)
}
pub struct MyTask;
impl Future for MyTask {
type Item = ();
type Error = ();
fn poll(&mut self) -> Result<Async<()>, ()> {
match p... |
pub fn run(&mut self) {
loop {
while let Some(mut task) = self.ready_tasks.pop_front() {
match task.poll().unwrap() {
Async::Ready(_) => {}
Async::NotReady => {
self.not_ready_tasks.push_back(task);
... | {
self.not_ready_tasks.push_back(Box::new(task));
} | identifier_body |
my_task.rs | use std::collections::VecDeque;
use std::{thread, time};
use tokio::prelude::*;
const SLEEP_MILLIS: u64 = 100;
fn poll_number() -> Async<u32> {
Async::Ready(233)
}
pub struct MyTask;
impl Future for MyTask {
type Item = ();
type Error = ();
fn poll(&mut self) -> Result<Async<()>, ()> {
match p... |
self.sleep_until_tasks_are_ready();
}
}
fn sleep_until_tasks_are_ready(&mut self) {
loop {
if self.not_ready_tasks.is_empty() {
thread::sleep(time::Duration::from_millis(SLEEP_MILLIS));
} else {
while let Some(mut task) = self.... | { return; } | conditional_block |
my_task.rs | use std::collections::VecDeque;
use std::{thread, time};
use tokio::prelude::*;
const SLEEP_MILLIS: u64 = 100;
fn poll_number() -> Async<u32> {
Async::Ready(233)
}
pub struct MyTask;
impl Future for MyTask {
type Item = ();
type Error = ();
fn poll(&mut self) -> Result<Async<()>, ()> {
match p... | Async::NotReady => {
self.not_ready_tasks.push_back(task);
}
}
}
if self.not_ready_tasks.is_empty() { return; }
self.sleep_until_tasks_are_ready();
}
}
fn sleep_until_tasks_are_ready(&mut ... | loop {
while let Some(mut task) = self.ready_tasks.pop_front() {
match task.poll().unwrap() {
Async::Ready(_) => {} | random_line_split |
my_task.rs | use std::collections::VecDeque;
use std::{thread, time};
use tokio::prelude::*;
const SLEEP_MILLIS: u64 = 100;
fn poll_number() -> Async<u32> {
Async::Ready(233)
}
pub struct MyTask;
impl Future for MyTask {
type Item = ();
type Error = ();
fn poll(&mut self) -> Result<Async<()>, ()> {
match p... | (&mut self) {
loop {
if self.not_ready_tasks.is_empty() {
thread::sleep(time::Duration::from_millis(SLEEP_MILLIS));
} else {
while let Some(mut task) = self.not_ready_tasks.pop_front() {
self.ready_tasks.push_back(task);
... | sleep_until_tasks_are_ready | identifier_name |
widgets2.py | #!/usr/bin/env python
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
from calibre.gui2.complete2 import LineEdit
from calibre.gui2.widgets import ... | history.set(self.store_name, self.history)
self.update_items_cache(self.history) | history.set(self.store_name, self.history)
self.update_items_cache(self.history)
def clear_history(self):
self.history = [] | random_line_split |
widgets2.py | #!/usr/bin/env python
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
from calibre.gui2.complete2 import LineEdit
from calibre.gui2.widgets import ... | try:
self.history.remove(ct)
except ValueError:
pass
self.history.insert(0, ct)
if self.max_history_items is not None:
del self.history[self.max_history_items:]
history.set(self.store_name, self.history)
... | max_history_items = None
def __init__(self, parent=None, completer_widget=None, sort_func=lambda x:None):
LineEdit.__init__(self, parent=parent, completer_widget=completer_widget, sort_func=sort_func)
@property
def store_name(self):
return 'lineedit_history_'+self._name
def initialize... | identifier_body |
widgets2.py | #!/usr/bin/env python
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
from calibre.gui2.complete2 import LineEdit
from calibre.gui2.widgets import ... |
def clear_history(self):
self.history = []
history.set(self.store_name, self.history)
self.update_items_cache(self.history)
| try:
self.history.remove(ct)
except ValueError:
pass
self.history.insert(0, ct)
if self.max_history_items is not None:
del self.history[self.max_history_items:]
history.set(self.store_name, self.history)
self.upd... | conditional_block |
widgets2.py | #!/usr/bin/env python
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
from calibre.gui2.complete2 import LineEdit
from calibre.gui2.widgets import ... | (self):
return 'lineedit_history_'+self._name
def initialize(self, name):
self._name = name
self.history = history.get(self.store_name, [])
self.set_separator(None)
self.update_items_cache(self.history)
self.setText('')
self.editingFinished.connect(self.save_... | store_name | identifier_name |
period.py | #
# Copyright 2013 Quantopian, 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 applicable law or agreed to in wr... |
return 1.0 - math.exp(max_drawdown)
| return 0.0 | conditional_block |
period.py | #
# Copyright 2013 Quantopian, 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 applicable law or agreed to in wr... | trade_day_mask = returns.index.normalize().isin(trade_days)
mask = ((returns.index >= self.start_date) &
(returns.index <= self.end_date) & trade_day_mask)
returns = returns[mask]
return returns
def calculate_period_returns(self, returns):
period_returns = ... | else: # otherwise we're receiving an index already
returns = daily_returns
trade_days = trading.environment.trading_days | random_line_split |
period.py | #
# Copyright 2013 Quantopian, 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 applicable law or agreed to in wr... | (self):
compounded_returns = []
cur_return = 0.0
for r in self.algorithm_returns:
try:
cur_return += math.log(1.0 + r)
# this is a guard for a single day returning -100%
except ValueError:
log.debug("{cur} return, zeroing the re... | calculate_max_drawdown | identifier_name |
period.py | #
# Copyright 2013 Quantopian, 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 applicable law or agreed to in wr... | }
return {k: None if check_entry(k, v) else v
for k, v in iteritems(rval)}
def __repr__(self):
statements = []
metrics = [
"algorithm_period_returns",
"benchmark_period_returns",
"excess_return",
"num_trading_days",
... | """
Creates a dictionary representing the state of the risk report.
Returns a dict object of the form:
"""
period_label = self.end_date.strftime("%Y-%m")
rval = {
'trading_days': self.num_trading_days,
'benchmark_volatility': self.benchmark_volatility,
... | identifier_body |
eoflineRule.ts | /**
* @license
* Copyright 2013 Palantir Technologies, 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... |
return [new Lint.RuleFailure(sourceFile, length, length, Rule.FAILURE_STRING, this.ruleName, fix)];
}
}
| {
fix = Lint.Replacement.appendText(length, sourceFile.text[lines[1] - 2] === "\r" ? "\r\n" : "\n");
} | conditional_block |
eoflineRule.ts | /**
* @license | * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed ... | * Copyright 2013 Palantir Technologies, Inc.
* | random_line_split |
eoflineRule.ts | /**
* @license
* Copyright 2013 Palantir Technologies, 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... | (sourceFile: ts.SourceFile): Lint.RuleFailure[] {
const length = sourceFile.text.length;
if (length === 0 || // if the file is empty, it "ends with a newline", so don't return a failure
sourceFile.text[length - 1] === "\n") {
return [];
}
let fix: Lint.Fix | unde... | apply | identifier_name |
ThemePreview.spec.tsx | import React from 'react';
import { setupComponentForTesting } from "utils/testing";
import { ThemePreview } from './ThemePreview';
describe("Theme preview page", function() {
it('renders without crashing', () => {
const tree = setupComponentForTesting(<ThemePreview />).toJSON();
expect(tree).toMatchSna... | id: 1,
instanceName: "test",
subdomain: "test",
}]
}
}
).toJSON();
expect(tree).toMatchSnapshot();
});
}); | random_line_split | |
pulse.js | $(function() {
var widgets = [];
var currentWidget = 0;
function updateWidgets() {
$.ajax({
url: '/widgets.json',
}).success(function(result) {
widgets = result;
iterate();
}).always(function(result) {
setTimeout(updateWidgets, 2000);
});
}
updateWidgets();
functio... | () {
console.log("Currentwidget:", currentWidget)
var widget_name = widgets[currentWidget];
console.log("Name:", widget_name)
$.ajax({
url: '/widgets-' + widget_name + '.html',
}).success(function(result) {
var template = Handlebars.compile(result);
$.ajax({
url: '/widge... | iterate | identifier_name |
pulse.js | $(function() {
var widgets = [];
var currentWidget = 0;
function updateWidgets() {
$.ajax({
url: '/widgets.json',
}).success(function(result) {
widgets = result;
iterate();
}).always(function(result) {
setTimeout(updateWidgets, 2000);
});
} | console.log("Currentwidget:", currentWidget)
var widget_name = widgets[currentWidget];
console.log("Name:", widget_name)
$.ajax({
url: '/widgets-' + widget_name + '.html',
}).success(function(result) {
var template = Handlebars.compile(result);
$.ajax({
url: '/widgets-' ... | updateWidgets();
function iterate() { | random_line_split |
pulse.js | $(function() {
var widgets = [];
var currentWidget = 0;
function updateWidgets() {
$.ajax({
url: '/widgets.json',
}).success(function(result) {
widgets = result;
iterate();
}).always(function(result) {
setTimeout(updateWidgets, 2000);
});
}
updateWidgets();
functio... |
}
});
| {
currentWidget = 0;
} | conditional_block |
pulse.js | $(function() {
var widgets = [];
var currentWidget = 0;
function updateWidgets() {
$.ajax({
url: '/widgets.json',
}).success(function(result) {
widgets = result;
iterate();
}).always(function(result) {
setTimeout(updateWidgets, 2000);
});
}
updateWidgets();
functio... |
});
// setTimeout(iterate, 2000);
currentWidget += 1;
if(currentWidget >= widgets.length) {
currentWidget = 0;
}
}
});
| {
console.log("Currentwidget:", currentWidget)
var widget_name = widgets[currentWidget];
console.log("Name:", widget_name)
$.ajax({
url: '/widgets-' + widget_name + '.html',
}).success(function(result) {
var template = Handlebars.compile(result);
$.ajax({
url: '/widgets-... | identifier_body |
mod.rs | //! Bounding volumes.
#[doc(inline)]
pub use bounding_volume::bounding_volume::{HasBoundingVolume, BoundingVolume};
#[doc(inline)]
pub use bounding_volume::aabb::{AABB, aabb};
#[doc(inline)]
pub use bounding_volume::bounding_sphere::{BoundingSphere, bounding_sphere};
pub use bounding_volume::aabb_utils::{implicit_sha... | pub type BoundingSphere3<N> = BoundingSphere<Pnt3<N>>;
/// A 3D AABB.
pub type AABB3<N> = AABB<Pnt3<N>>; |
/// A 3D bounding sphere: | random_line_split |
restclient.py |
self._sock.send(b'\r\n')
self._headersSent = True
# Closes the underlying socket
def close(self):
self._sock.close()
def doDelete(self, url):
self._method = "DELETE"
self._url = url
return self
# Specifies the url for this GET request
def doGet(self, url):
self._method = "GET"
self._url = url... | self._sock.send("{0}: {1}\r\n".format(key, value).encode('ascii')) | conditional_block | |
restclient.py | if len(cTypeParts) == 2:
charsetParts = cTypeParts[1].split('=')
if len(charsetParts) != 2 or charsetParts[0].lower().strip() != 'charset':
raise ValueError("Malformed charset declaration: {0}".format(cTypeParts[1]))
charset = charsetParts[1].strip().lower()
elif cType == 'application/json': # implicit... | return self._source.recv(maxLen) | random_line_split | |
restclient.py | write data
select.select([], [self._sock], [])
self._sendHeaders()
self._sock.send("{0:x}\r\n".format(len(data)).encode('ascii'))
self._sock.send(data)
self._sock.send(b"\r\n")
self._reqBodyPos += len(data)
# Represents a HTTP response
#
# Response objects are created by Request.send().
#
# They will par... | readExactly | identifier_name | |
restclient.py | ._sock.recv(dataLen)
else:
data = self._headers
raise HttpResponseError(self._statusMsg, self._status, data)
return rc
# Get a response header (key is case insensitive)
#
# Raises a KeyError if the header wasn't found, so use the `in` operator before calling
# this method.
def getHeader(self, key):... | self.message = message
self.cause = cause | identifier_body | |
host-callback.js | /**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... | * @private
* @type {number}
*/
this.nextMessageHandle_ = 1;
this.channel_.port1.onmessage = (e) => this.onMessageReceived_(e);
}
/**
* @param {function(): undefined} callback
* @return {number} A handle that can used for cancellation.
*/
queueCallback(callback) {
// We suppo... | {
/**
* @private
* @const {!MessageChannel}
*/
this.channel_ = new MessageChannel();
/**
* @private
* @const {MessagePort}
*/
this.sendPort_ = this.channel_.port2;
/**
* @private
* @const {!Object<number, function(): undefined>}
*/
this.messages_ = ... | identifier_body |
host-callback.js | /**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... |
return getPostMessageCallbackManager.instance_;
}
/** @enum {number} */
const CallbackType = {
REQUEST_IDLE_CALLBACK: 0,
SET_TIMEOUT: 1,
POST_MESSAGE: 2,
};
/**
* HostCallback is used for tracking host callbacks, both for the schedueler
* entrypoint --- which can be a postMessage, setTimeout, or
* request... | {
getPostMessageCallbackManager.instance_ = new PostMessageCallbackMananger();
} | conditional_block |
host-callback.js | /**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... | this.callback_ = callback;
/**
* @private
* @type {CallbackType}
*/
this.callbackType_ = null;
/**
* Handle for cancellation, which is set when the callback is scheduled.
* @private
* @type {?number}
*/
this.handle_ = null;
/**
* @private
* @type {... | /** @const {function(): undefined} */ | random_line_split |
host-callback.js | /**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... | () {
if (!getPostMessageCallbackManager.instance_) {
getPostMessageCallbackManager.instance_ = new PostMessageCallbackMananger();
}
return getPostMessageCallbackManager.instance_;
}
/** @enum {number} */
const CallbackType = {
REQUEST_IDLE_CALLBACK: 0,
SET_TIMEOUT: 1,
POST_MESSAGE: 2,
};
/**
* HostCa... | getPostMessageCallbackManager | identifier_name |
connect.js | var Q = require('q');
var uuid = require('uuid');
var crypto = require('../../../../crypto/crypto');
function Connect() |
var connect = new Connect();
module.exports = connect;
Connect.prototype.init = function(letter, handler) {
console.log(letter);
var deferred = Q.defer();
var back_letter = {
signature: letter.signature,
directive: {
connect: {
init: null
}
... | {
} | identifier_body |
connect.js | var Q = require('q');
var uuid = require('uuid');
var crypto = require('../../../../crypto/crypto');
function | () {
}
var connect = new Connect();
module.exports = connect;
Connect.prototype.init = function(letter, handler) {
console.log(letter);
var deferred = Q.defer();
var back_letter = {
signature: letter.signature,
directive: {
connect: {
init: null
}
... | Connect | identifier_name |
connect.js | var Q = require('q');
var uuid = require('uuid');
var crypto = require('../../../../crypto/crypto');
function Connect() {
}
var connect = new Connect();
module.exports = connect;
Connect.prototype.init = function(letter, handler) {
console.log(letter);
var deferred = Q.defer();
var back_letter = {
... | // 使用uuid 作为密码
// let secret = uuid.v4();
let secret = '12345678';
let encryptSecret = crypto.publicEncrypt(public_str, secret);
let json = encryptSecret.toJSON();
console.log('密码为:');
console.log(secret);
// console.log(encryptSecret.toString());
letter.crypto.encryptSecret = JSON... | random_line_split | |
config.py | from keras import backend as K
class Config:
def __init__(self):
self.verbose = True
self.network = 'resnet50'
# setting for data augmentation
self.use_horizontal_flips = True
self.use_vertical_flips = True
self.rot_90 = True
# anchor box scales
self.anchor_box_scales = [1, 2, 4, 8, 16, 32, 64, ... | self.img_scaling_factor = 1.0
# number of ROIs at once
self.num_rois = 8
# stride at the RPN (this depends on the network configuration)
self.rpn_stride = 16
self.balanced_classes = False
# scaling the stdev
self.std_scaling = 4.0
self.classifier_regr_std = [8.0, 8.0, 4.0, 4.0]
# overlaps for R... | random_line_split | |
config.py | from keras import backend as K
class Config:
def __init__(self):
| self.img_scaling_factor = 1.0
# number of ROIs at once
self.num_rois = 8
# stride at the RPN (this depends on the network configuration)
self.rpn_stride = 16
self.balanced_classes = False
# scaling the stdev
self.std_scaling = 4.0
self.classifier_regr_std = [8.0, 8.0, 4.0, 4.0]
# overlaps for R... | self.verbose = True
self.network = 'resnet50'
# setting for data augmentation
self.use_horizontal_flips = True
self.use_vertical_flips = True
self.rot_90 = True
# anchor box scales
self.anchor_box_scales = [1, 2, 4, 8, 16, 32, 64, 124, 256, 512]
# anchor box ratios
self.anchor_box_ratios = [[1, 1]... | identifier_body |
config.py | from keras import backend as K
class | :
def __init__(self):
self.verbose = True
self.network = 'resnet50'
# setting for data augmentation
self.use_horizontal_flips = True
self.use_vertical_flips = True
self.rot_90 = True
# anchor box scales
self.anchor_box_scales = [1, 2, 4, 8, 16, 32, 64, 124, 256, 512]
# anchor box ratios
self.... | Config | identifier_name |
index.js | var Image = require('./image');
var imageFields = ["fieldname", "originalname", "encoding", "mimetype", "destination",
"filename", "path", "size"];
module.exports = {
create: function (req, cb) {
var newImage = new Image();
//go through array fields which are the fields that are
//given from mutler... | });
});
},
delete: function (id, cb) {
Image.remove({
_id: id
}, function(err) {
if(err) {
cb(err);
}
});
}
} | cb(err);
}
cb(null,image); | random_line_split |
index.js | var Image = require('./image');
var imageFields = ["fieldname", "originalname", "encoding", "mimetype", "destination",
"filename", "path", "size"];
module.exports = {
create: function (req, cb) {
var newImage = new Image();
//go through array fields which are the fields that are
//given from mutler... |
cb(null, image);
});
},
all: function (cb) {
Image.find(function(err, images) {
if(err) {
cb(err);
}
cb(null, images);
});
},
put: function (req, cb) {
Image.findById(req.params.id, function(err, image) {
if(err) {
... | {
var error= new Error("Image not found");
error.type="image";
error.http_code = 404;
error.arguments ={id: id};
error.message="Image not found";
cb(error);
} | conditional_block |
charity_repository_test.py | from givabit.backend.charity import Charity
from givabit.backend.errors import MissingValueException, MultipleValueException
from givabit.test_common import test_data
from givabit.test_common import test_utils
class CharityRepositoryTest(test_utils.TestCase):
def | (self):
super(CharityRepositoryTest, self).setUp()
self.all_charities = [test_data.c1, test_data.c2, test_data.c3, test_data.c4]
for charity in self.all_charities:
self.charity_repo.add_or_update_charity(charity)
def test_lists_charities(self):
self.assertSequenceEqual(s... | setUp | identifier_name |
charity_repository_test.py | from givabit.backend.charity import Charity
from givabit.backend.errors import MissingValueException, MultipleValueException
from givabit.test_common import test_data
from givabit.test_common import test_utils
class CharityRepositoryTest(test_utils.TestCase):
def setUp(self):
super(CharityRepositoryTest, ... |
def test_getting_missing_charity_by_id_throws(self):
missing_id = 0
while missing_id in map(lambda charity: charity.key().id(), self.all_charities):
missing_id += 1
with self.assertRaises(MissingValueException):
self.charity_repo.get_charity(id=missing_id)
| self.assertEquals(self.charity_repo.get_charity(id=test_data.c1.key().id()), test_data.c1) | identifier_body |
charity_repository_test.py | from givabit.backend.charity import Charity
from givabit.backend.errors import MissingValueException, MultipleValueException
from givabit.test_common import test_data
from givabit.test_common import test_utils
class CharityRepositoryTest(test_utils.TestCase):
def setUp(self):
super(CharityRepositoryTest, ... |
def test_lists_charities(self):
self.assertSequenceEqual(self.charity_repo.list_charities(), self.all_charities)
def test_gets_single_charity(self):
self.assertEqual(self.charity_repo.get_charity('Shelter'), test_data.c1)
self.assertEqual(self.charity_repo.get_charity('Oxfam'), test_d... | self.charity_repo.add_or_update_charity(charity) | conditional_block |
charity_repository_test.py | from givabit.backend.charity import Charity
from givabit.backend.errors import MissingValueException, MultipleValueException
from givabit.test_common import test_data | def setUp(self):
super(CharityRepositoryTest, self).setUp()
self.all_charities = [test_data.c1, test_data.c2, test_data.c3, test_data.c4]
for charity in self.all_charities:
self.charity_repo.add_or_update_charity(charity)
def test_lists_charities(self):
self.assertSe... | from givabit.test_common import test_utils
class CharityRepositoryTest(test_utils.TestCase): | random_line_split |
hw3_2a.py | import sympy
x1, x2 = sympy.symbols('x1 x2')
f = 100*(x2 - x1**2)**2 + (1-x1)**2
| xs = sympy.solve([df_dx1, df_dx2], [x1, x2])
H_xs = H.subs([(x1,xs[0][0]), (x2,xs[0][1])])
lambda_xs = H_xs.eigenvals()
count = 0
for i in lambda_xs.keys():
if i.evalf() <= 0:
count += 1
if count == 0:
print 'Local minima'
elif count == len(lambda_xs.keys()):
print 'Lacal maxima'
else:
print ... | df_dx1 = sympy.diff(f,x1)
df_dx2 = sympy.diff(f,x2)
H = sympy.hessian(f, (x1, x2))
| random_line_split |
hw3_2a.py | import sympy
x1, x2 = sympy.symbols('x1 x2')
f = 100*(x2 - x1**2)**2 + (1-x1)**2
df_dx1 = sympy.diff(f,x1)
df_dx2 = sympy.diff(f,x2)
H = sympy.hessian(f, (x1, x2))
xs = sympy.solve([df_dx1, df_dx2], [x1, x2])
H_xs = H.subs([(x1,xs[0][0]), (x2,xs[0][1])])
lambda_xs = H_xs.eigenvals()
count = 0
for i in lambda_xs.ke... |
elif count == len(lambda_xs.keys()):
print 'Lacal maxima'
else:
print 'Saddle point'
| print 'Local minima' | conditional_block |
mir_raw_fat_ptr.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn simple_eq<'a>(a: *const (Foo+'a), b: *const (Foo+'a)) -> bool {
let result = a == b;
result
}
fn assert_inorder<T: Copy>(a: &[T],
compare: fn(T, T) -> ComparisonResults) {
for i in 0..a.len() {
for j in 0..a.len() {
let cres = compare(a[i], a[j]);
... | {
ComparisonResults {
lt: a < b,
le: a <= b,
gt: a > b,
ge: a >= b,
eq: a == b,
ne: a != b
}
} | identifier_body |
mir_raw_fat_ptr.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | assert!(!simple_eq(&0u8 as *const _, &1u8 as *const _));
} | random_line_split | |
mir_raw_fat_ptr.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <T: Copy>(a: &[T],
compare: fn(T, T) -> ComparisonResults) {
for i in 0..a.len() {
for j in 0..a.len() {
let cres = compare(a[i], a[j]);
if i < j {
assert_eq!(cres, LT);
} else if i == j {
assert_eq!(cres, EQ);
... | assert_inorder | identifier_name |
oldest_unique.py | class Node:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
class OldestUnique:
def __init__(self): | self.uniq = {}
self.seen = set()
self.head = None
self.tail = None
def feed(self, value):
if value in self.uniq:
# unlink from list but leave in uniq dict
node = self.uniq[value]
if node.prev is not None:
node.prev.next = n... | random_line_split | |
oldest_unique.py | class Node:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
class OldestUnique:
def __init__(self):
self.uniq = {}
self.seen = set()
self.head = None
self.tail = None
def feed(self, value):
if value in self.un... |
def query(self):
if self.tail is not None:
return self.tail.value
| node = Node(value)
if self.head is None:
self.tail = node
else:
node.next = self.head
self.head.prev = node
self.head = node
self.uniq[value] = node
self.seen.add(value) | conditional_block |
oldest_unique.py | class Node:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
class OldestUnique:
def __init__(self):
self.uniq = {}
self.seen = set()
self.head = None
self.tail = None
def feed(self, value):
if value in self.un... | if self.tail is not None:
return self.tail.value | identifier_body | |
oldest_unique.py | class Node:
def | (self, value):
self.value = value
self.next = None
self.prev = None
class OldestUnique:
def __init__(self):
self.uniq = {}
self.seen = set()
self.head = None
self.tail = None
def feed(self, value):
if value in self.uniq:
# unlink fro... | __init__ | identifier_name |
test_cloud_init.py | import json
import pytest
from mock.mock import Mock
from insights.core import filters
from insights.core.dr import SkipComponent
from insights.core.spec_factory import DatasourceProvider
from insights.specs import Specs
from insights.specs.datasources.cloud_init import cloud_cfg, LocalSpecs
CLOUD_CFG = """
users:
... | cloud_init_file = Mock()
cloud_init_file.content = CLOUD_CFG_BAD.splitlines()
broker = {LocalSpecs.cloud_cfg_input: cloud_init_file}
with pytest.raises(SkipComponent) as e:
cloud_cfg(broker)
assert 'Invalid YAML format' in str(e)
cloud_init_file.content = CLOUD_CFG_BAD_INDENT.splitlines()
... | identifier_body | |
test_cloud_init.py | import json
import pytest
from mock.mock import Mock
from insights.core import filters
from insights.core.dr import SkipComponent
from insights.core.spec_factory import DatasourceProvider
from insights.specs import Specs
from insights.specs.datasources.cloud_init import cloud_cfg, LocalSpecs
CLOUD_CFG = """
users:
... | (func):
if Specs.cloud_cfg in filters._CACHE:
del filters._CACHE[Specs.cloud_cfg]
if Specs.cloud_cfg in filters.FILTERS:
del filters.FILTERS[Specs.cloud_cfg]
if func is test_cloud_cfg:
filters.add_filter(Specs.cloud_cfg, ['ssh_deletekeys', 'network', 'debug'])
if func is test_cl... | setup_function | identifier_name |
test_cloud_init.py | import json
import pytest
from mock.mock import Mock
from insights.core import filters
from insights.core.dr import SkipComponent
from insights.core.spec_factory import DatasourceProvider
from insights.specs import Specs
from insights.specs.datasources.cloud_init import cloud_cfg, LocalSpecs
CLOUD_CFG = """
users:
... |
ssh_deletekeys: 1
network:
config: disabled
system_info:
default_user:
name: user2
plain_text_passwd: 'someP@assword'
home: /home/user2
""".strip()
CLOUD_CFG_BAD = """
users
name -demo
ssh-authorized-keys
- key_one
- key_two
""".strip()
CLOUD_CFG_JSON = {
"network": {
... | random_line_split | |
test_cloud_init.py | import json
import pytest
from mock.mock import Mock
from insights.core import filters
from insights.core.dr import SkipComponent
from insights.core.spec_factory import DatasourceProvider
from insights.specs import Specs
from insights.specs.datasources.cloud_init import cloud_cfg, LocalSpecs
CLOUD_CFG = """
users:
... |
if Specs.cloud_cfg in filters.FILTERS:
del filters.FILTERS[Specs.cloud_cfg]
if func is test_cloud_cfg:
filters.add_filter(Specs.cloud_cfg, ['ssh_deletekeys', 'network', 'debug'])
if func is test_cloud_cfg_no_filter:
filters.add_filter(Specs.cloud_cfg, [])
elif func is test_clou... | del filters._CACHE[Specs.cloud_cfg] | conditional_block |
lectures_participation.js | // Módulo respnsável pela criação do gráfico Stacked Area do relatório
// de participação dos alunos nas aulas da disciplina
var LectureParticipationGraph = function () {
var chart;
// Definição do gráfico
var options ={
chart: {
renderTo: '',
type: 'area',
style: { lineHeight: 'normal' }
... | name: 'Quantidade de Respostas às Postagens'
}]
}
return {
// Carregamento do gráfico
load: function (graphView) {
// Inicializa o form com o gráfico correspondente
var graph = graphView.form.plotGraphForm(graphView.chart.renderTo);
// Passa a função de carregamento do gráfico ... | name: 'Quantidade de Postagens',
}, {
name: 'Quantidade de Respostas aos Pedidos de Ajuda',
}, { | random_line_split |
core.py | unit has failed."""
class ExperimentUnitNotCompletedError(ExperimentUnitError):
"""Experiment unit is neither running nor completed.
For example it may be stopped by a user.
"""
class NotFoundError(KeyError):
"""Experiment/Work Unit/etc. has not been found."""
def _work_unit_arguments(
job: job_bloc... | (self,
job: job_blocks.JobType,
args: Optional[Mapping[str, Any]] = None) -> Awaitable[None]:
# pyformat: disable
"""Adds a Job / JobGroup to the experiment unit.
Only one JobGroup can be added to an ExperimentUnit. This limitation may be
lifted in future versions.
Args:
... | add | identifier_name |
core.py |
import abc
import asyncio
from concurrent import futures
import enum
import getpass
import inspect
import queue
import threading
from typing import Any, Awaitable, Callable, Collection, Dict, List, Mapping, Optional, Sequence, overload
import attr
from xmanager.xm import async_packager
from xmanager.xm import id_pred... | """ | random_line_split | |
core.py |
job.env_vars.update(args.get('env_vars', {}))
def _apply_args_to_job_group(job_group: job_blocks.JobGroup,
args: Mapping[str, Any]) -> None:
"""Recursively overrides job group properties."""
if args:
_check_if_unsupported_args_are_present(args, job_group.jobs.keys(),
... | job.args = job_blocks.merge_args(job.args, args['args']) | conditional_block | |
core.py | neither running nor completed.
For example it may be stopped by a user.
"""
class NotFoundError(KeyError):
"""Experiment/Work Unit/etc. has not been found."""
def _work_unit_arguments(
job: job_blocks.JobType,
args: Optional[Mapping[str, Any]],
) -> Mapping[str, Any]:
"""Constructs work unit argum... | """An experiment unit with this role is a work unit.
Work units contain jobs that are often run as trials as part of an
experiment's hyper-parameter search. The status of a work unit is used to
determine the status of the experiment.
""" | identifier_body | |
main.rs | #![feature(proc_macro_hygiene, decl_macro)]
extern crate rand;
#[macro_use]
extern crate rocket;
extern crate rocket_contrib;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate serde_derive;
use diesel::prelude::*;
use diesel::result::Error;
use rand::Rng;
use rocket_contrib::json::Json;
use rocket_contrib::... |
#[get("/updates?<q>")]
fn updates(conn: db::DbConn, q: u16) -> Json<Vec<models::World>> {
use schema::world::dsl::*;
let q = if q == 0 {
1
} else if q > 500 {
500
} else {
q
};
let mut results = Vec::with_capacity(q as usize);
for _ in 0..q {
let mut resu... | {
updates(conn, 1)
} | identifier_body |
main.rs | #![feature(proc_macro_hygiene, decl_macro)]
extern crate rand;
#[macro_use]
extern crate rocket;
extern crate rocket_contrib;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate serde_derive;
use diesel::prelude::*;
use diesel::result::Error;
use rand::Rng;
use rocket_contrib::json::Json;
use rocket_contrib::... | (conn: db::DbConn) -> Template {
use schema::fortune::dsl::*;
let mut context = fortune
.load::<models::Fortune>(&*conn)
.expect("error loading fortunes");
context.push(models::Fortune {
id: 0,
message: "Additional fortune added at request time.".to_string(),
});
c... | fortunes | identifier_name |
main.rs | #![feature(proc_macro_hygiene, decl_macro)]
extern crate rand;
#[macro_use]
extern crate rocket;
extern crate rocket_contrib;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate serde_derive;
use diesel::prelude::*;
use diesel::result::Error;
use rand::Rng;
use rocket_contrib::json::Json;
use rocket_contrib::... | let mut result = world
.filter(id.eq(random_number()))
.first::<models::World>(&*conn)
.expect("error loading world");
result.randomNumber = random_number();
results.push(result);
}
let _ = conn.transaction::<(), Error, _>(|| {
for w in &resul... |
let mut results = Vec::with_capacity(q as usize);
for _ in 0..q { | random_line_split |
main.rs | #![feature(proc_macro_hygiene, decl_macro)]
extern crate rand;
#[macro_use]
extern crate rocket;
extern crate rocket_contrib;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate serde_derive;
use diesel::prelude::*;
use diesel::result::Error;
use rand::Rng;
use rocket_contrib::json::Json;
use rocket_contrib::... | ;
let mut results = Vec::with_capacity(q as usize);
for _ in 0..q {
let result = world
.filter(id.eq(random_number()))
.first::<models::World>(&*conn)
.expect("error loading world");
results.push(result);
}
Json(results)
}
#[get("/fortunes")]
fn fo... | {
q
} | conditional_block |
errors.js | class RecoverableError extends Error {
| (...args) {
super(...args);
this.name = this.constructor.name;
}
}
class UnrecoverableError extends Error {
constructor(...args) {
super(...args);
this.name = this.constructor.name;
this.unrecoverable = true;
}
}
class SharpError extends UnrecoverableError {}
class ... | constructor | identifier_name |
errors.js | class RecoverableError extends Error {
constructor(...args) {
super(...args);
this.name = this.constructor.name;
}
}
class UnrecoverableError extends Error {
constructor(...args) {
super(...args);
this.name = this.constructor.name;
this.unrecoverable = true;
}
}
... |
}
module.exports = {
SharpError,
InvalidContentTypeError,
InvalidHttpResponseError,
RedisError,
LockExistsError,
InvalidUrl,
HttpRequestError,
InvalidTask,
};
| {
super(message);
this.name = this.constructor.name;
this.code = 'ELOCKEXISTS';
} | identifier_body |
errors.js | class RecoverableError extends Error {
constructor(...args) {
super(...args); |
class UnrecoverableError extends Error {
constructor(...args) {
super(...args);
this.name = this.constructor.name;
this.unrecoverable = true;
}
}
class SharpError extends UnrecoverableError {}
class InvalidContentTypeError extends UnrecoverableError {}
class InvalidHttpResponseError ex... | this.name = this.constructor.name;
}
} | random_line_split |
domtokenlist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrHelpers};
use dom::bindings::codegen::Bindings::DOMTokenListBinding;
use dom::bindings::... | }
}
}
}
| {
let element = self.element.root();
let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
let token = try!(self.check_token_exceptions(token.as_slice()));
match atoms.iter().position(|atom| *atom == token) {
Some(index) => match force {
Some(... | identifier_body |
domtokenlist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrHelpers};
use dom::bindings::codegen::Bindings::DOMTokenListBinding;
use dom::bindings::... | (element: JSRef<Element>, local_name: Atom) -> DOMTokenList {
DOMTokenList {
reflector_: Reflector::new(),
element: JS::from_rooted(element),
local_name: local_name,
}
}
pub fn new(element: JSRef<Element>, local_name: &Atom) -> Temporary<DOMTokenList> {
... | new_inherited | identifier_name |
domtokenlist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrHelpers};
use dom::bindings::codegen::Bindings::DOMTokenListBinding;
use dom::bindings::... | slice => Ok(Atom::from_slice(slice))
}
}
}
// http://dom.spec.whatwg.org/#domtokenlist
impl<'a> DOMTokenListMethods for JSRef<'a, DOMTokenList> {
// http://dom.spec.whatwg.org/#dom-domtokenlist-length
fn Length(self) -> u32 {
self.attribute().root().map(|attr| {
attr... | "" => Err(Syntax),
slice if slice.find(HTML_SPACE_CHARACTERS).is_some() => Err(InvalidCharacter), | random_line_split |
x86_64.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
},
target_triple: match target_os {
session::os_macos => ~"x86_64-apple-darwin",
session::os_win32 => ~"x86_64-pc-mingw32",
session::os_linux => ~"x86_64-unknown-linux-gnu",
session::os_android => ~"x86_64-unknown-android-gnu",
session::os_freebsd => ~... | {
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64-S128"
} | conditional_block |
x86_64.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | session::os_linux => {
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64-S128"
}
session::os_android => {
~"e-p:64:64:64-i1:8:8-i8:... | {
return target_strs::t {
module_asm: ~"",
meta_sect_name: meta_section_name(sess_os_to_meta_os(target_os)),
data_layout: match target_os {
session::os_macos => {
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:6... | identifier_body |
x86_64.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
session::os_win32 => {
// FIXME: Test this. Copied from linux (#2398)
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64-S128"
}
s... | session::os_macos => {
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64"
} | random_line_split |
x86_64.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (target_os: session::os) -> target_strs::t {
return target_strs::t {
module_asm: ~"",
meta_sect_name: meta_section_name(sess_os_to_meta_os(target_os)),
data_layout: match target_os {
session::os_macos => {
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
... | get_target_strs | identifier_name |
csvCreator.d.ts | // Type definitions for ag-grid v15.0.0
// Project: http://www.ag-grid.com/
// Definitions by: Niall Crosby <https://github.com/ag-grid/>
import { GridSerializer, RowAccumulator, BaseGridSerializingSession, RowSpanningAccumulator, GridSerializingSession } from "./gridSerializer";
import { Downloader } from "./downloade... | extends BaseGridSerializingSession<string> {
private suppressQuotes;
private columnSeparator;
private result;
private lineOpened;
constructor(columnController: ColumnController, valueService: ValueService, gridOptionsWrapper: GridOptionsWrapper, processCellCallback: (params: ProcessCellForExportPar... | CsvSerializingSession | identifier_name |
csvCreator.d.ts | // Type definitions for ag-grid v15.0.0 | import { GridSerializer, RowAccumulator, BaseGridSerializingSession, RowSpanningAccumulator, GridSerializingSession } from "./gridSerializer";
import { Downloader } from "./downloader";
import { Column } from "./entities/column";
import { ColumnController } from "./columnController/columnController";
import { ValueServ... | // Project: http://www.ag-grid.com/
// Definitions by: Niall Crosby <https://github.com/ag-grid/> | random_line_split |
main.js | /* eslint-disable no-undef */
/* eslint-disable no-unused-vars */
const documents = {
indexList: []
};
const elements = {
indexInput: null,
indexTable: null
};
function isCorrect(index) {
return index.length === 6;
}
function addIndex(index) {
documents.indexList.push(index);
elements.indexTable.append(... | }
nw.Window.open('modules/f20-print/html/print.html', { 'show': false }, (win) => {
win.maximize();
// data is the list
win.window.data = documents.indexList;
});
}
function initModule() {
elements.indexInput = $('#indexInput');
elements.indexInput.mask('999999');
elements.indexTable = $('#inde... | const toPush = '';
if (documents.indexList.length % 6 !== 0) {
while (documents.indexList.length % 6 !== 0) {
documents.indexList.push(toPush);
} | random_line_split |
main.js | /* eslint-disable no-undef */
/* eslint-disable no-unused-vars */
const documents = {
indexList: []
};
const elements = {
indexInput: null,
indexTable: null
};
function | (index) {
return index.length === 6;
}
function addIndex(index) {
documents.indexList.push(index);
elements.indexTable.append('<tr><td>' + index + '</td></tr>');
}
function sendToPrint() {
const toPush = '';
if (documents.indexList.length % 6 !== 0) {
while (documents.indexList.length % 6 !== 0) {
... | isCorrect | identifier_name |
main.js | /* eslint-disable no-undef */
/* eslint-disable no-unused-vars */
const documents = {
indexList: []
};
const elements = {
indexInput: null,
indexTable: null
};
function isCorrect(index) {
return index.length === 6;
}
function addIndex(index) {
documents.indexList.push(index);
elements.indexTable.append(... |
elements.indexInput.focus();
});
$('#printIndexesButton').button().click((event) => {
sendToPrint();
});
} | {
alert(global.strings.f20_print.badFormat);
} | conditional_block |
main.js | /* eslint-disable no-undef */
/* eslint-disable no-unused-vars */
const documents = {
indexList: []
};
const elements = {
indexInput: null,
indexTable: null
};
function isCorrect(index) {
return index.length === 6;
}
function addIndex(index) {
documents.indexList.push(index);
elements.indexTable.append(... |
function initModule() {
elements.indexInput = $('#indexInput');
elements.indexInput.mask('999999');
elements.indexTable = $('#indexTable');
$('#addIndexButton').button().click((event) => {
const index = elements.indexInput.val();
if (isCorrect(index)) {
addIndex(index);
} else {
alert(... | {
const toPush = '';
if (documents.indexList.length % 6 !== 0) {
while (documents.indexList.length % 6 !== 0) {
documents.indexList.push(toPush);
}
}
nw.Window.open('modules/f20-print/html/print.html', { 'show': false }, (win) => {
win.maximize();
// data is the list
win.window.data = ... | identifier_body |
backwards_compatibility.py | # Copyright 2016 Cisco Systems, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... |
def get_novaclient_images(nclient):
return nclient.images
if NEUTRON_VERSION >= NEUTRON_PIKE_VERSION:
from neutron.conf.agent import common as config
else:
from neutron.agent.common import config # noqa
core_opts = base_config.core_opts
# Bring in the union of all constants in neutron.common.c... | return context | identifier_body |
backwards_compatibility.py | # Copyright 2016 Cisco Systems, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | #
# In the plugin code, replace the following imports:
# from neutron.common import constants
# from neutron_lib import constants
# with (something like this):
# from networking_cisco import backward_compatibility as bc
# Then constants are referenced as shown in this example:
# port['devide_owner'] = b... |
# Bring in the union of all constants in neutron.common.constants
# and neutron_lib.constants. Handle any duplicates by using the
# values in neutron_lib. | random_line_split |
backwards_compatibility.py | # Copyright 2016 Cisco Systems, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | ():
return context.Context()
def get_db_ref(context):
return context
def get_tunnel_session(context):
return context.session
def get_novaclient_images(nclient):
return nclient.glance
else:
from neutron.api import extensions # noqa
from neutron.common import utils ... | get_context | identifier_name |
backwards_compatibility.py | # Copyright 2016 Cisco Systems, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | HasProject = models_v2.HasTenant
setattr(constants, 'L3', getattr(svc_constants, 'L3_ROUTER_NAT'))
VXLAN_TUNNEL_TYPE = type_tunnel.TunnelTypeDriver
Agent = agents_db.Agent
RouterPort = l3_db.RouterPort
Router = l3_db.Router
def get_context():
return None
def get_db_ref(context)... | from neutron.api import extensions # noqa
from neutron.common import utils as common_utils # noqa
from neutron import context
from neutron.db import agents_db
from neutron.db import api as db_api
from neutron.db import l3_db
from neutron.db import model_base # noqa
from neutron.db import ... | conditional_block |
saveErrorHandler.ts | Action.ID, RevertFileAction.LABEL);
revertFileAction.setResource(resource);
return revertFileAction.run().then(() => { revertFileAction.dispose(); return true; });
}));
// Save As
actions.push(new Action('workbench.files.action.saveAs', SaveFileAsAction.LABEL, null, true, () => {
let saveAsAction... |
// Again, we have to bring the model into conflict resolution because revert() would have cleared it
model.setConflictResolutionMode();
// Restore user value
model.textEditorModel.setValue(localModelValue);
// Reload the left hand side of the diff editor to show the up to date version and in... | conditional_block | |
saveErrorHandler.ts | WithAction, Severity, CancelAction} from 'vs/platform/message/common/message';
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
import {IModeService} from 'vs/editor/common/services/modeService';
import {IModelService} from 'vs/editor/common/services/modelService';
// A handler for save... | extends DiffEditorInput {
public static ID = 'workbench.editors.files.conflictResolutionDiffEditorInput';
private model: TextFileEditorModel;
constructor(
model: TextFileEditorModel,
name: string,
description: string,
originalInput: FileOnDiskEditorInput,
modifiedInput: FileEditorInput
) {
super(nam... | ConflictResolutionDiffEditorInput | identifier_name |
saveErrorHandler.ts | WithAction, Severity, CancelAction} from 'vs/platform/message/common/message';
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
import {IModeService} from 'vs/editor/common/services/modeService';
import {IModelService} from 'vs/editor/common/services/modelService';
// A handler for save... | constructor(
@IMessageService private messageService: IMessageService,
@IEventService private eventService: IEventService,
@IInstantiationService private instantiationService: IInstantiationService
) {
this.messages = Object.create(null);
this.registerListeners();
}
private registerListeners(): void {
... | random_line_split | |
saveErrorHandler.ts | WithAction, Severity, CancelAction} from 'vs/platform/message/common/message';
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
import {IModeService} from 'vs/editor/common/services/modeService';
import {IModelService} from 'vs/editor/common/services/modelService';
// A handler for save... |
public onSaveError(error: any, model: TextFileEditorModel): void {
let message: IMessageWithAction;
const resource = model.getResource();
// Dirty write prevention
if ((<IFileOperationResult>error).fileOperationResult === FileOperationResult.FILE_MODIFIED_SINCE) {
message = this.instantiationService.crea... | {
const hideMessage = this.messages[resource.toString()];
if (hideMessage) {
hideMessage();
this.messages[resource.toString()] = void 0;
}
} | identifier_body |
admin.js | var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');
var uniqueValidator = require('mongoose-unique-validator');
var adminSchema = new Schema({
name: {type: String, required: true},
email: {type: String, required: true, uniq... | })
}
module.exports = Admin; | if (err) throw err;
callback(admins); | random_line_split |
0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-08-01 19:47
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration): | ]
operations = [
migrations.CreateModel(
name='Broadcast',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date', models.DateField(default=django.utils.timezone.now, verbose_name='broad... |
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL), | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.