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 |
|---|---|---|---|---|
tracked_entity.ts | import DataLoader from "dataloader"
import { map, find, extend } from "lodash"
export interface TrackedEntityLoaderFactoryOptions {
/**
* The key that’s to be used for the list of IDs param that’s sent with the API request
*/
paramKey: string
/**
* The key that’s to be used for this entity, e.g. `is_fol... | return { id, [trackingKey]: false }
})
return parsedResults
})
},
{ batch: true, cache: true, maxBatchSize: batchSize }
)
return id => trackedEntityLoader.load(id)
}
export default trackedEntityLoaderFactory
| return extend(entityKeyPath ? match[entityKeyPath] : match, {
[trackingKey]: true,
})
}
| conditional_block |
tracked_entity.ts | import DataLoader from "dataloader"
import { map, find, extend } from "lodash"
export interface TrackedEntityLoaderFactoryOptions {
/**
* The key that’s to be used for the list of IDs param that’s sent with the API request
*/
paramKey: string
/**
* The key that’s to be used for this entity, e.g. `is_fol... | )
return id => trackedEntityLoader.load(id)
}
export default trackedEntityLoaderFactory | },
{ batch: true, cache: true, maxBatchSize: batchSize } | random_line_split |
tool_bar.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Create bars of buttons and other widgets
use libc::c_int;
use ffi;
use glib::{to_bo... | -> Option<Toolbar> {
let tmp_pointer = unsafe { ffi::gtk_toolbar_new() };
check_pointer!(tmp_pointer, Toolbar)
}
pub fn insert<T: ::ToolItemTrait>(&self,
item: &T,
pos: i32) -> () {
unsafe {
ffi::gtk_toolba... | w() | identifier_name |
tool_bar.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Create bars of buttons and other widgets
use libc::c_int;
use ffi;
use glib::{to_bo... | }
pub fn get_drop_index(&self, x: i32, y: i32) -> i32 {
unsafe {
ffi::gtk_toolbar_get_drop_index(GTK_TOOLBAR(self.pointer), x as c_int, y as c_int) as i32
}
}
pub fn set_drop_highlight_item<T: ::ToolItemTrait>(&self, item: &T, index: i32) -> () {
unsafe {
... | None
} else {
Some(::FFIWidget::wrap_widget(tmp_pointer))
}
} | random_line_split |
tool_bar.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Create bars of buttons and other widgets
use libc::c_int;
use ffi;
use glib::{to_bo... | lse {
Some(::FFIWidget::wrap_widget(tmp_pointer))
}
}
}
pub fn get_drop_index(&self, x: i32, y: i32) -> i32 {
unsafe {
ffi::gtk_toolbar_get_drop_index(GTK_TOOLBAR(self.pointer), x as c_int, y as c_int) as i32
}
}
pub fn set_drop_highlight... | None
} e | conditional_block |
tool_bar.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Create bars of buttons and other widgets
use libc::c_int;
use ffi;
use glib::{to_bo... | pub fn set_icon_size(&self, icon_size: IconSize) -> () {
unsafe {
ffi::gtk_toolbar_set_icon_size(GTK_TOOLBAR(self.pointer), icon_size);
}
}
pub fn unset_style(&self) -> () {
unsafe {
ffi::gtk_toolbar_unset_style(GTK_TOOLBAR(self.pointer));
}
}
}
... | unsafe {
ffi::gtk_toolbar_set_style(GTK_TOOLBAR(self.pointer), style);
}
}
| identifier_body |
e294.py | partial
import os
import __main__
from copy import deepcopy
from math import sqrt
import numpy as np
import theano.tensor as T
NAME = os.path.splitext(os.path.split(__main__.__file__)[1])[0]
PATH = "/homes/dk3810/workspace/python/neuralnilm/figures"
SAVE_PLOT_INTERVAL = 500
GRADIENT_STEPS = 100
source_dict = dict(
... | full_exp_name = NAME + experiment
func_call = init_experiment(PATH, experiment, full_exp_name)
logger = logging.getLogger(full_exp_name)
try:
net = eval(func_call)
run_experiment(net, epochs=10000)
except KeyboardInterrupt:
logger.info("KeyboardInterru... | conditional_block | |
e294.py | m.source import standardise, discretize, fdiff, power_and_fdiff
from neuralnilm.experiment import run_experiment, init_experiment
from neuralnilm.net import TrainingError
from neuralnilm.layers import MixtureDensityLayer
from neuralnilm.objectives import scaled_cost, mdn_nll
from neuralnilm.plot import MDNPlotter
from... |
N = 50
net_dict = dict(
save_plot_interval=SAVE_PLOT_INTERVAL,
loss_function=partial(scaled_cost, loss_func=mdn_nll),
# loss_function=lambda x, t: mdn_nll(x, t).mean(),
# loss_function=lambda x, t: mse(x, t).mean(),
updates_func=momentum,
learning_rate=1e-03,
learning_rate_changes_by_... | ) | random_line_split |
e294.py | m.source import standardise, discretize, fdiff, power_and_fdiff
from neuralnilm.experiment import run_experiment, init_experiment
from neuralnilm.net import TrainingError
from neuralnilm.layers import MixtureDensityLayer
from neuralnilm.objectives import scaled_cost, mdn_nll
from neuralnilm.plot import MDNPlotter
from... | (name):
# BLSTM
global source
source_dict_copy = deepcopy(source_dict)
source = RealApplianceSource(**source_dict_copy)
net_dict_copy = deepcopy(net_dict)
net_dict_copy.update(dict(
experiment_name=name,
source=source
))
N = 50
net_dict_copy['layers_config'] = [
... | exp_c | identifier_name |
e294.py | m.source import standardise, discretize, fdiff, power_and_fdiff
from neuralnilm.experiment import run_experiment, init_experiment
from neuralnilm.net import TrainingError
from neuralnilm.layers import MixtureDensityLayer
from neuralnilm.objectives import scaled_cost, mdn_nll
from neuralnilm.plot import MDNPlotter
from... | 'gradient_steps': GRADIENT_STEPS,
'W_in_to_hid': Normal(std=1/sqrt(N)),
'nonlinearity': tanh
},
{
'type': FeaturePoolLayer,
'ds': 4, # number of feature maps to be pooled together
'axis': 1, # pool over the time axis
'po... | global source
source_dict_copy = deepcopy(source_dict)
source = RealApplianceSource(**source_dict_copy)
net_dict_copy = deepcopy(net_dict)
net_dict_copy.update(dict(
experiment_name=name,
source=source
))
N = 50
net_dict_copy['layers_config'] = [
{
'type':... | identifier_body |
config.py | class Config:
# specific (for this development instance)
# SERVER_NAME = 'localhost:5000'
| # celery settings
REDIS_URI = "redis://localhost/0"
BROKER_URL = REDIS_URI
CELERY_RESULT_BACKEND = REDIS_URI
CELERY_STORE_ERRORS_EVEN_IF_IGNORED = True
CELERYD_PREFETCH_MULTIPLIER = 1
CELERY_ALWAYS_EAGER = False # True: run tasks locally, no async
CELERY_EAGER_PROPAGATES_EXCEPTIONS = Tr... | SQLALCHEMY_DATABASE_URI = "sqlite:///data.db"
ANTIVIRUS_CHECK_REQUIRED = False
SECRET_KEY = "toto"
# develop settings
DEBUG = True
ASSETS_DEBUG = True
DEBUG_TB_ENABLED = True
# TEMPLATE_DEBUG = False
DEBUG_TB_INTERCEPT_REDIRECTS = False
DEBUG_TB_PROFILER_ENABLED = False
# Gener... | identifier_body |
config.py | class Config:
# specific (for this development instance)
# SERVER_NAME = 'localhost:5000'
SQLALCHEMY_DATABASE_URI = "sqlite:///data.db"
ANTIVIRUS_CHECK_REQUIRED = False
SECRET_KEY = "toto"
| DEBUG = True
ASSETS_DEBUG = True
DEBUG_TB_ENABLED = True
# TEMPLATE_DEBUG = False
DEBUG_TB_INTERCEPT_REDIRECTS = False
DEBUG_TB_PROFILER_ENABLED = False
# Generic for this project
SITE_NAME = "Abilian Core Demo"
MAIL_SENDER = "sender@example.com"
SESSION_COOKIE_NAME = "abilian-c... | # develop settings | random_line_split |
config.py | class | :
# specific (for this development instance)
# SERVER_NAME = 'localhost:5000'
SQLALCHEMY_DATABASE_URI = "sqlite:///data.db"
ANTIVIRUS_CHECK_REQUIRED = False
SECRET_KEY = "toto"
# develop settings
DEBUG = True
ASSETS_DEBUG = True
DEBUG_TB_ENABLED = True
# TEMPLATE_DEBUG = False
... | Config | identifier_name |
routes.js | /* eslint-disable global-require */
import React from 'react';
import { Router, Route, IndexRoute } from 'react-router';
import App from './modules/App/App';
import Landing from './modules/App/Landing';
import TalentInput from './modules/App/TalentInput';
import Performer from './modules/App/Performer';
// require.ens... |
/* Workaround for async react routes to work with react-hot-reloader till
https://github.com/reactjs/react-router/issues/2182 and
https://github.com/gaearon/react-hot-loader/issues/288 is fixed.
*/
if (process.env.NODE_ENV !== 'production') {
// Require async routes only in development for react-hot-reloader t... | {
require.ensure = function requireModule(deps, callback) {
callback(require);
};
} | conditional_block |
routes.js | /* eslint-disable global-require */
import React from 'react';
import { Router, Route, IndexRoute } from 'react-router';
import App from './modules/App/App';
import Landing from './modules/App/Landing';
import TalentInput from './modules/App/TalentInput';
import Performer from './modules/App/Performer';
// require.ens... | export default (
<Router>
<Route path="/" component={Landing} />
{/*} <IndexRoute
getComponent={(nextState, cb) => {
require.ensure([], require => {
cb(null, require('./modules/Post/pages/PostDetailPage/PostDetailPage').default);
});
}}
/>*/}
<Route path="/room" compon... | // require('./modules/Post/pages/PostDetailPage/PostDetailPage');
}
// react-router setup with code-splitting
// More info: http://blog.mxstbr.com/2016/01/react-apps-with-pages/ | random_line_split |
pubsub.py | # Copyright 2015 Google 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 required by applicable law or a... | (self):
self.to_delete = []
def tearDown(self):
for doomed in self.to_delete:
doomed.delete()
def test_create_topic(self):
TOPIC_NAME = 'a-new-topic'
topic = Topic(TOPIC_NAME)
self.assertFalse(topic.exists())
topic.create()
self.to_delete.app... | setUp | identifier_name |
pubsub.py | # Copyright 2015 Google 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 required by applicable law or a... |
message1, message2 = sorted(messages, key=_by_timestamp)
self.assertEqual(message1.data, MESSAGE_1)
self.assertEqual(message1.attributes['extra'], EXTRA_1)
self.assertEqual(message2.data, MESSAGE_2)
self.assertEqual(message2.attributes['extra'], EXTRA_2)
| return message.timestamp | identifier_body |
pubsub.py | # Copyright 2015 Google 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 required by applicable law or a... |
# Retrieve the subscriptions.
all_subscriptions, _ = pubsub.list_subscriptions()
created = [subscription for subscription in all_subscriptions
if subscription.name in subscriptions_to_create and
subscription.topic.name == TOPIC_NAME]
self.assertEqu... | subscription = Subscription(subscription_name, topic)
subscription.create()
self.to_delete.append(subscription) | conditional_block |
pubsub.py | # Copyright 2015 Google 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 required by applicable law or a... | self.assertEqual(message2.data, MESSAGE_2)
self.assertEqual(message2.attributes['extra'], EXTRA_2) | message1, message2 = sorted(messages, key=_by_timestamp)
self.assertEqual(message1.data, MESSAGE_1)
self.assertEqual(message1.attributes['extra'], EXTRA_1) | random_line_split |
p3.rs | /// ### Largest prime factor
/// ## Problem 3
/// The prime factors of 13195 are 5, 7, 13 and 29.
///
/// What is the largest prime factor of the number 600851475143 ?
use std::collections::TreeSet;
fn factors(num: int) -> Option<(int, int)> {
for divisor in range(2, num / 2) {
if num % divisor == 0 {
ret... | ) {
let num = 600851475143;
println!("{}", prime_factors(num).iter().max().unwrap());
}
| ain( | identifier_name |
p3.rs | /// ### Largest prime factor
/// ## Problem 3
/// The prime factors of 13195 are 5, 7, 13 and 29.
///
/// What is the largest prime factor of the number 600851475143 ?
use std::collections::TreeSet;
fn factors(num: int) -> Option<(int, int)> {
for divisor in range(2, num / 2) {
if num % divisor == 0 {
ret... | None => {
primes.insert(numerator);
return primes
}
}
}
}
fn main() {
let num = 600851475143;
println!("{}", prime_factors(num).iter().max().unwrap());
}
|
primes.insert(a);
numerator = b;
}
| conditional_block |
p3.rs | /// ### Largest prime factor
/// ## Problem 3
/// The prime factors of 13195 are 5, 7, 13 and 29.
///
/// What is the largest prime factor of the number 600851475143 ?
use std::collections::TreeSet;
fn factors(num: int) -> Option<(int, int)> {
for divisor in range(2, num / 2) {
if num % divisor == 0 {
ret... |
fn main() {
let num = 600851475143;
println!("{}", prime_factors(num).iter().max().unwrap());
} | }
}
}
} | random_line_split |
p3.rs | /// ### Largest prime factor
/// ## Problem 3
/// The prime factors of 13195 are 5, 7, 13 and 29.
///
/// What is the largest prime factor of the number 600851475143 ?
use std::collections::TreeSet;
fn factors(num: int) -> Option<(int, int)> { |
fn prime_factors(num: int) -> TreeSet<int> {
let mut numerator = num;
let mut primes = TreeSet::<int>::new();
loop {
match factors(numerator) {
Some((a, b)) => {
primes.insert(a);
numerator = b;
}
None => {
primes.insert(numerator);
return primes
}
... |
for divisor in range(2, num / 2) {
if num % divisor == 0 {
return Some((divisor, num / divisor))
}
}
None
}
| identifier_body |
AnonymousStream.js | "use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b)... | }
AnonymousStream.create = function (subscribeFunc) {
var obj = new this(subscribeFunc);
return obj;
};
AnonymousStream.prototype.buildStream = function (observer) {
return SingleDisposable_1.SingleDisposable.create((this.subscribeFunc(observer) || function () { }));
};
A... | var _this = _super.call(this, subscribeFunc) || this;
_this.scheduler = Scheduler_1.Scheduler.create();
return _this; | random_line_split |
AnonymousStream.js | "use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b)... |
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Stream_1 = require("../core/Stream");
var Scheduler_1 = require("../core/Scheduler");
var Subject_1 = require("../subject/Subject");
var AutoDeta... | { this.constructor = d; } | identifier_body |
AnonymousStream.js | "use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b)... | () { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Stream_1 = require("../core/Stream");
var Scheduler_1 = require("../core/Scheduler");
var Subject_1 = require("../sub... | __ | identifier_name |
ShopWizardResult.py | """:mod:`ShopWizardResult` -- Provides an interface for shop wizard results
.. module:: ShopWizardResult
:synopsis: Provides an interface for shop wizard results
.. moduleauthor:: Joshua Gilman <joshuagilman@gmail.com>
"""
from neolib.exceptions import parseException
from neolib.inventory.Inventory import Inventor... |
Example
>>> res = ShopWizard.search(usr, "Mau Codestone")
>>> for item in res:
... print item.price
3,000
3,001
...
"""
usr = None
def __init__(self, pg, usr):
self.usr = usr
try:
items = pg.find("td", ... | """Represents a shop wizard search result
Sub-classes the Inventory class to provide an interface for the results
from a Shop Wizard search. Automatically populates itself with the results
upon initialization.
Attributes
usr (User) - The user associated with the results
Init... | identifier_body |
ShopWizardResult.py | """:mod:`ShopWizardResult` -- Provides an interface for shop wizard results
.. module:: ShopWizardResult
:synopsis: Provides an interface for shop wizard results
.. moduleauthor:: Joshua Gilman <joshuagilman@gmail.com>
"""
from neolib.exceptions import parseException
from neolib.inventory.Inventory import Inventor... |
except Exception:
logging.getLogger("neolib.shop").exception("Unable to parse shop wizard results.", {'pg': pg})
raise parseException
def shop(self, index):
""" Return's the user shop the indexed item is in
Parameters:
index (int) -- The item ... | tmpItem = Item(item.find_all("td")[1].text)
tmpItem.owner = item.td.a.text
tmpItem.location = item.td.a['href']
tmpItem.stock = item.find_all("td")[2].text
tmpItem.price = item.find_all("td")[3].text.replace(" NP", "").replace(",", "")
... | conditional_block |
ShopWizardResult.py | """:mod:`ShopWizardResult` -- Provides an interface for shop wizard results
.. module:: ShopWizardResult
:synopsis: Provides an interface for shop wizard results
.. moduleauthor:: Joshua Gilman <joshuagilman@gmail.com>
"""
from neolib.exceptions import parseException
from neolib.inventory.Inventory import Inventor... | parseException
Example
>>> res = ShopWizard.search(usr, "Mau Codestone")
>>> for item in res:
... print item.price
3,000
3,001
...
"""
usr = None
def __init__(self, pg, usr):
self.usr = usr
try:
... |
Raises | random_line_split |
ShopWizardResult.py | """:mod:`ShopWizardResult` -- Provides an interface for shop wizard results
.. module:: ShopWizardResult
:synopsis: Provides an interface for shop wizard results
.. moduleauthor:: Joshua Gilman <joshuagilman@gmail.com>
"""
from neolib.exceptions import parseException
from neolib.inventory.Inventory import Inventor... | (self, index):
""" Attempts to buy indexed item, returns result
Parameters:
index (int) -- The item index
Returns
bool - True if item was bought, false otherwise
"""
item = self.items[index]
us = UserShopFront(self.usr, item.o... | buy | identifier_name |
Test1.py | import numpy as np
import cv2
import cv2.cv as cv
#im = cv2.imread('/Users/asafvaladarsky/Documents/img/Ad0010401.png')
im = cv2.imread('pic.png')
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
invert = 255 - imgray
cv2.imwrite('/Users/asafvaladarsky/Documents/pic1.png', invert)
#ret,thresh = cv2.threshold(invert,0,0,... |
#cv2.drawContours(invert, contours, -1, (255,0,0), 1 )
cv2.imshow('image', invert)
0xFF & cv2.waitKey()
cv2.destroyAllWindows()
'''
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)
################# Now finding Contours ... | if (i % 2 == 0):
cnt = contours[i]
#mask = np.zeros(im2.shape,np.uint8)
#cv2.drawContours(mask,[cnt],0,255,-1)
x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(invert,(x,y),(x+w,y+h),(0,255,0),1) | conditional_block |
Test1.py | import numpy as np
import cv2
import cv2.cv as cv
#im = cv2.imread('/Users/asafvaladarsky/Documents/img/Ad0010401.png')
im = cv2.imread('pic.png')
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
invert = 255 - imgray
cv2.imwrite('/Users/asafvaladarsky/Documents/pic1.png', invert)
#ret,thresh = cv2.threshold(invert,0,0,... |
def update(levels):
vis = np.zeros((cvImg.height, cvImg.width, 3), np.uint8)
levels = levels - 3
cv2.drawContours( vis, contours, (-1, 3)[levels <= 0], (128,255,255),
3, cv2.CV_AA, hierarchy, abs(levels) )
cv2.imshow('contours', vis)
update(3)
cv2.createTrackbar( "levels+3", "contours", 3,... | contours = [cv2.approxPolyDP(cnt, 3, True) for cnt in contours0] | random_line_split |
Intro.tsx | /*
* Copyright (c) 2016-2022, Mike Thomas
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of cond... | </p>
</Container>
</div>
);
} | random_line_split | |
TreeRankProfile.py | import numpy
import logging
import sys
from apgl.graph import *
from apgl.generator import *
from sandbox.util.ProfileUtils import ProfileUtils
from exp.sandbox.predictors.leafrank.SVMLeafRank import SVMLeafRank
from exp.sandbox.predictors.TreeRank import TreeRank
logging.basicConfig(stream=sys.stdout, level=logging.D... | (self):
treeRank = TreeRank(self.leafRanklearner)
treeRank.setMaxDepth(10)
treeRank.setMinSplit(50)
numExamples = 5000
numFeatures = 10
X = numpy.random.rand(numExamples, numFeatures)
Y = numpy.array(numpy.random.rand(numExamples) < 0.1, numpy.int)*2-1
... | profileLearnModel | identifier_name |
TreeRankProfile.py | import numpy
import logging
import sys
from apgl.graph import *
from apgl.generator import *
from sandbox.util.ProfileUtils import ProfileUtils
from exp.sandbox.predictors.leafrank.SVMLeafRank import SVMLeafRank
from exp.sandbox.predictors.TreeRank import TreeRank
logging.basicConfig(stream=sys.stdout, level=logging.D... |
def profileLearnModel(self):
treeRank = TreeRank(self.leafRanklearner)
treeRank.setMaxDepth(10)
treeRank.setMinSplit(50)
numExamples = 5000
numFeatures = 10
X = numpy.random.rand(numExamples, numFeatures)
Y = numpy.array(numpy.random.rand(numExamples) < 0.... | self.folds = 3
self.paramDict = {}
self.paramDict["setC"] = 2**numpy.arange(-5, 5, dtype=numpy.float)
self.leafRanklearner = SVMLeafRank(self.paramDict, self.folds) | identifier_body |
TreeRankProfile.py | import numpy
import logging
import sys
from apgl.graph import *
from apgl.generator import *
from sandbox.util.ProfileUtils import ProfileUtils
from exp.sandbox.predictors.leafrank.SVMLeafRank import SVMLeafRank
from exp.sandbox.predictors.TreeRank import TreeRank
logging.basicConfig(stream=sys.stdout, level=logging.D... |
def run():
for i in range(5):
print("Iteration " + str(i))
treeRank.learnModel(X, Y)
#print(treeRank.getTreeSize())
#print(treeRank.getTreeDepth())
ProfileUtils.profile('run()', globals(), locals())
profiler = TreeRankProfile... | random_line_split | |
TreeRankProfile.py | import numpy
import logging
import sys
from apgl.graph import *
from apgl.generator import *
from sandbox.util.ProfileUtils import ProfileUtils
from exp.sandbox.predictors.leafrank.SVMLeafRank import SVMLeafRank
from exp.sandbox.predictors.TreeRank import TreeRank
logging.basicConfig(stream=sys.stdout, level=logging.D... |
ProfileUtils.profile('run()', globals(), locals())
profiler = TreeRankProfile()
profiler.profileLearnModel() | print("Iteration " + str(i))
treeRank.learnModel(X, Y)
#print(treeRank.getTreeSize())
#print(treeRank.getTreeDepth()) | conditional_block |
user-service.js | var app = angular.module("ToDoApp")
app.service('UserDbService', function($rootScope) {
var users = [];
var uniqueId = 0; // always incrementing
var anonymousUser = {
username: 'anonymous',
id: null,
admin: false
};
var currentUser = angular.copy(anonymousUser);
// add first and only user 'adm... | (username) {
if (!username) {
return null;
}
var index = users.findIndex(function(el, idx) {
if (el.username == username) {
return true
}
return false
});
return users[index];
}
// ----------------- functions exposed by service
var service = {};
service.newU... | getUserByUsername | identifier_name |
user-service.js | var app = angular.module("ToDoApp")
app.service('UserDbService', function($rootScope) {
var users = [];
var uniqueId = 0; // always incrementing
var anonymousUser = {
username: 'anonymous',
id: null,
admin: false
};
var currentUser = angular.copy(anonymousUser);
// add first and only user 'adm... |
var user = users[index]
// ensure data integrity by not allow by allowing blank status or title
var objectChanged = false;
// update object with user.id == userId
if (data.username) {
user.username = data.username;
objectChanged = true;
}
if (data.password) {
user.passw... | {
return false
} | conditional_block |
user-service.js | var app = angular.module("ToDoApp")
app.service('UserDbService', function($rootScope) {
var users = [];
var uniqueId = 0; // always incrementing
var anonymousUser = {
username: 'anonymous',
id: null,
admin: false
};
var currentUser = angular.copy(anonymousUser);
// add first and only user 'adm... | return angular.copy(users);
}
/**
return true if object added, false otherwise
*/
function addUser(user) {
if (user) {
uniqueId += 1;
// give each object a unique id before sotring
user.id = uniqueId;
users.push(user);
return true;
}
return false;
}
/**
... | */
function getAllUsers() { | random_line_split |
user-service.js | var app = angular.module("ToDoApp")
app.service('UserDbService', function($rootScope) {
var users = [];
var uniqueId = 0; // always incrementing
var anonymousUser = {
username: 'anonymous',
id: null,
admin: false
};
var currentUser = angular.copy(anonymousUser);
// add first and only user 'adm... |
function getUserByUsername(username) {
if (!username) {
return null;
}
var index = users.findIndex(function(el, idx) {
if (el.username == username) {
return true
}
return false
});
return users[index];
}
// ----------------- functions exposed by service
va... | {
if (!userId) {
return -1;
}
var index = users.findIndex(function(el, idx) {
if (el.id == userId) {
return true
}
return false
});
return index;
} | identifier_body |
CodeBox.tsx | /** @jsxRuntime classic */
/** @jsx jsx */
import type { HTMLAttributes } from 'react';
import { useToasts } from 'react-toast-notifications';
import { jsx } from '@emotion/react';
import copy from 'copy-to-clipboard';
import { Copy } from '../icons/Copy';
type CodeBoxProps = {
code: string;
} & HTMLAttributes<HTML... | else {
// Fallback to a library that leverages document.execCommand
// for browser versions that don't support the navigator object.
// As document.execCommand
try {
copy(code);
} catch (e) {
addToast('Failed to copy to clipboard', { appearance: 'error', ...toastOpt });
... | {
// use the new navigator.clipboard API if it exists
navigator.clipboard.writeText(code).then(
() => addToast('Copied to clipboard', { appearance: 'success', ...toastOpt }),
() => addToast('Failed to copy to clipboard', { appearance: 'error', ...toastOpt })
);
return;
} | conditional_block |
CodeBox.tsx | /** @jsxRuntime classic */
/** @jsx jsx */
import type { HTMLAttributes } from 'react';
import { useToasts } from 'react-toast-notifications';
import { jsx } from '@emotion/react';
import copy from 'copy-to-clipboard';
import { Copy } from '../icons/Copy';
type CodeBoxProps = {
code: string;
} & HTMLAttributes<HTML... | border: '0 none',
borderRadius: '100%',
boxShadow: 'none',
background: 'transparent',
padding: '0.25rem',
marginLeft: '1rem',
cursor: 'pointer',
color: 'var(--muted)',
alignItems: 'center',
}}
>
<Copy css={{ ... | onClick={handleCopy}
css={{
display: 'inline-flex',
appearance: 'none', | random_line_split |
path.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | b_basedir = os.path.dirname(b_basedir)
b_final_path = os.path.expanduser(os.path.expandvars(to_bytes(path, errors='surrogate_or_strict')))
if not os.path.isabs(b_final_path):
b_final_path = os.path.join(b_basedir, b_final_path)
if follow:
b_final_path = os.path.realpath(b_final_pa... | '''
Returns a path that is free of symlinks (if follow=True), environment variables, relative path traversals and symbols (~)
:arg path: A byte or text string representing a path to be canonicalized
:arg follow: A boolean to indicate of symlinks should be resolved or not
:raises UnicodeDecodeError: If ... | identifier_body |
path.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | the directory chain. This function is not safe to use under world-writable locations when the first level of the
path to be created contains a predictable component. Always create a randomly-named element first if there is any
chance the parent directory might be world-writable (eg, /tmp) to prevent symlink... | def makedirs_safe(path, mode=None):
'''
A *potentially insecure* way to ensure the existence of a directory chain. The "safe" in this function's name
refers only to its ability to ignore `EEXIST` in the case of multiple callers operating on the same part of | random_line_split |
path.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | (path, mode=None):
'''
A *potentially insecure* way to ensure the existence of a directory chain. The "safe" in this function's name
refers only to its ability to ignore `EEXIST` in the case of multiple callers operating on the same part of
the directory chain. This function is not safe to use under wor... | makedirs_safe | identifier_name |
path.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... |
if dname:
# don't follow symlinks for basedir, enables source re-use
dname = os.path.abspath(dname)
return to_text(dname, errors='surrogate_or_strict')
def cleanup_tmp_file(path, warn=False):
"""
Removes temporary file or directory. Optionally display a warning if unable
to remo... | dname = os.path.dirname(source) | conditional_block |
zone_sectag.py | #!/usr/bin/env python3.2
#
# Copyright (c) Net24 Limited, Christchurch, New Zealand 2011-2012
# and Voyager Internet Ltd, New Zealand, 2012-2013
#
# This file is part of py-magcode-core.
#
# Py-magcode-core is free software: you can redistribute it and/or modify
# it under the terms of the GNU Gener... |
def __gt__(self, other):
return self.sectag > other.sectag
def __le__(self, other):
return self.sectag <= other.sectag
def __ge__(self, other):
return self.sectag >= other.sectag
def __str__(self):
"""
Print out sectag name
"""
ret... | return self.sectag < other.sectag | identifier_body |
zone_sectag.py | #!/usr/bin/env python3.2
#
# Copyright (c) Net24 Limited, Christchurch, New Zealand 2011-2012
# and Voyager Internet Ltd, New Zealand, 2012-2013
#
# This file is part of py-magcode-core.
#
# Py-magcode-core is free software: you can redistribute it and/or modify
# it under the terms of the GNU Gener... |
zone_sectag = ZoneSecTag(sectag_label)
try:
zone_sectag = db_session.query(ZoneSecTag)\
.filter(ZoneSecTag.zone_id == None)\
.filter(ZoneSecTag.sectag == sectag_label).one()
except NoResultFound:
raise ZoneSecTagDoesNotExist(sectag_label)
... | raise ZoneSecTagStillUsed(sectag_label) | conditional_block |
zone_sectag.py | #!/usr/bin/env python3.2
#
# Copyright (c) Net24 Limited, Christchurch, New Zealand 2011-2012
# and Voyager Internet Ltd, New Zealand, 2012-2013
#
# This file is part of py-magcode-core.
#
# Py-magcode-core is free software: you can redistribute it and/or modify
# it under the terms of the GNU Gener... | # Check that it is no longer being used.
try:
in_use_count = db_session.query(ZoneSecTag.sectag)\
.filter(ZoneSecTag.zone_id != None)\
.filter(ZoneSecTag.sectag == sectag_label).count()
if in_use_count:
raise ZoneSecTagStillUsed(sectag_... | except NoResultFound:
raise ZoneSecTagDoesNotExist(sectag_label) | random_line_split |
zone_sectag.py | #!/usr/bin/env python3.2
#
# Copyright (c) Net24 Limited, Christchurch, New Zealand 2011-2012
# and Voyager Internet Ltd, New Zealand, 2012-2013
#
# This file is part of py-magcode-core.
#
# Py-magcode-core is free software: you can redistribute it and/or modify
# it under the terms of the GNU Gener... | (self, other):
return self.sectag < other.sectag
def __gt__(self, other):
return self.sectag > other.sectag
def __le__(self, other):
return self.sectag <= other.sectag
def __ge__(self, other):
return self.sectag >= other.sectag
def __str__(self):
"... | __lt__ | identifier_name |
router.rs | //! Routing entity for handling endpoints
//!
//! This module is intended for matching and converting a passed URLs by a client
//! in request into certain queue/topic names.
//!
use std::clone::Clone;
use std::collections::HashMap;
use crate::engine::router::endpoint::ReadOnlyEndpoint;
use crate::error::{PathfinderE... | () {
let router = get_router(&"./tests/files/config_with_invalid_endpoints.yaml");
let result_match = router.match_url(&"/api/matchmaking/search");
assert_eq!(result_match.is_err(), true);
}
}
| test_routers_match_url_returns_an_error_for_an_unknown_url | identifier_name |
router.rs | //! Routing entity for handling endpoints
//!
//! This module is intended for matching and converting a passed URLs by a client
//! in request into certain queue/topic names.
//!
use std::clone::Clone;
use std::collections::HashMap;
use crate::engine::router::endpoint::ReadOnlyEndpoint;
use crate::error::{PathfinderE... | Ok(endpoint)
}
false => Err(PathfinderError::EndpointNotFound(url.to_string()))
}
}
}
#[cfg(test)]
mod tests {
use crate::config::get_config;
use crate::engine::router::{extract_endpoints, Router};
fn get_router(file_path: &str) -> Box<Router> {
... | match self.endpoints.contains_key(url) {
true => {
let endpoint = self.endpoints[url].clone(); | random_line_split |
mutable-tree.ts | import {Change} from './change';
import {Node} from './node';
import {Path, deserializePath} from './path';
import {apply, compare} from '../utils/patch';
export class MutableTree {
public roots: Array<Node>;
/// Compare this tree to another tree and generate a delta
diff(nextTree: MutableTree): Array<Change> {... | } | return results;
} | random_line_split |
mutable-tree.ts | import {Change} from './change';
import {Node} from './node';
import {Path, deserializePath} from './path';
import {apply, compare} from '../utils/patch';
export class MutableTree {
public roots: Array<Node>;
/// Compare this tree to another tree and generate a delta
diff(nextTree: MutableTree): Array<Change> {... | case 'number':
if (iterator.children.length <= index) {
return null; // not found
}
iterator = iterator.children[index];
break;
case 'string':
iterator = iterator[index];
break;
}
}
return iterator;
}
/// Apply ... | {
path = path.slice(0);
const root = this.roots[path.shift()];
if (root == null) {
return null;
}
if (path.length === 0) {
return root;
}
let iterator = root;
for (const index of path) {
if (iterator == null) {
return null;
}
switch (typeof inde... | identifier_body |
mutable-tree.ts | import {Change} from './change';
import {Node} from './node';
import {Path, deserializePath} from './path';
import {apply, compare} from '../utils/patch';
export class MutableTree {
public roots: Array<Node>;
/// Compare this tree to another tree and generate a delta
diff(nextTree: MutableTree): Array<Change> {... | (fn: (node: Node) => boolean): Array<Node> {
const results = new Array<Node>();
this.recurseAll(node => {
if (fn(node)) {
results.push(node);
}
});
return results;
}
}
| filter | identifier_name |
mutable-tree.ts | import {Change} from './change';
import {Node} from './node';
import {Path, deserializePath} from './path';
import {apply, compare} from '../utils/patch';
export class MutableTree {
public roots: Array<Node>;
/// Compare this tree to another tree and generate a delta
diff(nextTree: MutableTree): Array<Change> {... |
}
filter(fn: (node: Node) => boolean): Array<Node> {
const results = new Array<Node>();
this.recurseAll(node => {
if (fn(node)) {
results.push(node);
}
});
return results;
}
}
| {
if (this.recurse(index, fn) === false) {
return false;
}
} | conditional_block |
VisualEffects.tsx | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import * as React from 'react';
import * as _ from 'lodash';
// declare var particlesJS: any;
declare var Par... | else {
this.initializeParallax();
}
}
private disableParallax = () => {
if (this.parallaxInstance) {
this.parallaxInstance.disable();
}
}
// private setParticles = () => {
// const { layerInfo } = this.props;
// if (_.isArray(layerInfo)) {
// // this.props.layerInfo is a... | {
this.parallaxInstance.enable();
} | conditional_block |
VisualEffects.tsx | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import * as React from 'react';
import * as _ from 'lodash';
// declare var particlesJS: any;
declare var Par... | private parallaxInstance: any;
public render() {
const { layerInfo } = this.props;
return (
<div className='videobg'>
<div className='parallax' data-relative-input='true' id={this.props.id}>
{_.isArray(layerInfo) ? layerInfo.map((layer, i) => {
if (layer.particleEffect) {... |
class VisualEffects extends React.PureComponent<Props, {}> { | random_line_split |
nurseconnect_tags.py | import calendar
from django.template import Library
from molo.core.templatetags.core_tags import load_sections
from molo.profiles.models import UserProfilesSettings
from nurseconnect.utils import get_survey_results_for_user
register = Library()
@register.filter('fieldtype')
def fieldtype(field):
return field.... |
@register.assignment_tag()
def get_next_article(page):
if page.get_next_sibling():
return page.get_next_sibling().specific
return None
@register.inclusion_tag("surveys/embedded_survey.html",
takes_context=True)
def embedded_survey_tag(context, page):
'''
Display the... | if value:
return calendar.month_name[value]
else:
return "" | identifier_body |
nurseconnect_tags.py | import calendar
from django.template import Library
from molo.core.templatetags.core_tags import load_sections
from molo.profiles.models import UserProfilesSettings
from nurseconnect.utils import get_survey_results_for_user
register = Library()
@register.filter('fieldtype')
def fieldtype(field):
return field.... | return {
"survey_answered": False,
"survey": survey
} | conditional_block | |
nurseconnect_tags.py | import calendar
from django.template import Library
from molo.core.templatetags.core_tags import load_sections
from molo.profiles.models import UserProfilesSettings
from nurseconnect.utils import get_survey_results_for_user |
register = Library()
@register.filter('fieldtype')
def fieldtype(field):
return field.field.widget.__class__.__name__
@register.inclusion_tag("core/tags/footerlink.html", takes_context=True)
def footer_link(context, id):
request = context["request"]
locale = context.get("locale_code")
terms = User... | random_line_split | |
nurseconnect_tags.py | import calendar
from django.template import Library
from molo.core.templatetags.core_tags import load_sections
from molo.profiles.models import UserProfilesSettings
from nurseconnect.utils import get_survey_results_for_user
register = Library()
@register.filter('fieldtype')
def fieldtype(field):
return field.... | (context):
locale_code = context.get("locale_code")
return {
"sections": load_sections(context),
"request": context["request"],
"locale_code": locale_code,
}
@register.assignment_tag()
def convert_month(value):
if value:
return calendar.month_name[value]
else:
... | section_listing_menu | identifier_name |
tuntap_tests.py | # Copyright (c) 2011 Mattias Nissler <mattias.nissler@gmx.de>
#
# Redistribution and use in source and binary forms, with or without modification, are permitted
# provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of
# condition... |
def loadTestsFromTestCase(testCaseClass, *args, **kwargs):
testCaseNames = unittest.getTestCaseNames(testCaseClass, 'test_')
return unittest.TestSuite(map(lambda n : testCaseClass(n, *args, **kwargs), testCaseNames))
def main(argv):
# Parse the command line.
parser = argparse.ArgumentParser(descripti... | def __init__(self, filter):
super(FilteringTestSuite, self).__init__()
self._matcher = re.compile(filter or '.*')
def __iter__(self):
return itertools.ifilter(lambda test : self._matcher.search(str(test)),
super(FilteringTestSuite, self).__iter__()) | identifier_body |
tuntap_tests.py | # Copyright (c) 2011 Mattias Nissler <mattias.nissler@gmx.de>
#
# Redistribution and use in source and binary forms, with or without modification, are permitted
# provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of
# condition... | verbosity = options.verbosity)
runner.run(suite)
if __name__ == '__main__':
main(sys.argv) | random_line_split | |
tuntap_tests.py | # Copyright (c) 2011 Mattias Nissler <mattias.nissler@gmx.de>
#
# Redistribution and use in source and binary forms, with or without modification, are permitted
# provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of
# condition... |
runner = unittest.TextTestRunner(stream = sys.stderr,
descriptions = True,
verbosity = options.verbosity)
runner.run(suite)
if __name__ == '__main__':
main(sys.argv)
| suite.addTests(loadTestsFromTestCase(test, lambda af, addr: codec(af, addr, source))) | conditional_block |
tuntap_tests.py | # Copyright (c) 2011 Mattias Nissler <mattias.nissler@gmx.de>
#
# Redistribution and use in source and binary forms, with or without modification, are permitted
# provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of
# condition... | (unittest.TestSuite):
def __init__(self, filter):
super(FilteringTestSuite, self).__init__()
self._matcher = re.compile(filter or '.*')
def __iter__(self):
return itertools.ifilter(lambda test : self._matcher.search(str(test)),
super(FilteringTestSuite,... | FilteringTestSuite | identifier_name |
file.py | import os
import re
import mimetypes
from collections import namedtuple
from aiohttp import web
from app.lib.helpers import (
http400,
http404,
)
DEFAULT_CONTENT_TYPE = 'application/octet-stream'
FILENAME_PARSER = re.compile(r"(?P<id>\d+)_(?P<name>.+)\.(?P<format>.+)")
ParsedFile = namedtuple('ParsedFile',... | [
'bmp', 'eps', 'icns', 'im', 'msp', 'pcx', 'ppm',
'png', 'tiff', 'ico', 'jpg', 'jpeg', 'gif',
]
}
)
def file_response(name, body, source):
if body is None:
return http404()
return web.Response(
body=body,
headers={
... | '.' in filename
and filename.rsplit('.', 1)[1] in { | random_line_split |
file.py | import os
import re
import mimetypes
from collections import namedtuple
from aiohttp import web
from app.lib.helpers import (
http400,
http404,
)
DEFAULT_CONTENT_TYPE = 'application/octet-stream'
FILENAME_PARSER = re.compile(r"(?P<id>\d+)_(?P<name>.+)\.(?P<format>.+)")
ParsedFile = namedtuple('ParsedFile',... | (filename):
return (
'.' in filename
and filename.rsplit('.', 1)[1] in {
[
'bmp', 'eps', 'icns', 'im', 'msp', 'pcx', 'ppm',
'png', 'tiff', 'ico', 'jpg', 'jpeg', 'gif',
]
}
)
def file_response(name, body, source):
if body is No... | allowed_file | identifier_name |
file.py | import os
import re
import mimetypes
from collections import namedtuple
from aiohttp import web
from app.lib.helpers import (
http400,
http404,
)
DEFAULT_CONTENT_TYPE = 'application/octet-stream'
FILENAME_PARSER = re.compile(r"(?P<id>\d+)_(?P<name>.+)\.(?P<format>.+)")
ParsedFile = namedtuple('ParsedFile',... |
async def store_mp3_handler(request):
reader = await request.multipart()
# /!\ Don't forget to validate your inputs /!\
file = await reader.next()
filename = file.filename
if not allowed_file(filename):
return http400()
# You cannot rely on Content-Length if transfer is chunked.
... | if body is None:
return http404()
return web.Response(
body=body,
headers={
'X-File-Source': source,
**get_file_headers(name)
}
) | identifier_body |
file.py | import os
import re
import mimetypes
from collections import namedtuple
from aiohttp import web
from app.lib.helpers import (
http400,
http404,
)
DEFAULT_CONTENT_TYPE = 'application/octet-stream'
FILENAME_PARSER = re.compile(r"(?P<id>\d+)_(?P<name>.+)\.(?P<format>.+)")
ParsedFile = namedtuple('ParsedFile',... |
# You cannot rely on Content-Length if transfer is chunked.
size = 0
with open(os.path.join('/media/', filename), 'wb') as f:
while True:
chunk = await file.read_chunk() # 8192 bytes by default.
if not chunk:
break
size += len(chunk)
... | return http400() | conditional_block |
at_exit_imp.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | use unstable::sync::Exclusive;
use slice::OwnedVector;
use vec::Vec;
type Queue = Exclusive<Vec<proc():Send>>;
// You'll note that these variables are *not* atomic, and this is done on
// purpose. This module is designed to have init() called *once* in a
// single-task context, and then run() is called only once in a... | use ptr::RawPtr; | random_line_split |
at_exit_imp.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn run() {
let vec = unsafe {
rtassert!(!RUNNING);
rtassert!(!QUEUE.is_null());
RUNNING = true;
let state: Box<Queue> = cast::transmute(QUEUE);
QUEUE = 0 as *mut Queue;
let mut vec = None;
state.with(|arr| {
vec = Some(mem::replace(arr, vec!(... | {
unsafe {
rtassert!(!RUNNING);
rtassert!(!QUEUE.is_null());
let state: &mut Queue = cast::transmute(QUEUE);
let mut f = Some(f);
state.with(|arr| {
arr.push(f.take_unwrap());
});
}
} | identifier_body |
at_exit_imp.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
unsafe {
rtassert!(!RUNNING);
rtassert!(QUEUE.is_null());
let state: Box<Queue> = box Exclusive::new(vec!());
QUEUE = cast::transmute(state);
}
}
pub fn push(f: proc():Send) {
unsafe {
rtassert!(!RUNNING);
rtassert!(!QUEUE.is_null());
let state: ... | init | identifier_name |
summary.py | # -*- encoding: UTF-8 -*-
from __future__ import unicode_literals
from HTMLParser import HTMLParser
from pelican import signals, contents
_MAX_SUMMARY_POS = 45
class FirstParagraphParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.paragraphTag = 'p'
self.data = ''
... | (self, tag):
if self.currTags:
self.currTags.pop()
def handle_data(self, data):
if self.currTags:
self.data += data
def content_object_init(instance):
if isinstance(instance, contents.Static):
return
if 'summary' in instance.metadata:
return
if n... | handle_endtag | identifier_name |
summary.py | # -*- encoding: UTF-8 -*-
from __future__ import unicode_literals
from HTMLParser import HTMLParser
from pelican import signals, contents
_MAX_SUMMARY_POS = 45
class FirstParagraphParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.paragraphTag = 'p'
self.data = ''
... |
def handle_data(self, data):
if self.currTags:
self.data += data
def content_object_init(instance):
if isinstance(instance, contents.Static):
return
if 'summary' in instance.metadata:
return
if not hasattr(instance, '_summary') and instance._content is not None:
... | if self.currTags:
self.currTags.pop() | identifier_body |
summary.py | # -*- encoding: UTF-8 -*-
from __future__ import unicode_literals
from HTMLParser import HTMLParser | def __init__(self):
HTMLParser.__init__(self)
self.paragraphTag = 'p'
self.data = ''
self.currTags = []
def handle_starttag(self, tag, attrs):
if not self.data and self.paragraphTag == tag.lower():
self.currTags.append('p')
elif self.currTags:
... | from pelican import signals, contents
_MAX_SUMMARY_POS = 45
class FirstParagraphParser(HTMLParser): | random_line_split |
summary.py | # -*- encoding: UTF-8 -*-
from __future__ import unicode_literals
from HTMLParser import HTMLParser
from pelican import signals, contents
_MAX_SUMMARY_POS = 45
class FirstParagraphParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.paragraphTag = 'p'
self.data = ''
... |
if 'summary' in instance.metadata:
return
if not hasattr(instance, '_summary') and instance._content is not None:
content = instance._content
firstP = FirstParagraphParser()
firstP.feed(content)
endCharA = '。'
endCharB = '.'
endPosA = firstP.data.find(end... | return | conditional_block |
method-ambig-two-traits-cross-crate.rs | // Copyright 2012-2014 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-MI... | }
fn main() { 1_usize.me(); } //~ ERROR E0034
| { *self } | identifier_body |
method-ambig-two-traits-cross-crate.rs | // Copyright 2012-2014 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-MI... | trait me2 {
fn me(&self) -> usize;
}
impl me2 for usize { fn me(&self) -> usize { *self } }
fn main() { 1_usize.me(); } //~ ERROR E0034 | random_line_split | |
method-ambig-two-traits-cross-crate.rs | // Copyright 2012-2014 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-MI... | (&self) -> usize { *self } }
fn main() { 1_usize.me(); } //~ ERROR E0034
| me | identifier_name |
conf.py | are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for sou... | node += textnode
node['classes'].append(typ)
return [node], []
# Use 'patched_menusel_role' function for processing the 'menuselection' role
roles.register_local_role("menuselection", patched_menusel_role)
# -- Options for HTML output ----------------------------------------------
# The theme to use... | ext = utils.unescape(text)
if typ == 'menuselection':
text = text.replace('-->', u'\N{RIGHTWARDS ARROW}') # Here is the patch
spans = _amp_re.split(text)
node = nodes.literal(rawtext=rawtext)
for i, span in enumerate(spans):
span = span.replace('&&', '&')
if i == 0:
... | identifier_body |
conf.py | two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source ... | typ, rawtext, text, lineno, inliner, options={}, content=[]):
text = utils.unescape(text)
if typ == 'menuselection':
text = text.replace('-->', u'\N{RIGHTWARDS ARROW}') # Here is the patch
spans = _amp_re.split(text)
node = nodes.literal(rawtext=rawtext)
for i, span in enumerate(spans):
... | atched_menusel_role( | identifier_name |
conf.py | are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for sou... | REAMBLE = r'''\def\docname{''' + texproject + '}'
PREAMBLE = (PREAMBLE
+ r'''\def\docdate{'''
+ time.strftime("%B %Y")
+ ' Edition}')
# define custom title page
PREAMBLE = PREAMBLE + r'''
% FreeNAS/TrueNAS LaTeX preamble
\usepackage[default,scale=0.95]{opensans}
\usepackage[T1]{fon... | xproject = project.replace(u'®', r'''\textsuperscript{\textregistered}''')
P | conditional_block |
conf.py | are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for sou... | node += textnode
node['classes'].append(typ)
return [node], []
# Use 'patched_menusel_role' function for processing the 'menuselection' role
roles.register_local_role("menuselection", patched_menusel_role)
# -- Options for HTML output ----------------------------------------------
# The theme to use... | accel_node['classes'].append('accelerator')
node += accel_node
textnode = nodes.Text(span[1:]) | random_line_split |
reducer.ts | import extend from 'xtend'
import { Actions } from './actions'
type AssessmentStage = 0 | 1 | 2 | 3 | 4
export type Assessment = {
address: string
cost: number
size: number
assessee: string
assessors: string[]
userStage: AssessmentStage
stage: AssessmentStage
finalScore: number
data... |
return state
}
case 'UPDATE_ASSESSMENT_VARIABLE': {
return {
...state,
[action.assessmentAddress]: extend(state[action.assessmentAddress], { [action.name]: action.value })
}
}
case 'SET_ASSESSMENT_AS_INVALID': {
return {
...state,
[action.assessmentAddress]: extend(stat... | {
newAssessors.push(action.assessor)
return {
...state,
[assessmentAddress]: extend(assessment, { assessors: newAssessors })
}
} | conditional_block |
reducer.ts | import extend from 'xtend'
import { Actions } from './actions'
type AssessmentStage = 0 | 1 | 2 | 3 | 4
export type Assessment = {
address: string
cost: number
size: number
assessee: string
assessors: string[]
userStage: AssessmentStage
stage: AssessmentStage
finalScore: number
data... | (state = initialState, action: Actions): AssessmentsState {
switch (action.type) {
case 'SET_CARD_VISIBILITY': {
let assessmentAddress = action.assessmentAddress
let assessment = state[assessmentAddress]
return extend(state, {
[assessmentAddress]: extend(assessment, { hidden: action.hidden })
... | AssessmentsReducer | identifier_name |
reducer.ts | import extend from 'xtend'
import { Actions } from './actions'
type AssessmentStage = 0 | 1 | 2 | 3 | 4
export type Assessment = {
address: string
cost: number
size: number
assessee: string
assessors: string[]
userStage: AssessmentStage
stage: AssessmentStage | }
payout: number
violation: number
refunded: boolean
hidden: boolean
}
export type AssessmentsState = {
[prop: string]: Assessment
}
let initialState: AssessmentsState = {}
export function AssessmentsReducer (state = initialState, action: Actions): AssessmentsState {
switch (action.type) {
c... | finalScore: number
data: {
[prop: string]: string | random_line_split |
reducer.ts | import extend from 'xtend'
import { Actions } from './actions'
type AssessmentStage = 0 | 1 | 2 | 3 | 4
export type Assessment = {
address: string
cost: number
size: number
assessee: string
assessors: string[]
userStage: AssessmentStage
stage: AssessmentStage
finalScore: number
data... | let assessment = state[assessmentAddress] || { assessors: [] }
let newAssessors = assessment.assessors.slice(0)
if (newAssessors.indexOf(action.assessor) === -1) {
newAssessors.push(action.assessor)
return {
...state,
[assessmentAddress]: extend(assessment, { assessors: newAssess... | {
switch (action.type) {
case 'SET_CARD_VISIBILITY': {
let assessmentAddress = action.assessmentAddress
let assessment = state[assessmentAddress]
return extend(state, {
[assessmentAddress]: extend(assessment, { hidden: action.hidden })
})
}
case 'RECEIVE_ASSESSMENT': {
let assessmentAd... | identifier_body |
test-s3-getting-started.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_s3::{Client, Error, Region};
use uuid::Uuid;
#[ignore]
#[tokio::test] | Err(_e) => assert!(false),
_ => assert!(true),
}
}
async fn run_s3_operations(
region: Region,
client: Client,
bucket_name: String,
file_name: String,
key: String,
target_key: String,
) -> Result<(), Error> {
s3_service::create_bucket(&client, &bucket_name, region.as_ref... | async fn test_it_runs() {
let (region, client, bucket_name, file_name, key, target_key) = setup().await;
match run_s3_operations(region, client, bucket_name, file_name, key, target_key).await { | random_line_split |
test-s3-getting-started.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_s3::{Client, Error, Region};
use uuid::Uuid;
#[ignore]
#[tokio::test]
async fn test_it_runs() {
let (region, client, bucket_name, file... | (
region: Region,
client: Client,
bucket_name: String,
file_name: String,
key: String,
target_key: String,
) -> Result<(), Error> {
s3_service::create_bucket(&client, &bucket_name, region.as_ref()).await?;
s3_service::upload_object(&client, &bucket_name, &file_name, &key).await?;
s3_... | run_s3_operations | identifier_name |
test-s3-getting-started.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_s3::{Client, Error, Region};
use uuid::Uuid;
#[ignore]
#[tokio::test]
async fn test_it_runs() {
let (region, client, bucket_name, file... | {
let region_provider = RegionProviderChain::first_try(Region::new("us-west-2"));
let region = region_provider.region().await.unwrap();
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
let bucket_name = format!("{}{}", "doc-... | identifier_body | |
t4_adm.py | ''' | This program can be distributed under the terms of the GNU GPLv3.
'''
from __future__ import division, print_function, absolute_import
from s3ql.backends import local
from s3ql.backends.common import BetterBackend
import shutil
import sys
import tempfile
import unittest2 as unittest
import subprocess
import os.path
... | t4_adm.py - this file is part of S3QL (http://s3ql.googlecode.com)
Copyright (C) 2008-2009 Nikolaus Rath <Nikolaus@rath.org>
| random_line_split |
t4_adm.py | '''
t4_adm.py - this file is part of S3QL (http://s3ql.googlecode.com)
Copyright (C) 2008-2009 Nikolaus Rath <Nikolaus@rath.org>
This program can be distributed under the terms of the GNU GPLv3.
'''
from __future__ import division, print_function, absolute_import
from s3ql.backends import local
from s3ql.backends.c... | (self):
proc = subprocess.Popen([sys.executable, os.path.join(BASEDIR, 'bin', 'mkfs.s3ql'),
'-L', 'test fs', '--max-obj-size', '500',
'--cachedir', self.cache_dir, '--quiet',
self.storage_url ], stdin=subprocess.P... | mkfs | identifier_name |
t4_adm.py | '''
t4_adm.py - this file is part of S3QL (http://s3ql.googlecode.com)
Copyright (C) 2008-2009 Nikolaus Rath <Nikolaus@rath.org>
This program can be distributed under the terms of the GNU GPLv3.
'''
from __future__ import division, print_function, absolute_import
from s3ql.backends import local
from s3ql.backends.c... |
else:
mypath = __file__
BASEDIR = os.path.abspath(os.path.join(os.path.dirname(mypath), '..'))
class AdmTests(unittest.TestCase):
def setUp(self):
self.cache_dir = tempfile.mkdtemp()
self.backend_dir = tempfile.mkdtemp()
self.storage_url = 'local://' + self.backend_dir
self.p... | mypath = sys.argv[0] | conditional_block |
t4_adm.py | '''
t4_adm.py - this file is part of S3QL (http://s3ql.googlecode.com)
Copyright (C) 2008-2009 Nikolaus Rath <Nikolaus@rath.org>
This program can be distributed under the terms of the GNU GPLv3.
'''
from __future__ import division, print_function, absolute_import
from s3ql.backends import local
from s3ql.backends.c... |
def tearDown(self):
shutil.rmtree(self.cache_dir)
shutil.rmtree(self.backend_dir)
def mkfs(self):
proc = subprocess.Popen([sys.executable, os.path.join(BASEDIR, 'bin', 'mkfs.s3ql'),
'-L', 'test fs', '--max-obj-size', '500',
... | self.cache_dir = tempfile.mkdtemp()
self.backend_dir = tempfile.mkdtemp()
self.storage_url = 'local://' + self.backend_dir
self.passphrase = 'oeut3d' | identifier_body |
scf.py | import numpy as np
from gpaw import KohnShamConvergenceError
class SCFLoop:
| self.reset()
def fix_density(self):
self.fixdensity = True
self.niter_fixdensity = 10000000
self.max_density_error = np.inf
def reset(self):
self.energies = []
self.eigenstates_error = None
self.energy_error = None
self.density_error = No... | """Self-consistent field loop.
converged: Do we have a self-consistent solution?
"""
def __init__(self, eigenstates=0.1, energy=0.1, density=0.1, maxiter=100,
fixdensity=False, niter_fixdensity=None):
self.max_eigenstates_error = max(eigenstates, 1e-20)
self.max_en... | identifier_body |
scf.py | import numpy as np
from gpaw import KohnShamConvergenceError
class SCFLoop:
"""Self-consistent field loop.
converged: Do we have a self-consistent solution?
"""
def __init__(self, eigenstates=0.1, energy=0.1, density=0.1, maxiter=100,
fixdensity=False, niter_fixdensity=None... | # XXX ortho, dens, wfs?
energy = hamiltonian.get_energy(occupations)
self.energies.append(energy)
self.check_convergence(density, wfs.eigensolver)
yield iter
if self.converged:
break
if iter > self.niter_f... | occupations.calculate(wfs) | random_line_split |
scf.py | import numpy as np
from gpaw import KohnShamConvergenceError
class | :
"""Self-consistent field loop.
converged: Do we have a self-consistent solution?
"""
def __init__(self, eigenstates=0.1, energy=0.1, density=0.1, maxiter=100,
fixdensity=False, niter_fixdensity=None):
self.max_eigenstates_error = max(eigenstates, 1e-20)
self.... | SCFLoop | identifier_name |
scf.py | import numpy as np
from gpaw import KohnShamConvergenceError
class SCFLoop:
"""Self-consistent field loop.
converged: Do we have a self-consistent solution?
"""
def __init__(self, eigenstates=0.1, energy=0.1, density=0.1, maxiter=100,
fixdensity=False, niter_fixdensity=None... |
self.converged = (
self.eigenstates_error < self.max_eigenstates_error and
self.energy_error < self.max_energy_error and
self.density_error < self.max_density_error)
return self.converged
| self.density_error = 1000000.0 | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.