file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
date.js | /*
* Javascript Humane Dates
* Copyright (c) 2008 Dean Landolt (deanlandolt.com)
* Re-write by Zach Leatherman (zachleat.com)
*
* Adopted from the John Resig's pretty.js
* at http://ejohn.org/blog/javascript-pretty-date
* and henrah's proposed modification
* at http://ejohn.org/blog/javascript-pretty-date/#comm... | [60, lang.now],
[3600, lang.minute, lang.minutes, 60], // 60 minutes, 1 minute
[86400, lang.hour, lang.hours, 3600], // 24 hours, 1 hour
[604800, lang.day, lang.days, 86400], // 7 days, 1 day
[2628000, lang.week, lang.weeks, 604800], // ~1 month, 1 week
... | months: 'Months',
year: 'Year',
years: 'Years'
},
formats = [ | random_line_split |
date.js | /*
* Javascript Humane Dates
* Copyright (c) 2008 Dean Landolt (deanlandolt.com)
* Re-write by Zach Leatherman (zachleat.com)
*
* Adopted from the John Resig's pretty.js
* at http://ejohn.org/blog/javascript-pretty-date
* and henrah's proposed modification
* at http://ejohn.org/blog/javascript-pretty-date/#comm... | (date, compareTo){
var lang = {
ago: 'Ago',
now: 'Just Now',
minute: 'Minute',
minutes: 'Minutes',
hour: 'Hour',
hours: 'Hours',
day: 'Day',
days: 'Days',
week: 'Week',
weeks: 'Weeks',
... | humaneDate | identifier_name |
date.js | /*
* Javascript Humane Dates
* Copyright (c) 2008 Dean Landolt (deanlandolt.com)
* Re-write by Zach Leatherman (zachleat.com)
*
* Adopted from the John Resig's pretty.js
* at http://ejohn.org/blog/javascript-pretty-date
* and henrah's proposed modification
* at http://ejohn.org/blog/javascript-pretty-date/#comm... |
/*
* Date Format 1.2.3
* (c) 2007-2009 Steven Levithan <stevenlevithan.com>
* MIT license
*
* Includes enhancements by Scott Trenda <scott.trenda.net>
* and Kris Kowal <cixar.com/~kris.kowal/>
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defau... | {
var date = new Date(Date.parse(obj));
return humaneDate(date);
} | identifier_body |
date.js | /*
* Javascript Humane Dates
* Copyright (c) 2008 Dean Landolt (deanlandolt.com)
* Re-write by Zach Leatherman (zachleat.com)
*
* Adopted from the John Resig's pretty.js
* at http://ejohn.org/blog/javascript-pretty-date
* and henrah's proposed modification
* at http://ejohn.org/blog/javascript-pretty-date/#comm... |
var _ = utc ? "getUTC" : "get",
d = date[_ + "Date"](),
D = date[_ + "Day"](),
m = date[_ + "Month"](),
y = date[_ + "FullYear"](),
H = date[_ + "Hours"](),
M = date[_ + "Minutes"](),
s = date[_ + "Seconds"](),
L = date[_ + "Milliseconds"](),
o = utc ? 0 : date.getTimezoneOffset(),
fla... | {
mask = mask.slice(4);
utc = true;
} | conditional_block |
dangerousStyleValue.js | /**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModu... |
}
if (!warned) {
process.env.NODE_ENV !== 'production' ? warning(false, 'a `%s` tag (owner: `%s`) was passed a numeric string value ' + 'for CSS property `%s` (value: `%s`) which will be treated ' + 'as a unitless number in a future version of React.', component._currentElement.type, ownerNam... | {
warnings[name] = true
} | conditional_block |
dangerousStyleValue.js | /**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved. | * This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule dangerousStyleValue
*/
import CSSProperty from './CSSProperty'
impor... | * | random_line_split |
dangerousStyleValue.js | /**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModu... | (name, value, component) {
// Note that we've removed escapeTextForBrowser() calls here since the
// whole string will be escaped when the attribute is injected into
// the markup. If you provide unsafe user data here they can inject
// arbitrary CSS which may be problematic (I couldn't repro this):
// https:... | dangerousStyleValue | identifier_name |
dangerousStyleValue.js | /**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModu... |
export default dangerousStyleValue
| {
// Note that we've removed escapeTextForBrowser() calls here since the
// whole string will be escaped when the attribute is injected into
// the markup. If you provide unsafe user data here they can inject
// arbitrary CSS which may be problematic (I couldn't repro this):
// https://www.owasp.org/index.php... | identifier_body |
fd-architecture.js | import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import { isBlank } from '@ember/utils';
export default Route.extend({
/**
Service that get current project contexts.
@property currentProjectContext
@type {Class}
@default service()
*/
currentProjectConte... |
});
| {
this._super(...arguments);
controller.set('routeName', this.get('routeName'));
} | identifier_body |
fd-architecture.js | import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import { isBlank } from '@ember/utils';
export default Route.extend({
/**
Service that get current project contexts.
@property currentProjectContext
@type {Class}
@default service()
*/
currentProjectConte... | (controller) {
this._super(...arguments);
controller.set('routeName', this.get('routeName'));
}
});
| setupController | identifier_name |
fd-architecture.js | import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import { isBlank } from '@ember/utils';
export default Route.extend({
/**
Service that get current project contexts.
@property currentProjectContext
@type {Class}
@default service()
*/
currentProjectConte... |
@method model
*/
model: function() {
const subsystems = this.get('subsystems');
const stage = this.get('currentProjectContext').getCurrentStage();
const adapter = this.get('store').adapterFor('application');
const data = { 'project': stage, 'moduleSettingTypes': subsystems };
return adapt... | A hook you can implement to convert the URL into the model for this route.
[More info](http://emberjs.com/api/classes/Ember.Route.html#method_model). | random_line_split |
index.d.ts | /**
* @license
* Copyright 2018 Google 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 | * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* An HttpsCallableResult wraps a single result from a functi... | *
* Unless required by applicable law or agreed to in writing, software | random_line_split |
index.d.ts | /**
* @license
* Copyright 2018 Google 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... | {
private constructor();
/**
* Gets an `HttpsCallable` instance that refers to the function with the given
* name.
*
* @param name The name of the https callable function.
* @return The `HttpsCallable` instance.
*/
httpsCallable(name: string, options?: HttpsCallableOptions): HttpsCallable;
... | FirebaseFunctions | identifier_name |
package.js | // package metadata file for Meteor.js
Package.describe({
name: 'startup-cafe',
"author": "Dragos Mateescu <dmateescu@tremend.ro>",
"licenses": [ | }
],
"scripts": {
},
"engines": {
"node": ">= 0.10.0"
},
"devDependencies": {
"grunt": "~0.4.5",
"grunt-autoprefixer": "~0.8.1",
"grunt-contrib-concat": "~0.4.0",
"grunt-contrib-jshint": "~0.10.0",
"grunt-contrib-less": "~0.11.3",
"grunt-contrib-uglify": "~0.5.0",
"grunt... | {
"type": "MIT",
"url": "http://opensource.org/licenses/MIT" | random_line_split |
conftest.py | # pylint: disable=redefined-outer-name
import os
import pytest
from pylint import checkers
from pylint.lint import PyLinter
# pylint: disable=no-name-in-module
from pylint.testutils import MinimalTestReporter
@pytest.fixture
def | (checker, register, enable, disable, reporter):
_linter = PyLinter()
_linter.set_reporter(reporter())
checkers.initialize(_linter)
if register:
register(_linter)
if checker:
_linter.register_checker(checker(_linter))
if disable:
for msg in disable:
_linter.dis... | linter | identifier_name |
conftest.py | # pylint: disable=redefined-outer-name
import os
import pytest
from pylint import checkers
from pylint.lint import PyLinter
# pylint: disable=no-name-in-module
from pylint.testutils import MinimalTestReporter
@pytest.fixture
def linter(checker, register, enable, disable, reporter):
_linter = PyLinter()
_lint... |
if enable:
for msg in enable:
_linter.enable(msg)
os.environ.pop('PYLINTRC', None)
return _linter
@pytest.fixture(scope='module')
def checker():
return None
@pytest.fixture(scope='module')
def register():
return None
@pytest.fixture(scope='module')
def enable():
return... | for msg in disable:
_linter.disable(msg) | conditional_block |
conftest.py | # pylint: disable=redefined-outer-name
import os
import pytest
from pylint import checkers
from pylint.lint import PyLinter
# pylint: disable=no-name-in-module
from pylint.testutils import MinimalTestReporter
@pytest.fixture
def linter(checker, register, enable, disable, reporter):
_linter = PyLinter()
_lint... | return MinimalTestReporter | identifier_body | |
conftest.py | # pylint: disable=redefined-outer-name
import os
import pytest
from pylint import checkers
from pylint.lint import PyLinter
# pylint: disable=no-name-in-module
from pylint.testutils import MinimalTestReporter
@pytest.fixture
def linter(checker, register, enable, disable, reporter):
_linter = PyLinter()
_lint... | return None
@pytest.fixture(scope='module')
def reporter():
return MinimalTestReporter | return None
@pytest.fixture(scope='module')
def disable(): | random_line_split |
15.2.3.12-3-28.js | /// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.2/15.2.3/15.2.3.12/15.2.3.12-3-28.js
* @description Object.isFrozen returns true when all own properties of 'O' are not writable and not configurable, and 'O' is not extensible
*/
function testcase() {
var obj = {};
... |
Object.defineProperty(obj, "foo2", {
get: get_func,
set: set_func,
configurable: false
});
Object.preventExtensions(obj);
return Object.isFrozen(obj);
}
runTestCase(testcase);
| { } | identifier_body |
15.2.3.12-3-28.js | /// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.2/15.2.3/15.2.3.12/15.2.3.12-3-28.js
* @description Object.isFrozen returns true when all own properties of 'O' are not writable and not configurable, and 'O' is not extensible
*/
function | () {
var obj = {};
Object.defineProperty(obj, "foo1", {
value: 20,
writable: false,
enumerable: false,
configurable: false
});
function get_func() {
return 10;
}
function set_func() { }
Object.define... | testcase | identifier_name |
15.2.3.12-3-28.js | /// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.2/15.2.3/15.2.3.12/15.2.3.12-3-28.js
* @description Object.isFrozen returns true when all own properties of 'O' are not writable and not configurable, and 'O' is not extensible
*/
function testcase() { |
var obj = {};
Object.defineProperty(obj, "foo1", {
value: 20,
writable: false,
enumerable: false,
configurable: false
});
function get_func() {
return 10;
}
function set_func() { }
Object.definePrope... | random_line_split | |
no-children-prop.js | /**
* @fileoverview Prevent passing of children as props
* @author Benjamin Stepp
*/
'use strict';
const docsUrl = require('../util/docsUrl');
// ------------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------... |
context.report({
node,
messageId: 'nestChildren'
});
},
CallExpression(node) {
if (!isCreateElementWithProps(node)) {
return;
}
const props = node.arguments[1].properties;
const childrenProp = props.find((prop) => prop.key && p... | {
return;
} | conditional_block |
no-children-prop.js | /**
* @fileoverview Prevent passing of children as props
* @author Benjamin Stepp
*/
'use strict';
const docsUrl = require('../util/docsUrl');
// ------------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------... | messageId: 'nestChildren'
});
},
CallExpression(node) {
if (!isCreateElementWithProps(node)) {
return;
}
const props = node.arguments[1].properties;
const childrenProp = props.find((prop) => prop.key && prop.key.name === 'children');
if (... | return;
}
context.report({
node, | random_line_split |
no-children-prop.js | /**
* @fileoverview Prevent passing of children as props
* @author Benjamin Stepp
*/
'use strict';
const docsUrl = require('../util/docsUrl');
// ------------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------... | (context) {
return {
JSXAttribute(node) {
if (node.name.name !== 'children') {
return;
}
context.report({
node,
messageId: 'nestChildren'
});
},
CallExpression(node) {
if (!isCreateElementWithProps(node)) {
return;
... | create | identifier_name |
no-children-prop.js | /**
* @fileoverview Prevent passing of children as props
* @author Benjamin Stepp
*/
'use strict';
const docsUrl = require('../util/docsUrl');
// ------------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------... |
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: 'Prevent passing of children as props.',
category: 'Best Practices',... | {
return node.callee
&& node.callee.type === 'MemberExpression'
&& node.callee.property.name === 'createElement'
&& node.arguments.length > 1
&& node.arguments[1].type === 'ObjectExpression';
} | identifier_body |
weald.js | var reposTable;
var dataTable;
var diskUsageChart;
var revisionsChart;
$(document).ready(function () {
$.ajaxSetup({ cache: false });
reposTable = $("#reposTable");
reposTable.on('init.dt', function () {
getBigRepoDetails();
drawCharts();
});
reposTable.on('xhr.dt', function () ... | ata) {
if (data == null || data == 0) return '0';
var k = 1024;
var sizes = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var i = Math.floor(Math.log(data) / Math.log(k));
return (data / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}
// http://www.mulinblog.com/a-color-palette-optim... | rmatByteSize(d | identifier_name |
weald.js | var reposTable;
var dataTable;
var diskUsageChart;
var revisionsChart;
$(document).ready(function () {
$.ajaxSetup({ cache: false });
reposTable = $("#reposTable");
reposTable.on('init.dt', function () {
getBigRepoDetails();
drawCharts();
});
reposTable.on('xhr.dt', function () ... | }
}
if (largestRevisionRepo != null) {
$('#summary-toprevisions').text(largestRevisionRepo.Name);
} else {
$('#summary-toprevisions').text("(not available)");
}
if (largestSizeRepo != null) {
$('#summary-topspace').text(largestSizeRepo.Name);
} else {
$(... | random_line_split | |
weald.js | var reposTable;
var dataTable;
var diskUsageChart;
var revisionsChart;
$(document).ready(function () {
$.ajaxSetup({ cache: false });
reposTable = $("#reposTable");
reposTable.on('init.dt', function () {
getBigRepoDetails();
drawCharts();
});
reposTable.on('xhr.dt', function () ... | jQuery.fn.dataTableExt.oApi.fnReloadAjax = function (oSettings, sNewSource, fnCallback, bStandingRedraw) {
// DataTables 1.10 compatibility - if 1.10 then `versionCheck` exists.
// 1.10's API has ajax reloading built in, so we use those abilities
// directly.
if (jQuery.fn.dataTable.versionCheck) {
... | var data = dataTable.api().data();
if (data == null) {
return;
}
var largestRevisionRepo;
var largestSizeRepo;
var highestRevision = Number.NEGATIVE_INFINITY;
var highestSize = Number.NEGATIVE_INFINITY;
var tmpRevision;
var tmpSize;
for (var i = data.length - 1; i >= 0... | identifier_body |
weald.js | var reposTable;
var dataTable;
var diskUsageChart;
var revisionsChart;
$(document).ready(function () {
$.ajaxSetup({ cache: false });
reposTable = $("#reposTable");
reposTable.on('init.dt', function () {
getBigRepoDetails();
drawCharts();
});
reposTable.on('xhr.dt', function () ... | var ctx = $("#diskUsageChart").get(0).getContext("2d");
diskUsageChart = new Chart(ctx).Pie(diskUsageChartData, {
'animation': false,
'tooltipTemplate': "<%if (label){%><%=label%> <%}%>",
});
ctx = $("#revisionChart").get(0).getContext("2d");
revisionsChart = new Chart(ctx).Doughnut... | revisionsChartData.push({
'value': revisionsSlice[j].LatestRevision,
'label': revisionsSlice[j].Name,
'color': colors[j]
});
}
| conditional_block |
fixedcouponbond_project.py | from datetime import date
from openpyxl import load_workbook
if __name__ == '__main__':
wb = load_workbook('FixedCouponBond.xlsx')
ws = wb.active
# Take the input parameters
today = ws['C2'].value.date()
# OIS Data
ois_startdate = today
ois_maturities = []
ois_mktquotes = []
for c... | ndps.append(cell[1].value)
# Bond data
nominals = []
start_dates = []
end_dates = []
cpn_frequency = []
coupons = []
recovery_rates = []
for cell in list(ws.iter_rows('E5:J19')):
nominals.append(cell[0].value)
start_dates.append(cell[1].value.date())
end... | ndps = []
ndpdates = []
for cell in list(ws.iter_rows('B6:C11')):
ndpdates.append(cell[0].value.date()) | random_line_split |
fixedcouponbond_project.py | from datetime import date
from openpyxl import load_workbook
if __name__ == '__main__':
wb = load_workbook('FixedCouponBond.xlsx')
ws = wb.active
# Take the input parameters
today = ws['C2'].value.date()
# OIS Data
ois_startdate = today
ois_maturities = []
ois_mktquotes = []
for c... |
# Bond data
nominals = []
start_dates = []
end_dates = []
cpn_frequency = []
coupons = []
recovery_rates = []
for cell in list(ws.iter_rows('E5:J19')):
nominals.append(cell[0].value)
start_dates.append(cell[1].value.date())
end_dates.append(cell[2].value.date()... | ndpdates.append(cell[0].value.date())
ndps.append(cell[1].value) | conditional_block |
conftest.py | import shutil
import tempfile
import numpy as np
import os
from os.path import getsize
import pytest
import yaml
from util import PATH_TO_TESTS, seed, dummy_predict_with_threshold
PATH_TO_ASSETS = os.path.join(PATH_TO_TESTS, 'assets')
PATH_TO_RETINA_DIR = os.path.join(PATH_TO_ASSETS, 'recordings', 'retina')
PATH_TO_R... |
@pytest.fixture()
def path_to_geometry():
return os.path.join(PATH_TO_RETINA_DIR, 'geometry.npy')
@pytest.fixture()
def path_to_sample_pipeline_folder():
return os.path.join(PATH_TO_RETINA_DIR,
'sample_pipeline_output')
@pytest.fixture()
def path_to_standardized_data():
return... | return os.path.join(PATH_TO_RETINA_DIR, 'data.bin') | identifier_body |
conftest.py | import shutil
import tempfile
import numpy as np
import os
from os.path import getsize
import pytest
import yaml
from util import PATH_TO_TESTS, seed, dummy_predict_with_threshold
PATH_TO_ASSETS = os.path.join(PATH_TO_TESTS, 'assets')
PATH_TO_RETINA_DIR = os.path.join(PATH_TO_ASSETS, 'recordings', 'retina')
PATH_TO_R... | ():
return os.path.join(PATH_TO_RETINA_DIR, 'data.bin')
@pytest.fixture()
def path_to_geometry():
return os.path.join(PATH_TO_RETINA_DIR, 'geometry.npy')
@pytest.fixture()
def path_to_sample_pipeline_folder():
return os.path.join(PATH_TO_RETINA_DIR,
'sample_pipeline_output')
@p... | path_to_data | identifier_name |
conftest.py | import shutil
import tempfile
import numpy as np
import os
from os.path import getsize
import pytest | from util import PATH_TO_TESTS, seed, dummy_predict_with_threshold
PATH_TO_ASSETS = os.path.join(PATH_TO_TESTS, 'assets')
PATH_TO_RETINA_DIR = os.path.join(PATH_TO_ASSETS, 'recordings', 'retina')
PATH_TO_RETINA_CONFIG_DIR = os.path.join(PATH_TO_RETINA_DIR, 'config')
@pytest.fixture(autouse=True)
def setup():
se... | import yaml | random_line_split |
slice_axis_python.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | # Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"... | # with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# | random_line_split |
slice_axis_python.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | """Slice input array along specific axis.
Parameters
----------
data : numpy.ndarray
The source array to be sliced.
axis : int
Axis to be sliced.
begin: int
The index to begin with in the slicing.
end: int, optional
The index indicating end of the slice.
... | identifier_body | |
slice_axis_python.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
slc = [slice(None)] * len(dshape)
slc[axis] = slice(begin, end)
return data[tuple(slc)]
| end += dshape[axis] | conditional_block |
slice_axis_python.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | (data, axis, begin, end=None):
"""Slice input array along specific axis.
Parameters
----------
data : numpy.ndarray
The source array to be sliced.
axis : int
Axis to be sliced.
begin: int
The index to begin with in the slicing.
end: int, optional
The index... | slice_axis_python | identifier_name |
models.py | # This file is part of OpenHatch.
# Copyright (C) 2010 John Stumpo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versi... |
class IrcMissionSession(models.Model):
person = models.ForeignKey('profile.Person', null=True)
nick = models.CharField(max_length=255, unique=True)
password = models.CharField(max_length=255)
| person = models.ForeignKey('profile.Person')
step = models.ForeignKey('Step')
# Current mission status (True - user have completed it, False - reseted)
is_currently_completed = models.BooleanField(default=True)
class Meta:
unique_together = ('person', 'step') | identifier_body |
models.py | # This file is part of OpenHatch.
# Copyright (C) 2010 John Stumpo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versi... | :
unique_together = ('person', 'step')
class IrcMissionSession(models.Model):
person = models.ForeignKey('profile.Person', null=True)
nick = models.CharField(max_length=255, unique=True)
password = models.CharField(max_length=255)
| Meta | identifier_name |
models.py | # This file is part of OpenHatch.
# Copyright (C) 2010 John Stumpo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versi... | from django.db import models
import mysite.search.models
class Step(models.Model):
name = models.CharField(max_length=255, unique=True)
class StepCompletion(mysite.search.models.OpenHatchModel):
person = models.ForeignKey('profile.Person')
step = models.ForeignKey('Step')
# Current mission status (T... | # You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
| random_line_split |
jobs.py | from __future__ import unicode_literals
from django.db import models
from django.utils.timezone import now, timedelta
Q = models.Q
class LogisticJob(models.Model):
LOCK_FOR = (
(60*15, '15 minutes'),
(60*30, '30 minutes'),
(60*45, '45 minutes'),
(60*60, '1 hour'),
(60*60*... | resource_limit = models.PositiveIntegerField()
lock_for = models.PositiveIntegerField(choices=LOCK_FOR, default=60*45)
locked_till = models.DateTimeField(default=now, db_index=True)
class Meta:
app_label = 'gge_proxy_manager'
def delay(self):
self.locked_till = now() + timedelta(se... | gold_limit = models.PositiveIntegerField(null=True, blank=True, default=None) | random_line_split |
jobs.py | from __future__ import unicode_literals
from django.db import models
from django.utils.timezone import now, timedelta
Q = models.Q
class LogisticJob(models.Model):
LOCK_FOR = (
(60*15, '15 minutes'),
(60*30, '30 minutes'),
(60*45, '45 minutes'),
(60*60, '1 hour'),
(60*60*... | (self):
self.locked_till = now() + timedelta(seconds=self.lock_for)
self.save()
def last_succeed(self):
from .log import LogisticLog
log = LogisticLog.objects.filter(castle=self.castle,
receiver=self.receiver,
... | delay | identifier_name |
jobs.py | from __future__ import unicode_literals
from django.db import models
from django.utils.timezone import now, timedelta
Q = models.Q
class LogisticJob(models.Model):
|
class ProductionJob(models.Model):
player = models.ForeignKey("gge_proxy_manager.Player", related_name='production_jobs')
castle = models.ForeignKey("gge_proxy_manager.Castle", related_name='production_jobs')
unit = models.ForeignKey("gge_proxy_manager.Unit")
valid_until = models.PositiveIntegerField... | LOCK_FOR = (
(60*15, '15 minutes'),
(60*30, '30 minutes'),
(60*45, '45 minutes'),
(60*60, '1 hour'),
(60*60*3, '3 hours'),
(60*60*6, '6 hours'),
(60*60*9, '9 hours'),
(60*60*12, '12 hours'),
(60*60*18, '18 hours'),
(60*60*24, '24 hours'),
... | identifier_body |
jobs.py | from __future__ import unicode_literals
from django.db import models
from django.utils.timezone import now, timedelta
Q = models.Q
class LogisticJob(models.Model):
LOCK_FOR = (
(60*15, '15 minutes'),
(60*30, '30 minutes'),
(60*45, '45 minutes'),
(60*60, '1 hour'),
(60*60*... |
return None
class ProductionJob(models.Model):
player = models.ForeignKey("gge_proxy_manager.Player", related_name='production_jobs')
castle = models.ForeignKey("gge_proxy_manager.Castle", related_name='production_jobs')
unit = models.ForeignKey("gge_proxy_manager.Unit")
valid_until = models... | return log.sent | conditional_block |
SSI.js |
var fs = require("fs");
var glob = require("glob");
var IOUtils = require("./IOUtils");
var DirectiveHandler = require("./DirectiveHandler");
var DIRECTIVE_MATCHER = /<!--#([a-z]+)([ ]+([a-z]+)="(.+?)")* -->/g;
(function() {
"use strict";
var ssi = function(inputDirectory, outputDirectory, matcher) {
this.inpu... |
},
parse: function(filename, contents, variables) {
var instance = this;
variables = variables || {};
contents = contents.replace(new RegExp(DIRECTIVE_MATCHER), function(directive, directiveName) {
var data = instance.directiveHandler.handleDirective(directive, directiveName, filename, variables);
... | {
var input = files[i];
var contents = fs.readFileSync(input, {encoding: "utf8"});
var data = this.parse(input, contents);
var output = input.replace(this.inputDirectory, this.outputDirectory);
this.ioUtils.writeFileSync(output, data.contents);
} | conditional_block |
SSI.js | var fs = require("fs");
var glob = require("glob");
var IOUtils = require("./IOUtils");
var DirectiveHandler = require("./DirectiveHandler");
var DIRECTIVE_MATCHER = /<!--#([a-z]+)([ ]+([a-z]+)="(.+?)")* -->/g;
(function() {
"use strict";
var ssi = function(inputDirectory, outputDirectory, matcher) {
this.input... |
var output = input.replace(this.inputDirectory, this.outputDirectory);
this.ioUtils.writeFileSync(output, data.contents);
}
},
parse: function(filename, contents, variables) {
var instance = this;
variables = variables || {};
contents = contents.replace(new RegExp(DIRECTIVE_MATCHER), function... | var contents = fs.readFileSync(input, {encoding: "utf8"});
var data = this.parse(input, contents); | random_line_split |
row.js | /**
* @class PrettyJSON.view.Row
* @extends Backbone.View
*
* @author #rbarriga
* @version 0.1
*
*/
PrettyTable.view.Row = Backbone.View.extend({
initialize:function(opt) {
this.el = $('<tr />');
this.counterpart = opt.counterpart; //used by comparer
this.model = opt.model;
... |
//Creating actions icons and binding to the passed in functions
if(this.next || this.previous) {
var actions = '';
if(this.previous) actions += '<a href="#" class="previous"><i class="fa fa-lg fa-chevron-left"></i>' //creating html
if(this.next) actions += '<a href=... | {
var cellCounterpart = this.counterpart === undefined ? undefined : this.counterpart.cells[0];
var opt = {counterpart: cellCounterpart, data: this.model, importantInfo: this.importantInfo};
var cell = new PrettyTable.view.Cell(opt);
this.el.append(cell.el);
this... | conditional_block |
row.js | /**
* @class PrettyJSON.view.Row
* @extends Backbone.View
*
* @author #rbarriga
* @version 0.1
*
*/
PrettyTable.view.Row = Backbone.View.extend({
initialize:function(opt) {
this.el = $('<tr />');
this.counterpart = opt.counterpart; //used by comparer
this.model = opt.model;
... | this.el.append(cell.el);
if(this.next) cell.el.find("a.next").on("click", {next: this.next, row: this, model: this.model}, function(e){
e.data.next(e.data.row, e.data.model)
})
if(this.previous) cell.el.find("a.previous").on("click", {previous: this.previo... | if(this.previous) actions += '<a href="#" class="previous"><i class="fa fa-lg fa-chevron-left"></i>' //creating html
if(this.next) actions += '<a href="#" class="next"><i class="fa fa-lg fa-chevron-right"></i></a>';
var opt = {data: actions}
var cell = new PrettyTable.vie... | random_line_split |
Event.tests.ts | /// <reference path="../../testframework/common.ts" />
/// <reference path="../../testframework/contracttesthelper.ts" />
/// <reference path="../../../JavaScriptSDK/telemetry/event.ts" />
class EventTelemetryTests extends ContractTestHelper {
constructor() {
super(() => new Microsoft.ApplicationInsights... | var telemetry = new Microsoft.ApplicationInsights.Telemetry.Event(eventName);
Assert.equal(1024, telemetry.name.length, "event name is too long");
}
});
}
}
new EventTelemetryTests().registerTests();
| eventName += char10;
}
| conditional_block |
Event.tests.ts | /// <reference path="../../testframework/common.ts" />
/// <reference path="../../testframework/contracttesthelper.ts" />
/// <reference path="../../../JavaScriptSDK/telemetry/event.ts" />
class EventTelemetryTests extends ContractTestHelper {
constructor() {
| /** Method called before the start of each test method */
public testInitialize() {
delete Microsoft.ApplicationInsights.Telemetry.Event["__extends"];
}
public registerTests() {
super.registerTests();
var name = this.name + ": ";
this.testCase({
name: name +... | super(() => new Microsoft.ApplicationInsights.Telemetry.Event("test"), "EventTelemetryTests");
}
| identifier_body |
Event.tests.ts | /// <reference path="../../testframework/common.ts" />
/// <reference path="../../testframework/contracttesthelper.ts" />
/// <reference path="../../../JavaScriptSDK/telemetry/event.ts" />
class EventTelemetryTests extends ContractTestHelper {
|
/** Method called before the start of each test method */
public testInitialize() {
delete Microsoft.ApplicationInsights.Telemetry.Event["__extends"];
}
public registerTests() {
super.registerTests();
var name = this.name + ": ";
this.testCase({
name: name ... | constructor() {
super(() => new Microsoft.ApplicationInsights.Telemetry.Event("test"), "EventTelemetryTests");
} | random_line_split |
Event.tests.ts | /// <reference path="../../testframework/common.ts" />
/// <reference path="../../testframework/contracttesthelper.ts" />
/// <reference path="../../../JavaScriptSDK/telemetry/event.ts" />
class EventTelemetryTests extends ContractTestHelper {
constructor() {
super(() => new Microsoft.ApplicationInsights... | {
super.registerTests();
var name = this.name + ": ";
this.testCase({
name: name + "Constructor initializes the name",
test: () => {
var eventName = "test";
var telemetry = new Microsoft.ApplicationInsights.Telemetry.Event(eventName);
... | gisterTests() | identifier_name |
BSA.Dialogs.js | /**
* BSA.Dialogs - Object dialog functions
*
* This object allows:
* - output ProgressBar
* - output messages
*
* JavaScript
*
* @author Sergii Beskorovainyi <bsa2657@yandex.ru>
* @license MIT <http://www.opensource.org/licenses/mit-license.php>
* @link https://github.com/bsa-git/zf-myblog/
*/
... | ей
this.createDialogContainer(params);
this.createOverlay();
// Получим содержимое для диалога
var template = this.getTemplateFor_DialogInfo(params);
var showData = this.getDataTemplateFor_DialogInfo(params);
var content = template.evaluate(showData);
... | страницу
if(params.width && params.height){
// Создадим шаблон
dialog_container = '<div id="modal-dialog-message" class="dialog-content" style="width:#{width}px;height:#{height}px"></div>';
var template = new Template(dialog_container);
var sh... | conditional_block |
BSA.Dialogs.js | /**
* BSA.Dialogs - Object dialog functions
*
* This object allows:
* - output ProgressBar
* - output messages
*
* JavaScript
*
* @author Sergii Beskorovainyi <bsa2657@yandex.ru>
* @license MIT <http://www.opensource.org/licenses/mit-license.php>
* @link https://github.com/bsa-git/zf-myblog/
*/
... | // Создадим элемент - 'iFrame'
if(params.type == 'ZendProgress'){
this.createIFrame(params);
return;
}
// Определим переодическую функцию для обновления данных
this.intervalID = window.setInterval(function() {
self.timeou... | random_line_split | |
8-functions.rs | #![allow(dead_code, unused_variables)]
fn main() {
// 8
// (http://rustbyexample.com/fn.html)
fn is_divisible_by(lhs: u32, rhs: u32) -> bool {
if rhs == 0 {
return false;
}
lhs % rhs == 0
}
fn void_return(n: u32) -> () {}
fn | (n: u32) {}
// 8.1
// (http://rustbyexample.com/fn/methods.html)
struct Point {
x: f64,
y: f64,
}
impl Point {
fn origin() -> Point { // static method
Point { x: 0.0, y: 0.0 }
}
fn new(x: f64, y: f64) -> Point { // static method
Point... | void_return2 | identifier_name |
8-functions.rs | #![allow(dead_code, unused_variables)]
fn main() {
// 8
// (http://rustbyexample.com/fn.html)
fn is_divisible_by(lhs: u32, rhs: u32) -> bool {
if rhs == 0 {
return false;
}
lhs % rhs == 0
}
fn void_return(n: u32) -> () {}
fn void_return2(n: u32) {}
// 8... | std::mem::drop(movable);
};
consume();
// error: use of moved value: `consume` [E0382]
// consume();
// 8.2.2
// (http://rustbyexample.com/fn/closures/input_parameters.html)
// FnOnce: takes captures by value (T)
fn apply<F>(f: F) where F: FnOnce() {
f()
}
// Fn... | random_line_split | |
8-functions.rs | #![allow(dead_code, unused_variables)]
fn main() {
// 8
// (http://rustbyexample.com/fn.html)
fn is_divisible_by(lhs: u32, rhs: u32) -> bool {
if rhs == 0 |
lhs % rhs == 0
}
fn void_return(n: u32) -> () {}
fn void_return2(n: u32) {}
// 8.1
// (http://rustbyexample.com/fn/methods.html)
struct Point {
x: f64,
y: f64,
}
impl Point {
fn origin() -> Point { // static method
Point { x: 0.0, y: 0.0 }
... | {
return false;
} | conditional_block |
8-functions.rs | #![allow(dead_code, unused_variables)]
fn main() {
// 8
// (http://rustbyexample.com/fn.html)
fn is_divisible_by(lhs: u32, rhs: u32) -> bool {
if rhs == 0 {
return false;
}
lhs % rhs == 0
}
fn void_return(n: u32) -> () {}
fn void_return2(n: u32) {}
// 8... |
let closure1 = |i: i32| -> i32 { i + 1 };
let closure2 = |i| i + 1;
let i = 1;
println!("function: {}", function(i));
println!("closure1: {}", closure1(i));
println!("closure2: {}", closure2(i));
let one = || 1;
println!("closure returning one: {}", one());
// 8.2.1
// (http:/... | { i + 1 } | identifier_body |
__init__.py | import logging
import datetime
import mediacloud.api
import re
from server import mc
from server.auth import is_user_logged_in
from server.util.csv import SOURCE_LIST_CSV_METADATA_PROPS
logger = logging.getLogger(__name__)
TOPIC_MEDIA_INFO_PROPS = ['media_id', 'name', 'url']
TOPIC_MEDIA_PROPS = ['story_count', 'me... | (args):
media_ids = []
if 'sources[]' in args:
src = args['sources[]']
if isinstance(src, str):
media_ids = src.split(',')
media_ids = " ".join([str(m) for m in media_ids])
src = re.sub(r'\[*\]*', '', str(src))
if len(src) == 0:
med... | _parse_media_ids | identifier_name |
__init__.py | import logging
import datetime
import mediacloud.api
import re
from server import mc
from server.auth import is_user_logged_in
from server.util.csv import SOURCE_LIST_CSV_METADATA_PROPS
logger = logging.getLogger(__name__)
TOPIC_MEDIA_INFO_PROPS = ['media_id', 'name', 'url']
TOPIC_MEDIA_PROPS = ['story_count', 'me... | query += "(*) AND ("
# add in the media sources they specified
if len(media_ids) > 0:
media_ids = media_ids.split(',') if isinstance(media_ids, str) else media_ids
query_media_ids = " ".join(map(str, media_ids))
query_media_ids = re.sub(r'\[*\]*', '', str(... | query += " AND ("
else: | random_line_split |
__init__.py | import logging
import datetime
import mediacloud.api
import re
from server import mc
from server.auth import is_user_logged_in
from server.util.csv import SOURCE_LIST_CSV_METADATA_PROPS
logger = logging.getLogger(__name__)
TOPIC_MEDIA_INFO_PROPS = ['media_id', 'name', 'url']
TOPIC_MEDIA_PROPS = ['story_count', 'me... |
def _parse_collection_ids(args):
collection_ids = []
if 'collections[]' in args:
coll = args['collections[]']
if isinstance(coll, str):
tags_ids = coll.split(',')
tags_ids = " ".join([str(m) for m in tags_ids])
coll = re.sub(r'\[*\]*', '', str(tags_ids))
... | media_ids = []
if 'sources[]' in args:
src = args['sources[]']
if isinstance(src, str):
media_ids = src.split(',')
media_ids = " ".join([str(m) for m in media_ids])
src = re.sub(r'\[*\]*', '', str(src))
if len(src) == 0:
media_ids = []
... | identifier_body |
__init__.py | import logging
import datetime
import mediacloud.api
import re
from server import mc
from server.auth import is_user_logged_in
from server.util.csv import SOURCE_LIST_CSV_METADATA_PROPS
logger = logging.getLogger(__name__)
TOPIC_MEDIA_INFO_PROPS = ['media_id', 'name', 'url']
TOPIC_MEDIA_PROPS = ['story_count', 'me... |
return media_ids
def _parse_collection_ids(args):
collection_ids = []
if 'collections[]' in args:
coll = args['collections[]']
if isinstance(coll, str):
tags_ids = coll.split(',')
tags_ids = " ".join([str(m) for m in tags_ids])
coll = re.sub(r'\[*\]*', ... | src = args['sources[]']
if isinstance(src, str):
media_ids = src.split(',')
media_ids = " ".join([str(m) for m in media_ids])
src = re.sub(r'\[*\]*', '', str(src))
if len(src) == 0:
media_ids = []
media_ids = src.split(',') if len(src) ... | conditional_block |
string.rs | use std::io;
use std::io::Write;
use std::str::from_utf8;
use dbutil::normalize_position;
use error::OperationError;
use rdbutil::constants::*;
use rdbutil::{EncodeError, encode_i64, encode_slice_u8};
#[derive(PartialEq, Debug, Clone)]
pub enum ValueString {
Integer(i64),
Data(Vec<u8>),
}
fn to_i64(newvalue:... | (&self) -> Vec<u8> {
match *self {
ValueString::Data(ref data) => data.clone(),
ValueString::Integer(ref int) => format!("{}", int).into_bytes(),
}
}
pub fn strlen(&self) -> usize {
match *self {
ValueString::Data(ref data) => data.len(),
... | to_vec | identifier_name |
string.rs | use std::io;
use std::io::Write;
use std::str::from_utf8;
use dbutil::normalize_position;
use error::OperationError;
use rdbutil::constants::*;
use rdbutil::{EncodeError, encode_i64, encode_slice_u8};
#[derive(PartialEq, Debug, Clone)]
pub enum ValueString {
Integer(i64),
Data(Vec<u8>),
}
fn to_i64(newvalue:... |
}
}
return None;
}
fn to_f64(newvalue: &Vec<u8>) -> Option<f64> {
if newvalue.len() > 0 && newvalue.len() < 32 { // ought to be enough!
if newvalue[0] as char != '0' && newvalue[0] as char != ' ' {
if let Ok(utf8) = from_utf8(&*newvalue) {
if let Ok(f) = utf8.pa... | {
if let Ok(i) = utf8.parse::<i64>() {
return Some(i);
}
} | conditional_block |
string.rs | use std::io;
use std::io::Write;
use std::str::from_utf8;
use dbutil::normalize_position;
use error::OperationError;
use rdbutil::constants::*;
use rdbutil::{EncodeError, encode_i64, encode_slice_u8};
#[derive(PartialEq, Debug, Clone)]
pub enum ValueString {
Integer(i64),
Data(Vec<u8>),
}
fn to_i64(newvalue:... |
pub fn to_vec(&self) -> Vec<u8> {
match *self {
ValueString::Data(ref data) => data.clone(),
ValueString::Integer(ref int) => format!("{}", int).into_bytes(),
}
}
pub fn strlen(&self) -> usize {
match *self {
ValueString::Data(ref data) => data.... | {
match to_i64(&newvalue) {
Some(i) => ValueString::Integer(i),
None => ValueString::Data(newvalue),
}
} | identifier_body |
string.rs | use std::io;
use std::io::Write;
use std::str::from_utf8;
use dbutil::normalize_position;
use error::OperationError;
use rdbutil::constants::*;
use rdbutil::{EncodeError, encode_i64, encode_slice_u8};
#[derive(PartialEq, Debug, Clone)]
pub enum ValueString {
Integer(i64),
Data(Vec<u8>),
}
fn to_i64(newvalue:... | #[test]
fn dump_string() {
let mut v = vec![];
ValueString::Data(b"hello world".to_vec()).dump(&mut v).unwrap();
assert_eq!(&*v, b"\x00\x0bhello world\x07\x00");
}
} | }
| random_line_split |
file_scanning.py | ## simple file type detection.
## if i had unlimited api access, i would send every single md5 to something like VirusTotal
forbidden_types = ['text/x-bash', 'text/scriptlet', 'application/x-opc+zip', 'application/com', 'application/x-msmetafile', 'application/x-shellscript', 'text/x-sh', 'text/x-csh', 'application/x-... |
for i in bparser.parseentries('files.log'):
if not i['local_orig'] or i['mime_type'] in forbidden_types: ## scan all of these types
print
print "{} downloaded a file from {} via {}".format(i['rx_hosts'],i['tx_hosts'],i['source'])
print "Filename: {} length: {} mime type: {}".format(i['filename'],i['total_byte... |
from config import *
import bparser
import notifiers | random_line_split |
file_scanning.py | ## simple file type detection.
## if i had unlimited api access, i would send every single md5 to something like VirusTotal
forbidden_types = ['text/x-bash', 'text/scriptlet', 'application/x-opc+zip', 'application/com', 'application/x-msmetafile', 'application/x-shellscript', 'text/x-sh', 'text/x-csh', 'application/x-... | if not i['local_orig'] or i['mime_type'] in forbidden_types: ## scan all of these types
print
print "{} downloaded a file from {} via {}".format(i['rx_hosts'],i['tx_hosts'],i['source'])
print "Filename: {} length: {} mime type: {}".format(i['filename'],i['total_bytes'],i['mime_type'])
print "MD5: {} SHA1: {}... | conditional_block | |
local_data_priv.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 ... |
&LocalStorage(ref mut map_ptr, ref mut at_exit) => {
assert!((*map_ptr).is_null());
let map: TaskLocalMap = @mut ~[];
*map_ptr = cast::transmute(map);
let at_exit_fn: ~fn(*libc::c_void) = |p|cleanup_task_local_map(p);
*at_exit = Some(at_exit_fn);
... | {
assert!(map_ptr.is_not_null());
let map = cast::transmute(map_ptr);
let nonmut = cast::transmute::<TaskLocalMap,
@~[Option<TaskLocalElement>]>(map);
cast::bump_box_refcount(nonmut);
return map;
} | conditional_block |
local_data_priv.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 ... | <T: 'static>(key: LocalDataKey<T>) -> *libc::c_void {
// Keys are closures, which are (fnptr,envptr) pairs. Use fnptr.
// Use reinterpret_cast -- transmute would leak (forget) the closure.
let pair: (*libc::c_void, *libc::c_void) = cast::transmute_copy(&key);
pair.first()
}
// If returning Some(..), re... | key_to_key_value | identifier_name |
local_data_priv.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 ... | assert!(!map_ptr.is_null());
// Get and keep the single reference that was created at the
// beginning.
let _map: TaskLocalMap = cast::transmute(map_ptr);
// All local_data will be destroyed along with the map.
}
}
// Gets the map from the runtime. Lazily initialises if not ... | unsafe { | random_line_split |
local_data_priv.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub unsafe fn local_set<T: 'static>(
handle: Handle, key: LocalDataKey<T>, data: @T) {
let map = get_local_map(handle);
// Store key+data as *voids. Data is invisibly referenced once; key isn't.
let keyval = key_to_key_value(key);
// We keep the data in two forms: one as an unsafe pointer, so we ... | {
local_get_helper(handle, key, false)
} | identifier_body |
test_environment.py | # Copyright 2012-2015 MongoDB, 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 writin... |
@property
def storage_engine(self):
try:
return self.server_status.get("storageEngine", {}).get("name")
except AttributeError:
# Raised if self.server_status is None.
return None
def supports_transactions(self):
if self.storage_engine == "mmapv1... | self.v8 = True | conditional_block |
test_environment.py | # Copyright 2012-2015 MongoDB, 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 writin... |
def setup_version(self):
"""Set self.version to the server's version."""
self.version = Version.from_client(self.sync_cx)
def setup_v8(self):
"""Determine if server is running SpiderMonkey or V8."""
if self.sync_cx.server_info().get("javascriptEngine") == "V8":
sel... | """Set self.auth and self.uri."""
if db_user or db_password:
if not (db_user and db_password):
sys.stderr.write("You must set both DB_USER and DB_PASSWORD, or neither\n")
sys.exit(1)
self.auth = True
uri_template = "mongodb://%s:%s@%s:%s/admin... | identifier_body |
test_environment.py | # Copyright 2012-2015 MongoDB, 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 writin... | socketTimeoutMS=socketTimeoutMS,
serverSelectionTimeoutMS=serverSelectionTimeoutMS,
)
)
response = client.admin.command("ismaster")
self.sessions_enabled = "logicalSessionTimeoutMinutes" in response
self.is_mong... | port,
username=db_user,
password=db_password,
directConnection=True,
connectTimeoutMS=connectTimeoutMS, | random_line_split |
test_environment.py | # Copyright 2012-2015 MongoDB, 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 writin... | (self, func):
"""Run a test only if the server is started with auth."""
return self.require(lambda: self.auth, "Server must be start with auth", func=func)
def require_version_min(self, *ver):
"""Run a test only if the server version is at least ``version``."""
other_version = Versi... | require_auth | identifier_name |
media-dd.js | define("device", function (a) {
var b = this, c = a.media = {};
a.media.mediamsg = {
0: "NONE ACTIVE.",
1: "ABORT_ERR.",
2: "CONNECTION ERR.",
3: "DECODE ERR.",
4: "SRC NOT SUPPORT."
};
a.MEDIA_DESTINATION = {}, a.MEDIA_ENCODEING = {}, a.MEDIA_TYPE = {}, ... | case"stop":
cloudaBLight("playAudio", a, "lightapp.device.AUDIO_TYPE.STOP", h, i);
break;
case"seekTo":
cloudaBLight("audioSeekTo", d.time, h, i);
break;
case"setVolume":
cloudaBLight("setVolume", ... | case"play":
cloudaBLight("playAudio", a, "lightapp.device.AUDIO_TYPE.PLAY", h, i);
break;
| random_line_split |
alieztv.py | import re
from os.path import splitext
from livestreamer.compat import urlparse, unquote
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http, validate
from livestreamer.stream import HTTPStream, RTMPStream
_url_re = re.compile("""
http(s)?://(\w+\.)?aliez.tv
(?:
/live/[^/]... | class Aliez(Plugin):
@classmethod
def can_handle_url(self, url):
return _url_re.match(url)
def _get_streams(self):
res = http.get(self.url, schema=_schema)
streams = {}
for url in res["urls"]:
parsed = urlparse(url)
if parsed.scheme.startswith("rtmp")... | )
| random_line_split |
alieztv.py | import re
from os.path import splitext
from livestreamer.compat import urlparse, unquote
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http, validate
from livestreamer.stream import HTTPStream, RTMPStream
_url_re = re.compile("""
http(s)?://(\w+\.)?aliez.tv
(?:
/live/[^/]... |
__plugin__ = Aliez
| @classmethod
def can_handle_url(self, url):
return _url_re.match(url)
def _get_streams(self):
res = http.get(self.url, schema=_schema)
streams = {}
for url in res["urls"]:
parsed = urlparse(url)
if parsed.scheme.startswith("rtmp"):
params ... | identifier_body |
alieztv.py | import re
from os.path import splitext
from livestreamer.compat import urlparse, unquote
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http, validate
from livestreamer.stream import HTTPStream, RTMPStream
_url_re = re.compile("""
http(s)?://(\w+\.)?aliez.tv
(?:
/live/[^/]... | (self, url):
return _url_re.match(url)
def _get_streams(self):
res = http.get(self.url, schema=_schema)
streams = {}
for url in res["urls"]:
parsed = urlparse(url)
if parsed.scheme.startswith("rtmp"):
params = {
"rtmp": url... | can_handle_url | identifier_name |
alieztv.py | import re
from os.path import splitext
from livestreamer.compat import urlparse, unquote
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http, validate
from livestreamer.stream import HTTPStream, RTMPStream
_url_re = re.compile("""
http(s)?://(\w+\.)?aliez.tv
(?:
/live/[^/]... |
stream = RTMPStream(self.session, params)
streams["live"] = stream
elif parsed.scheme.startswith("http"):
name = splitext(parsed.path)[1][1:]
stream = HTTPStream(self.session, url)
streams[name] = stream
return stream... | params["swfVfy"] = res["swf"] | conditional_block |
Gruntfile.js | /* jslint node: true */
var FILENAME = 'modules/empathy.js',
ALL_JAVASCRIPT_FILES = ['Gruntfile.js', '*/*.js',
'public/javascripts/*.js'];
module.exports = function(grunt) {
'use strict';
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
... | hooks: ['.git/hooks/pre-commit']
},
// Run shell commands
shell: {
hooks: {
// Copy the project's pre-commit hook into .git/hooks
command: 'cp git-hooks/pre-commit .git/hooks/pre-commit'
},
rmclogs: {
... | clean: {
// Clean any pre-commit hooks in .git/hooks directory | random_line_split |
sheet.js | var conf = require('../conf.js'),
log = require('../log.js');
var engine = require('engine'),
resMan = require('../resource_manager.js');
var errors = require('../errors.js');
var Bounds = require('./bounds.js');
Sheet.instances = 0;
Sheet.MISSED_SIDE = 50;
/* TODO: rename to Static and take optional functi... |
var https = engine.isHttps;
/**
* @private @method load
*/
Sheet.prototype.load = function(uid, player, callback, errback) {
callback = callback || this._callback;
if (this._image) throw errors.element('Image already loaded', uid); // just skip loading?
var me = this;
if (!me.src) {
log.error... | {
this.id = Sheet.instances++;
this.src = src;
this._dimen = /*dimen ||*/ [0, 0];
this.regions = [ [ 0, 0, 1, 1 ] ]; // for image, sheet contains just one image
this.regions_f = null;
// this.aliases = {}; // map of names to regions (or regions ranges)
/* use state property for region num? o... | identifier_body |
sheet.js | var conf = require('../conf.js'),
log = require('../log.js');
var engine = require('engine'),
resMan = require('../resource_manager.js');
var errors = require('../errors.js');
var Bounds = require('./bounds.js');
Sheet.instances = 0;
Sheet.MISSED_SIDE = 50;
/* TODO: rename to Static and take optional functi... |
var r = this.region;
return new Bounds(0, 0, r[2], r[3]);
};
/**
* @method inside
*
* Checks if point is inside the image. _Does no test for bounds_, the point is
* assumed to be already inside of the bounds, so check `image.bounds().inside(pt)`
* before calling this method manually.
*
* @param {Object}... | {
this.updateRegion();
} | conditional_block |
sheet.js | var conf = require('../conf.js'),
log = require('../log.js');
var engine = require('engine'),
resMan = require('../resource_manager.js');
var errors = require('../errors.js');
var Bounds = require('./bounds.js');
Sheet.instances = 0;
Sheet.MISSED_SIDE = 50;
/* TODO: rename to Static and take optional functi... | var region;
if (this.region_f) { region = this.region_f(this.cur_region); }
else {
var r = this.regions[this.cur_region],
d = this._dimen;
region = [ r[0] * d[0], r[1] * d[1],
r[2] * d[0], r[3] * d[1] ];
}
this.region = region;
};
/**
* @private @metho... | if (this.cur_region < 0) return; | random_line_split |
sheet.js | var conf = require('../conf.js'),
log = require('../log.js');
var engine = require('engine'),
resMan = require('../resource_manager.js');
var errors = require('../errors.js');
var Bounds = require('./bounds.js');
Sheet.instances = 0;
Sheet.MISSED_SIDE = 50;
/* TODO: rename to Static and take optional functi... | (src, callback, start_region) {
this.id = Sheet.instances++;
this.src = src;
this._dimen = /*dimen ||*/ [0, 0];
this.regions = [ [ 0, 0, 1, 1 ] ]; // for image, sheet contains just one image
this.regions_f = null;
// this.aliases = {}; // map of names to regions (or regions ranges)
/* use st... | Sheet | identifier_name |
Codec.py | __author__ = 'aniket'
import freenect
import cv2
import numpy as np
kernel = np.ones((5,5),np.uint8)
def grayscale():
maske = np.zeros((480,640,3))
a = freenect.sync_get_depth()[0]
np.clip(a, 0, 2**10 - 1, a)
a >>= 2
a = a.astype(np.uint8)
median = cv2.medianBlur(a,5)
ret,mask = cv2.thre... |
cv2.destroyAllWindows()
| break | conditional_block |
Codec.py | __author__ = 'aniket'
import freenect
import cv2
import numpy as np
kernel = np.ones((5,5),np.uint8)
def grayscale():
maske = np.zeros((480,640,3))
a = freenect.sync_get_depth()[0]
np.clip(a, 0, 2**10 - 1, a)
a >>= 2
a = a.astype(np.uint8)
median = cv2.medianBlur(a,5)
ret,mask = cv2.thre... |
while(True):
cv2.imshow('gray',grayscale())
#cv2.imshow('color',colored())
if cv2.waitKey(10) == 27:
break
cv2.destroyAllWindows()
| a = freenect.sync_get_video()[0]
return a | identifier_body |
Codec.py | __author__ = 'aniket'
import freenect
import cv2
import numpy as np
kernel = np.ones((5,5),np.uint8)
def | ():
maske = np.zeros((480,640,3))
a = freenect.sync_get_depth()[0]
np.clip(a, 0, 2**10 - 1, a)
a >>= 2
a = a.astype(np.uint8)
median = cv2.medianBlur(a,5)
ret,mask = cv2.threshold(median,254,255,cv2.THRESH_BINARY_INV)
mask = mask/255
ab = freenect.sync_get_video()[0]
ab = cv2.cvt... | grayscale | identifier_name |
Codec.py | __author__ = 'aniket'
import freenect
import cv2
import numpy as np
kernel = np.ones((5,5),np.uint8)
def grayscale():
maske = np.zeros((480,640,3))
a = freenect.sync_get_depth()[0]
np.clip(a, 0, 2**10 - 1, a)
a >>= 2
a = a.astype(np.uint8)
median = cv2.medianBlur(a,5)
ret,mask = cv2.thre... | cv2.imshow('gray',grayscale())
#cv2.imshow('color',colored())
if cv2.waitKey(10) == 27:
break
cv2.destroyAllWindows() | return a
while(True): | random_line_split |
base.js | define([
'jquery',
'../utils',
'../keys'
], function ($, Utils, KEYS) {
function BaseSelection ($element, options) |
Utils.Extend(BaseSelection, Utils.Observable);
BaseSelection.prototype.render = function () {
var $selection = $(
'<span class="select2-selection" role="combobox" ' +
' aria-haspopup="true" aria-expanded="false">' +
'</span>'
);
this._tabindex = 0;
if (Utils.GetData(this.$elem... | {
this.$element = $element;
this.options = options;
BaseSelection.__super__.constructor.call(this);
} | identifier_body |
base.js | define([
'jquery',
'../utils',
'../keys'
], function ($, Utils, KEYS) {
function BaseSelection ($element, options) {
this.$element = $element;
this.options = options;
BaseSelection.__super__.constructor.call(this);
} | BaseSelection.prototype.render = function () {
var $selection = $(
'<span class="select2-selection" role="combobox" ' +
' aria-haspopup="true" aria-expanded="false">' +
'</span>'
);
this._tabindex = 0;
if (Utils.GetData(this.$element[0], 'old-tabindex') != null) {
this._tabin... |
Utils.Extend(BaseSelection, Utils.Observable);
| random_line_split |
base.js | define([
'jquery',
'../utils',
'../keys'
], function ($, Utils, KEYS) {
function | ($element, options) {
this.$element = $element;
this.options = options;
BaseSelection.__super__.constructor.call(this);
}
Utils.Extend(BaseSelection, Utils.Observable);
BaseSelection.prototype.render = function () {
var $selection = $(
'<span class="select2-selection" role="combobox" ' +... | BaseSelection | identifier_name |
base.js | define([
'jquery',
'../utils',
'../keys'
], function ($, Utils, KEYS) {
function BaseSelection ($element, options) {
this.$element = $element;
this.options = options;
BaseSelection.__super__.constructor.call(this);
}
Utils.Extend(BaseSelection, Utils.Observable);
BaseSelection.prototype.ren... |
$selection.attr('title', this.$element.attr('title'));
$selection.attr('tabindex', this._tabindex);
this.$selection = $selection;
return $selection;
};
BaseSelection.prototype.bind = function (container, $container) {
var self = this;
var id = container.id + '-container';
var resul... | {
this._tabindex = this.$element.attr('tabindex');
} | conditional_block |
response_status.py | # coding: utf-8
"""
Wavefront REST API Documentation
<p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the W... | :type: int
"""
if self._configuration.client_side_validation and code is None:
raise ValueError("Invalid value for `code`, must not be `None`") # noqa: E501
self._code = code
@property
def message(self):
"""Gets the message of this ResponseStatus. # noqa: ... |
HTTP Response code corresponding to this response # noqa: E501
:param code: The code of this ResponseStatus. # noqa: E501 | random_line_split |
response_status.py | # coding: utf-8
"""
Wavefront REST API Documentation
<p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the W... | """NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
... | identifier_body | |
response_status.py | # coding: utf-8
"""
Wavefront REST API Documentation
<p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the W... | (self):
"""Gets the result of this ResponseStatus. # noqa: E501
:return: The result of this ResponseStatus. # noqa: E501
:rtype: str
"""
return self._result
@result.setter
def result(self, result):
"""Sets the result of this ResponseStatus.
:param r... | result | identifier_name |
response_status.py | # coding: utf-8
"""
Wavefront REST API Documentation
<p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the W... |
if issubclass(ResponseStatus, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `... | value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
... | conditional_block |
type-infer-generalize-ty-var.rs | // Copyright 2016 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 ... | (&self) -> &(MyShow + 'static) {
static x: usize = 42;
&x
}
}
impl Get<usize> for Wrap<U> {
fn get(&self) -> &usize {
static x: usize = 55;
&x
}
}
trait MyShow { fn dummy(&self) { } }
impl<'a> MyShow for &'a (MyShow + 'a) { }
impl MyShow for usize { }
fn constrain<'a>(rc: R... | get | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.