file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
capsule.rs | //! Work wih Python capsules
//!
use libc::c_void;
use std::ffi::{CStr, CString, NulError};
use std::mem;
use super::object::PyObject;
use crate::err::{self, PyErr, PyResult};
use crate::ffi::{PyCapsule_GetPointer, PyCapsule_Import, PyCapsule_New};
use crate::python::{Python, ToPythonPointer};
/// Capsules are the pr... |
/// Creates a new capsule from a raw void pointer
///
/// This is suitable in particular to store a function pointer in a capsule. These
/// can be obtained simply by a simple cast:
///
/// ```
/// use libc::c_void;
///
/// extern "C" fn inc(a: i32) -> i32 {
/// a + 1
/... | {
Self::new(py, data as *const T as *const c_void, name)
} | identifier_body |
capsule.rs | //! Work wih Python capsules
//!
use libc::c_void;
use std::ffi::{CStr, CString, NulError};
use std::mem;
use super::object::PyObject;
use crate::err::{self, PyErr, PyResult};
use crate::ffi::{PyCapsule_GetPointer, PyCapsule_Import, PyCapsule_New};
use crate::python::{Python, ToPythonPointer};
/// Capsules are the pr... | (py: Python, name: &CStr) -> PyResult<*const c_void> {
let caps_ptr = unsafe { PyCapsule_Import(name.as_ptr(), 0) };
if caps_ptr.is_null() {
return Err(PyErr::fetch(py));
}
Ok(caps_ptr)
}
/// Convenience method to create a capsule for some data
///
/// The en... | import | identifier_name |
capsule.rs | //! Work wih Python capsules
//!
use libc::c_void;
use std::ffi::{CStr, CString, NulError};
use std::mem;
use super::object::PyObject;
use crate::err::{self, PyErr, PyResult};
use crate::ffi::{PyCapsule_GetPointer, PyCapsule_Import, PyCapsule_New};
use crate::python::{Python, ToPythonPointer};
/// Capsules are the pr... |
/// Convenience method to create a capsule for some data
///
/// The encapsuled data may be an array of functions, but it can't be itself a
/// function directly.
///
/// May panic when running out of memory.
///
pub fn new_data<T, N>(py: Python, data: &'static T, name: N) -> Result<Sel... | Ok(caps_ptr)
} | random_line_split |
environment-type-def.ts | export interface Environment {
readonly production: boolean;
readonly geoLocation: {
readonly timeoutMillis: number
readonly firefoxWorkaroundTimeoutMillis: number
readonly updateMillis: number
};
readonly gastroLocationsUrl: string;
readonly shoppingLocationsUrl?: string;
... | };
} | readonly website?: string
readonly map?: string | random_line_split |
product-item-container.component.ts | import { Component, Input } from '@angular/core';
import { AppActions } from '../../app/app.actions';
import { AppDispatcher } from '../../app/app.dispatcher';
import { Product } from '../../interfaces/product';
/**
*
*
* @export
* @class ProductItemContainerComponent
*/
@Component({
selector: 'product-item-... | patcher.emit(this.actions.addToCart(this.product));
}
}
| identifier_body | |
product-item-container.component.ts | import { Component, Input } from '@angular/core';
import { AppActions } from '../../app/app.actions';
import { AppDispatcher } from '../../app/app.dispatcher';
import { Product } from '../../interfaces/product';
/**
*
*
* @export
* @class ProductItemContainerComponent
*/
@Component({
selector: 'product-item-... | {
@Input() public key: number;
@Input() public product: null | Product;
/**
* Creates an instance of ProductItemContainerComponent.
*
* @param {AppActions} actions
* @param {AppDispatcher} dispatcher
*
* @memberOf ProductItemContainerComponent
*/
constructor(private actions: AppActions... | ProductItemContainerComponent | identifier_name |
product-item-container.component.ts | import { Component, Input } from '@angular/core';
import { AppActions } from '../../app/app.actions';
import { AppDispatcher } from '../../app/app.dispatcher';
import { Product } from '../../interfaces/product';
/**
*
*
* @export
* @class ProductItemContainerComponent
*/
@Component({
selector: 'product-item-... | *
* @memberOf ProductItemContainerComponent
*/
constructor(private actions: AppActions,
private dispatcher: AppDispatcher) {}
/**
* Add to cartが押された際のObserver
*
*
* @memberOf ProductItemContainerComponent
*/
public onAddToCartClicked() {
this.dispatcher.emit(this.acti... | * @param {AppActions} actions
* @param {AppDispatcher} dispatcher | random_line_split |
test.xpi.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
var fs = require("fs");
var path = require("path");
var utils = require("../utils");
var chai = requ... | fs.unlink(xpiPath);
done();
});
});
});
}); | utils.unzipTo(xpiPath, utils.tmpOutputDir).then(function () {
utils.compareDirs(simpleAddonPath, utils.tmpOutputDir); | random_line_split |
GameBoilerplate.tsx | import * as React from 'react';
import THREE = require('three');
import {addComponentCSS} from '../../utils/css_styler';
import {isGL} from "../../helpers/WebGL";
addComponentCSS({
//language=CSS
default: `
.empty {
}
`
});
interface IProps {}
interface IState {
isFallback?: boolean
}
export... | (): JSX.Element {
return (
<div>
{this.state.isFallback
? "Unable to view due to browser or browser settings. Try another browser or reconfigure your current browser."
: null}
</div>
);
}
}
| render | identifier_name |
GameBoilerplate.tsx | import * as React from 'react';
import THREE = require('three');
import {addComponentCSS} from '../../utils/css_styler';
import {isGL} from "../../helpers/WebGL";
addComponentCSS({
//language=CSS
default: `
.empty {
}
`
});
interface IProps {}
interface IState {
isFallback?: boolean
}
export... |
componentWillUnmount() {
window.removeEventListener( 'resize'
, () => this.onWindowResized(this.renderer), false );
cancelAnimationFrame(this.animateLoop);
if (isGL()) document.body.removeChild( this.renderer.domElement );
}
onWindowResized(renderer) {
renderer... | {
this.setState({ isFallback: true })
} | identifier_body |
GameBoilerplate.tsx | import * as React from 'react';
import THREE = require('three');
import {addComponentCSS} from '../../utils/css_styler';
import {isGL} from "../../helpers/WebGL";
addComponentCSS({
//language=CSS
default: `
.empty {
}
`
});
interface IProps {}
interface IState {
isFallback?: boolean
}
export... | } | random_line_split | |
raised-button.js | var React = require('react');
var Classable = require('./mixins/classable');
var EnhancedButton = require('./enhanced-button');
var Paper = require('./paper');
var RaisedButton = React.createClass({displayName: "RaisedButton",
mixins: [Classable],
propTypes: {
className: React.PropTypes.string,
label: fu... | initialZDepth: zDepth
};
},
componentWillReceiveProps: function(nextProps) {
var zDepth = nextProps.disabled ? 0 : 1;
this.setState({
zDepth: zDepth,
initialZDepth: zDepth
});
},
render: function() {
var $__0=
this.props,label=$__0.label,prim... | return {
zDepth: zDepth, | random_line_split |
raised-button.js | var React = require('react');
var Classable = require('./mixins/classable');
var EnhancedButton = require('./enhanced-button');
var Paper = require('./paper');
var RaisedButton = React.createClass({displayName: "RaisedButton",
mixins: [Classable],
propTypes: {
className: React.PropTypes.string,
label: fu... | }return rest;})($__0,{label:1,primary:1,secondary:1});
var classes = this.getClasses('mui-raised-button', {
'mui-is-primary': !this.props.disabled && primary,
'mui-is-secondary': !this.props.disabled && !primary && secondary
});
var children;
if (label) children = React.createElement("span"... | {rest[key] = source[key];} | conditional_block |
data.py | import math
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score, precision_score, recall_score
class Random2DGaussian(object):
min_x = 0
max_x = 10
min_y = 0
max_y = 10
def __init__(self):
self.mean = [(self.max_x-se... |
return np.array(X), np.array(Y)
def graph_data(X, Y, Y_, special=None):
correct_idx = (Y==Y_).T.flatten()
wrong_idx = (Y!=Y_).T.flatten()
s = np.ones(Y.shape) * 20
if special is not None:
s[special] *= 2
plt.scatter(X[correct_idx, 0], X[correct_idx, 1], c=Y_[correct_idx], marke... | gauss = Random2DGaussian()
j = np.random.randint(C)
x = gauss.get_sample(N)
X.extend(x)
y=[[j] for k in range(N)]
Y.extend(y) | conditional_block |
data.py | import math
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score, precision_score, recall_score
class Random2DGaussian(object):
min_x = 0
max_x = 10
min_y = 0
max_y = 10
def __init__(self):
self.mean = [(self.max_x-se... | D = [[eigval_x, 0], [0, eigval_y]]
angle = 2 * math.pi * np.random.random_sample()
R = [[math.cos(angle), -math.sin(angle)], [math.sin(angle), math.cos(angle)]]
self.cov = np.dot(np.dot(R, D), np.transpose(R))
def get_sample(self, n):
return np.random.multivariate_... | eigval_x = (np.random.random_sample() * (self.max_x - self.min_x) / 5)**2
eigval_y = (np.random.random_sample() * (self.max_y - self.min_y) / 5)**2 | random_line_split |
data.py | import math
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score, precision_score, recall_score
class Random2DGaussian(object):
min_x = 0
max_x = 10
min_y = 0
max_y = 10
def __init__(self):
|
def get_sample(self, n):
return np.random.multivariate_normal(self.mean, self.cov, size=n)
def sample_gmm_2d(K, C, N):
X, Y = [], []
for i in range(K):
gauss = Random2DGaussian()
j = np.random.randint(C)
x = gauss.get_sample(N)
X.extend(x)
y=[[j] for k ... | self.mean = [(self.max_x-self.min_x) * np.random.random_sample() + self.min_x,
(self.max_y-self.min_y) * np.random.random_sample() + self.min_y]
eigval_x = (np.random.random_sample() * (self.max_x - self.min_x) / 5)**2
eigval_y = (np.random.random_sample() * (self.max_y... | identifier_body |
data.py | import math
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score, precision_score, recall_score
class Random2DGaussian(object):
min_x = 0
max_x = 10
min_y = 0
max_y = 10
def | (self):
self.mean = [(self.max_x-self.min_x) * np.random.random_sample() + self.min_x,
(self.max_y-self.min_y) * np.random.random_sample() + self.min_y]
eigval_x = (np.random.random_sample() * (self.max_x - self.min_x) / 5)**2
eigval_y = (np.random.random_sample... | __init__ | identifier_name |
heuristic-instructions.py | import wasp
def onConflict():
"""
Optional.
A conflict happened during the solving
"""
pass
def onDeletion():
"""
Optional.
The method for deleting clauses is invoked.
"""
pass
def onLearningClause(lbd, size, *lits):
"""
Optional.
When a clause is learnt.
:para... | (*unfounded_set):
"""
Optional.
When an unfounded set is found.
:param unfounded_set: all atoms in the unfounded set
"""
pass
def initFallback():
"""
Optional.
Init the activities of variables in the fallback heuristic.
:return: List of pairs (v, i), the activity variable v is a... | onUnfoundedSet | identifier_name |
heuristic-instructions.py | import wasp
def onConflict():
"""
Optional.
A conflict happened during the solving
"""
pass
def onDeletion():
"""
Optional.
The method for deleting clauses is invoked.
"""
pass
def onLearningClause(lbd, size, *lits):
"""
Optional.
When a clause is learnt.
:para... | Special values:
- wasp.restart() force the solver to perform a restart
- wasp.fallback(n) use the fallback heuristic for n steps (n<=0 use always fallback heuristic) -> require the presence of the method fallback() in the script
- wasp.unroll(v) unroll the truth value of the variable v
:return: w... | Required.
This method is invoked when a choice is needed. It can return a choice and special
values for performing special actions. | random_line_split |
heuristic-instructions.py | import wasp
def onConflict():
"""
Optional.
A conflict happened during the solving
"""
pass
def onDeletion():
"""
Optional.
The method for deleting clauses is invoked.
"""
pass
def onLearningClause(lbd, size, *lits):
"""
Optional.
When a clause is learnt.
:para... |
def onLoopFormula(lbd, size, *lits):
"""
Optional.
When a loop formula is learnt for an unfounded set.
:param lbd: the lbd value of the loop formula
:param size: the size of the loop formula
:param lits: the literals in the loop formula
"""
pass
def onNewClause(*clause):
"""
O... | """
Optional.
When a literal is involved in the computation of the learned clause.
:param lit: the literal involved in the conflict
"""
pass | identifier_body |
tax_rate.js | Ext.define('TaxRate', {
extend: 'Ext.data.Model',
fields: [{name: "id"},
{name: "date",type: 'date',dateFormat: 'Y-m-d'},
{name: "rate"},
{name: "remark"},
{name: "create_time",type: 'date',dateFormat: 'timestamp'},
{name: "update_time",type:... | }
}
}, '->', {
text: '刷新',
iconCls: 'icon-refresh',
handler: function(){
taxRateStore.reload();
}
}],
plugins: taxRateRowEditing,
columns: [{
xtype: 'rownumberer'
}, {
text: 'ID',
dataIndex: 'id',
... | Ext.MessageBox.alert('提示', '没有修改任何数据!'); | random_line_split |
tax_rate.js | Ext.define('TaxRate', {
extend: 'Ext.data.Model',
fields: [{name: "id"},
{name: "date",type: 'date',dateFormat: 'Y-m-d'},
{name: "rate"},
{name: "remark"},
{name: "create_time",type: 'date',dateFormat: 'timestamp'},
{name: "update_time",type:... | changeRows.deleted.push(deleteRecords[i].data)
}
Ext.MessageBox.confirm('确认', '确定保存修改内容?', function(button, text){
if(button == 'yes'){
var json = Ext.JSON.encode(changeRows);
var selection = Ex... | eRows.inserted.push(data)
}
for(var i = 0; i < deleteRecords.length; i++){
| conditional_block |
ScheduledQueryRuns.d.ts | declare module 'stripe' {
namespace Stripe {
namespace Sigma {
/**
* The ScheduledQueryRun object.
*/
interface ScheduledQueryRun {
/**
* Unique identifier for the object.
*/
id: string;
/**
* String representing the object's type. Obje... | */
sql: string;
/**
* The query's execution status, which will be `completed` for successful runs, and `canceled`, `failed`, or `timed_out` otherwise.
*/
status: string;
/**
* Title of the query.
*/
title: string;
}
name... | * SQL for the query. | random_line_split |
ScheduledQueryRuns.d.ts | declare module 'stripe' {
namespace Stripe {
namespace Sigma {
/**
* The ScheduledQueryRun object.
*/
interface ScheduledQueryRun {
/**
* Unique identifier for the object.
*/
id: string;
/**
* String representing the object's type. Obje... | {
/**
* Retrieves the details of an scheduled query run.
*/
retrieve(
id: string,
params?: ScheduledQueryRunRetrieveParams,
options?: RequestOptions
): Promise<Stripe.Sigma.ScheduledQueryRun>;
retrieve(
id: string,
opti... | ScheduledQueryRunsResource | identifier_name |
gulpfile.js | 'use strict';
const gulp = require('gulp');
const autoprefixer = require('gulp-autoprefixer');
const browserSync = require('browser-sync').create();
const sass = require('gulp-sass');
const sassGlob = require('gulp-sass-glob');
const scssLint = require('gulp-scss-lint');
const webpack ... | gulp.src(scriptsDir + 'main.js')
.pipe(webpack(webpackConfig))
.on('error', webpackError)
.pipe(gulp.dest(publicDir))
.pipe(browserSync.stream());
});
gulp.task('scssLint', () => {
gulp.src(styles)
.pipe(scssLint({
'config': 'config/scss-lint.yml'
}));
});
gulp.task('sass', ['scssLin... | gulp.task('js', () => { | random_line_split |
gulpfile.js | 'use strict';
const gulp = require('gulp');
const autoprefixer = require('gulp-autoprefixer');
const browserSync = require('browser-sync').create();
const sass = require('gulp-sass');
const sassGlob = require('gulp-sass-glob');
const scssLint = require('gulp-scss-lint');
const webpack ... | () {
this.emit('end');
}
gulp.task('js', () => {
gulp.src(scriptsDir + 'main.js')
.pipe(webpack(webpackConfig))
.on('error', webpackError)
.pipe(gulp.dest(publicDir))
.pipe(browserSync.stream());
});
gulp.task('scssLint', () => {
gulp.src(styles)
.pipe(scssLint({
'config': 'config/scss... | webpackError | identifier_name |
gulpfile.js | 'use strict';
const gulp = require('gulp');
const autoprefixer = require('gulp-autoprefixer');
const browserSync = require('browser-sync').create();
const sass = require('gulp-sass');
const sassGlob = require('gulp-sass-glob');
const scssLint = require('gulp-scss-lint');
const webpack ... |
gulp.task('js', () => {
gulp.src(scriptsDir + 'main.js')
.pipe(webpack(webpackConfig))
.on('error', webpackError)
.pipe(gulp.dest(publicDir))
.pipe(browserSync.stream());
});
gulp.task('scssLint', () => {
gulp.src(styles)
.pipe(scssLint({
'config': 'config/scss-lint.yml'
}));
});
g... | {
this.emit('end');
} | identifier_body |
jnotify.js | // Copyright (C) 2011 Regis Houssin <regis@dolibarr.fr>
// Copyright (C) 2009 Laurent Destailleur <eldy@users.sourceforge.net>
//
// This program 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; eithe... | , classNotification: "jnotify-notification"
, classBackground: "jnotify-background"
, classClose: "jnotify-close"
, classMessage: "jnotify-message"
, init: null // callback that occurs when the main jnotify container is created
, create: null // ca... | , classContainer: "jnotify-container" | random_line_split |
loglisteners.js | (function() {
'use strict';
angular
.module('blocks.logger')
.factory('logListeners', logListeners);
/**
* @ngdoc service
* @name spaghetto.logger:logListeners
*
* @description
* Manage different log listeners so that log messages can have various
* destinatio... |
/**
* @ngdoc method
* @name getListeners
* @methodOf spaghetto.logger:logListeners
* @kind function
*
* @description
* returns all installed log listeners
*
* @return {Array} keys is the log listener name
* ... | {
delete listeners[name];
} | identifier_body |
loglisteners.js | (function() {
'use strict';
angular
.module('blocks.logger')
.factory('logListeners', logListeners);
/**
* @ngdoc service
* @name spaghetto.logger:logListeners
*
* @description
* Manage different log listeners so that log messages can have various
* destinatio... | addListener: addListener,
getListeners: getListeners,
removeListener: removeListener
};
return service;
///////////////
/**
* @ngdoc method
* @name addListener
* @methodOf spaghetto.logger:logListeners
* @kind func... | var listeners = {};
var service = { | random_line_split |
loglisteners.js | (function() {
'use strict';
angular
.module('blocks.logger')
.factory('logListeners', logListeners);
/**
* @ngdoc service
* @name spaghetto.logger:logListeners
*
* @description
* Manage different log listeners so that log messages can have various
* destinatio... | (name) {
delete listeners[name];
}
/**
* @ngdoc method
* @name getListeners
* @methodOf spaghetto.logger:logListeners
* @kind function
*
* @description
* returns all installed log listeners
*
* @return {Array} ... | removeListener | identifier_name |
ut.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# @file ut.py
# @brief The main unit test program of whole project
# README: organize the unit tests in the number range
# refer UTGeneral functions
# print the suggested procedure in the console
# print the suggested check procedure in the console
# support c... |
def test_04_check_grib(self):
import pygrib # import pygrib interface to grib_api
grbs = pygrib.open('include/M-A0060-000.grb2')
print("grbs[:4] count=%i" %(len(grbs[:4])))
def test_11_loadjson(self):
gc.LASSDATA.load_site_list()
print("LASS sites count = %i" % ... | pass | identifier_body |
ut.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# @file ut.py
# @brief The main unit test program of whole project
# README: organize the unit tests in the number range
# refer UTGeneral functions
# print the suggested procedure in the console
# print the suggested check procedure in the console
# support c... | gc.LASSDATA.load_site_list()
print("LASS sites count = %i" % (len(gc.LASSDATA.sites)))
self.assertTrue(len(gc.LASSDATA.sites)>0) |
def test_11_loadjson(self): | random_line_split |
ut.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# @file ut.py
# @brief The main unit test program of whole project
# README: organize the unit tests in the number range
# refer UTGeneral functions
# print the suggested procedure in the console
# print the suggested check procedure in the console
# support c... | (self):
print("\nThe expected unit test environment is")
print("1. TBD")
self.assertEqual(gc.SETTING["SIGNATURE"],'LASS-SIM')
def test_02_check_library(self):
#check external library that need to be installed
import simpy
from configobj import ConfigObj
... | test_01_setting_signature | identifier_name |
nul-characters.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 ... | ()
{
let all_nuls1 = "\0\x00\u0000\U00000000";
let all_nuls2 = "\U00000000\u0000\x00\0";
let all_nuls3 = "\u0000\U00000000\x00\0";
let all_nuls4 = "\x00\u0000\0\U00000000";
// sizes for two should suffice
assert_eq!(all_nuls1.len(), 4);
assert_eq!(all_nuls2.len(), 4);
// string equali... | main | identifier_name |
nul-characters.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 ... | {
let all_nuls1 = "\0\x00\u0000\U00000000";
let all_nuls2 = "\U00000000\u0000\x00\0";
let all_nuls3 = "\u0000\U00000000\x00\0";
let all_nuls4 = "\x00\u0000\0\U00000000";
// sizes for two should suffice
assert_eq!(all_nuls1.len(), 4);
assert_eq!(all_nuls2.len(), 4);
// string equality ... | identifier_body | |
nul-characters.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 ... | assert_eq!(c1,c2);
}
}
// testing equality between explicit character literals
assert_eq!('\0', '\x00');
assert_eq!('\u0000', '\x00');
assert_eq!('\u0000', '\U00000000');
// NUL characters should make a difference
assert!("Hello World" != "Hello \0World");
asser... | {
for c2 in all_nuls1.iter()
{ | random_line_split |
profile-image.tsx | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
import { Map as ImmutableMap } from "immutable";
import { Button, ButtonToolbar, FormControl, Well } from "../antd-bootstrap";
import { React, Component, Rendered, redux } from... | }
render_crop_selection(): Rendered {
return (
<>
{this.state.custom_image_src && (
<ReactCropComponent
src={this.state.custom_image_src}
crop={this.state.crop}
circularCrop={true}
minWidth={20}
minHeight={20}
onChang... | const croppedImageUrl = await getCroppedImg(this.imageRef, crop);
this.setState({ croppedImageUrl });
}
| identifier_body |
profile-image.tsx | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
import { Map as ImmutableMap } from "immutable";
import { Button, ButtonToolbar, FormControl, Well } from "../antd-bootstrap";
import { React, Component, Rendered, redux } from... | await table.set({ profile: { image: src } }, "none");
} catch (err) {
if (this.is_mounted) {
this.setState({ error: `${err}` });
}
} finally {
if (this.is_mounted) {
this.setState({ is_loading: false });
}
}
};
handle_gravatar_click = () => {
if (!this.... | set_image = async (src: string) => {
this.setState({ is_loading: true });
const table = redux.getTable("account");
try { | random_line_split |
profile-image.tsx | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
import { Map as ImmutableMap } from "immutable";
import { Button, ButtonToolbar, FormControl, Well } from "../antd-bootstrap";
import { React, Component, Rendered, redux } from... | his.imageRef && crop.width && crop.height) {
const croppedImageUrl = await getCroppedImg(this.imageRef, crop);
this.setState({ croppedImageUrl });
}
}
render_crop_selection(): Rendered {
return (
<>
{this.state.custom_image_src && (
<ReactCropComponent
src={t... | (t | identifier_name |
profile-image.tsx | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
import { Map as ImmutableMap } from "immutable";
import { Button, ButtonToolbar, FormControl, Well } from "../antd-bootstrap";
import { React, Component, Rendered, redux } from... | }
const text = e.clipboardData.getData("text") || "";
if (text.startsWith("http") || text.startsWith("data:image")) {
this.handle_image_file(text);
}
};
handle_image_file_input = (e: any) => {
e.preventDefault();
const files = e.target.files;
if (files.length > 0 && files[0].type.st... | this.handle_image_file(item.getAsFile());
return;
}
| conditional_block |
fetch.py | #!/usr/bin/env python
import datetime
# import os for file system functions
import os
# import json
import json
# import regex
import re
# for date parsing
import time
# import flickrapi
# `easy_install flickrapi` or `pip install flickrapi`
import flickrapi
# main program
def fetch(api_key, api_secret):
# create a... | ( photo ):
return "http://farm%s.staticflickr.com/%s/%s_%s_o.%s" % (photo.get('farm'), photo.get('server'), photo.get('id'), photo.get('originalsecret'), photo.get('originalformat'))
# map Flickr licenses to short names
def getLicense( num ):
licenses = {}
licenses['0'] = ''
licenses['4'] = 'CC BY'
licenses[... | constructUrl | identifier_name |
fetch.py | #!/usr/bin/env python
import datetime
# import os for file system functions
import os
# import json
import json
# import regex
import re
# for date parsing
import time
# import flickrapi
# `easy_install flickrapi` or `pip install flickrapi`
import flickrapi
# main program
def fetch(api_key, api_secret):
# create a... |
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='Backup your Flickr photos')
parser.add_argument('--api-key', required=True, help='Flickr API key')
parser.add_argument('--api-secret', required=True, help='Flickr API secret')
config = parser.parse_args()
# check ... | licenses = {}
licenses['0'] = ''
licenses['4'] = 'CC BY'
licenses['5'] = 'CC BY-SA'
licenses['6'] = 'CC BY-ND'
licenses['2'] = 'CC BY-NC'
licenses['1'] = 'CC BY-NC-SA'
licenses['3'] = 'CC BY-NC-ND'
if licenses[num] is None:
return licenses[0]
else:
return licenses[num] | identifier_body |
fetch.py | #!/usr/bin/env python
import datetime
# import os for file system functions
import os
# import json
import json
# import regex
import re
# for date parsing
import time
# import flickrapi
# `easy_install flickrapi` or `pip install flickrapi`
import flickrapi
# main program
def fetch(api_key, api_secret):
# create a... |
else:
return licenses[num]
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='Backup your Flickr photos')
parser.add_argument('--api-key', required=True, help='Flickr API key')
parser.add_argument('--api-secret', required=True, help='Flickr API secret')
config ... | return licenses[0] | conditional_block |
fetch.py | #!/usr/bin/env python
import datetime
# import os for file system functions
import os
# import json
import json
# import regex
import re
# for date parsing
import time
# import flickrapi
# `easy_install flickrapi` or `pip install flickrapi`
import flickrapi
# main program
def fetch(api_key, api_secret):
# create a... | p['photo'] = photo.get('url_b')
elif photo.get('url_c') is not None:
p['photo'] = photo.get('url_c')
elif photo.get('url_z') is not None:
p['photo'] = photo.get('url_z')
t = datetime.datetime.fromtimestamp(float(p['dateUploaded']))
filename = '%s-%s' % (t.strftime('%Y%m%... | p['photo'] = photo.get('url_o')
elif photo.get('url_b') is not None: | random_line_split |
year-filter.component_angular.ts | import { Component } from '@angular/core';
import { IFilterAngularComp } from "@ag-grid-community/angular";
@Component({
selector: 'year-filter',
template: `
<div class="year-filter">
<label>
<input type="radio" name="isFilterActive" [checked]="!isActive" (change)="toggleFil... |
setModel(model): void {
this.toggleFilter(!!model);
}
onFloatingFilterChanged(value): void {
this.setModel(value);
}
} | return this.isFilterActive() || null;
} | random_line_split |
year-filter.component_angular.ts | import { Component } from '@angular/core';
import { IFilterAngularComp } from "@ag-grid-community/angular";
@Component({
selector: 'year-filter',
template: `
<div class="year-filter">
<label>
<input type="radio" name="isFilterActive" [checked]="!isActive" (change)="toggleFil... |
onFloatingFilterChanged(value): void {
this.setModel(value);
}
}
| {
this.toggleFilter(!!model);
} | identifier_body |
year-filter.component_angular.ts | import { Component } from '@angular/core';
import { IFilterAngularComp } from "@ag-grid-community/angular";
@Component({
selector: 'year-filter',
template: `
<div class="year-filter">
<label>
<input type="radio" name="isFilterActive" [checked]="!isActive" (change)="toggleFil... | (params): boolean {
return params.data.year > 2004;
}
isFilterActive(): boolean {
return this.isActive;
}
getModel(): boolean | null {
return this.isFilterActive() || null;
}
setModel(model): void {
this.toggleFilter(!!model);
}
onFloatingFilterChanged... | doesFilterPass | identifier_name |
bootstrap-buttons.js | /* ============================================================
* bootstrap-buttons.js v1.4.0
* http://twitter.github.com/bootstrap/javascript.html#buttons
* ============================================================
* Copyright 2011 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "L... |
options && setState(this, options)
})
}
$.fn.button.defaults = {
loadingText: 'loading...'
}
$(function () {
$('body').delegate('.btn[data-toggle]', 'click', function () {
$(this).button('toggle')
})
})
}( window.jQuery || window.ender ); | {
return toggle(this)
} | conditional_block |
bootstrap-buttons.js | /* ============================================================
* bootstrap-buttons.js v1.4.0
* http://twitter.github.com/bootstrap/javascript.html#buttons
* ============================================================
* Copyright 2011 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "L... |
$.fn.button = function(options) {
return this.each(function () {
if (options == 'toggle') {
return toggle(this)
}
options && setState(this, options)
})
}
$.fn.button.defaults = {
loadingText: 'loading...'
}
$(function () {
$('body').delegate('.btn[... | {
$(el).toggleClass('active')
} | identifier_body |
bootstrap-buttons.js | /* ============================================================
* bootstrap-buttons.js v1.4.0
* http://twitter.github.com/bootstrap/javascript.html#buttons
* ============================================================
* Copyright 2011 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "L... | (el, state) {
var d = 'disabled'
, $el = $(el)
, data = $el.data()
state = state + 'Text'
data.resetText || $el.data('resetText', $el.html())
$el.html( data[state] || $.fn.button.defaults[state] )
setTimeout(function () {
state == 'loadingText' ?
$el.addClass... | setState | identifier_name |
bootstrap-buttons.js | /* ============================================================
* bootstrap-buttons.js v1.4.0
* http://twitter.github.com/bootstrap/javascript.html#buttons
* ============================================================
* Copyright 2011 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "L... | $el.html( data[state] || $.fn.button.defaults[state] )
setTimeout(function () {
state == 'loadingText' ?
$el.addClass(d).attr(d, d) :
$el.removeClass(d).removeAttr(d)
}, 0)
}
function toggle(el) {
$(el).toggleClass('active')
}
$.fn.button = function(options)... | random_line_split | |
new-entity.component.ts | import { Component, HostListener, Inject } from '@angular/core';
import { MdlDialogReference } from '@angular-mdl/core';
import * as _ from 'lodash';
@Component({
selector: 'app-new-entity',
templateUrl: './new-entity.component.html',
styleUrls: ['./new-entity.component.scss']
})
export class NewEntityComponen... | () {
if (this.entity.info.title && this.entity.info.title.length > 0) {
this.hide();
if (this.actions && this.actions.save) {
this.actions.save(this.entity);
}
}
}
cancel() {
this.hide();
}
}
| create | identifier_name |
new-entity.component.ts | import { Component, HostListener, Inject } from '@angular/core';
import { MdlDialogReference } from '@angular-mdl/core';
import * as _ from 'lodash';
@Component({
selector: 'app-new-entity', | styleUrls: ['./new-entity.component.scss']
})
export class NewEntityComponent {
actions: any;
pluginFormats = [
{ label: 'Javascript', value: 'JAVASCRIPT' },
{ label: 'XQuery', value: 'XQUERY' },
];
dataFormats = [
{ label: 'JSON', value: 'JSON' },
{ label: 'XML', value: 'XML' },
];
DEFA... | templateUrl: './new-entity.component.html', | random_line_split |
new-entity.component.ts | import { Component, HostListener, Inject } from '@angular/core';
import { MdlDialogReference } from '@angular-mdl/core';
import * as _ from 'lodash';
@Component({
selector: 'app-new-entity',
templateUrl: './new-entity.component.html',
styleUrls: ['./new-entity.component.scss']
})
export class NewEntityComponen... |
}
}
cancel() {
this.hide();
}
}
| {
this.actions.save(this.entity);
} | conditional_block |
new-entity.component.ts | import { Component, HostListener, Inject } from '@angular/core';
import { MdlDialogReference } from '@angular-mdl/core';
import * as _ from 'lodash';
@Component({
selector: 'app-new-entity',
templateUrl: './new-entity.component.html',
styleUrls: ['./new-entity.component.scss']
})
export class NewEntityComponen... |
}
| {
this.hide();
} | identifier_body |
hrtb-perfect-forwarding.rs | // Copyright 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-MIT or ... |
fn main() { }
| {
// OK -- now we have `T : for<'b> Bar&'b isize>`.
foo_hrtb_bar_hrtb(&mut t);
} | identifier_body |
hrtb-perfect-forwarding.rs | // Copyright 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-MIT or ... |
fn foo_hrtb_bar_not<'b,T>(mut t: T)
where T : for<'a> Foo<&'a isize> + Bar<&'b isize>
{
// Not OK -- The forwarding impl for `Foo` requires that `Bar` also
// be implemented. Thus to satisfy `&mut T : for<'a> Foo<&'a
// isize>`, we require `T : for<'a> Bar<&'a isize>`, but the where
// clause only ... | // example of a "perfect forwarding" impl.
bar_hrtb(&mut t);
} | random_line_split |
hrtb-perfect-forwarding.rs | // Copyright 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-MIT or ... | (&mut self, x: X) { }
}
impl<'a,X,F> Foo<X> for &'a mut F
where F : Foo<X> + Bar<X>
{
}
impl<'a,X,F> Bar<X> for &'a mut F
where F : Bar<X>
{
}
fn no_hrtb<'b,T>(mut t: T)
where T : Bar<&'b isize>
{
// OK -- `T : Bar<&'b isize>`, and thus the impl above ensures that
// `&mut T : Bar<&'b isize>`.
... | bar | identifier_name |
package.rs | use std::get_slice::GetSlice;
use std::url::Url;
use std::fs::File;
use std::io::Read;
use orbital::BmpFile;
/// A package (_REDOX content serialized)
pub struct | {
/// The URL
pub url: Url,
/// The ID of the package
pub id: String,
/// The name of the package
pub name: String,
/// The binary for the package
pub binary: String,
/// The icon for the package
pub icon: BmpFile,
/// The accepted extensions
pub accepts: Vec<String>,
... | Package | identifier_name |
package.rs | use std::get_slice::GetSlice;
use std::url::Url;
use std::fs::File;
use std::io::Read;
use orbital::BmpFile;
/// A package (_REDOX content serialized)
pub struct Package {
/// The URL
pub url: Url,
/// The ID of the package
pub id: String,
/// The name of the package
pub name: String,
/// ... | }
let mut info = String::new();
if let Ok(mut file) = File::open(&(url.to_string() + "_REDOX")) {
file.read_to_string(&mut info);
}
for line in info.lines() {
if line.starts_with("name=") {
package.name = line.get_slice(Some(5), None).to... | for part in url.to_string().rsplit('/') {
if !part.is_empty() {
package.id = part.to_string();
break;
} | random_line_split |
package.rs | use std::get_slice::GetSlice;
use std::url::Url;
use std::fs::File;
use std::io::Read;
use orbital::BmpFile;
/// A package (_REDOX content serialized)
pub struct Package {
/// The URL
pub url: Url,
/// The ID of the package
pub id: String,
/// The name of the package
pub name: String,
/// ... | else if line.starts_with("icon=") {
package.icon = BmpFile::from_path(line.get_slice(Some(5), None));
} else if line.starts_with("accept=") {
package.accepts.push(line.get_slice(Some(7), None).to_string());
} else if line.starts_with("author=") {
... | {
package.binary = url.to_string() + line.get_slice(Some(7), None);
} | conditional_block |
CircularWithValueLabel.tsx | import React from 'react';
import CircularProgress, { CircularProgressProps } from '@material-ui/core/CircularProgress';
import Typography from '@material-ui/core/Typography';
import Box from '@material-ui/core/Box';
function | (props: CircularProgressProps & { value: number }) {
return (
<Box position="relative" display="inline-flex">
<CircularProgress variant="determinate" {...props} />
<Box
top={0}
left={0}
bottom={0}
right={0}
position="absolute"
display="flex"
alig... | CircularProgressWithLabel | identifier_name |
CircularWithValueLabel.tsx | import React from 'react';
import CircularProgress, { CircularProgressProps } from '@material-ui/core/CircularProgress';
import Typography from '@material-ui/core/Typography';
import Box from '@material-ui/core/Box';
function CircularProgressWithLabel(props: CircularProgressProps & { value: number }) {
return (
... | {
const [progress, setProgress] = React.useState(10);
React.useEffect(() => {
const timer = setInterval(() => {
setProgress((prevProgress) => (prevProgress >= 100 ? 0 : prevProgress + 10));
}, 800);
return () => {
clearInterval(timer);
};
}, []);
return <CircularProgressWithLabel v... | identifier_body | |
CircularWithValueLabel.tsx | import React from 'react';
import CircularProgress, { CircularProgressProps } from '@material-ui/core/CircularProgress';
import Typography from '@material-ui/core/Typography';
import Box from '@material-ui/core/Box';
function CircularProgressWithLabel(props: CircularProgressProps & { value: number }) {
return (
... |
return <CircularProgressWithLabel value={progress} />;
} | return () => {
clearInterval(timer);
};
}, []); | random_line_split |
index.js | 'use strict';
const EmberApp = require('./ember-app');
/**
* FastBoot renders your Ember.js applications in Node.js. Start by
* instantiating this class with the path to your compiled Ember app:
*
*
* #### Sandboxing
*
* For security and correctness reasons, Ember applications running in FastBoot
* are run in... |
}
/**
* Destroy the existing Ember application instance, and recreate it from the provided dist path.
* This is commonly done when `dist` has been updated, and you need to prepare to serve requests
* with the updated assets.
*
* @param {Object} options
* @param {string} options.distPath the path... | {
return result;
} | conditional_block |
index.js | 'use strict';
const EmberApp = require('./ember-app');
/**
* FastBoot renders your Ember.js applications in Node.js. Start by
* instantiating this class with the path to your compiled Ember app:
*
*
* #### Sandboxing
*
* For security and correctness reasons, Ember applications running in FastBoot
* are run in... | (
distPath = this.distPath,
buildSandboxGlobals = this.buildSandboxGlobals,
maxSandboxQueueSize = this.maxSandboxQueueSize
) {
if (!distPath) {
throw new Error(
'You must instantiate FastBoot with a distPath ' +
'option that contains a path to a dist directory ' +
'pr... | _buildEmberApp | identifier_name |
index.js | 'use strict';
const EmberApp = require('./ember-app');
/**
* FastBoot renders your Ember.js applications in Node.js. Start by
* instantiating this class with the path to your compiled Ember app:
*
*
* #### Sandboxing
*
* For security and correctness reasons, Ember applications running in FastBoot
* are run in... |
/**
* Renders the Ember app at a specific URL, returning a promise that resolves
* to a {@link Result}, giving you access to the rendered HTML as well as
* metadata about the request such as the HTTP status code.
*
* @param {string} path the URL path to render, like `/photos/1`
* @param {Object} o... | {
let { distPath, buildSandboxGlobals, maxSandboxQueueSize } = options;
this.resilient = 'resilient' in options ? Boolean(options.resilient) : false;
this.distPath = distPath;
// deprecate the legacy path, but support it
if (buildSandboxGlobals === undefined && options.sandboxGlobals !== undefine... | identifier_body |
index.js | 'use strict';
const EmberApp = require('./ember-app');
/**
* FastBoot renders your Ember.js applications in Node.js. Start by
* instantiating this class with the path to your compiled Ember app:
*
*
* #### Sandboxing
*
* For security and correctness reasons, Ember applications running in FastBoot
* are run in... | throw result.error;
} else {
return result;
}
}
/**
* Destroy the existing Ember application instance, and recreate it from the provided dist path.
* This is commonly done when `dist` has been updated, and you need to prepare to serve requests
* with the updated assets.
*
* @para... | let resilient = 'resilient' in options ? options.resilient : this.resilient;
let result = await this._app.visit(path, options);
if (!resilient && result.error) { | random_line_split |
common.py | import re
import sys
class URI():
def __init__( self, root_path ):
super().__init__()
if root_path[-1] != '/' or root_path[0] != '/':
raise ValueError( 'root_path must start and end with "/"' )
self.root_path = root_path
self.uri_regex = re.compile( r'^({0}|/)(([a-zA-Z0-9\-_.!~*<>]+/)*)([a-zA... |
# barrowed from https://www.python.org/dev/peps/pep-0257/
def doccstring_prep( docstring ):
if not docstring:
return ''
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines:
lines = docstring.expandtabs().splitlines()
# Determine minimum indentation (first line... | random_line_split | |
common.py | import re
import sys
class URI():
def __init__( self, root_path ):
super().__init__()
if root_path[-1] != '/' or root_path[0] != '/':
raise ValueError( 'root_path must start and end with "/"' )
self.root_path = root_path
self.uri_regex = re.compile( r'^({0}|/)(([a-zA-Z0-9\-_.!~*<>]+/)*)([a-zA... | ( self, uri, root_optional=False ):
uri_match = self.uri_regex.match( uri )
if not uri_match:
raise ValueError( 'Unable to parse URI "{0}"'.format( uri ) )
( root, namespace, _, model, rec_id, _, action ) = uri_match.groups()
if root != self.root_path and not root_optional:
raise ValueError... | split | identifier_name |
common.py | import re
import sys
class URI():
def __init__( self, root_path ):
super().__init__()
if root_path[-1] != '/' or root_path[0] != '/':
raise ValueError( 'root_path must start and end with "/"' )
self.root_path = root_path
self.uri_regex = re.compile( r'^({0}|/)(([a-zA-Z0-9\-_.!~*<>]+/)*)([a-zA... |
( namespace_list, model, action, _, _ ) = self.split( uri_list[0] )
return self.build( namespace_list, model, action, id_list, True )
# barrowed from https://www.python.org/dev/peps/pep-0257/
def doccstring_prep( docstring ):
if not docstring:
return ''
# Convert tabs to spaces (following the norma... | return [] | conditional_block |
common.py | import re
import sys
class URI():
def __init__( self, root_path ):
super().__init__()
if root_path[-1] != '/' or root_path[0] != '/':
raise ValueError( 'root_path must start and end with "/"' )
self.root_path = root_path
self.uri_regex = re.compile( r'^({0}|/)(([a-zA-Z0-9\-_.!~*<>]+/)*)([a-zA... |
def build( self, namespace=None, model=None, action=None, id_list=None, in_root=True ):
"""
build a uri, NOTE: if model is None, id_list and action are skiped
"""
if in_root:
result = self.root_path
else:
result = '/'
if namespace is not None:
if not isinstance( namespace,... | uri_match = self.uri_regex.match( uri )
if not uri_match:
raise ValueError( 'Unable to parse URI "{0}"'.format( uri ) )
( root, namespace, _, model, rec_id, _, action ) = uri_match.groups()
if root != self.root_path and not root_optional:
raise ValueError( 'URI does not start in the root_path' ... | identifier_body |
youtubech.py | # coding=UTF-8
from datetime import timedelta
import resource
import time
import urllib
from django.core.exceptions import ObjectDoesNotExist
from snh.models.youtubemodel import *
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
import snhlogger
logger = snhlogger.init_logger(__name__, ... | harvester.end_current_harvest()
logger.info(u"End: %s Stats:%s Mem:%s MB" % (harvester,unicode(harvester.get_stats()),unicode(getattr(usage, "ru_maxrss")/(1024.0)))) | finally:
usage = resource.getrusage(resource.RUSAGE_SELF) | random_line_split |
youtubech.py | # coding=UTF-8
from datetime import timedelta
import resource
import time
import urllib
from django.core.exceptions import ObjectDoesNotExist
from snh.models.youtubemodel import *
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
import snhlogger
logger = snhlogger.init_logger(__name__, ... |
def update_user(harvester, userid):
snh_user = None
try:
uniuserid = urllib.urlencode({"k":userid.encode('utf-8')}).split("=")[1:][0]
ytuser = harvester.api_call("GetYouTubeUserEntry",{"username":uniuserid})
split_uri = ytuser.id.text.split("/")
fid = split_uri[len(split_uri)-... | user = None
try:
user = YTUser.objects.get(**param)
except MultipleObjectsReturned:
user = YTUser.objects.filter(**param)[0]
logger.warning(u"Duplicated user in DB! %s, %s" % (user, user.fid))
except ObjectDoesNotExist:
pass
return user | identifier_body |
youtubech.py | # coding=UTF-8
from datetime import timedelta
import resource
import time
import urllib
from django.core.exceptions import ObjectDoesNotExist
from snh.models.youtubemodel import *
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
import snhlogger
logger = snhlogger.init_logger(__name__, ... |
if not out_of_window:
get_vid_url = video_list.GetNextLink().href if video_list.GetNextLink() else None
else:
logger.info(u"Skipping user update: %s(%s) because user has triggered the error flag." % (unicode(snhuser), snhuser.fid if snhuser.fid else "0"))
us... | out_of_window = True
break | conditional_block |
youtubech.py | # coding=UTF-8
from datetime import timedelta
import resource
import time
import urllib
from django.core.exceptions import ObjectDoesNotExist
from snh.models.youtubemodel import *
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
import snhlogger
logger = snhlogger.init_logger(__name__, ... | (dm_time):
ts = datetime.strptime(dm_time,'%Y-%m-%dT%H:%M:%S+0000')
return (datetime.utcnow() - ts).days
def get_existing_user(param):
user = None
try:
user = YTUser.objects.get(**param)
except MultipleObjectsReturned:
user = YTUser.objects.filter(**param)[0]
logger.warning(... | get_timedelta | identifier_name |
test_minicluster.py | '''
New Test For mini cluster creation and roll back when creation failed
@author: Glody
'''
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpe... | pass | identifier_body | |
test_minicluster.py | '''
New Test For mini cluster creation and roll back when creation failed
@author: Glody
'''
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpe... | def test():
zone_uuid = res_ops.query_resource_fields(res_ops.ZONE)[0].uuid
cluster_uuid = res_ops.query_resource_fields(res_ops.CLUSTER)[0].uuid
cond = res_ops.gen_query_conditions('clusterUuid', '=', cluster_uuid)
hosts = res_ops.query_resource_fields(res_ops.HOST, cond)
minicluster_name = 'min... | test_obj_dict = test_state.TestStateDict()
| random_line_split |
test_minicluster.py | '''
New Test For mini cluster creation and roll back when creation failed
@author: Glody
'''
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpe... |
test_util.test_pass("Mini cluster test passed")
def error_cleanup():
pass
| test_util.test_fail("Fail to roll back when create mini cluster failed") | conditional_block |
test_minicluster.py | '''
New Test For mini cluster creation and roll back when creation failed
@author: Glody
'''
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpe... | ():
zone_uuid = res_ops.query_resource_fields(res_ops.ZONE)[0].uuid
cluster_uuid = res_ops.query_resource_fields(res_ops.CLUSTER)[0].uuid
cond = res_ops.gen_query_conditions('clusterUuid', '=', cluster_uuid)
hosts = res_ops.query_resource_fields(res_ops.HOST, cond)
minicluster_name = 'minicluster... | test | identifier_name |
action-at-a-distance.js | var ActionAtADistance = function() {
var _socket, _lastRequestedUrl, _currentlyLoadedUrl,
_uuid, _lastEvalResp, _connected = false, _onCallback, _initCallback, _onDisconnect;
function _log(msg) {
if (typeof console !== 'undefined' &&
(typeof console.log === 'function' || typeof co... |
return {
connect: function(port, callback) {
_loadSocketIO(port, callback);
},
init: function() {
_socket.on('initResp', function (data) {
_uuid = data.uuid;
_connected = true;
_initCallback();
});
... | {
$.getScript('/aaad-socket-uri.js', function(data, textStatus, jqxhr) {
var socketIOUrl = 'http://' + document.location.hostname + aaadSocketURI;
_log('SocketIO URL: ' + socketIOUrl);
$.getScript(socketIOUrl + "socket.io/socket.io.js", function(data, textStatus, jqxhr) {
... | identifier_body |
action-at-a-distance.js | var ActionAtADistance = function() {
var _socket, _lastRequestedUrl, _currentlyLoadedUrl,
_uuid, _lastEvalResp, _connected = false, _onCallback, _initCallback, _onDisconnect;
function _log(msg) {
if (typeof console !== 'undefined' &&
(typeof console.log === 'function' || typeof co... | else if (data.action === 'documentLoaded') {
_currentlyLoadedUrl = data.documentLocationHref;
} else if (data.action === 'evaluate') {
_lastEvalResp = data;
}
_onCallback(data);
});
... | {
_currentlyLoadedUrl = _lastRequestedUrl; //TODO pass the URL as part of the Socket.io response data
} | conditional_block |
action-at-a-distance.js | var ActionAtADistance = function() {
var _socket, _lastRequestedUrl, _currentlyLoadedUrl,
_uuid, _lastEvalResp, _connected = false, _onCallback, _initCallback, _onDisconnect;
function | (msg) {
if (typeof console !== 'undefined' &&
(typeof console.log === 'function' || typeof console.log === 'object')) {
console.log(msg);
}
}
function _logJson(msg) {
if (typeof JSON !== 'undefined' &&
(typeof JSON.stringify === 'function' || typeof... | _log | identifier_name |
action-at-a-distance.js | var ActionAtADistance = function() {
var _socket, _lastRequestedUrl, _currentlyLoadedUrl,
_uuid, _lastEvalResp, _connected = false, _onCallback, _initCallback, _onDisconnect;
function _log(msg) {
if (typeof console !== 'undefined' &&
(typeof console.log === 'function' || typeof co... | }
}
function _logJson(msg) {
if (typeof JSON !== 'undefined' &&
(typeof JSON.stringify === 'function' || typeof JSON.stringify === 'object')) {
_log(JSON.stringify(msg));
}
}
function _loadSocketIO(callback) {
$.getScript('/aaad-socket-uri.js', ... | random_line_split | |
netmiko_sh_arp.py | #!/usr/bin/env python
# Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, and juniper-srx.
from netmiko import ConnectHandler
def main():
# Definition of routers
|
if __name__ == "__main__":
main()
| rtr1 = {
'device_type': 'cisco_ios',
'ip': '50.76.53.27',
'username': 'pyclass',
'password': '88newclass',
}
rtr2 = {
'device_type': 'cisco_ios',
'ip': '50.76.53.27',
'username': 'pyclass',
'password': '88newclass',
'port': 8022,
}... | identifier_body |
netmiko_sh_arp.py | #!/usr/bin/env python
# Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, and juniper-srx.
from netmiko import ConnectHandler
def main():
# Definition of routers
rtr1 = {
'device_type': 'cisco_ios',
'ip': '50.76.53.27',
'username': 'pyclass',
'password': '88newcl... |
if __name__ == "__main__":
main()
| net_connect = ConnectHandler(**a_router)
output = net_connect.send_command("show arp")
print "\n\n>>>>>>>>> Device {0} <<<<<<<<<".format(a_router['device_type'])
print output
print ">>>>>>>>> End <<<<<<<<<" | conditional_block |
netmiko_sh_arp.py | #!/usr/bin/env python
# Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, and juniper-srx.
from netmiko import ConnectHandler
def main():
# Definition of routers
rtr1 = {
'device_type': 'cisco_ios',
'ip': '50.76.53.27',
'username': 'pyclass',
'password': '88newcl... | output = net_connect.send_command("show arp")
print "\n\n>>>>>>>>> Device {0} <<<<<<<<<".format(a_router['device_type'])
print output
print ">>>>>>>>> End <<<<<<<<<"
if __name__ == "__main__":
main() |
# Loop through all the routers and show arp.
for a_router in all_routers:
net_connect = ConnectHandler(**a_router) | random_line_split |
netmiko_sh_arp.py | #!/usr/bin/env python
# Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, and juniper-srx.
from netmiko import ConnectHandler
def | ():
# Definition of routers
rtr1 = {
'device_type': 'cisco_ios',
'ip': '50.76.53.27',
'username': 'pyclass',
'password': '88newclass',
}
rtr2 = {
'device_type': 'cisco_ios',
'ip': '50.76.53.27',
'username': 'pyclass',
'password': '88n... | main | identifier_name |
GameServerMethods.ts | import * as GS from "../GameState";
export const SelectFaction = "SelectFaction";
export interface ISelectFactionParams {
factionType: GS.FactionType;
}
export type ISelectFactionResponse = void;
export const ChangeSettings = "ChangeSettings";
export interface IChangeSettingsParams {
settings: GS.MapSettings;... | }
export type IRenameCityResponse = void;
export const PushProductionQueue = "PushProductionQueue";
export interface IPushProductionQueueParams {
city: string;
unitType: string;
}
export type IPushProductionQueueResponse = void;
/**
* Todo automatically populated from above
*/
export const SERVER_METHODS = ... | export const RenameCity = "RenameCity";
export interface IRenameCityParams {
id: string;
name: string; | random_line_split |
_app.main.ts | <%# | for more information.
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
dis... | Copyright 2013-2017 the original author or authors from the JHipster project.
This file is part of the JHipster project, see https://jhipster.github.io/ | random_line_split |
_app.main.ts | <%#
Copyright 2013-2017 the original author or authors from the JHipster project.
This file is part of the JHipster project, see https://jhipster.github.io/
for more information.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You ... |
platformBrowserDynamic().bootstrapModule(<%=angular2AppName%>AppModule)
.then((success) => console.log(`Application started`))
.catch((err) => console.error(err));
| {
module['hot'].accept();
} | conditional_block |
CollectionEntity.tsx | import { Box, Link, Sans, Serif, color } from "@artsy/palette"
import { CollectionEntity_collection } from "v2/__generated__/CollectionEntity_collection.graphql"
import { track } from "v2/System/Analytics"
import * as Schema from "v2/System/Analytics/Schema"
import currency from "currency.js"
import React from "react"
... | <Sans size="2">
Works from ${/* @ts-expect-error STRICT_NULL_CHECK */}
{currency(collection.price_guidance, {
separator: ",",
precision: 0,
}).format()}
</Sans>
</StyledLink>
</Box>
)
}
}
export const CollectionEnti... | random_line_split | |
base.py | # -*- coding: utf-8 -*-
"""Define the base module for server test."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
from influxdb.tests import using_pypy
from influxdb.tests.server_tests.influxdb_instanc... | # 'influxdb_template_conf' attribute must be set
# on the TestCase class or instance.
setUp = _setup_influxdb_server
tearDown = _teardown_influxdb_server
class ManyTestCasesWithServerMixin(object):
"""Define the many testcase with server mixin.
Same as the SingleTestCaseWithServerMixin but t... | random_line_split | |
base.py | # -*- coding: utf-8 -*-
"""Define the base module for server test."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
from influxdb.tests import using_pypy
from influxdb.tests.server_tests.influxdb_instanc... |
def _teardown_influxdb_server(inst):
remove_tree = sys.exc_info() == (None, None, None)
inst.influxd_inst.close(remove_tree=remove_tree)
class SingleTestCaseWithServerMixin(object):
"""Define the single testcase with server mixin.
A mixin for unittest.TestCase to start an influxdb server instance
... | inst.cliDF = DataFrameClient('localhost',
inst.influxd_inst.http_port,
'root',
'',
database='db') | conditional_block |
base.py | # -*- coding: utf-8 -*-
"""Define the base module for server test."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
from influxdb.tests import using_pypy
from influxdb.tests.server_tests.influxdb_instanc... | (object):
"""Define the many testcase with server mixin.
Same as the SingleTestCaseWithServerMixin but this module creates
a single instance for the whole class. Also pre-creates a fresh
database: 'db'.
"""
# 'influxdb_template_conf' attribute must be set on the class itself !
@classmetho... | ManyTestCasesWithServerMixin | identifier_name |
base.py | # -*- coding: utf-8 -*-
"""Define the base module for server test."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
from influxdb.tests import using_pypy
from influxdb.tests.server_tests.influxdb_instanc... |
def setUp(self):
"""Set up an instance of the ManyTestCasesWithServerMixin."""
self.cli.create_database('db')
@classmethod
def tearDownClass(cls):
"""Deconstruct an instance of ManyTestCasesWithServerMixin."""
_teardown_influxdb_server(cls)
def tearDown(self):
... | """Set up an instance of the ManyTestCasesWithServerMixin."""
_setup_influxdb_server(cls) | identifier_body |
scaler.py | import time
import config
from ophyd import scaler
from ophyd.utils import enum
ScalerMode = enum(ONE_SHOT=0, AUTO_COUNT=1)
loggers = ('ophyd.signal',
'ophyd.scaler',
)
config.setup_loggers(loggers)
logger = config.logger
sca = scaler.EpicsScaler(config.scalers[0])
sca.preset_time.put(5.2, ... | time.sleep(2)
logger.info('Set mode to OneShot')
sca.count_mode.put(ScalerMode.ONE_SHOT, wait=True)
time.sleep(1)
logger.info('Stopping (aborting) auto-counting.')
sca.count.put(0)
logger.info('read() all channels in one-shot mode...')
vals = sca.read()
logger.info(vals)
logger.info('sca.channels.get() shows: %s', sc... | sca.trigger()
logger.info('Begin auto-counting (aka "background counting")...') | random_line_split |
prepare.py | # -*- coding: utf-8 -*-
#
# This file is part of kwalitee
# Copyright (C) 2014, 2015 CERN.
#
# kwalitee 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 2 of the
# License, or (at your option) an... | (body_paragraph, labels=None):
"""Analyse commit body paragraph and return (label, message).
>>> analyse_body_paragraph('* BETTER Foo and bar.',
>>> ... {'BETTER': 'Improvements'})
('BETTER', 'Foo and bar.')
>>> analyse_body_paragraph('* Foo and bar.')
(None, 'Foo and bar.')
>>> analyse_bod... | analyse_body_paragraph | identifier_name |
prepare.py | # -*- coding: utf-8 -*-
#
# This file is part of kwalitee
# Copyright (C) 2014, 2015 CERN.
#
# kwalitee 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 2 of the
# License, or (at your option) an... |
full_messages = list(
enrich_git_log_dict(messages, options.get('commit_msg_labels'))
)
indent = ' ' if group_components else ''
wrapper = textwrap.TextWrapper(
width=70,
initial_indent=indent + '- ',
subsequent_indent=indent + ' ',
)
for label, section in op... | del messages[commit_sha1] | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.