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 |
|---|---|---|---|---|
user.rs | import_controller_generic_requeriments!();
use dal::models::user::{User, UpdateUser};
use dal::models::post::{Post};
pub fn get(req: &mut Request) -> IronResult<Response>{
let connection = req.get_db_conn();
let logger = req.get_logger();
let user_id = get_route_parameter_as!(i32, req, "id", response_not_found("U... | {
let connection = req.get_db_conn();
let logger = req.get_logger();
let user_id = req.get_user_data().id;
let posts = Post::get_post_from_user(user_id, &connection, &logger);
response_ok(&posts)
} | identifier_body | |
user.rs | import_controller_generic_requeriments!();
use dal::models::user::{User, UpdateUser};
use dal::models::post::{Post};
pub fn get(req: &mut Request) -> IronResult<Response>{
let connection = req.get_db_conn();
let logger = req.get_logger();
let user_id = get_route_parameter_as!(i32, req, "id", response_not_found("U... | (req: &mut Request) -> IronResult<Response> {
response_ok(&req.get_user_data())
}
pub fn delete(req: &mut Request) -> IronResult<Response> {
let connection = req.get_db_conn();
let logger = req.get_logger();
let user_id = get_route_parameter_as!(i32, req, "id", response_not_found("User not found"));
let quatity... | get_me | identifier_name |
user.rs | import_controller_generic_requeriments!();
use dal::models::user::{User, UpdateUser}; | pub fn get(req: &mut Request) -> IronResult<Response>{
let connection = req.get_db_conn();
let logger = req.get_logger();
let user_id = get_route_parameter_as!(i32, req, "id", response_not_found("User not found"));
let user_data = some_or_return!(
User::get_by_id(user_id, &connection, &logger),
response_not_... | use dal::models::post::{Post};
| random_line_split |
dyn.rs | use rstest::*;
#[fixture]
fn dyn_box() -> Box<dyn Iterator<Item=i32>> {
Box::new(std::iter::once(42))
}
#[fixture]
fn dyn_ref() -> &'static dyn ToString {
&42
}
#[fixture]
fn dyn_box_resolve(mut dyn_box: Box<dyn Iterator<Item=i32>>) -> i32 {
dyn_box.next().unwrap()
}
#[fixture]
fn dyn_ref_resolve(dyn_re... |
#[rstest]
fn test_dyn_box_resolve(dyn_box_resolve: i32) {
assert_eq!(42, dyn_box_resolve)
}
#[rstest]
fn test_dyn_ref_resolve(dyn_ref_resolve: String) {
assert_eq!("42", dyn_ref_resolve)
}
| {
assert_eq!("42", dyn_ref.to_string())
} | identifier_body |
dyn.rs | use rstest::*;
#[fixture]
fn dyn_box() -> Box<dyn Iterator<Item=i32>> {
Box::new(std::iter::once(42))
}
#[fixture]
fn dyn_ref() -> &'static dyn ToString {
&42
}
#[fixture]
fn dyn_box_resolve(mut dyn_box: Box<dyn Iterator<Item=i32>>) -> i32 {
dyn_box.next().unwrap()
}
#[fixture]
fn dyn_ref_resolve(dyn_re... | (dyn_box_resolve: i32) {
assert_eq!(42, dyn_box_resolve)
}
#[rstest]
fn test_dyn_ref_resolve(dyn_ref_resolve: String) {
assert_eq!("42", dyn_ref_resolve)
}
| test_dyn_box_resolve | identifier_name |
dyn.rs | use rstest::*;
#[fixture]
fn dyn_box() -> Box<dyn Iterator<Item=i32>> {
Box::new(std::iter::once(42))
}
#[fixture]
fn dyn_ref() -> &'static dyn ToString {
&42
}
#[fixture]
fn dyn_box_resolve(mut dyn_box: Box<dyn Iterator<Item=i32>>) -> i32 {
dyn_box.next().unwrap()
}
#[fixture]
fn dyn_ref_resolve(dyn_re... | } | assert_eq!("42", dyn_ref_resolve) | random_line_split |
forward.py | # -*- mode: python; fill-column: 100; comment-column: 100; -*-
import unittest
import sys
import os
sys.path.append(
os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
import base_test
class ForwardTest(base_test.WebDriverBaseTest):
# Get a static page that must be the same upon refr... | (self):
self.driver.get(
self.webserver.where_is('navigation/res/forwardStart.html'))
self.driver.get(
self.webserver.where_is('navigation/res/forwardNext.html'))
nextbody = self.driver.find_element_by_css("body").get_text()
self.driver.go_back()
currbody... | test_forward | identifier_name |
forward.py | # -*- mode: python; fill-column: 100; comment-column: 100; -*-
import unittest
import sys
import os
sys.path.append(
os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
import base_test
class ForwardTest(base_test.WebDriverBaseTest):
# Get a static page that must be the same upon refr... |
if __name__ == '__main__':
unittest.main()
| self.driver.get(
self.webserver.where_is('navigation/res/forwardStart.html'))
self.driver.get(
self.webserver.where_is('navigation/res/forwardNext.html'))
nextbody = self.driver.find_element_by_css("body").get_text()
self.driver.go_back()
currbody = self.driver.fi... | identifier_body |
forward.py | # -*- mode: python; fill-column: 100; comment-column: 100; -*-
import unittest
import sys
import os
sys.path.append(
os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
import base_test
class ForwardTest(base_test.WebDriverBaseTest):
# Get a static page that must be the same upon refr... | unittest.main() | conditional_block | |
forward.py | # -*- mode: python; fill-column: 100; comment-column: 100; -*-
import unittest
import sys
import os
sys.path.append(
os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
import base_test
class ForwardTest(base_test.WebDriverBaseTest):
# Get a static page that must be the same upon refr... | self.webserver.where_is('navigation/res/forwardStart.html'))
self.driver.get(
self.webserver.where_is('navigation/res/forwardNext.html'))
nextbody = self.driver.find_element_by_css("body").get_text()
self.driver.go_back()
currbody = self.driver.find_element_by_css... | random_line_split | |
NodeController.ts | import e = require('express');
import BaseController from "./BaseController";
import { router } from "../decorators/Web";
import { Node,NodeModel, UserModel,NodeHelper } from '../models/index';
class NodeController extends BaseController {
@router({
method: 'get',
path: '/api/nodes/:nodeId'
})
async find(req: ... | (req: e.Request, res: e.Response) {
if (req.params.ucId) {
let result = await Node.find({ ucId: req.params.ucId });
res.send(super.wrapperRes(result));
} else {
res.send(super.wrapperRes([]));
}
}
@router({
method: 'put',
path: '/api/ucs/:ucId/nodes'
})
async saveNode(req: e.Request, res: e.Resp... | getUcNodes | identifier_name |
NodeController.ts | import e = require('express');
import BaseController from "./BaseController";
import { router } from "../decorators/Web";
import { Node,NodeModel, UserModel,NodeHelper } from '../models/index';
class NodeController extends BaseController {
@router({
method: 'get',
path: '/api/nodes/:nodeId'
})
async find(req: ... |
}
@router({
method: 'put',
path: '/api/ucs/:ucId/nodes'
})
async saveNode(req: e.Request, res: e.Response) {
let user: UserModel = super.getUser(req);
let node: NodeModel = NodeHelper.buildModel(req.body);
if (req.body._id) {
node.setModifiedInfo(user);
let result = await Node.update(node);
... | {
res.send(super.wrapperRes([]));
} | conditional_block |
NodeController.ts | import e = require('express');
import BaseController from "./BaseController";
import { router } from "../decorators/Web";
import { Node,NodeModel, UserModel,NodeHelper } from '../models/index';
class NodeController extends BaseController {
@router({
method: 'get',
path: '/api/nodes/:nodeId'
})
async find(req: ... | path: '/api/ucs/:ucId/nodes'
})
async getUcNodes(req: e.Request, res: e.Response) {
if (req.params.ucId) {
let result = await Node.find({ ucId: req.params.ucId });
res.send(super.wrapperRes(result));
} else {
res.send(super.wrapperRes([]));
}
}
@router({
method: 'put',
path: '/api/ucs/:ucId/no... |
@router({
method: 'get', | random_line_split |
index.js | import {getQueriesForElement} from './get-queries-for-element'
import * as queries from './queries'
import * as queryHelpers from './query-helpers'
export * from './queries'
export * from './wait-for'
export * from './wait-for-element-to-be-removed'
export {getDefaultNormalizer} from './matches'
export * from './get-n... | // "within" reads better in user-code
// "getQueriesForElement" reads better in library code
// so we have both
getQueriesForElement as within,
// export query utils under a namespace for convenience:
queries,
queryHelpers,
} |
export { | random_line_split |
sortedLastIndexBy.js | var baseIteratee = require('./_baseIteratee'),
baseSortedIndexBy = require('./_baseSortedIndexBy');
/**
* This method is like `_.sortedLastIndex` except that it accepts `iteratee`
* which is invoked for `value` and each element of `array` to compute their
* sort ranking. The iteratee is invoked with one argumen... | (array, value, iteratee) {
return baseSortedIndexBy(array, value, baseIteratee(iteratee), true);
}
module.exports = sortedLastIndexBy;
| sortedLastIndexBy | identifier_name |
sortedLastIndexBy.js | var baseIteratee = require('./_baseIteratee'),
baseSortedIndexBy = require('./_baseSortedIndexBy');
/**
* This method is like `_.sortedLastIndex` except that it accepts `iteratee`
* which is invoked for `value` and each element of `array` to compute their
* sort ranking. The iteratee is invoked with one argumen... |
module.exports = sortedLastIndexBy;
| {
return baseSortedIndexBy(array, value, baseIteratee(iteratee), true);
} | identifier_body |
sortedLastIndexBy.js | var baseIteratee = require('./_baseIteratee'),
baseSortedIndexBy = require('./_baseSortedIndexBy');
/**
* This method is like `_.sortedLastIndex` except that it accepts `iteratee`
* which is invoked for `value` and each element of `array` to compute their
* sort ranking. The iteratee is invoked with one argumen... | }
module.exports = sortedLastIndexBy; | * _.sortedLastIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, 'x');
* // => 1
*/
function sortedLastIndexBy(array, value, iteratee) {
return baseSortedIndexBy(array, value, baseIteratee(iteratee), true); | random_line_split |
adaline.py | #!/usr/bin/python2
import math, sys, time
def drange(start, stop, step): #Generator for step <1, from http://stackoverflow.com/questions/477486/python-decimal-range-step-value
r = start
while r < stop:
yield r
r += step
class adaline:
def __init__(self, w_vec):#, bias): #absorbed
... |
def train(self, s_vec_list, t_vec, rate):
if rate <= 0:
raise Exception('Rate not positive: ' + str(rate))
if len(s_vec_list) != len(t_vec):
raise Exception('Training set problem: input count does not match result count.')
insigFlag = False
loopCount = 0
... | yin += xx*ww
return yin | random_line_split |
adaline.py | #!/usr/bin/python2
import math, sys, time
def drange(start, stop, step): #Generator for step <1, from http://stackoverflow.com/questions/477486/python-decimal-range-step-value
|
class adaline:
def __init__(self, w_vec):#, bias): #absorbed
self.w_vec = w_vec
#self.bias = bias #absorbed
def transfer(self, yin, isTraining = False):
if isTraining: #training, f(yin) = yin
return yin
else: #not training, f(yin) = bipolar Heaviside step function... | r = start
while r < stop:
yield r
r += step | identifier_body |
adaline.py | #!/usr/bin/python2
import math, sys, time
def drange(start, stop, step): #Generator for step <1, from http://stackoverflow.com/questions/477486/python-decimal-range-step-value
r = start
while r < stop:
yield r
r += step
class adaline:
def __init__(self, w_vec):#, bias): #absorbed
... |
else:
raise Exception('Bad argument. Usage: adaline.py [-v|--verbose]')
numEpochs = 100
#ACTUAL
test_s_vec_list = [[1, 1, 1, 1], [-1, 1, -1, -1], [1, 1, 1, -1], [1, -1, -1, 1]]
test_t_vec = [1, 1, -1, -1]
#AND for 2
#test_s_vec_list = [[1, 1], [1, -1], [-1, 1], [-1, -1]]
#test_t_vec = [1, -1, -1, -1]
#AND for 4
#... | verbose_flag = True | conditional_block |
adaline.py | #!/usr/bin/python2
import math, sys, time
def | (start, stop, step): #Generator for step <1, from http://stackoverflow.com/questions/477486/python-decimal-range-step-value
r = start
while r < stop:
yield r
r += step
class adaline:
def __init__(self, w_vec):#, bias): #absorbed
self.w_vec = w_vec
#self.bias = bias #... | drange | identifier_name |
serializer.py | # Copyright 2013 IBM Corp.
#
# 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 agree... |
class NoOpSerializer(Serializer):
"""A serializer that does nothing."""
def serialize_entity(self, context, entity):
return entity
def deserialize_entity(self, context, entity):
return entity
| """Deserialize something from primitive form.
:param context: Security context
:param entity: Primitive to be deserialized
:returns: Deserialized form of entity
"""
pass | identifier_body |
serializer.py | # Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may | # not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# ... | random_line_split | |
serializer.py | # Copyright 2013 IBM Corp.
#
# 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 agree... | (Serializer):
"""A serializer that does nothing."""
def serialize_entity(self, context, entity):
return entity
def deserialize_entity(self, context, entity):
return entity
| NoOpSerializer | identifier_name |
invite_list.js | /**
A data model representing a list of Invites
@class InviteList
@extends Discourse.Model
@namespace Discourse
@module Discourse
**/
Discourse.InviteList = Discourse.Model.extend({
empty: (function() {
return this.blank('pending') && this.blank('redeemed');
}).property('pending.@each', 'redeemed.@ea... |
if (invitedList.redeemed) {
invitedList.redeemed = invitedList.redeemed.map(function(i) {
return Discourse.Invite.create(i);
});
}
invitedList.user = user;
return promise.resolve(Discourse.InviteList.create(invitedList));
}
});
return promis... | {
invitedList.pending = invitedList.pending.map(function(i) {
return Discourse.Invite.create(i);
});
} | conditional_block |
invite_list.js | /**
A data model representing a list of Invites
@class InviteList
@extends Discourse.Model
@namespace Discourse
@module Discourse
**/
Discourse.InviteList = Discourse.Model.extend({
empty: (function() {
return this.blank('pending') && this.blank('redeemed');
}).property('pending.@each', 'redeemed.@ea... | $.ajax({
url: "/users/" + (user.get('username_lower')) + "/invited.json",
success: function(result) {
var invitedList;
invitedList = result.invited_list;
if (invitedList.pending) {
invitedList.pending = invitedList.pending.map(function(i) {
return Discourse.... | findInvitedBy: function(user) {
var promise;
promise = new RSVP.Promise(); | random_line_split |
client.js | var PROPS = injectProps;
var hookOnReload = injectOnReload;
const io = require('socket.io-client');
const socket = io(`http://127.0.0.1:${PROPS.port}`);
const { id: ext_id } = chrome.runtime;
const onReload = (query = {}, cb) => {
query = Object.assign({
url: [`chrome-extension://${ext_id}/*`]
}, quer... |
socket.on('reload', onReload);
socket.on('reopen', onReopen); | chrome.tabs.create(new_tab);
});
cb(tabs);
} | random_line_split |
command.js | 'use strict';
/*
* Creates a fake project object for unit tests.
*
* @method getProject
* @private
*/
function getProject(options) {
options = options || {};
let root = options.root || 'default-root';
let pkg = options.pkg || {
version: '1.0.0'
};
return {
root,
pkg,
};
}
/*
* Creates ... |
module.exports = {
contextFor
}
| {
options = options || {};
let command = require(`../../lib/commands/${name}`);
command.project = getProject(options);
return command;
} | identifier_body |
command.js | 'use strict';
/*
* Creates a fake project object for unit tests.
*
* @method getProject
* @private
*/
function getProject(options) {
options = options || {};
let root = options.root || 'default-root';
let pkg = options.pkg || {
version: '1.0.0'
};
return {
root,
pkg,
};
}
/*
* Creates ... | (name, options) {
options = options || {};
let command = require(`../../lib/commands/${name}`);
command.project = getProject(options);
return command;
}
module.exports = {
contextFor
}
| contextFor | identifier_name |
command.js | 'use strict';
/*
* Creates a fake project object for unit tests.
*
* @method getProject
* @private
*/
function getProject(options) { | options = options || {};
let root = options.root || 'default-root';
let pkg = options.pkg || {
version: '1.0.0'
};
return {
root,
pkg,
};
}
/*
* Creates a context (`this`) for `ember-cli` command to be able to successfully
* execute and test `run` method.
*
* In unit tests, we could simpl... | random_line_split | |
apiServer.js | /* 實作 ck.Express 物件 for API Server */
class ApiServe | ck.Express {
static _addSlash (url) {
return url.indexOf(`/`) === 0 ? url : `/${url}`
}
static _genRouteFn (genFn) {
return async (req, res, next) => {
try {
await genFn(req, res, next)
} catch (e) {
next(e)
}
}
}
getGroupPath (group, version = require(`package... | r extends | identifier_name |
apiServer.js | /* 實作 ck.Express 物件 for API Server */
class ApiServer extends ck.Express {
static _addSlash (url) {
return url.indexOf(`/`) === 0 ? url : `/${url}`
}
static _genRouteFn (genFn) {
return async (req, res, next) => {
try {
await genFn(req, res, next)
} catch (e) {
next(e)
}... | const originalFn = router[method]
router[method] = (...args) => {
const lastArgIndex = args.length - 1
args[0] = ApiServer._addSlash(args[0])
args[lastArgIndex] = ApiServer._genRouteFn(args[lastArgIndex])
originalFn.apply(router, args)
}
}
return router
}
}
m... | createRouter (path = ``) {
const router = super.createRouter(path)
const methods = [`get`, `post`, `put`, `delete`]
for (const method of methods) { | random_line_split |
mod.rs | //! Provide helpers for making ioctl system calls
//!
//! Currently supports Linux on all architectures. Other platforms welcome!
//!
//! This library is pretty low-level and messy. `ioctl` is not fun.
//!
//! What is an `ioctl`?
//! ===================
//!
//! The `ioctl` syscall is the grab-bag syscall on POSIX syste... | mod platform;
pub use self::platform::*;
// liblibc has the wrong decl for linux :| hack until #26809 lands.
extern "C" {
#[doc(hidden)]
pub fn ioctl(fd: libc::c_int, req: libc::c_ulong, ...) -> libc::c_int;
}
/// A hack to get the macros to work nicely.
#[doc(hidden)]
pub use ::libc as libc; | #[path = "platform/dragonfly.rs"]
#[macro_use] | random_line_split |
lasduplicate.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
lasduplicate.py
---------------------
Date : September 2013
Copyright : (C) 2013 by Martin Isenburg
Email : martin near rapidlasso point com
************... | (LAStoolsAlgorithm):
LOWEST_Z = "LOWEST_Z"
UNIQUE_XYZ = "UNIQUE_XYZ"
SINGLE_RETURNS = "SINGLE_RETURNS"
RECORD_REMOVED = "RECORD_REMOVED"
def defineCharacteristics(self):
self.name, self.i18n_name = self.trAlgorithm('lasduplicate')
self.group, self.i18n_group = self.trAlgorithm('LAS... | lasduplicate | identifier_name |
lasduplicate.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
lasduplicate.py
---------------------
Date : September 2013
Copyright : (C) 2013 by Martin Isenburg
Email : martin near rapidlasso point com
************... |
def processAlgorithm(self, progress):
commands = [os.path.join(LAStoolsUtils.LAStoolsPath(), "bin", "lasduplicate")]
self.addParametersVerboseCommands(commands)
self.addParametersPointInputCommands(commands)
if self.getParameterValue(lasduplicate.LOWEST_Z):
commands.app... | self.name, self.i18n_name = self.trAlgorithm('lasduplicate')
self.group, self.i18n_group = self.trAlgorithm('LAStools')
self.addParametersVerboseGUI()
self.addParametersPointInputGUI()
self.addParameter(ParameterBoolean(lasduplicate.LOWEST_Z,
se... | identifier_body |
lasduplicate.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
lasduplicate.py
---------------------
Date : September 2013
Copyright : (C) 2013 by Martin Isenburg
Email : martin near rapidlasso point com
************... |
record_removed = self.getParameterValue(lasduplicate.RECORD_REMOVED)
if record_removed is not None and record_removed != "":
commands.append("-record_removed")
commands.append(record_removed)
self.addParametersPointOutputCommands(commands)
self.addParametersAddit... | commands.append("-single_returns") | conditional_block |
lasduplicate.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
lasduplicate.py
---------------------
Date : September 2013
Copyright : (C) 2013 by Martin Isenburg
Email : martin near rapidlasso point com
************... | * *
***************************************************************************
"""
__author__ = 'Martin Isenburg'
__date__ = 'September 2013'
__copyright__ = '(C) 2013, Martin Isenburg'
# This will get replaced with a git SHA1 when you do a git a... | * it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. * | random_line_split |
urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin |
urlpatterns = patterns(
'',
# Examples:
# url(r'^$', 'chatter.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'', include('chatter.base.urls')),
url(r'^admin/', include(admin.site.urls)),
)
# The documentation for authentication views can be found at:
# https://docs.dj... | random_line_split | |
index.d.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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 ap... | /**
* Table mapping data types to a list of data types to which data types can be safely cast.
*/
interface Table {
/**
* Mapping of a data type to a list of data types to which a data type can be safely cast.
*/
[key: string]: CastingTable;
}
/**
* Table mapping a data type to a list of data types to which a data... |
import { DataType } from '@stdlib/types/array';
| random_line_split |
yubico.py | - Python >= 2.5
import re
import os
import sys
import time
import socket
import urllib
import urllib2
import hmac
import base64
import hashlib
import threading
import logging
import traceback
from otp import OTP
from yubico_exceptions import *
try:
import httplib_ssl
except ImportError:
httplib_ssl = None
... | else:
return True
elif status == 'NO_SUCH_CLIENT':
raise InvalidClientIdError(self.client_id)
elif status == 'REPLAYED_OTP':
raise StatusCodeError(status)
return False
def generate_query_string(self, otp, nonce, timestamp=False, sl=None,
... | uery_string = self.parse_parameters_from_response(response)[1]
response = self.get_parameters_as_dictionary(query_string)
return response
| conditional_block |
yubico.py | - Python >= 2.5
import re
import os
import sys
import time
import socket
import urllib
import urllib2
import hmac
import base64
import hashlib
import threading
import logging
import traceback
from otp import OTP
from yubico_exceptions import *
try:
import httplib_ssl
except ImportError:
httplib_ssl = None
... | self, query_string):
""" Returns query string parameters as a dictionary. """
dictionary = dict([parameter.split('=') for parameter \
in query_string.split('&')])
return dictionary
def generate_request_urls(self):
"""
Returns a list of the API URLs.
... | et_parameters_as_dictionary( | identifier_name |
yubico.py | # - Python >= 2.5
import re
import os
import sys
import time
import socket
import urllib
import urllib2
import hmac
import base64
import hashlib
import threading
import logging
import traceback
from otp import OTP
from yubico_exceptions import *
try:
import httplib_ssl
except ImportError:
httplib_ssl = None
... | for otp in otps:
device_ids.add(otp.device_id)
# Check that all the OTPs contain same device id
if len(device_ids) != 1:
raise Exception('OTPs contain different device ids')
# Now we verify the OTPs and save the server response for each OTP.
# We need th... | device_ids = set() | random_line_split |
yubico.py | - Python >= 2.5
import re
import os
import sys
import time
import socket
import urllib
import urllib2
import hmac
import base64
import hashlib
import threading
import logging
import traceback
from otp import OTP
from yubico_exceptions import *
try:
import httplib_ssl
except ImportError:
httplib_ssl = None
... |
def verify(self, otp, timestamp=False, sl=None, timeout=None,
return_response=False):
"""
Returns True is the provided OTP is valid,
False if the REPLAYED_OTP status value is returned or the response
message signature verification failed and None for the rest of the
... | f use_https and not httplib_ssl:
raise Exception('SSL support not available')
if use_https and httplib_ssl and httplib_ssl.CA_CERTS == '':
raise Exception('If you want to validate server certificate,'
' you need to set CA_CERTS '
'... | identifier_body |
test_crop_op.py | # Copyright (c) 2018 PaddlePaddle Authors. 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 app... |
else:
self.attrs['shape'] = self.crop_shape
self.inputs = {
'X': np.random.random(self.x_shape).astype("float32"),
}
if self.offset_by_input:
self.inputs['Offsets'] = np.array(self.offsets).astype('int32')
else:
self.at... | self.inputs = {
'X': np.random.random(self.x_shape).astype("float32"),
'Y': np.random.random(self.crop_shape).astype("float32")
} | conditional_block |
test_crop_op.py | # Copyright (c) 2018 PaddlePaddle Authors. 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 app... | (TestCropOp):
def initTestCase(self):
self.x_shape = (4, 8, 16)
self.crop_shape = [2, 2, 3]
self.offsets = [1, 5, 3]
self.crop_by_input = True
class TestCase4(TestCropOp):
def initTestCase(self):
self.x_shape = (4, 4)
self.crop_shape = [4, 4]
self.offset... | TestCase3 | identifier_name |
test_crop_op.py | # Copyright (c) 2018 PaddlePaddle Authors. 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 app... |
class TestCase2(TestCropOp):
def initTestCase(self):
self.x_shape = (4, 8)
self.crop_shape = [4, 8]
self.offsets = [0, 0]
class TestCase3(TestCropOp):
def initTestCase(self):
self.x_shape = (4, 8, 16)
self.crop_shape = [2, 2, 3]
self.offsets = [1, 5, 3]
... | def initTestCase(self):
self.x_shape = (16, 8, 32)
self.crop_shape = [2, 2, 3]
self.offsets = [1, 5, 3] | identifier_body |
test_crop_op.py | # Copyright (c) 2018 PaddlePaddle Authors. 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 app... | self.crop_shape = [2, 2, 3]
self.offsets = [1, 5, 3]
class TestCase2(TestCropOp):
def initTestCase(self):
self.x_shape = (4, 8)
self.crop_shape = [4, 8]
self.offsets = [0, 0]
class TestCase3(TestCropOp):
def initTestCase(self):
self.x_shape = (4, 8, 16)
... |
class TestCase1(TestCropOp):
def initTestCase(self):
self.x_shape = (16, 8, 32) | random_line_split |
admin.js | clicked),
$tab = $this.closest('.nav-tab');
if (!$this.hasClass('nav-tab-active')) {
$this.addClass('nav-tab-active');
$tab.siblings().removeClass('nav-tab-active');
this.switchWPFormat($this.attr('href'));
}
},
switchWPFormat: function(formatHash) {
$(formatHash).t... | this.el.innerHTML = 'Working...';
// $('#post-format-gallery-items').html( loadImages(ids) );
// frame.close();
$.ajax({
type: 'POST',
url: ajaxurl,
data: {
ids: ids,
action: 'save_gallery_images',
post_id: $('#... | {
frame.toolbar.get('view').set({
insert: {
style: 'primary',
text: 'Create Gallery',
click: function() {
var models = frame.state().get('library'),
ids = '';
items = '';
models.each( function( attachment ) {
console.log('attachment... | identifier_body |
admin.js | $(clicked),
$tab = $this.closest('.nav-tab');
if (!$this.hasClass('nav-tab-active')) {
$this.addClass('nav-tab-active');
$tab.siblings().removeClass('nav-tab-active');
this.switchWPFormat($this.attr('href'));
}
},
switchWPFormat: function(formatHash) {
$(formatHash... | (images) {
if( images ){
var shortcode = new wp.shortcode({
tag: 'gallery',
attrs: { ids: images },
type: 'single'
});
console.log('Shortcode: ', shortcode);
var attachments = wp.media.gallery.attachments( shortcode );
console.log('Attachments: '... | loadImages | identifier_name |
admin.js | $(clicked),
$tab = $this.closest('.nav-tab');
if (!$this.hasClass('nav-tab-active')) {
$this.addClass('nav-tab-active');
$tab.siblings().removeClass('nav-tab-active');
this.switchWPFormat($this.attr('href'));
}
},
switchWPFormat: function(formatHash) {
$(formatHash... | $('#postimagediv-placeholder').replaceWith($('#postimagediv'));
},
quote: function() {
$('#cfpf-format-link-url, #cfpf-format-video-fields, #cfpf-format-audio-fields, #cfpf-format-gallery-preview').hide();
$('#titlewrap, #cfpf-format-quote-fields').show().find(':input:first').focus();
$('#p... | random_line_split | |
bolly.py | #! /usr/bin/env python3
from bollinger import bands, plot, strategies
import argparse
parser = argparse.ArgumentParser(description="plots bollinger bands or suggests investments", epilog="example: bolly.py plot AMZN FB")
parser.add_argument("action", metavar="ACTION", choices=["plot", "suggest"], help="either plot o... | for symbol in args.symbols:
print("suggest [ %s ]: " %(symbol), end="")
b = bands.Bands(symbol)
b.fetch()
try:
if args.strategy == "uponce": s = strategies.UpOnce(b)
elif args.strategy == "downonce": s = strategies.DownOnce(b)
elif args.strategy == "mo... | conditional_block | |
bolly.py | #! /usr/bin/env python3
from bollinger import bands, plot, strategies
import argparse
parser = argparse.ArgumentParser(description="plots bollinger bands or suggests investments", epilog="example: bolly.py plot AMZN FB")
parser.add_argument("action", metavar="ACTION", choices=["plot", "suggest"], help="either plot o... | b = bands.Bands(symbol)
b.fetch()
try:
if args.strategy == "uponce": s = strategies.UpOnce(b)
elif args.strategy == "downonce": s = strategies.DownOnce(b)
elif args.strategy == "moreup": s = strategies.MoreUp(b)
elif args.strategy == "moredown": s ... | print("suggest [ %s ]: " %(symbol), end="") | random_line_split |
debugSmoke.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | await this.editors.waitForEditorFocus('launch.json');
}
async setBreakpointOnLine(lineNumber: number): Promise<any> {
await this.code.waitForElement(`${GLYPH_AREA}(${lineNumber})`);
await this.code.waitAndClick(`${GLYPH_AREA}(${lineNumber})`, 5, 5);
await this.code.waitForElement(BREAKPOINT_GLYPH);
}
asyn... | async configure(): Promise<any> {
await this.code.waitAndClick(CONFIGURE); | random_line_split |
debugSmoke.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | else {
await this.code.dispatchKeybinding('ctrl+shift+d');
}
await this.code.waitForElement(DEBUG_VIEW);
}
async configure(): Promise<any> {
await this.code.waitAndClick(CONFIGURE);
await this.editors.waitForEditorFocus('launch.json');
}
async setBreakpointOnLine(lineNumber: number): Promise<any> {
... | {
await this.code.dispatchKeybinding('cmd+shift+d');
} | conditional_block |
debugSmoke.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
async startDebugging(): Promise<number> {
await this.code.dispatchKeybinding('f5');
await this.code.waitForElement(PAUSE);
await this.code.waitForElement(DEBUG_STATUS_BAR);
const portPrefix = 'Port: ';
const output = await this.waitForOutput(output => output.some(line => line.indexOf(portPrefix) >= 0));
... | {
await this.code.waitForElement(`${GLYPH_AREA}(${lineNumber})`);
await this.code.waitAndClick(`${GLYPH_AREA}(${lineNumber})`, 5, 5);
await this.code.waitForElement(BREAKPOINT_GLYPH);
} | identifier_body |
debugSmoke.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (): Promise<any> {
await this.code.waitAndClick(STOP);
await this.code.waitForElement(TOOLBAR_HIDDEN);
await this.code.waitForElement(NOT_DEBUG_STATUS_BAR);
}
async waitForStackFrame(func: (stackFrame: IStackFrame) => boolean, message: string): Promise<IStackFrame> {
const elements = await this.code.waitForE... | stopDebugging | identifier_name |
gruntfile.js | 'use strict';
module.exports = function(grunt) {
// Unified Watch Object
var watchFiles = {
serverViews: ['app/views/**/*.*'],
serverJS: ['gruntfile.js', 'server.js', 'config/**/*.js', 'app/**/*.js'],
clientViews: ['public/modules/**/views/**/*.html'],
clientJS: ['public/js/*.js', 'public/modules/**/*.js'],
... | };
grunt.loadNpmTasks('grunt-contrib-less');
// Project Configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
serverViews: {
files: watchFiles.serverViews,
options: {
livereload: true
}
},
serverJS: {
files: watchFiles.serverJS,
tasks: ['jshint']... | clientLESS: ['public/less/**/*.less', 'public/modules/**/*.less'],
mochaTests: ['app/tests/**/*.js'] | random_line_split |
codes.js | // This module is compiled away!
//
// micromark works based on character codes.
// This module contains constants for the ASCII block and the replacement
// character.
// A couple of them are handled in a special way, such as the line endings
// (CR, LF, and CR+LF, commonly known as end-of-line: EOLs), the tab (horizo... | exports.enq = 5
exports.ack = 6
exports.bel = 7
exports.bs = 8
exports.ht = 9 // `\t`
exports.lf = 10 // `\n`
exports.vt = 11 // `\v`
exports.ff = 12 // `\f`
exports.cr = 13 // `\r`
exports.so = 14
exports.si = 15
exports.dle = 16
exports.dc1 = 17
exports.dc2 = 18
exports.dc3 = 19
exports.dc4 = 20
exports.nak = 21
expo... | exports.eot = 4 | random_line_split |
libraries.py | valid.
"""
mounts = {}
contents = self._contents
masked = self._masked
for item in items:
mountpoint = item.mountpoint
if mountpoint not in mounts:
is_mounted = ismount(mountpoint)
# In case mountpoint is mounted throug... | """List of mount points that contain masked items"""
return list(self._masked.keys()) | identifier_body | |
libraries.py | Load many items into the library (on start)"""
# Subclasses should override this if they want to check
# item validity; see `FileLibrary`.
content = self._contents
for item in items:
content[item.key] = item
def | (self, items):
"""Add items. This causes an 'added' signal.
Return the sequence of items actually added, filtering out items
already in the library.
"""
items = {item for item in items if item not in self}
if not items:
return items
print_d("Adding ... | add | identifier_name |
libraries.py | Load many items into the library (on start)"""
# Subclasses should override this if they want to check
# item validity; see `FileLibrary`.
content = self._contents
for item in items:
content[item.key] = item
def add(self, items):
"""Add items. This causes an 'add... |
def iter_paths(root, exclude=[], skip_hidden=True):
"""yields paths contained in root (symlinks dereferenced)
Any path starting with any of the path parts included in exclude
| random_line_split | |
libraries.py | , changed=None):
"""Rename a song.
This requires a special method because it can change the
song's key.
The 'changed' signal may fire for this library or the changed
song is added to the passed changed set().
If the song exists in multiple libraries you cannot use this... | last_yield[0] = current
return True | conditional_block | |
FriendDetail.spec.js | import React from 'react';
import { render } from 'react-testing-library';
import { MemoryRouter } from 'react-router-dom';
import ThemeProvider from '../theme/Provider';
import FriendDetail from './FriendDetail';
describe('./friend-detail/FriendDetail', () => {
it('renders loading if friend isn`t loaded yet', () =... | <MemoryRouter>
<ThemeProvider>
<FriendDetail friend={friend} />
</ThemeProvider>
</MemoryRouter>
);
expect(context.queryByText('Loading...')).not.toBeNull();
});
it('renders a friend if friend is loaded', () => {
const friend = {
name: 'Mr. Smidgens',
... | random_line_split | |
tournament.rs | #![feature(slice_patterns)]
#![feature(convert)]
use std::fs::File;
use std::path::Path;
use std::io::Read;
extern crate tournament;
fn file_equal(output_file: &str, expected_file: &str) {
let output = match File::open(&Path::new(output_file)) {
Err(e) => panic!("Couldn't open {}: {}", output_file, e),
... | {
assert_eq!(tournament::tally(&Path::new("tests/input3.txt"), &Path::new("tests/output3.txt")), Ok(4));
file_equal("tests/output3.txt", "tests/expected3.txt");
} | identifier_body | |
tournament.rs | #![feature(slice_patterns)]
#![feature(convert)]
use std::fs::File;
use std::path::Path;
use std::io::Read;
extern crate tournament;
fn file_equal(output_file: &str, expected_file: &str) {
let output = match File::open(&Path::new(output_file)) {
Err(e) => panic!("Couldn't open {}: {}", output_file, e),
... | () {
assert_eq!(tournament::tally(&Path::new("tests/input3.txt"), &Path::new("tests/output3.txt")), Ok(4));
file_equal("tests/output3.txt", "tests/expected3.txt");
}
| test_incomplete_competition | identifier_name |
tournament.rs | #![feature(slice_patterns)]
#![feature(convert)]
use std::fs::File;
use std::path::Path;
use std::io::Read;
extern crate tournament;
fn file_equal(output_file: &str, expected_file: &str) {
let output = match File::open(&Path::new(output_file)) {
Err(e) => panic!("Couldn't open {}: {}", output_file, e),
... | file_equal("tests/output3.txt", "tests/expected3.txt");
} | fn test_incomplete_competition() {
assert_eq!(tournament::tally(&Path::new("tests/input3.txt"), &Path::new("tests/output3.txt")), Ok(4)); | random_line_split |
channels.ts | import { AnyAction } from 'redux';
import { Download } from '../downloads/common';
import { Server } from '../servers/common';
import { SystemIdleState } from '../userPresence/common';
type ChannelToArgsMap = {
'redux/get-initial-state': () => unknown;
'redux/action-dispatched': (action: AnyAction) => void;
'se... | ) => Electron.DesktopCapturerSource[];
};
export type Channel = keyof ChannelToArgsMap;
export type Handler<N extends Channel> = ChannelToArgsMap[N]; | 'downloads/remove': (itemId: Download['itemId']) => void;
'server-view/get-url': () => Server['url'] | undefined;
'server-view/ready': () => void;
'desktop-capturer-get-sources': (
options: Electron.SourcesOptions | random_line_split |
info-modal.ts | import { Component, OnDestroy, OnInit } from "@angular/core";
import { Page } from "tns-core-modules/ui/page";
import { PluginInfo } from "~/shared/plugin-info";
import { openUrl } from "tns-core-modules/utils/utils";
import { PluginInfoWrapper } from "~/shared/plugin-info-wrapper";
import { addTabletCss } from "~/util... | () {
this.queryParamsSubscription.unsubscribe();
}
openPluginUrl(pluginInfo: PluginInfo): void {
// open in the default browser
openUrl(pluginInfo.url);
}
back() {
this.routerExtensions.back();
}
}
| ngOnDestroy | identifier_name |
info-modal.ts | import { Component, OnDestroy, OnInit } from "@angular/core";
import { Page } from "tns-core-modules/ui/page";
import { PluginInfo } from "~/shared/plugin-info";
import { openUrl } from "tns-core-modules/utils/utils";
import { PluginInfoWrapper } from "~/shared/plugin-info-wrapper";
import { addTabletCss } from "~/util... | export class InfoModalComponent implements OnInit, OnDestroy {
pluginInfo: PluginInfoWrapper;
private queryParamsSubscription: any;
constructor(private page: Page,
private route: ActivatedRoute,
private routerExtensions: RouterExtensions) {
// if (page.android) {
// this.pa... | styleUrls: ["./info-modal-common.css"]
}) | random_line_split |
info-modal.ts | import { Component, OnDestroy, OnInit } from "@angular/core";
import { Page } from "tns-core-modules/ui/page";
import { PluginInfo } from "~/shared/plugin-info";
import { openUrl } from "tns-core-modules/utils/utils";
import { PluginInfoWrapper } from "~/shared/plugin-info-wrapper";
import { addTabletCss } from "~/util... |
ngOnDestroy() {
this.queryParamsSubscription.unsubscribe();
}
openPluginUrl(pluginInfo: PluginInfo): void {
// open in the default browser
openUrl(pluginInfo.url);
}
back() {
this.routerExtensions.back();
}
}
| {
this.queryParamsSubscription = this.route
.queryParams
.subscribe(params => this.pluginInfo = JSON.parse(params['pluginInfo']));
} | identifier_body |
generic.py | # Copyright 2020 Red Hat, Inc. Jake Hunsaker <jhunsake@redhat.com>
# This file is part of the sos project: https://github.com/sosreport/sos
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# version 2 of the GNU General ... | """A generic tar archive that is not associated with any known or supported
collection utility
"""
type_name = 'tarball'
description = 'unassociated tarball'
@classmethod
def check_is_type(cls, arc_path):
try:
return tarfile.is_tarfile(arc_path)
except Exception:
... | identifier_body | |
generic.py | # Copyright 2020 Red Hat, Inc. Jake Hunsaker <jhunsake@redhat.com>
# This file is part of the sos project: https://github.com/sosreport/sos
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# version 2 of the GNU General ... | type_name = 'tarball'
description = 'unassociated tarball'
@classmethod
def check_is_type(cls, arc_path):
try:
return tarfile.is_tarfile(arc_path)
except Exception:
return False
def set_archive_root(self):
if self.tarobj.firstmember.isdir():
... | """
| random_line_split |
generic.py | # Copyright 2020 Red Hat, Inc. Jake Hunsaker <jhunsake@redhat.com>
# This file is part of the sos project: https://github.com/sosreport/sos
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# version 2 of the GNU General ... |
return ''
| return self.tarobj.firstmember.name | conditional_block |
generic.py | # Copyright 2020 Red Hat, Inc. Jake Hunsaker <jhunsake@redhat.com>
# This file is part of the sos project: https://github.com/sosreport/sos
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# version 2 of the GNU General ... | (SoSObfuscationArchive):
"""A plain directory on the filesystem that is not directly associated with
any known or supported collection utility
"""
type_name = 'data_dir'
description = 'unassociated directory'
@classmethod
def check_is_type(cls, arc_path):
return os.path.isdir(arc_p... | DataDirArchive | identifier_name |
LibCache.ts | /*
The MIT License (MIT)
Copyright (c) 2014 Joel Takvorian, https://github.com/jotak/mipod
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the righ... |
static saveTags(filepath: string, data: ThemeTags): q.Promise<string> {
var deferred: q.Deferred<string> = q.defer<string>();
fs.writeFile(filepath, JSON.stringify(data, null, 2), function(err) {
if (err) {
deferred.reject(new Error(err.code));
} else {
... | {
var deferred: q.Deferred<ThemeTags> = q.defer<ThemeTags>();
fs.readFile(filepath, {encoding: "utf8"}, function(err, data) {
if (err) {
deferred.reject(err);
} else {
var jsonContent: ThemeTags = eval('(' + data + ')');
deferred.re... | identifier_body |
LibCache.ts | /*
The MIT License (MIT)
Copyright (c) 2014 Joel Takvorian, https://github.com/jotak/mipod
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the righ... | (filepath: string): q.Promise<SongInfo[]> {
var deferred: q.Deferred<SongInfo[]> = q.defer<SongInfo[]>();
fs.readFile(filepath, {encoding: "utf8"}, function(err, data) {
if (err) {
deferred.reject(err);
} else {
var jsonContent: SongInfo[] = eval('... | loadCache | identifier_name |
LibCache.ts | /*
The MIT License (MIT)
Copyright (c) 2014 Joel Takvorian, https://github.com/jotak/mipod
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the righ... | }
}
export = LibCache; | } else {
deferred.resolve("OK");
}
});
return deferred.promise; | random_line_split |
LibCache.ts | /*
The MIT License (MIT)
Copyright (c) 2014 Joel Takvorian, https://github.com/jotak/mipod
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the righ... | else {
var jsonContent: ThemeTags = eval('(' + data + ')');
deferred.resolve(jsonContent);
}
});
return deferred.promise;
}
static saveTags(filepath: string, data: ThemeTags): q.Promise<string> {
var deferred: q.Deferred<string> = q.defer<str... | {
deferred.reject(err);
} | conditional_block |
smanager.py | import os
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
# create our little application :)
app = Flask(__name__)
app.config.from_object(__name__)
# Load default config and override config from an environment variable
app.config.update(dict(
DATABAS... | def close_db(error):
"""Closes the database again at the end of the request."""
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()
def init_db():
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
@app.cli.command('init... | @app.teardown_appcontext | random_line_split |
smanager.py | import os
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
# create our little application :)
app = Flask(__name__)
app.config.from_object(__name__)
# Load default config and override config from an environment variable
app.config.update(dict(
DATABAS... |
# update a selected entry
@app.route('/update/<int:story_id>', methods=['POST'])
def update_story(story_id):
if session.get('logged_in'):
db = get_db()
db.execute('UPDATE entries SET story_title=?, user_story=?,\
acceptance_criteria=?, business_value=?, estimation=?,\
... | flash('please log in first')
return redirect(url_for('login')) | conditional_block |
smanager.py | import os
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
# create our little application :)
app = Flask(__name__)
app.config.from_object(__name__)
# Load default config and override config from an environment variable
app.config.update(dict(
DATABAS... | ():
"""Connects to the database."""
rv = sqlite3.connect(app.config['DATABASE'])
rv.row_factory = sqlite3.Row
return rv
def get_db():
"""Opens a new database connection if there is none yet for the
current application context."""
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = connec... | connect_db | identifier_name |
smanager.py | import os
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
# create our little application :)
app = Flask(__name__)
app.config.from_object(__name__)
# Load default config and override config from an environment variable
app.config.update(dict(
DATABAS... |
# view all entries in the database
@app.route('/')
@app.route('/list')
def list_entries():
if session.get('logged_in'):
db = get_db()
cur = db.execute('SELECT id, story_title, user_story, acceptance_criteria,\
business_value, estimation, status FROM entries ORDER BY id DESC')
... | """Initializes the database."""
init_db()
print('Initialized the database.') | identifier_body |
mixins.py | import Certifiable
from lino.mixins.periods import rangefmt
from .choicelists import ConfirmationStates
from .roles import AidsStaff
def e2text(v):
return tostring(v)
# if isinstance(v, types.GeneratorType):
# return "".join([e2text(x) for x in v])
# if E.iselement(v):
# return tostring(... | self.language = obj.language | conditional_block | |
mixins.py |
from lino.modlib.checkdata.choicelists import Checker
from lino.modlib.users.mixins import UserAuthored
from lino_xl.lib.contacts.mixins import ContactRelated
from lino_xl.lib.excerpts.mixins import Certifiable
from lino.mixins.periods import rangefmt
from .choicelists import ConfirmationStates
from .roles import Ai... | (
Confirmable, UserAuthored, ContactRelated,
mixins.Created, Certifiable):
"""Base class for all aid confirmations.
Subclassed by :class:`SimpleConfirmation
<lino_welfare.modlib.aids.models.SimpleConfirmation>`,
:class:`IncomeConfirmation
<lino_welfare.modlib.aids.models.IncomeConfi... | Confirmation | identifier_name |
mixins.py |
from lino.modlib.checkdata.choicelists import Checker
from lino.modlib.users.mixins import UserAuthored
from lino_xl.lib.contacts.mixins import ContactRelated
from lino_xl.lib.excerpts.mixins import Certifiable
from lino.mixins.periods import rangefmt
from .choicelists import ConfirmationStates
from .roles import Ai... | and self.signer is not None \
and self.signer != ar.get_user():
return ba.action.readonly
return True
def disabled_fields(self, ar):
if self.state != ConfirmationStates.requested:
return self.CONFIRMED_FIELDS
return super(Confirmable, self).disa... |
"""
if not super(Confirmable, self).get_row_permission(ar, state, ba):
return False
if self.state == ConfirmationStates.confirmed \ | random_line_split |
mixins.py |
from lino.modlib.checkdata.choicelists import Checker
from lino.modlib.users.mixins import UserAuthored
from lino_xl.lib.contacts.mixins import ContactRelated
from lino_xl.lib.excerpts.mixins import Certifiable
from lino.mixins.periods import rangefmt
from .choicelists import ConfirmationStates
from .roles import Ai... |
@classmethod
def get_simple_parameters(cls):
for p in super(Confirmable, cls).get_simple_parameters():
yield p
yield 'signer'
yield 'state'
def full_clean(self):
super(Confirmable, self).full_clean()
if self.signer is None and self.state == Confirmation... | fields.update(signer=dd.ForeignKey(
settings.SITE.user_model,
verbose_name=pgettext("aids", "Signer"),
blank=True, null=True))
fields.update(state=ConfirmationStates.field(blank=True))
super(Confirmable, cls).setup_parameters(fields) | identifier_body |
selftest.py | # Sort of an experiment in thread programming. This script locates all
# ASCEND files in the ASCENDLIBRARY path, then for any that contain 'self_test'
# methods, it loads them and solves them and runs the self test. It's not
# very good at checking the results just yet: probably there needs to be a
# 'TestReporter' hoo... |
def run(self):
inspectlock.acquire()
try:
(path,file) = os.path.split(self.filepath)
#print "Checking",self.filepath,"for '"+TEST_METHOD_NAME+"' method"
size = os.path.getsize(self.filepath)
#print "File size is",size
if size > 0:
f = open(self.filepath,'r')
s = mmap.mmap(f.fileno(... | self.filepath = filepath; | identifier_body |
selftest.py | # Sort of an experiment in thread programming. This script locates all
# ASCEND files in the ASCENDLIBRARY path, then for any that contain 'self_test'
# methods, it loads them and solves them and runs the self test. It's not
# very good at checking the results just yet: probably there needs to be a
# 'TestReporter' hoo... | (self):
ascendlock.acquire()
try:
L = ascpy.Library()
L.clear()
L.load(self.filepath)
t = L.findType(self.modelname)
testmethod = None
for m in t.getMethods():
if m.getName()==TEST_METHOD_NAME:
testmethod = m;
if not testmethod:
raise RuntimeError("No method '"+TEST_METHOD_NAME+"'... | run | identifier_name |
selftest.py | # Sort of an experiment in thread programming. This script locates all
# ASCEND files in the ASCENDLIBRARY path, then for any that contain 'self_test'
# methods, it loads them and solves them and runs the self test. It's not
# very good at checking the results just yet: probably there needs to be a
# 'TestReporter' hoo... |
else:
self.separator=":"
print 'Search path:',self.path
for p in self.path.split(self.separator):
j = AscendScanDirectory(p)
jobslock.acquire()
heapq.heappush(jobs, (20,j) )
jobslock.release()
def run(self,num_threads):
for i in range(num_threads):
t = AscendModelLibraryTester.D... | self.separator=";" | conditional_block |
selftest.py | # Sort of an experiment in thread programming. This script locates all
# ASCEND files in the ASCENDLIBRARY path, then for any that contain 'self_test'
# methods, it loads them and solves them and runs the self test. It's not
# very good at checking the results just yet: probably there needs to be a
# 'TestReporter' hoo... | for t in L.getModuleTypes(M):
#print "Looking at type '"+str(t.getName())+"'"
for m in t.getMethods():
#print "Looking at method '"+str(m.getName())+"'"
if m.getName()==TEST_METHOD_NAME:
jobslock.acquire()
heapq.heappush(jobs, (0, AscendTestModel( self.filepath,t.getName().toString())) ... | L.load(self.filepath)
for M in L.getModules():
print "Looking at module '"+M.getName()+"'" | random_line_split |
index.test-d.ts | import {expectType, expectError, expectAssignable} from 'tsd';
import {readPackage, readPackageSync, NormalizedPackageJson, PackageJson} from './index.js';
expectError<NormalizedPackageJson>({});
expectAssignable<PackageJson>({});
expectType<Promise<NormalizedPackageJson>>(readPackage());
expectType<Promise<Normalize... | expectType<NormalizedPackageJson>(readPackageSync({cwd: '.'})); | random_line_split | |
main.js | var _debug = true;
var ajaxCalls = new Array();
var resultDisplayed = false;
$( document ).ready(function() {
$("#searchField").first().focus();
});
$('#advanced_link').click(function() {
$('#advanced_link').addClass("hide");
$('#row_advanced_search').removeClass("hide");
});
$('#combo_structure').chang... |
function cancelAjaxCalls() {
debug("Cancelling all ajax calls...");
debug(ajaxCalls);
ajaxCalls.forEach(function (a) {
a.abort();
ajaxCalls.slice(ajaxCalls.indexOf(a),1);
});
}
function debug(msg) {
if (_debug) {
console.log(msg);
}
} | {
if (!resultDisplayed)
{
$('#search').removeClass("vertical-center");
$('#search').addClass("top-search");
$('#column_logo').removeClass("small-12");
$('#column_logo').addClass("small-5");
$('#column_logo').addClass("medium-3");
$('#column_logo').addClass("large-... | identifier_body |
main.js | var _debug = true;
var ajaxCalls = new Array();
var resultDisplayed = false;
$( document ).ready(function() {
$("#searchField").first().focus();
});
$('#advanced_link').click(function() {
$('#advanced_link').addClass("hide");
$('#row_advanced_search').removeClass("hide");
});
$('#combo_structure').chang... | .always(function () {
debug("complete");
});
search();
});
$('#combo_sous_structure').change(function() {
search();
});
$('#searchField').on('input', function (e) {
cancelAjaxCalls();
search();
});
function search() {
text = $('#searchField').val();
if (text.len... | })
.fail(function () {
debug("error");
}) | random_line_split |
main.js | var _debug = true;
var ajaxCalls = new Array();
var resultDisplayed = false;
$( document ).ready(function() {
$("#searchField").first().focus();
});
$('#advanced_link').click(function() {
$('#advanced_link').addClass("hide");
$('#row_advanced_search').removeClass("hide");
});
$('#combo_structure').chang... | (msg) {
if (_debug) {
console.log(msg);
}
} | debug | identifier_name |
main.js | var _debug = true;
var ajaxCalls = new Array();
var resultDisplayed = false;
$( document ).ready(function() {
$("#searchField").first().focus();
});
$('#advanced_link').click(function() {
$('#advanced_link').addClass("hide");
$('#row_advanced_search').removeClass("hide");
});
$('#combo_structure').chang... |
}
function displayResult() {
if (!resultDisplayed)
{
$('#search').removeClass("vertical-center");
$('#search').addClass("top-search");
$('#column_logo').removeClass("small-12");
$('#column_logo').addClass("small-5");
$('#column_logo').addClass("medium-3");
$('#... | {
$("#row_result").html('');
$("#row_result").removeClass('loading');
} | conditional_block |
errors.ts | import {
AnyJson,
checkIsString,
getRefinement,
isDefined,
checkIsNonEmptyArray,
JsonMap,
NonEmptyArray,
Nullable,
} from './typescript';
export type Errors = NonEmptyArray<string>;
export type ErrorSource = 'api' | 'decoding';
const checkIsObject = getRefinement(
(response: AnyJson): Nullable<JsonM... | {
constructor(readonly message: string) {}
}
| DecodingError | identifier_name |
errors.ts | import {
AnyJson,
checkIsString,
getRefinement,
isDefined,
checkIsNonEmptyArray,
JsonMap,
NonEmptyArray,
Nullable,
} from './typescript';
export type Errors = NonEmptyArray<string>;
export type ErrorSource = 'api' | 'decoding';
const checkIsObject = getRefinement(
(response: AnyJson): Nullable<JsonM... |
};
export class DecodingError {
constructor(readonly message: string) {}
}
| {
return {
errors: [
'Responded with a status code outside the 2xx range, and the response body is not recognisable.',
],
source: 'decoding',
};
} | conditional_block |
errors.ts | import {
AnyJson,
checkIsString,
getRefinement,
isDefined,
checkIsNonEmptyArray,
JsonMap,
NonEmptyArray,
Nullable,
} from './typescript';
export type Errors = NonEmptyArray<string>;
export type ErrorSource = 'api' | 'decoding';
const checkIsObject = getRefinement(
(response: AnyJson): Nullable<JsonM... | ): { errors: Errors; source: ErrorSource } => {
if (checkIsApiError(jsonResponse)) {
return { errors: jsonResponse.errors, source: 'api' };
} else {
return {
errors: [
'Responded with a status code outside the 2xx range, and the response body is not recognisable.',
],
source: 'deco... | random_line_split | |
start-webpack-server.ts | import openurl from "better-opn"
import report from "gatsby-cli/lib/reporter"
import chalk from "chalk"
import { Compiler } from "webpack"
import { Stage } from "../commands/types"
import {
reportWebpackWarnings,
structureWebpackErrors,
} from "../utils/webpack-error-utils"
import { printDeprecationWarnings } fro... | // webpack will not emit assets or `done` event until all pending invalidated
// inputs were compiled
webpackActivity = report.activityTimer(`Re-building development bundle`, {
id: `webpack-develop`,
})
webpackActivity.start()
}
done()
})
let isFirstCompile = true
... | {
if (!program || !app || !store) {
report.panic(`Missing required params`)
}
let { compiler, webpackActivity, websocketManager, webpackWatching } =
await startServer(program, app, workerPool)
compiler.hooks.invalid.tap(`log compiling`, function () {
if (!webpackActivity) {
// mark webpack as... | identifier_body |
start-webpack-server.ts | import openurl from "better-opn"
import report from "gatsby-cli/lib/reporter"
import chalk from "chalk"
import { Compiler } from "webpack"
import { Stage } from "../commands/types"
import {
reportWebpackWarnings,
structureWebpackErrors,
} from "../utils/webpack-error-utils"
import { printDeprecationWarnings } fro... | ({
program,
app,
workerPool,
store,
}: Partial<IBuildContext>): Promise<{
compiler: Compiler
websocketManager: WebsocketManager
webpackWatching: IWebpackWatchingPauseResume
}> {
if (!program || !app || !store) {
report.panic(`Missing required params`)
}
let { compiler, webpackActivity, websocket... | startWebpackServer | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.