file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
user.py
from flask import (Blueprint, request, session, g, render_template, url_for, redirect, jsonify) from werkzeug.contrib.cache import SimpleCache from flask.ext.oauthlib.client import OAuth, OAuthException bp = Blueprint('user', __name__) oauth = OAuth() github = oauth.remote_app( 'github', app_...
(): """사용자가 GitHub 계정으로 인증한 상태인지 확인한다""" try: token, _ = session['github_token'] except KeyError: g.user_info = None return None user_data = _cache.get('user_info:' + token) if user_data is None: try: resp = github.get('user') except OAuthException...
authenticated
identifier_name
user.py
from flask import (Blueprint, request, session, g, render_template, url_for, redirect, jsonify) from werkzeug.contrib.cache import SimpleCache from flask.ext.oauthlib.client import OAuth, OAuthException bp = Blueprint('user', __name__) oauth = OAuth() github = oauth.remote_app( 'github', app_...
user_data = resp.data _cache.set('user_info:' + token, user_data) g.user_info = user_data return user_data @bp.route('/login') def login(): return github.authorize(callback=url_for('.authorized', _external=True)) @bp.route('/logout') def logout(): session.pop('github_token', ...
session.pop('github_token', None) user_data = None else:
random_line_split
user.py
from flask import (Blueprint, request, session, g, render_template, url_for, redirect, jsonify) from werkzeug.contrib.cache import SimpleCache from flask.ext.oauthlib.client import OAuth, OAuthException bp = Blueprint('user', __name__) oauth = OAuth() github = oauth.remote_app( 'github', app_...
n user_data @bp.route('/login') def login(): return github.authorize(callback=url_for('.authorized', _external=True)) @bp.route('/logout') def logout(): session.pop('github_token', None) return redirect(url_for('home.index')) @bp.route('/login/authorized') @github.authorized_handler def authorized(res...
er') except OAuthException: session.pop('github_token', None) user_data = None else: user_data = resp.data _cache.set('user_info:' + token, user_data) g.user_info = user_data retur
conditional_block
AuthController.js
/** * Created by Roman on 16.12.13. */ var moment = require('moment'); function AuthController($scope, $api) { var ctrl = this; $scope.client_id = store.get('client_id'); $scope.api_key = store.get('api_key'); $scope.api_secret = store.get('api_secret'); $scope.err = null; // catch html p...
// notify parent that we authenticated $scope.$parent.authenticated(); NProgress.done(); }) .error(function(){ $scope.err = "Failed to verify credentials. Are they correct?"; NProgress.done(); }); }...
random_line_split
AuthController.js
/** * Created by Roman on 16.12.13. */ var moment = require('moment'); function AuthController($scope, $api)
// save data store.set('client_id', $scope.client_id); store.set('api_key', $scope.api_key); store.set('api_secret', $scope.api_secret); store.set('transactions', transactions); store.set('transactions_updated', moment().un...
{ var ctrl = this; $scope.client_id = store.get('client_id'); $scope.api_key = store.get('api_key'); $scope.api_secret = store.get('api_secret'); $scope.err = null; // catch html pieces var $modal = $('#modal-auth').modal({backdrop: true, show: false}); $scope.authenticate_clicked = ...
identifier_body
AuthController.js
/** * Created by Roman on 16.12.13. */ var moment = require('moment'); function
($scope, $api) { var ctrl = this; $scope.client_id = store.get('client_id'); $scope.api_key = store.get('api_key'); $scope.api_secret = store.get('api_secret'); $scope.err = null; // catch html pieces var $modal = $('#modal-auth').modal({backdrop: true, show: false}); $scope.authenti...
AuthController
identifier_name
scale_button.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hop...
}
{ unsafe { gtk::Adjustment::wrap_pointer(ffi::gtk_scale_button_get_adjustment(GTK_SCALEBUTTON(self.unwrap_widget()))) } }
identifier_body
scale_button.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hop...
} }
fn get_adjustment(&self) -> gtk::Adjustment { unsafe { gtk::Adjustment::wrap_pointer(ffi::gtk_scale_button_get_adjustment(GTK_SCALEBUTTON(self.unwrap_widget()))) }
random_line_split
scale_button.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hop...
(&mut self, value: f64) -> () { unsafe { ffi::gtk_scale_button_set_value(GTK_SCALEBUTTON(self.unwrap_widget()), value as c_double); } } fn get_value(&self) -> f64 { unsafe { ffi::gtk_scale_button_get_value(GTK_SCALEBUTTON(self.unwrap_widget())) as f64 } ...
set_value
identifier_name
mod.rs
use std::default::Default; use std::str::FromStr; use std::string::ToString; mod tag; pub use self::tag::Tag; #[derive(Debug)] pub struct Playlist { tags: Vec<Tag> } impl Default for Playlist { fn default() -> Playlist { let mut tags: Vec<Tag> = Vec::new(); tags.push(Tag::M3U); tags....
} impl FromStr for Playlist { type Err = (); fn from_str(s: &str) -> Result<Playlist, ()> { let mut lines: Vec<&str> = s.split("#").collect(); lines.remove(0); let mut tags: Vec<Tag> = Vec::new(); for line in lines.iter(){ match Tag::from_str(line.trim()) { ...
random_line_split
mod.rs
use std::default::Default; use std::str::FromStr; use std::string::ToString; mod tag; pub use self::tag::Tag; #[derive(Debug)] pub struct Playlist { tags: Vec<Tag> } impl Default for Playlist { fn default() -> Playlist { let mut tags: Vec<Tag> = Vec::new(); tags.push(Tag::M3U); tags...
(&self) -> String { self.tags.iter().map(|tag: &Tag| -> String { tag.to_string() }).collect::<Vec<String>>().join("\n") } } impl FromStr for Playlist { type Err = (); fn from_str(s: &str) -> Result<Playlist, ()> { let mut lines: Vec<&str> = s.split("#").collect(); ...
to_string
identifier_name
mod.rs
use std::default::Default; use std::str::FromStr; use std::string::ToString; mod tag; pub use self::tag::Tag; #[derive(Debug)] pub struct Playlist { tags: Vec<Tag> } impl Default for Playlist { fn default() -> Playlist { let mut tags: Vec<Tag> = Vec::new(); tags.push(Tag::M3U); tags...
}
{ self.tags.as_slice() }
identifier_body
mod.rs
use std::default::Default; use std::str::FromStr; use std::string::ToString; mod tag; pub use self::tag::Tag; #[derive(Debug)] pub struct Playlist { tags: Vec<Tag> } impl Default for Playlist { fn default() -> Playlist { let mut tags: Vec<Tag> = Vec::new(); tags.push(Tag::M3U); tags...
} } impl Playlist { pub fn new () -> Playlist { let tags: Vec<Tag> = Vec::new(); Playlist{tags: tags} } pub fn append(&mut self, tag: Tag) { self.tags.push(tag); } pub fn tags(&self) -> &[Tag] { self.tags.as_slice() } }
{ Ok(Playlist{tags: tags}) }
conditional_block
BuildOverview.tsx
import "whatwg-fetch"; import { BuildPlan } from "./BuildPlan"; interface IBuildPlanModel { key: string; name: string; } interface IBuildOverviewState { buildPlans: IBuildPlanModel[]; } export class BuildOverview extends React.Component<undefined, IBuildOverviewState> { constructor(props: undefined...
import * as React from "react";
random_line_split
BuildOverview.tsx
import * as React from "react"; import "whatwg-fetch"; import { BuildPlan } from "./BuildPlan"; interface IBuildPlanModel { key: string; name: string; } interface IBuildOverviewState { buildPlans: IBuildPlanModel[]; } export class BuildOverview extends React.Component<undefined, IBuildOverviewState> { ...
() { this.getBuildPlans(); } public render() { let buildPlans: JSX.Element[] = this.state.buildPlans.map(buildPlan => { return <BuildPlan key={buildPlan.key} planKey={buildPlan.key} name={buildPlan.name} />; }); return ( <div> {buildPlans...
componentDidMount
identifier_name
fork.js
import React from 'react' import Icon from 'react-icon-base'
const IoFork = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m21.1 11.6z m3.9 1.4c0 2-1.2 3.7-2.9 4.5-0.9 0.5-0.8 0.9-0.8 0.9s1.2 15.6 1.2 16.6-0.2 1.4-0.7 1.9-1.2 0.6-1.8 0.6-1.2-0.2-1.7-0.6-0.8-1-0.8-1.9 1.3-16.6 1.3-16.6 0-0.5-0.9-0.9c-1.7-0.8-2.9-2.5-2.9-4.5 0-3.4 1.2-7.3 1.9-10.5h0.6v9....
random_line_split
kendo.culture.ur.js
/* * Kendo UI v2015.2.805 (http://www.telerik.com/kendo-ui) * Copyright 2015 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial licen...
name: "ur", numberFormat: { pattern: ["-n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], percent: { pattern: ["-n %","n %"], decimals: 2, ",": ",", ".": ".", ...
kendo.cultures["ur"] = {
random_line_split
igdateeditor.component.ts
import { IgEditorBase } from "./igeditorbase"; import { Renderer, ElementRef, IterableDiffers, Optional, Component } from "@angular/core"; import { NgModel } from "@angular/forms"; @Component({ selector: "ig-date-editor", template: "<ng-content></ng-content>", inputs: ["widgetId", "options", "changeDetectionInterva...
(): string { return; } ; /** * Returns a reference to the spin down UI element of the editor. */ public spinDownButton(): string { return; } ; /** * Checks if the value in the editor is valid. Note: This function will not trigger automatic notifications. */ public isValid(): boolean { return; } ; publi...
spinUpButton
identifier_name
igdateeditor.component.ts
import { IgEditorBase } from "./igeditorbase"; import { Renderer, ElementRef, IterableDiffers, Optional, Component } from "@angular/core"; import { NgModel } from "@angular/forms"; @Component({ selector: "ig-date-editor", template: "<ng-content></ng-content>", inputs: ["widgetId", "options", "changeDetectionInterva...
; public selectedListIndex(): void { return; } ; }
{ return; }
identifier_body
igdateeditor.component.ts
import { IgEditorBase } from "./igeditorbase"; import { Renderer, ElementRef, IterableDiffers, Optional, Component } from "@angular/core"; import { NgModel } from "@angular/forms"; @Component({ selector: "ig-date-editor", template: "<ng-content></ng-content>", inputs: ["widgetId", "options", "changeDetectionInterva...
public findListItemIndex(): void { return; } ; public getSelectedListItem(): void { return; } ; public selectedListIndex(): void { return; } ; }
*/ public isValid(): boolean { return; } ; public dropDownButton(): void { return; } ; public dropDownContainer(): void { return; } ; public dropDownVisible(): void { return; } ;
random_line_split
testutil.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashSet; use std::str::FromStr; use quickcheck::Arbitrary; use quickcheck::Gen; use crate::hgid::HgId; use crate::k...
} let mut buffer = String::new(); for _i in 0..HgId::hex_len() - hex.len() { buffer.push('0'); } buffer.push_str(hex); HgId::from_str(&buffer).unwrap() } pub fn key(path: &str, hexnode: &str) -> Key { Key::new(repo_path_buf(path), hgid(hexnode)) } /// The null hgid id is special an...
panic!("hgid 0 is special, use HgId::null_id() to build");
random_line_split
testutil.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashSet; use std::str::FromStr; use quickcheck::Arbitrary; use quickcheck::Gen; use crate::hgid::HgId; use crate::k...
pub fn repo_path_buf(s: &str) -> RepoPathBuf { if s == "" { panic!("the empty repo path is special, use RepoPathBuf::new() to build"); } RepoPathBuf::from_string(s.to_owned()).unwrap() } pub fn path_component(s: &str) -> &PathComponent { PathComponent::from_str(s).unwrap() } pub fn path_comp...
{ if s == "" { panic!("the empty repo path is special, use RepoPath::empty() to build"); } RepoPath::from_str(s).unwrap() }
identifier_body
testutil.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashSet; use std::str::FromStr; use quickcheck::Arbitrary; use quickcheck::Gen; use crate::hgid::HgId; use crate::k...
if hex == "0" { panic!("hgid 0 is special, use HgId::null_id() to build"); } let mut buffer = String::new(); for _i in 0..HgId::hex_len() - hex.len() { buffer.push('0'); } buffer.push_str(hex); HgId::from_str(&buffer).unwrap() } pub fn key(path: &str, hexnode: &str) -> Key ...
{ panic!("invalid length for hex hgid: {}", hex); }
conditional_block
testutil.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashSet; use std::str::FromStr; use quickcheck::Arbitrary; use quickcheck::Gen; use crate::hgid::HgId; use crate::k...
() { let mut qc_gen = Gen::new(10); let count = 10000; let paths = generate_repo_paths(count, &mut qc_gen); assert_eq!(paths.len(), count); } }
test_generate_repo_paths
identifier_name
dtstats.rs
use std::io::Result; use std::io::BufReader; use std::io::BufRead; use std::fs::File; use std::time::Duration; extern crate dtlib; fn main() { let log_result = parse_log(dtlib::constants::LOG_FILE); if !log_result.is_ok() { println!("Could not load log."); } else { let log = log_resu...
return Box::new(it) as LogIterator; } ); }
random_line_split
dtstats.rs
use std::io::Result; use std::io::BufReader; use std::io::BufRead; use std::fs::File; use std::time::Duration; extern crate dtlib; fn main() { let log_result = parse_log(dtlib::constants::LOG_FILE); if !log_result.is_ok() { println!("Could not load log."); } else { let log = log_res...
(path : &str) -> Result<LogIterator> { let file = File::open(path); return file.map( |f| { let buf_file = BufReader::new(f); let it = buf_file .lines() .filter(|line| line.is_ok()) .map(|line| line.unwrap()) .map(|...
parse_log
identifier_name
dtstats.rs
use std::io::Result; use std::io::BufReader; use std::io::BufRead; use std::fs::File; use std::time::Duration; extern crate dtlib; fn main() { let log_result = parse_log(dtlib::constants::LOG_FILE); if !log_result.is_ok()
else { let log = log_result.unwrap(); let stats_opt = calc_stats(log); if !stats_opt.is_some() { println!("Could not calculate stats."); } else { let stats = stats_opt.unwrap(); print!( " == DT Stats == \n\ ...
{ println!("Could not load log."); }
conditional_block
dtstats.rs
use std::io::Result; use std::io::BufReader; use std::io::BufRead; use std::fs::File; use std::time::Duration; extern crate dtlib; fn main()
\n\ Sectors written: {}\n\ GB written: {}\n\ \n\ Uptime (h): {}\n\ Uptime (d): {}\n\ Uptime (y): {}\n\ \n\ GB/h: {}\n\ GB/d: {}\n\ GB...
{ let log_result = parse_log(dtlib::constants::LOG_FILE); if !log_result.is_ok() { println!("Could not load log."); } else { let log = log_result.unwrap(); let stats_opt = calc_stats(log); if !stats_opt.is_some() { println!("Could not calculate stats."); ...
identifier_body
day12.rs
extern crate serde_json; use std::ops::Add; use self::serde_json::value::Value; pub fn json_sum(value: &Value) -> i64 { match *value { Value::I64(n) => n, Value::U64(n) => n as i64, Value::Array(ref vec) => vec.iter().map(json_sum).fold(0, Add::add), Value::Object(ref o) => o.value...
#[cfg(test)] mod tests { use super::{json_sum_str, json_sum_unred_str}; #[test] fn test_json_sum() { assert_eq!(json_sum_str("[1,2,3]"), 6); assert_eq!(json_sum_str("{\"a\":2,\"b\":4}"), 6); assert_eq!(json_sum_str("[[[3]]]"), 3); assert_eq!(json_sum_str("{\"a\":{\"b\":4},\"...
println!("Part 1: {}", json_sum(&json)); println!("Part 2: {}", json_sum_unred(&json)); }
random_line_split
day12.rs
extern crate serde_json; use std::ops::Add; use self::serde_json::value::Value; pub fn json_sum(value: &Value) -> i64 { match *value { Value::I64(n) => n, Value::U64(n) => n as i64, Value::Array(ref vec) => vec.iter().map(json_sum).fold(0, Add::add), Value::Object(ref o) => o.value...
} _ => 0, } } pub fn json_sum_unred_str(json: &str) -> i64 { match serde_json::from_str(json) { Ok(val) => json_sum_unred(&val), Err(_) => 0, } } pub fn process_file(path: &str) { use std::fs::File; use std::io::prelude::*; let mut file = File::open(path).unwra...
{ o.values().map(json_sum_unred).fold(0, Add::add) }
conditional_block
day12.rs
extern crate serde_json; use std::ops::Add; use self::serde_json::value::Value; pub fn json_sum(value: &Value) -> i64 { match *value { Value::I64(n) => n, Value::U64(n) => n as i64, Value::Array(ref vec) => vec.iter().map(json_sum).fold(0, Add::add), Value::Object(ref o) => o.value...
(path: &str) { use std::fs::File; use std::io::prelude::*; let mut file = File::open(path).unwrap(); let mut string = String::new(); file.read_to_string(&mut string).unwrap(); let json = serde_json::from_str(&string).unwrap(); println!("Part 1: {}", json_sum(&json)); println!("Part 2: {}...
process_file
identifier_name
day12.rs
extern crate serde_json; use std::ops::Add; use self::serde_json::value::Value; pub fn json_sum(value: &Value) -> i64 { match *value { Value::I64(n) => n, Value::U64(n) => n as i64, Value::Array(ref vec) => vec.iter().map(json_sum).fold(0, Add::add), Value::Object(ref o) => o.value...
pub fn process_file(path: &str) { use std::fs::File; use std::io::prelude::*; let mut file = File::open(path).unwrap(); let mut string = String::new(); file.read_to_string(&mut string).unwrap(); let json = serde_json::from_str(&string).unwrap(); println!("Part 1: {}", json_sum(&json)); ...
{ match serde_json::from_str(json) { Ok(val) => json_sum_unred(&val), Err(_) => 0, } }
identifier_body
lib.rs
//! A library for encoding/decoding Apple Icon Image (.icns) files. //! //! # ICNS concepts //! //! To understand this library, it helps to be familiar with the structure of //! an ICNS file; this section will give a high-level overview, or see //! [Wikipedia](https://en.wikipedia.org/wiki/Apple_Icon_Image_format) for ...
#[cfg(feature = "pngio")] extern crate png; #[cfg(feature = "pngio")] mod pngio; mod element; pub use self::element::IconElement; mod family; pub use self::family::IconFamily; mod icontype; pub use self::icontype::{Encoding, IconType, OSType}; mod image; pub use self::image::{Image, PixelFormat};
#![warn(missing_docs)] extern crate byteorder;
random_line_split
basic.ts
// https://f2.antv.vision/zh/examples/basic import F2 from '@antv/f2'; // F2 对数据源格式的要求,仅仅是 JSON 数组,数组的每个元素是一个标准 JSON 对象。 const data = [ { genre: 'Sports', sold: 275 }, { genre: 'Strategy', sold: 115 }, { genre: 'Action', sold: 120 }, { genre: 'Shooter', sold: 350 }, { genre: 'Other', sold: 150 }, ]; // Ste...
// Step 4: 渲染图表 chart.render();
random_line_split
0050_auto_20170313_1224.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.11 on 2017-03-13 11:24 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import mezzanine.core.fields class Migration(migrations.Migration): dependencies = [ ('organization_projects', '0049_...
), migrations.DeleteModel( name='ProjectSimpleImage', ), ]
model_name='projectsimpleimage', name='project',
random_line_split
0050_auto_20170313_1224.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.11 on 2017-03-13 11:24 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import mezzanine.core.fields class
(migrations.Migration): dependencies = [ ('organization_projects', '0049_auto_20170310_1658'), ] operations = [ migrations.CreateModel( name='ProjectUserImage', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, ve...
Migration
identifier_name
0050_auto_20170313_1224.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.11 on 2017-03-13 11:24 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import mezzanine.core.fields class Migration(migrations.Migration):
migrations.RemoveField( model_name='projectsimpleimage', name='project', ), migrations.DeleteModel( name='ProjectSimpleImage', ), ]
dependencies = [ ('organization_projects', '0049_auto_20170310_1658'), ] operations = [ migrations.CreateModel( name='ProjectUserImage', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ...
identifier_body
addusertogroup.py
from django.core.management.base import BaseCommand, CommandError from django.db import IntegrityError import olympia.core.logger from olympia.access.models import Group, GroupUser from olympia.users.models import UserProfile class Command(BaseCommand): help = 'Add a new user to a group.' log = olympia.core...
else: raise CommandError('Unknown input for user.') group = Group.objects.get(pk=group) GroupUser.objects.create(user=user, group=group) except IntegrityError, e: raise CommandError('User is already in that group? %s' % e) except UserProfile.DoesNotExist: r...
user = UserProfile.objects.get(email=user) elif user.isdigit(): user = UserProfile.objects.get(pk=user)
random_line_split
addusertogroup.py
from django.core.management.base import BaseCommand, CommandError from django.db import IntegrityError import olympia.core.logger from olympia.access.models import Group, GroupUser from olympia.users.models import UserProfile class Command(BaseCommand): help = 'Add a new user to a group.' log = olympia.core...
group = Group.objects.get(pk=group) GroupUser.objects.create(user=user, group=group) except IntegrityError, e: raise CommandError('User is already in that group? %s' % e) except UserProfile.DoesNotExist: raise CommandError('User ({user}) does not exist.'.format(user=user)) ...
raise CommandError('Unknown input for user.')
conditional_block
addusertogroup.py
from django.core.management.base import BaseCommand, CommandError from django.db import IntegrityError import olympia.core.logger from olympia.access.models import Group, GroupUser from olympia.users.models import UserProfile class Command(BaseCommand): help = 'Add a new user to a group.' log = olympia.core...
try: if '@' in user: user = UserProfile.objects.get(email=user) elif user.isdigit(): user = UserProfile.objects.get(pk=user) else: raise CommandError('Unknown input for user.') group = Group.objects.get(pk=group) GroupUser.objects.create(user...
identifier_body
addusertogroup.py
from django.core.management.base import BaseCommand, CommandError from django.db import IntegrityError import olympia.core.logger from olympia.access.models import Group, GroupUser from olympia.users.models import UserProfile class
(BaseCommand): help = 'Add a new user to a group.' log = olympia.core.logger.getLogger('z.users') def add_arguments(self, parser): parser.add_argument('user', type=unicode, help='User id or email') parser.add_argument('group_id', type=int, help='Group id') def handle(self, *args, **op...
Command
identifier_name
jquery.gritter.js
/* * Gritter for jQuery * http://www.boedesign.com/ * * Copyright (c) 2009 Jordan Boesch * Dual licensed under the MIT and GPL licenses. * * Date: June 26, 2009 * Version: 1.0 */ jQuery(document).ready(function($){ /******************************************** * First, we'll define our ob...
} return sa ? s : s[0]; }, // Remove the border styles and (X) close button when you mouse out unhoveringItem: function(e){ $(e).removeClass('hover'); $(e).find('.gritter-close').remove(); }, // Make sure we ...
{ temp = s[i]+''; repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0]; s[i] = (temp).split(f[j]).join(repl); if (count && s[i] !== temp) { this.window[count] += (temp.length-s[i].length)/f[j].length;} }
conditional_block
jquery.gritter.js
/* * Gritter for jQuery * http://www.boedesign.com/ * * Copyright (c) 2009 Jordan Boesch * Dual licensed under the MIT and GPL licenses. * * Date: June 26, 2009 * Version: 1.0 */ jQuery(document).ready(function($){ /******************************************** * First, we'll define our ob...
*/ // Set it up as an object $.gritter = {}; // Add a gritter notification $.gritter.add = function(params){ try { if(!params.title || !params.text){ throw "Missing_Fields"; } } catch(e) { if(e == "Missing_Fields"){ alert('Gritter Error: You need to fill out the first 2 pa...
random_line_split
conftest.py
""" :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ import pytest from byceps.services.ticketing import ( category_service, ticket_bundle_service as bundle_service, ticket_creation_service as creation_service, ticket_service, ) from tests.helpers ...
for ticket in tickets: ticket_service.delete_ticket(ticket.id) bundle_service.delete_bundle(bundle.id)
yield bundle
random_line_split
conftest.py
""" :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ import pytest from byceps.services.ticketing import ( category_service, ticket_bundle_service as bundle_service, ticket_creation_service as creation_service, ticket_service, ) from tests.helpers ...
bundle_service.delete_bundle(bundle.id)
ticket_service.delete_ticket(ticket.id)
conditional_block
conftest.py
""" :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ import pytest from byceps.services.ticketing import ( category_service, ticket_bundle_service as bundle_service, ticket_creation_service as creation_service, ticket_service, ) from tests.helpers ...
@pytest.fixture(scope='package') def bundle(category, ticket_owner): quantity = 4 bundle = bundle_service.create_bundle( category.party_id, category.id, quantity, ticket_owner.id ) tickets = bundle.tickets yield bundle for ticket in tickets: ticket_service.delete_ticket(tick...
ticket = creation_service.create_ticket( category.party_id, category.id, ticket_owner.id ) ticket_id = ticket.id yield ticket ticket_service.delete_ticket(ticket_id)
identifier_body
conftest.py
""" :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ import pytest from byceps.services.ticketing import ( category_service, ticket_bundle_service as bundle_service, ticket_creation_service as creation_service, ticket_service, ) from tests.helpers ...
(make_user): return make_user('Ticket_Owner') @pytest.fixture(scope='package') def category(party): category = category_service.create_category(party.id, 'Basic') yield category category_service.delete_category(category.id) @pytest.fixture(scope='package') def ticket(category, ticket_owner): t...
ticket_owner
identifier_name
titlebar.py
# This file is part of ranger, the console file manager. # License: GNU GPL version 3, see the file "AUTHORS" for details. """The titlebar is the widget at the top, giving you broad overview. It displays the current path among other things. """ from __future__ import (absolute_import, division, print_function) from...
self.win.move(0, 0) for part in result: self.color(*part.lst) y, x = self.win.getyx() self.addstr(y, x, str(part)) self.color_reset()
identifier_body
titlebar.py
# This file is part of ranger, the console file manager. # License: GNU GPL version 3, see the file "AUTHORS" for details. """The titlebar is the widget at the top, giving you broad overview. It displays the current path among other things. """ from __future__ import (absolute_import, division, print_function) from...
else: clr = 'good' bar.add(self.fm.username, 'hostname', clr, fixed=True) bar.add('@', 'hostname', clr, fixed=True) bar.add(self.fm.hostname, 'hostname', clr, fixed=True) bar.add(' ', 'hostname', clr, fixed=True) pathway = self.fm.th...
clr = 'bad'
conditional_block
titlebar.py
# This file is part of ranger, the console file manager. # License: GNU GPL version 3, see the file "AUTHORS" for details.
It displays the current path among other things. """ from __future__ import (absolute_import, division, print_function) from os.path import basename from ranger.gui.bar import Bar from . import Widget class TitleBar(Widget): old_thisfile = None old_keybuffer = None old_wid = None result = None ...
"""The titlebar is the widget at the top, giving you broad overview.
random_line_split
titlebar.py
# This file is part of ranger, the console file manager. # License: GNU GPL version 3, see the file "AUTHORS" for details. """The titlebar is the widget at the top, giving you broad overview. It displays the current path among other things. """ from __future__ import (absolute_import, division, print_function) from...
(self, event): """Handle a MouseEvent""" direction = event.mouse_wheel_direction() if direction: self.fm.tab_move(direction) self.need_redraw = True return True if not event.pressed(1) or not self.result: return False pos = self.w...
click
identifier_name
changePassword.component.ts
import {Component, OnInit, ViewChild, ElementRef, Renderer, AfterViewInit} from '@angular/core'; import {FormGroup, FormControl, FormBuilder, Validators} from '@angular/forms'; import {ToastsManager} from 'ng2-toastr'; import {Router} from '@angular/router'; import {newPassword} from '../userProfile.model'; import {Pro...
ngOnInit() { this.currentPassword = new FormControl('', [Validators.required, Validators.minLength(6)]); this.newPassword = new FormControl('', [Validators.required, Validators.minLength(6)]); this.resetPasswordForm = this.fb.group({ currentPassword: this.currentPassword, newPassword ...
random_line_split
changePassword.component.ts
import {Component, OnInit, ViewChild, ElementRef, Renderer, AfterViewInit} from '@angular/core'; import {FormGroup, FormControl, FormBuilder, Validators} from '@angular/forms'; import {ToastsManager} from 'ng2-toastr'; import {Router} from '@angular/router'; import {newPassword} from '../userProfile.model'; import {Pro...
// submit the password change form to the backend with the new desired credentials onSubmit() { const newPass = new newPassword(this.resetPasswordForm.value.currentPassword, this.resetPasswordForm.value.newPassword); this.profileService.newPassword(newPass) .subscribe( data => { //...
{ setTimeout(() => { this.renderer.invokeElementMethod(this.userPassword.nativeElement, 'focus', []); }, 50); }
identifier_body
changePassword.component.ts
import {Component, OnInit, ViewChild, ElementRef, Renderer, AfterViewInit} from '@angular/core'; import {FormGroup, FormControl, FormBuilder, Validators} from '@angular/forms'; import {ToastsManager} from 'ng2-toastr'; import {Router} from '@angular/router'; import {newPassword} from '../userProfile.model'; import {Pro...
() { this.currentPassword = new FormControl('', [Validators.required, Validators.minLength(6)]); this.newPassword = new FormControl('', [Validators.required, Validators.minLength(6)]); this.resetPasswordForm = this.fb.group({ currentPassword: this.currentPassword, newPassword : this.newP...
ngOnInit
identifier_name
DistributedTask.py
''' Created on Feb 22, 2013 @author: u5682 ''' from datetime import datetime import os, sys, pickle import subprocess from time import sleep import xml.dom.minidom from xml.dom.minidom import Node class DistributedTask(object): ''' classdocs ''' def __init__(self, fileName = None): ''' Constructor '''...
def fromXML(self, fileName): #primerp rseamos el fichero doc = xml.dom.minidom.parse(fileName) self.executable = obtainText(doc, 'executable') self.arguments = obtainTextList(doc, 'arguments', 'argument') self.outputPath = obtainText(doc, 'outputPath') self.outputFile = obtainText(doc, 'outputFi...
self.fromXML(fileName)
conditional_block
DistributedTask.py
''' Created on Feb 22, 2013 @author: u5682 ''' from datetime import datetime
from time import sleep import xml.dom.minidom from xml.dom.minidom import Node class DistributedTask(object): ''' classdocs ''' def __init__(self, fileName = None): ''' Constructor ''' self.creationDate = datetime.now() if fileName == None: self.executable = "" self.arguments = [] self.o...
import os, sys, pickle import subprocess
random_line_split
DistributedTask.py
''' Created on Feb 22, 2013 @author: u5682 ''' from datetime import datetime import os, sys, pickle import subprocess from time import sleep import xml.dom.minidom from xml.dom.minidom import Node class DistributedTask(object): ''' classdocs ''' def __init__(self, fileName = None): ''' Constructor '''...
def getInputFiles(self): inputFileList = [] for inputF in self.inputFiles: inputFileList.append(inputF.text) return inputFileList def getOutputFiles(self): outputFileList = [] for outputF in self.outputFiles: outputFileList.append(outputF.text) return outputFileList def outputFilesExi...
argumentList = [] for arg in self.arguments: argumentList.append(arg.encode('ascii','ignore')) return argumentList
identifier_body
DistributedTask.py
''' Created on Feb 22, 2013 @author: u5682 ''' from datetime import datetime import os, sys, pickle import subprocess from time import sleep import xml.dom.minidom from xml.dom.minidom import Node class DistributedTask(object): ''' classdocs ''' def __init__(self, fileName = None): ''' Constructor '''...
(self): outputFileList = [] for outputF in self.outputFiles: outputFileList.append(outputF.text) return outputFileList def outputFilesExist(self): for outputF in self.outputFiles: requiredFile = self.taskInfo.workingDirectory + "/" + outputF.text if not os.path.exists(requiredFile): pri...
getOutputFiles
identifier_name
index.js
#!/usr/bin/env node const assert = require('assert'); const converter = require('../lib/index.js'); const src = `body font 14px/1.5 Helvetica, arial, sans-serif & #logo border-radius 5px; .foo min-width() height(1px, 2px) // single line comment .bar width 42 /* block comment */ .baz &_...
& #logo { border-radius: 5px; } } .foo { @mixin min-width; @mixin height 1px, 2px; } // single line comment; .bar { width: 42; } /* block comment */; .baz { &_mod { position: absolute; } } .bar_2 { width: 123px; } .bar_3 { width: 123px; } .bar_4 { width: 123px; }...
random_line_split
frag.rs
//! API for blowing strings into fragments and putting them back together. use regex::Regex; use eval::{self, Error, Value}; use eval::api::conv::str_; use eval::value::{ArrayRepr, StringRepr}; lazy_static!{ static ref WORD_SEP: Regex = Regex::new(r"\s+").unwrap(); static ref LINE_SEP: Regex = Regex::new("\...
else { // TODO: include the error message of the offending element's conversion return Err(Error::new(&format!( "join() failed to stringify {} element(s) of the input array", error_count))); } } Err(Error::new(&format!( "join() expects a ...
{ return Ok(Value::String(strings.join(&d))); }
conditional_block
frag.rs
//! API for blowing strings into fragments and putting them back together. use regex::Regex;
lazy_static!{ static ref WORD_SEP: Regex = Regex::new(r"\s+").unwrap(); static ref LINE_SEP: Regex = Regex::new("\r?\n").unwrap(); } /// Join an array of values into a single delimited string. pub fn join(delim: Value, array: Value) -> eval::Result { let delim_type = delim.typename(); let array_type...
use eval::{self, Error, Value}; use eval::api::conv::str_; use eval::value::{ArrayRepr, StringRepr};
random_line_split
frag.rs
//! API for blowing strings into fragments and putting them back together. use regex::Regex; use eval::{self, Error, Value}; use eval::api::conv::str_; use eval::value::{ArrayRepr, StringRepr}; lazy_static!{ static ref WORD_SEP: Regex = Regex::new(r"\s+").unwrap(); static ref LINE_SEP: Regex = Regex::new("\...
(delim: Value, array: Value) -> eval::Result { let delim_type = delim.typename(); let array_type = array.typename(); if let (Value::String(d), Value::Array(a)) = (delim, array) { let elem_count = a.len(); let strings: Vec<_> = a.into_iter() .map(str_).filter(Result::is_ok) ...
join
identifier_name
frag.rs
//! API for blowing strings into fragments and putting them back together. use regex::Regex; use eval::{self, Error, Value}; use eval::api::conv::str_; use eval::value::{ArrayRepr, StringRepr}; lazy_static!{ static ref WORD_SEP: Regex = Regex::new(r"\s+").unwrap(); static ref LINE_SEP: Regex = Regex::new("\...
// Utility functions #[inline] fn do_regex_split(delim: &Regex, string: &str) -> ArrayRepr { delim.split(string).map(StringRepr::from).map(Value::String).collect() }
{ eval1!((string: &String) -> Array { do_regex_split(&LINE_SEP, string) }); mismatch!("lines"; ("string") => (string)) }
identifier_body
alias.js
import { get } from "ember-metal/property_get"; import { set } from "ember-metal/property_set"; import Ember from "ember-metal/core"; // Ember.assert import EmberError from "ember-metal/error"; import { Descriptor, defineProperty } from "ember-metal/properties"; import { ComputedProperty } from "ember-metal/compute...
(altKey) { return new AliasedProperty(altKey); } export function AliasedProperty(altKey) { this.altKey = altKey; this._dependentKeys = [altKey]; } AliasedProperty.prototype = create(Descriptor.prototype); AliasedProperty.prototype.get = function AliasedProperty_get(obj, keyName) { return get(obj, this.altKey...
alias
identifier_name
alias.js
import { get } from "ember-metal/property_get"; import { set } from "ember-metal/property_set"; import Ember from "ember-metal/core"; // Ember.assert import EmberError from "ember-metal/error"; import { Descriptor, defineProperty } from "ember-metal/properties"; import { ComputedProperty } from "ember-metal/compute...
AliasedProperty.prototype = create(Descriptor.prototype); AliasedProperty.prototype.get = function AliasedProperty_get(obj, keyName) { return get(obj, this.altKey); }; AliasedProperty.prototype.set = function AliasedProperty_set(obj, keyName, value) { return set(obj, this.altKey, value); }; AliasedProperty.pro...
{ this.altKey = altKey; this._dependentKeys = [altKey]; }
identifier_body
alias.js
import { get } from "ember-metal/property_get"; import { set } from "ember-metal/property_set"; import Ember from "ember-metal/core"; // Ember.assert import EmberError from "ember-metal/error"; import { Descriptor, defineProperty } from "ember-metal/properties"; import { ComputedProperty } from "ember-metal/compute...
}; AliasedProperty.prototype.readOnly = function() { this.set = AliasedProperty_readOnlySet; return this; }; function AliasedProperty_readOnlySet(obj, keyName, value) { throw new EmberError('Cannot set read-only property "' + keyName + '" on object: ' + inspect(obj)); } AliasedProperty.prototype.oneWay = func...
{ removeDependentKeys(this, obj, keyName, m); }
conditional_block
alias.js
import { get } from "ember-metal/property_get"; import { set } from "ember-metal/property_set"; import Ember from "ember-metal/core"; // Ember.assert import EmberError from "ember-metal/error"; import { Descriptor, defineProperty } from "ember-metal/properties"; import { ComputedProperty } from "ember-metal/compute...
AliasedProperty.prototype.set = function AliasedProperty_set(obj, keyName, value) { return set(obj, this.altKey, value); }; AliasedProperty.prototype.willWatch = function(obj, keyName) { addDependentKeys(this, obj, keyName, meta(obj)); }; AliasedProperty.prototype.didUnwatch = function(obj, keyName) { removeDe...
};
random_line_split
core_dependencies.py
#!/usr/bin/python # Copyright 2003 Vladimir Prus # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) # This tests correct handling of dependencies, specifically, on generated # sources, and from generated sources. import Bo...
(s1, s2): def correct_order(s): n1 = string.find(s, s1) n2 = string.find(s, s2) return ( n1 != -1 ) and ( n2 != -1 ) and ( n1 < n2 ) return correct_order correct_order = mk_correct_order_func("create-foo", "copy a") t.rm(["a", "b", "foo.h"]) t.run_build_system("-d+2 -f-", stdin=code + ...
mk_correct_order_func
identifier_name
core_dependencies.py
#!/usr/bin/python # Copyright 2003 Vladimir Prus # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) # This tests correct handling of dependencies, specifically, on generated # sources, and from generated sources. import Bo...
correct_order = mk_correct_order_func("create-foo", "copy a") t.rm(["a", "b", "foo.h"]) t.run_build_system("-d+2 -f-", stdin=code + " DEPENDS all : foo.h ;") t.fail_test(not correct_order(t.stdout())) t.rm(["a", "b", "foo.h"]) t.run_build_system("-d+2 -f-", stdin=" DEPENDS all : foo.h ; " + code) t.fail_test(not co...
def correct_order(s): n1 = string.find(s, s1) n2 = string.find(s, s2) return ( n1 != -1 ) and ( n2 != -1 ) and ( n1 < n2 ) return correct_order
identifier_body
core_dependencies.py
#!/usr/bin/python # Copyright 2003 Vladimir Prus # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) # This tests correct handling of dependencies, specifically, on generated # sources, and from generated sources. import Bo...
t.run_build_system("-f-", stdin=code) # Run two times, adding explicit dependency from all to foo.h at the beginning # and at the end, to make sure that foo.h is generated before 'a' in all cases. def mk_correct_order_func(s1, s2): def correct_order(s): n1 = string.find(s, s1) n2 = string.find(s, ...
{ echo // > $(<) } create-foo foo.h ; """
random_line_split
app.rs
use gtk; use gdk; use gio; use gtk::prelude::*; use gio::prelude::*; use std::cell::RefCell; use std::sync::mpsc::Receiver; use {NAME, TAGLINE}; use static_resources; use preferences; use headerbar; use sentinel_api::youtube; use views::trending; // Define thread local storage keys. thread_local! { pub static V...
)>> = RefCell::new(None); #[allow(unknown_lints, type_complexity)] pub static THUMBNAILS: RefCell<Option<( Vec<gtk::Image>, Receiver<Option<String>>, )>> = RefCell::new(None); } pub fn run_app() -> Result<(), String> { let application = match gtk::Application::new( Some("com...
Receiver<Option<Vec<youtube::Video>>>,
random_line_split
app.rs
use gtk; use gdk; use gio; use gtk::prelude::*; use gio::prelude::*; use std::cell::RefCell; use std::sync::mpsc::Receiver; use {NAME, TAGLINE}; use static_resources; use preferences; use headerbar; use sentinel_api::youtube; use views::trending; // Define thread local storage keys. thread_local! { pub static V...
}); let headerbar = headerbar::get_headerbar(&stack, &revealer, &viewport); win.add(&vbox); win.set_title(NAME); win.set_wmclass(NAME, NAME); win.set_titlebar(&headerbar); win.show_all(); win.activate(); }
{ let builder = gtk::Builder::new_from_resource("/com/github/kil0meters/sentinel/gtk/interface.ui"); let win = gtk::ApplicationWindow::new(app); win.set_default_size(732, 500); win.set_gravity(gdk::Gravity::Center); let vbox: gtk::Box = builder.get_object("vbox").unwrap(); let revealer: gtk::R...
identifier_body
app.rs
use gtk; use gdk; use gio; use gtk::prelude::*; use gio::prelude::*; use std::cell::RefCell; use std::sync::mpsc::Receiver; use {NAME, TAGLINE}; use static_resources; use preferences; use headerbar; use sentinel_api::youtube; use views::trending; // Define thread local storage keys. thread_local! { pub static V...
() -> Result<(), String> { let application = match gtk::Application::new( Some("com.github.kil0meters.sentinel"), gio::ApplicationFlags::empty(), ) { Ok(app) => { app.connect_activate(move |app| { build_ui(app); }); app } Err(e) => { re...
run_app
identifier_name
proximity_variational_inference.py
import tensorflow as tf import numpy as np import collections import time import util from .variational_inference import VariationalInference from inferences import proximity_statistics fw = tf.contrib.framework layers = tf.contrib.layers dist = tf.contrib.distributions class ProximityVariationalInference(Variatio...
self.q_gradients = q_gradients self.q_constraint_grad = constraint_grad
param_name = util.tensor_name(self.q_params[i]) update = magnitude * distance_grad[i] constraint_grad[i] += update q_gradients[i] += update update_norm = util.norm(update) fraction = tf.reduce_mean( update_norm / util.norm(self.q_neg_elbo_grad[i] + update)...
conditional_block
proximity_variational_inference.py
import tensorflow as tf import numpy as np import collections import time import util from .variational_inference import VariationalInference from inferences import proximity_statistics fw = tf.contrib.framework layers = tf.contrib.layers dist = tf.contrib.distributions class ProximityVariationalInference(Variatio...
(np_var): return np.where(np_var > 0.01)[0].shape[0] msg += ' Active units: %d ' % np.mean([active(v) for v in np_variances]) self.t0 = self.t self.summary_writer.add_summary(summary_str, global_step=np_step) self.save_params(np_step) # self.log_grad_stats(feed_dict) return msg + constraint_ms...
active
identifier_name
proximity_variational_inference.py
import tensorflow as tf import numpy as np import collections import time import util from .variational_inference import VariationalInference from inferences import proximity_statistics fw = tf.contrib.framework layers = tf.contrib.layers dist = tf.contrib.distributions class ProximityVariationalInference(Variatio...
self.q_constraint_grad = constraint_grad
self.q_gradients = q_gradients
random_line_split
proximity_variational_inference.py
import tensorflow as tf import numpy as np import collections import time import util from .variational_inference import VariationalInference from inferences import proximity_statistics fw = tf.contrib.framework layers = tf.contrib.layers dist = tf.contrib.distributions class ProximityVariationalInference(Variatio...
s = proximity_statistics.Activations(cfg, self.variational) elif cfg['c/proximity_statistic'] == 'log_likelihood': s = proximity_statistics.LogLikelihood( cfg, self.variational, model=self.model, q_z_sample=self.q_z_sample, data=self.data) elif cfg['c/proximity_statistic'] == 'or...
def __init__(self, session, config, model, variational, data): super(ProximityVariationalInference, self).__init__( session, config, model, variational, data) cfg = self.config self.build_proximity_statistic() self.build_distance() if not cfg['optim/deterministic_annealing']: self.buil...
identifier_body
940_more_supplier_details.py
""" Extend suppliers table with new fields (to be initially populated from declaration data) Revision ID: 940 Revises: 930 Create Date: 2017-08-16 16:39:00.000000 """ # revision identifiers, used by Alembic. revision = '940' down_revision = '930' from alembic import op import sqlalchemy as sa def
(): op.add_column(u'suppliers', sa.Column('registered_name', sa.String(), nullable=True)) op.add_column(u'suppliers', sa.Column('registration_country', sa.String(), nullable=True)) op.add_column(u'suppliers', sa.Column('other_company_registration_number', sa.String(), nullable=True)) op.add_column(u'sup...
upgrade
identifier_name
940_more_supplier_details.py
""" Extend suppliers table with new fields (to be initially populated from declaration data) Revision ID: 940 Revises: 930 Create Date: 2017-08-16 16:39:00.000000 """ # revision identifiers, used by Alembic. revision = '940' down_revision = '930' from alembic import op import sqlalchemy as sa def upgrade():
op.add_column(u'suppliers', sa.Column('organisation_size', sa.String(), nullable=True)) op.add_column(u'suppliers', sa.Column('trading_status', sa.String(), nullable=True)) def downgrade(): op.drop_column(u'suppliers', 'registered_name') op.drop_column(u'suppliers', 'registration_country') op.drop...
op.add_column(u'suppliers', sa.Column('registered_name', sa.String(), nullable=True)) op.add_column(u'suppliers', sa.Column('registration_country', sa.String(), nullable=True)) op.add_column(u'suppliers', sa.Column('other_company_registration_number', sa.String(), nullable=True)) op.add_column(u'supplie...
random_line_split
940_more_supplier_details.py
""" Extend suppliers table with new fields (to be initially populated from declaration data) Revision ID: 940 Revises: 930 Create Date: 2017-08-16 16:39:00.000000 """ # revision identifiers, used by Alembic. revision = '940' down_revision = '930' from alembic import op import sqlalchemy as sa def upgrade():
def downgrade(): op.drop_column(u'suppliers', 'registered_name') op.drop_column(u'suppliers', 'registration_country') op.drop_column(u'suppliers', 'other_company_registration_number') op.drop_column(u'suppliers', 'registration_date') op.drop_column(u'suppliers', 'vat_number') op.drop_column(u...
op.add_column(u'suppliers', sa.Column('registered_name', sa.String(), nullable=True)) op.add_column(u'suppliers', sa.Column('registration_country', sa.String(), nullable=True)) op.add_column(u'suppliers', sa.Column('other_company_registration_number', sa.String(), nullable=True)) op.add_column(u'suppliers',...
identifier_body
grub2.py
# This file is part of the sos project: https://github.com/sosreport/sos # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # version 2 of the GNU General Public License. # # See the LICENSE file in the source distribution ...
"/etc/default/grub", "/etc/grub2.cfg", "/etc/grub.d" ]) self.add_cmd_output("ls -lanR /boot") # call grub2-mkconfig with GRUB_DISABLE_OS_PROBER=true to prevent # possible unwanted loading of some kernel modules env = {} env['GRUB_DISAB...
random_line_split
grub2.py
# This file is part of the sos project: https://github.com/sosreport/sos # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # version 2 of the GNU General Public License. # # See the LICENSE file in the source distribution ...
) self.do_path_regex_sub( r".*\/grub\.", passwd_pbkdf2_exp, passwd_pbkdf2_sub ) # vim: set et ts=4 sw=4 :
passwd_exp = r"(password )\s*(\S*)\s*(\S*)" passwd_pbkdf2_exp = r"(password_pbkdf2)\s*(\S*)\s*(\S*)" passwd_sub = r"\1 \2 ********" passwd_pbkdf2_sub = r"\1 \2 grub.pbkdf2.********" self.do_cmd_output_sub( "grub2-mkconfig", passwd_pbkdf2_exp, passwd_p...
identifier_body
grub2.py
# This file is part of the sos project: https://github.com/sosreport/sos # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # version 2 of the GNU General Public License. # # See the LICENSE file in the source distribution ...
(Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin): """GRUB2 bootloader """ plugin_name = 'grub2' profiles = ('boot',) packages = ('grub2', 'grub2-efi') def setup(self): self.add_copy_spec([ "/boot/efi/EFI/*/grub.cfg", "/boot/grub2/grub.cfg", "/boot/...
Grub2
identifier_name
threading.py
# Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
(mwdv.ModelWithDefaultViews): """A Green Thread Model This model holds data for information about an individual thread. Unlike the thread model, it holds just a stack trace, since green threads do not have thread ids. .. seealso:: Class :class:`StackTraceModel` :param stack: the...
GreenThreadModel
identifier_name
threading.py
# Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
super(GreenThreadModel, self).__init__( {'stack_trace': StackTraceModel(stack)}, text_view=text_views.GreenThreadView())
identifier_body
threading.py
# Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
# under the License. """Provides threading and stack-trace models This module defines classes representing thread, green thread, and stack trace data models """ import traceback from openstack.common.report.models import with_default_views as mwdv from openstack.common.report.views.text import threading as text_...
random_line_split
threading.py
# Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
class ThreadModel(mwdv.ModelWithDefaultViews): """A Thread Model This model holds data for information about an individual thread. It holds both a thread id, as well as a stack trace for the thread .. seealso:: Class :class:`StackTraceModel` :param int thread_id: the id of the th...
self['lines'] = [] self['root_exception'] = None
conditional_block
associated-type-projection-from-multiple-supertraits.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 dent<C:BoxCar>(c: C, color: C::Color) { //~^ ERROR ambiguous associated type `Color` in bounds of `C` //~| NOTE could derive from `Vehicle` //~| NOTE could derive from `Box` } fn dent_object<COLOR>(c: BoxCar<Color=COLOR>) { //~^ ERROR ambiguous associated type } fn paint<C:BoxCar>(c: C, d: C::Color...
pub trait BoxCar : Box + Vehicle { }
random_line_split
associated-type-projection-from-multiple-supertraits.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 ...
pub fn main() { }
{ //~^ ERROR ambiguous associated type `Color` in bounds of `C` //~| NOTE could derive from `Vehicle` //~| NOTE could derive from `Box` }
identifier_body
associated-type-projection-from-multiple-supertraits.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 ...
<COLOR>(c: BoxCar<Color=COLOR>) { //~^ ERROR ambiguous associated type } fn paint<C:BoxCar>(c: C, d: C::Color) { //~^ ERROR ambiguous associated type `Color` in bounds of `C` //~| NOTE could derive from `Vehicle` //~| NOTE could derive from `Box` } pub fn main() { }
dent_object
identifier_name
post_submit.js
Template.postSubmit.onCreated(function() { Session.set('postSubmitErrors', {}); }); Template.postSubmit.helpers({ errorMessage: function(field) { return Session.get('postSubmitErrors')[field]; },
}); Template.postSubmit.onRendered(function(){ // AutoForm.hooks({ // postSubmitForm: hooksObject // }); }); // Template.postSubmit.events({ // 'submit form': function(e) { // e.preventDefault(); // var post = { // url: $(e.target).find('[name=url]').val(), // title: $(e.target).f...
errorClass: function (field) { return !!Session.get('postSubmitErrors')[field] ? 'has-error' : ''; }
random_line_split
issue-3979-generics.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ x: isize, y: isize } impl Positioned<isize> for Point { fn SetX(&mut self, x: isize) { self.x = x; } fn X(&self) -> isize { self.x } } impl Movable<isize> for Point {} pub fn main() { let mut p = Point{ x: 1, y: 2}; p.translate(3); assert_eq!(p.X(), 4); }
Point
identifier_name
issue-3979-generics.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
trait Positioned<S> { fn SetX(&mut self, S); fn X(&self) -> S; } trait Movable<S: Add<Output=S>>: Positioned<S> { fn translate(&mut self, dx: S) { let x = self.X() + dx; self.SetX(x); } } struct Point { x: isize, y: isize } impl Positioned<isize> for Point { fn SetX(&mut self, x: isize) { ...
// pretty-expanded FIXME #23616 use std::ops::Add;
random_line_split
issue-3979-generics.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} impl Movable<isize> for Point {} pub fn main() { let mut p = Point{ x: 1, y: 2}; p.translate(3); assert_eq!(p.X(), 4); }
{ self.x }
identifier_body
main.js
angular.module('aac.controllers.main', []) /** * Main layout controller * @param $scope */ .controller('MainCtrl', function($scope, $rootScope, $location, Data, Utils) { $scope.go = function(v) { $location.path(v); } $scope.activeView = function(view) { return view == $rootScope.currentView ? 'ac...
}).catch(function(err) { Utils.showError(err); }); $scope.cancel = function() { window.history.back(); } $scope.save = function() { if (!$scope.profile.name || !$scope.profile.surname || !$scope.profile.username || $scope.profile.password && $scope.profile.password != $scope.profile.password2) ...
{ $scope.password_required = true; }
conditional_block
main.js
angular.module('aac.controllers.main', [])
*/ .controller('MainCtrl', function($scope, $rootScope, $location, Data, Utils) { $scope.go = function(v) { $location.path(v); } $scope.activeView = function(view) { return view == $rootScope.currentView ? 'active' : ''; }; $scope.signOut = function() { window.document.location = "./logout"; ...
/** * Main layout controller * @param $scope
random_line_split
assembler.py
import collections import itertools import nengo import pacman103 from .config import Config import connection import ensemble import node import probe import utils class Assembler(object): """The Assembler object takes a built collection of objects and connections and converts them into PACMAN vertices and...
(utils.vertices.NengoVertex): # NOTE This is intended to be temporary while PACMAN is refactored MODEL_NAME = 'nengo_mc_player' MAX_ATOMS = 1 def __init__(self): super(MulticastPlayer, self).__init__(1) self.regions = [None, None, None, None] @classmethod def assemble(cls, mcp,...
MulticastPlayer
identifier_name
assembler.py
import collections import itertools import nengo import pacman103 from .config import Config import connection import ensemble import node import probe import utils class Assembler(object): """The Assembler object takes a built collection of objects and connections and converts them into PACMAN vertices and...
else: raise TypeError("Cannot assemble object of type '%s'." % obj.__class__.__name__) vertex = self.object_builders[obj_type](obj, self) if vertex is not None: assert isinstance(vertex, pacman103.lib.graph.Vertex) vertex.runtime ...
if obj_type in self.object_builders: break
conditional_block
assembler.py
import collections import itertools import nengo import pacman103 from .config import Config import connection import ensemble import node import probe import utils class Assembler(object): """The Assembler object takes a built collection of objects and connections and converts them into PACMAN vertices and...
for p in sink.end_packets: end_items.extend([0, p.key, 0 if p.payload is None else p.payload, p.payload is not None]) # Build the regions start_items.insert(0, len(start_items)/4) start_region = uti...
random_line_split
assembler.py
import collections import itertools import nengo import pacman103 from .config import Config import connection import ensemble import node import probe import utils class Assembler(object): """The Assembler object takes a built collection of objects and connections and converts them into PACMAN vertices and...
def __call__(self, objs, conns, time_in_seconds, dt, config=None): """Construct PACMAN vertices and edges, and a reduced version of the model for simulation on host. :param objs: A list of objects to convert into PACMAN vertices. :param conns: A list of connections which will beco...
pre_c = list(connection.pre_obj.__class__.__mro__) + [None] post_c = list(connection.post_obj.__class__.__mro__) + [None] for key in itertools.chain(*[[(a, b) for b in post_c] for a in pre_c]): if key in self.connection_builders: return self.connection_builders[key](connecti...
identifier_body