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
lifecycle.js
/** * The file lifecycle.js.js Create with WebStorm * @Author gaosi * @Email angus_gaosi@163.com * @Date 2014/10/13 15:49:00 * To change this template use File | Setting |File Template */ var pomelo = require('pomelo'); var logger = require('pomelo/node_modules/pomelo-logger').getLogger('l...
logger.fatal('beforeShutdown no players on this js, shutdown.'); cb(); });*/ }; module.exports.afterStartAll = function (app) { logger.fatal('afterStartAll.'); };
return !playerManager.GetNumPlayer(1, 0).length; }, function () {
random_line_split
SimpleForm.qunit.js
(function () { "use strict"; sap.ui.require([ "sap/ui/dt/test/report/QUnit", "sap/ui/dt/test/ElementEnablementTest", "sap/ui/rta/test/controlEnablingCheck", "sap/m/Input", "sap/m/Label", "sap/ui/core/Title", "sap/ui/layout/form/SimpleForm", "sap/m/Toolbar" ], function(QUnit, ElementEnablementTest, r...
'</mvc:View>' , action: { name: "move", controlId: "simpleForm", parameter: function(oView) { return { movedElements: [{ element: oView.byId("title2").getParent(), sourceIndex: 1, targetIndex: 0 }], source: { aggregation: "form", parent: oVi...
'<m:Label/>' + '<m:Input/>' + '</f:content>' + '</f:SimpleForm>' +
random_line_split
AdminUserManagement.js
Ext.define('Testprok.view.usermanagement.admin.AdminUserManagement', { extend : 'Ext.tab.Panel', requires : ['Testprok.view.usermanagement.admin.UserPasswordReset', 'Testprok.view.usermanagement.admin.AddUserDetails', 'Testprok.view.usermanagement.admin.ViewUser'], xtype : 'adminUserMainVie...
xtype:'viewUser', itemId:'viewUser', title:'View User', iconCls:'viewUserTabIcon', tooltip:'View users details' }, { xtype:'userPwdResetView', itemId:'userPwdResetView', title:'User Password Settings', iconCls:'settingTabIcon', tooltip:'User Account settings' }] });
}, {
random_line_split
0013_auto_20140925_1616.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration):
migrations.AlterField( model_name='ups', name='notes', field=models.TextField(default=b'', verbose_name=b'Notes', blank=True), ), ]
dependencies = [ ('devices', '0012_auto_20140925_1540'), ] operations = [ migrations.AlterField( model_name='ap', name='notes', field=models.TextField(default=b'', verbose_name=b'Notes', blank=True), ), migrations.AlterField( model...
identifier_body
0013_auto_20140925_1616.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class
(migrations.Migration): dependencies = [ ('devices', '0012_auto_20140925_1540'), ] operations = [ migrations.AlterField( model_name='ap', name='notes', field=models.TextField(default=b'', verbose_name=b'Notes', blank=True), ), migrations....
Migration
identifier_name
0013_auto_20140925_1616.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration):
operations = [ migrations.AlterField( model_name='ap', name='notes', field=models.TextField(default=b'', verbose_name=b'Notes', blank=True), ), migrations.AlterField( model_name='phone', name='notes', field=models.TextF...
dependencies = [ ('devices', '0012_auto_20140925_1540'), ]
random_line_split
serialisation.spec.js
import { createLogger } from '../src'; describe('serialisation', () => { const sandbox = sinon.sandbox.create(); const logFunction = sinon.stub(); const jsonString = 'JSON!'; let logger; beforeEach(() => { logFunction.reset(); sandbox.stub(JSON, 'stringify').returns(jsonString); logger = createL...
afterEach(() => { sandbox.restore(); }); context('when logging a string', () => { it('should print the exact string', () => { const testString = 'foo'; logger.log(testString); expect(logFunction).to.have.been.calledWith(testString); }); }); context('when logging a number', () ...
});
random_line_split
Human_GATK_RNA_vari_call.py
""" this file does variant calling for RNAseq """ #============= import required packages ================= import os import sys import subprocess sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # disable buffer from Modules.f00_Message import Message from Modules.f01_list_trim_fq import list_files_human,Trimmoma...
sys.stdout.write('add group failed\n') Message('add group failed',email) sys.exit(1) #======== (2) mark duplicates ============================ try: dedup_bams = markduplicates(picard,group_bams) sys.stdout.write('mark duplicate succeed\n') sys.stdout.write('dedup_bams is: {dedup}\n'.format(de...
random_line_split
Human_GATK_RNA_vari_call.py
""" this file does variant calling for RNAseq """ #============= import required packages ================= import os import sys import subprocess sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # disable buffer from Modules.f00_Message import Message from Modules.f01_list_trim_fq import list_files_human,Trimmoma...
sys.stdout.write('list file succeed\n') sys.stdout.write('fastqFiles is: {fq}\n'.format(fq=fastqFiles)) #======== (2) align using 2 pass STAR ==================== try: map_sams= STAR2Pass(fastqFiles,starDb,ref_fa,thread) sys.stdout.write('align succeed\n') sys.stdout.write('map_sams is: {map}\n'.format(m...
fastqFiles = Trimmomatic(trimmomatic,fastqFiles,phred,trimmoAdapter)
conditional_block
like.py
# -*- coding: utf-8 -*- from util.token import token_required from server import db from api import api, GlobalError, ERROR_LIKE from model.wish import Wish, WishLike from flask import abort from sqlalchemy.exc import IntegrityError from util.jsonResponse import jsonSuccess, jsonError ''' 重要提示:Model的设计中,需要确保每个Like的类的...
except Exception, e: print e db.session.rollback() return jsonError(GlobalError.UNDEFINED_ERROR), 403
return jsonSuccess(), 200 else: return jsonError(LikeError.NOT_LIKED), 403
random_line_split
like.py
# -*- coding: utf-8 -*- from util.token import token_required from server import db from api import api, GlobalError, ERROR_LIKE from model.wish import Wish, WishLike from flask import abort from sqlalchemy.exc import IntegrityError from util.jsonResponse import jsonSuccess, jsonError ''' 重要提示:Model的设计中,需要确保每个Like的类的...
n_required def cancel_like(current_user, resource_name=None, target_id=None): if not target_id: return jsonError(GlobalError.INVALID_ARGUMENTS), 403 Cls = ALLOW_RESOURCE.get(resource_name, None) if not Cls: abort(404) try: effect_row = Cls[0].query.get(target_id).likers.filter_b...
s = ALLOW_RESOURCE.get(resource_name, None) if not Cls: abort(404) try: like = Cls[1](current_user.id, target_id) db.session.add(like) db.session.commit() return jsonSuccess(), 201 except IntegrityError, e: db.session.rollback() return jsonError(LikeE...
identifier_body
like.py
# -*- coding: utf-8 -*- from util.token import token_required from server import db from api import api, GlobalError, ERROR_LIKE from model.wish import Wish, WishLike from flask import abort from sqlalchemy.exc import IntegrityError from util.jsonResponse import jsonSuccess, jsonError ''' 重要提示:Model的设计中,需要确保每个Like的类的...
try: like = Cls[1](current_user.id, target_id) db.session.add(like) db.session.commit() return jsonSuccess(), 201 except IntegrityError, e: db.session.rollback() return jsonError(LikeError.HAS_LIKED), 403 @api.route('/<string:resource_name>/like/<int:target_id>...
ource_name, None) if not Cls: abort(404)
conditional_block
like.py
# -*- coding: utf-8 -*- from util.token import token_required from server import db from api import api, GlobalError, ERROR_LIKE from model.wish import Wish, WishLike from flask import abort from sqlalchemy.exc import IntegrityError from util.jsonResponse import jsonSuccess, jsonError ''' 重要提示:Model的设计中,需要确保每个Like的类的...
rn jsonError(GlobalError.INVALID_ARGUMENTS), 403 Cls = ALLOW_RESOURCE.get(resource_name, None) if not Cls: abort(404) try: like = Cls[1](current_user.id, target_id) db.session.add(like) db.session.commit() return jsonSuccess(), 201 except IntegrityError, e: ...
retu
identifier_name
sequence.js
// Copyright 2007 The Closure Library 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 requ...
/** * Pattern object that matches a sequence of other patterns. * * @param {Array<goog.dom.pattern.AbstractPattern>} patterns Ordered array of * patterns to match. * @param {boolean=} opt_ignoreWhitespace Optional flag to ignore text nodes * consisting entirely of whitespace. The default is to not ign...
goog.require('goog.dom.NodeType'); goog.require('goog.dom.pattern'); goog.require('goog.dom.pattern.AbstractPattern'); goog.require('goog.dom.pattern.MatchType');
random_line_split
sequence.js
// Copyright 2007 The Closure Library 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 requ...
else { // Retry the same token on the next pattern. return this.matchToken(token, type); } default: this.reset(); return goog.dom.pattern.MatchType.NO_MATCH; } }; /** * Reset any internal state this pattern keeps. * @override */ goog.dom.pattern.Sequence.prototype.reset = ...
{ this.reset(); return goog.dom.pattern.MatchType.BACKTRACK_MATCH; }
conditional_block
main.rs
extern crate clap; extern crate colored; extern crate lockchain_core as lockchain; extern crate question; extern crate rpassword;
// #[macro_use] // extern crate human_panic; mod cli; mod keystore; mod keywoman; mod ssh; mod config; use config::Config; use clap::ArgMatches; use colored::*; use question::{Answer, Question}; use std::process; use std::{env, fs}; fn main() { /* This makes panic! pretty */ // setup_panic!(); /* Defin...
extern crate serde; #[macro_use] extern crate serde_derive; extern crate toml;
random_line_split
main.rs
extern crate clap; extern crate colored; extern crate lockchain_core as lockchain; extern crate question; extern crate rpassword; extern crate serde; #[macro_use] extern crate serde_derive; extern crate toml; // #[macro_use] // extern crate human_panic; mod cli; mod keystore; mod keywoman; mod ssh; mod config; use ...
(matches: &ArgMatches) { if !ssh::get_directory().exists() { fs::create_dir_all(ssh::get_directory()).unwrap(); } let name = matches.value_of("name").unwrap(); let addr = matches.value_of("addr").unwrap(); ssh::generate_key( &ssh::get_directory().to_str().unwrap(), &format!(...
handle_generate
identifier_name
main.rs
extern crate clap; extern crate colored; extern crate lockchain_core as lockchain; extern crate question; extern crate rpassword; extern crate serde; #[macro_use] extern crate serde_derive; extern crate toml; // #[macro_use] // extern crate human_panic; mod cli; mod keystore; mod keywoman; mod ssh; mod config; use ...
let pub_path = keywoman::generate_root(ks_path, pass); /* Print about our success */ println!(""); println!("{}", "✨ A new keystore was generated for you ✨".green()); println!("Your root public key can be found here: '{}'", pub_path); } fn handle_load(matches: &ArgMatches) {}
{ eprintln!("{}", "The two passwords did not match!".red()); process::exit(2); }
conditional_block
main.rs
extern crate clap; extern crate colored; extern crate lockchain_core as lockchain; extern crate question; extern crate rpassword; extern crate serde; #[macro_use] extern crate serde_derive; extern crate toml; // #[macro_use] // extern crate human_panic; mod cli; mod keystore; mod keywoman; mod ssh; mod config; use ...
fn handle_generate(matches: &ArgMatches) { if !ssh::get_directory().exists() { fs::create_dir_all(ssh::get_directory()).unwrap(); } let name = matches.value_of("name").unwrap(); let addr = matches.value_of("addr").unwrap(); ssh::generate_key( &ssh::get_directory().to_str().unwrap(...
{ /* This makes panic! pretty */ // setup_panic!(); /* Define our CLI App */ let m = cli::create().get_matches(); /* In this block we can unwrap quite viciously because clap will protect us */ match m.subcommand() { ("setup", Some(m)) => handle_setup(m), ("load", Some(m)) => ha...
identifier_body
NotificationPresenter.ts
/** * @license MIT License * * Copyright (c) 2015 Tetsuharu OHZEKI <saneyuki.snyk@gmail.com> * Copyright (c) 2015 Yusuke Suzuki <utatane.tea@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal ...
body: text, icon: ICON_URL, }); const timeout: Rx.Observable<void> = Rx.Observable.empty<void>().delay(5 * 1000); const click: Rx.Observable<void> = Rx.Observable.fromEvent<void>(notification, 'click').take(1).do<void>(() => { this._ui...
if (settings.badge && Notification.permission === 'granted') { let notification = new Notification(from + ' says:', {
random_line_split
NotificationPresenter.ts
/** * @license MIT License * * Copyright (c) 2015 Tetsuharu OHZEKI <saneyuki.snyk@gmail.com> * Copyright (c) 2015 Yusuke Suzuki <utatane.tea@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal ...
(): void { if (Notification.permission !== 'granted') { Notification.requestPermission(); } } showNotification(channelId: ChannelId, from: string, text: string): void { const settings = this._config.get(); if (settings.notification) { // FIXME: should cal...
requestPermission
identifier_name
NotificationPresenter.ts
/** * @license MIT License * * Copyright (c) 2015 Tetsuharu OHZEKI <saneyuki.snyk@gmail.com> * Copyright (c) 2015 Yusuke Suzuki <utatane.tea@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal ...
} }
{ let notification = new Notification(from + ' says:', { body: text, icon: ICON_URL, }); const timeout: Rx.Observable<void> = Rx.Observable.empty<void>().delay(5 * 1000); const click: Rx.Observable<void> = Rx.Observable.fromEvent<void>(not...
conditional_block
NotificationPresenter.ts
/** * @license MIT License * * Copyright (c) 2015 Tetsuharu OHZEKI <saneyuki.snyk@gmail.com> * Copyright (c) 2015 Yusuke Suzuki <utatane.tea@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal ...
showNotification(channelId: ChannelId, from: string, text: string): void { const settings = this._config.get(); if (settings.notification) { // FIXME: should call in `NotificationActionCreator.showNotification()` this._notifyAction.playSound(); } if (settin...
{ if (Notification.permission !== 'granted') { Notification.requestPermission(); } }
identifier_body
auth.service.ts
import { Injectable } from '@angular/core'; import { Http, RequestOptionsArgs, Headers } from '@angular/http'; import { tokenNotExpired } from 'angular2-jwt'; import { AuthConfiguration, ResponseCode } from '../support/model'; import Auth0UserProfile from 'auth0-js'; import Auth0Error from 'auth0-js'; import Auth0Stati...
public logout() { // Remove token and profile from localStorage localStorage.removeItem('id_token'); localStorage.removeItem('profile'); this.userProfile = undefined; this.displayName = undefined; } }
return tokenNotExpired(); }
random_line_split
auth.service.ts
import { Injectable } from '@angular/core'; import { Http, RequestOptionsArgs, Headers } from '@angular/http'; import { tokenNotExpired } from 'angular2-jwt'; import { AuthConfiguration, ResponseCode } from '../support/model'; import Auth0UserProfile from 'auth0-js'; import Auth0Error from 'auth0-js'; import Auth0Stati...
console.log('Error in signup: %s', JSON.stringify(error)); let status: number = error.status; if (status === 0) { return { 'result': ResponseCode.SYSTEM_ERROR }; } else { return { 'result': ResponseCode.UNKNOWN_ERROR }; } } ); ...
{ let body: any = { 'userName': userName, 'password': password, 'email': email, 'firstName': firstName, 'lastName': lastName }; let options: RequestOptionsArgs = { headers: new Headers({ 'Content-Type': 'application/json' }) }; try { return this.http.post(Au...
identifier_body
auth.service.ts
import { Injectable } from '@angular/core'; import { Http, RequestOptionsArgs, Headers } from '@angular/http'; import { tokenNotExpired } from 'angular2-jwt'; import { AuthConfiguration, ResponseCode } from '../support/model'; import Auth0UserProfile from 'auth0-js'; import Auth0Error from 'auth0-js'; import Auth0Stati...
() { // Remove token and profile from localStorage localStorage.removeItem('id_token'); localStorage.removeItem('profile'); this.userProfile = undefined; this.displayName = undefined; } }
logout
identifier_name
auth.service.ts
import { Injectable } from '@angular/core'; import { Http, RequestOptionsArgs, Headers } from '@angular/http'; import { tokenNotExpired } from 'angular2-jwt'; import { AuthConfiguration, ResponseCode } from '../support/model'; import Auth0UserProfile from 'auth0-js'; import Auth0Error from 'auth0-js'; import Auth0Stati...
return { 'result': 'success' }; }); } public signup(userName: string, password: string, email: string, firstName: string, lastName: string): any { let body: any = { 'userName': userName, 'password': password, 'email': email, 'firstName': firstName, 'lastName': l...
{ this.displayName = userMetadata.fullName; }
conditional_block
auth.js
import reducer from '../../../src/renderer/reducers/auth'; describe('reducer/auth', () => { const initialState = { mail: '' }; it('should return the initial state', () => { const expectedResult = initialState; expect(reducer(undefined, {})).toEqual(expectedResult); });
it('should handle LOGIN', () => { expect(reducer(undefined, { type: 'LOGIN' })).toEqual(initialState); }); it('should handle LOGOUT', () => { expect(reducer(undefined, { type: 'LOGOUT' })).toEqual(initialState); }); it('should handle LOGIN_SUCCESS', () => { const expectedResult = Object.assign({...
random_line_split
lib.rs
use std::fmt; use std::io; use std::io::Write; use thud_game::board::Cells; use thud_game::board::Content; use thud_game::coordinate::Coordinate; use thud_game::Role; pub fn prompt_for_piece(board: &Cells, role: Role) -> Coordinate { loop { let c = read_coordinate(); match board[c] { Content::Occupied...
() -> Coordinate { let stdin = io::stdin(); let mut stdout = io::stdout(); let mut input = String::new(); loop { input.clear(); print!("row? "); stdout.flush().ok().expect("could not flush stdout"); stdin .read_line(&mut input) .ok() .expect("could not read from stdin"); le...
read_coordinate
identifier_name
lib.rs
use std::fmt; use std::io; use std::io::Write; use thud_game::board::Cells; use thud_game::board::Content; use thud_game::coordinate::Coordinate; use thud_game::Role; pub fn prompt_for_piece(board: &Cells, role: Role) -> Coordinate { loop { let c = read_coordinate(); match board[c] { Content::Occupied...
}; match Coordinate::new(row, col) { None => { println!("coordinate out of playable range"); continue; } Some(c) => return c, } } } // pub fn write_search_graph(graph: &mcts::ThudGraph, state: &ThudState) { // println!("to play: {:?}", state.active_role()); // m...
{ println!("bad col"); continue; }
conditional_block
lib.rs
use std::fmt; use std::io; use std::io::Write; use thud_game::board::Cells; use thud_game::board::Content; use thud_game::coordinate::Coordinate; use thud_game::Role; pub fn prompt_for_piece(board: &Cells, role: Role) -> Coordinate { loop { let c = read_coordinate(); match board[c] { Content::Occupied...
print!("col? "); stdout.flush().ok().expect("could not flush stdout"); stdin .read_line(&mut input) .ok() .expect("could not read from stdin"); let col: u8 = match input.trim().parse() { Ok(c) if c <= 14 => c, _ => { println!("bad col"); continue; } ...
{ let stdin = io::stdin(); let mut stdout = io::stdout(); let mut input = String::new(); loop { input.clear(); print!("row? "); stdout.flush().ok().expect("could not flush stdout"); stdin .read_line(&mut input) .ok() .expect("could not read from stdin"); let row: u8 = match...
identifier_body
lib.rs
use std::fmt; use std::io; use std::io::Write; use thud_game::board::Cells; use thud_game::board::Content; use thud_game::coordinate::Coordinate; use thud_game::Role; pub fn prompt_for_piece(board: &Cells, role: Role) -> Coordinate { loop { let c = read_coordinate(); match board[c] { Content::Occupied...
.expect("could not read from stdin"); let row: u8 = match input.trim().parse() { Ok(r) if r <= 14 => r, _ => { println!("bad row"); continue; } }; input.clear(); print!("col? "); stdout.flush().ok().expect("could not flush stdout"); stdin .read_line(...
stdout.flush().ok().expect("could not flush stdout"); stdin .read_line(&mut input) .ok()
random_line_split
frozen_lj.py
""" this example shows how to freeze degrees of freedom using the Lennard Jones potential as an example """ import numpy as np from pele.potentials import LJ, FrozenPotentialWrapper from pele.optimize import mylbfgs def
(): natoms = 4 pot = LJ() reference_coords = np.random.uniform(-1, 1, [3 * natoms]) print reference_coords # freeze the first two atoms (6 degrees of freedom) frozen_dof = range(6) fpot = FrozenPotentialWrapper(pot, reference_coords, frozen_dof) reduced_coords = fpot.get_reduced_coor...
main
identifier_name
frozen_lj.py
""" this example shows how to freeze degrees of freedom using the Lennard Jones potential as an example """ import numpy as np from pele.potentials import LJ, FrozenPotentialWrapper from pele.optimize import mylbfgs def main(): natoms = 4 pot = LJ() reference_coords = np.random.uniform(-1, 1, [3 * natoms...
main()
conditional_block
frozen_lj.py
""" this example shows how to freeze degrees of freedom using the Lennard Jones potential as an example """ import numpy as np from pele.potentials import LJ, FrozenPotentialWrapper from pele.optimize import mylbfgs def main():
print "the coordinates of the frozen degrees of freedom are unchanged" print "starting coords:", reference_coords print "minimized coords:", fpot.get_full_coords(ret.coords) if __name__ == "__main__": main()
natoms = 4 pot = LJ() reference_coords = np.random.uniform(-1, 1, [3 * natoms]) print reference_coords # freeze the first two atoms (6 degrees of freedom) frozen_dof = range(6) fpot = FrozenPotentialWrapper(pot, reference_coords, frozen_dof) reduced_coords = fpot.get_reduced_coords(refer...
identifier_body
frozen_lj.py
""" this example shows how to freeze degrees of freedom using the Lennard Jones potential as an example """ import numpy as np from pele.potentials import LJ, FrozenPotentialWrapper from pele.optimize import mylbfgs def main(): natoms = 4 pot = LJ() reference_coords = np.random.uniform(-1, 1, [3 * natoms...
if __name__ == "__main__": main()
print "the coordinates of the frozen degrees of freedom are unchanged" print "starting coords:", reference_coords print "minimized coords:", fpot.get_full_coords(ret.coords)
random_line_split
borrowed-enum.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// // 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-androi...
// http://rust-lang.org/COPYRIGHT.
random_line_split
borrowed-enum.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
} fn zzz() {()}
{ // 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452 // 0b01111100011111000111110001111100 = 2088533116 // 0b0111110001111100 = 31868 // 0b01111100 = 124 let the_a = TheA { x: 0, y: 8970181431921507452 }; let the_a_ref: &ABC = &the_a; // 0b000100010...
identifier_body
borrowed-enum.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() {()}
zzz
identifier_name
test_custom_templates.py
# This file is part of Shuup. # # Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. import datetime import pytest from shuup.simple_cms.models import Page from shuup.simple_...
template_path = "shuup/simple_cms/" + template_name page = create_page(template_name=template_path, available_from=datetime.date(1988, 1, 1), shop=get_default_shop()) view_func = PageView.as_view() request = apply_request_middleware(rf.get("/")) response = view_func(request, url=page.url) response.r...
identifier_body
test_custom_templates.py
# This file is part of Shuup. # # Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. import datetime import pytest from shuup.simple_cms.models import Page from shuup.simple_...
(rf, template_name): template_path = "shuup/simple_cms/" + template_name page = create_page(template_name=template_path, available_from=datetime.date(1988, 1, 1), shop=get_default_shop()) view_func = PageView.as_view() request = apply_request_middleware(rf.get("/")) response = view_func(request, url...
test_superuser_can_see_invisible_page
identifier_name
test_custom_templates.py
# This file is part of Shuup. # # Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. import datetime import pytest
@pytest.mark.django_db @pytest.mark.parametrize("template_name", ["page.jinja", "page_sidebar.jinja"]) def test_superuser_can_see_invisible_page(rf, template_name): template_path = "shuup/simple_cms/" + template_name page = create_page(template_name=template_path, available_from=datetime.date(1988, 1, 1), sho...
from shuup.simple_cms.models import Page from shuup.simple_cms.views import PageView from shuup.testing.factories import get_default_shop from shuup.testing.utils import apply_request_middleware from shuup_tests.simple_cms.utils import create_page
random_line_split
behavior.ts
/* ***************************************************************************** * Caleydo - Visualization for Molecular Biology - http://caleydo.org * Copyright (c) The Caleydo Team. All rights reserved. * Licensed under the new BSD license, available at http://caleydo.org/license *********************************...
this.fire('zoom', { scale: s, rotate: old.rotate }, old); return this.v.transform(s, old.rotate); } /** * zooms to a given width and height based on the rawSize of the visualization * @param w * @param h * @returns {any} */ zoomTo(w: number, h: number) { if (!this.v) {...
{ //same aspect ratio use min scale s[0] = s[1] = Math.min(...s); }
conditional_block
behavior.ts
/* ***************************************************************************** * Caleydo - Visualization for Molecular Biology - http://caleydo.org * Copyright (c) The Caleydo Team. All rights reserved. * Licensed under the new BSD license, available at http://caleydo.org/license *********************************...
}, old); return this.v.transform(s, old.rotate); } /** * zooms to a given width and height based on the rawSize of the visualization * @param w * @param h * @returns {any} */ zoomTo(w: number, h: number) { if (!this.v) { return null; } const ori = this.v.rawSize; retu...
random_line_split
behavior.ts
/* ***************************************************************************** * Caleydo - Visualization for Molecular Biology - http://caleydo.org * Copyright (c) The Caleydo Team. All rights reserved. * Licensed under the new BSD license, available at http://caleydo.org/license *********************************...
get isWidthFixed() { return (this.meta && this.meta.scaling === 'height-only'); } get isHeightFixed() { return (this.meta && this.meta.scaling === 'width-only'); } get isFixedAspectRatio() { return (this.meta && this.meta.scaling === 'aspect'); } /** * set specific zoom factors * @p...
{ if (!this.v) { return null; } function toDelta(x: number) { return x > 0 ? 0.2 : (x < 0 ? -0.2 : 0); } const old = this.v.transform(); const deltaX = toDelta(zoomX); const deltaY = toDelta(zoomY); return this.zoomSet(old.scale[0] + deltaX, old.scale[1] + deltaY); }
identifier_body
behavior.ts
/* ***************************************************************************** * Caleydo - Visualization for Molecular Biology - http://caleydo.org * Copyright (c) The Caleydo Team. All rights reserved. * Licensed under the new BSD license, available at http://caleydo.org/license *********************************...
() { return this.zoom(1, 1); } zoomOut() { return this.zoom(-1, -1); } /** * zooms in/out, -1 = zoom out, +1 zoom in, 0 no zoom operation * @param zoomX * @param zoomY * @returns {any} */ zoom(zoomX: number, zoomY: number) { if (!this.v) { return null; } function toD...
zoomIn
identifier_name
register.js
/** * Created by panos on 4/5/16. */ import angular from 'angular/index' let _app = new WeakMap() export default class Register { constructor (appName, deps) { deps = deps || [] let module try { module = angular.module(appName) } catch (error) { module = angular.module(appName, deps) ...
run (constructorFn) { constructorFn = this._normalizeConstructor(constructorFn) let factoryArray = this._createFactoryArray(constructorFn) _app.get(this).run(factoryArray) return this } service (name, constructorFn) { _app.get(this).service(name, constructorFn) return this } val...
{ _app.get(this).provider(name, constructorFn) return this }
identifier_body
register.js
/** * Created by panos on 4/5/16. */ import angular from 'angular/index' let _app = new WeakMap() export default class
{ constructor (appName, deps) { deps = deps || [] let module try { module = angular.module(appName) } catch (error) { module = angular.module(appName, deps) } _app.set(this, module) } config (constructorFn) { constructorFn = this._normalizeConstructor(constructorFn) l...
Register
identifier_name
register.js
/** * Created by panos on 4/5/16. */ import angular from 'angular/index' let _app = new WeakMap() export default class Register { constructor (appName, deps) { deps = deps || [] let module try { module = angular.module(appName) } catch (error) { module = angular.module(appName, deps) ...
} }) let factoryArray = this._createFactoryArray(constructorFn) _app.get(this).directive(name, factoryArray) return this } factory (name, constructorFn) { constructorFn = this._normalizeConstructor(constructorFn) let factoryArray = this._createFactoryArray(constructorFn) _app....
{ return constructorFn.prototype.link.bind(this) }
conditional_block
register.js
/** * Created by panos on 4/5/16. */ import angular from 'angular/index' let _app = new WeakMap() export default class Register { constructor (appName, deps) { deps = deps || [] let module try { module = angular.module(appName) } catch (error) { module = angular.module(appName, deps) ...
_app.get(this).config(factoryArray) return this } constant (name, obj) { _app.get(this).constant(name, obj) return this } controller (name, constructorFn) { _app.get(this).controller(name, constructorFn) return this } directive (name, constructorFn) { constructorFn = this....
config (constructorFn) { constructorFn = this._normalizeConstructor(constructorFn) let factoryArray = this._createFactoryArray(constructorFn)
random_line_split
experiment.py
ImageEnhance, ImageChops, ImageFilter from io import BytesIO, StringIO import time import sys, os import codecs url = 'http://d1222391-23d7-46de-abef-73cbb63c1862.levels.pathwar.net' imgurl = url + '/captcha.php' headers = { 'Host' : 'd1222391-23d7-46de-abef-73cbb63c1862.levels.pathwar.net', 'User-Agent'...
datfile.close() datfile = open("ads.dat", "at") for bound in bounds: img.crop(bound).show() letter = input("Type in the letters you see in the image above (ENTER to skip): ") bmpfile = BytesIO() img.crop(bound).save(bmpfile, format='BMP') # g = codecs.encode...
random_line_split
experiment.py
Enhance, ImageChops, ImageFilter from io import BytesIO, StringIO import time import sys, os import codecs url = 'http://d1222391-23d7-46de-abef-73cbb63c1862.levels.pathwar.net' imgurl = url + '/captcha.php' headers = { 'Host' : 'd1222391-23d7-46de-abef-73cbb63c1862.levels.pathwar.net', 'User-Agent' : 'Mo...
(img, bounds): # read dataset of images for each letter imgs = {} datfile = open("ads.dat", "rt") line = datfile.readline() while line!="": key = line[0] if key not in imgs: imgs[key] = [] imgs[key].append(Image.open(StringIO.StringIO(line[2:-1].decode("hex")))) ...
recognize
identifier_name
experiment.py
ImageEnhance, ImageChops, ImageFilter from io import BytesIO, StringIO import time import sys, os import codecs url = 'http://d1222391-23d7-46de-abef-73cbb63c1862.levels.pathwar.net' imgurl = url + '/captcha.php' headers = { 'Host' : 'd1222391-23d7-46de-abef-73cbb63c1862.levels.pathwar.net', 'User-Agent'...
# im2 = im2.convert("RGB") im2 = im2.resize((im2.size[0]*8, im2.size[1]*8), Image.BILINEAR) # im2 = im2.resize((int(im2.size[0] / 2), int(im2.size[1] / 2)), Image.ANTIALIAS) # im2 = ImageEnhance.Contrast(im2).enhance(1.4) # im2 = ImageEnhance.Sharpness(im2).enhance(5) # im2 = ImageChops.invert(...
pix = im.getpixel((y,x)) if pix == 1: # these are the numbers to get im2.putpixel((y,x),0)
conditional_block
experiment.py
ImageEnhance, ImageChops, ImageFilter from io import BytesIO, StringIO import time import sys, os import codecs url = 'http://d1222391-23d7-46de-abef-73cbb63c1862.levels.pathwar.net' imgurl = url + '/captcha.php' headers = { 'Host' : 'd1222391-23d7-46de-abef-73cbb63c1862.levels.pathwar.net', 'User-Agent'...
if left!=0 and colPixCnts[col]<=20: # if (begin is set) and (col no letter) right = col # then letter end if right-left>8: # if (the letter is wide enough) ############################################## print((right-left)) top = -1 ...
colPixCnts = [] for col in range(img.size[0]): pixels = list(img.crop([col, 0, col+1, img.size[1]]).getdata()) colPixCnts.append(sum(i==0 for i in pixels)) print (colPixCnts) print("\n") # average out pixel counts for trough column for i in range(3, len(colPixCnts)-3, 2): if ...
identifier_body
setup.py
# -*- coding: utf-8 -*- from distutils.core import setup from distutils.command.build import build as _build from distutils.command.install import install as _install from distutils.command.install_data import install_data as _install_data from distutils.command.sdist import sdist as _sdist from distutils.extension imp...
(_install_data): def run (self): def chmod_data_file (file): try: os.chmod (file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) except: self.warn ("Could not chmod data file %s" % file) _install_data.run (self) map (chmod_data_file, self.get...
install_data
identifier_name
setup.py
# -*- coding: utf-8 -*- from distutils.core import setup from distutils.command.build import build as _build from distutils.command.install import install as _install from distutils.command.install_data import install_data as _install_data from distutils.command.sdist import sdist as _sdist from distutils.extension imp...
file = open (INSTALLED_FILES, "w") except: self.warn ("Could not write installed files list %s" % \ INSTALLED_FILES) return file.write (data) file.close () class install_data (_install_data): def run (self): def chmod_data...
for counter in xrange (len (outputs)): outputs[counter] = outputs[counter][length:] data = "\n".join (outputs) try:
random_line_split
setup.py
# -*- coding: utf-8 -*- from distutils.core import setup from distutils.command.build import build as _build from distutils.command.install import install as _install from distutils.command.install_data import install_data as _install_data from distutils.command.sdist import sdist as _sdist from distutils.extension imp...
version_file = open ("VERSION", "r") version = version_file.read ().strip () if "=" in version: version = version.split ("=")[1] def pkgconfig(*packages, **kw): flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries', '-R': 'runtime_library_dirs'} cmd = ['pkg-config', '--libs', '--cflag...
from distutils.command.build_ext import build_ext ext_module_src = "src/compizconfig.c"
conditional_block
setup.py
# -*- coding: utf-8 -*- from distutils.core import setup from distutils.command.build import build as _build from distutils.command.install import install as _install from distutils.command.install_data import install_data as _install_data from distutils.command.sdist import sdist as _sdist from distutils.extension imp...
def add_defaults (self): _sdist.add_defaults (self) # Remove pyx source and add c source if os.path.exists ("src/compizconfig.pyx"): self.filelist.exclude_pattern ("src/compizconfig.pyx") self.filelist.append ("src/compizconfig.c") setup ( name = "compizconfig-py...
if os.path.exists ("src/compizconfig.pyx"): from Cython.Compiler.Main import compile as cython_compile cython_compile ("src/compizconfig.pyx") # Run regular sdist _sdist.run (self)
identifier_body
macros.rs
// Most of our lookups follow the same pattern - macro out the repetition. macro_rules! ares_call { ( $ares_call:ident, $channel:expr, $name:expr, $dns_class:expr, $query_type:expr, $callback:expr, $handler:expr ) => {{ let c_name = CString::new($n...
$dns_class as c_int, $query_type as c_int, Some($callback), c_arg as *mut c_void, ); } panic::propagate(); }}; } macro_rules! ares_query { ($($arg:tt)*) => { ares_call!(ares_query, $($arg)*) } } macro_rules! ares_searc...
$channel, c_name.as_ptr(),
random_line_split
ThemeBuilder.tsx
import { ReactElement } from "react"; import { Grid } from "@react-md/utils"; import scssVariables from "@react-md/theme/dist/scssVariables"; import { useTheme } from "components/Theme"; import ThemeConfiguration from "./ThemeConfiguration"; import Preview from "./Preview"; import ThemeUsage from "./ThemeUsage"; imp...
(): ReactElement { const { primary, secondary, accent, theme } = useTheme(); const primaryName = `rmd-${primary}-500` as "rmd-teal-500"; const primaryColor = scssVariables[primaryName]; const secondaryName = `rmd-${secondary}-a-${accent}` as "rmd-pink-a-200"; const secondaryColor = scssVariables[secondaryName...
ThemeBuilder
identifier_name
ThemeBuilder.tsx
import { ReactElement } from "react"; import { Grid } from "@react-md/utils"; import scssVariables from "@react-md/theme/dist/scssVariables"; import { useTheme } from "components/Theme"; import ThemeConfiguration from "./ThemeConfiguration"; import Preview from "./Preview"; import ThemeUsage from "./ThemeUsage"; imp...
theme={theme} primaryColor={primaryColor} secondaryColor={secondaryColor} /> <Preview /> <ThemeUsage primary={primary} secondary={secondary} accent={accent} theme={theme} /> </Grid> ); }
accent={accent}
random_line_split
ThemeBuilder.tsx
import { ReactElement } from "react"; import { Grid } from "@react-md/utils"; import scssVariables from "@react-md/theme/dist/scssVariables"; import { useTheme } from "components/Theme"; import ThemeConfiguration from "./ThemeConfiguration"; import Preview from "./Preview"; import ThemeUsage from "./ThemeUsage"; imp...
secondary={secondary} accent={accent} theme={theme} /> </Grid> ); }
{ const { primary, secondary, accent, theme } = useTheme(); const primaryName = `rmd-${primary}-500` as "rmd-teal-500"; const primaryColor = scssVariables[primaryName]; const secondaryName = `rmd-${secondary}-a-${accent}` as "rmd-pink-a-200"; const secondaryColor = scssVariables[secondaryName]; return ( ...
identifier_body
database_client.py
from collections import defaultdict import pandas as pd import pickle from sqlalchemy import create_engine, inspect, Table, Column from sqlalchemy.engine.url import make_url from sys import exit class DatabaseClient: """ Takes care of the database pass opening to find the url and can query the respected ...
outfile.close()
random_line_split
database_client.py
from collections import defaultdict import pandas as pd import pickle from sqlalchemy import create_engine, inspect, Table, Column from sqlalchemy.engine.url import make_url from sys import exit class DatabaseClient: """ Takes care of the database pass opening to find the url and can query the respected ...
def get_db_url(self): with open(self.dbpass_path, 'r') as infile: db_names = [] for raw_url in infile.read().splitlines(): url_obj = make_url(raw_url) if url_obj.database == self.dbname: infile.close() return r...
self.dbpass_path = dbpass_path self.dbname = dbname self.db_url = self.get_db_url() self.engine = create_engine(self.db_url)
identifier_body
database_client.py
from collections import defaultdict import pandas as pd import pickle from sqlalchemy import create_engine, inspect, Table, Column from sqlalchemy.engine.url import make_url from sys import exit class DatabaseClient: """ Takes care of the database pass opening to find the url and can query the respected ...
(self, query, output): """ Dumps in df in chunks to avoid crashes. """ chunk_size = 100000 offset = 0 data = defaultdict(lambda : defaultdict(list)) with open(output, 'wb') as outfile: query = query.replace(';', '') query += """ LIMIT {chunk_size}...
create_df_file_with_query
identifier_name
database_client.py
from collections import defaultdict import pandas as pd import pickle from sqlalchemy import create_engine, inspect, Table, Column from sqlalchemy.engine.url import make_url from sys import exit class DatabaseClient: """ Takes care of the database pass opening to find the url and can query the respected ...
outfile.close()
print(offset) query = query.format( chunk_size=chunk_size, offset=offset ) df = pd.read_sql(query, self.engine) pickle.dump(df, outfile) offset += chunk_size if len(df) < chunk_size: ...
conditional_block
iptorrents.py
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with SickRage. If not, see <http://www.gnu.org/licenses/>. import re import traceback import datetime import urlparse import sick...
sqlResults = myDB.select( 'SELECT s.show_name, e.showid, e.season, e.episode, e.status, e.airdate FROM tv_episodes AS e' + ' INNER JOIN tv_shows AS s ON (e.showid = s.indexer_id)' + ' WHERE e.airdate >= ' + str(search_date.toordinal()) + ' AND (e.status IN (' + ',...
myDB = db.DBConnection()
random_line_split
iptorrents.py
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with SickRage. If not, see <http://www.gnu.org/licenses/>. import re import traceback import datetime import urlparse import sick...
def getQuality(self, item, anime=False): quality = Quality.sceneQuality(item[0], anime) return quality def _checkAuth(self): if not self.username or not self.password: raise AuthException("Your authentication credentials for " + self.name + " are missing, check your conf...
return 'iptorrents.png'
identifier_body
iptorrents.py
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with SickRage. If not, see <http://www.gnu.org/licenses/>. import re import traceback import datetime import urlparse import sick...
(self, search_params, search_mode='eponly', epcount=0, age=0): results = [] items = {'Season': [], 'Episode': [], 'RSS': []} freeleech = '&free=on' if self.freeleech else '' if not self._doLogin(): return results for mode in search_params.keys(): for s...
_doSearch
identifier_name
iptorrents.py
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with SickRage. If not, see <http://www.gnu.org/licenses/>. import re import traceback import datetime import urlparse import sick...
if html.find(text='No Torrents Found!'): logger.log(u"No results found for: " + search_string + " (" + searchURL + ")", logger.DEBUG) continue torrent_table = html.find('table', attrs={'class': 'torrents'}) ...
logger.log(u"Invalid HTML data: " + str(data), logger.DEBUG) continue
conditional_block
conftest.py
# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
@pytest.fixture def file_data(client, bucket): blob = client.bucket(bucket.name).blob(uuid.uuid4().hex) payload = _create_block(_SIZE_9MB) blob.upload_from_string(payload) yield blob, payload try: blob.delete() except NotFound: # in cases where object is deleted within the test ...
hmac_key, _secret = client.create_hmac_key( service_account_email=_CONF_TEST_SERVICE_ACCOUNT_EMAIL, project_id=_CONF_TEST_PROJECT_ID, ) yield hmac_key try: hmac_key.state = "INACTIVE" hmac_key.update() hmac_key.delete() except NotFound: # in cases where hmac_key ...
identifier_body
conftest.py
# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
def hmac_key(client): hmac_key, _secret = client.create_hmac_key( service_account_email=_CONF_TEST_SERVICE_ACCOUNT_EMAIL, project_id=_CONF_TEST_PROJECT_ID, ) yield hmac_key try: hmac_key.state = "INACTIVE" hmac_key.update() hmac_key.delete() except NotFound: ...
@pytest.fixture
random_line_split
conftest.py
# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
(client, bucket): notification = client.bucket(bucket.name).notification( topic_name=_CONF_TEST_PUBSUB_TOPIC_NAME ) notification.create() notification.reload() yield notification try: notification.delete() except NotFound: # in cases where notification is deleted within the ...
notification
identifier_name
t411.py
from __future__ import unicode_literals, division, absolute_import from builtins import * # pylint: disable=unused-import, redefined-builtin from flexget import options, plugin from flexget.event import event from flexget.terminal import console from flexget.manager import Session try: from flexget.plugins.inter...
@event('options.register') def register_parser_arguments(): # Register the command parser = options.register_command('t411', do_cli, help='view and manipulate the Torrent411 plugin database') # Set up our subparsers action_parsers = parser.add_subparsers(title='actions', metavar='<action>', dest='t4...
""" Print category and its sub-categories :param parent_category_name: if None, all categories will be displayed :return: """ proxy = T411Proxy() proxy.set_credential() with Session() as session: if parent_category_name is None: categories = proxy.main_categories(session=...
identifier_body
t411.py
from __future__ import unicode_literals, division, absolute_import from builtins import * # pylint: disable=unused-import, redefined-builtin from flexget import options, plugin from flexget.event import event from flexget.terminal import console from flexget.manager import Session try: from flexget.plugins.inter...
else: with Session() as session: categories = proxy.find_categories(category_name=category_name, is_sub_category=True, session=session) for category in categories: console(formatting_main % (category.name, category.parent_id, category.id)) for term_typ...
if term_type_name: console("Not yet implemented !")
random_line_split
t411.py
from __future__ import unicode_literals, division, absolute_import from builtins import * # pylint: disable=unused-import, redefined-builtin from flexget import options, plugin from flexget.event import event from flexget.terminal import console from flexget.manager import Session try: from flexget.plugins.inter...
(): # Register the command parser = options.register_command('t411', do_cli, help='view and manipulate the Torrent411 plugin database') # Set up our subparsers action_parsers = parser.add_subparsers(title='actions', metavar='<action>', dest='t411_action') auth_parser = action_parsers.add_parser('ad...
register_parser_arguments
identifier_name
t411.py
from __future__ import unicode_literals, division, absolute_import from builtins import * # pylint: disable=unused-import, redefined-builtin from flexget import options, plugin from flexget.event import event from flexget.terminal import console from flexget.manager import Session try: from flexget.plugins.inter...
formatting_main = '%-30s %-5s %-5s' formatting_sub = ' %-25s %-5s %-5s' console(formatting_main % ('Category name', 'PID', 'ID')) for category in categories: console(formatting_main % (category.name, category.parent_id, category.id)) for sub_category in categ...
categories = proxy.find_categories(parent_category_name, session=session)
conditional_block
rapidvideo.py
# -*- coding: iso-8859-1 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Conector para rapidvideo # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import urllib,re from core import scrapertools from...
): video_urls = get_video_url( "http://www.rapidvideo.org/xr1nb7cfh58a" ) return len( video_urls ) > 0
est(
identifier_name
rapidvideo.py
# Conector para rapidvideo # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import urllib,re from core import scrapertools from core import logger from lib.jsbeautifier.unpackers import packer def test_video_exists( page_url ): logger.info( ...
# -*- coding: iso-8859-1 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin
random_line_split
rapidvideo.py
# -*- coding: iso-8859-1 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Conector para rapidvideo # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import urllib,re from core import scrapertools from...
return True, "" def get_video_url( page_url, premium = False, user="", password="", video_password="" ): logger.info( "[rapidvideo.py] url=" + page_url ) video_id = scrapertools.get_match( page_url, 'org/([A-Za-z0-9]+)' ) url = 'http://www.rapidvideo.org/embed-%s-607x360.html' % video_id #data ...
return False, "The file not exists or was removed from RapidVideo."
conditional_block
rapidvideo.py
# -*- coding: iso-8859-1 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Conector para rapidvideo # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import urllib,re from core import scrapertools from...
def get_video_url( page_url, premium = False, user="", password="", video_password="" ): logger.info( "[rapidvideo.py] url=" + page_url ) video_id = scrapertools.get_match( page_url, 'org/([A-Za-z0-9]+)' ) url = 'http://www.rapidvideo.org/embed-%s-607x360.html' % video_id #data = scrapertools.cache_...
logger.info( "[rapidvideo.py] test_video_exists(page_url='%s')" % page_url ) video_id = scrapertools.get_match( page_url, 'org/([A-Za-z0-9]+)' ) url = 'http://www.rapidvideo.org/embed-%s-607x360.html' % video_id data = scrapertools.cache_page( url ) if "The file was removed from RapidVideo" in data: ...
identifier_body
stylus.js
/*! * Stylus * Copyright(c) 2010 LearnBoost <dev@learnboost.com> * MIT Licensed */ /** * Module dependencies. */ var Renderer = require('./renderer') , Parser = require('./parser') , nodes = require('./nodes') , utils = require('./utils'); /** * Export render as the module. */ exports = module.exports...
* @api public */ exports.render = function(str, options, fn){ if ('function' == typeof options) fn = options, options = {}; new Renderer(str, options).render(fn); }; /** * Return a new `Renderer` for the given `str` and `options`. * * @param {String} str * @param {Object} options * @return {Renderer} * @a...
* @param {String} str * @param {Object|Function} options * @param {Function} fn
random_line_split
stylus.js
/*! * Stylus * Copyright(c) 2010 LearnBoost <dev@learnboost.com> * MIT Licensed */ /** * Module dependencies. */ var Renderer = require('./renderer') , Parser = require('./parser') , nodes = require('./nodes') , utils = require('./utils'); /** * Export render as the module. */ exports = module.export...
(str, options) { return new Renderer(str, options); } /** * Expose optional functions. */ exports.url = require('./functions/url');
render
identifier_name
stylus.js
/*! * Stylus * Copyright(c) 2010 LearnBoost <dev@learnboost.com> * MIT Licensed */ /** * Module dependencies. */ var Renderer = require('./renderer') , Parser = require('./parser') , nodes = require('./nodes') , utils = require('./utils'); /** * Export render as the module. */ exports = module.export...
/** * Expose optional functions. */ exports.url = require('./functions/url');
{ return new Renderer(str, options); }
identifier_body
noise.py
# Copyright 2015 The TensorFlow 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 applica...
class AlphaDropout(Layer): """Applies Alpha Dropout to the input. Alpha Dropout is a `Dropout` that keeps mean and variance of inputs to their original values, in order to ensure the self-normalizing property even after this dropout. Alpha Dropout fits well to Scaled Exponential Linear Units by randomly...
config = {'rate': self.rate} base_config = super(GaussianDropout, self).get_config() return dict(list(base_config.items()) + list(config.items()))
identifier_body
noise.py
# Copyright 2015 The TensorFlow 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 applica...
return inputs def get_config(self): config = {'rate': self.rate} base_config = super(AlphaDropout, self).get_config() return dict(list(base_config.items()) + list(config.items()))
noise_shape = self._get_noise_shape(inputs) alpha = 1.6732632423543772848170429916717 scale = 1.0507009873554804934193349852946 def dropped_inputs(inputs=inputs, rate=self.rate, seed=self.seed): alpha_p = -alpha * scale kept_idx = K.greater_equal(K.random_uniform(noise_shape, seed=see...
conditional_block
noise.py
# Copyright 2015 The TensorFlow 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 applica...
when using this layer as the first layer in a model. Output shape: Same shape as input. References: - [Dropout: A Simple Way to Prevent Neural Networks from Overfitting Srivastava, Hinton, et al. 2014](http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf) """ def __i...
standard deviation `sqrt(rate / (1 - rate))`. Input shape: Arbitrary. Use the keyword argument `input_shape` (tuple of integers, does not include the samples axis)
random_line_split
noise.py
# Copyright 2015 The TensorFlow 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 applica...
(self): config = {'rate': self.rate} base_config = super(GaussianDropout, self).get_config() return dict(list(base_config.items()) + list(config.items())) class AlphaDropout(Layer): """Applies Alpha Dropout to the input. Alpha Dropout is a `Dropout` that keeps mean and variance of inputs to their o...
get_config
identifier_name
AbstractHiloIdGenerator.ts
import { IHiloIdGenerator } from "./IHiloIdGenerator"; import { IDocumentStore } from "../../Documents/IDocumentStore"; import { DocumentConventions } from "../../Documents/Conventions/DocumentConventions"; import { IRavenObject } from "../../Types/IRavenObject"; import { getLogger } from "../../Utility/LogUtil"; cons...
} public returnUnusedRange(): Promise<void> { const returnPromises = Object.keys(this._generators) .map(key => { return Promise.resolve() .then(() => this._generators[key].returnUnusedRange()) .catch(err => { lo...
this._dbName = dbName || store.database;
random_line_split
AbstractHiloIdGenerator.ts
import { IHiloIdGenerator } from "./IHiloIdGenerator"; import { IDocumentStore } from "../../Documents/IDocumentStore"; import { DocumentConventions } from "../../Documents/Conventions/DocumentConventions"; import { IRavenObject } from "../../Types/IRavenObject"; import { getLogger } from "../../Utility/LogUtil"; cons...
public returnUnusedRange(): Promise<void> { const returnPromises = Object.keys(this._generators) .map(key => { return Promise.resolve() .then(() => this._generators[key].returnUnusedRange()) .catch(err => { log.war...
{ this._tag = tag; this._store = store; this._conventions = store.conventions; this._dbName = dbName || store.database; }
identifier_body
AbstractHiloIdGenerator.ts
import { IHiloIdGenerator } from "./IHiloIdGenerator"; import { IDocumentStore } from "../../Documents/IDocumentStore"; import { DocumentConventions } from "../../Documents/Conventions/DocumentConventions"; import { IRavenObject } from "../../Types/IRavenObject"; import { getLogger } from "../../Utility/LogUtil"; cons...
(): Promise<void> { const returnPromises = Object.keys(this._generators) .map(key => { return Promise.resolve() .then(() => this._generators[key].returnUnusedRange()) .catch(err => { log.warn(err, "Error returning unused...
returnUnusedRange
identifier_name
lib.rs
color library #![crate_id = "term#0.10"] #![comment = "Simple ANSI color library"] #![license = "MIT/ASL2"] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", ht...
(&mut self, color: color::Color) -> io::IoResult<bool> { let color = self.dim_if_necessary(color); if self.num_colors > color { let s = expand(self.ti .strings .find_equiv(&("setab")) .unwrap() ...
bg
identifier_name
lib.rs
color library #![crate_id = "term#0.10"] #![comment = "Simple ANSI color library"] #![license = "MIT/ASL2"] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", ht...
if ti.is_err() { return Err(ti.unwrap_err()); } let inf = ti.unwrap(); let nc = if inf.strings.find_equiv(&("setaf")).is_some() && inf.strings.find_equiv(&("setab")).is_some() { inf.numbers.find_equiv(&("colors")).map_or(0, |&n| n) ...
let mut file = entry.unwrap(); let ti = parse(&mut file, false);
random_line_split
lib.rs
http://www.rust-lang.org/favicon.ico", html_root_url = "http://static.rust-lang.org/doc/master")] #![feature(macro_rules)] #![deny(missing_doc)] extern crate collections; use std::io; use std::os; use terminfo::TermInfo; use terminfo::searcher::open; use terminfo::parser::compiled::{parse, msys_terminfo}; use...
{ let mut cap = self.ti.strings.find_equiv(&("sgr0")); if cap.is_none() { // are there any terminals that have color/attrs and not sgr0? // Try falling back to sgr, then op cap = self.ti.strings.find_equiv(&("sgr")); if cap.is_none() { cap ...
identifier_body
lib.rs
library #![crate_id = "term#0.10"] #![comment = "Simple ANSI color library"] #![license = "MIT/ASL2"] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_roo...
let mut file = entry.unwrap(); let ti = parse(&mut file, false); if ti.is_err() { return Err(ti.unwrap_err()); } let inf = ti.unwrap(); let nc = if inf.strings.find_equiv(&("setaf")).is_some() && inf.strings.find_equiv(&("setab")).is_some()...
{ if "cygwin" == term { // msys terminal return Ok(Terminal {out: out, ti: msys_terminfo(), num_colors: 8}); } return Err(entry.unwrap_err()); }
conditional_block
definitions.d.ts
// import all definitions // don't reference this file from your typescript files, instead use the TS file: // import refdef = require('lib/ReferenceDefinitions'); ///<reference path="../require/require.d.ts" /> ///<reference path="../jquery/jquery.d.ts" /> ///<reference path="../mootools/mootools.d.ts" /> ///<referen...
{ // dummy export, needed for not removing the import var ext:any; export = ext; } declare module "app/config/config" { // dummy export, needed for not removing the import var cfg:any; export = cfg; } // declare global libaries and variables that have no typescript definitions declare var DEBUG:boolean; declar...
random_line_split
create-document.7.x.py
# Download the Python helper library from twilio.com/docs/python/install import os from twilio.rest import Client from datetime import datetime # Your Account Sid and Auth Token from twilio.com/user/account # To set up environmental variables, see http://twil.io/secure account_sid = os.environ['TWILIO_ACCOUNT_SID'] au...
'genre': "Romance" } document = client.sync \ .services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ .documents \ .create(unique_name="MyFirstDocument", data=data, ttl=1814400) # expires in 21 days print(document.sid)
'movie_title': "On The Line", 'show_times': ["12:30:00Z", "14:45:00Z", "15:30:00Z", "17:45:00Z"], 'starring': ["Lance Bass", "Joey Fatone"],
random_line_split
i18n.js
// i18n.js App.i18n = { strings: {}, loaded: false, setLanguage: function(languageCode, callback) { this.languageCode = languageCode; App.localStorage.set('selected_interface_locale', languageCode); this.loadStrings(callback); }, getLanguage: function(languageCode) {
stringId = string; if (typeof(this.strings[stringId]) === 'undefined' || this.strings[stringId] === false || this.strings[stringId] === '') return string; else return this.strings[stringId]; }, translateDOM: function() { var that = this; $("[data-i18n]").each(function() { var string = $(this).data...
return this.languageCode; }, translate: function(string, stringId) { if (typeof(stringId) == 'undefined')
random_line_split
silence.rs
// STD Dependencies ----------------------------------------------------------- use std::fmt; // Internal Dependencies ------------------------------------------------------ use ::bot::{Bot, BotConfig}; use ::core::{EventQueue, Message}; use ::action::{ActionHandler, ActionGroup}; // Action Implementation ---------...
(&mut self, bot: &mut Bot, _: &BotConfig, _: &mut EventQueue) -> ActionGroup { if let Some(server) = bot.get_server(&self.message.server_id) { server.silence_active_effects() } vec![] } } impl fmt::Display for Action { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { ...
run
identifier_name
silence.rs
// STD Dependencies ----------------------------------------------------------- use std::fmt; // Internal Dependencies ------------------------------------------------------ use ::bot::{Bot, BotConfig}; use ::core::{EventQueue, Message}; use ::action::{ActionHandler, ActionGroup}; // Action Implementation ---------...
vec![] } } impl fmt::Display for Action { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "[Action] [SilenceActiveEffects] Server #{}", self.message.server_id ) } }
{ server.silence_active_effects() }
conditional_block